1/*
2 * Copyright (C) 2013 University of Szeged
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27
28#if USE(CURL)
29
30#include "SSLHandle.h"
31
32#include "ResourceHandleInternal.h"
33
34#include <openssl/pem.h>
35#include <openssl/ssl.h>
36#include <openssl/x509_vfy.h>
37#include <wtf/ListHashSet.h>
38#include <wtf/text/CString.h>
39
40namespace WebCore {
41
42typedef std::tuple<WTF::String, WTF::String> clientCertificate;
43static HashMap<String, ListHashSet<String>> allowedHosts;
44static HashMap<String, clientCertificate> allowedClientHosts;
45
46void allowsAnyHTTPSCertificateHosts(const String& host)
47{
48    ListHashSet<String> certificates;
49    allowedHosts.set(host, certificates);
50}
51
52void addAllowedClientCertificate(const String& host, const String& certificate, const String& key)
53{
54    clientCertificate clientInfo(certificate, key);
55    allowedClientHosts.set(host.lower(), clientInfo);
56}
57
58void setSSLClientCertificate(ResourceHandle* handle)
59{
60    String host = handle->firstRequest().url().host();
61    HashMap<String, clientCertificate>::iterator it = allowedClientHosts.find(host.lower());
62    if (it == allowedClientHosts.end())
63        return;
64
65    ResourceHandleInternal* d = handle->getInternal();
66    clientCertificate clientInfo = it->value;
67    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERT, std::get<0>(clientInfo).utf8().data());
68    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERTTYPE, "P12");
69    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERTPASSWD, std::get<1>(clientInfo).utf8().data());
70}
71
72bool sslIgnoreHTTPSCertificate(const String& host, const ListHashSet<String>& certificates)
73{
74    HashMap<String, ListHashSet<String>>::iterator it = allowedHosts.find(host);
75    if (it != allowedHosts.end()) {
76        if ((it->value).isEmpty()) {
77            it->value = certificates;
78            return true;
79        }
80        if (certificates.size() != it->value.size())
81            return false;
82        ListHashSet<String>::const_iterator certsIter = certificates.begin();
83        ListHashSet<String>::iterator valueIter = (it->value).begin();
84        for (; valueIter != (it->value).end(); ++valueIter, ++certsIter) {
85            if (*certsIter != *valueIter)
86                return false;
87        }
88        return true;
89    }
90    return false;
91}
92
93unsigned sslCertificateFlag(const unsigned& sslError)
94{
95    switch (sslError) {
96    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT : // the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.
97    case X509_V_ERR_UNABLE_TO_GET_CRL : // the CRL of a certificate could not be found.
98    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY : // the issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
99        return SSL_CERTIFICATE_UNKNOWN_CA;
100    case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE : // the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys.
101    case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE : // the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused.
102    case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY : // the public key in the certificate SubjectPublicKeyInfo could not be read.
103    case X509_V_ERR_CERT_SIGNATURE_FAILURE : // the signature of the certificate is invalid.
104    case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT : // the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.
105    case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN : // the certificate chain could be built up using the untrusted certificates but the root could not be found locally.
106    case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE : // no signatures could be verified because the chain contains only one certificate and it is not self signed.
107    case X509_V_ERR_INVALID_PURPOSE : // the supplied certificate cannot be used for the specified purpose.
108    case X509_V_ERR_CERT_UNTRUSTED : // the root CA is not marked as trusted for the specified purpose.
109    case X509_V_ERR_CERT_REJECTED : // the root CA is marked to reject the specified purpose.
110    case X509_V_ERR_NO_EXPLICIT_POLICY : // the verification flags were set to require and explicit policy but none was present.
111    case X509_V_ERR_DIFFERENT_CRL_SCOPE : // the only CRLs that could be found did not match the scope of the certificate.
112        return SSL_CERTIFICATE_INSECURE;
113    case X509_V_ERR_CERT_NOT_YET_VALID : // the certificate is not yet valid: the notBefore date is after the current time.
114    case X509_V_ERR_CRL_NOT_YET_VALID : // the CRL is not yet valid.
115        return SSL_CERTIFICATE_NOT_ACTIVATED;
116    case X509_V_ERR_CERT_HAS_EXPIRED : // the certificate has expired: that is the notAfter date is before the current time.
117    case X509_V_ERR_CRL_HAS_EXPIRED : // the CRL has expired.
118        return SSL_CERTIFICATE_EXPIRED;
119    case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD : // the certificate notBefore field contains an invalid time.
120    case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD : // the certificate notAfter field contains an invalid time.
121    case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD : // the CRL lastUpdate field contains an invalid time.
122    case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD : // the CRL nextUpdate field contains an invalid time.
123    case X509_V_ERR_OUT_OF_MEM : // an error occurred trying to allocate memory. This should never happen.
124    case X509_V_ERR_CERT_CHAIN_TOO_LONG : // the certificate chain length is greater than the supplied maximum depth. Unused.
125    case X509_V_ERR_PATH_LENGTH_EXCEEDED : // the basicConstraints pathlength parameter has been exceeded.
126    case X509_V_ERR_INVALID_EXTENSION : // a certificate extension had an invalid value (for example an incorrect encoding) or some value inconsistent with other extensions.
127    case X509_V_ERR_INVALID_POLICY_EXTENSION : // a certificate policies extension had an invalid value (for example an incorrect encoding) or some value inconsistent with other extensions. This error only occurs if policy processing is enabled.
128    case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE : // some feature of a certificate extension is not supported. Unused.
129    case X509_V_ERR_PERMITTED_VIOLATION : // a name constraint violation occured in the permitted subtrees.
130    case X509_V_ERR_EXCLUDED_VIOLATION : // a name constraint violation occured in the excluded subtrees.
131    case X509_V_ERR_SUBTREE_MINMAX : // a certificate name constraints extension included a minimum or maximum field: this is not supported.
132    case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE : // an unsupported name constraint type was encountered. OpenSSL currently only supports directory name, DNS name, email and URI types.
133    case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX : // the format of the name constraint is not recognised: for example an email address format of a form not mentioned in RFC3280. This could be caused by a garbage extension or some new feature not currently supported.
134    case X509_V_ERR_CRL_PATH_VALIDATION_ERROR : // an error occured when attempting to verify the CRL path. This error can only happen if extended CRL checking is enabled.
135    case X509_V_ERR_APPLICATION_VERIFICATION : // an application specific error. This will never be returned unless explicitly set by an application.
136        return SSL_CERTIFICATE_GENERIC_ERROR;
137    case X509_V_ERR_CERT_REVOKED : // the certificate has been revoked.
138        return SSL_CERTIFICATE_REVOKED;
139    case X509_V_ERR_INVALID_CA : // a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
140    case X509_V_ERR_SUBJECT_ISSUER_MISMATCH : // the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
141    case X509_V_ERR_AKID_SKID_MISMATCH : // the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
142    case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH : // the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
143    case X509_V_ERR_KEYUSAGE_NO_CERTSIGN : // the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
144        return SSL_CERTIFICATE_BAD_IDENTITY;
145    default :
146        return SSL_CERTIFICATE_GENERIC_ERROR;
147    }
148}
149
150#if !PLATFORM(WIN)
151// success of certificates extraction
152bool pemData(X509_STORE_CTX* ctx, ListHashSet<String>& certificates)
153{
154    bool ok = true;
155    STACK_OF(X509)* certs = X509_STORE_CTX_get1_chain(ctx);
156    for (int i = 0; i < sk_X509_num(certs); i++) {
157        X509* uCert = sk_X509_value(certs, i);
158        BIO* bio = BIO_new(BIO_s_mem());
159        int res = PEM_write_bio_X509(bio, uCert);
160        if (!res) {
161            ok = false;
162            BIO_free(bio);
163            break;
164        }
165
166        unsigned char* certificateData;
167        long length = BIO_get_mem_data(bio, &certificateData);
168        if (length < 0) {
169            ok = false;
170            BIO_free(bio);
171            break;
172        }
173
174        certificateData[length] = '\0';
175        String certificate = certificateData;
176        certificates.add(certificate);
177        BIO_free(bio);
178    }
179        sk_X509_pop_free(certs, X509_free);
180        return ok;
181}
182#endif
183
184static int certVerifyCallback(int ok, X509_STORE_CTX* ctx)
185{
186    // whether the verification of the certificate in question was passed (preverify_ok=1) or not (preverify_ok=0)
187
188    unsigned err = X509_STORE_CTX_get_error(ctx);
189    if (!err)
190        return 1;
191
192    SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
193    SSL_CTX* sslctx = SSL_get_SSL_CTX(ssl);
194    ResourceHandle* job = reinterpret_cast<ResourceHandle*>(SSL_CTX_get_app_data(sslctx));
195    String host = job->firstRequest().url().host();
196    ResourceHandleInternal* d = job->getInternal();
197
198    d->m_sslErrors = sslCertificateFlag(err);
199
200#if PLATFORM(WIN)
201    HashMap<String, ListHashSet<String>>::iterator it = allowedHosts.find(host);
202    ok = (it != allowedHosts.end());
203#else
204    ListHashSet<String> certificates;
205    if (!pemData(ctx, certificates))
206        return 0;
207    ok = sslIgnoreHTTPSCertificate(host.lower(), certificates);
208#endif
209
210    if (ok) {
211        // if the host and the certificate are stored for the current handle that means is enabled,
212        // so don't need to curl verifies the authenticity of the peer's certificate
213        curl_easy_setopt(d->m_handle, CURLOPT_SSL_VERIFYPEER, false);
214    }
215    return ok;
216}
217
218static CURLcode sslctxfun(CURL* curl, void* sslctx, void* parm)
219{
220    SSL_CTX_set_app_data(reinterpret_cast<SSL_CTX*>(sslctx), parm);
221    SSL_CTX_set_verify(reinterpret_cast<SSL_CTX*>(sslctx), SSL_VERIFY_PEER, certVerifyCallback);
222    return CURLE_OK;
223}
224
225void setSSLVerifyOptions(ResourceHandle* handle)
226{
227    ResourceHandleInternal* d = handle->getInternal();
228    curl_easy_setopt(d->m_handle, CURLOPT_SSL_CTX_DATA, handle);
229    curl_easy_setopt(d->m_handle, CURLOPT_SSL_CTX_FUNCTION, sslctxfun);
230}
231
232}
233
234#endif
235