xref: /curl/lib/vtls/vtls.c (revision fa0ccd9f)
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 "vtls_scache.h"
59 
60 #include "openssl.h"        /* OpenSSL versions */
61 #include "gtls.h"           /* GnuTLS versions */
62 #include "wolfssl.h"        /* wolfSSL versions */
63 #include "schannel.h"       /* Schannel SSPI version */
64 #include "sectransp.h"      /* Secure Transport (Darwin) version */
65 #include "mbedtls.h"        /* mbedTLS versions */
66 #include "bearssl.h"        /* BearSSL versions */
67 #include "rustls.h"         /* Rustls versions */
68 
69 #include "slist.h"
70 #include "sendf.h"
71 #include "strcase.h"
72 #include "url.h"
73 #include "progress.h"
74 #include "share.h"
75 #include "multiif.h"
76 #include "timeval.h"
77 #include "curl_md5.h"
78 #include "curl_sha256.h"
79 #include "warnless.h"
80 #include "curl_base64.h"
81 #include "curl_printf.h"
82 #include "inet_pton.h"
83 #include "connect.h"
84 #include "select.h"
85 #include "strdup.h"
86 #include "rand.h"
87 
88 /* The last #include files should be: */
89 #include "curl_memory.h"
90 #include "memdebug.h"
91 
92 
93 #define CLONE_STRING(var)                    \
94   do {                                       \
95     if(source->var) {                        \
96       dest->var = strdup(source->var);       \
97       if(!dest->var)                         \
98         return FALSE;                        \
99     }                                        \
100     else                                     \
101       dest->var = NULL;                      \
102   } while(0)
103 
104 #define CLONE_BLOB(var)                        \
105   do {                                         \
106     if(blobdup(&dest->var, source->var))       \
107       return FALSE;                            \
108   } while(0)
109 
blobdup(struct curl_blob ** dest,struct curl_blob * src)110 static CURLcode blobdup(struct curl_blob **dest,
111                         struct curl_blob *src)
112 {
113   DEBUGASSERT(dest);
114   DEBUGASSERT(!*dest);
115   if(src) {
116     /* only if there is data to dupe! */
117     struct curl_blob *d;
118     d = malloc(sizeof(struct curl_blob) + src->len);
119     if(!d)
120       return CURLE_OUT_OF_MEMORY;
121     d->len = src->len;
122     /* Always duplicate because the connection may survive longer than the
123        handle that passed in the blob. */
124     d->flags = CURL_BLOB_COPY;
125     d->data = (void *)((char *)d + sizeof(struct curl_blob));
126     memcpy(d->data, src->data, src->len);
127     *dest = d;
128   }
129   return CURLE_OK;
130 }
131 
132 /* returns TRUE if the blobs are identical */
blobcmp(struct curl_blob * first,struct curl_blob * second)133 static bool blobcmp(struct curl_blob *first, struct curl_blob *second)
134 {
135   if(!first && !second) /* both are NULL */
136     return TRUE;
137   if(!first || !second) /* one is NULL */
138     return FALSE;
139   if(first->len != second->len) /* different sizes */
140     return FALSE;
141   return !memcmp(first->data, second->data, first->len); /* same data */
142 }
143 
144 #ifdef USE_SSL
145 static const struct alpn_spec ALPN_SPEC_H11 = {
146   { ALPN_HTTP_1_1 }, 1
147 };
148 #ifdef USE_HTTP2
149 static const struct alpn_spec ALPN_SPEC_H2 = {
150   { ALPN_H2 }, 1
151 };
152 static const struct alpn_spec ALPN_SPEC_H2_H11 = {
153   { ALPN_H2, ALPN_HTTP_1_1 }, 2
154 };
155 #endif
156 
alpn_get_spec(int httpwant,bool use_alpn)157 static const struct alpn_spec *alpn_get_spec(int httpwant, bool use_alpn)
158 {
159   if(!use_alpn)
160     return NULL;
161 #ifdef USE_HTTP2
162   if(httpwant == CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE)
163     return &ALPN_SPEC_H2;
164   if(httpwant >= CURL_HTTP_VERSION_2)
165     return &ALPN_SPEC_H2_H11;
166 #else
167   (void)httpwant;
168 #endif
169   /* Use the ALPN protocol "http/1.1" for HTTP/1.x.
170      Avoid "http/1.0" because some servers do not support it. */
171   return &ALPN_SPEC_H11;
172 }
173 #endif /* USE_SSL */
174 
175 
Curl_ssl_easy_config_init(struct Curl_easy * data)176 void Curl_ssl_easy_config_init(struct Curl_easy *data)
177 {
178   /*
179    * libcurl 7.10 introduced SSL verification *by default*! This needs to be
180    * switched off unless wanted.
181    */
182   data->set.ssl.primary.verifypeer = TRUE;
183   data->set.ssl.primary.verifyhost = TRUE;
184   data->set.ssl.primary.cache_session = TRUE; /* caching by default */
185 #ifndef CURL_DISABLE_PROXY
186   data->set.proxy_ssl = data->set.ssl;
187 #endif
188 }
189 
190 static bool
match_ssl_primary_config(struct Curl_easy * data,struct ssl_primary_config * c1,struct ssl_primary_config * c2)191 match_ssl_primary_config(struct Curl_easy *data,
192                          struct ssl_primary_config *c1,
193                          struct ssl_primary_config *c2)
194 {
195   (void)data;
196   if((c1->version == c2->version) &&
197      (c1->version_max == c2->version_max) &&
198      (c1->ssl_options == c2->ssl_options) &&
199      (c1->verifypeer == c2->verifypeer) &&
200      (c1->verifyhost == c2->verifyhost) &&
201      (c1->verifystatus == c2->verifystatus) &&
202      blobcmp(c1->cert_blob, c2->cert_blob) &&
203      blobcmp(c1->ca_info_blob, c2->ca_info_blob) &&
204      blobcmp(c1->issuercert_blob, c2->issuercert_blob) &&
205      Curl_safecmp(c1->CApath, c2->CApath) &&
206      Curl_safecmp(c1->CAfile, c2->CAfile) &&
207      Curl_safecmp(c1->issuercert, c2->issuercert) &&
208      Curl_safecmp(c1->clientcert, c2->clientcert) &&
209 #ifdef USE_TLS_SRP
210      !Curl_timestrcmp(c1->username, c2->username) &&
211      !Curl_timestrcmp(c1->password, c2->password) &&
212 #endif
213      strcasecompare(c1->cipher_list, c2->cipher_list) &&
214      strcasecompare(c1->cipher_list13, c2->cipher_list13) &&
215      strcasecompare(c1->curves, c2->curves) &&
216      strcasecompare(c1->CRLfile, c2->CRLfile) &&
217      strcasecompare(c1->pinned_key, c2->pinned_key))
218     return TRUE;
219 
220   return FALSE;
221 }
222 
Curl_ssl_conn_config_match(struct Curl_easy * data,struct connectdata * candidate,bool proxy)223 bool Curl_ssl_conn_config_match(struct Curl_easy *data,
224                                 struct connectdata *candidate,
225                                 bool proxy)
226 {
227 #ifndef CURL_DISABLE_PROXY
228   if(proxy)
229     return match_ssl_primary_config(data, &data->set.proxy_ssl.primary,
230                                     &candidate->proxy_ssl_config);
231 #else
232   (void)proxy;
233 #endif
234   return match_ssl_primary_config(data, &data->set.ssl.primary,
235                                   &candidate->ssl_config);
236 }
237 
clone_ssl_primary_config(struct ssl_primary_config * source,struct ssl_primary_config * dest)238 static bool clone_ssl_primary_config(struct ssl_primary_config *source,
239                                      struct ssl_primary_config *dest)
240 {
241   dest->version = source->version;
242   dest->version_max = source->version_max;
243   dest->verifypeer = source->verifypeer;
244   dest->verifyhost = source->verifyhost;
245   dest->verifystatus = source->verifystatus;
246   dest->cache_session = source->cache_session;
247   dest->ssl_options = source->ssl_options;
248 
249   CLONE_BLOB(cert_blob);
250   CLONE_BLOB(ca_info_blob);
251   CLONE_BLOB(issuercert_blob);
252   CLONE_STRING(CApath);
253   CLONE_STRING(CAfile);
254   CLONE_STRING(issuercert);
255   CLONE_STRING(clientcert);
256   CLONE_STRING(cipher_list);
257   CLONE_STRING(cipher_list13);
258   CLONE_STRING(pinned_key);
259   CLONE_STRING(curves);
260   CLONE_STRING(CRLfile);
261 #ifdef USE_TLS_SRP
262   CLONE_STRING(username);
263   CLONE_STRING(password);
264 #endif
265 
266   return TRUE;
267 }
268 
free_primary_ssl_config(struct ssl_primary_config * sslc)269 static void free_primary_ssl_config(struct ssl_primary_config *sslc)
270 {
271   Curl_safefree(sslc->CApath);
272   Curl_safefree(sslc->CAfile);
273   Curl_safefree(sslc->issuercert);
274   Curl_safefree(sslc->clientcert);
275   Curl_safefree(sslc->cipher_list);
276   Curl_safefree(sslc->cipher_list13);
277   Curl_safefree(sslc->pinned_key);
278   Curl_safefree(sslc->cert_blob);
279   Curl_safefree(sslc->ca_info_blob);
280   Curl_safefree(sslc->issuercert_blob);
281   Curl_safefree(sslc->curves);
282   Curl_safefree(sslc->CRLfile);
283 #ifdef USE_TLS_SRP
284   Curl_safefree(sslc->username);
285   Curl_safefree(sslc->password);
286 #endif
287 }
288 
Curl_ssl_easy_config_complete(struct Curl_easy * data)289 CURLcode Curl_ssl_easy_config_complete(struct Curl_easy *data)
290 {
291   data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH];
292   data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE];
293   data->set.ssl.primary.CRLfile = data->set.str[STRING_SSL_CRLFILE];
294   data->set.ssl.primary.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
295   data->set.ssl.primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT];
296   data->set.ssl.primary.cipher_list =
297     data->set.str[STRING_SSL_CIPHER_LIST];
298   data->set.ssl.primary.cipher_list13 =
299     data->set.str[STRING_SSL_CIPHER13_LIST];
300   data->set.ssl.primary.pinned_key =
301     data->set.str[STRING_SSL_PINNEDPUBLICKEY];
302   data->set.ssl.primary.cert_blob = data->set.blobs[BLOB_CERT];
303   data->set.ssl.primary.ca_info_blob = data->set.blobs[BLOB_CAINFO];
304   data->set.ssl.primary.curves = data->set.str[STRING_SSL_EC_CURVES];
305 #ifdef USE_TLS_SRP
306   data->set.ssl.primary.username = data->set.str[STRING_TLSAUTH_USERNAME];
307   data->set.ssl.primary.password = data->set.str[STRING_TLSAUTH_PASSWORD];
308 #endif
309   data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE];
310   data->set.ssl.key = data->set.str[STRING_KEY];
311   data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE];
312   data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD];
313   data->set.ssl.primary.clientcert = data->set.str[STRING_CERT];
314   data->set.ssl.key_blob = data->set.blobs[BLOB_KEY];
315 
316 #ifndef CURL_DISABLE_PROXY
317   data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
318   data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
319   data->set.proxy_ssl.primary.cipher_list =
320     data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
321   data->set.proxy_ssl.primary.cipher_list13 =
322     data->set.str[STRING_SSL_CIPHER13_LIST_PROXY];
323   data->set.proxy_ssl.primary.pinned_key =
324     data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY];
325   data->set.proxy_ssl.primary.cert_blob = data->set.blobs[BLOB_CERT_PROXY];
326   data->set.proxy_ssl.primary.ca_info_blob =
327     data->set.blobs[BLOB_CAINFO_PROXY];
328   data->set.proxy_ssl.primary.issuercert =
329     data->set.str[STRING_SSL_ISSUERCERT_PROXY];
330   data->set.proxy_ssl.primary.issuercert_blob =
331     data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY];
332   data->set.proxy_ssl.primary.CRLfile =
333     data->set.str[STRING_SSL_CRLFILE_PROXY];
334   data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
335   data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
336   data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
337   data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
338   data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
339   data->set.proxy_ssl.key_blob = data->set.blobs[BLOB_KEY_PROXY];
340 #ifdef USE_TLS_SRP
341   data->set.proxy_ssl.primary.username =
342     data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
343   data->set.proxy_ssl.primary.password =
344     data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
345 #endif
346 #endif /* CURL_DISABLE_PROXY */
347 
348   return CURLE_OK;
349 }
350 
Curl_ssl_conn_config_init(struct Curl_easy * data,struct connectdata * conn)351 CURLcode Curl_ssl_conn_config_init(struct Curl_easy *data,
352                                    struct connectdata *conn)
353 {
354   /* Clone "primary" SSL configurations from the esay handle to
355    * the connection. They are used for connection cache matching and
356    * probably outlive the easy handle */
357   if(!clone_ssl_primary_config(&data->set.ssl.primary, &conn->ssl_config))
358     return CURLE_OUT_OF_MEMORY;
359 #ifndef CURL_DISABLE_PROXY
360   if(!clone_ssl_primary_config(&data->set.proxy_ssl.primary,
361                                &conn->proxy_ssl_config))
362     return CURLE_OUT_OF_MEMORY;
363 #endif
364   return CURLE_OK;
365 }
366 
Curl_ssl_conn_config_cleanup(struct connectdata * conn)367 void Curl_ssl_conn_config_cleanup(struct connectdata *conn)
368 {
369   free_primary_ssl_config(&conn->ssl_config);
370 #ifndef CURL_DISABLE_PROXY
371   free_primary_ssl_config(&conn->proxy_ssl_config);
372 #endif
373 }
374 
Curl_ssl_conn_config_update(struct Curl_easy * data,bool for_proxy)375 void Curl_ssl_conn_config_update(struct Curl_easy *data, bool for_proxy)
376 {
377   /* May be called on an easy that has no connection yet */
378   if(data->conn) {
379     struct ssl_primary_config *src, *dest;
380 #ifndef CURL_DISABLE_PROXY
381     src = for_proxy ? &data->set.proxy_ssl.primary : &data->set.ssl.primary;
382     dest = for_proxy ? &data->conn->proxy_ssl_config : &data->conn->ssl_config;
383 #else
384     (void)for_proxy;
385     src = &data->set.ssl.primary;
386     dest = &data->conn->ssl_config;
387 #endif
388     dest->verifyhost = src->verifyhost;
389     dest->verifypeer = src->verifypeer;
390     dest->verifystatus = src->verifystatus;
391   }
392 }
393 
394 #ifdef USE_SSL
395 static int multissl_setup(const struct Curl_ssl *backend);
396 #endif
397 
Curl_ssl_backend(void)398 curl_sslbackend Curl_ssl_backend(void)
399 {
400 #ifdef USE_SSL
401   multissl_setup(NULL);
402   return Curl_ssl->info.id;
403 #else
404   return CURLSSLBACKEND_NONE;
405 #endif
406 }
407 
408 #ifdef USE_SSL
409 
410 /* "global" init done? */
411 static bool init_ssl = FALSE;
412 
413 /**
414  * Global SSL init
415  *
416  * @retval 0 error initializing SSL
417  * @retval 1 SSL initialized successfully
418  */
Curl_ssl_init(void)419 int Curl_ssl_init(void)
420 {
421   /* make sure this is only done once */
422   if(init_ssl)
423     return 1;
424   init_ssl = TRUE; /* never again */
425 
426   if(Curl_ssl->init)
427     return Curl_ssl->init();
428   return 1;
429 }
430 
ssl_prefs_check(struct Curl_easy * data)431 static bool ssl_prefs_check(struct Curl_easy *data)
432 {
433   /* check for CURLOPT_SSLVERSION invalid parameter value */
434   const unsigned char sslver = data->set.ssl.primary.version;
435   if(sslver >= CURL_SSLVERSION_LAST) {
436     failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
437     return FALSE;
438   }
439 
440   switch(data->set.ssl.primary.version_max) {
441   case CURL_SSLVERSION_MAX_NONE:
442   case CURL_SSLVERSION_MAX_DEFAULT:
443     break;
444 
445   default:
446     if((data->set.ssl.primary.version_max >> 16) < sslver) {
447       failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION");
448       return FALSE;
449     }
450   }
451 
452   return TRUE;
453 }
454 
cf_ctx_new(struct Curl_easy * data,const struct alpn_spec * alpn)455 static struct ssl_connect_data *cf_ctx_new(struct Curl_easy *data,
456                                            const struct alpn_spec *alpn)
457 {
458   struct ssl_connect_data *ctx;
459 
460   (void)data;
461   ctx = calloc(1, sizeof(*ctx));
462   if(!ctx)
463     return NULL;
464 
465   ctx->ssl_impl = Curl_ssl;
466   ctx->alpn = alpn;
467   Curl_bufq_init2(&ctx->earlydata, CURL_SSL_EARLY_MAX, 1, BUFQ_OPT_NO_SPARES);
468   ctx->backend = calloc(1, ctx->ssl_impl->sizeof_ssl_backend_data);
469   if(!ctx->backend) {
470     free(ctx);
471     return NULL;
472   }
473   return ctx;
474 }
475 
cf_ctx_free(struct ssl_connect_data * ctx)476 static void cf_ctx_free(struct ssl_connect_data *ctx)
477 {
478   if(ctx) {
479     Curl_safefree(ctx->negotiated.alpn);
480     Curl_bufq_free(&ctx->earlydata);
481     free(ctx->backend);
482     free(ctx);
483   }
484 }
485 
ssl_connect(struct Curl_cfilter * cf,struct Curl_easy * data)486 static CURLcode ssl_connect(struct Curl_cfilter *cf, struct Curl_easy *data)
487 {
488   struct ssl_connect_data *connssl = cf->ctx;
489   CURLcode result;
490 
491   if(!ssl_prefs_check(data))
492     return CURLE_SSL_CONNECT_ERROR;
493 
494   /* mark this is being ssl-enabled from here on. */
495   connssl->state = ssl_connection_negotiating;
496 
497   result = connssl->ssl_impl->connect_blocking(cf, data);
498 
499   if(!result) {
500     DEBUGASSERT(connssl->state == ssl_connection_complete);
501   }
502 
503   return result;
504 }
505 
506 static CURLcode
ssl_connect_nonblocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)507 ssl_connect_nonblocking(struct Curl_cfilter *cf, struct Curl_easy *data,
508                         bool *done)
509 {
510   struct ssl_connect_data *connssl = cf->ctx;
511 
512   if(!ssl_prefs_check(data))
513     return CURLE_SSL_CONNECT_ERROR;
514 
515   /* mark this is being ssl requested from here on. */
516   return connssl->ssl_impl->connect_nonblocking(cf, data, done);
517 }
518 
Curl_ssl_get_channel_binding(struct Curl_easy * data,int sockindex,struct dynbuf * binding)519 CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int sockindex,
520                                        struct dynbuf *binding)
521 {
522   if(Curl_ssl->get_channel_binding)
523     return Curl_ssl->get_channel_binding(data, sockindex, binding);
524   return CURLE_OK;
525 }
526 
Curl_ssl_close_all(struct Curl_easy * data)527 void Curl_ssl_close_all(struct Curl_easy *data)
528 {
529   /* kill the session ID cache if not shared */
530   if(data->state.ssl_scache && !CURL_SHARE_ssl_scache(data)) {
531     Curl_ssl_scache_destroy(data->state.ssl_scache);
532     data->state.ssl_scache = NULL;
533   }
534 
535   if(Curl_ssl->close_all)
536     Curl_ssl->close_all(data);
537 }
538 
Curl_ssl_adjust_pollset(struct Curl_cfilter * cf,struct Curl_easy * data,struct easy_pollset * ps)539 void Curl_ssl_adjust_pollset(struct Curl_cfilter *cf, struct Curl_easy *data,
540                               struct easy_pollset *ps)
541 {
542   struct ssl_connect_data *connssl = cf->ctx;
543 
544   if(connssl->io_need) {
545     curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data);
546     if(sock != CURL_SOCKET_BAD) {
547       if(connssl->io_need & CURL_SSL_IO_NEED_SEND) {
548         Curl_pollset_set_out_only(data, ps, sock);
549         CURL_TRC_CF(data, cf, "adjust_pollset, POLLOUT fd=%" FMT_SOCKET_T,
550                     sock);
551       }
552       else {
553         Curl_pollset_set_in_only(data, ps, sock);
554         CURL_TRC_CF(data, cf, "adjust_pollset, POLLIN fd=%" FMT_SOCKET_T,
555                     sock);
556       }
557     }
558   }
559 }
560 
561 /* Selects an SSL crypto engine
562  */
Curl_ssl_set_engine(struct Curl_easy * data,const char * engine)563 CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
564 {
565   if(Curl_ssl->set_engine)
566     return Curl_ssl->set_engine(data, engine);
567   return CURLE_NOT_BUILT_IN;
568 }
569 
570 /* Selects the default SSL crypto engine
571  */
Curl_ssl_set_engine_default(struct Curl_easy * data)572 CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
573 {
574   if(Curl_ssl->set_engine_default)
575     return Curl_ssl->set_engine_default(data);
576   return CURLE_NOT_BUILT_IN;
577 }
578 
579 /* Return list of OpenSSL crypto engine names. */
Curl_ssl_engines_list(struct Curl_easy * data)580 struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
581 {
582   if(Curl_ssl->engines_list)
583     return Curl_ssl->engines_list(data);
584   return NULL;
585 }
586 
587 static size_t multissl_version(char *buffer, size_t size);
588 
Curl_ssl_version(char * buffer,size_t size)589 void Curl_ssl_version(char *buffer, size_t size)
590 {
591 #ifdef CURL_WITH_MULTI_SSL
592   (void)multissl_version(buffer, size);
593 #else
594   (void)Curl_ssl->version(buffer, size);
595 #endif
596 }
597 
Curl_ssl_free_certinfo(struct Curl_easy * data)598 void Curl_ssl_free_certinfo(struct Curl_easy *data)
599 {
600   struct curl_certinfo *ci = &data->info.certs;
601 
602   if(ci->num_of_certs) {
603     /* free all individual lists used */
604     int i;
605     for(i = 0; i < ci->num_of_certs; i++) {
606       curl_slist_free_all(ci->certinfo[i]);
607       ci->certinfo[i] = NULL;
608     }
609 
610     free(ci->certinfo); /* free the actual array too */
611     ci->certinfo = NULL;
612     ci->num_of_certs = 0;
613   }
614 }
615 
Curl_ssl_init_certinfo(struct Curl_easy * data,int num)616 CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
617 {
618   struct curl_certinfo *ci = &data->info.certs;
619   struct curl_slist **table;
620 
621   /* Free any previous certificate information structures */
622   Curl_ssl_free_certinfo(data);
623 
624   /* Allocate the required certificate information structures */
625   table = calloc((size_t) num, sizeof(struct curl_slist *));
626   if(!table)
627     return CURLE_OUT_OF_MEMORY;
628 
629   ci->num_of_certs = num;
630   ci->certinfo = table;
631 
632   return CURLE_OK;
633 }
634 
635 /*
636  * 'value' is NOT a null-terminated string
637  */
Curl_ssl_push_certinfo_len(struct Curl_easy * data,int certnum,const char * label,const char * value,size_t valuelen)638 CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
639                                     int certnum,
640                                     const char *label,
641                                     const char *value,
642                                     size_t valuelen)
643 {
644   struct curl_certinfo *ci = &data->info.certs;
645   struct curl_slist *nl;
646   CURLcode result = CURLE_OK;
647   struct dynbuf build;
648 
649   DEBUGASSERT(certnum < ci->num_of_certs);
650 
651   Curl_dyn_init(&build, CURL_X509_STR_MAX);
652 
653   if(Curl_dyn_add(&build, label) ||
654      Curl_dyn_addn(&build, ":", 1) ||
655      Curl_dyn_addn(&build, value, valuelen))
656     return CURLE_OUT_OF_MEMORY;
657 
658   nl = Curl_slist_append_nodup(ci->certinfo[certnum],
659                                Curl_dyn_ptr(&build));
660   if(!nl) {
661     Curl_dyn_free(&build);
662     curl_slist_free_all(ci->certinfo[certnum]);
663     result = CURLE_OUT_OF_MEMORY;
664   }
665 
666   ci->certinfo[certnum] = nl;
667   return result;
668 }
669 
670 /* get 32 bits of random */
Curl_ssl_random(struct Curl_easy * data,unsigned char * entropy,size_t length)671 CURLcode Curl_ssl_random(struct Curl_easy *data,
672                          unsigned char *entropy,
673                          size_t length)
674 {
675   DEBUGASSERT(length == sizeof(int));
676   if(Curl_ssl->random)
677     return Curl_ssl->random(data, entropy, length);
678   else
679     return CURLE_NOT_BUILT_IN;
680 }
681 
682 /*
683  * Public key pem to der conversion
684  */
685 
pubkey_pem_to_der(const char * pem,unsigned char ** der,size_t * der_len)686 static CURLcode pubkey_pem_to_der(const char *pem,
687                                   unsigned char **der, size_t *der_len)
688 {
689   char *begin_pos, *end_pos;
690   size_t pem_count, pem_len;
691   CURLcode result;
692   struct dynbuf pbuf;
693 
694   /* if no pem, exit. */
695   if(!pem)
696     return CURLE_BAD_CONTENT_ENCODING;
697 
698   Curl_dyn_init(&pbuf, MAX_PINNED_PUBKEY_SIZE);
699 
700   begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
701   if(!begin_pos)
702     return CURLE_BAD_CONTENT_ENCODING;
703 
704   pem_count = begin_pos - pem;
705   /* Invalid if not at beginning AND not directly following \n */
706   if(0 != pem_count && '\n' != pem[pem_count - 1])
707     return CURLE_BAD_CONTENT_ENCODING;
708 
709   /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
710   pem_count += 26;
711 
712   /* Invalid if not directly following \n */
713   end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
714   if(!end_pos)
715     return CURLE_BAD_CONTENT_ENCODING;
716 
717   pem_len = end_pos - pem;
718 
719   /*
720    * Here we loop through the pem array one character at a time between the
721    * correct indices, and place each character that is not '\n' or '\r'
722    * into the stripped_pem array, which should represent the raw base64 string
723    */
724   while(pem_count < pem_len) {
725     if('\n' != pem[pem_count] && '\r' != pem[pem_count]) {
726       result = Curl_dyn_addn(&pbuf, &pem[pem_count], 1);
727       if(result)
728         return result;
729     }
730     ++pem_count;
731   }
732 
733   result = Curl_base64_decode(Curl_dyn_ptr(&pbuf), der, der_len);
734 
735   Curl_dyn_free(&pbuf);
736 
737   return result;
738 }
739 
740 /*
741  * Generic pinned public key check.
742  */
743 
Curl_pin_peer_pubkey(struct Curl_easy * data,const char * pinnedpubkey,const unsigned char * pubkey,size_t pubkeylen)744 CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
745                               const char *pinnedpubkey,
746                               const unsigned char *pubkey, size_t pubkeylen)
747 {
748   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
749 #ifdef CURL_DISABLE_VERBOSE_STRINGS
750   (void)data;
751 #endif
752 
753   /* if a path was not specified, do not pin */
754   if(!pinnedpubkey)
755     return CURLE_OK;
756   if(!pubkey || !pubkeylen)
757     return result;
758 
759   /* only do this if pinnedpubkey starts with "sha256//", length 8 */
760   if(!strncmp(pinnedpubkey, "sha256//", 8)) {
761     CURLcode encode;
762     size_t encodedlen = 0;
763     char *encoded = NULL, *pinkeycopy, *begin_pos, *end_pos;
764     unsigned char *sha256sumdigest;
765 
766     if(!Curl_ssl->sha256sum) {
767       /* without sha256 support, this cannot match */
768       return result;
769     }
770 
771     /* compute sha256sum of public key */
772     sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH);
773     if(!sha256sumdigest)
774       return CURLE_OUT_OF_MEMORY;
775     encode = Curl_ssl->sha256sum(pubkey, pubkeylen,
776                                  sha256sumdigest, CURL_SHA256_DIGEST_LENGTH);
777 
778     if(!encode)
779       encode = Curl_base64_encode((char *)sha256sumdigest,
780                                   CURL_SHA256_DIGEST_LENGTH, &encoded,
781                                   &encodedlen);
782     Curl_safefree(sha256sumdigest);
783 
784     if(encode)
785       return encode;
786 
787     infof(data, " public key hash: sha256//%s", encoded);
788 
789     /* it starts with sha256//, copy so we can modify it */
790     pinkeycopy = strdup(pinnedpubkey);
791     if(!pinkeycopy) {
792       Curl_safefree(encoded);
793       return CURLE_OUT_OF_MEMORY;
794     }
795     /* point begin_pos to the copy, and start extracting keys */
796     begin_pos = pinkeycopy;
797     do {
798       end_pos = strstr(begin_pos, ";sha256//");
799       /*
800        * if there is an end_pos, null terminate,
801        * otherwise it will go to the end of the original string
802        */
803       if(end_pos)
804         end_pos[0] = '\0';
805 
806       /* compare base64 sha256 digests, 8 is the length of "sha256//" */
807       if(encodedlen == strlen(begin_pos + 8) &&
808          !memcmp(encoded, begin_pos + 8, encodedlen)) {
809         result = CURLE_OK;
810         break;
811       }
812 
813       /*
814        * change back the null-terminator we changed earlier,
815        * and look for next begin
816        */
817       if(end_pos) {
818         end_pos[0] = ';';
819         begin_pos = strstr(end_pos, "sha256//");
820       }
821     } while(end_pos && begin_pos);
822     Curl_safefree(encoded);
823     Curl_safefree(pinkeycopy);
824   }
825   else {
826     long filesize;
827     size_t size, pem_len;
828     CURLcode pem_read;
829     struct dynbuf buf;
830     char unsigned *pem_ptr = NULL;
831     size_t left;
832     FILE *fp = fopen(pinnedpubkey, "rb");
833     if(!fp)
834       return result;
835 
836     Curl_dyn_init(&buf, MAX_PINNED_PUBKEY_SIZE);
837 
838     /* Determine the file's size */
839     if(fseek(fp, 0, SEEK_END))
840       goto end;
841     filesize = ftell(fp);
842     if(fseek(fp, 0, SEEK_SET))
843       goto end;
844     if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
845       goto end;
846 
847     /*
848      * if the size of our certificate is bigger than the file
849      * size then it cannot match
850      */
851     size = curlx_sotouz((curl_off_t) filesize);
852     if(pubkeylen > size)
853       goto end;
854 
855     /*
856      * Read the file into the dynbuf
857      */
858     left = size;
859     do {
860       char buffer[1024];
861       size_t want = left > sizeof(buffer) ? sizeof(buffer) : left;
862       if(want != fread(buffer, 1, want, fp))
863         goto end;
864       if(Curl_dyn_addn(&buf, buffer, want))
865         goto end;
866       left -= want;
867     } while(left);
868 
869     /* If the sizes are the same, it cannot be base64 encoded, must be der */
870     if(pubkeylen == size) {
871       if(!memcmp(pubkey, Curl_dyn_ptr(&buf), pubkeylen))
872         result = CURLE_OK;
873       goto end;
874     }
875 
876     /*
877      * Otherwise we will assume it is PEM and try to decode it
878      * after placing null terminator
879      */
880     pem_read = pubkey_pem_to_der(Curl_dyn_ptr(&buf), &pem_ptr, &pem_len);
881     /* if it was not read successfully, exit */
882     if(pem_read)
883       goto end;
884 
885     /*
886      * if the size of our certificate does not match the size of
887      * the decoded file, they cannot be the same, otherwise compare
888      */
889     if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
890       result = CURLE_OK;
891 end:
892     Curl_dyn_free(&buf);
893     Curl_safefree(pem_ptr);
894     fclose(fp);
895   }
896 
897   return result;
898 }
899 
900 /*
901  * Check whether the SSL backend supports the status_request extension.
902  */
Curl_ssl_cert_status_request(void)903 bool Curl_ssl_cert_status_request(void)
904 {
905   if(Curl_ssl->cert_status_request)
906     return Curl_ssl->cert_status_request();
907   return FALSE;
908 }
909 
910 /*
911  * Check whether the SSL backend supports false start.
912  */
Curl_ssl_false_start(void)913 bool Curl_ssl_false_start(void)
914 {
915   if(Curl_ssl->false_start)
916     return Curl_ssl->false_start();
917   return FALSE;
918 }
919 
multissl_init(void)920 static int multissl_init(void)
921 {
922   if(multissl_setup(NULL))
923     return 1;
924   return Curl_ssl->init();
925 }
926 
multissl_connect(struct Curl_cfilter * cf,struct Curl_easy * data)927 static CURLcode multissl_connect(struct Curl_cfilter *cf,
928                                  struct Curl_easy *data)
929 {
930   if(multissl_setup(NULL))
931     return CURLE_FAILED_INIT;
932   return Curl_ssl->connect_blocking(cf, data);
933 }
934 
multissl_connect_nonblocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)935 static CURLcode multissl_connect_nonblocking(struct Curl_cfilter *cf,
936                                              struct Curl_easy *data,
937                                              bool *done)
938 {
939   if(multissl_setup(NULL))
940     return CURLE_FAILED_INIT;
941   return Curl_ssl->connect_nonblocking(cf, data, done);
942 }
943 
multissl_adjust_pollset(struct Curl_cfilter * cf,struct Curl_easy * data,struct easy_pollset * ps)944 static void multissl_adjust_pollset(struct Curl_cfilter *cf,
945                                      struct Curl_easy *data,
946                                      struct easy_pollset *ps)
947 {
948   if(multissl_setup(NULL))
949     return;
950   Curl_ssl->adjust_pollset(cf, data, ps);
951 }
952 
multissl_get_internals(struct ssl_connect_data * connssl,CURLINFO info)953 static void *multissl_get_internals(struct ssl_connect_data *connssl,
954                                     CURLINFO info)
955 {
956   if(multissl_setup(NULL))
957     return NULL;
958   return Curl_ssl->get_internals(connssl, info);
959 }
960 
multissl_close(struct Curl_cfilter * cf,struct Curl_easy * data)961 static void multissl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
962 {
963   if(multissl_setup(NULL))
964     return;
965   Curl_ssl->close(cf, data);
966 }
967 
multissl_recv_plain(struct Curl_cfilter * cf,struct Curl_easy * data,char * buf,size_t len,CURLcode * code)968 static ssize_t multissl_recv_plain(struct Curl_cfilter *cf,
969                                    struct Curl_easy *data,
970                                    char *buf, size_t len, CURLcode *code)
971 {
972   if(multissl_setup(NULL))
973     return CURLE_FAILED_INIT;
974   return Curl_ssl->recv_plain(cf, data, buf, len, code);
975 }
976 
multissl_send_plain(struct Curl_cfilter * cf,struct Curl_easy * data,const void * mem,size_t len,CURLcode * code)977 static ssize_t multissl_send_plain(struct Curl_cfilter *cf,
978                                    struct Curl_easy *data,
979                                    const void *mem, size_t len,
980                                    CURLcode *code)
981 {
982   if(multissl_setup(NULL))
983     return CURLE_FAILED_INIT;
984   return Curl_ssl->send_plain(cf, data, mem, len, code);
985 }
986 
987 static const struct Curl_ssl Curl_ssl_multi = {
988   { CURLSSLBACKEND_NONE, "multi" },  /* info */
989   0, /* supports nothing */
990   (size_t)-1, /* something insanely large to be on the safe side */
991 
992   multissl_init,                     /* init */
993   NULL,                              /* cleanup */
994   multissl_version,                  /* version */
995   NULL,                              /* shutdown */
996   NULL,                              /* data_pending */
997   NULL,                              /* random */
998   NULL,                              /* cert_status_request */
999   multissl_connect,                  /* connect */
1000   multissl_connect_nonblocking,      /* connect_nonblocking */
1001   multissl_adjust_pollset,           /* adjust_pollset */
1002   multissl_get_internals,            /* get_internals */
1003   multissl_close,                    /* close_one */
1004   NULL,                              /* close_all */
1005   NULL,                              /* set_engine */
1006   NULL,                              /* set_engine_default */
1007   NULL,                              /* engines_list */
1008   NULL,                              /* false_start */
1009   NULL,                              /* sha256sum */
1010   multissl_recv_plain,               /* recv decrypted data */
1011   multissl_send_plain,               /* send data to encrypt */
1012   NULL,                              /* get_channel_binding */
1013 };
1014 
1015 const struct Curl_ssl *Curl_ssl =
1016 #if defined(CURL_WITH_MULTI_SSL)
1017   &Curl_ssl_multi;
1018 #elif defined(USE_WOLFSSL)
1019   &Curl_ssl_wolfssl;
1020 #elif defined(USE_GNUTLS)
1021   &Curl_ssl_gnutls;
1022 #elif defined(USE_MBEDTLS)
1023   &Curl_ssl_mbedtls;
1024 #elif defined(USE_RUSTLS)
1025   &Curl_ssl_rustls;
1026 #elif defined(USE_OPENSSL)
1027   &Curl_ssl_openssl;
1028 #elif defined(USE_SECTRANSP)
1029   &Curl_ssl_sectransp;
1030 #elif defined(USE_SCHANNEL)
1031   &Curl_ssl_schannel;
1032 #elif defined(USE_BEARSSL)
1033   &Curl_ssl_bearssl;
1034 #else
1035 #error "Missing struct Curl_ssl for selected SSL backend"
1036 #endif
1037 
1038 static const struct Curl_ssl *available_backends[] = {
1039 #if defined(USE_WOLFSSL)
1040   &Curl_ssl_wolfssl,
1041 #endif
1042 #if defined(USE_GNUTLS)
1043   &Curl_ssl_gnutls,
1044 #endif
1045 #if defined(USE_MBEDTLS)
1046   &Curl_ssl_mbedtls,
1047 #endif
1048 #if defined(USE_OPENSSL)
1049   &Curl_ssl_openssl,
1050 #endif
1051 #if defined(USE_SECTRANSP)
1052   &Curl_ssl_sectransp,
1053 #endif
1054 #if defined(USE_SCHANNEL)
1055   &Curl_ssl_schannel,
1056 #endif
1057 #if defined(USE_BEARSSL)
1058   &Curl_ssl_bearssl,
1059 #endif
1060 #if defined(USE_RUSTLS)
1061   &Curl_ssl_rustls,
1062 #endif
1063   NULL
1064 };
1065 
1066 /* Global cleanup */
Curl_ssl_cleanup(void)1067 void Curl_ssl_cleanup(void)
1068 {
1069   if(init_ssl) {
1070     /* only cleanup if we did a previous init */
1071     if(Curl_ssl->cleanup)
1072       Curl_ssl->cleanup();
1073 #if defined(CURL_WITH_MULTI_SSL)
1074     Curl_ssl = &Curl_ssl_multi;
1075 #endif
1076     init_ssl = FALSE;
1077   }
1078 }
1079 
multissl_version(char * buffer,size_t size)1080 static size_t multissl_version(char *buffer, size_t size)
1081 {
1082   static const struct Curl_ssl *selected;
1083   static char backends[200];
1084   static size_t backends_len;
1085   const struct Curl_ssl *current;
1086 
1087   current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl;
1088 
1089   if(current != selected) {
1090     char *p = backends;
1091     char *end = backends + sizeof(backends);
1092     int i;
1093 
1094     selected = current;
1095 
1096     backends[0] = '\0';
1097 
1098     for(i = 0; available_backends[i]; ++i) {
1099       char vb[200];
1100       bool paren = (selected != available_backends[i]);
1101 
1102       if(available_backends[i]->version(vb, sizeof(vb))) {
1103         p += msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""),
1104                        (paren ? "(" : ""), vb, (paren ? ")" : ""));
1105       }
1106     }
1107 
1108     backends_len = p - backends;
1109   }
1110 
1111   if(size) {
1112     if(backends_len < size)
1113       strcpy(buffer, backends);
1114     else
1115       *buffer = 0; /* did not fit */
1116   }
1117   return 0;
1118 }
1119 
multissl_setup(const struct Curl_ssl * backend)1120 static int multissl_setup(const struct Curl_ssl *backend)
1121 {
1122   const char *env;
1123   char *env_tmp;
1124 
1125   if(Curl_ssl != &Curl_ssl_multi)
1126     return 1;
1127 
1128   if(backend) {
1129     Curl_ssl = backend;
1130     return 0;
1131   }
1132 
1133   if(!available_backends[0])
1134     return 1;
1135 
1136   env = env_tmp = curl_getenv("CURL_SSL_BACKEND");
1137 #ifdef CURL_DEFAULT_SSL_BACKEND
1138   if(!env)
1139     env = CURL_DEFAULT_SSL_BACKEND;
1140 #endif
1141   if(env) {
1142     int i;
1143     for(i = 0; available_backends[i]; i++) {
1144       if(strcasecompare(env, available_backends[i]->info.name)) {
1145         Curl_ssl = available_backends[i];
1146         free(env_tmp);
1147         return 0;
1148       }
1149     }
1150   }
1151 
1152   /* Fall back to first available backend */
1153   Curl_ssl = available_backends[0];
1154   free(env_tmp);
1155   return 0;
1156 }
1157 
1158 /* This function is used to select the SSL backend to use. It is called by
1159    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)1160 CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
1161                                    const curl_ssl_backend ***avail)
1162 {
1163   int i;
1164 
1165   if(avail)
1166     *avail = (const curl_ssl_backend **)&available_backends;
1167 
1168   if(Curl_ssl != &Curl_ssl_multi)
1169     return id == Curl_ssl->info.id ||
1170            (name && strcasecompare(name, Curl_ssl->info.name)) ?
1171            CURLSSLSET_OK :
1172 #if defined(CURL_WITH_MULTI_SSL)
1173            CURLSSLSET_TOO_LATE;
1174 #else
1175            CURLSSLSET_UNKNOWN_BACKEND;
1176 #endif
1177 
1178   for(i = 0; available_backends[i]; i++) {
1179     if(available_backends[i]->info.id == id ||
1180        (name && strcasecompare(available_backends[i]->info.name, name))) {
1181       multissl_setup(available_backends[i]);
1182       return CURLSSLSET_OK;
1183     }
1184   }
1185 
1186   return CURLSSLSET_UNKNOWN_BACKEND;
1187 }
1188 
1189 #else /* USE_SSL */
Curl_init_sslset_nolock(curl_sslbackend id,const char * name,const curl_ssl_backend *** avail)1190 CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
1191                                    const curl_ssl_backend ***avail)
1192 {
1193   (void)id;
1194   (void)name;
1195   (void)avail;
1196   return CURLSSLSET_NO_BACKENDS;
1197 }
1198 
1199 #endif /* !USE_SSL */
1200 
1201 #ifdef USE_SSL
1202 
Curl_ssl_peer_cleanup(struct ssl_peer * peer)1203 void Curl_ssl_peer_cleanup(struct ssl_peer *peer)
1204 {
1205   Curl_safefree(peer->sni);
1206   if(peer->dispname != peer->hostname)
1207     free(peer->dispname);
1208   peer->dispname = NULL;
1209   Curl_safefree(peer->hostname);
1210   Curl_safefree(peer->scache_key);
1211   peer->type = CURL_SSL_PEER_DNS;
1212 }
1213 
cf_close(struct Curl_cfilter * cf,struct Curl_easy * data)1214 static void cf_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1215 {
1216   struct ssl_connect_data *connssl = cf->ctx;
1217   if(connssl) {
1218     connssl->ssl_impl->close(cf, data);
1219     connssl->state = ssl_connection_none;
1220     Curl_ssl_peer_cleanup(&connssl->peer);
1221   }
1222   cf->connected = FALSE;
1223 }
1224 
get_peer_type(const char * hostname)1225 static ssl_peer_type get_peer_type(const char *hostname)
1226 {
1227   if(hostname && hostname[0]) {
1228 #ifdef USE_IPV6
1229     struct in6_addr addr;
1230 #else
1231     struct in_addr addr;
1232 #endif
1233     if(Curl_inet_pton(AF_INET, hostname, &addr))
1234       return CURL_SSL_PEER_IPV4;
1235 #ifdef USE_IPV6
1236     else if(Curl_inet_pton(AF_INET6, hostname, &addr)) {
1237       return CURL_SSL_PEER_IPV6;
1238     }
1239 #endif
1240   }
1241   return CURL_SSL_PEER_DNS;
1242 }
1243 
Curl_ssl_peer_init(struct ssl_peer * peer,struct Curl_cfilter * cf,const char * tls_id,int transport)1244 CURLcode Curl_ssl_peer_init(struct ssl_peer *peer,
1245                             struct Curl_cfilter *cf,
1246                             const char *tls_id,
1247                             int transport)
1248 {
1249   const char *ehostname, *edispname;
1250   CURLcode result = CURLE_OUT_OF_MEMORY;
1251 
1252   /* We expect a clean struct, e.g. called only ONCE */
1253   DEBUGASSERT(peer);
1254   DEBUGASSERT(!peer->hostname);
1255   DEBUGASSERT(!peer->dispname);
1256   DEBUGASSERT(!peer->sni);
1257   /* We need the hostname for SNI negotiation. Once handshaked, this remains
1258    * the SNI hostname for the TLS connection. When the connection is reused,
1259    * the settings in cf->conn might change. We keep a copy of the hostname we
1260    * use for SNI.
1261    */
1262   peer->transport = transport;
1263 #ifndef CURL_DISABLE_PROXY
1264   if(Curl_ssl_cf_is_proxy(cf)) {
1265     ehostname = cf->conn->http_proxy.host.name;
1266     edispname = cf->conn->http_proxy.host.dispname;
1267     peer->port = cf->conn->http_proxy.port;
1268   }
1269   else
1270 #endif
1271   {
1272     ehostname = cf->conn->host.name;
1273     edispname = cf->conn->host.dispname;
1274     peer->port = cf->conn->remote_port;
1275   }
1276 
1277   /* hostname MUST exist and not be empty */
1278   if(!ehostname || !ehostname[0]) {
1279     result = CURLE_FAILED_INIT;
1280     goto out;
1281   }
1282 
1283   peer->hostname = strdup(ehostname);
1284   if(!peer->hostname)
1285     goto out;
1286   if(!edispname || !strcmp(ehostname, edispname))
1287     peer->dispname = peer->hostname;
1288   else {
1289     peer->dispname = strdup(edispname);
1290     if(!peer->dispname)
1291       goto out;
1292   }
1293   peer->type = get_peer_type(peer->hostname);
1294   if(peer->type == CURL_SSL_PEER_DNS) {
1295     /* not an IP address, normalize according to RCC 6066 ch. 3,
1296      * max len of SNI is 2^16-1, no trailing dot */
1297     size_t len = strlen(peer->hostname);
1298     if(len && (peer->hostname[len-1] == '.'))
1299       len--;
1300     if(len < USHRT_MAX) {
1301       peer->sni = calloc(1, len + 1);
1302       if(!peer->sni)
1303         goto out;
1304       Curl_strntolower(peer->sni, peer->hostname, len);
1305       peer->sni[len] = 0;
1306     }
1307   }
1308 
1309   result = Curl_ssl_peer_key_make(cf, peer, tls_id, &peer->scache_key);
1310 
1311 out:
1312   if(result)
1313     Curl_ssl_peer_cleanup(peer);
1314   return result;
1315 }
1316 
ssl_cf_destroy(struct Curl_cfilter * cf,struct Curl_easy * data)1317 static void ssl_cf_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
1318 {
1319   struct cf_call_data save;
1320 
1321   CF_DATA_SAVE(save, cf, data);
1322   cf_close(cf, data);
1323   CF_DATA_RESTORE(cf, save);
1324   cf_ctx_free(cf->ctx);
1325   cf->ctx = NULL;
1326 }
1327 
ssl_cf_close(struct Curl_cfilter * cf,struct Curl_easy * data)1328 static void ssl_cf_close(struct Curl_cfilter *cf,
1329                          struct Curl_easy *data)
1330 {
1331   struct cf_call_data save;
1332 
1333   CF_DATA_SAVE(save, cf, data);
1334   cf_close(cf, data);
1335   if(cf->next)
1336     cf->next->cft->do_close(cf->next, data);
1337   CF_DATA_RESTORE(cf, save);
1338 }
1339 
ssl_cf_connect(struct Curl_cfilter * cf,struct Curl_easy * data,bool blocking,bool * done)1340 static CURLcode ssl_cf_connect(struct Curl_cfilter *cf,
1341                                struct Curl_easy *data,
1342                                bool blocking, bool *done)
1343 {
1344   struct ssl_connect_data *connssl = cf->ctx;
1345   struct cf_call_data save;
1346   CURLcode result;
1347 
1348   if(cf->connected) {
1349     *done = TRUE;
1350     return CURLE_OK;
1351   }
1352 
1353   if(!cf->next) {
1354     *done = FALSE;
1355     return CURLE_FAILED_INIT;
1356   }
1357 
1358   if(!cf->next->connected) {
1359     result = cf->next->cft->do_connect(cf->next, data, blocking, done);
1360     if(result || !*done)
1361       return result;
1362   }
1363 
1364   CF_DATA_SAVE(save, cf, data);
1365   CURL_TRC_CF(data, cf, "cf_connect()");
1366   DEBUGASSERT(data->conn);
1367   DEBUGASSERT(data->conn == cf->conn);
1368   DEBUGASSERT(connssl);
1369 
1370   *done = FALSE;
1371   if(!connssl->peer.hostname) {
1372     char tls_id[80];
1373     connssl->ssl_impl->version(tls_id, sizeof(tls_id) - 1);
1374     result = Curl_ssl_peer_init(&connssl->peer, cf, tls_id, TRNSPRT_TCP);
1375     if(result)
1376       goto out;
1377   }
1378 
1379   if(blocking) {
1380     result = ssl_connect(cf, data);
1381     *done = (result == CURLE_OK);
1382   }
1383   else {
1384     result = ssl_connect_nonblocking(cf, data, done);
1385   }
1386 
1387   if(!result && *done) {
1388     cf->connected = TRUE;
1389     connssl->handshake_done = Curl_now();
1390     /* Connection can be deferred when sending early data */
1391     DEBUGASSERT(connssl->state == ssl_connection_complete ||
1392                 connssl->state == ssl_connection_deferred);
1393   }
1394 out:
1395   CURL_TRC_CF(data, cf, "cf_connect() -> %d, done=%d", result, *done);
1396   CF_DATA_RESTORE(cf, save);
1397   return result;
1398 }
1399 
ssl_cf_data_pending(struct Curl_cfilter * cf,const struct Curl_easy * data)1400 static bool ssl_cf_data_pending(struct Curl_cfilter *cf,
1401                                 const struct Curl_easy *data)
1402 {
1403   struct ssl_connect_data *connssl = cf->ctx;
1404   struct cf_call_data save;
1405   bool result;
1406 
1407   CF_DATA_SAVE(save, cf, data);
1408   if(connssl->ssl_impl->data_pending &&
1409      connssl->ssl_impl->data_pending(cf, data))
1410     result = TRUE;
1411   else
1412     result = cf->next->cft->has_data_pending(cf->next, data);
1413   CF_DATA_RESTORE(cf, save);
1414   return result;
1415 }
1416 
ssl_cf_send(struct Curl_cfilter * cf,struct Curl_easy * data,const void * buf,size_t len,bool eos,CURLcode * err)1417 static ssize_t ssl_cf_send(struct Curl_cfilter *cf,
1418                            struct Curl_easy *data, const void *buf, size_t len,
1419                            bool eos, CURLcode *err)
1420 {
1421   struct ssl_connect_data *connssl = cf->ctx;
1422   struct cf_call_data save;
1423   ssize_t nwritten = 0;
1424 
1425   (void)eos;
1426   /* OpenSSL and maybe other TLS libs do not like 0-length writes. Skip. */
1427   *err = CURLE_OK;
1428   if(len > 0) {
1429     CF_DATA_SAVE(save, cf, data);
1430     nwritten = connssl->ssl_impl->send_plain(cf, data, buf, len, err);
1431     CF_DATA_RESTORE(cf, save);
1432   }
1433   return nwritten;
1434 }
1435 
ssl_cf_recv(struct Curl_cfilter * cf,struct Curl_easy * data,char * buf,size_t len,CURLcode * err)1436 static ssize_t ssl_cf_recv(struct Curl_cfilter *cf,
1437                            struct Curl_easy *data, char *buf, size_t len,
1438                            CURLcode *err)
1439 {
1440   struct ssl_connect_data *connssl = cf->ctx;
1441   struct cf_call_data save;
1442   ssize_t nread;
1443 
1444   CF_DATA_SAVE(save, cf, data);
1445   *err = CURLE_OK;
1446   nread = connssl->ssl_impl->recv_plain(cf, data, buf, len, err);
1447   if(nread > 0) {
1448     DEBUGASSERT((size_t)nread <= len);
1449   }
1450   else if(nread == 0) {
1451     /* eof */
1452     *err = CURLE_OK;
1453   }
1454   CURL_TRC_CF(data, cf, "cf_recv(len=%zu) -> %zd, %d", len,
1455               nread, *err);
1456   CF_DATA_RESTORE(cf, save);
1457   return nread;
1458 }
1459 
ssl_cf_shutdown(struct Curl_cfilter * cf,struct Curl_easy * data,bool * done)1460 static CURLcode ssl_cf_shutdown(struct Curl_cfilter *cf,
1461                                 struct Curl_easy *data,
1462                                 bool *done)
1463 {
1464   struct ssl_connect_data *connssl = cf->ctx;
1465   CURLcode result = CURLE_OK;
1466 
1467   *done = TRUE;
1468   if(!cf->shutdown && Curl_ssl->shut_down) {
1469     struct cf_call_data save;
1470 
1471     CF_DATA_SAVE(save, cf, data);
1472     result = connssl->ssl_impl->shut_down(cf, data, TRUE, done);
1473     CURL_TRC_CF(data, cf, "cf_shutdown -> %d, done=%d", result, *done);
1474     CF_DATA_RESTORE(cf, save);
1475     cf->shutdown = (result || *done);
1476   }
1477   return result;
1478 }
1479 
ssl_cf_adjust_pollset(struct Curl_cfilter * cf,struct Curl_easy * data,struct easy_pollset * ps)1480 static void ssl_cf_adjust_pollset(struct Curl_cfilter *cf,
1481                                   struct Curl_easy *data,
1482                                   struct easy_pollset *ps)
1483 {
1484   struct ssl_connect_data *connssl = cf->ctx;
1485   struct cf_call_data save;
1486 
1487   CF_DATA_SAVE(save, cf, data);
1488   connssl->ssl_impl->adjust_pollset(cf, data, ps);
1489   CF_DATA_RESTORE(cf, save);
1490 }
1491 
ssl_cf_query(struct Curl_cfilter * cf,struct Curl_easy * data,int query,int * pres1,void * pres2)1492 static CURLcode ssl_cf_query(struct Curl_cfilter *cf,
1493                              struct Curl_easy *data,
1494                              int query, int *pres1, void *pres2)
1495 {
1496   struct ssl_connect_data *connssl = cf->ctx;
1497 
1498   switch(query) {
1499   case CF_QUERY_TIMER_APPCONNECT: {
1500     struct curltime *when = pres2;
1501     if(cf->connected && !Curl_ssl_cf_is_proxy(cf))
1502       *when = connssl->handshake_done;
1503     return CURLE_OK;
1504   }
1505   default:
1506     break;
1507   }
1508   return cf->next ?
1509     cf->next->cft->query(cf->next, data, query, pres1, pres2) :
1510     CURLE_UNKNOWN_OPTION;
1511 }
1512 
cf_ssl_is_alive(struct Curl_cfilter * cf,struct Curl_easy * data,bool * input_pending)1513 static bool cf_ssl_is_alive(struct Curl_cfilter *cf, struct Curl_easy *data,
1514                             bool *input_pending)
1515 {
1516   /*
1517    * This function tries to determine connection status.
1518    */
1519   return cf->next ?
1520     cf->next->cft->is_alive(cf->next, data, input_pending) :
1521     FALSE; /* pessimistic in absence of data */
1522 }
1523 
1524 struct Curl_cftype Curl_cft_ssl = {
1525   "SSL",
1526   CF_TYPE_SSL,
1527   CURL_LOG_LVL_NONE,
1528   ssl_cf_destroy,
1529   ssl_cf_connect,
1530   ssl_cf_close,
1531   ssl_cf_shutdown,
1532   Curl_cf_def_get_host,
1533   ssl_cf_adjust_pollset,
1534   ssl_cf_data_pending,
1535   ssl_cf_send,
1536   ssl_cf_recv,
1537   Curl_cf_def_cntrl,
1538   cf_ssl_is_alive,
1539   Curl_cf_def_conn_keep_alive,
1540   ssl_cf_query,
1541 };
1542 
1543 #ifndef CURL_DISABLE_PROXY
1544 
1545 struct Curl_cftype Curl_cft_ssl_proxy = {
1546   "SSL-PROXY",
1547   CF_TYPE_SSL|CF_TYPE_PROXY,
1548   CURL_LOG_LVL_NONE,
1549   ssl_cf_destroy,
1550   ssl_cf_connect,
1551   ssl_cf_close,
1552   ssl_cf_shutdown,
1553   Curl_cf_def_get_host,
1554   ssl_cf_adjust_pollset,
1555   ssl_cf_data_pending,
1556   ssl_cf_send,
1557   ssl_cf_recv,
1558   Curl_cf_def_cntrl,
1559   cf_ssl_is_alive,
1560   Curl_cf_def_conn_keep_alive,
1561   Curl_cf_def_query,
1562 };
1563 
1564 #endif /* !CURL_DISABLE_PROXY */
1565 
cf_ssl_create(struct Curl_cfilter ** pcf,struct Curl_easy * data,struct connectdata * conn)1566 static CURLcode cf_ssl_create(struct Curl_cfilter **pcf,
1567                               struct Curl_easy *data,
1568                               struct connectdata *conn)
1569 {
1570   struct Curl_cfilter *cf = NULL;
1571   struct ssl_connect_data *ctx;
1572   CURLcode result;
1573 
1574   DEBUGASSERT(data->conn);
1575 
1576   ctx = cf_ctx_new(data, alpn_get_spec(data->state.httpwant,
1577                                        conn->bits.tls_enable_alpn));
1578   if(!ctx) {
1579     result = CURLE_OUT_OF_MEMORY;
1580     goto out;
1581   }
1582 
1583   result = Curl_cf_create(&cf, &Curl_cft_ssl, ctx);
1584 
1585 out:
1586   if(result)
1587     cf_ctx_free(ctx);
1588   *pcf = result ? NULL : cf;
1589   return result;
1590 }
1591 
Curl_ssl_cfilter_add(struct Curl_easy * data,struct connectdata * conn,int sockindex)1592 CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data,
1593                               struct connectdata *conn,
1594                               int sockindex)
1595 {
1596   struct Curl_cfilter *cf;
1597   CURLcode result;
1598 
1599   result = cf_ssl_create(&cf, data, conn);
1600   if(!result)
1601     Curl_conn_cf_add(data, conn, sockindex, cf);
1602   return result;
1603 }
1604 
Curl_cf_ssl_insert_after(struct Curl_cfilter * cf_at,struct Curl_easy * data)1605 CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at,
1606                                   struct Curl_easy *data)
1607 {
1608   struct Curl_cfilter *cf;
1609   CURLcode result;
1610 
1611   result = cf_ssl_create(&cf, data, cf_at->conn);
1612   if(!result)
1613     Curl_conn_cf_insert_after(cf_at, cf);
1614   return result;
1615 }
1616 
1617 #ifndef CURL_DISABLE_PROXY
1618 
cf_ssl_proxy_create(struct Curl_cfilter ** pcf,struct Curl_easy * data,struct connectdata * conn)1619 static CURLcode cf_ssl_proxy_create(struct Curl_cfilter **pcf,
1620                                     struct Curl_easy *data,
1621                                     struct connectdata *conn)
1622 {
1623   struct Curl_cfilter *cf = NULL;
1624   struct ssl_connect_data *ctx;
1625   CURLcode result;
1626   bool use_alpn = conn->bits.tls_enable_alpn;
1627   int httpwant = CURL_HTTP_VERSION_1_1;
1628 
1629 #ifdef USE_HTTP2
1630   if(conn->http_proxy.proxytype == CURLPROXY_HTTPS2) {
1631     use_alpn = TRUE;
1632     httpwant = CURL_HTTP_VERSION_2;
1633   }
1634 #endif
1635 
1636   ctx = cf_ctx_new(data, alpn_get_spec(httpwant, use_alpn));
1637   if(!ctx) {
1638     result = CURLE_OUT_OF_MEMORY;
1639     goto out;
1640   }
1641   result = Curl_cf_create(&cf, &Curl_cft_ssl_proxy, ctx);
1642 
1643 out:
1644   if(result)
1645     cf_ctx_free(ctx);
1646   *pcf = result ? NULL : cf;
1647   return result;
1648 }
1649 
Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter * cf_at,struct Curl_easy * data)1650 CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at,
1651                                         struct Curl_easy *data)
1652 {
1653   struct Curl_cfilter *cf;
1654   CURLcode result;
1655 
1656   result = cf_ssl_proxy_create(&cf, data, cf_at->conn);
1657   if(!result)
1658     Curl_conn_cf_insert_after(cf_at, cf);
1659   return result;
1660 }
1661 
1662 #endif /* !CURL_DISABLE_PROXY */
1663 
Curl_ssl_supports(struct Curl_easy * data,unsigned int ssl_option)1664 bool Curl_ssl_supports(struct Curl_easy *data, unsigned int ssl_option)
1665 {
1666   (void)data;
1667   return (Curl_ssl->supports & ssl_option);
1668 }
1669 
get_ssl_filter(struct Curl_cfilter * cf)1670 static struct Curl_cfilter *get_ssl_filter(struct Curl_cfilter *cf)
1671 {
1672   for(; cf; cf = cf->next) {
1673     if(cf->cft == &Curl_cft_ssl)
1674       return cf;
1675 #ifndef CURL_DISABLE_PROXY
1676     if(cf->cft == &Curl_cft_ssl_proxy)
1677       return cf;
1678 #endif
1679   }
1680   return NULL;
1681 }
1682 
1683 
Curl_ssl_get_internals(struct Curl_easy * data,int sockindex,CURLINFO info,int n)1684 void *Curl_ssl_get_internals(struct Curl_easy *data, int sockindex,
1685                              CURLINFO info, int n)
1686 {
1687   void *result = NULL;
1688   (void)n;
1689   if(data->conn) {
1690     struct Curl_cfilter *cf;
1691     /* get first SSL filter in chain, if any is present */
1692     cf = get_ssl_filter(data->conn->cfilter[sockindex]);
1693     if(cf) {
1694       struct ssl_connect_data *connssl = cf->ctx;
1695       struct cf_call_data save;
1696       CF_DATA_SAVE(save, cf, data);
1697       result = connssl->ssl_impl->get_internals(cf->ctx, info);
1698       CF_DATA_RESTORE(cf, save);
1699     }
1700   }
1701   return result;
1702 }
1703 
vtls_shutdown_blocking(struct Curl_cfilter * cf,struct Curl_easy * data,bool send_shutdown,bool * done)1704 static CURLcode vtls_shutdown_blocking(struct Curl_cfilter *cf,
1705                                        struct Curl_easy *data,
1706                                        bool send_shutdown, bool *done)
1707 {
1708   struct ssl_connect_data *connssl = cf->ctx;
1709   struct cf_call_data save;
1710   CURLcode result = CURLE_OK;
1711   timediff_t timeout_ms;
1712   int what, loop = 10;
1713 
1714   if(cf->shutdown) {
1715     *done = TRUE;
1716     return CURLE_OK;
1717   }
1718   CF_DATA_SAVE(save, cf, data);
1719 
1720   *done = FALSE;
1721   while(!result && !*done && loop--) {
1722     timeout_ms = Curl_shutdown_timeleft(cf->conn, cf->sockindex, NULL);
1723 
1724     if(timeout_ms < 0) {
1725       /* no need to continue if time is already up */
1726       failf(data, "SSL shutdown timeout");
1727       return CURLE_OPERATION_TIMEDOUT;
1728     }
1729 
1730     result = connssl->ssl_impl->shut_down(cf, data, send_shutdown, done);
1731     if(result ||*done)
1732       goto out;
1733 
1734     if(connssl->io_need) {
1735       what = Curl_conn_cf_poll(cf, data, timeout_ms);
1736       if(what < 0) {
1737         /* fatal error */
1738         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1739         result = CURLE_RECV_ERROR;
1740         goto out;
1741       }
1742       else if(0 == what) {
1743         /* timeout */
1744         failf(data, "SSL shutdown timeout");
1745         result = CURLE_OPERATION_TIMEDOUT;
1746         goto out;
1747       }
1748       /* socket is readable or writable */
1749     }
1750   }
1751 out:
1752   CF_DATA_RESTORE(cf, save);
1753   cf->shutdown = (result || *done);
1754   return result;
1755 }
1756 
Curl_ssl_cfilter_remove(struct Curl_easy * data,int sockindex,bool send_shutdown)1757 CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data,
1758                                  int sockindex, bool send_shutdown)
1759 {
1760   struct Curl_cfilter *cf, *head;
1761   CURLcode result = CURLE_OK;
1762 
1763   head = data->conn ? data->conn->cfilter[sockindex] : NULL;
1764   for(cf = head; cf; cf = cf->next) {
1765     if(cf->cft == &Curl_cft_ssl) {
1766       bool done;
1767       CURL_TRC_CF(data, cf, "shutdown and remove SSL, start");
1768       Curl_shutdown_start(data, sockindex, NULL);
1769       result = vtls_shutdown_blocking(cf, data, send_shutdown, &done);
1770       Curl_shutdown_clear(data, sockindex);
1771       if(!result && !done) /* blocking failed? */
1772         result = CURLE_SSL_SHUTDOWN_FAILED;
1773       Curl_conn_cf_discard_sub(head, cf, data, FALSE);
1774       CURL_TRC_CF(data, cf, "shutdown and remove SSL, done -> %d", result);
1775       break;
1776     }
1777   }
1778   return result;
1779 }
1780 
Curl_ssl_cf_is_proxy(struct Curl_cfilter * cf)1781 bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf)
1782 {
1783   return (cf->cft->flags & CF_TYPE_SSL) && (cf->cft->flags & CF_TYPE_PROXY);
1784 }
1785 
1786 struct ssl_config_data *
Curl_ssl_cf_get_config(struct Curl_cfilter * cf,struct Curl_easy * data)1787 Curl_ssl_cf_get_config(struct Curl_cfilter *cf, struct Curl_easy *data)
1788 {
1789 #ifdef CURL_DISABLE_PROXY
1790   (void)cf;
1791   return &data->set.ssl;
1792 #else
1793   return Curl_ssl_cf_is_proxy(cf) ? &data->set.proxy_ssl : &data->set.ssl;
1794 #endif
1795 }
1796 
1797 struct ssl_primary_config *
Curl_ssl_cf_get_primary_config(struct Curl_cfilter * cf)1798 Curl_ssl_cf_get_primary_config(struct Curl_cfilter *cf)
1799 {
1800 #ifdef CURL_DISABLE_PROXY
1801   return &cf->conn->ssl_config;
1802 #else
1803   return Curl_ssl_cf_is_proxy(cf) ?
1804     &cf->conn->proxy_ssl_config : &cf->conn->ssl_config;
1805 #endif
1806 }
1807 
Curl_alpn_to_proto_buf(struct alpn_proto_buf * buf,const struct alpn_spec * spec)1808 CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf,
1809                                 const struct alpn_spec *spec)
1810 {
1811   size_t i, len;
1812   int off = 0;
1813   unsigned char blen;
1814 
1815   memset(buf, 0, sizeof(*buf));
1816   for(i = 0; spec && i < spec->count; ++i) {
1817     len = strlen(spec->entries[i]);
1818     if(len >= ALPN_NAME_MAX)
1819       return CURLE_FAILED_INIT;
1820     blen = (unsigned  char)len;
1821     if(off + blen + 1 >= (int)sizeof(buf->data))
1822       return CURLE_FAILED_INIT;
1823     buf->data[off++] = blen;
1824     memcpy(buf->data + off, spec->entries[i], blen);
1825     off += blen;
1826   }
1827   buf->len = off;
1828   return CURLE_OK;
1829 }
1830 
Curl_alpn_to_proto_str(struct alpn_proto_buf * buf,const struct alpn_spec * spec)1831 CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf,
1832                                 const struct alpn_spec *spec)
1833 {
1834   size_t i, len;
1835   size_t off = 0;
1836 
1837   memset(buf, 0, sizeof(*buf));
1838   for(i = 0; spec && i < spec->count; ++i) {
1839     len = strlen(spec->entries[i]);
1840     if(len >= ALPN_NAME_MAX)
1841       return CURLE_FAILED_INIT;
1842     if(off + len + 2 >= sizeof(buf->data))
1843       return CURLE_FAILED_INIT;
1844     if(off)
1845       buf->data[off++] = ',';
1846     memcpy(buf->data + off, spec->entries[i], len);
1847     off += len;
1848   }
1849   buf->data[off] = '\0';
1850   buf->len = (int)off;
1851   return CURLE_OK;
1852 }
1853 
Curl_alpn_contains_proto(const struct alpn_spec * spec,const char * proto)1854 bool Curl_alpn_contains_proto(const struct alpn_spec *spec,
1855                               const char *proto)
1856 {
1857   size_t i, plen = proto ? strlen(proto) : 0;
1858   for(i = 0; spec && plen && i < spec->count; ++i) {
1859     size_t slen = strlen(spec->entries[i]);
1860     if((slen == plen) && !memcmp(proto, spec->entries[i], plen))
1861       return TRUE;
1862   }
1863   return FALSE;
1864 }
1865 
Curl_alpn_set_negotiated(struct Curl_cfilter * cf,struct Curl_easy * data,struct ssl_connect_data * connssl,const unsigned char * proto,size_t proto_len)1866 CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf,
1867                                   struct Curl_easy *data,
1868                                   struct ssl_connect_data *connssl,
1869                                   const unsigned char *proto,
1870                                   size_t proto_len)
1871 {
1872   CURLcode result = CURLE_OK;
1873   unsigned char *palpn =
1874 #ifndef CURL_DISABLE_PROXY
1875     (cf->conn->bits.tunnel_proxy && Curl_ssl_cf_is_proxy(cf)) ?
1876     &cf->conn->proxy_alpn : &cf->conn->alpn
1877 #else
1878     &cf->conn->alpn
1879 #endif
1880     ;
1881 
1882   if(connssl->negotiated.alpn) {
1883     /* When we ask for a specific ALPN protocol, we need the confirmation
1884      * of it by the server, as we have installed protocol handler and
1885      * connection filter chain for exactly this protocol. */
1886     if(!proto_len) {
1887       failf(data, "ALPN: asked for '%s' from previous session, "
1888             "but server did not confirm it. Refusing to continue.",
1889             connssl->negotiated.alpn);
1890       result = CURLE_SSL_CONNECT_ERROR;
1891       goto out;
1892     }
1893     else if((strlen(connssl->negotiated.alpn) != proto_len) ||
1894             memcmp(connssl->negotiated.alpn, proto, proto_len)) {
1895       failf(data, "ALPN: asked for '%s' from previous session, but server "
1896             "selected '%.*s'. Refusing to continue.",
1897             connssl->negotiated.alpn, (int)proto_len, proto);
1898       result = CURLE_SSL_CONNECT_ERROR;
1899       goto out;
1900     }
1901     /* ALPN is exactly what we asked for, done. */
1902     infof(data, "ALPN: server confirmed to use '%s'",
1903           connssl->negotiated.alpn);
1904     goto out;
1905   }
1906 
1907   if(proto && proto_len) {
1908     if(memchr(proto, '\0', proto_len)) {
1909       failf(data, "ALPN: server selected protocol contains NUL. "
1910             "Refusing to continue.");
1911       result = CURLE_SSL_CONNECT_ERROR;
1912       goto out;
1913     }
1914     connssl->negotiated.alpn = malloc(proto_len + 1);
1915     if(!connssl->negotiated.alpn)
1916       return CURLE_OUT_OF_MEMORY;
1917     memcpy(connssl->negotiated.alpn, proto, proto_len);
1918     connssl->negotiated.alpn[proto_len] = 0;
1919   }
1920 
1921   if(proto && proto_len) {
1922     if(proto_len == ALPN_HTTP_1_1_LENGTH &&
1923        !memcmp(ALPN_HTTP_1_1, proto, ALPN_HTTP_1_1_LENGTH)) {
1924       *palpn = CURL_HTTP_VERSION_1_1;
1925     }
1926 #ifdef USE_HTTP2
1927     else if(proto_len == ALPN_H2_LENGTH &&
1928             !memcmp(ALPN_H2, proto, ALPN_H2_LENGTH)) {
1929       *palpn = CURL_HTTP_VERSION_2;
1930     }
1931 #endif
1932 #ifdef USE_HTTP3
1933     else if(proto_len == ALPN_H3_LENGTH &&
1934             !memcmp(ALPN_H3, proto, ALPN_H3_LENGTH)) {
1935       *palpn = CURL_HTTP_VERSION_3;
1936     }
1937 #endif
1938     else {
1939       *palpn = CURL_HTTP_VERSION_NONE;
1940       failf(data, "unsupported ALPN protocol: '%.*s'", (int)proto_len, proto);
1941       /* TODO: do we want to fail this? Previous code just ignored it and
1942        * some vtls backends even ignore the return code of this function. */
1943       /* return CURLE_NOT_BUILT_IN; */
1944       goto out;
1945     }
1946 
1947     if(connssl->state == ssl_connection_deferred)
1948       infof(data, VTLS_INFOF_ALPN_DEFERRED, (int)proto_len, proto);
1949     else
1950       infof(data, VTLS_INFOF_ALPN_ACCEPTED, (int)proto_len, proto);
1951   }
1952   else {
1953     *palpn = CURL_HTTP_VERSION_NONE;
1954     if(connssl->state == ssl_connection_deferred)
1955       infof(data, VTLS_INFOF_NO_ALPN_DEFERRED);
1956     else
1957       infof(data, VTLS_INFOF_NO_ALPN);
1958   }
1959 
1960 out:
1961   return result;
1962 }
1963 
1964 #endif /* USE_SSL */
1965