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