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