• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 
23 /*
24  * Source file for all CyaSSL-specific code for the TLS/SSL layer. No code
25  * but vtls.c should ever call or use these functions.
26  *
27  */
28 
29 #include "curl_setup.h"
30 
31 #ifdef USE_CYASSL
32 
33 #define WOLFSSL_OPTIONS_IGNORE_SYS
34 /* CyaSSL's version.h, which should contain only the version, should come
35 before all other CyaSSL includes and be immediately followed by build config
36 aka options.h. https://curl.haxx.se/mail/lib-2015-04/0069.html */
37 #include <cyassl/version.h>
38 #if defined(HAVE_CYASSL_OPTIONS_H) && (LIBCYASSL_VERSION_HEX > 0x03004008)
39 #if defined(CYASSL_API) || defined(WOLFSSL_API)
40 /* Safety measure. If either is defined some API include was already included
41 and that's a problem since options.h hasn't been included yet. */
42 #error "CyaSSL API was included before the CyaSSL build options."
43 #endif
44 #include <cyassl/options.h>
45 #endif
46 
47 /* To determine what functions are available we rely on one or both of:
48    - the user's options.h generated by CyaSSL/wolfSSL
49    - the symbols detected by curl's configure
50    Since they are markedly different from one another, and one or the other may
51    not be available, we do some checking below to bring things in sync. */
52 
53 /* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */
54 #ifndef HAVE_ALPN
55 #ifdef HAVE_WOLFSSL_USEALPN
56 #define HAVE_ALPN
57 #endif
58 #endif
59 
60 /* WOLFSSL_ALLOW_SSLV3 is wolfSSL's build time symbol for enabling SSLv3 in
61    options.h, but is only seen in >= 3.6.6 since that's when they started
62    disabling SSLv3 by default. */
63 #ifndef WOLFSSL_ALLOW_SSLV3
64 #if (LIBCYASSL_VERSION_HEX < 0x03006006) || \
65     defined(HAVE_WOLFSSLV3_CLIENT_METHOD)
66 #define WOLFSSL_ALLOW_SSLV3
67 #endif
68 #endif
69 
70 /* HAVE_SUPPORTED_CURVES is wolfSSL's build time symbol for enabling the ECC
71    supported curve extension in options.h. Note ECC is enabled separately. */
72 #ifndef HAVE_SUPPORTED_CURVES
73 #if defined(HAVE_CYASSL_CTX_USESUPPORTEDCURVE) || \
74     defined(HAVE_WOLFSSL_CTX_USESUPPORTEDCURVE)
75 #define HAVE_SUPPORTED_CURVES
76 #endif
77 #endif
78 
79 #include <limits.h>
80 
81 #include "urldata.h"
82 #include "sendf.h"
83 #include "inet_pton.h"
84 #include "vtls.h"
85 #include "parsedate.h"
86 #include "connect.h" /* for the connect timeout */
87 #include "select.h"
88 #include "strcase.h"
89 #include "x509asn1.h"
90 #include "curl_printf.h"
91 
92 #include <cyassl/openssl/ssl.h>
93 #include <cyassl/ssl.h>
94 #ifdef HAVE_CYASSL_ERROR_SSL_H
95 #include <cyassl/error-ssl.h>
96 #else
97 #include <cyassl/error.h>
98 #endif
99 #include <cyassl/ctaocrypt/random.h>
100 #include <cyassl/ctaocrypt/sha256.h>
101 
102 #include "cyassl.h"
103 
104 /* The last #include files should be: */
105 #include "curl_memory.h"
106 #include "memdebug.h"
107 
108 #if LIBCYASSL_VERSION_HEX < 0x02007002 /* < 2.7.2 */
109 #define CYASSL_MAX_ERROR_SZ 80
110 #endif
111 
112 /* KEEP_PEER_CERT is a product of the presence of build time symbol
113    OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
114    in wolfSSL's settings.h, and the latter two are build time symbols in
115    options.h. */
116 #ifndef KEEP_PEER_CERT
117 #if defined(HAVE_CYASSL_GET_PEER_CERTIFICATE) || \
118     defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
119     (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
120 #define KEEP_PEER_CERT
121 #endif
122 #endif
123 
124 struct ssl_backend_data {
125   SSL_CTX* ctx;
126   SSL*     handle;
127 };
128 
129 #define BACKEND connssl->backend
130 
131 static Curl_recv cyassl_recv;
132 static Curl_send cyassl_send;
133 
134 
do_file_type(const char * type)135 static int do_file_type(const char *type)
136 {
137   if(!type || !type[0])
138     return SSL_FILETYPE_PEM;
139   if(strcasecompare(type, "PEM"))
140     return SSL_FILETYPE_PEM;
141   if(strcasecompare(type, "DER"))
142     return SSL_FILETYPE_ASN1;
143   return -1;
144 }
145 
146 /*
147  * This function loads all the client/CA certificates and CRLs. Setup the TLS
148  * layer and do all necessary magic.
149  */
150 static CURLcode
cyassl_connect_step1(struct connectdata * conn,int sockindex)151 cyassl_connect_step1(struct connectdata *conn,
152                      int sockindex)
153 {
154   char error_buffer[CYASSL_MAX_ERROR_SZ];
155   char *ciphers;
156   struct Curl_easy *data = conn->data;
157   struct ssl_connect_data* connssl = &conn->ssl[sockindex];
158   SSL_METHOD* req_method = NULL;
159   curl_socket_t sockfd = conn->sock[sockindex];
160 #ifdef HAVE_SNI
161   bool sni = FALSE;
162 #define use_sni(x)  sni = (x)
163 #else
164 #define use_sni(x)  Curl_nop_stmt
165 #endif
166 
167   if(connssl->state == ssl_connection_complete)
168     return CURLE_OK;
169 
170   if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) {
171     failf(data, "CyaSSL does not support to set maximum SSL/TLS version");
172     return CURLE_SSL_CONNECT_ERROR;
173   }
174 
175   /* check to see if we've been told to use an explicit SSL/TLS version */
176   switch(SSL_CONN_CONFIG(version)) {
177   case CURL_SSLVERSION_DEFAULT:
178   case CURL_SSLVERSION_TLSv1:
179 #if LIBCYASSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */
180     /* minimum protocol version is set later after the CTX object is created */
181     req_method = SSLv23_client_method();
182 #else
183     infof(data, "CyaSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, "
184           "TLS 1.0 is used exclusively\n");
185     req_method = TLSv1_client_method();
186 #endif
187     use_sni(TRUE);
188     break;
189   case CURL_SSLVERSION_TLSv1_0:
190     req_method = TLSv1_client_method();
191     use_sni(TRUE);
192     break;
193   case CURL_SSLVERSION_TLSv1_1:
194     req_method = TLSv1_1_client_method();
195     use_sni(TRUE);
196     break;
197   case CURL_SSLVERSION_TLSv1_2:
198     req_method = TLSv1_2_client_method();
199     use_sni(TRUE);
200     break;
201   case CURL_SSLVERSION_TLSv1_3:
202     failf(data, "CyaSSL: TLS 1.3 is not yet supported");
203     return CURLE_SSL_CONNECT_ERROR;
204   case CURL_SSLVERSION_SSLv3:
205 #ifdef WOLFSSL_ALLOW_SSLV3
206     req_method = SSLv3_client_method();
207     use_sni(FALSE);
208 #else
209     failf(data, "CyaSSL does not support SSLv3");
210     return CURLE_NOT_BUILT_IN;
211 #endif
212     break;
213   case CURL_SSLVERSION_SSLv2:
214     failf(data, "CyaSSL does not support SSLv2");
215     return CURLE_SSL_CONNECT_ERROR;
216   default:
217     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
218     return CURLE_SSL_CONNECT_ERROR;
219   }
220 
221   if(!req_method) {
222     failf(data, "SSL: couldn't create a method!");
223     return CURLE_OUT_OF_MEMORY;
224   }
225 
226   if(BACKEND->ctx)
227     SSL_CTX_free(BACKEND->ctx);
228   BACKEND->ctx = SSL_CTX_new(req_method);
229 
230   if(!BACKEND->ctx) {
231     failf(data, "SSL: couldn't create a context!");
232     return CURLE_OUT_OF_MEMORY;
233   }
234 
235   switch(SSL_CONN_CONFIG(version)) {
236   case CURL_SSLVERSION_DEFAULT:
237   case CURL_SSLVERSION_TLSv1:
238 #if LIBCYASSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */
239     /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is whatever
240     minimum version of TLS was built in and at least TLS 1.0. For later library
241     versions that could change (eg TLS 1.0 built in but defaults to TLS 1.1) so
242     we have this short circuit evaluation to find the minimum supported TLS
243     version. We use wolfSSL_CTX_SetMinVersion and not CyaSSL_SetMinVersion
244     because only the former will work before the user's CTX callback is called.
245     */
246     if((wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1) != 1) &&
247        (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_1) != 1) &&
248        (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_2) != 1)) {
249       failf(data, "SSL: couldn't set the minimum protocol version");
250       return CURLE_SSL_CONNECT_ERROR;
251     }
252 #endif
253     break;
254   }
255 
256   ciphers = SSL_CONN_CONFIG(cipher_list);
257   if(ciphers) {
258     if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
259       failf(data, "failed setting cipher list: %s", ciphers);
260       return CURLE_SSL_CIPHER;
261     }
262     infof(data, "Cipher selection: %s\n", ciphers);
263   }
264 
265 #ifndef NO_FILESYSTEM
266   /* load trusted cacert */
267   if(SSL_CONN_CONFIG(CAfile)) {
268     if(1 != SSL_CTX_load_verify_locations(BACKEND->ctx,
269                                       SSL_CONN_CONFIG(CAfile),
270                                       SSL_CONN_CONFIG(CApath))) {
271       if(SSL_CONN_CONFIG(verifypeer)) {
272         /* Fail if we insist on successfully verifying the server. */
273         failf(data, "error setting certificate verify locations:\n"
274               "  CAfile: %s\n  CApath: %s",
275               SSL_CONN_CONFIG(CAfile)?
276               SSL_CONN_CONFIG(CAfile): "none",
277               SSL_CONN_CONFIG(CApath)?
278               SSL_CONN_CONFIG(CApath) : "none");
279         return CURLE_SSL_CACERT_BADFILE;
280       }
281       else {
282         /* Just continue with a warning if no strict certificate
283            verification is required. */
284         infof(data, "error setting certificate verify locations,"
285               " continuing anyway:\n");
286       }
287     }
288     else {
289       /* Everything is fine. */
290       infof(data, "successfully set certificate verify locations:\n");
291     }
292     infof(data,
293           "  CAfile: %s\n"
294           "  CApath: %s\n",
295           SSL_CONN_CONFIG(CAfile) ? SSL_CONN_CONFIG(CAfile):
296           "none",
297           SSL_CONN_CONFIG(CApath) ? SSL_CONN_CONFIG(CApath):
298           "none");
299   }
300 
301   /* Load the client certificate, and private key */
302   if(SSL_SET_OPTION(cert) && SSL_SET_OPTION(key)) {
303     int file_type = do_file_type(SSL_SET_OPTION(cert_type));
304 
305     if(SSL_CTX_use_certificate_file(BACKEND->ctx, SSL_SET_OPTION(cert),
306                                      file_type) != 1) {
307       failf(data, "unable to use client certificate (no key or wrong pass"
308             " phrase?)");
309       return CURLE_SSL_CONNECT_ERROR;
310     }
311 
312     file_type = do_file_type(SSL_SET_OPTION(key_type));
313     if(SSL_CTX_use_PrivateKey_file(BACKEND->ctx, SSL_SET_OPTION(key),
314                                     file_type) != 1) {
315       failf(data, "unable to set private key");
316       return CURLE_SSL_CONNECT_ERROR;
317     }
318   }
319 #endif /* !NO_FILESYSTEM */
320 
321   /* SSL always tries to verify the peer, this only says whether it should
322    * fail to connect if the verification fails, or if it should continue
323    * anyway. In the latter case the result of the verification is checked with
324    * SSL_get_verify_result() below. */
325   SSL_CTX_set_verify(BACKEND->ctx,
326                      SSL_CONN_CONFIG(verifypeer)?SSL_VERIFY_PEER:
327                                                  SSL_VERIFY_NONE,
328                      NULL);
329 
330 #ifdef HAVE_SNI
331   if(sni) {
332     struct in_addr addr4;
333 #ifdef ENABLE_IPV6
334     struct in6_addr addr6;
335 #endif
336     const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
337       conn->host.name;
338     size_t hostname_len = strlen(hostname);
339     if((hostname_len < USHRT_MAX) &&
340        (0 == Curl_inet_pton(AF_INET, hostname, &addr4)) &&
341 #ifdef ENABLE_IPV6
342        (0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) &&
343 #endif
344        (CyaSSL_CTX_UseSNI(BACKEND->ctx, CYASSL_SNI_HOST_NAME, hostname,
345                           (unsigned short)hostname_len) != 1)) {
346       infof(data, "WARNING: failed to configure server name indication (SNI) "
347             "TLS extension\n");
348     }
349   }
350 #endif
351 
352 #ifdef HAVE_SUPPORTED_CURVES
353   /* CyaSSL/wolfSSL does not send the supported ECC curves ext automatically:
354      https://github.com/wolfSSL/wolfssl/issues/366
355      The supported curves below are those also supported by OpenSSL 1.0.2 and
356      in the same order. */
357   CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x17); /* secp256r1 */
358   CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x19); /* secp521r1 */
359   CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x18); /* secp384r1 */
360 #endif
361 
362   /* give application a chance to interfere with SSL set up. */
363   if(data->set.ssl.fsslctx) {
364     CURLcode result = CURLE_OK;
365     result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
366                                       data->set.ssl.fsslctxp);
367     if(result) {
368       failf(data, "error signaled by ssl ctx callback");
369       return result;
370     }
371   }
372 #ifdef NO_FILESYSTEM
373   else if(SSL_CONN_CONFIG(verifypeer)) {
374     failf(data, "SSL: Certificates couldn't be loaded because CyaSSL was built"
375           " with \"no filesystem\". Either disable peer verification"
376           " (insecure) or if you are building an application with libcurl you"
377           " can load certificates via CURLOPT_SSL_CTX_FUNCTION.");
378     return CURLE_SSL_CONNECT_ERROR;
379   }
380 #endif
381 
382   /* Let's make an SSL structure */
383   if(BACKEND->handle)
384     SSL_free(BACKEND->handle);
385   BACKEND->handle = SSL_new(BACKEND->ctx);
386   if(!BACKEND->handle) {
387     failf(data, "SSL: couldn't create a context (handle)!");
388     return CURLE_OUT_OF_MEMORY;
389   }
390 
391 #ifdef HAVE_ALPN
392   if(conn->bits.tls_enable_alpn) {
393     char protocols[128];
394     *protocols = '\0';
395 
396     /* wolfSSL's ALPN protocol name list format is a comma separated string of
397        protocols in descending order of preference, eg: "h2,http/1.1" */
398 
399 #ifdef USE_NGHTTP2
400     if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
401       strcpy(protocols + strlen(protocols), NGHTTP2_PROTO_VERSION_ID ",");
402       infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
403     }
404 #endif
405 
406     strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1);
407     infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
408 
409     if(wolfSSL_UseALPN(BACKEND->handle, protocols,
410                        (unsigned)strlen(protocols),
411                        WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) {
412       failf(data, "SSL: failed setting ALPN protocols");
413       return CURLE_SSL_CONNECT_ERROR;
414     }
415   }
416 #endif /* HAVE_ALPN */
417 
418   /* Check if there's a cached ID we can/should use here! */
419   if(SSL_SET_OPTION(primary.sessionid)) {
420     void *ssl_sessionid = NULL;
421 
422     Curl_ssl_sessionid_lock(conn);
423     if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
424       /* we got a session id, use it! */
425       if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
426         Curl_ssl_sessionid_unlock(conn);
427         failf(data, "SSL: SSL_set_session failed: %s",
428               ERR_error_string(SSL_get_error(BACKEND->handle, 0),
429               error_buffer));
430         return CURLE_SSL_CONNECT_ERROR;
431       }
432       /* Informational message */
433       infof(data, "SSL re-using session ID\n");
434     }
435     Curl_ssl_sessionid_unlock(conn);
436   }
437 
438   /* pass the raw socket into the SSL layer */
439   if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
440     failf(data, "SSL: SSL_set_fd failed");
441     return CURLE_SSL_CONNECT_ERROR;
442   }
443 
444   connssl->connecting_state = ssl_connect_2;
445   return CURLE_OK;
446 }
447 
448 
449 static CURLcode
cyassl_connect_step2(struct connectdata * conn,int sockindex)450 cyassl_connect_step2(struct connectdata *conn,
451                      int sockindex)
452 {
453   int ret = -1;
454   struct Curl_easy *data = conn->data;
455   struct ssl_connect_data* connssl = &conn->ssl[sockindex];
456   const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
457     conn->host.name;
458   const char * const dispname = SSL_IS_PROXY() ?
459     conn->http_proxy.host.dispname : conn->host.dispname;
460   const char * const pinnedpubkey = SSL_IS_PROXY() ?
461                         data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
462                         data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
463 
464   conn->recv[sockindex] = cyassl_recv;
465   conn->send[sockindex] = cyassl_send;
466 
467   /* Enable RFC2818 checks */
468   if(SSL_CONN_CONFIG(verifyhost)) {
469     ret = CyaSSL_check_domain_name(BACKEND->handle, hostname);
470     if(ret == SSL_FAILURE)
471       return CURLE_OUT_OF_MEMORY;
472   }
473 
474   ret = SSL_connect(BACKEND->handle);
475   if(ret != 1) {
476     char error_buffer[CYASSL_MAX_ERROR_SZ];
477     int  detail = SSL_get_error(BACKEND->handle, ret);
478 
479     if(SSL_ERROR_WANT_READ == detail) {
480       connssl->connecting_state = ssl_connect_2_reading;
481       return CURLE_OK;
482     }
483     else if(SSL_ERROR_WANT_WRITE == detail) {
484       connssl->connecting_state = ssl_connect_2_writing;
485       return CURLE_OK;
486     }
487     /* There is no easy way to override only the CN matching.
488      * This will enable the override of both mismatching SubjectAltNames
489      * as also mismatching CN fields */
490     else if(DOMAIN_NAME_MISMATCH == detail) {
491 #if 1
492       failf(data, "\tsubject alt name(s) or common name do not match \"%s\"\n",
493             dispname);
494       return CURLE_PEER_FAILED_VERIFICATION;
495 #else
496       /* When the CyaSSL_check_domain_name() is used and you desire to continue
497        * on a DOMAIN_NAME_MISMATCH, i.e. 'conn->ssl_config.verifyhost == 0',
498        * CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA error. The only
499        * way to do this is currently to switch the CyaSSL_check_domain_name()
500        * in and out based on the 'conn->ssl_config.verifyhost' value. */
501       if(SSL_CONN_CONFIG(verifyhost)) {
502         failf(data,
503               "\tsubject alt name(s) or common name do not match \"%s\"\n",
504               dispname);
505         return CURLE_PEER_FAILED_VERIFICATION;
506       }
507       else {
508         infof(data,
509               "\tsubject alt name(s) and/or common name do not match \"%s\"\n",
510               dispname);
511         return CURLE_OK;
512       }
513 #endif
514     }
515 #if LIBCYASSL_VERSION_HEX >= 0x02007000 /* 2.7.0 */
516     else if(ASN_NO_SIGNER_E == detail) {
517       if(SSL_CONN_CONFIG(verifypeer)) {
518         failf(data, "\tCA signer not available for verification\n");
519         return CURLE_SSL_CACERT_BADFILE;
520       }
521       else {
522         /* Just continue with a warning if no strict certificate
523            verification is required. */
524         infof(data, "CA signer not available for verification, "
525                     "continuing anyway\n");
526       }
527     }
528 #endif
529     else {
530       failf(data, "SSL_connect failed with error %d: %s", detail,
531           ERR_error_string(detail, error_buffer));
532       return CURLE_SSL_CONNECT_ERROR;
533     }
534   }
535 
536   if(pinnedpubkey) {
537 #ifdef KEEP_PEER_CERT
538     X509 *x509;
539     const char *x509_der;
540     int x509_der_len;
541     curl_X509certificate x509_parsed;
542     curl_asn1Element *pubkey;
543     CURLcode result;
544 
545     x509 = SSL_get_peer_certificate(BACKEND->handle);
546     if(!x509) {
547       failf(data, "SSL: failed retrieving server certificate");
548       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
549     }
550 
551     x509_der = (const char *)CyaSSL_X509_get_der(x509, &x509_der_len);
552     if(!x509_der) {
553       failf(data, "SSL: failed retrieving ASN.1 server certificate");
554       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
555     }
556 
557     memset(&x509_parsed, 0, sizeof x509_parsed);
558     if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
559       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
560 
561     pubkey = &x509_parsed.subjectPublicKeyInfo;
562     if(!pubkey->header || pubkey->end <= pubkey->header) {
563       failf(data, "SSL: failed retrieving public key from server certificate");
564       return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
565     }
566 
567     result = Curl_pin_peer_pubkey(data,
568                                   pinnedpubkey,
569                                   (const unsigned char *)pubkey->header,
570                                   (size_t)(pubkey->end - pubkey->header));
571     if(result) {
572       failf(data, "SSL: public key does not match pinned public key!");
573       return result;
574     }
575 #else
576     failf(data, "Library lacks pinning support built-in");
577     return CURLE_NOT_BUILT_IN;
578 #endif
579   }
580 
581 #ifdef HAVE_ALPN
582   if(conn->bits.tls_enable_alpn) {
583     int rc;
584     char *protocol = NULL;
585     unsigned short protocol_len = 0;
586 
587     rc = wolfSSL_ALPN_GetProtocol(BACKEND->handle, &protocol, &protocol_len);
588 
589     if(rc == SSL_SUCCESS) {
590       infof(data, "ALPN, server accepted to use %.*s\n", protocol_len,
591             protocol);
592 
593       if(protocol_len == ALPN_HTTP_1_1_LENGTH &&
594          !memcmp(protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH))
595         conn->negnpn = CURL_HTTP_VERSION_1_1;
596 #ifdef USE_NGHTTP2
597       else if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
598               protocol_len == NGHTTP2_PROTO_VERSION_ID_LEN &&
599               !memcmp(protocol, NGHTTP2_PROTO_VERSION_ID,
600                       NGHTTP2_PROTO_VERSION_ID_LEN))
601         conn->negnpn = CURL_HTTP_VERSION_2;
602 #endif
603       else
604         infof(data, "ALPN, unrecognized protocol %.*s\n", protocol_len,
605               protocol);
606     }
607     else if(rc == SSL_ALPN_NOT_FOUND)
608       infof(data, "ALPN, server did not agree to a protocol\n");
609     else {
610       failf(data, "ALPN, failure getting protocol, error %d", rc);
611       return CURLE_SSL_CONNECT_ERROR;
612     }
613   }
614 #endif /* HAVE_ALPN */
615 
616   connssl->connecting_state = ssl_connect_3;
617 #if (LIBCYASSL_VERSION_HEX >= 0x03009010)
618   infof(data, "SSL connection using %s / %s\n",
619         wolfSSL_get_version(BACKEND->handle),
620         wolfSSL_get_cipher_name(BACKEND->handle));
621 #else
622   infof(data, "SSL connected\n");
623 #endif
624 
625   return CURLE_OK;
626 }
627 
628 
629 static CURLcode
cyassl_connect_step3(struct connectdata * conn,int sockindex)630 cyassl_connect_step3(struct connectdata *conn,
631                      int sockindex)
632 {
633   CURLcode result = CURLE_OK;
634   struct Curl_easy *data = conn->data;
635   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
636 
637   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
638 
639   if(SSL_SET_OPTION(primary.sessionid)) {
640     bool incache;
641     SSL_SESSION *our_ssl_sessionid;
642     void *old_ssl_sessionid = NULL;
643 
644     our_ssl_sessionid = SSL_get_session(BACKEND->handle);
645 
646     Curl_ssl_sessionid_lock(conn);
647     incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
648                                       sockindex));
649     if(incache) {
650       if(old_ssl_sessionid != our_ssl_sessionid) {
651         infof(data, "old SSL session ID is stale, removing\n");
652         Curl_ssl_delsessionid(conn, old_ssl_sessionid);
653         incache = FALSE;
654       }
655     }
656 
657     if(!incache) {
658       result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
659                                      0 /* unknown size */, sockindex);
660       if(result) {
661         Curl_ssl_sessionid_unlock(conn);
662         failf(data, "failed to store ssl session");
663         return result;
664       }
665     }
666     Curl_ssl_sessionid_unlock(conn);
667   }
668 
669   connssl->connecting_state = ssl_connect_done;
670 
671   return result;
672 }
673 
674 
cyassl_send(struct connectdata * conn,int sockindex,const void * mem,size_t len,CURLcode * curlcode)675 static ssize_t cyassl_send(struct connectdata *conn,
676                            int sockindex,
677                            const void *mem,
678                            size_t len,
679                            CURLcode *curlcode)
680 {
681   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
682   char error_buffer[CYASSL_MAX_ERROR_SZ];
683   int  memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
684   int  rc     = SSL_write(BACKEND->handle, mem, memlen);
685 
686   if(rc < 0) {
687     int err = SSL_get_error(BACKEND->handle, rc);
688 
689     switch(err) {
690     case SSL_ERROR_WANT_READ:
691     case SSL_ERROR_WANT_WRITE:
692       /* there's data pending, re-invoke SSL_write() */
693       *curlcode = CURLE_AGAIN;
694       return -1;
695     default:
696       failf(conn->data, "SSL write: %s, errno %d",
697             ERR_error_string(err, error_buffer),
698             SOCKERRNO);
699       *curlcode = CURLE_SEND_ERROR;
700       return -1;
701     }
702   }
703   return rc;
704 }
705 
Curl_cyassl_close(struct connectdata * conn,int sockindex)706 static void Curl_cyassl_close(struct connectdata *conn, int sockindex)
707 {
708   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
709 
710   if(BACKEND->handle) {
711     (void)SSL_shutdown(BACKEND->handle);
712     SSL_free(BACKEND->handle);
713     BACKEND->handle = NULL;
714   }
715   if(BACKEND->ctx) {
716     SSL_CTX_free(BACKEND->ctx);
717     BACKEND->ctx = NULL;
718   }
719 }
720 
cyassl_recv(struct connectdata * conn,int num,char * buf,size_t buffersize,CURLcode * curlcode)721 static ssize_t cyassl_recv(struct connectdata *conn,
722                            int num,
723                            char *buf,
724                            size_t buffersize,
725                            CURLcode *curlcode)
726 {
727   struct ssl_connect_data *connssl = &conn->ssl[num];
728   char error_buffer[CYASSL_MAX_ERROR_SZ];
729   int  buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
730   int  nread    = SSL_read(BACKEND->handle, buf, buffsize);
731 
732   if(nread < 0) {
733     int err = SSL_get_error(BACKEND->handle, nread);
734 
735     switch(err) {
736     case SSL_ERROR_ZERO_RETURN: /* no more data */
737       break;
738     case SSL_ERROR_WANT_READ:
739     case SSL_ERROR_WANT_WRITE:
740       /* there's data pending, re-invoke SSL_read() */
741       *curlcode = CURLE_AGAIN;
742       return -1;
743     default:
744       failf(conn->data, "SSL read: %s, errno %d",
745             ERR_error_string(err, error_buffer),
746             SOCKERRNO);
747       *curlcode = CURLE_RECV_ERROR;
748       return -1;
749     }
750   }
751   return nread;
752 }
753 
754 
Curl_cyassl_session_free(void * ptr)755 static void Curl_cyassl_session_free(void *ptr)
756 {
757   (void)ptr;
758   /* CyaSSL reuses sessions on own, no free */
759 }
760 
761 
Curl_cyassl_version(char * buffer,size_t size)762 static size_t Curl_cyassl_version(char *buffer, size_t size)
763 {
764 #if LIBCYASSL_VERSION_HEX >= 0x03006000
765   return snprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
766 #elif defined(WOLFSSL_VERSION)
767   return snprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION);
768 #elif defined(CYASSL_VERSION)
769   return snprintf(buffer, size, "CyaSSL/%s", CYASSL_VERSION);
770 #else
771   return snprintf(buffer, size, "CyaSSL/%s", "<1.8.8");
772 #endif
773 }
774 
775 
Curl_cyassl_init(void)776 static int Curl_cyassl_init(void)
777 {
778   return (CyaSSL_Init() == SSL_SUCCESS);
779 }
780 
781 
Curl_cyassl_data_pending(const struct connectdata * conn,int connindex)782 static bool Curl_cyassl_data_pending(const struct connectdata* conn,
783                                      int connindex)
784 {
785   const struct ssl_connect_data *connssl = &conn->ssl[connindex];
786   if(BACKEND->handle)   /* SSL is in use */
787     return (0 != SSL_pending(BACKEND->handle)) ? TRUE : FALSE;
788   else
789     return FALSE;
790 }
791 
792 
793 /*
794  * This function is called to shut down the SSL layer but keep the
795  * socket open (CCC - Clear Command Channel)
796  */
Curl_cyassl_shutdown(struct connectdata * conn,int sockindex)797 static int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex)
798 {
799   int retval = 0;
800   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
801 
802   if(BACKEND->handle) {
803     SSL_free(BACKEND->handle);
804     BACKEND->handle = NULL;
805   }
806   return retval;
807 }
808 
809 
810 static CURLcode
cyassl_connect_common(struct connectdata * conn,int sockindex,bool nonblocking,bool * done)811 cyassl_connect_common(struct connectdata *conn,
812                       int sockindex,
813                       bool nonblocking,
814                       bool *done)
815 {
816   CURLcode result;
817   struct Curl_easy *data = conn->data;
818   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
819   curl_socket_t sockfd = conn->sock[sockindex];
820   time_t timeout_ms;
821   int what;
822 
823   /* check if the connection has already been established */
824   if(ssl_connection_complete == connssl->state) {
825     *done = TRUE;
826     return CURLE_OK;
827   }
828 
829   if(ssl_connect_1 == connssl->connecting_state) {
830     /* Find out how much more time we're allowed */
831     timeout_ms = Curl_timeleft(data, NULL, TRUE);
832 
833     if(timeout_ms < 0) {
834       /* no need to continue if time already is up */
835       failf(data, "SSL connection timeout");
836       return CURLE_OPERATION_TIMEDOUT;
837     }
838 
839     result = cyassl_connect_step1(conn, sockindex);
840     if(result)
841       return result;
842   }
843 
844   while(ssl_connect_2 == connssl->connecting_state ||
845         ssl_connect_2_reading == connssl->connecting_state ||
846         ssl_connect_2_writing == connssl->connecting_state) {
847 
848     /* check allowed time left */
849     timeout_ms = Curl_timeleft(data, NULL, TRUE);
850 
851     if(timeout_ms < 0) {
852       /* no need to continue if time already is up */
853       failf(data, "SSL connection timeout");
854       return CURLE_OPERATION_TIMEDOUT;
855     }
856 
857     /* if ssl is expecting something, check if it's available. */
858     if(connssl->connecting_state == ssl_connect_2_reading
859        || connssl->connecting_state == ssl_connect_2_writing) {
860 
861       curl_socket_t writefd = ssl_connect_2_writing ==
862         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
863       curl_socket_t readfd = ssl_connect_2_reading ==
864         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
865 
866       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
867                                nonblocking?0:timeout_ms);
868       if(what < 0) {
869         /* fatal error */
870         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
871         return CURLE_SSL_CONNECT_ERROR;
872       }
873       else if(0 == what) {
874         if(nonblocking) {
875           *done = FALSE;
876           return CURLE_OK;
877         }
878         else {
879           /* timeout */
880           failf(data, "SSL connection timeout");
881           return CURLE_OPERATION_TIMEDOUT;
882         }
883       }
884       /* socket is readable or writable */
885     }
886 
887     /* Run transaction, and return to the caller if it failed or if
888      * this connection is part of a multi handle and this loop would
889      * execute again. This permits the owner of a multi handle to
890      * abort a connection attempt before step2 has completed while
891      * ensuring that a client using select() or epoll() will always
892      * have a valid fdset to wait on.
893      */
894     result = cyassl_connect_step2(conn, sockindex);
895     if(result || (nonblocking &&
896                   (ssl_connect_2 == connssl->connecting_state ||
897                    ssl_connect_2_reading == connssl->connecting_state ||
898                    ssl_connect_2_writing == connssl->connecting_state)))
899       return result;
900   } /* repeat step2 until all transactions are done. */
901 
902   if(ssl_connect_3 == connssl->connecting_state) {
903     result = cyassl_connect_step3(conn, sockindex);
904     if(result)
905       return result;
906   }
907 
908   if(ssl_connect_done == connssl->connecting_state) {
909     connssl->state = ssl_connection_complete;
910     conn->recv[sockindex] = cyassl_recv;
911     conn->send[sockindex] = cyassl_send;
912     *done = TRUE;
913   }
914   else
915     *done = FALSE;
916 
917   /* Reset our connect state machine */
918   connssl->connecting_state = ssl_connect_1;
919 
920   return CURLE_OK;
921 }
922 
923 
Curl_cyassl_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)924 static CURLcode Curl_cyassl_connect_nonblocking(struct connectdata *conn,
925                                                 int sockindex, bool *done)
926 {
927   return cyassl_connect_common(conn, sockindex, TRUE, done);
928 }
929 
930 
Curl_cyassl_connect(struct connectdata * conn,int sockindex)931 static CURLcode Curl_cyassl_connect(struct connectdata *conn, int sockindex)
932 {
933   CURLcode result;
934   bool done = FALSE;
935 
936   result = cyassl_connect_common(conn, sockindex, FALSE, &done);
937   if(result)
938     return result;
939 
940   DEBUGASSERT(done);
941 
942   return CURLE_OK;
943 }
944 
Curl_cyassl_random(struct Curl_easy * data,unsigned char * entropy,size_t length)945 static CURLcode Curl_cyassl_random(struct Curl_easy *data,
946                                    unsigned char *entropy, size_t length)
947 {
948   RNG rng;
949   (void)data;
950   if(InitRng(&rng))
951     return CURLE_FAILED_INIT;
952   if(length > UINT_MAX)
953     return CURLE_FAILED_INIT;
954   if(RNG_GenerateBlock(&rng, entropy, (unsigned)length))
955     return CURLE_FAILED_INIT;
956   return CURLE_OK;
957 }
958 
Curl_cyassl_sha256sum(const unsigned char * tmp,size_t tmplen,unsigned char * sha256sum,size_t unused)959 static void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */
960                                   size_t tmplen,
961                                   unsigned char *sha256sum /* output */,
962                                   size_t unused)
963 {
964   Sha256 SHA256pw;
965   (void)unused;
966   InitSha256(&SHA256pw);
967   Sha256Update(&SHA256pw, tmp, (word32)tmplen);
968   Sha256Final(&SHA256pw, sha256sum);
969 }
970 
Curl_cyassl_get_internals(struct ssl_connect_data * connssl,CURLINFO info UNUSED_PARAM)971 static void *Curl_cyassl_get_internals(struct ssl_connect_data *connssl,
972                                        CURLINFO info UNUSED_PARAM)
973 {
974   (void)info;
975   return BACKEND->handle;
976 }
977 
978 const struct Curl_ssl Curl_ssl_cyassl = {
979   { CURLSSLBACKEND_WOLFSSL, "WolfSSL" }, /* info */
980 
981   0, /* have_ca_path */
982   0, /* have_certinfo */
983 #ifdef KEEP_PEER_CERT
984   1, /* have_pinnedpubkey */
985 #else
986   0, /* have_pinnedpubkey */
987 #endif
988   1, /* have_ssl_ctx */
989   0, /* support_https_proxy */
990 
991   sizeof(struct ssl_backend_data),
992 
993   Curl_cyassl_init,                /* init */
994   Curl_none_cleanup,               /* cleanup */
995   Curl_cyassl_version,             /* version */
996   Curl_none_check_cxn,             /* check_cxn */
997   Curl_cyassl_shutdown,            /* shutdown */
998   Curl_cyassl_data_pending,        /* data_pending */
999   Curl_cyassl_random,              /* random */
1000   Curl_none_cert_status_request,   /* cert_status_request */
1001   Curl_cyassl_connect,             /* connect */
1002   Curl_cyassl_connect_nonblocking, /* connect_nonblocking */
1003   Curl_cyassl_get_internals,       /* get_internals */
1004   Curl_cyassl_close,               /* close_one */
1005   Curl_none_close_all,             /* close_all */
1006   Curl_cyassl_session_free,        /* session_free */
1007   Curl_none_set_engine,            /* set_engine */
1008   Curl_none_set_engine_default,    /* set_engine_default */
1009   Curl_none_engines_list,          /* engines_list */
1010   Curl_none_false_start,           /* false_start */
1011   Curl_none_md5sum,                /* md5sum */
1012   Curl_cyassl_sha256sum            /* sha256sum */
1013 };
1014 
1015 #endif
1016