"Fossies" - the Fresh Open Source Software Archive

Member "neon-0.31.2/src/ne_openssl.c" (20 Jun 2020, 38248 Bytes) of package /linux/www/neon-0.31.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "ne_openssl.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 0.31.1_vs_0.31.2.

    1 /* 
    2    neon SSL/TLS support using OpenSSL
    3    Copyright (C) 2002-2011, Joe Orton <joe@manyfish.co.uk>
    4 
    5    This library is free software; you can redistribute it and/or
    6    modify it under the terms of the GNU Library General Public
    7    License as published by the Free Software Foundation; either
    8    version 2 of the License, or (at your option) any later version.
    9    
   10    This library is distributed in the hope that it will be useful,
   11    but WITHOUT ANY WARRANTY; without even the implied warranty of
   12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   13    Library General Public License for more details.
   14 
   15    You should have received a copy of the GNU Library General Public
   16    License along with this library; if not, write to the Free
   17    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
   18    MA 02111-1307, USA
   19 
   20 */
   21 
   22 #include "config.h"
   23 
   24 #include <sys/types.h>
   25 
   26 #ifdef HAVE_STRING_H
   27 #include <string.h>
   28 #endif
   29 
   30 #include <stdio.h>
   31 
   32 #include <openssl/ssl.h>
   33 #include <openssl/err.h>
   34 #include <openssl/pkcs12.h>
   35 #include <openssl/x509v3.h>
   36 #include <openssl/rand.h>
   37 #include <openssl/opensslv.h>
   38 #include <openssl/evp.h>
   39 
   40 #ifdef NE_HAVE_TS_SSL
   41 #include <stdlib.h> /* for abort() */
   42 #ifndef _WIN32
   43 #include <pthread.h>
   44 #endif
   45 #endif
   46 
   47 #include "ne_ssl.h"
   48 #include "ne_string.h"
   49 #include "ne_session.h"
   50 #include "ne_internal.h"
   51 #include "ne_md5.h"
   52 #include "ne_private.h"
   53 #include "ne_privssl.h"
   54 
   55 /* OpenSSL 0.9.6 compatibility */
   56 #if OPENSSL_VERSION_NUMBER < 0x0090700fL
   57 #define PKCS12_unpack_authsafes M_PKCS12_unpack_authsafes
   58 #define PKCS12_unpack_p7data M_PKCS12_unpack_p7data
   59 /* cast away lack of const-ness */
   60 #define OBJ_cmp(a,b) OBJ_cmp((ASN1_OBJECT *)(a), (ASN1_OBJECT *)(b))
   61 #endif
   62 
   63 /* Second argument for d2i_X509() changed type in 0.9.8. */
   64 #if OPENSSL_VERSION_NUMBER < 0x0090800fL
   65 typedef unsigned char ne_d2i_uchar;
   66 #else
   67 typedef const unsigned char ne_d2i_uchar;
   68 #endif
   69 
   70 #if OPENSSL_VERSION_NUMBER < 0x10100000L
   71 #define X509_get0_notBefore X509_get_notBefore
   72 #define X509_get0_notAfter X509_get_notAfter
   73 #define X509_up_ref(x) x->references++
   74 #define EVP_PKEY_up_ref(x) x->references++
   75 #define EVP_MD_CTX_new() ne_calloc(sizeof(EVP_MD_CTX))
   76 #define EVP_MD_CTX_free(ctx) ne_free(ctx)
   77 #define EVP_MD_CTX_reset EVP_MD_CTX_cleanup
   78 #define EVP_PKEY_get0_RSA(evp) (evp->pkey.rsa)
   79 #endif
   80 
   81 struct ne_ssl_dname_s {
   82     X509_NAME *dn;
   83 };
   84 
   85 struct ne_ssl_certificate_s {
   86     ne_ssl_dname subj_dn, issuer_dn;
   87     X509 *subject;
   88     ne_ssl_certificate *issuer;
   89     char *identity;
   90 };
   91 
   92 struct ne_ssl_client_cert_s {
   93     PKCS12 *p12;
   94     int decrypted; /* non-zero if successfully decrypted. */
   95     ne_ssl_certificate cert;
   96     EVP_PKEY *pkey;
   97     char *friendly_name;
   98 };
   99 
  100 #define NE_SSL_UNHANDLED (0x20) /* failure bit for unhandled case. */
  101 
  102 /* Append an ASN.1 DirectoryString STR to buffer BUF as UTF-8.
  103  * Returns zero on success or non-zero on error. */
  104 static int append_dirstring(ne_buffer *buf, ASN1_STRING *str)
  105 {
  106     unsigned char *tmp = (unsigned char *)""; /* initialize to workaround 0.9.6 bug */
  107     int len;
  108 
  109     switch (str->type) {
  110     case V_ASN1_IA5STRING: /* definitely ASCII */
  111     case V_ASN1_VISIBLESTRING: /* probably ASCII */
  112     case V_ASN1_PRINTABLESTRING: /* subset of ASCII */
  113         ne_buffer_qappend(buf, str->data, str->length);
  114         break;
  115     case V_ASN1_UTF8STRING:
  116         /* Fail for embedded NUL bytes. */
  117         if (strlen((char *)str->data) != (size_t)str->length) {
  118             return -1;
  119         }
  120         ne_buffer_append(buf, (char *)str->data, str->length);
  121         break;
  122     case V_ASN1_UNIVERSALSTRING:
  123     case V_ASN1_T61STRING: /* let OpenSSL convert it as ISO-8859-1 */
  124     case V_ASN1_BMPSTRING: 
  125         len = ASN1_STRING_to_UTF8(&tmp, str);
  126         if (len > 0) {
  127             /* Fail if there were embedded NUL bytes. */
  128             if (strlen((char *)tmp) != (size_t)len) {
  129                 OPENSSL_free(tmp);
  130                 return -1;
  131             } 
  132             else {
  133                 ne_buffer_append(buf, (char *)tmp, len);
  134                 OPENSSL_free(tmp);
  135             }
  136             break;
  137         } else {
  138             ERR_clear_error();
  139             return -1;
  140         }
  141         break;
  142     default:
  143         NE_DEBUG(NE_DBG_SSL, "Could not convert DirectoryString type %d\n",
  144                  str->type);
  145         return -1;
  146     }
  147     return 0;
  148 }
  149 
  150 /* Returns a malloc-allocated version of IA5 string AS, escaped for
  151  * safety. */
  152 static char *dup_ia5string(const ASN1_IA5STRING *as)
  153 {
  154     return ne_strnqdup(as->data, as->length);
  155 }
  156 
  157 char *ne_ssl_readable_dname(const ne_ssl_dname *name)
  158 {
  159     int n, flag = 0;
  160     ne_buffer *dump = ne_buffer_create();
  161     const ASN1_OBJECT * const cname = OBJ_nid2obj(NID_commonName),
  162     * const email = OBJ_nid2obj(NID_pkcs9_emailAddress);
  163 
  164     for (n = X509_NAME_entry_count(name->dn); n > 0; n--) {
  165     X509_NAME_ENTRY *ent = X509_NAME_get_entry(name->dn, n-1);
  166     ASN1_OBJECT *obj = X509_NAME_ENTRY_get_object(ent);
  167     
  168         /* Skip commonName or emailAddress except if there is no other
  169          * attribute in dname. */
  170     if ((OBJ_cmp(obj, cname) && OBJ_cmp(obj, email)) ||
  171             (!flag && n == 1)) {
  172         if (flag++)
  173         ne_buffer_append(dump, ", ", 2);
  174 
  175             if (append_dirstring(dump, X509_NAME_ENTRY_get_data(ent)))
  176                 ne_buffer_czappend(dump, "???");
  177     }
  178     }
  179 
  180     return ne_buffer_finish(dump);
  181 }
  182 
  183 int ne_ssl_dname_cmp(const ne_ssl_dname *dn1, const ne_ssl_dname *dn2)
  184 {
  185     return X509_NAME_cmp(dn1->dn, dn2->dn);
  186 }
  187 
  188 void ne_ssl_clicert_free(ne_ssl_client_cert *cc)
  189 {
  190     if (cc->p12)
  191         PKCS12_free(cc->p12);
  192     if (cc->decrypted) {
  193         if (cc->cert.identity) ne_free(cc->cert.identity);
  194         EVP_PKEY_free(cc->pkey);
  195         X509_free(cc->cert.subject);
  196     }
  197     if (cc->friendly_name) ne_free(cc->friendly_name);
  198     ne_free(cc);
  199 }
  200 
  201 /* Format an ASN1 time to a string. 'buf' must be at least of size
  202  * 'NE_SSL_VDATELEN'. */
  203 static time_t asn1time_to_timet(const ASN1_TIME *atm)
  204 {
  205     struct tm tm = {0};
  206     int i = atm->length;
  207     
  208     if (i < 10)
  209         return (time_t )-1;
  210 
  211     tm.tm_year = (atm->data[0]-'0') * 10 + (atm->data[1]-'0');
  212 
  213     /* Deal with Year 2000 */
  214     if (tm.tm_year < 70)
  215         tm.tm_year += 100;
  216 
  217     tm.tm_mon = (atm->data[2]-'0') * 10 + (atm->data[3]-'0') - 1;
  218     tm.tm_mday = (atm->data[4]-'0') * 10 + (atm->data[5]-'0');
  219     tm.tm_hour = (atm->data[6]-'0') * 10 + (atm->data[7]-'0');
  220     tm.tm_min = (atm->data[8]-'0') * 10 + (atm->data[9]-'0');
  221     tm.tm_sec = (atm->data[10]-'0') * 10 + (atm->data[11]-'0');
  222 
  223 #ifdef HAVE_TIMEZONE
  224     /* ANSI C time handling is... interesting. */
  225     return mktime(&tm) - timezone;
  226 #else
  227     return mktime(&tm);
  228 #endif
  229 }
  230 
  231 void ne_ssl_cert_validity_time(const ne_ssl_certificate *cert,
  232                                time_t *from, time_t *until)
  233 {
  234     if (from) {
  235         *from = asn1time_to_timet(X509_get0_notBefore(cert->subject));
  236     }
  237     if (until) {
  238         *until = asn1time_to_timet(X509_get0_notAfter(cert->subject));
  239     }
  240 }
  241 
  242 /* Check certificate identity.  Returns zero if identity matches; 1 if
  243  * identity does not match, or <0 if the certificate had no identity.
  244  * If 'identity' is non-NULL, store the malloc-allocated identity in
  245  * *identity.  Logic specified by RFC 2818 and RFC 3280. */
  246 static int check_identity(const ne_uri *server, X509 *cert, char **identity)
  247 {
  248     STACK_OF(GENERAL_NAME) *names;
  249     int match = 0, found = 0;
  250     const char *hostname;
  251     
  252     hostname = server ? server->host : "";
  253 
  254     names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
  255     if (names) {
  256     int n;
  257 
  258         /* subjectAltName contains a sequence of GeneralNames */
  259     for (n = 0; n < sk_GENERAL_NAME_num(names) && !match; n++) {
  260         GENERAL_NAME *nm = sk_GENERAL_NAME_value(names, n);
  261         
  262             /* handle dNSName and iPAddress name extensions only. */
  263         if (nm->type == GEN_DNS) {
  264         char *name = dup_ia5string(nm->d.ia5);
  265                 if (identity && !found) *identity = ne_strdup(name);
  266         match = ne__ssl_match_hostname(name, strlen(name), hostname);
  267         ne_free(name);
  268         found = 1;
  269             } 
  270             else if (nm->type == GEN_IPADD) {
  271                 /* compare IP address with server IP address. */
  272                 ne_inet_addr *ia;
  273                 if (nm->d.ip->length == 4)
  274                     ia = ne_iaddr_make(ne_iaddr_ipv4, nm->d.ip->data);
  275                 else if (nm->d.ip->length == 16)
  276                     ia = ne_iaddr_make(ne_iaddr_ipv6, nm->d.ip->data);
  277                 else
  278                     ia = NULL;
  279                 /* ne_iaddr_make returns NULL if address type is unsupported */
  280                 if (ia != NULL) { /* address type was supported. */
  281                     char buf[128];
  282 
  283                     match = strcmp(hostname, 
  284                                    ne_iaddr_print(ia, buf, sizeof buf)) == 0;
  285                     found = 1;
  286                     ne_iaddr_free(ia);
  287                 } else {
  288                     NE_DEBUG(NE_DBG_SSL, "iPAddress name with unsupported "
  289                              "address type (length %d), skipped.\n",
  290                              nm->d.ip->length);
  291                 }
  292             } 
  293             else if (nm->type == GEN_URI) {
  294                 char *name = dup_ia5string(nm->d.ia5);
  295                 ne_uri uri;
  296 
  297                 if (ne_uri_parse(name, &uri) == 0 && uri.host && uri.scheme) {
  298                     ne_uri tmp;
  299 
  300                     if (identity && !found) *identity = ne_strdup(name);
  301                     found = 1;
  302 
  303                     if (server) {
  304                         /* For comparison purposes, all that matters is
  305                          * host, scheme and port; ignore the rest. */
  306                         memset(&tmp, 0, sizeof tmp);
  307                         tmp.host = uri.host;
  308                         tmp.scheme = uri.scheme;
  309                         tmp.port = uri.port;
  310                         
  311                         match = ne_uri_cmp(server, &tmp) == 0;
  312                     }
  313                 }
  314 
  315                 ne_uri_free(&uri);
  316                 ne_free(name);
  317             }
  318     }
  319         /* free the whole stack. */
  320         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
  321     }
  322     
  323     /* Check against the commonName if no DNS alt. names were found,
  324      * as per RFC3280. */
  325     if (!found) {
  326     X509_NAME *subj = X509_get_subject_name(cert);
  327     X509_NAME_ENTRY *entry;
  328     ne_buffer *cname = ne_buffer_ncreate(30);
  329     int idx = -1, lastidx;
  330 
  331     /* find the most specific commonName attribute. */
  332     do {
  333         lastidx = idx;
  334         idx = X509_NAME_get_index_by_NID(subj, NID_commonName, lastidx);
  335     } while (idx >= 0);
  336     
  337     if (lastidx < 0) {
  338             /* no commonName attributes at all. */
  339             ne_buffer_destroy(cname);
  340         return -1;
  341         }
  342 
  343     /* extract the string from the entry */
  344         entry = X509_NAME_get_entry(subj, lastidx);
  345         if (append_dirstring(cname, X509_NAME_ENTRY_get_data(entry))) {
  346             ne_buffer_destroy(cname);
  347             return -1;
  348         }
  349         if (identity) *identity = ne_strdup(cname->data);
  350         match = ne__ssl_match_hostname(cname->data, cname->used - 1, hostname);
  351         ne_buffer_destroy(cname);
  352     }
  353 
  354     NE_DEBUG(NE_DBG_SSL, "Identity match for '%s': %s\n", hostname, 
  355              match ? "good" : "bad");
  356     return match ? 0 : 1;
  357 }
  358 
  359 /* Populate an ne_ssl_certificate structure from an X509 object. */
  360 static ne_ssl_certificate *populate_cert(ne_ssl_certificate *cert, X509 *x5)
  361 {
  362     cert->subj_dn.dn = X509_get_subject_name(x5);
  363     cert->issuer_dn.dn = X509_get_issuer_name(x5);
  364     cert->issuer = NULL;
  365     cert->subject = x5;
  366     /* Retrieve the cert identity; pass a dummy hostname to match. */
  367     cert->identity = NULL;
  368     check_identity(NULL, x5, &cert->identity);
  369     return cert;
  370 }
  371 
  372 /* OpenSSL cert verification callback.  This is invoked for *each*
  373  * error which is encountered whilst verifying the cert chain; multiple
  374  * invocations for any particular cert in the chain are possible. */
  375 static int verify_callback(int ok, X509_STORE_CTX *ctx)
  376 {
  377     /* OpenSSL, living in its own little happy world of global state,
  378      * where userdata was just a twinkle in the eye of an API designer
  379      * yet to be born.  Or... "Seriously, wtf?"  */
  380     SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, 
  381                                           SSL_get_ex_data_X509_STORE_CTX_idx());
  382     ne_session *sess = SSL_get_app_data(ssl);
  383     int depth = X509_STORE_CTX_get_error_depth(ctx);
  384     int err = X509_STORE_CTX_get_error(ctx);
  385     int failures = 0;
  386 
  387     /* If there's no error, nothing to do here. */
  388     if (ok) return ok;
  389 
  390     NE_DEBUG(NE_DBG_SSL, "ssl: Verify callback @ %d => %d\n", depth, err);
  391 
  392     /* Map the error code onto any of the exported cert validation
  393      * errors, if possible. */
  394     switch (err) {
  395     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  396     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  397     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  398     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  399     case X509_V_ERR_CERT_UNTRUSTED:
  400     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  401         failures |= NE_SSL_UNTRUSTED;
  402         break;
  403     case X509_V_ERR_CERT_NOT_YET_VALID:
  404         failures |= depth > 0 ? NE_SSL_BADCHAIN : NE_SSL_NOTYETVALID;
  405         break;
  406     case X509_V_ERR_CERT_HAS_EXPIRED:
  407         failures |= depth > 0 ? NE_SSL_BADCHAIN : NE_SSL_EXPIRED;
  408         break;
  409     case X509_V_OK:
  410         break;
  411     default:
  412         /* Clear the failures bitmask so check_certificate knows this
  413          * is a bailout. */
  414         sess->ssl_context->failures |= NE_SSL_UNHANDLED;
  415         NE_DEBUG(NE_DBG_SSL, "ssl: Unhandled verification error %d -> %s\n", 
  416                  err, X509_verify_cert_error_string(err));
  417         return 0;
  418     }
  419 
  420     sess->ssl_context->failures |= failures;
  421 
  422     NE_DEBUG(NE_DBG_SSL, "ssl: Verify failures |= %d => %d\n", failures,
  423              sess->ssl_context->failures);
  424     
  425     return 1;
  426 }
  427 
  428 /* Return a linked list of certificate objects from an OpenSSL chain. */
  429 static ne_ssl_certificate *make_chain(STACK_OF(X509) *chain)
  430 {
  431     int n, count = sk_X509_num(chain);
  432     ne_ssl_certificate *top = NULL, *current = NULL;
  433     
  434     NE_DEBUG(NE_DBG_SSL, "Chain depth: %d\n", count);
  435 
  436     for (n = 0; n < count; n++) {
  437         ne_ssl_certificate *cert = ne_malloc(sizeof *cert);
  438         populate_cert(cert, X509_dup(sk_X509_value(chain, n)));
  439 #ifdef NE_DEBUGGING
  440         if (ne_debug_mask & NE_DBG_SSL) {
  441             fprintf(ne_debug_stream, "Cert #%d:\n", n);
  442             X509_print_fp(ne_debug_stream, cert->subject);
  443         }
  444 #endif
  445         if (top == NULL) {
  446             current = top = cert;
  447         } else {
  448             current->issuer = cert;
  449             current = cert;
  450         }
  451     }
  452 
  453     return top;
  454 }
  455 
  456 /* Verifies an SSL server certificate. */
  457 static int check_certificate(ne_session *sess, SSL *ssl, ne_ssl_certificate *chain)
  458 {
  459     X509 *cert = chain->subject;
  460     int ret, failures = sess->ssl_context->failures;
  461     ne_uri server;
  462 
  463     /* If the verification callback hit a case which can't be mapped
  464      * to one of the exported error bits, it's treated as a hard
  465      * failure rather than invoking the callback, which can't present
  466      * a useful error to the user.  "Um, something is wrong.  OK?" */
  467     if (failures & NE_SSL_UNHANDLED) {
  468         long result = SSL_get_verify_result(ssl);
  469 
  470         ne_set_error(sess, _("Certificate verification error: %s"),
  471                     X509_verify_cert_error_string(result));
  472 
  473         return NE_ERROR;
  474     }
  475 
  476     /* Check certificate was issued to this server; pass URI of
  477      * server. */
  478     memset(&server, 0, sizeof server);
  479     ne_fill_server_uri(sess, &server);
  480     ret = check_identity(&server, cert, NULL);
  481     ne_uri_free(&server);
  482     if (ret < 0) {
  483         ne_set_error(sess, _("Server certificate was missing commonName "
  484                              "attribute in subject name"));
  485         return NE_ERROR;
  486     } else if (ret > 0) failures |= NE_SSL_IDMISMATCH;
  487 
  488     if (failures == 0) {
  489         /* verified OK! */
  490         ret = NE_OK;
  491     } else {
  492         /* Set up the error string. */
  493         ne__ssl_set_verify_err(sess, failures);
  494         ret = NE_ERROR;
  495         /* Allow manual override */
  496         if (sess->ssl_verify_fn && 
  497             sess->ssl_verify_fn(sess->ssl_verify_ud, failures, chain) == 0)
  498             ret = NE_OK;
  499     }
  500 
  501     return ret;
  502 }
  503 
  504 /* Duplicate a client certificate, which must be in the decrypted state. */
  505 static ne_ssl_client_cert *dup_client_cert(const ne_ssl_client_cert *cc)
  506 {
  507     ne_ssl_client_cert *newcc = ne_calloc(sizeof *newcc);
  508     
  509     newcc->decrypted = 1;
  510     newcc->pkey = cc->pkey;
  511     if (cc->friendly_name)
  512         newcc->friendly_name = ne_strdup(cc->friendly_name);
  513 
  514     populate_cert(&newcc->cert, cc->cert.subject);
  515 
  516     X509_up_ref(cc->cert.subject);
  517     EVP_PKEY_up_ref(cc->pkey);
  518     return newcc;
  519 }
  520 
  521 /* Callback invoked when the SSL server requests a client certificate.  */
  522 static int provide_client_cert(SSL *ssl, X509 **cert, EVP_PKEY **pkey)
  523 {
  524     ne_session *const sess = SSL_get_app_data(ssl);
  525 
  526     if (!sess->client_cert && sess->ssl_provide_fn) {
  527     ne_ssl_dname **dnames = NULL, *dnarray = NULL;
  528         int n, count = 0;
  529     STACK_OF(X509_NAME) *ca_list = SSL_get_client_CA_list(ssl);
  530 
  531         count = ca_list ? sk_X509_NAME_num(ca_list) : 0;
  532 
  533         if (count > 0) {
  534             dnames = ne_malloc(count * sizeof(ne_ssl_dname *));
  535             dnarray = ne_malloc(count * sizeof(ne_ssl_dname));
  536             
  537             for (n = 0; n < count; n++) {
  538                 dnames[n] = &dnarray[n];
  539                 dnames[n]->dn = sk_X509_NAME_value(ca_list, n);
  540             }
  541         }
  542 
  543     NE_DEBUG(NE_DBG_SSL, "Calling client certificate provider...\n");
  544     sess->ssl_provide_fn(sess->ssl_provide_ud, sess, 
  545                              (const ne_ssl_dname *const *)dnames, count);
  546         if (count) {
  547             ne_free(dnarray);
  548             ne_free(dnames);
  549         }
  550     }
  551 
  552     if (sess->client_cert) {
  553         ne_ssl_client_cert *const cc = sess->client_cert;
  554     NE_DEBUG(NE_DBG_SSL, "Supplying client certificate.\n");
  555     EVP_PKEY_up_ref(cc->pkey);
  556     X509_up_ref(cc->cert.subject);
  557     *cert = cc->cert.subject;
  558     *pkey = cc->pkey;
  559     return 1;
  560     } else {
  561         sess->ssl_cc_requested = 1;
  562     NE_DEBUG(NE_DBG_SSL, "No client certificate supplied.\n");
  563     return 0;
  564     }
  565 }
  566 
  567 void ne_ssl_set_clicert(ne_session *sess, const ne_ssl_client_cert *cc)
  568 {
  569     sess->client_cert = dup_client_cert(cc);
  570 }
  571 
  572 ne_ssl_context *ne_ssl_context_create(int mode)
  573 {
  574     ne_ssl_context *ctx = ne_calloc(sizeof *ctx);
  575     if (mode == NE_SSL_CTX_CLIENT) {
  576         ctx->ctx = SSL_CTX_new(SSLv23_client_method());
  577         ctx->sess = NULL;
  578         /* set client cert callback. */
  579         SSL_CTX_set_client_cert_cb(ctx->ctx, provide_client_cert);
  580         /* enable workarounds for buggy SSL server implementations */
  581         SSL_CTX_set_options(ctx->ctx, SSL_OP_ALL);
  582         SSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, verify_callback);
  583 #if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10101000L
  584         SSL_CTX_set_post_handshake_auth(ctx->ctx, 1);
  585 #endif
  586     } else if (mode == NE_SSL_CTX_SERVER) {
  587         ctx->ctx = SSL_CTX_new(SSLv23_server_method());
  588         SSL_CTX_set_session_cache_mode(ctx->ctx, SSL_SESS_CACHE_CLIENT);
  589 #ifdef SSL_OP_NO_TICKET
  590         /* disable ticket support since it inhibits testing of session
  591          * caching. */
  592         SSL_CTX_set_options(ctx->ctx, SSL_OP_NO_TICKET);
  593 #endif
  594     } else {
  595         ne_free(ctx);
  596         return NULL;
  597     }
  598     return ctx;
  599 }
  600 
  601 void ne_ssl_context_set_flag(ne_ssl_context *ctx, int flag, int value)
  602 {
  603     long opts = SSL_CTX_get_options(ctx->ctx);
  604 
  605     switch (flag) {
  606     case NE_SSL_CTX_SSLv2:
  607         if (value) { 
  608             /* Enable SSLv2 support; clear the "no SSLv2" flag. */
  609             opts &= ~SSL_OP_NO_SSLv2;
  610         } else {
  611             /* Disable it: set the flag. */
  612             opts |= SSL_OP_NO_SSLv2;
  613         }
  614         break;
  615     }
  616 
  617     SSL_CTX_set_options(ctx->ctx, opts);
  618 }
  619 
  620 int ne_ssl_context_get_flag(ne_ssl_context *ctx, int flag)
  621 {
  622     switch (flag) {
  623     case NE_SSL_CTX_SSLv2:
  624 #ifdef OPENSSL_NO_SSL2
  625         return 0;
  626 #else
  627         return ! (SSL_CTX_get_options(ctx->ctx) & SSL_OP_NO_SSLv2);
  628 #endif
  629     default:
  630         break;
  631     }
  632 
  633     return 0;
  634 }
  635 
  636 int ne_ssl_context_keypair(ne_ssl_context *ctx, const char *cert,
  637                            const char *key)
  638 {
  639     int ret;
  640 
  641     ret = SSL_CTX_use_PrivateKey_file(ctx->ctx, key, SSL_FILETYPE_PEM);
  642     if (ret == 1) {
  643         ret = SSL_CTX_use_certificate_chain_file(ctx->ctx, cert);
  644     }
  645 
  646     return ret == 1 ? 0 : -1;
  647 }
  648 
  649 int ne_ssl_context_set_verify(ne_ssl_context *ctx, 
  650                               int required,
  651                               const char *ca_names,
  652                               const char *verify_cas)
  653 {
  654     if (required) {
  655         SSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER | 
  656                            SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  657     }
  658     if (ca_names) {
  659         SSL_CTX_set_client_CA_list(ctx->ctx, 
  660                                    SSL_load_client_CA_file(ca_names));
  661     }
  662     if (verify_cas) {
  663         SSL_CTX_load_verify_locations(ctx->ctx, verify_cas, NULL);
  664     }
  665     return 0;
  666 }
  667 
  668 void ne_ssl_context_destroy(ne_ssl_context *ctx)
  669 {
  670     SSL_CTX_free(ctx->ctx);
  671     if (ctx->sess)
  672         SSL_SESSION_free(ctx->sess);
  673     ne_free(ctx);
  674 }
  675 
  676 #if !defined(HAVE_SSL_SESSION_CMP) && !defined(SSL_SESSION_cmp) \
  677     && defined(OPENSSL_VERSION_NUMBER) \
  678     && OPENSSL_VERSION_NUMBER > 0x10000000L
  679 /* OpenSSL 1.0 removed SSL_SESSION_cmp for no apparent reason - hoping
  680  * it is reasonable to assume that comparing the session IDs is
  681  * sufficient. */
  682 static int SSL_SESSION_cmp(SSL_SESSION *a, SSL_SESSION *b)
  683 {
  684     const unsigned char *session1_buf, *session2_buf;
  685     unsigned int session1_len, session2_len;
  686 
  687     session1_buf = SSL_SESSION_get_id(a, &session1_len);
  688     session2_buf = SSL_SESSION_get_id(b, &session2_len);
  689 
  690     return session1_len == session2_len
  691         && memcmp(session1_buf, session2_buf, session1_len) == 0;
  692 }
  693 #endif
  694 
  695 /* For internal use only. */
  696 int ne__negotiate_ssl(ne_session *sess)
  697 {
  698     ne_ssl_context *ctx = sess->ssl_context;
  699     SSL *ssl;
  700     STACK_OF(X509) *chain;
  701     int freechain = 0; /* non-zero if chain should be free'd. */
  702 
  703     NE_DEBUG(NE_DBG_SSL, "Doing SSL negotiation.\n");
  704     
  705     /* Pass through the hostname if SNI is enabled. */
  706     ctx->hostname = 
  707         sess->flags[NE_SESSFLAG_TLS_SNI] ? sess->server.hostname : NULL;
  708 
  709     sess->ssl_cc_requested = 0;
  710     ctx->failures = 0;
  711 
  712     if (ne_sock_connect_ssl(sess->socket, ctx, sess)) {
  713     if (ctx->sess) {
  714         /* remove cached session. */
  715         SSL_SESSION_free(ctx->sess);
  716         ctx->sess = NULL;
  717     }
  718         if (sess->ssl_cc_requested) {
  719             ne_set_error(sess, _("SSL handshake failed, "
  720                                  "client certificate was requested: %s"),
  721                          ne_sock_error(sess->socket));
  722         }
  723         else {
  724             ne_set_error(sess, _("SSL handshake failed: %s"),
  725                          ne_sock_error(sess->socket));
  726         }
  727         return NE_ERROR;
  728     }   
  729     
  730     ssl = ne__sock_sslsock(sess->socket);
  731 
  732     chain = SSL_get_peer_cert_chain(ssl);
  733     /* For an SSLv2 connection, the cert chain will always be NULL. */
  734     if (chain == NULL) {
  735         X509 *cert = SSL_get_peer_certificate(ssl);
  736         if (cert) {
  737             chain = sk_X509_new_null();
  738             sk_X509_push(chain, cert);
  739             freechain = 1;
  740         }
  741     }
  742 
  743     if (chain == NULL || sk_X509_num(chain) == 0) {
  744     ne_set_error(sess, _("SSL server did not present certificate"));
  745     return NE_ERROR;
  746     }
  747 
  748     if (sess->server_cert 
  749         && X509_cmp(sk_X509_value(chain, 0), sess->server_cert->subject) == 0) {
  750         /* Same leaf cert used as last time - no need to reverify. */
  751         if (freechain) sk_X509_free(chain); /* no longer need the chain */
  752     } else {
  753     /* new connection: create the chain. */
  754         ne_ssl_certificate *cert = make_chain(chain);
  755 
  756         if (freechain) sk_X509_free(chain); /* no longer need the chain */
  757 
  758     if (check_certificate(sess, ssl, cert)) {
  759         NE_DEBUG(NE_DBG_SSL, "SSL certificate checks failed: %s\n",
  760              sess->error);
  761         ne_ssl_cert_free(cert);
  762         return NE_ERROR;
  763     }
  764     /* remember the chain. */
  765         sess->server_cert = cert;
  766     }
  767     
  768     if (ctx->sess) {
  769         SSL_SESSION *newsess = SSL_get0_session(ssl);
  770         /* Replace the session if it has changed. */ 
  771         if (newsess != ctx->sess || SSL_SESSION_cmp(ctx->sess, newsess)) {
  772             SSL_SESSION_free(ctx->sess);
  773             ctx->sess = SSL_get1_session(ssl); /* bumping the refcount */
  774         }
  775     } else {
  776     /* Store the session. */
  777     ctx->sess = SSL_get1_session(ssl);
  778     }
  779 
  780     return NE_OK;
  781 }
  782 
  783 const ne_ssl_dname *ne_ssl_cert_issuer(const ne_ssl_certificate *cert)
  784 {
  785     return &cert->issuer_dn;
  786 }
  787 
  788 const ne_ssl_dname *ne_ssl_cert_subject(const ne_ssl_certificate *cert)
  789 {
  790     return &cert->subj_dn;
  791 }
  792 
  793 const ne_ssl_certificate *ne_ssl_cert_signedby(const ne_ssl_certificate *cert)
  794 {
  795     return cert->issuer;
  796 }
  797 
  798 const char *ne_ssl_cert_identity(const ne_ssl_certificate *cert)
  799 {
  800     return cert->identity;
  801 }
  802 
  803 void ne_ssl_context_trustcert(ne_ssl_context *ctx, const ne_ssl_certificate *cert)
  804 {
  805     X509_STORE *store = SSL_CTX_get_cert_store(ctx->ctx);
  806     
  807     X509_STORE_add_cert(store, cert->subject);
  808 }
  809 
  810 void ne_ssl_trust_default_ca(ne_session *sess)
  811 {
  812     X509_STORE *store = SSL_CTX_get_cert_store(sess->ssl_context->ctx);
  813     
  814 #ifdef NE_SSL_CA_BUNDLE
  815     X509_STORE_load_locations(store, NE_SSL_CA_BUNDLE, NULL);
  816 #else
  817     X509_STORE_set_default_paths(store);
  818 #endif
  819 }
  820 
  821 /* Find a friendly name in a PKCS12 structure the hard way, without
  822  * decrypting the parts which are encrypted.. */
  823 static char *find_friendly_name(PKCS12 *p12)
  824 {
  825     STACK_OF(PKCS7) *safes = PKCS12_unpack_authsafes(p12);
  826     int n, m;
  827     char *name = NULL;
  828 
  829     if (safes == NULL) return NULL;
  830     
  831     /* Iterate over the unpacked authsafes: */
  832     for (n = 0; n < sk_PKCS7_num(safes) && !name; n++) {
  833         PKCS7 *safe = sk_PKCS7_value(safes, n);
  834         STACK_OF(PKCS12_SAFEBAG) *bags;
  835     
  836         /* Only looking for unencrypted authsafes. */
  837         if (OBJ_obj2nid(safe->type) != NID_pkcs7_data) continue;
  838 
  839         bags = PKCS12_unpack_p7data(safe);
  840         if (!bags) continue;
  841 
  842         /* Iterate through the bags, picking out a friendly name */
  843         for (m = 0; m < sk_PKCS12_SAFEBAG_num(bags) && !name; m++) {
  844             PKCS12_SAFEBAG *bag = sk_PKCS12_SAFEBAG_value(bags, m);
  845             name = PKCS12_get_friendlyname(bag);
  846         }
  847     
  848         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
  849     }
  850 
  851     sk_PKCS7_pop_free(safes, PKCS7_free);
  852     return name;
  853 }
  854 
  855 static ne_ssl_client_cert *parse_client_cert(PKCS12 *p12)
  856 {
  857     X509 *cert;
  858     EVP_PKEY *pkey;
  859     ne_ssl_client_cert *cc;
  860 
  861     if (p12 == NULL) {
  862         ERR_clear_error();
  863         return NULL;
  864     }
  865 
  866     /* Try parsing with no password. */
  867     if (PKCS12_parse(p12, NULL, &pkey, &cert, NULL) == 1) {
  868         /* Success - no password needed for decryption. */
  869         int len = 0;
  870         unsigned char *name;
  871 
  872         if (!cert || !pkey) {
  873             PKCS12_free(p12);
  874             return NULL;
  875         }
  876 
  877         name = X509_alias_get0(cert, &len);
  878         
  879         cc = ne_calloc(sizeof *cc);
  880         cc->pkey = pkey;
  881         cc->decrypted = 1;
  882         if (name && len > 0)
  883             cc->friendly_name = ne_strndup((char *)name, len);
  884         populate_cert(&cc->cert, cert);
  885         PKCS12_free(p12);
  886         return cc;
  887     } else {
  888         /* Failed to parse the file */
  889         int err = ERR_get_error();
  890         ERR_clear_error();
  891         if (ERR_GET_LIB(err) == ERR_LIB_PKCS12 &&
  892             ERR_GET_REASON(err) == PKCS12_R_MAC_VERIFY_FAILURE) {
  893             /* Decryption error due to bad password. */
  894             cc = ne_calloc(sizeof *cc);
  895             cc->friendly_name = find_friendly_name(p12);
  896             cc->p12 = p12;
  897             return cc;
  898         } else {
  899             /* Some parse error, give up. */
  900             PKCS12_free(p12);
  901             return NULL;
  902         }
  903     }
  904 }
  905 
  906 ne_ssl_client_cert *ne_ssl_clicert_import(const unsigned char *buffer, 
  907                                           size_t buflen)
  908 {
  909     ne_d2i_uchar *p;
  910     PKCS12 *p12;
  911 
  912     p = buffer;
  913     p12 = d2i_PKCS12(NULL, &p, buflen);
  914     
  915     return parse_client_cert(p12);
  916 }
  917     
  918 ne_ssl_client_cert *ne_ssl_clicert_read(const char *filename)
  919 {
  920     PKCS12 *p12;
  921     FILE *fp;
  922 
  923     fp = fopen(filename, "rb");
  924     if (fp == NULL)
  925         return NULL;
  926 
  927     p12 = d2i_PKCS12_fp(fp, NULL);
  928 
  929     fclose(fp);
  930 
  931     return parse_client_cert(p12);
  932 }
  933 
  934 #ifdef HAVE_PAKCHOIS
  935 ne_ssl_client_cert *ne__ssl_clicert_exkey_import(const unsigned char *der,
  936                                                  size_t der_len,
  937                                                  const RSA_METHOD *method)
  938 {
  939     ne_ssl_client_cert *cc;
  940     ne_d2i_uchar *p;
  941     X509 *x5;
  942     EVP_PKEY *pubkey, *privkey;
  943     RSA *rsa;
  944 
  945     p = der;
  946     x5 = d2i_X509(NULL, &p, der_len); /* p is incremented */
  947     if (x5 == NULL) {
  948         ERR_clear_error();
  949         return NULL;
  950     }
  951 
  952     pubkey = X509_get_pubkey(x5);
  953     if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_RSA) {
  954         X509_free(x5);
  955         NE_DEBUG(NE_DBG_SSL, "ssl: Only RSA private keys are supported via PKCS#11.\n");
  956         return NULL;
  957     }
  958 
  959     /* Duplicate the public parameters of the RSA key. */
  960     rsa = RSAPublicKey_dup(EVP_PKEY_get0_RSA(pubkey));
  961     /* Done with the copied public key. */
  962     EVP_PKEY_free(pubkey);
  963     
  964     /* Switch to using customer RSA_METHOD for RSA object. */
  965     RSA_set_method(rsa, method);
  966     /* Set up new EVP_PKEY. */
  967     privkey = EVP_PKEY_new();
  968     EVP_PKEY_assign_RSA(privkey, rsa);
  969     
  970     cc = ne_calloc(sizeof *cc);
  971     cc->decrypted = 1;
  972     cc->pkey = privkey;
  973 
  974     populate_cert(&cc->cert, x5);
  975 
  976     return cc;    
  977 }
  978 #endif
  979 
  980 int ne_ssl_clicert_encrypted(const ne_ssl_client_cert *cc)
  981 {
  982     return !cc->decrypted;
  983 }
  984 
  985 int ne_ssl_clicert_decrypt(ne_ssl_client_cert *cc, const char *password)
  986 {
  987     X509 *cert;
  988     EVP_PKEY *pkey;
  989 
  990     if (PKCS12_parse(cc->p12, password, &pkey, &cert, NULL) != 1) {
  991         ERR_clear_error();
  992         return -1;
  993     }
  994     
  995     if (X509_check_private_key(cert, pkey) != 1) {
  996         ERR_clear_error();
  997         X509_free(cert);
  998         EVP_PKEY_free(pkey);
  999         NE_DEBUG(NE_DBG_SSL, "Decrypted private key/cert are not matched.");
 1000         return -1;
 1001     }
 1002 
 1003     PKCS12_free(cc->p12);
 1004     populate_cert(&cc->cert, cert);
 1005     cc->pkey = pkey;
 1006     cc->decrypted = 1;
 1007     cc->p12 = NULL;
 1008     return 0;
 1009 }
 1010 
 1011 const ne_ssl_certificate *ne_ssl_clicert_owner(const ne_ssl_client_cert *cc)
 1012 {
 1013     return &cc->cert;
 1014 }
 1015 
 1016 const char *ne_ssl_clicert_name(const ne_ssl_client_cert *ccert)
 1017 {
 1018     return ccert->friendly_name;
 1019 }
 1020 
 1021 ne_ssl_certificate *ne_ssl_cert_read(const char *filename)
 1022 {
 1023     FILE *fp = fopen(filename, "r");
 1024     X509 *cert;
 1025 
 1026     if (fp == NULL)
 1027         return NULL;
 1028 
 1029     cert = PEM_read_X509(fp, NULL, NULL, NULL);
 1030     fclose(fp);
 1031 
 1032     if (cert == NULL) {
 1033         NE_DEBUG(NE_DBG_SSL, "d2i_X509_fp failed: %s\n", 
 1034                  ERR_reason_error_string(ERR_get_error()));
 1035         ERR_clear_error();
 1036         return NULL;
 1037     }
 1038 
 1039     return populate_cert(ne_calloc(sizeof(struct ne_ssl_certificate_s)), cert);
 1040 }
 1041 
 1042 int ne_ssl_cert_write(const ne_ssl_certificate *cert, const char *filename)
 1043 {
 1044     FILE *fp = fopen(filename, "w");
 1045 
 1046     if (fp == NULL) return -1;
 1047 
 1048     if (PEM_write_X509(fp, cert->subject) != 1) {
 1049         ERR_clear_error();
 1050         fclose(fp);
 1051         return -1;
 1052     }
 1053     
 1054     if (fclose(fp) != 0)
 1055         return -1;
 1056 
 1057     return 0;
 1058 }
 1059 
 1060 void ne_ssl_cert_free(ne_ssl_certificate *cert)
 1061 {
 1062     X509_free(cert->subject);
 1063     if (cert->issuer)
 1064         ne_ssl_cert_free(cert->issuer);
 1065     if (cert->identity)
 1066         ne_free(cert->identity);
 1067     ne_free(cert);
 1068 }
 1069 
 1070 int ne_ssl_cert_cmp(const ne_ssl_certificate *c1, const ne_ssl_certificate *c2)
 1071 {
 1072     return X509_cmp(c1->subject, c2->subject);
 1073 }
 1074 
 1075 /* The certificate import/export format is the base64 encoding of the
 1076  * raw DER; PEM without the newlines and wrapping. */
 1077 
 1078 ne_ssl_certificate *ne_ssl_cert_import(const char *data)
 1079 {
 1080     unsigned char *der;
 1081     ne_d2i_uchar *p;
 1082     size_t len;
 1083     X509 *x5;
 1084     
 1085     /* decode the base64 to get the raw DER representation */
 1086     len = ne_unbase64(data, &der);
 1087     if (len == 0) return NULL;
 1088 
 1089     p = der;
 1090     x5 = d2i_X509(NULL, &p, len); /* p is incremented */
 1091     ne_free(der);
 1092     if (x5 == NULL) {
 1093         ERR_clear_error();
 1094         return NULL;
 1095     }
 1096 
 1097     return populate_cert(ne_calloc(sizeof(struct ne_ssl_certificate_s)), x5);
 1098 }
 1099 
 1100 char *ne_ssl_cert_export(const ne_ssl_certificate *cert)
 1101 {
 1102     int len;
 1103     unsigned char *der, *p;
 1104     char *ret;
 1105     
 1106     /* find the length of the DER encoding. */
 1107     len = i2d_X509(cert->subject, NULL);
 1108 
 1109     p = der = ne_malloc(len);
 1110     i2d_X509(cert->subject, &p); /* p is incremented */
 1111 
 1112     ret = ne_base64(der, len);
 1113     ne_free(der);
 1114     return ret;
 1115 }
 1116 
 1117 #if SHA_DIGEST_LENGTH != 20
 1118 # error SHA digest length is not 20 bytes
 1119 #endif
 1120 
 1121 int ne_ssl_cert_digest(const ne_ssl_certificate *cert, char *digest)
 1122 {
 1123     unsigned char sha1[EVP_MAX_MD_SIZE];
 1124     unsigned int len, j;
 1125     char *p;
 1126 
 1127     if (!X509_digest(cert->subject, EVP_sha1(), sha1, &len) || len != 20) {
 1128         ERR_clear_error();
 1129         return -1;
 1130     }
 1131     
 1132     for (j = 0, p = digest; j < 20; j++) {
 1133         *p++ = NE_HEX2ASC((sha1[j] >> 4) & 0x0f);
 1134         *p++ = NE_HEX2ASC(sha1[j] & 0x0f);
 1135         *p++ = ':';
 1136     }
 1137 
 1138     p[-1] = '\0';
 1139     return 0;
 1140 }
 1141 
 1142 #if defined(NE_HAVE_TS_SSL) && OPENSSL_VERSION_NUMBER < 0x10100000L
 1143 /* From OpenSSL 1.1.0 locking callbacks are no longer needed. */
 1144 #define WITH_OPENSSL_LOCKING (1)
 1145 
 1146 /* Implementation of locking callbacks to make OpenSSL thread-safe.
 1147  * If the OpenSSL API was better designed, this wouldn't be necessary.
 1148  * In OpenSSL releases without CRYPTO_set_idptr_callback, it's not
 1149  * possible to implement the locking in a POSIX-compliant way, since
 1150  * it's necessary to cast from a pthread_t to an unsigned long at some
 1151  * point.  */
 1152 
 1153 #ifndef _WIN32
 1154 static pthread_mutex_t *locks;
 1155 #else
 1156 static HANDLE *locks;
 1157 #endif
 1158 static size_t num_locks;
 1159 
 1160 #ifndef HAVE_CRYPTO_SET_IDPTR_CALLBACK
 1161 /* Named to be obvious when it shows up in a backtrace. */
 1162 static unsigned long thread_id_neon(void)
 1163 {
 1164 #ifndef _WIN32
 1165     /* This will break if pthread_t is a structure; upgrading OpenSSL
 1166      * >= 0.9.9 (which does not require this callback) is the only
 1167      * solution.  */
 1168     return (unsigned long) pthread_self();
 1169 #else
 1170     return (unsigned long) GetCurrentThreadId();
 1171 #endif
 1172 }
 1173 #endif
 1174 
 1175 /* Another great API design win for OpenSSL: no return value!  So if
 1176  * the lock/unlock fails, all that can be done is to abort. */
 1177 static void thread_lock_neon(int mode, int n, const char *file, int line)
 1178 {
 1179     if (mode & CRYPTO_LOCK) {
 1180 #ifndef _WIN32
 1181         if (pthread_mutex_lock(&locks[n])) {
 1182 #else
 1183         if (WaitForSingleObject(locks[n], INFINITE)) {
 1184 #endif
 1185             abort();
 1186         }
 1187     }
 1188     else {
 1189 #ifndef _WIN32
 1190         if (pthread_mutex_unlock(&locks[n])) {
 1191 #else
 1192         if (!ReleaseMutex(locks[n])) {
 1193 #endif
 1194             abort();
 1195         }
 1196     }
 1197 }
 1198 
 1199 /* ID_CALLBACK_IS_{NEON,OTHER} evaluate as true if the currently
 1200  * registered OpenSSL ID callback is the neon function (_NEON), or has
 1201  * been overwritten by some other app (_OTHER). */
 1202 #ifdef HAVE_CRYPTO_SET_IDPTR_CALLBACK
 1203 #define ID_CALLBACK_IS_OTHER (0)
 1204 #define ID_CALLBACK_IS_NEON (1)
 1205 #else
 1206 #define ID_CALLBACK_IS_OTHER (CRYPTO_get_id_callback() != NULL)
 1207 #define ID_CALLBACK_IS_NEON (CRYPTO_get_id_callback() == thread_id_neon)
 1208 #endif
 1209         
 1210 #endif /* NE_HAVE_TS_SSL && OPENSSL_VERSION_NUMBER < 1.1.1 */
 1211 
 1212 int ne__ssl_init(void)
 1213 {
 1214 #if OPENSSL_VERSION_NUMBER < 0x10100000L
 1215     CRYPTO_malloc_init();
 1216     SSL_load_error_strings();
 1217     SSL_library_init();
 1218     OpenSSL_add_all_algorithms();
 1219 
 1220 #ifdef WITH_OPENSSL_LOCKING
 1221     /* If some other library has already come along and set up the
 1222      * thread-safety callbacks, then it must be presumed that the
 1223      * other library will have a longer lifetime in the process than
 1224      * neon.  If the library which has installed the callbacks is
 1225      * unloaded, then all bets are off. */
 1226     if (ID_CALLBACK_IS_OTHER || CRYPTO_get_locking_callback() != NULL) {
 1227         NE_DEBUG(NE_DBG_SOCKET, "ssl: OpenSSL thread-safety callbacks already installed.\n");
 1228         NE_DEBUG(NE_DBG_SOCKET, "ssl: neon will not replace existing callbacks.\n");
 1229     } else {
 1230         size_t n;
 1231 
 1232         num_locks = CRYPTO_num_locks();
 1233 
 1234         /* For releases where CRYPTO_set_idptr_callback is present,
 1235          * the default ID callback should be sufficient. */
 1236 #ifndef HAVE_CRYPTO_SET_IDPTR_CALLBACK
 1237         CRYPTO_set_id_callback(thread_id_neon);
 1238 #endif
 1239         CRYPTO_set_locking_callback(thread_lock_neon);
 1240 
 1241         locks = malloc(num_locks * sizeof *locks);
 1242         for (n = 0; n < num_locks; n++) {
 1243 #ifndef _WIN32
 1244             if (pthread_mutex_init(&locks[n], NULL)) {
 1245 #else
 1246             if ((locks[n] = CreateMutex(NULL, FALSE, NULL)) == NULL) {
 1247 #endif
 1248                 NE_DEBUG(NE_DBG_SOCKET, "ssl: Failed to initialize pthread mutex.\n");
 1249                 return -1;
 1250             }
 1251         }
 1252         
 1253         NE_DEBUG(NE_DBG_SOCKET, "ssl: Initialized OpenSSL thread-safety callbacks "
 1254                  "for %" NE_FMT_SIZE_T " locks.\n", num_locks);
 1255     }
 1256 #endif
 1257 #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
 1258 
 1259     return 0;
 1260 }
 1261 
 1262 void ne__ssl_exit(void)
 1263 {
 1264     /* Cannot call ERR_free_strings() etc here in case any other code
 1265      * in the process using OpenSSL. */
 1266 
 1267 #ifdef WITH_OPENSSL_LOCKING
 1268     /* Only unregister the callbacks if some *other* library has not
 1269      * come along in the mean-time and trampled over the callbacks
 1270      * installed by neon. */
 1271     if (CRYPTO_get_locking_callback() == thread_lock_neon
 1272         && ID_CALLBACK_IS_NEON) {
 1273         size_t n;
 1274 
 1275 #ifndef HAVE_CRYPTO_SET_IDPTR_CALLBACK
 1276         CRYPTO_set_id_callback(NULL);
 1277 #endif
 1278         CRYPTO_set_locking_callback(NULL);
 1279 
 1280         for (n = 0; n < num_locks; n++) {
 1281 #ifndef _WIN32
 1282             pthread_mutex_destroy(&locks[n]);
 1283 #else
 1284             CloseHandle(locks[n]);
 1285 #endif
 1286         }
 1287 
 1288         free(locks);
 1289     }
 1290 #endif
 1291 }