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