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