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