• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 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  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 
25 /* This file is for implementing all "generic" SSL functions that all libcurl
26    internals should use. It is then responsible for calling the proper
27    "backend" function.
28 
29    SSL-functions in libcurl should call functions in this source file, and not
30    to any specific SSL-layer.
31 
32    Curl_ssl_ - prefix for generic ones
33 
34    Note that this source code uses the functions of the configured SSL
35    backend via the global Curl_ssl instance.
36 
37    "SSL/TLS Strong Encryption: An Introduction"
38    https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
39 */
40 
41 #include "curl_setup.h"
42 
43 #ifdef HAVE_SYS_TYPES_H
44 #include <sys/types.h>
45 #endif
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif
49 #ifdef HAVE_FCNTL_H
50 #include <fcntl.h>
51 #endif
52 
53 #include "urldata.h"
54 #include "cfilters.h"
55 
56 #include "vtls.h" /* generic SSL protos etc */
57 #include "vtls_int.h"
58 #include "slist.h"
59 #include "sendf.h"
60 #include "strcase.h"
61 #include "url.h"
62 #include "progress.h"
63 #include "share.h"
64 #include "multiif.h"
65 #include "timeval.h"
66 #include "curl_md5.h"
67 #include "warnless.h"
68 #include "curl_base64.h"
69 #include "curl_printf.h"
70 #include "strdup.h"
71 
72 /* The last #include files should be: */
73 #include "curl_memory.h"
74 #include "memdebug.h"
75 
76 
77 /* convenience macro to check if this handle is using a shared SSL session */
78 #define SSLSESSION_SHARED(data) (data->share &&                        \
79                                  (data->share->specifier &             \
80                                   (1<<CURL_LOCK_DATA_SSL_SESSION)))
81 
82 #define CLONE_STRING(var)                    \
83   do {                                       \
84     if(source->var) {                        \
85       dest->var = strdup(source->var);       \
86       if(!dest->var)                         \
87         return FALSE;                        \
88     }                                        \
89     else                                     \
90       dest->var = NULL;                      \
91   } while(0)
92 
93 #define CLONE_BLOB(var)                        \
94   do {                                         \
95     if(blobdup(&dest->var, source->var))       \
96       return FALSE;                            \
97   } while(0)
98 
blobdup(struct curl_blob ** dest,struct curl_blob * src)99 static CURLcode blobdup(struct curl_blob **dest,
100                         struct curl_blob *src)
101 {
102   DEBUGASSERT(dest);
103   DEBUGASSERT(!*dest);
104   if(src) {
105     /* only if there's data to dupe! */
106     struct curl_blob *d;
107     d = malloc(sizeof(struct curl_blob) + src->len);
108     if(!d)
109       return CURLE_OUT_OF_MEMORY;
110     d->len = src->len;
111     /* Always duplicate because the connection may survive longer than the
112        handle that passed in the blob. */
113     d->flags = CURL_BLOB_COPY;
114     d->data = (void *)((char *)d + sizeof(struct curl_blob));
115     memcpy(d->data, src->data, src->len);
116     *dest = d;
117   }
118   return CURLE_OK;
119 }
120 
121 /* returns TRUE if the blobs are identical */
blobcmp(struct curl_blob * first,struct curl_blob * second)122 static bool blobcmp(struct curl_blob *first, struct curl_blob *second)
123 {
124   if(!first && !second) /* both are NULL */
125     return TRUE;
126   if(!first || !second) /* one is NULL */
127     return FALSE;
128   if(first->len != second->len) /* different sizes */
129     return FALSE;
130   return !memcmp(first->data, second->data, first->len); /* same data */
131 }
132 
133 
134 bool
Curl_ssl_config_matches(struct ssl_primary_config * data,struct ssl_primary_config * needle)135 Curl_ssl_config_matches(struct ssl_primary_config *data,
136                         struct ssl_primary_config *needle)
137 {
138   if((data->version == needle->version) &&
139      (data->version_max == needle->version_max) &&
140      (data->ssl_options == needle->ssl_options) &&
141      (data->verifypeer == needle->verifypeer) &&
142      (data->verifyhost == needle->verifyhost) &&
143      (data->verifystatus == needle->verifystatus) &&
144      blobcmp(data->cert_blob, needle->cert_blob) &&
145      blobcmp(data->ca_info_blob, needle->ca_info_blob) &&
146      blobcmp(data->issuercert_blob, needle->issuercert_blob) &&
147      Curl_safecmp(data->CApath, needle->CApath) &&
148      Curl_safecmp(data->CAfile, needle->CAfile) &&
149      Curl_safecmp(data->issuercert, needle->issuercert) &&
150      Curl_safecmp(data->clientcert, needle->clientcert) &&
151 #ifdef USE_TLS_SRP
152      !Curl_timestrcmp(data->username, needle->username) &&
153      !Curl_timestrcmp(data->password, needle->password) &&
154 #endif
155      strcasecompare(data->cipher_list, needle->cipher_list) &&
156      strcasecompare(data->cipher_list13, needle->cipher_list13) &&
157      strcasecompare(data->curves, needle->curves) &&
158      strcasecompare(data->CRLfile, needle->CRLfile) &&
159      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   dest->ssl_options = source->ssl_options;
176 
177   CLONE_BLOB(cert_blob);
178   CLONE_BLOB(ca_info_blob);
179   CLONE_BLOB(issuercert_blob);
180   CLONE_STRING(CApath);
181   CLONE_STRING(CAfile);
182   CLONE_STRING(issuercert);
183   CLONE_STRING(clientcert);
184   CLONE_STRING(cipher_list);
185   CLONE_STRING(cipher_list13);
186   CLONE_STRING(pinned_key);
187   CLONE_STRING(curves);
188   CLONE_STRING(CRLfile);
189 #ifdef USE_TLS_SRP
190   CLONE_STRING(username);
191   CLONE_STRING(password);
192 #endif
193 
194   return TRUE;
195 }
196 
Curl_free_primary_ssl_config(struct ssl_primary_config * sslc)197 void Curl_free_primary_ssl_config(struct ssl_primary_config *sslc)
198 {
199   Curl_safefree(sslc->CApath);
200   Curl_safefree(sslc->CAfile);
201   Curl_safefree(sslc->issuercert);
202   Curl_safefree(sslc->clientcert);
203   Curl_safefree(sslc->cipher_list);
204   Curl_safefree(sslc->cipher_list13);
205   Curl_safefree(sslc->pinned_key);
206   Curl_safefree(sslc->cert_blob);
207   Curl_safefree(sslc->ca_info_blob);
208   Curl_safefree(sslc->issuercert_blob);
209   Curl_safefree(sslc->curves);
210   Curl_safefree(sslc->CRLfile);
211 #ifdef USE_TLS_SRP
212   Curl_safefree(sslc->username);
213   Curl_safefree(sslc->password);
214 #endif
215 }
216 
217 #ifdef USE_SSL
218 static int multissl_setup(const struct Curl_ssl *backend);
219 #endif
220 
Curl_ssl_backend(void)221 curl_sslbackend Curl_ssl_backend(void)
222 {
223 #ifdef USE_SSL
224   multissl_setup(NULL);
225   return Curl_ssl->info.id;
226 #else
227   return CURLSSLBACKEND_NONE;
228 #endif
229 }
230 
231 #ifdef USE_SSL
232 
233 /* "global" init done? */
234 static bool init_ssl = FALSE;
235 
236 /**
237  * Global SSL init
238  *
239  * @retval 0 error initializing SSL
240  * @retval 1 SSL initialized successfully
241  */
Curl_ssl_init(void)242 int Curl_ssl_init(void)
243 {
244   /* make sure this is only done once */
245   if(init_ssl)
246     return 1;
247   init_ssl = TRUE; /* never again */
248 
249   return Curl_ssl->init();
250 }
251 
252 #if defined(CURL_WITH_MULTI_SSL)
253 static const struct Curl_ssl Curl_ssl_multi;
254 #endif
255 
256 /* Global cleanup */
Curl_ssl_cleanup(void)257 void Curl_ssl_cleanup(void)
258 {
259   if(init_ssl) {
260     /* only cleanup if we did a previous init */
261     Curl_ssl->cleanup();
262 #if defined(CURL_WITH_MULTI_SSL)
263     Curl_ssl = &Curl_ssl_multi;
264 #endif
265     init_ssl = FALSE;
266   }
267 }
268 
ssl_prefs_check(struct Curl_easy * data)269 static bool ssl_prefs_check(struct Curl_easy *data)
270 {
271   /* check for CURLOPT_SSLVERSION invalid parameter value */
272   const unsigned char sslver = data->set.ssl.primary.version;
273   if(sslver >= CURL_SSLVERSION_LAST) {
274     failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
275     return FALSE;
276   }
277 
278   switch(data->set.ssl.primary.version_max) {
279   case CURL_SSLVERSION_MAX_NONE:
280   case CURL_SSLVERSION_MAX_DEFAULT:
281     break;
282 
283   default:
284     if((data->set.ssl.primary.version_max >> 16) < sslver) {
285       failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION");
286       return FALSE;
287     }
288   }
289 
290   return TRUE;
291 }
292 
cf_ctx_new(struct Curl_easy * data,const struct alpn_spec * alpn)293 static struct ssl_connect_data *cf_ctx_new(struct Curl_easy *data,
294                                            const struct alpn_spec *alpn)
295 {
296   struct ssl_connect_data *ctx;
297 
298   (void)data;
299   ctx = calloc(1, sizeof(*ctx));
300   if(!ctx)
301     return NULL;
302 
303   ctx->alpn = alpn;
304   ctx->backend = calloc(1, Curl_ssl->sizeof_ssl_backend_data);
305   if(!ctx->backend) {
306     free(ctx);
307     return NULL;
308   }
309   return ctx;
310 }
311 
cf_ctx_free(struct ssl_connect_data * ctx)312 static void cf_ctx_free(struct ssl_connect_data *ctx)
313 {
314   if(ctx) {
315     free(ctx->backend);
316     free(ctx);
317   }
318 }
319 
ssl_connect(struct Curl_cfilter * cf,struct Curl_easy * data)320 static CURLcode ssl_connect(struct Curl_cfilter *cf, struct Curl_easy *data)
321 {
322   struct ssl_connect_data *connssl = cf->ctx;
323   CURLcode result;
324 
325   if(!ssl_prefs_check(data))
326     return CURLE_SSL_CONNECT_ERROR;
327 
328   /* mark this is being ssl-enabled from here on. */
329   connssl->state = ssl_connection_negotiating;
330 
331   result = Curl_ssl->connect_blocking(cf, data);
332 
333   if(!result) {
334     DEBUGASSERT(connssl->state == ssl_connection_complete);
335   }
336 
337   return result;
338 }
339 
340 static CURLcode
ssl_connect_nonblocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)341 ssl_connect_nonblocking(struct Curl_cfilter *cf, struct Curl_easy *data,
342                         bool *done)
343 {
344   if(!ssl_prefs_check(data))
345     return CURLE_SSL_CONNECT_ERROR;
346 
347   /* mark this is being ssl requested from here on. */
348   return Curl_ssl->connect_nonblocking(cf, data, done);
349 }
350 
351 /*
352  * Lock shared SSL session data
353  */
Curl_ssl_sessionid_lock(struct Curl_easy * data)354 void Curl_ssl_sessionid_lock(struct Curl_easy *data)
355 {
356   if(SSLSESSION_SHARED(data))
357     Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
358 }
359 
360 /*
361  * Unlock shared SSL session data
362  */
Curl_ssl_sessionid_unlock(struct Curl_easy * data)363 void Curl_ssl_sessionid_unlock(struct Curl_easy *data)
364 {
365   if(SSLSESSION_SHARED(data))
366     Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
367 }
368 
369 /*
370  * Check if there's a session ID for the given connection in the cache, and if
371  * there's one suitable, it is provided. Returns TRUE when no entry matched.
372  */
Curl_ssl_getsessionid(struct Curl_cfilter * cf,struct Curl_easy * data,void ** ssl_sessionid,size_t * idsize)373 bool Curl_ssl_getsessionid(struct Curl_cfilter *cf,
374                            struct Curl_easy *data,
375                            void **ssl_sessionid,
376                            size_t *idsize) /* set 0 if unknown */
377 {
378   struct ssl_connect_data *connssl = cf->ctx;
379   struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
380   struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
381   struct Curl_ssl_session *check;
382   size_t i;
383   long *general_age;
384   bool no_match = TRUE;
385 
386   *ssl_sessionid = NULL;
387   if(!ssl_config)
388     return TRUE;
389 
390   DEBUGASSERT(ssl_config->primary.sessionid);
391 
392   if(!ssl_config->primary.sessionid || !data->state.session)
393     /* session ID re-use is disabled or the session cache has not been
394        setup */
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(connssl->hostname, check->name) &&
409        ((!cf->conn->bits.conn_to_host && !check->conn_to_host) ||
410         (cf->conn->bits.conn_to_host && check->conn_to_host &&
411          strcasecompare(cf->conn->conn_to_host.name, check->conn_to_host))) &&
412        ((!cf->conn->bits.conn_to_port && check->conn_to_port == -1) ||
413         (cf->conn->bits.conn_to_port && check->conn_to_port != -1 &&
414          cf->conn->conn_to_port == check->conn_to_port)) &&
415        (connssl->port == check->remote_port) &&
416        strcasecompare(cf->conn->handler->scheme, check->scheme) &&
417        Curl_ssl_config_matches(conn_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   DEBUGF(infof(data, DMSG(data, "%s Session ID in cache for %s %s://%s:%d"),
430                no_match? "Didn't find": "Found",
431                Curl_ssl_cf_is_proxy(cf) ? "proxy" : "host",
432                cf->conn->handler->scheme, connssl->hostname, connssl->port));
433   return no_match;
434 }
435 
436 /*
437  * Kill a single session ID entry in the cache.
438  */
Curl_ssl_kill_session(struct Curl_ssl_session * session)439 void Curl_ssl_kill_session(struct Curl_ssl_session *session)
440 {
441   if(session->sessionid) {
442     /* defensive check */
443 
444     /* free the ID the SSL-layer specific way */
445     Curl_ssl->session_free(session->sessionid);
446 
447     session->sessionid = NULL;
448     session->age = 0; /* fresh */
449 
450     Curl_free_primary_ssl_config(&session->ssl_config);
451 
452     Curl_safefree(session->name);
453     Curl_safefree(session->conn_to_host);
454   }
455 }
456 
457 /*
458  * Delete the given session ID from the cache.
459  */
Curl_ssl_delsessionid(struct Curl_easy * data,void * ssl_sessionid)460 void Curl_ssl_delsessionid(struct Curl_easy *data, void *ssl_sessionid)
461 {
462   size_t i;
463 
464   for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
465     struct Curl_ssl_session *check = &data->state.session[i];
466 
467     if(check->sessionid == ssl_sessionid) {
468       Curl_ssl_kill_session(check);
469       break;
470     }
471   }
472 }
473 
474 /*
475  * Store session id in the session cache. The ID passed on to this function
476  * must already have been extracted and allocated the proper way for the SSL
477  * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
478  * later on.
479  */
Curl_ssl_addsessionid(struct Curl_cfilter * cf,struct Curl_easy * data,void * ssl_sessionid,size_t idsize,bool * added)480 CURLcode Curl_ssl_addsessionid(struct Curl_cfilter *cf,
481                                struct Curl_easy *data,
482                                void *ssl_sessionid,
483                                size_t idsize,
484                                bool *added)
485 {
486   struct ssl_connect_data *connssl = cf->ctx;
487   struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
488   struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
489   size_t i;
490   struct Curl_ssl_session *store;
491   long oldest_age;
492   char *clone_host;
493   char *clone_conn_to_host;
494   int conn_to_port;
495   long *general_age;
496 
497   if(added)
498     *added = FALSE;
499 
500   if(!data->state.session)
501     return CURLE_OK;
502 
503   store = &data->state.session[0];
504   oldest_age = data->state.session[0].age; /* zero if unused */
505   (void)ssl_config;
506   DEBUGASSERT(ssl_config->primary.sessionid);
507 
508   clone_host = strdup(connssl->hostname);
509   if(!clone_host)
510     return CURLE_OUT_OF_MEMORY; /* bail out */
511 
512   if(cf->conn->bits.conn_to_host) {
513     clone_conn_to_host = strdup(cf->conn->conn_to_host.name);
514     if(!clone_conn_to_host) {
515       free(clone_host);
516       return CURLE_OUT_OF_MEMORY; /* bail out */
517     }
518   }
519   else
520     clone_conn_to_host = NULL;
521 
522   if(cf->conn->bits.conn_to_port)
523     conn_to_port = cf->conn->conn_to_port;
524   else
525     conn_to_port = -1;
526 
527   /* Now we should add the session ID and the host name to the cache, (remove
528      the oldest if necessary) */
529 
530   /* If using shared SSL session, lock! */
531   if(SSLSESSION_SHARED(data)) {
532     general_age = &data->share->sessionage;
533   }
534   else {
535     general_age = &data->state.sessionage;
536   }
537 
538   /* find an empty slot for us, or find the oldest */
539   for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) &&
540         data->state.session[i].sessionid; i++) {
541     if(data->state.session[i].age < oldest_age) {
542       oldest_age = data->state.session[i].age;
543       store = &data->state.session[i];
544     }
545   }
546   if(i == data->set.general_ssl.max_ssl_sessions)
547     /* cache is full, we must "kill" the oldest entry! */
548     Curl_ssl_kill_session(store);
549   else
550     store = &data->state.session[i]; /* use this slot */
551 
552   /* now init the session struct wisely */
553   store->sessionid = ssl_sessionid;
554   store->idsize = idsize;
555   store->age = *general_age;    /* set current age */
556   /* free it if there's one already present */
557   free(store->name);
558   free(store->conn_to_host);
559   store->name = clone_host;               /* clone host name */
560   store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
561   store->conn_to_port = conn_to_port; /* connect to port number */
562   /* port number */
563   store->remote_port = connssl->port;
564   store->scheme = cf->conn->handler->scheme;
565 
566   if(!Curl_clone_primary_ssl_config(conn_config, &store->ssl_config)) {
567     Curl_free_primary_ssl_config(&store->ssl_config);
568     store->sessionid = NULL; /* let caller free sessionid */
569     free(clone_host);
570     free(clone_conn_to_host);
571     return CURLE_OUT_OF_MEMORY;
572   }
573 
574   if(added)
575     *added = TRUE;
576 
577   DEBUGF(infof(data, DMSG(data, "Added Session ID to cache for %s://%s:%d"
578                " [%s]"), store->scheme, store->name, store->remote_port,
579                Curl_ssl_cf_is_proxy(cf) ? "PROXY" : "server"));
580   return CURLE_OK;
581 }
582 
Curl_free_multi_ssl_backend_data(struct multi_ssl_backend_data * mbackend)583 void Curl_free_multi_ssl_backend_data(struct multi_ssl_backend_data *mbackend)
584 {
585   if(Curl_ssl->free_multi_ssl_backend_data && mbackend)
586     Curl_ssl->free_multi_ssl_backend_data(mbackend);
587 }
588 
Curl_ssl_close_all(struct Curl_easy * data)589 void Curl_ssl_close_all(struct Curl_easy *data)
590 {
591   /* kill the session ID cache if not shared */
592   if(data->state.session && !SSLSESSION_SHARED(data)) {
593     size_t i;
594     for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++)
595       /* the single-killer function handles empty table slots */
596       Curl_ssl_kill_session(&data->state.session[i]);
597 
598     /* free the cache data */
599     Curl_safefree(data->state.session);
600   }
601 
602   Curl_ssl->close_all(data);
603 }
604 
Curl_ssl_get_select_socks(struct Curl_cfilter * cf,struct Curl_easy * data,curl_socket_t * socks)605 int Curl_ssl_get_select_socks(struct Curl_cfilter *cf, struct Curl_easy *data,
606                               curl_socket_t *socks)
607 {
608   struct ssl_connect_data *connssl = cf->ctx;
609   curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data);
610 
611   if(sock != CURL_SOCKET_BAD) {
612     if(connssl->connecting_state == ssl_connect_2_writing) {
613       /* write mode */
614       socks[0] = sock;
615       return GETSOCK_WRITESOCK(0);
616     }
617     if(connssl->connecting_state == ssl_connect_2_reading) {
618       /* read mode */
619       socks[0] = sock;
620       return GETSOCK_READSOCK(0);
621     }
622   }
623   return GETSOCK_BLANK;
624 }
625 
626 /* Selects an SSL crypto engine
627  */
Curl_ssl_set_engine(struct Curl_easy * data,const char * engine)628 CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
629 {
630   return Curl_ssl->set_engine(data, engine);
631 }
632 
633 /* Selects the default SSL crypto engine
634  */
Curl_ssl_set_engine_default(struct Curl_easy * data)635 CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
636 {
637   return Curl_ssl->set_engine_default(data);
638 }
639 
640 /* Return list of OpenSSL crypto engine names. */
Curl_ssl_engines_list(struct Curl_easy * data)641 struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
642 {
643   return Curl_ssl->engines_list(data);
644 }
645 
646 /*
647  * This sets up a session ID cache to the specified size. Make sure this code
648  * is agnostic to what underlying SSL technology we use.
649  */
Curl_ssl_initsessions(struct Curl_easy * data,size_t amount)650 CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
651 {
652   struct Curl_ssl_session *session;
653 
654   if(data->state.session)
655     /* this is just a precaution to prevent multiple inits */
656     return CURLE_OK;
657 
658   session = calloc(amount, sizeof(struct Curl_ssl_session));
659   if(!session)
660     return CURLE_OUT_OF_MEMORY;
661 
662   /* store the info in the SSL section */
663   data->set.general_ssl.max_ssl_sessions = amount;
664   data->state.session = session;
665   data->state.sessionage = 1; /* this is brand new */
666   return CURLE_OK;
667 }
668 
669 static size_t multissl_version(char *buffer, size_t size);
670 
Curl_ssl_version(char * buffer,size_t size)671 void Curl_ssl_version(char *buffer, size_t size)
672 {
673 #ifdef CURL_WITH_MULTI_SSL
674   (void)multissl_version(buffer, size);
675 #else
676   (void)Curl_ssl->version(buffer, size);
677 #endif
678 }
679 
Curl_ssl_free_certinfo(struct Curl_easy * data)680 void Curl_ssl_free_certinfo(struct Curl_easy *data)
681 {
682   struct curl_certinfo *ci = &data->info.certs;
683 
684   if(ci->num_of_certs) {
685     /* free all individual lists used */
686     int i;
687     for(i = 0; i<ci->num_of_certs; i++) {
688       curl_slist_free_all(ci->certinfo[i]);
689       ci->certinfo[i] = NULL;
690     }
691 
692     free(ci->certinfo); /* free the actual array too */
693     ci->certinfo = NULL;
694     ci->num_of_certs = 0;
695   }
696 }
697 
Curl_ssl_init_certinfo(struct Curl_easy * data,int num)698 CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
699 {
700   struct curl_certinfo *ci = &data->info.certs;
701   struct curl_slist **table;
702 
703   /* Free any previous certificate information structures */
704   Curl_ssl_free_certinfo(data);
705 
706   /* Allocate the required certificate information structures */
707   table = calloc((size_t) num, sizeof(struct curl_slist *));
708   if(!table)
709     return CURLE_OUT_OF_MEMORY;
710 
711   ci->num_of_certs = num;
712   ci->certinfo = table;
713 
714   return CURLE_OK;
715 }
716 
717 /*
718  * 'value' is NOT a null-terminated string
719  */
Curl_ssl_push_certinfo_len(struct Curl_easy * data,int certnum,const char * label,const char * value,size_t valuelen)720 CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
721                                     int certnum,
722                                     const char *label,
723                                     const char *value,
724                                     size_t valuelen)
725 {
726   struct curl_certinfo *ci = &data->info.certs;
727   char *output;
728   struct curl_slist *nl;
729   CURLcode result = CURLE_OK;
730   size_t labellen = strlen(label);
731   size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
732 
733   output = malloc(outlen);
734   if(!output)
735     return CURLE_OUT_OF_MEMORY;
736 
737   /* sprintf the label and colon */
738   msnprintf(output, outlen, "%s:", label);
739 
740   /* memcpy the value (it might not be null-terminated) */
741   memcpy(&output[labellen + 1], value, valuelen);
742 
743   /* null-terminate the output */
744   output[labellen + 1 + valuelen] = 0;
745 
746   nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
747   if(!nl) {
748     free(output);
749     curl_slist_free_all(ci->certinfo[certnum]);
750     result = CURLE_OUT_OF_MEMORY;
751   }
752 
753   ci->certinfo[certnum] = nl;
754   return result;
755 }
756 
757 /*
758  * This is a convenience function for push_certinfo_len that takes a zero
759  * terminated value.
760  */
Curl_ssl_push_certinfo(struct Curl_easy * data,int certnum,const char * label,const char * value)761 CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data,
762                                 int certnum,
763                                 const char *label,
764                                 const char *value)
765 {
766   size_t valuelen = strlen(value);
767 
768   return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
769 }
770 
Curl_ssl_random(struct Curl_easy * data,unsigned char * entropy,size_t length)771 CURLcode Curl_ssl_random(struct Curl_easy *data,
772                          unsigned char *entropy,
773                          size_t length)
774 {
775   return Curl_ssl->random(data, entropy, length);
776 }
777 
778 /*
779  * Curl_ssl_snihost() converts the input host name to a suitable SNI name put
780  * in data->state.buffer. Returns a pointer to the name (or NULL if a problem)
781  * and stores the new length in 'olen'.
782  *
783  * SNI fields must not have any trailing dot and while RFC 6066 section 3 says
784  * the SNI field is case insensitive, browsers always send the data lowercase
785  * and subsequently there are numerous servers out there that don't work
786  * unless the name is lowercased.
787  */
788 
Curl_ssl_snihost(struct Curl_easy * data,const char * host,size_t * olen)789 char *Curl_ssl_snihost(struct Curl_easy *data, const char *host, size_t *olen)
790 {
791   size_t len = strlen(host);
792   if(len && (host[len-1] == '.'))
793     len--;
794   if(len >= data->set.buffer_size)
795     return NULL;
796 
797   Curl_strntolower(data->state.buffer, host, len);
798   data->state.buffer[len] = 0;
799   if(olen)
800     *olen = len;
801   return data->state.buffer;
802 }
803 
804 /*
805  * Public key pem to der conversion
806  */
807 
pubkey_pem_to_der(const char * pem,unsigned char ** der,size_t * der_len)808 static CURLcode pubkey_pem_to_der(const char *pem,
809                                   unsigned char **der, size_t *der_len)
810 {
811   char *stripped_pem, *begin_pos, *end_pos;
812   size_t pem_count, stripped_pem_count = 0, pem_len;
813   CURLcode result;
814 
815   /* if no pem, exit. */
816   if(!pem)
817     return CURLE_BAD_CONTENT_ENCODING;
818 
819   begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
820   if(!begin_pos)
821     return CURLE_BAD_CONTENT_ENCODING;
822 
823   pem_count = begin_pos - pem;
824   /* Invalid if not at beginning AND not directly following \n */
825   if(0 != pem_count && '\n' != pem[pem_count - 1])
826     return CURLE_BAD_CONTENT_ENCODING;
827 
828   /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
829   pem_count += 26;
830 
831   /* Invalid if not directly following \n */
832   end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
833   if(!end_pos)
834     return CURLE_BAD_CONTENT_ENCODING;
835 
836   pem_len = end_pos - pem;
837 
838   stripped_pem = malloc(pem_len - pem_count + 1);
839   if(!stripped_pem)
840     return CURLE_OUT_OF_MEMORY;
841 
842   /*
843    * Here we loop through the pem array one character at a time between the
844    * correct indices, and place each character that is not '\n' or '\r'
845    * into the stripped_pem array, which should represent the raw base64 string
846    */
847   while(pem_count < pem_len) {
848     if('\n' != pem[pem_count] && '\r' != pem[pem_count])
849       stripped_pem[stripped_pem_count++] = pem[pem_count];
850     ++pem_count;
851   }
852   /* Place the null terminator in the correct place */
853   stripped_pem[stripped_pem_count] = '\0';
854 
855   result = Curl_base64_decode(stripped_pem, der, der_len);
856 
857   Curl_safefree(stripped_pem);
858 
859   return result;
860 }
861 
862 /*
863  * Generic pinned public key check.
864  */
865 
Curl_pin_peer_pubkey(struct Curl_easy * data,const char * pinnedpubkey,const unsigned char * pubkey,size_t pubkeylen)866 CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
867                               const char *pinnedpubkey,
868                               const unsigned char *pubkey, size_t pubkeylen)
869 {
870   FILE *fp;
871   unsigned char *buf = NULL, *pem_ptr = NULL;
872   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
873 
874   /* if a path wasn't specified, don't pin */
875   if(!pinnedpubkey)
876     return CURLE_OK;
877   if(!pubkey || !pubkeylen)
878     return result;
879 
880   /* only do this if pinnedpubkey starts with "sha256//", length 8 */
881   if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
882     CURLcode encode;
883     size_t encodedlen, pinkeylen;
884     char *encoded, *pinkeycopy, *begin_pos, *end_pos;
885     unsigned char *sha256sumdigest;
886 
887     if(!Curl_ssl->sha256sum) {
888       /* without sha256 support, this cannot match */
889       return result;
890     }
891 
892     /* compute sha256sum of public key */
893     sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH);
894     if(!sha256sumdigest)
895       return CURLE_OUT_OF_MEMORY;
896     encode = Curl_ssl->sha256sum(pubkey, pubkeylen,
897                         sha256sumdigest, CURL_SHA256_DIGEST_LENGTH);
898 
899     if(encode != CURLE_OK)
900       return encode;
901 
902     encode = Curl_base64_encode((char *)sha256sumdigest,
903                                 CURL_SHA256_DIGEST_LENGTH, &encoded,
904                                 &encodedlen);
905     Curl_safefree(sha256sumdigest);
906 
907     if(encode)
908       return encode;
909 
910     infof(data, " public key hash: sha256//%s", encoded);
911 
912     /* it starts with sha256//, copy so we can modify it */
913     pinkeylen = strlen(pinnedpubkey) + 1;
914     pinkeycopy = malloc(pinkeylen);
915     if(!pinkeycopy) {
916       Curl_safefree(encoded);
917       return CURLE_OUT_OF_MEMORY;
918     }
919     memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
920     /* point begin_pos to the copy, and start extracting keys */
921     begin_pos = pinkeycopy;
922     do {
923       end_pos = strstr(begin_pos, ";sha256//");
924       /*
925        * if there is an end_pos, null terminate,
926        * otherwise it'll go to the end of the original string
927        */
928       if(end_pos)
929         end_pos[0] = '\0';
930 
931       /* compare base64 sha256 digests, 8 is the length of "sha256//" */
932       if(encodedlen == strlen(begin_pos + 8) &&
933          !memcmp(encoded, begin_pos + 8, encodedlen)) {
934         result = CURLE_OK;
935         break;
936       }
937 
938       /*
939        * change back the null-terminator we changed earlier,
940        * and look for next begin
941        */
942       if(end_pos) {
943         end_pos[0] = ';';
944         begin_pos = strstr(end_pos, "sha256//");
945       }
946     } while(end_pos && begin_pos);
947     Curl_safefree(encoded);
948     Curl_safefree(pinkeycopy);
949     return result;
950   }
951 
952   fp = fopen(pinnedpubkey, "rb");
953   if(!fp)
954     return result;
955 
956   do {
957     long filesize;
958     size_t size, pem_len;
959     CURLcode pem_read;
960 
961     /* Determine the file's size */
962     if(fseek(fp, 0, SEEK_END))
963       break;
964     filesize = ftell(fp);
965     if(fseek(fp, 0, SEEK_SET))
966       break;
967     if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
968       break;
969 
970     /*
971      * if the size of our certificate is bigger than the file
972      * size then it can't match
973      */
974     size = curlx_sotouz((curl_off_t) filesize);
975     if(pubkeylen > size)
976       break;
977 
978     /*
979      * Allocate buffer for the pinned key
980      * With 1 additional byte for null terminator in case of PEM key
981      */
982     buf = malloc(size + 1);
983     if(!buf)
984       break;
985 
986     /* Returns number of elements read, which should be 1 */
987     if((int) fread(buf, size, 1, fp) != 1)
988       break;
989 
990     /* If the sizes are the same, it can't be base64 encoded, must be der */
991     if(pubkeylen == size) {
992       if(!memcmp(pubkey, buf, pubkeylen))
993         result = CURLE_OK;
994       break;
995     }
996 
997     /*
998      * Otherwise we will assume it's PEM and try to decode it
999      * after placing null terminator
1000      */
1001     buf[size] = '\0';
1002     pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
1003     /* if it wasn't read successfully, exit */
1004     if(pem_read)
1005       break;
1006 
1007     /*
1008      * if the size of our certificate doesn't match the size of
1009      * the decoded file, they can't be the same, otherwise compare
1010      */
1011     if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
1012       result = CURLE_OK;
1013   } while(0);
1014 
1015   Curl_safefree(buf);
1016   Curl_safefree(pem_ptr);
1017   fclose(fp);
1018 
1019   return result;
1020 }
1021 
1022 /*
1023  * Check whether the SSL backend supports the status_request extension.
1024  */
Curl_ssl_cert_status_request(void)1025 bool Curl_ssl_cert_status_request(void)
1026 {
1027   return Curl_ssl->cert_status_request();
1028 }
1029 
1030 /*
1031  * Check whether the SSL backend supports false start.
1032  */
Curl_ssl_false_start(struct Curl_easy * data)1033 bool Curl_ssl_false_start(struct Curl_easy *data)
1034 {
1035   (void)data;
1036   return Curl_ssl->false_start();
1037 }
1038 
1039 /*
1040  * Default implementations for unsupported functions.
1041  */
1042 
Curl_none_init(void)1043 int Curl_none_init(void)
1044 {
1045   return 1;
1046 }
1047 
Curl_none_cleanup(void)1048 void Curl_none_cleanup(void)
1049 { }
1050 
Curl_none_shutdown(struct Curl_cfilter * cf UNUSED_PARAM,struct Curl_easy * data UNUSED_PARAM)1051 int Curl_none_shutdown(struct Curl_cfilter *cf UNUSED_PARAM,
1052                        struct Curl_easy *data UNUSED_PARAM)
1053 {
1054   (void)data;
1055   (void)cf;
1056   return 0;
1057 }
1058 
Curl_none_check_cxn(struct Curl_cfilter * cf,struct Curl_easy * data)1059 int Curl_none_check_cxn(struct Curl_cfilter *cf, struct Curl_easy *data)
1060 {
1061   (void)cf;
1062   (void)data;
1063   return -1;
1064 }
1065 
Curl_none_random(struct Curl_easy * data UNUSED_PARAM,unsigned char * entropy UNUSED_PARAM,size_t length UNUSED_PARAM)1066 CURLcode Curl_none_random(struct Curl_easy *data UNUSED_PARAM,
1067                           unsigned char *entropy UNUSED_PARAM,
1068                           size_t length UNUSED_PARAM)
1069 {
1070   (void)data;
1071   (void)entropy;
1072   (void)length;
1073   return CURLE_NOT_BUILT_IN;
1074 }
1075 
Curl_none_close_all(struct Curl_easy * data UNUSED_PARAM)1076 void Curl_none_close_all(struct Curl_easy *data UNUSED_PARAM)
1077 {
1078   (void)data;
1079 }
1080 
Curl_none_session_free(void * ptr UNUSED_PARAM)1081 void Curl_none_session_free(void *ptr UNUSED_PARAM)
1082 {
1083   (void)ptr;
1084 }
1085 
Curl_none_data_pending(struct Curl_cfilter * cf UNUSED_PARAM,const struct Curl_easy * data UNUSED_PARAM)1086 bool Curl_none_data_pending(struct Curl_cfilter *cf UNUSED_PARAM,
1087                             const struct Curl_easy *data UNUSED_PARAM)
1088 {
1089   (void)cf;
1090   (void)data;
1091   return 0;
1092 }
1093 
Curl_none_cert_status_request(void)1094 bool Curl_none_cert_status_request(void)
1095 {
1096   return FALSE;
1097 }
1098 
Curl_none_set_engine(struct Curl_easy * data UNUSED_PARAM,const char * engine UNUSED_PARAM)1099 CURLcode Curl_none_set_engine(struct Curl_easy *data UNUSED_PARAM,
1100                               const char *engine UNUSED_PARAM)
1101 {
1102   (void)data;
1103   (void)engine;
1104   return CURLE_NOT_BUILT_IN;
1105 }
1106 
Curl_none_set_engine_default(struct Curl_easy * data UNUSED_PARAM)1107 CURLcode Curl_none_set_engine_default(struct Curl_easy *data UNUSED_PARAM)
1108 {
1109   (void)data;
1110   return CURLE_NOT_BUILT_IN;
1111 }
1112 
Curl_none_engines_list(struct Curl_easy * data UNUSED_PARAM)1113 struct curl_slist *Curl_none_engines_list(struct Curl_easy *data UNUSED_PARAM)
1114 {
1115   (void)data;
1116   return (struct curl_slist *)NULL;
1117 }
1118 
Curl_none_false_start(void)1119 bool Curl_none_false_start(void)
1120 {
1121   return FALSE;
1122 }
1123 
multissl_init(void)1124 static int multissl_init(void)
1125 {
1126   if(multissl_setup(NULL))
1127     return 1;
1128   return Curl_ssl->init();
1129 }
1130 
multissl_connect(struct Curl_cfilter * cf,struct Curl_easy * data)1131 static CURLcode multissl_connect(struct Curl_cfilter *cf,
1132                                  struct Curl_easy *data)
1133 {
1134   if(multissl_setup(NULL))
1135     return CURLE_FAILED_INIT;
1136   return Curl_ssl->connect_blocking(cf, data);
1137 }
1138 
multissl_connect_nonblocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)1139 static CURLcode multissl_connect_nonblocking(struct Curl_cfilter *cf,
1140                                              struct Curl_easy *data,
1141                                              bool *done)
1142 {
1143   if(multissl_setup(NULL))
1144     return CURLE_FAILED_INIT;
1145   return Curl_ssl->connect_nonblocking(cf, data, done);
1146 }
1147 
multissl_get_select_socks(struct Curl_cfilter * cf,struct Curl_easy * data,curl_socket_t * socks)1148 static int multissl_get_select_socks(struct Curl_cfilter *cf,
1149                                      struct Curl_easy *data,
1150                                      curl_socket_t *socks)
1151 {
1152   if(multissl_setup(NULL))
1153     return 0;
1154   return Curl_ssl->get_select_socks(cf, data, socks);
1155 }
1156 
multissl_get_internals(struct ssl_connect_data * connssl,CURLINFO info)1157 static void *multissl_get_internals(struct ssl_connect_data *connssl,
1158                                     CURLINFO info)
1159 {
1160   if(multissl_setup(NULL))
1161     return NULL;
1162   return Curl_ssl->get_internals(connssl, info);
1163 }
1164 
multissl_close(struct Curl_cfilter * cf,struct Curl_easy * data)1165 static void multissl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1166 {
1167   if(multissl_setup(NULL))
1168     return;
1169   Curl_ssl->close(cf, data);
1170 }
1171 
multissl_recv_plain(struct Curl_cfilter * cf,struct Curl_easy * data,char * buf,size_t len,CURLcode * code)1172 static ssize_t multissl_recv_plain(struct Curl_cfilter *cf,
1173                                    struct Curl_easy *data,
1174                                    char *buf, size_t len, CURLcode *code)
1175 {
1176   if(multissl_setup(NULL))
1177     return CURLE_FAILED_INIT;
1178   return Curl_ssl->recv_plain(cf, data, buf, len, code);
1179 }
1180 
multissl_send_plain(struct Curl_cfilter * cf,struct Curl_easy * data,const void * mem,size_t len,CURLcode * code)1181 static ssize_t multissl_send_plain(struct Curl_cfilter *cf,
1182                                    struct Curl_easy *data,
1183                                    const void *mem, size_t len,
1184                                    CURLcode *code)
1185 {
1186   if(multissl_setup(NULL))
1187     return CURLE_FAILED_INIT;
1188   return Curl_ssl->send_plain(cf, data, mem, len, code);
1189 }
1190 
1191 static const struct Curl_ssl Curl_ssl_multi = {
1192   { CURLSSLBACKEND_NONE, "multi" },  /* info */
1193   0, /* supports nothing */
1194   (size_t)-1, /* something insanely large to be on the safe side */
1195 
1196   multissl_init,                     /* init */
1197   Curl_none_cleanup,                 /* cleanup */
1198   multissl_version,                  /* version */
1199   Curl_none_check_cxn,               /* check_cxn */
1200   Curl_none_shutdown,                /* shutdown */
1201   Curl_none_data_pending,            /* data_pending */
1202   Curl_none_random,                  /* random */
1203   Curl_none_cert_status_request,     /* cert_status_request */
1204   multissl_connect,                  /* connect */
1205   multissl_connect_nonblocking,      /* connect_nonblocking */
1206   multissl_get_select_socks,         /* getsock */
1207   multissl_get_internals,            /* get_internals */
1208   multissl_close,                    /* close_one */
1209   Curl_none_close_all,               /* close_all */
1210   Curl_none_session_free,            /* session_free */
1211   Curl_none_set_engine,              /* set_engine */
1212   Curl_none_set_engine_default,      /* set_engine_default */
1213   Curl_none_engines_list,            /* engines_list */
1214   Curl_none_false_start,             /* false_start */
1215   NULL,                              /* sha256sum */
1216   NULL,                              /* associate_connection */
1217   NULL,                              /* disassociate_connection */
1218   NULL,                              /* free_multi_ssl_backend_data */
1219   multissl_recv_plain,               /* recv decrypted data */
1220   multissl_send_plain,               /* send data to encrypt */
1221 };
1222 
1223 const struct Curl_ssl *Curl_ssl =
1224 #if defined(CURL_WITH_MULTI_SSL)
1225   &Curl_ssl_multi;
1226 #elif defined(USE_WOLFSSL)
1227   &Curl_ssl_wolfssl;
1228 #elif defined(USE_SECTRANSP)
1229   &Curl_ssl_sectransp;
1230 #elif defined(USE_GNUTLS)
1231   &Curl_ssl_gnutls;
1232 #elif defined(USE_GSKIT)
1233   &Curl_ssl_gskit;
1234 #elif defined(USE_MBEDTLS)
1235   &Curl_ssl_mbedtls;
1236 #elif defined(USE_NSS)
1237   &Curl_ssl_nss;
1238 #elif defined(USE_RUSTLS)
1239   &Curl_ssl_rustls;
1240 #elif defined(USE_OPENSSL)
1241   &Curl_ssl_openssl;
1242 #elif defined(USE_SCHANNEL)
1243   &Curl_ssl_schannel;
1244 #elif defined(USE_BEARSSL)
1245   &Curl_ssl_bearssl;
1246 #else
1247 #error "Missing struct Curl_ssl for selected SSL backend"
1248 #endif
1249 
1250 static const struct Curl_ssl *available_backends[] = {
1251 #if defined(USE_WOLFSSL)
1252   &Curl_ssl_wolfssl,
1253 #endif
1254 #if defined(USE_SECTRANSP)
1255   &Curl_ssl_sectransp,
1256 #endif
1257 #if defined(USE_GNUTLS)
1258   &Curl_ssl_gnutls,
1259 #endif
1260 #if defined(USE_GSKIT)
1261   &Curl_ssl_gskit,
1262 #endif
1263 #if defined(USE_MBEDTLS)
1264   &Curl_ssl_mbedtls,
1265 #endif
1266 #if defined(USE_NSS)
1267   &Curl_ssl_nss,
1268 #endif
1269 #if defined(USE_OPENSSL)
1270   &Curl_ssl_openssl,
1271 #endif
1272 #if defined(USE_SCHANNEL)
1273   &Curl_ssl_schannel,
1274 #endif
1275 #if defined(USE_BEARSSL)
1276   &Curl_ssl_bearssl,
1277 #endif
1278 #if defined(USE_RUSTLS)
1279   &Curl_ssl_rustls,
1280 #endif
1281   NULL
1282 };
1283 
multissl_version(char * buffer,size_t size)1284 static size_t multissl_version(char *buffer, size_t size)
1285 {
1286   static const struct Curl_ssl *selected;
1287   static char backends[200];
1288   static size_t backends_len;
1289   const struct Curl_ssl *current;
1290 
1291   current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl;
1292 
1293   if(current != selected) {
1294     char *p = backends;
1295     char *end = backends + sizeof(backends);
1296     int i;
1297 
1298     selected = current;
1299 
1300     backends[0] = '\0';
1301 
1302     for(i = 0; available_backends[i]; ++i) {
1303       char vb[200];
1304       bool paren = (selected != available_backends[i]);
1305 
1306       if(available_backends[i]->version(vb, sizeof(vb))) {
1307         p += msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""),
1308                        (paren ? "(" : ""), vb, (paren ? ")" : ""));
1309       }
1310     }
1311 
1312     backends_len = p - backends;
1313   }
1314 
1315   if(!size)
1316     return 0;
1317 
1318   if(size <= backends_len) {
1319     strncpy(buffer, backends, size - 1);
1320     buffer[size - 1] = '\0';
1321     return size - 1;
1322   }
1323 
1324   strcpy(buffer, backends);
1325   return backends_len;
1326 }
1327 
multissl_setup(const struct Curl_ssl * backend)1328 static int multissl_setup(const struct Curl_ssl *backend)
1329 {
1330   const char *env;
1331   char *env_tmp;
1332 
1333   if(Curl_ssl != &Curl_ssl_multi)
1334     return 1;
1335 
1336   if(backend) {
1337     Curl_ssl = backend;
1338     return 0;
1339   }
1340 
1341   if(!available_backends[0])
1342     return 1;
1343 
1344   env = env_tmp = curl_getenv("CURL_SSL_BACKEND");
1345 #ifdef CURL_DEFAULT_SSL_BACKEND
1346   if(!env)
1347     env = CURL_DEFAULT_SSL_BACKEND;
1348 #endif
1349   if(env) {
1350     int i;
1351     for(i = 0; available_backends[i]; i++) {
1352       if(strcasecompare(env, available_backends[i]->info.name)) {
1353         Curl_ssl = available_backends[i];
1354         free(env_tmp);
1355         return 0;
1356       }
1357     }
1358   }
1359 
1360   /* Fall back to first available backend */
1361   Curl_ssl = available_backends[0];
1362   free(env_tmp);
1363   return 0;
1364 }
1365 
1366 /* This function is used to select the SSL backend to use. It is called by
1367    curl_global_sslset (easy.c) which uses the global init lock. */
Curl_init_sslset_nolock(curl_sslbackend id,const char * name,const curl_ssl_backend *** avail)1368 CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
1369                                    const curl_ssl_backend ***avail)
1370 {
1371   int i;
1372 
1373   if(avail)
1374     *avail = (const curl_ssl_backend **)&available_backends;
1375 
1376   if(Curl_ssl != &Curl_ssl_multi)
1377     return id == Curl_ssl->info.id ||
1378            (name && strcasecompare(name, Curl_ssl->info.name)) ?
1379            CURLSSLSET_OK :
1380 #if defined(CURL_WITH_MULTI_SSL)
1381            CURLSSLSET_TOO_LATE;
1382 #else
1383            CURLSSLSET_UNKNOWN_BACKEND;
1384 #endif
1385 
1386   for(i = 0; available_backends[i]; i++) {
1387     if(available_backends[i]->info.id == id ||
1388        (name && strcasecompare(available_backends[i]->info.name, name))) {
1389       multissl_setup(available_backends[i]);
1390       return CURLSSLSET_OK;
1391     }
1392   }
1393 
1394   return CURLSSLSET_UNKNOWN_BACKEND;
1395 }
1396 
1397 #else /* USE_SSL */
Curl_init_sslset_nolock(curl_sslbackend id,const char * name,const curl_ssl_backend *** avail)1398 CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
1399                                    const curl_ssl_backend ***avail)
1400 {
1401   (void)id;
1402   (void)name;
1403   (void)avail;
1404   return CURLSSLSET_NO_BACKENDS;
1405 }
1406 
1407 #endif /* !USE_SSL */
1408 
1409 #ifdef USE_SSL
1410 
free_hostname(struct ssl_connect_data * connssl)1411 static void free_hostname(struct ssl_connect_data *connssl)
1412 {
1413   if(connssl->dispname != connssl->hostname)
1414     free(connssl->dispname);
1415   free(connssl->hostname);
1416   connssl->hostname = connssl->dispname = NULL;
1417 }
1418 
cf_close(struct Curl_cfilter * cf,struct Curl_easy * data)1419 static void cf_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1420 {
1421   struct ssl_connect_data *connssl = cf->ctx;
1422   if(connssl) {
1423     Curl_ssl->close(cf, data);
1424     connssl->state = ssl_connection_none;
1425     free_hostname(connssl);
1426   }
1427   cf->connected = FALSE;
1428 }
1429 
reinit_hostname(struct Curl_cfilter * cf)1430 static CURLcode reinit_hostname(struct Curl_cfilter *cf)
1431 {
1432   struct ssl_connect_data *connssl = cf->ctx;
1433   const char *ehostname, *edispname;
1434   int eport;
1435 
1436   /* We need the hostname for SNI negotiation. Once handshaked, this
1437    * remains the SNI hostname for the TLS connection. But when the
1438    * connection is reused, the settings in cf->conn might change.
1439    * So we keep a copy of the hostname we use for SNI.
1440    */
1441 #ifndef CURL_DISABLE_PROXY
1442   if(Curl_ssl_cf_is_proxy(cf)) {
1443     ehostname = cf->conn->http_proxy.host.name;
1444     edispname = cf->conn->http_proxy.host.dispname;
1445     eport = cf->conn->http_proxy.port;
1446   }
1447   else
1448 #endif
1449   {
1450     ehostname = cf->conn->host.name;
1451     edispname = cf->conn->host.dispname;
1452     eport = cf->conn->remote_port;
1453   }
1454 
1455   /* change if ehostname changed */
1456   if(ehostname && (!connssl->hostname
1457                    || strcmp(ehostname, connssl->hostname))) {
1458     free_hostname(connssl);
1459     connssl->hostname = strdup(ehostname);
1460     if(!connssl->hostname) {
1461       free_hostname(connssl);
1462       return CURLE_OUT_OF_MEMORY;
1463     }
1464     if(!edispname || !strcmp(ehostname, edispname))
1465       connssl->dispname = connssl->hostname;
1466     else {
1467       connssl->dispname = strdup(edispname);
1468       if(!connssl->dispname) {
1469         free_hostname(connssl);
1470         return CURLE_OUT_OF_MEMORY;
1471       }
1472     }
1473   }
1474   connssl->port = eport;
1475   return CURLE_OK;
1476 }
1477 
ssl_cf_destroy(struct Curl_cfilter * cf,struct Curl_easy * data)1478 static void ssl_cf_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
1479 {
1480   struct cf_call_data save;
1481 
1482   CF_DATA_SAVE(save, cf, data);
1483   cf_close(cf, data);
1484   CF_DATA_RESTORE(cf, save);
1485   cf_ctx_free(cf->ctx);
1486   cf->ctx = NULL;
1487 }
1488 
ssl_cf_close(struct Curl_cfilter * cf,struct Curl_easy * data)1489 static void ssl_cf_close(struct Curl_cfilter *cf,
1490                          struct Curl_easy *data)
1491 {
1492   struct cf_call_data save;
1493 
1494   CF_DATA_SAVE(save, cf, data);
1495   cf_close(cf, data);
1496   cf->next->cft->close(cf->next, data);
1497   CF_DATA_RESTORE(cf, save);
1498 }
1499 
ssl_cf_connect(struct Curl_cfilter * cf,struct Curl_easy * data,bool blocking,bool * done)1500 static CURLcode ssl_cf_connect(struct Curl_cfilter *cf,
1501                                struct Curl_easy *data,
1502                                bool blocking, bool *done)
1503 {
1504   struct ssl_connect_data *connssl = cf->ctx;
1505   struct cf_call_data save;
1506   CURLcode result;
1507 
1508   if(cf->connected) {
1509     *done = TRUE;
1510     return CURLE_OK;
1511   }
1512 
1513   CF_DATA_SAVE(save, cf, data);
1514   (void)connssl;
1515   DEBUGASSERT(data->conn);
1516   DEBUGASSERT(data->conn == cf->conn);
1517   DEBUGASSERT(connssl);
1518   DEBUGASSERT(cf->conn->host.name);
1519 
1520   result = cf->next->cft->connect(cf->next, data, blocking, done);
1521   if(result || !*done)
1522     goto out;
1523 
1524   *done = FALSE;
1525   result = reinit_hostname(cf);
1526   if(result)
1527     goto out;
1528 
1529   if(blocking) {
1530     result = ssl_connect(cf, data);
1531     *done = (result == CURLE_OK);
1532   }
1533   else {
1534     result = ssl_connect_nonblocking(cf, data, done);
1535   }
1536 
1537   if(!result && *done) {
1538     cf->connected = TRUE;
1539     connssl->handshake_done = Curl_now();
1540     DEBUGASSERT(connssl->state == ssl_connection_complete);
1541   }
1542 out:
1543   CF_DATA_RESTORE(cf, save);
1544   return result;
1545 }
1546 
ssl_cf_data_pending(struct Curl_cfilter * cf,const struct Curl_easy * data)1547 static bool ssl_cf_data_pending(struct Curl_cfilter *cf,
1548                                 const struct Curl_easy *data)
1549 {
1550   struct cf_call_data save;
1551   bool result;
1552 
1553   CF_DATA_SAVE(save, cf, data);
1554   if(Curl_ssl->data_pending(cf, data))
1555     result = TRUE;
1556   else
1557     result = cf->next->cft->has_data_pending(cf->next, data);
1558   CF_DATA_RESTORE(cf, save);
1559   return result;
1560 }
1561 
ssl_cf_send(struct Curl_cfilter * cf,struct Curl_easy * data,const void * buf,size_t len,CURLcode * err)1562 static ssize_t ssl_cf_send(struct Curl_cfilter *cf,
1563                            struct Curl_easy *data, const void *buf, size_t len,
1564                            CURLcode *err)
1565 {
1566   struct cf_call_data save;
1567   ssize_t nwritten;
1568 
1569   CF_DATA_SAVE(save, cf, data);
1570   *err = CURLE_OK;
1571   nwritten = Curl_ssl->send_plain(cf, data, buf, len, err);
1572   CF_DATA_RESTORE(cf, save);
1573   return nwritten;
1574 }
1575 
ssl_cf_recv(struct Curl_cfilter * cf,struct Curl_easy * data,char * buf,size_t len,CURLcode * err)1576 static ssize_t ssl_cf_recv(struct Curl_cfilter *cf,
1577                            struct Curl_easy *data, char *buf, size_t len,
1578                            CURLcode *err)
1579 {
1580   struct cf_call_data save;
1581   ssize_t nread;
1582 
1583   CF_DATA_SAVE(save, cf, data);
1584   *err = CURLE_OK;
1585   nread = Curl_ssl->recv_plain(cf, data, buf, len, err);
1586   CF_DATA_RESTORE(cf, save);
1587   return nread;
1588 }
1589 
ssl_cf_get_select_socks(struct Curl_cfilter * cf,struct Curl_easy * data,curl_socket_t * socks)1590 static int ssl_cf_get_select_socks(struct Curl_cfilter *cf,
1591                                    struct Curl_easy *data,
1592                                    curl_socket_t *socks)
1593 {
1594   struct cf_call_data save;
1595   int result;
1596 
1597   CF_DATA_SAVE(save, cf, data);
1598   result = Curl_ssl->get_select_socks(cf, data, socks);
1599   CF_DATA_RESTORE(cf, save);
1600   return result;
1601 }
1602 
ssl_cf_cntrl(struct Curl_cfilter * cf,struct Curl_easy * data,int event,int arg1,void * arg2)1603 static CURLcode ssl_cf_cntrl(struct Curl_cfilter *cf,
1604                              struct Curl_easy *data,
1605                              int event, int arg1, void *arg2)
1606 {
1607   struct cf_call_data save;
1608 
1609   (void)arg1;
1610   (void)arg2;
1611   switch(event) {
1612   case CF_CTRL_DATA_ATTACH:
1613     if(Curl_ssl->attach_data) {
1614       CF_DATA_SAVE(save, cf, data);
1615       Curl_ssl->attach_data(cf, data);
1616       CF_DATA_RESTORE(cf, save);
1617     }
1618     break;
1619   case CF_CTRL_DATA_DETACH:
1620     if(Curl_ssl->detach_data) {
1621       CF_DATA_SAVE(save, cf, data);
1622       Curl_ssl->detach_data(cf, data);
1623       CF_DATA_RESTORE(cf, save);
1624     }
1625     break;
1626   default:
1627     break;
1628   }
1629   return CURLE_OK;
1630 }
1631 
ssl_cf_query(struct Curl_cfilter * cf,struct Curl_easy * data,int query,int * pres1,void * pres2)1632 static CURLcode ssl_cf_query(struct Curl_cfilter *cf,
1633                              struct Curl_easy *data,
1634                              int query, int *pres1, void *pres2)
1635 {
1636   struct ssl_connect_data *connssl = cf->ctx;
1637 
1638   switch(query) {
1639   case CF_QUERY_TIMER_APPCONNECT: {
1640     struct curltime *when = pres2;
1641     if(cf->connected && !Curl_ssl_cf_is_proxy(cf))
1642       *when = connssl->handshake_done;
1643     return CURLE_OK;
1644   }
1645   default:
1646     break;
1647   }
1648   return cf->next?
1649     cf->next->cft->query(cf->next, data, query, pres1, pres2) :
1650     CURLE_UNKNOWN_OPTION;
1651 }
1652 
cf_ssl_is_alive(struct Curl_cfilter * cf,struct Curl_easy * data,bool * input_pending)1653 static bool cf_ssl_is_alive(struct Curl_cfilter *cf, struct Curl_easy *data,
1654                             bool *input_pending)
1655 {
1656   struct cf_call_data save;
1657   int result;
1658   /*
1659    * This function tries to determine connection status.
1660    *
1661    * Return codes:
1662    *     1 means the connection is still in place
1663    *     0 means the connection has been closed
1664    *    -1 means the connection status is unknown
1665    */
1666   CF_DATA_SAVE(save, cf, data);
1667   result = Curl_ssl->check_cxn(cf, data);
1668   CF_DATA_RESTORE(cf, save);
1669   if(result > 0) {
1670     *input_pending = TRUE;
1671     return TRUE;
1672   }
1673   if(result == 0) {
1674     *input_pending = FALSE;
1675     return FALSE;
1676   }
1677   /* ssl backend does not know */
1678   return cf->next?
1679     cf->next->cft->is_alive(cf->next, data, input_pending) :
1680     FALSE; /* pessimistic in absence of data */
1681 }
1682 
1683 struct Curl_cftype Curl_cft_ssl = {
1684   "SSL",
1685   CF_TYPE_SSL,
1686   CURL_LOG_DEFAULT,
1687   ssl_cf_destroy,
1688   ssl_cf_connect,
1689   ssl_cf_close,
1690   Curl_cf_def_get_host,
1691   ssl_cf_get_select_socks,
1692   ssl_cf_data_pending,
1693   ssl_cf_send,
1694   ssl_cf_recv,
1695   ssl_cf_cntrl,
1696   cf_ssl_is_alive,
1697   Curl_cf_def_conn_keep_alive,
1698   ssl_cf_query,
1699 };
1700 
1701 struct Curl_cftype Curl_cft_ssl_proxy = {
1702   "SSL-PROXY",
1703   CF_TYPE_SSL,
1704   CURL_LOG_DEFAULT,
1705   ssl_cf_destroy,
1706   ssl_cf_connect,
1707   ssl_cf_close,
1708   Curl_cf_def_get_host,
1709   ssl_cf_get_select_socks,
1710   ssl_cf_data_pending,
1711   ssl_cf_send,
1712   ssl_cf_recv,
1713   ssl_cf_cntrl,
1714   cf_ssl_is_alive,
1715   Curl_cf_def_conn_keep_alive,
1716   Curl_cf_def_query,
1717 };
1718 
cf_ssl_create(struct Curl_cfilter ** pcf,struct Curl_easy * data,struct connectdata * conn)1719 static CURLcode cf_ssl_create(struct Curl_cfilter **pcf,
1720                               struct Curl_easy *data,
1721                               struct connectdata *conn)
1722 {
1723   struct Curl_cfilter *cf = NULL;
1724   struct ssl_connect_data *ctx;
1725   CURLcode result;
1726 
1727   DEBUGASSERT(data->conn);
1728 
1729   ctx = cf_ctx_new(data, Curl_alpn_get_spec(data, conn));
1730   if(!ctx) {
1731     result = CURLE_OUT_OF_MEMORY;
1732     goto out;
1733   }
1734 
1735   result = Curl_cf_create(&cf, &Curl_cft_ssl, ctx);
1736 
1737 out:
1738   if(result)
1739     cf_ctx_free(ctx);
1740   *pcf = result? NULL : cf;
1741   return result;
1742 }
1743 
Curl_ssl_cfilter_add(struct Curl_easy * data,struct connectdata * conn,int sockindex)1744 CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data,
1745                               struct connectdata *conn,
1746                               int sockindex)
1747 {
1748   struct Curl_cfilter *cf;
1749   CURLcode result;
1750 
1751   result = cf_ssl_create(&cf, data, conn);
1752   if(!result)
1753     Curl_conn_cf_add(data, conn, sockindex, cf);
1754   return result;
1755 }
1756 
Curl_cf_ssl_insert_after(struct Curl_cfilter * cf_at,struct Curl_easy * data)1757 CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at,
1758                                   struct Curl_easy *data)
1759 {
1760   struct Curl_cfilter *cf;
1761   CURLcode result;
1762 
1763   result = cf_ssl_create(&cf, data, cf_at->conn);
1764   if(!result)
1765     Curl_conn_cf_insert_after(cf_at, cf);
1766   return result;
1767 }
1768 
1769 #ifndef CURL_DISABLE_PROXY
cf_ssl_proxy_create(struct Curl_cfilter ** pcf,struct Curl_easy * data,struct connectdata * conn)1770 static CURLcode cf_ssl_proxy_create(struct Curl_cfilter **pcf,
1771                                     struct Curl_easy *data,
1772                                     struct connectdata *conn)
1773 {
1774   struct Curl_cfilter *cf = NULL;
1775   struct ssl_connect_data *ctx;
1776   CURLcode result;
1777 
1778   ctx = cf_ctx_new(data, Curl_alpn_get_proxy_spec(data, conn));
1779   if(!ctx) {
1780     result = CURLE_OUT_OF_MEMORY;
1781     goto out;
1782   }
1783   result = Curl_cf_create(&cf, &Curl_cft_ssl_proxy, ctx);
1784 
1785 out:
1786   if(result)
1787     cf_ctx_free(ctx);
1788   *pcf = result? NULL : cf;
1789   return result;
1790 }
1791 
Curl_ssl_cfilter_proxy_add(struct Curl_easy * data,struct connectdata * conn,int sockindex)1792 CURLcode Curl_ssl_cfilter_proxy_add(struct Curl_easy *data,
1793                                     struct connectdata *conn,
1794                                     int sockindex)
1795 {
1796   struct Curl_cfilter *cf;
1797   CURLcode result;
1798 
1799   result = cf_ssl_proxy_create(&cf, data, conn);
1800   if(!result)
1801     Curl_conn_cf_add(data, conn, sockindex, cf);
1802   return result;
1803 }
1804 
Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter * cf_at,struct Curl_easy * data)1805 CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at,
1806                                         struct Curl_easy *data)
1807 {
1808   struct Curl_cfilter *cf;
1809   CURLcode result;
1810 
1811   result = cf_ssl_proxy_create(&cf, data, cf_at->conn);
1812   if(!result)
1813     Curl_conn_cf_insert_after(cf_at, cf);
1814   return result;
1815 }
1816 
1817 #endif /* !CURL_DISABLE_PROXY */
1818 
Curl_ssl_supports(struct Curl_easy * data,int option)1819 bool Curl_ssl_supports(struct Curl_easy *data, int option)
1820 {
1821   (void)data;
1822   return (Curl_ssl->supports & option)? TRUE : FALSE;
1823 }
1824 
Curl_ssl_get_internals(struct Curl_easy * data,int sockindex,CURLINFO info,int n)1825 void *Curl_ssl_get_internals(struct Curl_easy *data, int sockindex,
1826                              CURLINFO info, int n)
1827 {
1828   void *result = NULL;
1829   (void)n;
1830   if(data->conn) {
1831     struct Curl_cfilter *cf;
1832     /* get first filter in chain, if any is present */
1833     cf = Curl_ssl_cf_get_ssl(data->conn->cfilter[sockindex]);
1834     if(cf) {
1835       struct cf_call_data save;
1836       CF_DATA_SAVE(save, cf, data);
1837       result = Curl_ssl->get_internals(cf->ctx, info);
1838       CF_DATA_RESTORE(cf, save);
1839     }
1840   }
1841   return result;
1842 }
1843 
Curl_ssl_cfilter_remove(struct Curl_easy * data,int sockindex)1844 CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data,
1845                                  int sockindex)
1846 {
1847   struct Curl_cfilter *cf = data->conn? data->conn->cfilter[sockindex] : NULL;
1848   CURLcode result = CURLE_OK;
1849 
1850   (void)data;
1851   for(; cf; cf = cf->next) {
1852     if(cf->cft == &Curl_cft_ssl) {
1853       if(Curl_ssl->shut_down(cf, data))
1854         result = CURLE_SSL_SHUTDOWN_FAILED;
1855       Curl_conn_cf_discard(cf, data);
1856       break;
1857     }
1858   }
1859   return result;
1860 }
1861 
get_ssl_cf_engaged(struct connectdata * conn,int sockindex)1862 static struct Curl_cfilter *get_ssl_cf_engaged(struct connectdata *conn,
1863                                                int sockindex)
1864 {
1865   struct Curl_cfilter *cf, *lowest_ssl_cf = NULL;
1866 
1867   for(cf = conn->cfilter[sockindex]; cf; cf = cf->next) {
1868     if(cf->cft == &Curl_cft_ssl || cf->cft == &Curl_cft_ssl_proxy) {
1869       lowest_ssl_cf = cf;
1870       if(cf->connected || (cf->next && cf->next->connected)) {
1871         /* connected or about to start */
1872         return cf;
1873       }
1874     }
1875   }
1876   return lowest_ssl_cf;
1877 }
1878 
Curl_ssl_cf_is_proxy(struct Curl_cfilter * cf)1879 bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf)
1880 {
1881   return (cf->cft == &Curl_cft_ssl_proxy);
1882 }
1883 
1884 struct ssl_config_data *
Curl_ssl_cf_get_config(struct Curl_cfilter * cf,struct Curl_easy * data)1885 Curl_ssl_cf_get_config(struct Curl_cfilter *cf, struct Curl_easy *data)
1886 {
1887 #ifdef CURL_DISABLE_PROXY
1888   (void)cf;
1889   return &data->set.ssl;
1890 #else
1891   return Curl_ssl_cf_is_proxy(cf)? &data->set.proxy_ssl : &data->set.ssl;
1892 #endif
1893 }
1894 
1895 struct ssl_config_data *
Curl_ssl_get_config(struct Curl_easy * data,int sockindex)1896 Curl_ssl_get_config(struct Curl_easy *data, int sockindex)
1897 {
1898   struct Curl_cfilter *cf;
1899 
1900   (void)data;
1901   DEBUGASSERT(data->conn);
1902   cf = get_ssl_cf_engaged(data->conn, sockindex);
1903   return cf? Curl_ssl_cf_get_config(cf, data) : &data->set.ssl;
1904 }
1905 
1906 struct ssl_primary_config *
Curl_ssl_cf_get_primary_config(struct Curl_cfilter * cf)1907 Curl_ssl_cf_get_primary_config(struct Curl_cfilter *cf)
1908 {
1909 #ifdef CURL_DISABLE_PROXY
1910   return &cf->conn->ssl_config;
1911 #else
1912   return Curl_ssl_cf_is_proxy(cf)?
1913     &cf->conn->proxy_ssl_config : &cf->conn->ssl_config;
1914 #endif
1915 }
1916 
1917 struct ssl_primary_config *
Curl_ssl_get_primary_config(struct Curl_easy * data,struct connectdata * conn,int sockindex)1918 Curl_ssl_get_primary_config(struct Curl_easy *data,
1919                             struct connectdata *conn,
1920                             int sockindex)
1921 {
1922   struct Curl_cfilter *cf;
1923 
1924   (void)data;
1925   DEBUGASSERT(conn);
1926   cf = get_ssl_cf_engaged(conn, sockindex);
1927   return cf? Curl_ssl_cf_get_primary_config(cf) : NULL;
1928 }
1929 
Curl_ssl_cf_get_ssl(struct Curl_cfilter * cf)1930 struct Curl_cfilter *Curl_ssl_cf_get_ssl(struct Curl_cfilter *cf)
1931 {
1932   for(; cf; cf = cf->next) {
1933     if(cf->cft == &Curl_cft_ssl || cf->cft == &Curl_cft_ssl_proxy)
1934       return cf;
1935   }
1936   return NULL;
1937 }
1938 
1939 static const struct alpn_spec ALPN_SPEC_H10 = {
1940   { ALPN_HTTP_1_0 }, 1
1941 };
1942 static const struct alpn_spec ALPN_SPEC_H11 = {
1943   { ALPN_HTTP_1_1 }, 1
1944 };
1945 #ifdef USE_HTTP2
1946 static const struct alpn_spec ALPN_SPEC_H2_H11 = {
1947   { ALPN_H2, ALPN_HTTP_1_1 }, 2
1948 };
1949 #endif
1950 
1951 const struct alpn_spec *
Curl_alpn_get_spec(struct Curl_easy * data,struct connectdata * conn)1952 Curl_alpn_get_spec(struct Curl_easy *data, struct connectdata *conn)
1953 {
1954   if(!conn->bits.tls_enable_alpn)
1955     return NULL;
1956   if(data->state.httpwant == CURL_HTTP_VERSION_1_0)
1957     return &ALPN_SPEC_H10;
1958 #ifdef USE_HTTP2
1959   if(data->state.httpwant >= CURL_HTTP_VERSION_2)
1960     return &ALPN_SPEC_H2_H11;
1961 #endif
1962   return &ALPN_SPEC_H11;
1963 }
1964 
1965 const struct alpn_spec *
Curl_alpn_get_proxy_spec(struct Curl_easy * data,struct connectdata * conn)1966 Curl_alpn_get_proxy_spec(struct Curl_easy *data, struct connectdata *conn)
1967 {
1968   if(!conn->bits.tls_enable_alpn)
1969     return NULL;
1970   if(data->state.httpwant == CURL_HTTP_VERSION_1_0)
1971     return &ALPN_SPEC_H10;
1972   return &ALPN_SPEC_H11;
1973 }
1974 
Curl_alpn_to_proto_buf(struct alpn_proto_buf * buf,const struct alpn_spec * spec)1975 CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf,
1976                                 const struct alpn_spec *spec)
1977 {
1978   size_t i, len;
1979   int off = 0;
1980   unsigned char blen;
1981 
1982   memset(buf, 0, sizeof(*buf));
1983   for(i = 0; spec && i < spec->count; ++i) {
1984     len = strlen(spec->entries[i]);
1985     if(len >= ALPN_NAME_MAX)
1986       return CURLE_FAILED_INIT;
1987     blen = (unsigned  char)len;
1988     if(off + blen + 1 >= (int)sizeof(buf->data))
1989       return CURLE_FAILED_INIT;
1990     buf->data[off++] = blen;
1991     memcpy(buf->data + off, spec->entries[i], blen);
1992     off += blen;
1993   }
1994   buf->len = off;
1995   return CURLE_OK;
1996 }
1997 
Curl_alpn_to_proto_str(struct alpn_proto_buf * buf,const struct alpn_spec * spec)1998 CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf,
1999                                 const struct alpn_spec *spec)
2000 {
2001   size_t i, len;
2002   size_t off = 0;
2003 
2004   memset(buf, 0, sizeof(*buf));
2005   for(i = 0; spec && i < spec->count; ++i) {
2006     len = strlen(spec->entries[i]);
2007     if(len >= ALPN_NAME_MAX)
2008       return CURLE_FAILED_INIT;
2009     if(off + len + 2 >= (int)sizeof(buf->data))
2010       return CURLE_FAILED_INIT;
2011     if(off)
2012       buf->data[off++] = ',';
2013     memcpy(buf->data + off, spec->entries[i], len);
2014     off += len;
2015   }
2016   buf->data[off] = '\0';
2017   buf->len = (int)off;
2018   return CURLE_OK;
2019 }
2020 
Curl_alpn_set_negotiated(struct Curl_cfilter * cf,struct Curl_easy * data,const unsigned char * proto,size_t proto_len)2021 CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf,
2022                                   struct Curl_easy *data,
2023                                   const unsigned char *proto,
2024                                   size_t proto_len)
2025 {
2026   int can_multi = 0;
2027 
2028   if(proto && proto_len) {
2029     if(proto_len == ALPN_HTTP_1_1_LENGTH &&
2030             !memcmp(ALPN_HTTP_1_1, proto, ALPN_HTTP_1_1_LENGTH)) {
2031       cf->conn->alpn = CURL_HTTP_VERSION_1_1;
2032     }
2033     else if(proto_len == ALPN_HTTP_1_0_LENGTH &&
2034             !memcmp(ALPN_HTTP_1_0, proto, ALPN_HTTP_1_0_LENGTH)) {
2035       cf->conn->alpn = CURL_HTTP_VERSION_1_0;
2036     }
2037 #ifdef USE_HTTP2
2038     else if(proto_len == ALPN_H2_LENGTH &&
2039             !memcmp(ALPN_H2, proto, ALPN_H2_LENGTH)) {
2040       cf->conn->alpn = CURL_HTTP_VERSION_2;
2041       can_multi = 1;
2042     }
2043 #endif
2044 #ifdef USE_HTTP3
2045     else if(proto_len == ALPN_H3_LENGTH &&
2046        !memcmp(ALPN_H3, proto, ALPN_H3_LENGTH)) {
2047       cf->conn->alpn = CURL_HTTP_VERSION_3;
2048       can_multi = 1;
2049     }
2050 #endif
2051     else {
2052       cf->conn->alpn = CURL_HTTP_VERSION_NONE;
2053       failf(data, "unsupported ALPN protocol: '%.*s'", (int)proto_len, proto);
2054       /* TODO: do we want to fail this? Previous code just ignored it and
2055        * some vtls backends even ignore the return code of this function. */
2056       /* return CURLE_NOT_BUILT_IN; */
2057       goto out;
2058     }
2059     infof(data, VTLS_INFOF_ALPN_ACCEPTED_LEN_1STR, (int)proto_len, proto);
2060   }
2061   else {
2062     cf->conn->alpn = CURL_HTTP_VERSION_NONE;
2063     infof(data, VTLS_INFOF_NO_ALPN);
2064   }
2065 
2066 out:
2067   Curl_multiuse_state(data, can_multi? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
2068   return CURLE_OK;
2069 }
2070 
2071 #endif /* USE_SSL */
2072