• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2020, 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 /* This file is for implementing all "generic" SSL functions that all libcurl
24    internals should use. It is then responsible for calling the proper
25    "backend" function.
26 
27    SSL-functions in libcurl should call functions in this source file, and not
28    to any specific SSL-layer.
29 
30    Curl_ssl_ - prefix for generic ones
31 
32    Note that this source code uses the functions of the configured SSL
33    backend via the global Curl_ssl instance.
34 
35    "SSL/TLS Strong Encryption: An Introduction"
36    https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
37 */
38 
39 #include "curl_setup.h"
40 
41 #ifdef HAVE_SYS_TYPES_H
42 #include <sys/types.h>
43 #endif
44 #ifdef HAVE_SYS_STAT_H
45 #include <sys/stat.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50 
51 #include "urldata.h"
52 
53 #include "vtls.h" /* generic SSL protos etc */
54 #include "slist.h"
55 #include "sendf.h"
56 #include "strcase.h"
57 #include "url.h"
58 #include "progress.h"
59 #include "share.h"
60 #include "multiif.h"
61 #include "timeval.h"
62 #include "curl_md5.h"
63 #include "warnless.h"
64 #include "curl_base64.h"
65 #include "curl_printf.h"
66 #include "strdup.h"
67 
68 /* The last #include files should be: */
69 #include "curl_memory.h"
70 #include "memdebug.h"
71 
72 /* convenience macro to check if this handle is using a shared SSL session */
73 #define SSLSESSION_SHARED(data) (data->share &&                        \
74                                  (data->share->specifier &             \
75                                   (1<<CURL_LOCK_DATA_SSL_SESSION)))
76 
77 #define CLONE_STRING(var)                    \
78   if(source->var) {                          \
79     dest->var = strdup(source->var);         \
80     if(!dest->var)                           \
81       return FALSE;                          \
82   }                                          \
83   else                                       \
84     dest->var = NULL;
85 
86 #define CLONE_BLOB(var)                         \
87   if(blobdup(&dest->var, source->var))         \
88     return FALSE;
89 
blobdup(struct curl_blob ** dest,struct curl_blob * src)90 static CURLcode blobdup(struct curl_blob **dest,
91                         struct curl_blob *src)
92 {
93   DEBUGASSERT(dest);
94   DEBUGASSERT(!*dest);
95   if(src) {
96     /* only if there's data to dupe! */
97     struct curl_blob *d;
98     d = malloc(sizeof(struct curl_blob) + src->len);
99     if(!d)
100       return CURLE_OUT_OF_MEMORY;
101     d->len = src->len;
102     /* Always duplicate because the connection may survive longer than the
103        handle that passed in the blob. */
104     d->flags = CURL_BLOB_COPY;
105     d->data = (void *)((char *)d + sizeof(struct curl_blob));
106     memcpy(d->data, src->data, src->len);
107     *dest = d;
108   }
109   return CURLE_OK;
110 }
111 
112 /* returns TRUE if the blobs are identical */
blobcmp(struct curl_blob * first,struct curl_blob * second)113 static bool blobcmp(struct curl_blob *first, struct curl_blob *second)
114 {
115   if(!first && !second) /* both are NULL */
116     return TRUE;
117   if(!first || !second) /* one is NULL */
118     return FALSE;
119   if(first->len != second->len) /* different sizes */
120     return FALSE;
121   return !memcmp(first->data, second->data, first->len); /* same data */
122 }
123 
124 bool
Curl_ssl_config_matches(struct ssl_primary_config * data,struct ssl_primary_config * needle)125 Curl_ssl_config_matches(struct ssl_primary_config *data,
126                         struct ssl_primary_config *needle)
127 {
128   if((data->version == needle->version) &&
129      (data->version_max == needle->version_max) &&
130      (data->verifypeer == needle->verifypeer) &&
131      (data->verifyhost == needle->verifyhost) &&
132      (data->verifystatus == needle->verifystatus) &&
133      blobcmp(data->cert_blob, needle->cert_blob) &&
134      Curl_safe_strcasecompare(data->CApath, needle->CApath) &&
135      Curl_safe_strcasecompare(data->CAfile, needle->CAfile) &&
136      Curl_safe_strcasecompare(data->clientcert, needle->clientcert) &&
137      Curl_safe_strcasecompare(data->random_file, needle->random_file) &&
138      Curl_safe_strcasecompare(data->egdsocket, needle->egdsocket) &&
139      Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list) &&
140      Curl_safe_strcasecompare(data->cipher_list13, needle->cipher_list13) &&
141      Curl_safe_strcasecompare(data->curves, needle->curves) &&
142      Curl_safe_strcasecompare(data->pinned_key, needle->pinned_key))
143     return TRUE;
144 
145   return FALSE;
146 }
147 
148 bool
Curl_clone_primary_ssl_config(struct ssl_primary_config * source,struct ssl_primary_config * dest)149 Curl_clone_primary_ssl_config(struct ssl_primary_config *source,
150                               struct ssl_primary_config *dest)
151 {
152   dest->version = source->version;
153   dest->version_max = source->version_max;
154   dest->verifypeer = source->verifypeer;
155   dest->verifyhost = source->verifyhost;
156   dest->verifystatus = source->verifystatus;
157   dest->sessionid = source->sessionid;
158 
159   CLONE_BLOB(cert_blob);
160   CLONE_STRING(CApath);
161   CLONE_STRING(CAfile);
162   CLONE_STRING(clientcert);
163   CLONE_STRING(random_file);
164   CLONE_STRING(egdsocket);
165   CLONE_STRING(cipher_list);
166   CLONE_STRING(cipher_list13);
167   CLONE_STRING(pinned_key);
168   CLONE_STRING(curves);
169 
170   return TRUE;
171 }
172 
Curl_free_primary_ssl_config(struct ssl_primary_config * sslc)173 void Curl_free_primary_ssl_config(struct ssl_primary_config *sslc)
174 {
175   Curl_safefree(sslc->CApath);
176   Curl_safefree(sslc->CAfile);
177   Curl_safefree(sslc->clientcert);
178   Curl_safefree(sslc->random_file);
179   Curl_safefree(sslc->egdsocket);
180   Curl_safefree(sslc->cipher_list);
181   Curl_safefree(sslc->cipher_list13);
182   Curl_safefree(sslc->pinned_key);
183   Curl_safefree(sslc->cert_blob);
184   Curl_safefree(sslc->curves);
185 }
186 
187 #ifdef USE_SSL
188 static int multissl_init(const struct Curl_ssl *backend);
189 #endif
190 
Curl_ssl_backend(void)191 int Curl_ssl_backend(void)
192 {
193 #ifdef USE_SSL
194   multissl_init(NULL);
195   return Curl_ssl->info.id;
196 #else
197   return (int)CURLSSLBACKEND_NONE;
198 #endif
199 }
200 
201 #ifdef USE_SSL
202 
203 /* "global" init done? */
204 static bool init_ssl = FALSE;
205 
206 /**
207  * Global SSL init
208  *
209  * @retval 0 error initializing SSL
210  * @retval 1 SSL initialized successfully
211  */
Curl_ssl_init(void)212 int Curl_ssl_init(void)
213 {
214   /* make sure this is only done once */
215   if(init_ssl)
216     return 1;
217   init_ssl = TRUE; /* never again */
218 
219   return Curl_ssl->init();
220 }
221 
222 #if defined(CURL_WITH_MULTI_SSL)
223 static const struct Curl_ssl Curl_ssl_multi;
224 #endif
225 
226 /* Global cleanup */
Curl_ssl_cleanup(void)227 void Curl_ssl_cleanup(void)
228 {
229   if(init_ssl) {
230     /* only cleanup if we did a previous init */
231     Curl_ssl->cleanup();
232 #if defined(CURL_WITH_MULTI_SSL)
233     Curl_ssl = &Curl_ssl_multi;
234 #endif
235     init_ssl = FALSE;
236   }
237 }
238 
ssl_prefs_check(struct Curl_easy * data)239 static bool ssl_prefs_check(struct Curl_easy *data)
240 {
241   /* check for CURLOPT_SSLVERSION invalid parameter value */
242   const long sslver = data->set.ssl.primary.version;
243   if((sslver < 0) || (sslver >= CURL_SSLVERSION_LAST)) {
244     failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
245     return FALSE;
246   }
247 
248   switch(data->set.ssl.primary.version_max) {
249   case CURL_SSLVERSION_MAX_NONE:
250   case CURL_SSLVERSION_MAX_DEFAULT:
251     break;
252 
253   default:
254     if((data->set.ssl.primary.version_max >> 16) < sslver) {
255       failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION");
256       return FALSE;
257     }
258   }
259 
260   return TRUE;
261 }
262 
263 #ifndef CURL_DISABLE_PROXY
264 static CURLcode
ssl_connect_init_proxy(struct connectdata * conn,int sockindex)265 ssl_connect_init_proxy(struct connectdata *conn, int sockindex)
266 {
267   DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]);
268   if(ssl_connection_complete == conn->ssl[sockindex].state &&
269      !conn->proxy_ssl[sockindex].use) {
270     struct ssl_backend_data *pbdata;
271 
272     if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
273       return CURLE_NOT_BUILT_IN;
274 
275     /* The pointers to the ssl backend data, which is opaque here, are swapped
276        rather than move the contents. */
277     pbdata = conn->proxy_ssl[sockindex].backend;
278     conn->proxy_ssl[sockindex] = conn->ssl[sockindex];
279 
280     memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex]));
281     memset(pbdata, 0, Curl_ssl->sizeof_ssl_backend_data);
282 
283     conn->ssl[sockindex].backend = pbdata;
284   }
285   return CURLE_OK;
286 }
287 #endif
288 
289 CURLcode
Curl_ssl_connect(struct connectdata * conn,int sockindex)290 Curl_ssl_connect(struct connectdata *conn, int sockindex)
291 {
292   CURLcode result;
293 
294 #ifndef CURL_DISABLE_PROXY
295   if(conn->bits.proxy_ssl_connected[sockindex]) {
296     result = ssl_connect_init_proxy(conn, sockindex);
297     if(result)
298       return result;
299   }
300 #endif
301 
302   if(!ssl_prefs_check(conn->data))
303     return CURLE_SSL_CONNECT_ERROR;
304 
305   /* mark this is being ssl-enabled from here on. */
306   conn->ssl[sockindex].use = TRUE;
307   conn->ssl[sockindex].state = ssl_connection_negotiating;
308 
309   result = Curl_ssl->connect_blocking(conn, sockindex);
310 
311   if(!result)
312     Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
313 
314   return result;
315 }
316 
317 CURLcode
Curl_ssl_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)318 Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
319                              bool *done)
320 {
321   CURLcode result;
322 #ifndef CURL_DISABLE_PROXY
323   if(conn->bits.proxy_ssl_connected[sockindex]) {
324     result = ssl_connect_init_proxy(conn, sockindex);
325     if(result)
326       return result;
327   }
328 #endif
329   if(!ssl_prefs_check(conn->data))
330     return CURLE_SSL_CONNECT_ERROR;
331 
332   /* mark this is being ssl requested from here on. */
333   conn->ssl[sockindex].use = TRUE;
334   result = Curl_ssl->connect_nonblocking(conn, sockindex, done);
335   if(!result && *done)
336     Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
337   return result;
338 }
339 
340 /*
341  * Lock shared SSL session data
342  */
Curl_ssl_sessionid_lock(struct connectdata * conn)343 void Curl_ssl_sessionid_lock(struct connectdata *conn)
344 {
345   if(SSLSESSION_SHARED(conn->data))
346     Curl_share_lock(conn->data,
347                     CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
348 }
349 
350 /*
351  * Unlock shared SSL session data
352  */
Curl_ssl_sessionid_unlock(struct connectdata * conn)353 void Curl_ssl_sessionid_unlock(struct connectdata *conn)
354 {
355   if(SSLSESSION_SHARED(conn->data))
356     Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION);
357 }
358 
359 /*
360  * Check if there's a session ID for the given connection in the cache, and if
361  * there's one suitable, it is provided. Returns TRUE when no entry matched.
362  */
Curl_ssl_getsessionid(struct connectdata * conn,void ** ssl_sessionid,size_t * idsize,int sockindex)363 bool Curl_ssl_getsessionid(struct connectdata *conn,
364                            void **ssl_sessionid,
365                            size_t *idsize, /* set 0 if unknown */
366                            int sockindex)
367 {
368   struct Curl_ssl_session *check;
369   struct Curl_easy *data = conn->data;
370   size_t i;
371   long *general_age;
372   bool no_match = TRUE;
373 
374 #ifndef CURL_DISABLE_PROXY
375   const bool isProxy = CONNECT_PROXY_SSL();
376   struct ssl_primary_config * const ssl_config = isProxy ?
377     &conn->proxy_ssl_config :
378     &conn->ssl_config;
379   const char * const name = isProxy ?
380     conn->http_proxy.host.name : conn->host.name;
381   int port = isProxy ? (int)conn->port : conn->remote_port;
382 #else
383   /* no proxy support */
384   struct ssl_primary_config * const ssl_config = &conn->ssl_config;
385   const char * const name = conn->host.name;
386   int port = conn->remote_port;
387   (void)sockindex;
388 #endif
389   *ssl_sessionid = NULL;
390 
391   DEBUGASSERT(SSL_SET_OPTION(primary.sessionid));
392 
393   if(!SSL_SET_OPTION(primary.sessionid))
394     /* session ID re-use is disabled */
395     return TRUE;
396 
397   /* Lock if shared */
398   if(SSLSESSION_SHARED(data))
399     general_age = &data->share->sessionage;
400   else
401     general_age = &data->state.sessionage;
402 
403   for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
404     check = &data->state.session[i];
405     if(!check->sessionid)
406       /* not session ID means blank entry */
407       continue;
408     if(strcasecompare(name, check->name) &&
409        ((!conn->bits.conn_to_host && !check->conn_to_host) ||
410         (conn->bits.conn_to_host && check->conn_to_host &&
411          strcasecompare(conn->conn_to_host.name, check->conn_to_host))) &&
412        ((!conn->bits.conn_to_port && check->conn_to_port == -1) ||
413         (conn->bits.conn_to_port && check->conn_to_port != -1 &&
414          conn->conn_to_port == check->conn_to_port)) &&
415        (port == check->remote_port) &&
416        strcasecompare(conn->handler->scheme, check->scheme) &&
417        Curl_ssl_config_matches(ssl_config, &check->ssl_config)) {
418       /* yes, we have a session ID! */
419       (*general_age)++;          /* increase general age */
420       check->age = *general_age; /* set this as used in this age */
421       *ssl_sessionid = check->sessionid;
422       if(idsize)
423         *idsize = check->idsize;
424       no_match = FALSE;
425       break;
426     }
427   }
428 
429   return no_match;
430 }
431 
432 /*
433  * Kill a single session ID entry in the cache.
434  */
Curl_ssl_kill_session(struct Curl_ssl_session * session)435 void Curl_ssl_kill_session(struct Curl_ssl_session *session)
436 {
437   if(session->sessionid) {
438     /* defensive check */
439 
440     /* free the ID the SSL-layer specific way */
441     Curl_ssl->session_free(session->sessionid);
442 
443     session->sessionid = NULL;
444     session->age = 0; /* fresh */
445 
446     Curl_free_primary_ssl_config(&session->ssl_config);
447 
448     Curl_safefree(session->name);
449     Curl_safefree(session->conn_to_host);
450   }
451 }
452 
453 /*
454  * Delete the given session ID from the cache.
455  */
Curl_ssl_delsessionid(struct connectdata * conn,void * ssl_sessionid)456 void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
457 {
458   size_t i;
459   struct Curl_easy *data = conn->data;
460 
461   for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
462     struct Curl_ssl_session *check = &data->state.session[i];
463 
464     if(check->sessionid == ssl_sessionid) {
465       Curl_ssl_kill_session(check);
466       break;
467     }
468   }
469 }
470 
471 /*
472  * Store session id in the session cache. The ID passed on to this function
473  * must already have been extracted and allocated the proper way for the SSL
474  * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
475  * later on.
476  */
Curl_ssl_addsessionid(struct connectdata * conn,void * ssl_sessionid,size_t idsize,int sockindex)477 CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
478                                void *ssl_sessionid,
479                                size_t idsize,
480                                int sockindex)
481 {
482   size_t i;
483   struct Curl_easy *data = conn->data; /* the mother of all structs */
484   struct Curl_ssl_session *store = &data->state.session[0];
485   long oldest_age = data->state.session[0].age; /* zero if unused */
486   char *clone_host;
487   char *clone_conn_to_host;
488   int conn_to_port;
489   long *general_age;
490 #ifndef CURL_DISABLE_PROXY
491   const bool isProxy = CONNECT_PROXY_SSL();
492   struct ssl_primary_config * const ssl_config = isProxy ?
493     &conn->proxy_ssl_config :
494     &conn->ssl_config;
495   const char *hostname = isProxy ? conn->http_proxy.host.name :
496     conn->host.name;
497 #else
498   /* proxy support disabled */
499   const bool isProxy = FALSE;
500   struct ssl_primary_config * const ssl_config = &conn->ssl_config;
501   const char *hostname = conn->host.name;
502   (void)sockindex;
503 #endif
504   DEBUGASSERT(SSL_SET_OPTION(primary.sessionid));
505 
506   clone_host = strdup(hostname);
507   if(!clone_host)
508     return CURLE_OUT_OF_MEMORY; /* bail out */
509 
510   if(conn->bits.conn_to_host) {
511     clone_conn_to_host = strdup(conn->conn_to_host.name);
512     if(!clone_conn_to_host) {
513       free(clone_host);
514       return CURLE_OUT_OF_MEMORY; /* bail out */
515     }
516   }
517   else
518     clone_conn_to_host = NULL;
519 
520   if(conn->bits.conn_to_port)
521     conn_to_port = conn->conn_to_port;
522   else
523     conn_to_port = -1;
524 
525   /* Now we should add the session ID and the host name to the cache, (remove
526      the oldest if necessary) */
527 
528   /* If using shared SSL session, lock! */
529   if(SSLSESSION_SHARED(data)) {
530     general_age = &data->share->sessionage;
531   }
532   else {
533     general_age = &data->state.sessionage;
534   }
535 
536   /* find an empty slot for us, or find the oldest */
537   for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) &&
538         data->state.session[i].sessionid; i++) {
539     if(data->state.session[i].age < oldest_age) {
540       oldest_age = data->state.session[i].age;
541       store = &data->state.session[i];
542     }
543   }
544   if(i == data->set.general_ssl.max_ssl_sessions)
545     /* cache is full, we must "kill" the oldest entry! */
546     Curl_ssl_kill_session(store);
547   else
548     store = &data->state.session[i]; /* use this slot */
549 
550   /* now init the session struct wisely */
551   store->sessionid = ssl_sessionid;
552   store->idsize = idsize;
553   store->age = *general_age;    /* set current age */
554   /* free it if there's one already present */
555   free(store->name);
556   free(store->conn_to_host);
557   store->name = clone_host;               /* clone host name */
558   store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
559   store->conn_to_port = conn_to_port; /* connect to port number */
560   /* port number */
561   store->remote_port = isProxy ? (int)conn->port : conn->remote_port;
562   store->scheme = conn->handler->scheme;
563 
564   if(!Curl_clone_primary_ssl_config(ssl_config, &store->ssl_config)) {
565     Curl_free_primary_ssl_config(&store->ssl_config);
566     store->sessionid = NULL; /* let caller free sessionid */
567     free(clone_host);
568     free(clone_conn_to_host);
569     return CURLE_OUT_OF_MEMORY;
570   }
571 
572   return CURLE_OK;
573 }
574 
575 
Curl_ssl_close_all(struct Curl_easy * data)576 void Curl_ssl_close_all(struct Curl_easy *data)
577 {
578   /* kill the session ID cache if not shared */
579   if(data->state.session && !SSLSESSION_SHARED(data)) {
580     size_t i;
581     for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++)
582       /* the single-killer function handles empty table slots */
583       Curl_ssl_kill_session(&data->state.session[i]);
584 
585     /* free the cache data */
586     Curl_safefree(data->state.session);
587   }
588 
589   Curl_ssl->close_all(data);
590 }
591 
592 #if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
593   defined(USE_SECTRANSP) || defined(USE_NSS) || \
594   defined(USE_MBEDTLS) || defined(USE_WOLFSSL) || defined(USE_BEARSSL)
Curl_ssl_getsock(struct connectdata * conn,curl_socket_t * socks)595 int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks)
596 {
597   struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
598 
599   if(connssl->connecting_state == ssl_connect_2_writing) {
600     /* write mode */
601     socks[0] = conn->sock[FIRSTSOCKET];
602     return GETSOCK_WRITESOCK(0);
603   }
604   if(connssl->connecting_state == ssl_connect_2_reading) {
605     /* read mode */
606     socks[0] = conn->sock[FIRSTSOCKET];
607     return GETSOCK_READSOCK(0);
608   }
609 
610   return GETSOCK_BLANK;
611 }
612 #else
Curl_ssl_getsock(struct connectdata * conn,curl_socket_t * socks)613 int Curl_ssl_getsock(struct connectdata *conn,
614                      curl_socket_t *socks)
615 {
616   (void)conn;
617   (void)socks;
618   return GETSOCK_BLANK;
619 }
620 /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL || USE_SECTRANSP || USE_NSS */
621 #endif
622 
Curl_ssl_close(struct connectdata * conn,int sockindex)623 void Curl_ssl_close(struct connectdata *conn, int sockindex)
624 {
625   DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
626   Curl_ssl->close_one(conn, sockindex);
627   conn->ssl[sockindex].state = ssl_connection_none;
628 }
629 
Curl_ssl_shutdown(struct connectdata * conn,int sockindex)630 CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
631 {
632   if(Curl_ssl->shut_down(conn, sockindex))
633     return CURLE_SSL_SHUTDOWN_FAILED;
634 
635   conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
636   conn->ssl[sockindex].state = ssl_connection_none;
637 
638   conn->recv[sockindex] = Curl_recv_plain;
639   conn->send[sockindex] = Curl_send_plain;
640 
641   return CURLE_OK;
642 }
643 
644 /* Selects an SSL crypto engine
645  */
Curl_ssl_set_engine(struct Curl_easy * data,const char * engine)646 CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
647 {
648   return Curl_ssl->set_engine(data, engine);
649 }
650 
651 /* Selects the default SSL crypto engine
652  */
Curl_ssl_set_engine_default(struct Curl_easy * data)653 CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
654 {
655   return Curl_ssl->set_engine_default(data);
656 }
657 
658 /* Return list of OpenSSL crypto engine names. */
Curl_ssl_engines_list(struct Curl_easy * data)659 struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
660 {
661   return Curl_ssl->engines_list(data);
662 }
663 
664 /*
665  * This sets up a session ID cache to the specified size. Make sure this code
666  * is agnostic to what underlying SSL technology we use.
667  */
Curl_ssl_initsessions(struct Curl_easy * data,size_t amount)668 CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
669 {
670   struct Curl_ssl_session *session;
671 
672   if(data->state.session)
673     /* this is just a precaution to prevent multiple inits */
674     return CURLE_OK;
675 
676   session = calloc(amount, sizeof(struct Curl_ssl_session));
677   if(!session)
678     return CURLE_OUT_OF_MEMORY;
679 
680   /* store the info in the SSL section */
681   data->set.general_ssl.max_ssl_sessions = amount;
682   data->state.session = session;
683   data->state.sessionage = 1; /* this is brand new */
684   return CURLE_OK;
685 }
686 
687 static size_t Curl_multissl_version(char *buffer, size_t size);
688 
Curl_ssl_version(char * buffer,size_t size)689 size_t Curl_ssl_version(char *buffer, size_t size)
690 {
691 #ifdef CURL_WITH_MULTI_SSL
692   return Curl_multissl_version(buffer, size);
693 #else
694   return Curl_ssl->version(buffer, size);
695 #endif
696 }
697 
698 /*
699  * This function tries to determine connection status.
700  *
701  * Return codes:
702  *     1 means the connection is still in place
703  *     0 means the connection has been closed
704  *    -1 means the connection status is unknown
705  */
Curl_ssl_check_cxn(struct connectdata * conn)706 int Curl_ssl_check_cxn(struct connectdata *conn)
707 {
708   return Curl_ssl->check_cxn(conn);
709 }
710 
Curl_ssl_data_pending(const struct connectdata * conn,int connindex)711 bool Curl_ssl_data_pending(const struct connectdata *conn,
712                            int connindex)
713 {
714   return Curl_ssl->data_pending(conn, connindex);
715 }
716 
Curl_ssl_free_certinfo(struct Curl_easy * data)717 void Curl_ssl_free_certinfo(struct Curl_easy *data)
718 {
719   struct curl_certinfo *ci = &data->info.certs;
720 
721   if(ci->num_of_certs) {
722     /* free all individual lists used */
723     int i;
724     for(i = 0; i<ci->num_of_certs; i++) {
725       curl_slist_free_all(ci->certinfo[i]);
726       ci->certinfo[i] = NULL;
727     }
728 
729     free(ci->certinfo); /* free the actual array too */
730     ci->certinfo = NULL;
731     ci->num_of_certs = 0;
732   }
733 }
734 
Curl_ssl_init_certinfo(struct Curl_easy * data,int num)735 CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
736 {
737   struct curl_certinfo *ci = &data->info.certs;
738   struct curl_slist **table;
739 
740   /* Free any previous certificate information structures */
741   Curl_ssl_free_certinfo(data);
742 
743   /* Allocate the required certificate information structures */
744   table = calloc((size_t) num, sizeof(struct curl_slist *));
745   if(!table)
746     return CURLE_OUT_OF_MEMORY;
747 
748   ci->num_of_certs = num;
749   ci->certinfo = table;
750 
751   return CURLE_OK;
752 }
753 
754 /*
755  * 'value' is NOT a null-terminated string
756  */
Curl_ssl_push_certinfo_len(struct Curl_easy * data,int certnum,const char * label,const char * value,size_t valuelen)757 CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
758                                     int certnum,
759                                     const char *label,
760                                     const char *value,
761                                     size_t valuelen)
762 {
763   struct curl_certinfo *ci = &data->info.certs;
764   char *output;
765   struct curl_slist *nl;
766   CURLcode result = CURLE_OK;
767   size_t labellen = strlen(label);
768   size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
769 
770   output = malloc(outlen);
771   if(!output)
772     return CURLE_OUT_OF_MEMORY;
773 
774   /* sprintf the label and colon */
775   msnprintf(output, outlen, "%s:", label);
776 
777   /* memcpy the value (it might not be null-terminated) */
778   memcpy(&output[labellen + 1], value, valuelen);
779 
780   /* null-terminate the output */
781   output[labellen + 1 + valuelen] = 0;
782 
783   nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
784   if(!nl) {
785     free(output);
786     curl_slist_free_all(ci->certinfo[certnum]);
787     result = CURLE_OUT_OF_MEMORY;
788   }
789 
790   ci->certinfo[certnum] = nl;
791   return result;
792 }
793 
794 /*
795  * This is a convenience function for push_certinfo_len that takes a zero
796  * terminated value.
797  */
Curl_ssl_push_certinfo(struct Curl_easy * data,int certnum,const char * label,const char * value)798 CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data,
799                                 int certnum,
800                                 const char *label,
801                                 const char *value)
802 {
803   size_t valuelen = strlen(value);
804 
805   return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
806 }
807 
Curl_ssl_random(struct Curl_easy * data,unsigned char * entropy,size_t length)808 CURLcode Curl_ssl_random(struct Curl_easy *data,
809                          unsigned char *entropy,
810                          size_t length)
811 {
812   return Curl_ssl->random(data, entropy, length);
813 }
814 
815 /*
816  * Public key pem to der conversion
817  */
818 
pubkey_pem_to_der(const char * pem,unsigned char ** der,size_t * der_len)819 static CURLcode pubkey_pem_to_der(const char *pem,
820                                   unsigned char **der, size_t *der_len)
821 {
822   char *stripped_pem, *begin_pos, *end_pos;
823   size_t pem_count, stripped_pem_count = 0, pem_len;
824   CURLcode result;
825 
826   /* if no pem, exit. */
827   if(!pem)
828     return CURLE_BAD_CONTENT_ENCODING;
829 
830   begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
831   if(!begin_pos)
832     return CURLE_BAD_CONTENT_ENCODING;
833 
834   pem_count = begin_pos - pem;
835   /* Invalid if not at beginning AND not directly following \n */
836   if(0 != pem_count && '\n' != pem[pem_count - 1])
837     return CURLE_BAD_CONTENT_ENCODING;
838 
839   /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
840   pem_count += 26;
841 
842   /* Invalid if not directly following \n */
843   end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
844   if(!end_pos)
845     return CURLE_BAD_CONTENT_ENCODING;
846 
847   pem_len = end_pos - pem;
848 
849   stripped_pem = malloc(pem_len - pem_count + 1);
850   if(!stripped_pem)
851     return CURLE_OUT_OF_MEMORY;
852 
853   /*
854    * Here we loop through the pem array one character at a time between the
855    * correct indices, and place each character that is not '\n' or '\r'
856    * into the stripped_pem array, which should represent the raw base64 string
857    */
858   while(pem_count < pem_len) {
859     if('\n' != pem[pem_count] && '\r' != pem[pem_count])
860       stripped_pem[stripped_pem_count++] = pem[pem_count];
861     ++pem_count;
862   }
863   /* Place the null terminator in the correct place */
864   stripped_pem[stripped_pem_count] = '\0';
865 
866   result = Curl_base64_decode(stripped_pem, der, der_len);
867 
868   Curl_safefree(stripped_pem);
869 
870   return result;
871 }
872 
873 /*
874  * Generic pinned public key check.
875  */
876 
Curl_pin_peer_pubkey(struct Curl_easy * data,const char * pinnedpubkey,const unsigned char * pubkey,size_t pubkeylen)877 CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
878                               const char *pinnedpubkey,
879                               const unsigned char *pubkey, size_t pubkeylen)
880 {
881   FILE *fp;
882   unsigned char *buf = NULL, *pem_ptr = NULL;
883   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
884 
885   /* if a path wasn't specified, don't pin */
886   if(!pinnedpubkey)
887     return CURLE_OK;
888   if(!pubkey || !pubkeylen)
889     return result;
890 
891   /* only do this if pinnedpubkey starts with "sha256//", length 8 */
892   if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
893     CURLcode encode;
894     size_t encodedlen, pinkeylen;
895     char *encoded, *pinkeycopy, *begin_pos, *end_pos;
896     unsigned char *sha256sumdigest;
897 
898     if(!Curl_ssl->sha256sum) {
899       /* without sha256 support, this cannot match */
900       return result;
901     }
902 
903     /* compute sha256sum of public key */
904     sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH);
905     if(!sha256sumdigest)
906       return CURLE_OUT_OF_MEMORY;
907     encode = Curl_ssl->sha256sum(pubkey, pubkeylen,
908                         sha256sumdigest, CURL_SHA256_DIGEST_LENGTH);
909 
910     if(encode != CURLE_OK)
911       return encode;
912 
913     encode = Curl_base64_encode(data, (char *)sha256sumdigest,
914                                 CURL_SHA256_DIGEST_LENGTH, &encoded,
915                                 &encodedlen);
916     Curl_safefree(sha256sumdigest);
917 
918     if(encode)
919       return encode;
920 
921     infof(data, "\t public key hash: sha256//%s\n", encoded);
922 
923     /* it starts with sha256//, copy so we can modify it */
924     pinkeylen = strlen(pinnedpubkey) + 1;
925     pinkeycopy = malloc(pinkeylen);
926     if(!pinkeycopy) {
927       Curl_safefree(encoded);
928       return CURLE_OUT_OF_MEMORY;
929     }
930     memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
931     /* point begin_pos to the copy, and start extracting keys */
932     begin_pos = pinkeycopy;
933     do {
934       end_pos = strstr(begin_pos, ";sha256//");
935       /*
936        * if there is an end_pos, null terminate,
937        * otherwise it'll go to the end of the original string
938        */
939       if(end_pos)
940         end_pos[0] = '\0';
941 
942       /* compare base64 sha256 digests, 8 is the length of "sha256//" */
943       if(encodedlen == strlen(begin_pos + 8) &&
944          !memcmp(encoded, begin_pos + 8, encodedlen)) {
945         result = CURLE_OK;
946         break;
947       }
948 
949       /*
950        * change back the null-terminator we changed earlier,
951        * and look for next begin
952        */
953       if(end_pos) {
954         end_pos[0] = ';';
955         begin_pos = strstr(end_pos, "sha256//");
956       }
957     } while(end_pos && begin_pos);
958     Curl_safefree(encoded);
959     Curl_safefree(pinkeycopy);
960     return result;
961   }
962 
963   fp = fopen(pinnedpubkey, "rb");
964   if(!fp)
965     return result;
966 
967   do {
968     long filesize;
969     size_t size, pem_len;
970     CURLcode pem_read;
971 
972     /* Determine the file's size */
973     if(fseek(fp, 0, SEEK_END))
974       break;
975     filesize = ftell(fp);
976     if(fseek(fp, 0, SEEK_SET))
977       break;
978     if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
979       break;
980 
981     /*
982      * if the size of our certificate is bigger than the file
983      * size then it can't match
984      */
985     size = curlx_sotouz((curl_off_t) filesize);
986     if(pubkeylen > size)
987       break;
988 
989     /*
990      * Allocate buffer for the pinned key
991      * With 1 additional byte for null terminator in case of PEM key
992      */
993     buf = malloc(size + 1);
994     if(!buf)
995       break;
996 
997     /* Returns number of elements read, which should be 1 */
998     if((int) fread(buf, size, 1, fp) != 1)
999       break;
1000 
1001     /* If the sizes are the same, it can't be base64 encoded, must be der */
1002     if(pubkeylen == size) {
1003       if(!memcmp(pubkey, buf, pubkeylen))
1004         result = CURLE_OK;
1005       break;
1006     }
1007 
1008     /*
1009      * Otherwise we will assume it's PEM and try to decode it
1010      * after placing null terminator
1011      */
1012     buf[size] = '\0';
1013     pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
1014     /* if it wasn't read successfully, exit */
1015     if(pem_read)
1016       break;
1017 
1018     /*
1019      * if the size of our certificate doesn't match the size of
1020      * the decoded file, they can't be the same, otherwise compare
1021      */
1022     if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
1023       result = CURLE_OK;
1024   } while(0);
1025 
1026   Curl_safefree(buf);
1027   Curl_safefree(pem_ptr);
1028   fclose(fp);
1029 
1030   return result;
1031 }
1032 
1033 #ifndef CURL_DISABLE_CRYPTO_AUTH
Curl_ssl_md5sum(unsigned char * tmp,size_t tmplen,unsigned char * md5sum,size_t md5len)1034 CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
1035                          size_t tmplen,
1036                          unsigned char *md5sum, /* output */
1037                          size_t md5len)
1038 {
1039   return Curl_ssl->md5sum(tmp, tmplen, md5sum, md5len);
1040 }
1041 #endif
1042 
1043 /*
1044  * Check whether the SSL backend supports the status_request extension.
1045  */
Curl_ssl_cert_status_request(void)1046 bool Curl_ssl_cert_status_request(void)
1047 {
1048   return Curl_ssl->cert_status_request();
1049 }
1050 
1051 /*
1052  * Check whether the SSL backend supports false start.
1053  */
Curl_ssl_false_start(void)1054 bool Curl_ssl_false_start(void)
1055 {
1056   return Curl_ssl->false_start();
1057 }
1058 
1059 /*
1060  * Check whether the SSL backend supports setting TLS 1.3 cipher suites
1061  */
Curl_ssl_tls13_ciphersuites(void)1062 bool Curl_ssl_tls13_ciphersuites(void)
1063 {
1064   return Curl_ssl->supports & SSLSUPP_TLS13_CIPHERSUITES;
1065 }
1066 
1067 /*
1068  * Default implementations for unsupported functions.
1069  */
1070 
Curl_none_init(void)1071 int Curl_none_init(void)
1072 {
1073   return 1;
1074 }
1075 
Curl_none_cleanup(void)1076 void Curl_none_cleanup(void)
1077 { }
1078 
Curl_none_shutdown(struct connectdata * conn UNUSED_PARAM,int sockindex UNUSED_PARAM)1079 int Curl_none_shutdown(struct connectdata *conn UNUSED_PARAM,
1080                        int sockindex UNUSED_PARAM)
1081 {
1082   (void)conn;
1083   (void)sockindex;
1084   return 0;
1085 }
1086 
Curl_none_check_cxn(struct connectdata * conn UNUSED_PARAM)1087 int Curl_none_check_cxn(struct connectdata *conn UNUSED_PARAM)
1088 {
1089   (void)conn;
1090   return -1;
1091 }
1092 
Curl_none_random(struct Curl_easy * data UNUSED_PARAM,unsigned char * entropy UNUSED_PARAM,size_t length UNUSED_PARAM)1093 CURLcode Curl_none_random(struct Curl_easy *data UNUSED_PARAM,
1094                           unsigned char *entropy UNUSED_PARAM,
1095                           size_t length UNUSED_PARAM)
1096 {
1097   (void)data;
1098   (void)entropy;
1099   (void)length;
1100   return CURLE_NOT_BUILT_IN;
1101 }
1102 
Curl_none_close_all(struct Curl_easy * data UNUSED_PARAM)1103 void Curl_none_close_all(struct Curl_easy *data UNUSED_PARAM)
1104 {
1105   (void)data;
1106 }
1107 
Curl_none_session_free(void * ptr UNUSED_PARAM)1108 void Curl_none_session_free(void *ptr UNUSED_PARAM)
1109 {
1110   (void)ptr;
1111 }
1112 
Curl_none_data_pending(const struct connectdata * conn UNUSED_PARAM,int connindex UNUSED_PARAM)1113 bool Curl_none_data_pending(const struct connectdata *conn UNUSED_PARAM,
1114                             int connindex UNUSED_PARAM)
1115 {
1116   (void)conn;
1117   (void)connindex;
1118   return 0;
1119 }
1120 
Curl_none_cert_status_request(void)1121 bool Curl_none_cert_status_request(void)
1122 {
1123   return FALSE;
1124 }
1125 
Curl_none_set_engine(struct Curl_easy * data UNUSED_PARAM,const char * engine UNUSED_PARAM)1126 CURLcode Curl_none_set_engine(struct Curl_easy *data UNUSED_PARAM,
1127                               const char *engine UNUSED_PARAM)
1128 {
1129   (void)data;
1130   (void)engine;
1131   return CURLE_NOT_BUILT_IN;
1132 }
1133 
Curl_none_set_engine_default(struct Curl_easy * data UNUSED_PARAM)1134 CURLcode Curl_none_set_engine_default(struct Curl_easy *data UNUSED_PARAM)
1135 {
1136   (void)data;
1137   return CURLE_NOT_BUILT_IN;
1138 }
1139 
Curl_none_engines_list(struct Curl_easy * data UNUSED_PARAM)1140 struct curl_slist *Curl_none_engines_list(struct Curl_easy *data UNUSED_PARAM)
1141 {
1142   (void)data;
1143   return (struct curl_slist *)NULL;
1144 }
1145 
Curl_none_false_start(void)1146 bool Curl_none_false_start(void)
1147 {
1148   return FALSE;
1149 }
1150 
1151 #ifndef CURL_DISABLE_CRYPTO_AUTH
Curl_none_md5sum(unsigned char * input,size_t inputlen,unsigned char * md5sum,size_t md5len UNUSED_PARAM)1152 CURLcode Curl_none_md5sum(unsigned char *input, size_t inputlen,
1153                           unsigned char *md5sum, size_t md5len UNUSED_PARAM)
1154 {
1155   struct MD5_context *MD5pw;
1156 
1157   (void)md5len;
1158 
1159   MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
1160   if(!MD5pw)
1161     return CURLE_OUT_OF_MEMORY;
1162   Curl_MD5_update(MD5pw, input, curlx_uztoui(inputlen));
1163   Curl_MD5_final(MD5pw, md5sum);
1164   return CURLE_OK;
1165 }
1166 #else
Curl_none_md5sum(unsigned char * input UNUSED_PARAM,size_t inputlen UNUSED_PARAM,unsigned char * md5sum UNUSED_PARAM,size_t md5len UNUSED_PARAM)1167 CURLcode Curl_none_md5sum(unsigned char *input UNUSED_PARAM,
1168                           size_t inputlen UNUSED_PARAM,
1169                           unsigned char *md5sum UNUSED_PARAM,
1170                           size_t md5len UNUSED_PARAM)
1171 {
1172   (void)input;
1173   (void)inputlen;
1174   (void)md5sum;
1175   (void)md5len;
1176   return CURLE_NOT_BUILT_IN;
1177 }
1178 #endif
1179 
Curl_multissl_init(void)1180 static int Curl_multissl_init(void)
1181 {
1182   if(multissl_init(NULL))
1183     return 1;
1184   return Curl_ssl->init();
1185 }
1186 
Curl_multissl_connect(struct connectdata * conn,int sockindex)1187 static CURLcode Curl_multissl_connect(struct connectdata *conn, int sockindex)
1188 {
1189   if(multissl_init(NULL))
1190     return CURLE_FAILED_INIT;
1191   return Curl_ssl->connect_blocking(conn, sockindex);
1192 }
1193 
Curl_multissl_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)1194 static CURLcode Curl_multissl_connect_nonblocking(struct connectdata *conn,
1195                                                   int sockindex, bool *done)
1196 {
1197   if(multissl_init(NULL))
1198     return CURLE_FAILED_INIT;
1199   return Curl_ssl->connect_nonblocking(conn, sockindex, done);
1200 }
1201 
Curl_multissl_get_internals(struct ssl_connect_data * connssl,CURLINFO info)1202 static void *Curl_multissl_get_internals(struct ssl_connect_data *connssl,
1203                                          CURLINFO info)
1204 {
1205   if(multissl_init(NULL))
1206     return NULL;
1207   return Curl_ssl->get_internals(connssl, info);
1208 }
1209 
Curl_multissl_close(struct connectdata * conn,int sockindex)1210 static void Curl_multissl_close(struct connectdata *conn, int sockindex)
1211 {
1212   if(multissl_init(NULL))
1213     return;
1214   Curl_ssl->close_one(conn, sockindex);
1215 }
1216 
1217 static const struct Curl_ssl Curl_ssl_multi = {
1218   { CURLSSLBACKEND_NONE, "multi" },  /* info */
1219   0, /* supports nothing */
1220   (size_t)-1, /* something insanely large to be on the safe side */
1221 
1222   Curl_multissl_init,                /* init */
1223   Curl_none_cleanup,                 /* cleanup */
1224   Curl_multissl_version,             /* version */
1225   Curl_none_check_cxn,               /* check_cxn */
1226   Curl_none_shutdown,                /* shutdown */
1227   Curl_none_data_pending,            /* data_pending */
1228   Curl_none_random,                  /* random */
1229   Curl_none_cert_status_request,     /* cert_status_request */
1230   Curl_multissl_connect,             /* connect */
1231   Curl_multissl_connect_nonblocking, /* connect_nonblocking */
1232   Curl_multissl_get_internals,       /* get_internals */
1233   Curl_multissl_close,               /* close_one */
1234   Curl_none_close_all,               /* close_all */
1235   Curl_none_session_free,            /* session_free */
1236   Curl_none_set_engine,              /* set_engine */
1237   Curl_none_set_engine_default,      /* set_engine_default */
1238   Curl_none_engines_list,            /* engines_list */
1239   Curl_none_false_start,             /* false_start */
1240   Curl_none_md5sum,                  /* md5sum */
1241   NULL                               /* sha256sum */
1242 };
1243 
1244 const struct Curl_ssl *Curl_ssl =
1245 #if defined(CURL_WITH_MULTI_SSL)
1246   &Curl_ssl_multi;
1247 #elif defined(USE_WOLFSSL)
1248   &Curl_ssl_wolfssl;
1249 #elif defined(USE_SECTRANSP)
1250   &Curl_ssl_sectransp;
1251 #elif defined(USE_GNUTLS)
1252   &Curl_ssl_gnutls;
1253 #elif defined(USE_GSKIT)
1254   &Curl_ssl_gskit;
1255 #elif defined(USE_MBEDTLS)
1256   &Curl_ssl_mbedtls;
1257 #elif defined(USE_NSS)
1258   &Curl_ssl_nss;
1259 #elif defined(USE_OPENSSL)
1260   &Curl_ssl_openssl;
1261 #elif defined(USE_SCHANNEL)
1262   &Curl_ssl_schannel;
1263 #elif defined(USE_MESALINK)
1264   &Curl_ssl_mesalink;
1265 #elif defined(USE_BEARSSL)
1266   &Curl_ssl_bearssl;
1267 #else
1268 #error "Missing struct Curl_ssl for selected SSL backend"
1269 #endif
1270 
1271 static const struct Curl_ssl *available_backends[] = {
1272 #if defined(USE_WOLFSSL)
1273   &Curl_ssl_wolfssl,
1274 #endif
1275 #if defined(USE_SECTRANSP)
1276   &Curl_ssl_sectransp,
1277 #endif
1278 #if defined(USE_GNUTLS)
1279   &Curl_ssl_gnutls,
1280 #endif
1281 #if defined(USE_GSKIT)
1282   &Curl_ssl_gskit,
1283 #endif
1284 #if defined(USE_MBEDTLS)
1285   &Curl_ssl_mbedtls,
1286 #endif
1287 #if defined(USE_NSS)
1288   &Curl_ssl_nss,
1289 #endif
1290 #if defined(USE_OPENSSL)
1291   &Curl_ssl_openssl,
1292 #endif
1293 #if defined(USE_SCHANNEL)
1294   &Curl_ssl_schannel,
1295 #endif
1296 #if defined(USE_MESALINK)
1297   &Curl_ssl_mesalink,
1298 #endif
1299 #if defined(USE_BEARSSL)
1300   &Curl_ssl_bearssl,
1301 #endif
1302   NULL
1303 };
1304 
Curl_multissl_version(char * buffer,size_t size)1305 static size_t Curl_multissl_version(char *buffer, size_t size)
1306 {
1307   static const struct Curl_ssl *selected;
1308   static char backends[200];
1309   static size_t backends_len;
1310   const struct Curl_ssl *current;
1311 
1312   current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl;
1313 
1314   if(current != selected) {
1315     char *p = backends;
1316     char *end = backends + sizeof(backends);
1317     int i;
1318 
1319     selected = current;
1320 
1321     backends[0] = '\0';
1322 
1323     for(i = 0; available_backends[i]; ++i) {
1324       char vb[200];
1325       bool paren = (selected != available_backends[i]);
1326 
1327       if(available_backends[i]->version(vb, sizeof(vb))) {
1328         p += msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""),
1329                        (paren ? "(" : ""), vb, (paren ? ")" : ""));
1330       }
1331     }
1332 
1333     backends_len = p - backends;
1334   }
1335 
1336   if(!size)
1337     return 0;
1338 
1339   if(size <= backends_len) {
1340     strncpy(buffer, backends, size - 1);
1341     buffer[size - 1] = '\0';
1342     return size - 1;
1343   }
1344 
1345   strcpy(buffer, backends);
1346   return backends_len;
1347 }
1348 
multissl_init(const struct Curl_ssl * backend)1349 static int multissl_init(const struct Curl_ssl *backend)
1350 {
1351   const char *env;
1352   char *env_tmp;
1353 
1354   if(Curl_ssl != &Curl_ssl_multi)
1355     return 1;
1356 
1357   if(backend) {
1358     Curl_ssl = backend;
1359     return 0;
1360   }
1361 
1362   if(!available_backends[0])
1363     return 1;
1364 
1365   env = env_tmp = curl_getenv("CURL_SSL_BACKEND");
1366 #ifdef CURL_DEFAULT_SSL_BACKEND
1367   if(!env)
1368     env = CURL_DEFAULT_SSL_BACKEND;
1369 #endif
1370   if(env) {
1371     int i;
1372     for(i = 0; available_backends[i]; i++) {
1373       if(strcasecompare(env, available_backends[i]->info.name)) {
1374         Curl_ssl = available_backends[i];
1375         curl_free(env_tmp);
1376         return 0;
1377       }
1378     }
1379   }
1380 
1381   /* Fall back to first available backend */
1382   Curl_ssl = available_backends[0];
1383   curl_free(env_tmp);
1384   return 0;
1385 }
1386 
curl_global_sslset(curl_sslbackend id,const char * name,const curl_ssl_backend *** avail)1387 CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
1388                               const curl_ssl_backend ***avail)
1389 {
1390   int i;
1391 
1392   if(avail)
1393     *avail = (const curl_ssl_backend **)&available_backends;
1394 
1395   if(Curl_ssl != &Curl_ssl_multi)
1396     return id == Curl_ssl->info.id ||
1397            (name && strcasecompare(name, Curl_ssl->info.name)) ?
1398            CURLSSLSET_OK :
1399 #if defined(CURL_WITH_MULTI_SSL)
1400            CURLSSLSET_TOO_LATE;
1401 #else
1402            CURLSSLSET_UNKNOWN_BACKEND;
1403 #endif
1404 
1405   for(i = 0; available_backends[i]; i++) {
1406     if(available_backends[i]->info.id == id ||
1407        (name && strcasecompare(available_backends[i]->info.name, name))) {
1408       multissl_init(available_backends[i]);
1409       return CURLSSLSET_OK;
1410     }
1411   }
1412 
1413   return CURLSSLSET_UNKNOWN_BACKEND;
1414 }
1415 
1416 #else /* USE_SSL */
curl_global_sslset(curl_sslbackend id,const char * name,const curl_ssl_backend *** avail)1417 CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
1418                               const curl_ssl_backend ***avail)
1419 {
1420   (void)id;
1421   (void)name;
1422   (void)avail;
1423   return CURLSSLSET_NO_BACKENDS;
1424 }
1425 
1426 #endif /* !USE_SSL */
1427