Imported Upstream version 7.53.1
[platform/upstream/curl.git] / lib / vtls / vtls.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 /* This file is for implementing all "generic" SSL functions that all libcurl
24    internals should use. It is then responsible for calling the proper
25    "backend" function.
26
27    SSL-functions in libcurl should call functions in this source file, and not
28    to any specific SSL-layer.
29
30    Curl_ssl_ - prefix for generic ones
31    Curl_ossl_ - prefix for OpenSSL ones
32    Curl_gtls_ - prefix for GnuTLS ones
33    Curl_nss_ - prefix for NSS ones
34    Curl_gskit_ - prefix for GSKit ones
35    Curl_polarssl_ - prefix for PolarSSL ones
36    Curl_cyassl_ - prefix for CyaSSL ones
37    Curl_schannel_ - prefix for Schannel SSPI ones
38    Curl_darwinssl_ - prefix for SecureTransport (Darwin) ones
39
40    Note that this source code uses curlssl_* functions, and they are all
41    defines/macros #defined by the lib-specific header files.
42
43    "SSL/TLS Strong Encryption: An Introduction"
44    https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
45 */
46
47 #include "curl_setup.h"
48
49 #ifdef HAVE_SYS_TYPES_H
50 #include <sys/types.h>
51 #endif
52 #ifdef HAVE_SYS_STAT_H
53 #include <sys/stat.h>
54 #endif
55 #ifdef HAVE_FCNTL_H
56 #include <fcntl.h>
57 #endif
58
59 #include "urldata.h"
60
61 #include "vtls.h" /* generic SSL protos etc */
62 #include "slist.h"
63 #include "sendf.h"
64 #include "strcase.h"
65 #include "url.h"
66 #include "progress.h"
67 #include "share.h"
68 #include "multiif.h"
69 #include "timeval.h"
70 #include "curl_md5.h"
71 #include "warnless.h"
72 #include "curl_base64.h"
73 #include "curl_printf.h"
74
75 /* The last #include files should be: */
76 #include "curl_memory.h"
77 #include "memdebug.h"
78
79 /* convenience macro to check if this handle is using a shared SSL session */
80 #define SSLSESSION_SHARED(data) (data->share &&                        \
81                                  (data->share->specifier &             \
82                                   (1<<CURL_LOCK_DATA_SSL_SESSION)))
83
84 #define CLONE_STRING(var)                    \
85   if(source->var) {                          \
86     dest->var = strdup(source->var);         \
87     if(!dest->var)                           \
88       return FALSE;                          \
89   }                                          \
90   else                                       \
91     dest->var = NULL;
92
93 bool
94 Curl_ssl_config_matches(struct ssl_primary_config* data,
95                         struct ssl_primary_config* needle)
96 {
97   if((data->version == needle->version) &&
98      (data->verifypeer == needle->verifypeer) &&
99      (data->verifyhost == needle->verifyhost) &&
100      Curl_safe_strcasecompare(data->CApath, needle->CApath) &&
101      Curl_safe_strcasecompare(data->CAfile, needle->CAfile) &&
102      Curl_safe_strcasecompare(data->clientcert, needle->clientcert) &&
103      Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list))
104     return TRUE;
105
106   return FALSE;
107 }
108
109 bool
110 Curl_clone_primary_ssl_config(struct ssl_primary_config *source,
111                               struct ssl_primary_config *dest)
112 {
113   dest->verifyhost = source->verifyhost;
114   dest->verifypeer = source->verifypeer;
115   dest->version = source->version;
116
117   CLONE_STRING(CAfile);
118   CLONE_STRING(CApath);
119   CLONE_STRING(cipher_list);
120   CLONE_STRING(egdsocket);
121   CLONE_STRING(random_file);
122   CLONE_STRING(clientcert);
123   return TRUE;
124 }
125
126 void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc)
127 {
128   Curl_safefree(sslc->CAfile);
129   Curl_safefree(sslc->CApath);
130   Curl_safefree(sslc->cipher_list);
131   Curl_safefree(sslc->egdsocket);
132   Curl_safefree(sslc->random_file);
133   Curl_safefree(sslc->clientcert);
134 }
135
136 int Curl_ssl_backend(void)
137 {
138   return (int)CURL_SSL_BACKEND;
139 }
140
141 #ifdef USE_SSL
142
143 /* "global" init done? */
144 static bool init_ssl=FALSE;
145
146 /**
147  * Global SSL init
148  *
149  * @retval 0 error initializing SSL
150  * @retval 1 SSL initialized successfully
151  */
152 int Curl_ssl_init(void)
153 {
154   /* make sure this is only done once */
155   if(init_ssl)
156     return 1;
157   init_ssl = TRUE; /* never again */
158
159   return curlssl_init();
160 }
161
162
163 /* Global cleanup */
164 void Curl_ssl_cleanup(void)
165 {
166   if(init_ssl) {
167     /* only cleanup if we did a previous init */
168     curlssl_cleanup();
169     init_ssl = FALSE;
170   }
171 }
172
173 static bool ssl_prefs_check(struct Curl_easy *data)
174 {
175   /* check for CURLOPT_SSLVERSION invalid parameter value */
176   if((data->set.ssl.primary.version < 0)
177      || (data->set.ssl.primary.version >= CURL_SSLVERSION_LAST)) {
178     failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
179     return FALSE;
180   }
181   return TRUE;
182 }
183
184 static CURLcode
185 ssl_connect_init_proxy(struct connectdata *conn, int sockindex)
186 {
187   DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]);
188   if(ssl_connection_complete == conn->ssl[sockindex].state &&
189      !conn->proxy_ssl[sockindex].use) {
190 #if defined(HTTPS_PROXY_SUPPORT)
191     conn->proxy_ssl[sockindex] = conn->ssl[sockindex];
192     memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex]));
193 #else
194     return CURLE_NOT_BUILT_IN;
195 #endif
196   }
197   return CURLE_OK;
198 }
199
200 CURLcode
201 Curl_ssl_connect(struct connectdata *conn, int sockindex)
202 {
203   CURLcode result;
204
205   if(conn->bits.proxy_ssl_connected[sockindex]) {
206     result = ssl_connect_init_proxy(conn, sockindex);
207     if(result)
208       return result;
209   }
210
211   if(!ssl_prefs_check(conn->data))
212     return CURLE_SSL_CONNECT_ERROR;
213
214   /* mark this is being ssl-enabled from here on. */
215   conn->ssl[sockindex].use = TRUE;
216   conn->ssl[sockindex].state = ssl_connection_negotiating;
217
218   result = curlssl_connect(conn, sockindex);
219
220   if(!result)
221     Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
222
223   return result;
224 }
225
226 CURLcode
227 Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
228                              bool *done)
229 {
230   CURLcode result;
231   if(conn->bits.proxy_ssl_connected[sockindex]) {
232     result = ssl_connect_init_proxy(conn, sockindex);
233     if(result)
234       return result;
235   }
236
237   if(!ssl_prefs_check(conn->data))
238     return CURLE_SSL_CONNECT_ERROR;
239
240   /* mark this is being ssl requested from here on. */
241   conn->ssl[sockindex].use = TRUE;
242 #ifdef curlssl_connect_nonblocking
243   result = curlssl_connect_nonblocking(conn, sockindex, done);
244 #else
245   *done = TRUE; /* fallback to BLOCKING */
246   result = curlssl_connect(conn, sockindex);
247 #endif /* non-blocking connect support */
248   if(!result && *done)
249     Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
250   return result;
251 }
252
253 /*
254  * Lock shared SSL session data
255  */
256 void Curl_ssl_sessionid_lock(struct connectdata *conn)
257 {
258   if(SSLSESSION_SHARED(conn->data))
259     Curl_share_lock(conn->data,
260                     CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
261 }
262
263 /*
264  * Unlock shared SSL session data
265  */
266 void Curl_ssl_sessionid_unlock(struct connectdata *conn)
267 {
268   if(SSLSESSION_SHARED(conn->data))
269     Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION);
270 }
271
272 /*
273  * Check if there's a session ID for the given connection in the cache, and if
274  * there's one suitable, it is provided. Returns TRUE when no entry matched.
275  */
276 bool Curl_ssl_getsessionid(struct connectdata *conn,
277                            void **ssl_sessionid,
278                            size_t *idsize, /* set 0 if unknown */
279                            int sockindex)
280 {
281   struct curl_ssl_session *check;
282   struct Curl_easy *data = conn->data;
283   size_t i;
284   long *general_age;
285   bool no_match = TRUE;
286
287   const bool isProxy = CONNECT_PROXY_SSL();
288   struct ssl_primary_config * const ssl_config = isProxy ?
289     &conn->proxy_ssl_config :
290     &conn->ssl_config;
291   const char * const name = isProxy ? conn->http_proxy.host.name :
292     conn->host.name;
293   int port = isProxy ? (int)conn->port : conn->remote_port;
294   *ssl_sessionid = NULL;
295
296   DEBUGASSERT(data->set.general_ssl.sessionid);
297
298   if(!data->set.general_ssl.sessionid)
299     /* session ID re-use is disabled */
300     return TRUE;
301
302   /* Lock if shared */
303   if(SSLSESSION_SHARED(data))
304     general_age = &data->share->sessionage;
305   else
306     general_age = &data->state.sessionage;
307
308   for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
309     check = &data->state.session[i];
310     if(!check->sessionid)
311       /* not session ID means blank entry */
312       continue;
313     if(strcasecompare(name, check->name) &&
314        ((!conn->bits.conn_to_host && !check->conn_to_host) ||
315         (conn->bits.conn_to_host && check->conn_to_host &&
316          strcasecompare(conn->conn_to_host.name, check->conn_to_host))) &&
317        ((!conn->bits.conn_to_port && check->conn_to_port == -1) ||
318         (conn->bits.conn_to_port && check->conn_to_port != -1 &&
319          conn->conn_to_port == check->conn_to_port)) &&
320        (port == check->remote_port) &&
321        strcasecompare(conn->handler->scheme, check->scheme) &&
322        Curl_ssl_config_matches(ssl_config, &check->ssl_config)) {
323       /* yes, we have a session ID! */
324       (*general_age)++;          /* increase general age */
325       check->age = *general_age; /* set this as used in this age */
326       *ssl_sessionid = check->sessionid;
327       if(idsize)
328         *idsize = check->idsize;
329       no_match = FALSE;
330       break;
331     }
332   }
333
334   return no_match;
335 }
336
337 /*
338  * Kill a single session ID entry in the cache.
339  */
340 void Curl_ssl_kill_session(struct curl_ssl_session *session)
341 {
342   if(session->sessionid) {
343     /* defensive check */
344
345     /* free the ID the SSL-layer specific way */
346     curlssl_session_free(session->sessionid);
347
348     session->sessionid = NULL;
349     session->age = 0; /* fresh */
350
351     Curl_free_primary_ssl_config(&session->ssl_config);
352
353     Curl_safefree(session->name);
354     Curl_safefree(session->conn_to_host);
355   }
356 }
357
358 /*
359  * Delete the given session ID from the cache.
360  */
361 void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
362 {
363   size_t i;
364   struct Curl_easy *data=conn->data;
365
366   for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
367     struct curl_ssl_session *check = &data->state.session[i];
368
369     if(check->sessionid == ssl_sessionid) {
370       Curl_ssl_kill_session(check);
371       break;
372     }
373   }
374 }
375
376 /*
377  * Store session id in the session cache. The ID passed on to this function
378  * must already have been extracted and allocated the proper way for the SSL
379  * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
380  * later on.
381  */
382 CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
383                                void *ssl_sessionid,
384                                size_t idsize,
385                                int sockindex)
386 {
387   size_t i;
388   struct Curl_easy *data=conn->data; /* the mother of all structs */
389   struct curl_ssl_session *store = &data->state.session[0];
390   long oldest_age=data->state.session[0].age; /* zero if unused */
391   char *clone_host;
392   char *clone_conn_to_host;
393   int conn_to_port;
394   long *general_age;
395   const bool isProxy = CONNECT_PROXY_SSL();
396   struct ssl_primary_config * const ssl_config = isProxy ?
397     &conn->proxy_ssl_config :
398     &conn->ssl_config;
399
400   DEBUGASSERT(data->set.general_ssl.sessionid);
401
402   clone_host = strdup(isProxy ? conn->http_proxy.host.name : conn->host.name);
403   if(!clone_host)
404     return CURLE_OUT_OF_MEMORY; /* bail out */
405
406   if(conn->bits.conn_to_host) {
407     clone_conn_to_host = strdup(conn->conn_to_host.name);
408     if(!clone_conn_to_host) {
409       free(clone_host);
410       return CURLE_OUT_OF_MEMORY; /* bail out */
411     }
412   }
413   else
414     clone_conn_to_host = NULL;
415
416   if(conn->bits.conn_to_port)
417     conn_to_port = conn->conn_to_port;
418   else
419     conn_to_port = -1;
420
421   /* Now we should add the session ID and the host name to the cache, (remove
422      the oldest if necessary) */
423
424   /* If using shared SSL session, lock! */
425   if(SSLSESSION_SHARED(data)) {
426     general_age = &data->share->sessionage;
427   }
428   else {
429     general_age = &data->state.sessionage;
430   }
431
432   /* find an empty slot for us, or find the oldest */
433   for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) &&
434         data->state.session[i].sessionid; i++) {
435     if(data->state.session[i].age < oldest_age) {
436       oldest_age = data->state.session[i].age;
437       store = &data->state.session[i];
438     }
439   }
440   if(i == data->set.general_ssl.max_ssl_sessions)
441     /* cache is full, we must "kill" the oldest entry! */
442     Curl_ssl_kill_session(store);
443   else
444     store = &data->state.session[i]; /* use this slot */
445
446   /* now init the session struct wisely */
447   store->sessionid = ssl_sessionid;
448   store->idsize = idsize;
449   store->age = *general_age;    /* set current age */
450   /* free it if there's one already present */
451   free(store->name);
452   free(store->conn_to_host);
453   store->name = clone_host;               /* clone host name */
454   store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
455   store->conn_to_port = conn_to_port; /* connect to port number */
456   /* port number */
457   store->remote_port = isProxy ? (int)conn->port : conn->remote_port;
458   store->scheme = conn->handler->scheme;
459
460   if(!Curl_clone_primary_ssl_config(ssl_config, &store->ssl_config)) {
461     store->sessionid = NULL; /* let caller free sessionid */
462     free(clone_host);
463     free(clone_conn_to_host);
464     return CURLE_OUT_OF_MEMORY;
465   }
466
467   return CURLE_OK;
468 }
469
470
471 void Curl_ssl_close_all(struct Curl_easy *data)
472 {
473   size_t i;
474   /* kill the session ID cache if not shared */
475   if(data->state.session && !SSLSESSION_SHARED(data)) {
476     for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++)
477       /* the single-killer function handles empty table slots */
478       Curl_ssl_kill_session(&data->state.session[i]);
479
480     /* free the cache data */
481     Curl_safefree(data->state.session);
482   }
483
484   curlssl_close_all(data);
485 }
486
487 #if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
488   defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS) || \
489   defined(USE_MBEDTLS)
490 int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks,
491                      int numsocks)
492 {
493   struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
494
495   if(!numsocks)
496     return GETSOCK_BLANK;
497
498   if(connssl->connecting_state == ssl_connect_2_writing) {
499     /* write mode */
500     socks[0] = conn->sock[FIRSTSOCKET];
501     return GETSOCK_WRITESOCK(0);
502   }
503   else if(connssl->connecting_state == ssl_connect_2_reading) {
504     /* read mode */
505     socks[0] = conn->sock[FIRSTSOCKET];
506     return GETSOCK_READSOCK(0);
507   }
508
509   return GETSOCK_BLANK;
510 }
511 #else
512 int Curl_ssl_getsock(struct connectdata *conn,
513                      curl_socket_t *socks,
514                      int numsocks)
515 {
516   (void)conn;
517   (void)socks;
518   (void)numsocks;
519   return GETSOCK_BLANK;
520 }
521 /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL || USE_DARWINSSL || USE_NSS */
522 #endif
523
524 void Curl_ssl_close(struct connectdata *conn, int sockindex)
525 {
526   DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
527   curlssl_close(conn, sockindex);
528 }
529
530 CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
531 {
532   if(curlssl_shutdown(conn, sockindex))
533     return CURLE_SSL_SHUTDOWN_FAILED;
534
535   conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
536   conn->ssl[sockindex].state = ssl_connection_none;
537
538   conn->recv[sockindex] = Curl_recv_plain;
539   conn->send[sockindex] = Curl_send_plain;
540
541   return CURLE_OK;
542 }
543
544 /* Selects an SSL crypto engine
545  */
546 CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
547 {
548   return curlssl_set_engine(data, engine);
549 }
550
551 /* Selects the default SSL crypto engine
552  */
553 CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
554 {
555   return curlssl_set_engine_default(data);
556 }
557
558 /* Return list of OpenSSL crypto engine names. */
559 struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
560 {
561   return curlssl_engines_list(data);
562 }
563
564 /*
565  * This sets up a session ID cache to the specified size. Make sure this code
566  * is agnostic to what underlying SSL technology we use.
567  */
568 CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
569 {
570   struct curl_ssl_session *session;
571
572   if(data->state.session)
573     /* this is just a precaution to prevent multiple inits */
574     return CURLE_OK;
575
576   session = calloc(amount, sizeof(struct curl_ssl_session));
577   if(!session)
578     return CURLE_OUT_OF_MEMORY;
579
580   /* store the info in the SSL section */
581   data->set.general_ssl.max_ssl_sessions = amount;
582   data->state.session = session;
583   data->state.sessionage = 1; /* this is brand new */
584   return CURLE_OK;
585 }
586
587 size_t Curl_ssl_version(char *buffer, size_t size)
588 {
589   return curlssl_version(buffer, size);
590 }
591
592 /*
593  * This function tries to determine connection status.
594  *
595  * Return codes:
596  *     1 means the connection is still in place
597  *     0 means the connection has been closed
598  *    -1 means the connection status is unknown
599  */
600 int Curl_ssl_check_cxn(struct connectdata *conn)
601 {
602   return curlssl_check_cxn(conn);
603 }
604
605 bool Curl_ssl_data_pending(const struct connectdata *conn,
606                            int connindex)
607 {
608   return curlssl_data_pending(conn, connindex);
609 }
610
611 void Curl_ssl_free_certinfo(struct Curl_easy *data)
612 {
613   int i;
614   struct curl_certinfo *ci = &data->info.certs;
615
616   if(ci->num_of_certs) {
617     /* free all individual lists used */
618     for(i=0; i<ci->num_of_certs; i++) {
619       curl_slist_free_all(ci->certinfo[i]);
620       ci->certinfo[i] = NULL;
621     }
622
623     free(ci->certinfo); /* free the actual array too */
624     ci->certinfo = NULL;
625     ci->num_of_certs = 0;
626   }
627 }
628
629 CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
630 {
631   struct curl_certinfo *ci = &data->info.certs;
632   struct curl_slist **table;
633
634   /* Free any previous certificate information structures */
635   Curl_ssl_free_certinfo(data);
636
637   /* Allocate the required certificate information structures */
638   table = calloc((size_t) num, sizeof(struct curl_slist *));
639   if(!table)
640     return CURLE_OUT_OF_MEMORY;
641
642   ci->num_of_certs = num;
643   ci->certinfo = table;
644
645   return CURLE_OK;
646 }
647
648 /*
649  * 'value' is NOT a zero terminated string
650  */
651 CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
652                                     int certnum,
653                                     const char *label,
654                                     const char *value,
655                                     size_t valuelen)
656 {
657   struct curl_certinfo *ci = &data->info.certs;
658   char *output;
659   struct curl_slist *nl;
660   CURLcode result = CURLE_OK;
661   size_t labellen = strlen(label);
662   size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
663
664   output = malloc(outlen);
665   if(!output)
666     return CURLE_OUT_OF_MEMORY;
667
668   /* sprintf the label and colon */
669   snprintf(output, outlen, "%s:", label);
670
671   /* memcpy the value (it might not be zero terminated) */
672   memcpy(&output[labellen+1], value, valuelen);
673
674   /* zero terminate the output */
675   output[labellen + 1 + valuelen] = 0;
676
677   nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
678   if(!nl) {
679     free(output);
680     curl_slist_free_all(ci->certinfo[certnum]);
681     result = CURLE_OUT_OF_MEMORY;
682   }
683
684   ci->certinfo[certnum] = nl;
685   return result;
686 }
687
688 /*
689  * This is a convenience function for push_certinfo_len that takes a zero
690  * terminated value.
691  */
692 CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data,
693                                 int certnum,
694                                 const char *label,
695                                 const char *value)
696 {
697   size_t valuelen = strlen(value);
698
699   return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
700 }
701
702 CURLcode Curl_ssl_random(struct Curl_easy *data,
703                          unsigned char *entropy,
704                          size_t length)
705 {
706   return curlssl_random(data, entropy, length);
707 }
708
709 /*
710  * Public key pem to der conversion
711  */
712
713 static CURLcode pubkey_pem_to_der(const char *pem,
714                                   unsigned char **der, size_t *der_len)
715 {
716   char *stripped_pem, *begin_pos, *end_pos;
717   size_t pem_count, stripped_pem_count = 0, pem_len;
718   CURLcode result;
719
720   /* if no pem, exit. */
721   if(!pem)
722     return CURLE_BAD_CONTENT_ENCODING;
723
724   begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
725   if(!begin_pos)
726     return CURLE_BAD_CONTENT_ENCODING;
727
728   pem_count = begin_pos - pem;
729   /* Invalid if not at beginning AND not directly following \n */
730   if(0 != pem_count && '\n' != pem[pem_count - 1])
731     return CURLE_BAD_CONTENT_ENCODING;
732
733   /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
734   pem_count += 26;
735
736   /* Invalid if not directly following \n */
737   end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
738   if(!end_pos)
739     return CURLE_BAD_CONTENT_ENCODING;
740
741   pem_len = end_pos - pem;
742
743   stripped_pem = malloc(pem_len - pem_count + 1);
744   if(!stripped_pem)
745     return CURLE_OUT_OF_MEMORY;
746
747   /*
748    * Here we loop through the pem array one character at a time between the
749    * correct indices, and place each character that is not '\n' or '\r'
750    * into the stripped_pem array, which should represent the raw base64 string
751    */
752   while(pem_count < pem_len) {
753     if('\n' != pem[pem_count] && '\r' != pem[pem_count])
754       stripped_pem[stripped_pem_count++] = pem[pem_count];
755     ++pem_count;
756   }
757   /* Place the null terminator in the correct place */
758   stripped_pem[stripped_pem_count] = '\0';
759
760   result = Curl_base64_decode(stripped_pem, der, der_len);
761
762   Curl_safefree(stripped_pem);
763
764   return result;
765 }
766
767 /*
768  * Generic pinned public key check.
769  */
770
771 CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
772                               const char *pinnedpubkey,
773                               const unsigned char *pubkey, size_t pubkeylen)
774 {
775   FILE *fp;
776   unsigned char *buf = NULL, *pem_ptr = NULL;
777   long filesize;
778   size_t size, pem_len;
779   CURLcode pem_read;
780   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
781 #ifdef curlssl_sha256sum
782   CURLcode encode;
783   size_t encodedlen, pinkeylen;
784   char *encoded, *pinkeycopy, *begin_pos, *end_pos;
785   unsigned char *sha256sumdigest = NULL;
786 #endif
787
788   /* if a path wasn't specified, don't pin */
789   if(!pinnedpubkey)
790     return CURLE_OK;
791   if(!pubkey || !pubkeylen)
792     return result;
793
794   /* only do this if pinnedpubkey starts with "sha256//", length 8 */
795   if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
796 #ifdef curlssl_sha256sum
797     /* compute sha256sum of public key */
798     sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
799     if(!sha256sumdigest)
800       return CURLE_OUT_OF_MEMORY;
801     curlssl_sha256sum(pubkey, pubkeylen,
802                       sha256sumdigest, SHA256_DIGEST_LENGTH);
803     encode = Curl_base64_encode(data, (char *)sha256sumdigest,
804                                 SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
805     Curl_safefree(sha256sumdigest);
806
807     if(encode)
808       return encode;
809
810     infof(data, "\t public key hash: sha256//%s\n", encoded);
811
812     /* it starts with sha256//, copy so we can modify it */
813     pinkeylen = strlen(pinnedpubkey) + 1;
814     pinkeycopy = malloc(pinkeylen);
815     if(!pinkeycopy) {
816       Curl_safefree(encoded);
817       return CURLE_OUT_OF_MEMORY;
818     }
819     memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
820     /* point begin_pos to the copy, and start extracting keys */
821     begin_pos = pinkeycopy;
822     do {
823       end_pos = strstr(begin_pos, ";sha256//");
824       /*
825        * if there is an end_pos, null terminate,
826        * otherwise it'll go to the end of the original string
827        */
828       if(end_pos)
829         end_pos[0] = '\0';
830
831       /* compare base64 sha256 digests, 8 is the length of "sha256//" */
832       if(encodedlen == strlen(begin_pos + 8) &&
833          !memcmp(encoded, begin_pos + 8, encodedlen)) {
834         result = CURLE_OK;
835         break;
836       }
837
838       /*
839        * change back the null-terminator we changed earlier,
840        * and look for next begin
841        */
842       if(end_pos) {
843         end_pos[0] = ';';
844         begin_pos = strstr(end_pos, "sha256//");
845       }
846     } while(end_pos && begin_pos);
847     Curl_safefree(encoded);
848     Curl_safefree(pinkeycopy);
849 #else
850     /* without sha256 support, this cannot match */
851     (void)data;
852 #endif
853     return result;
854   }
855
856   fp = fopen(pinnedpubkey, "rb");
857   if(!fp)
858     return result;
859
860   do {
861     /* Determine the file's size */
862     if(fseek(fp, 0, SEEK_END))
863       break;
864     filesize = ftell(fp);
865     if(fseek(fp, 0, SEEK_SET))
866       break;
867     if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
868       break;
869
870     /*
871      * if the size of our certificate is bigger than the file
872      * size then it can't match
873      */
874     size = curlx_sotouz((curl_off_t) filesize);
875     if(pubkeylen > size)
876       break;
877
878     /*
879      * Allocate buffer for the pinned key
880      * With 1 additional byte for null terminator in case of PEM key
881      */
882     buf = malloc(size + 1);
883     if(!buf)
884       break;
885
886     /* Returns number of elements read, which should be 1 */
887     if((int) fread(buf, size, 1, fp) != 1)
888       break;
889
890     /* If the sizes are the same, it can't be base64 encoded, must be der */
891     if(pubkeylen == size) {
892       if(!memcmp(pubkey, buf, pubkeylen))
893         result = CURLE_OK;
894       break;
895     }
896
897     /*
898      * Otherwise we will assume it's PEM and try to decode it
899      * after placing null terminator
900      */
901     buf[size] = '\0';
902     pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
903     /* if it wasn't read successfully, exit */
904     if(pem_read)
905       break;
906
907     /*
908      * if the size of our certificate doesn't match the size of
909      * the decoded file, they can't be the same, otherwise compare
910      */
911     if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
912       result = CURLE_OK;
913   } while(0);
914
915   Curl_safefree(buf);
916   Curl_safefree(pem_ptr);
917   fclose(fp);
918
919   return result;
920 }
921
922 #ifndef CURL_DISABLE_CRYPTO_AUTH
923 CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
924                          size_t tmplen,
925                          unsigned char *md5sum, /* output */
926                          size_t md5len)
927 {
928 #ifdef curlssl_md5sum
929   curlssl_md5sum(tmp, tmplen, md5sum, md5len);
930 #else
931   MD5_context *MD5pw;
932
933   (void) md5len;
934
935   MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
936   if(!MD5pw)
937     return CURLE_OUT_OF_MEMORY;
938   Curl_MD5_update(MD5pw, tmp, curlx_uztoui(tmplen));
939   Curl_MD5_final(MD5pw, md5sum);
940 #endif
941   return CURLE_OK;
942 }
943 #endif
944
945 /*
946  * Check whether the SSL backend supports the status_request extension.
947  */
948 bool Curl_ssl_cert_status_request(void)
949 {
950 #ifdef curlssl_cert_status_request
951   return curlssl_cert_status_request();
952 #else
953   return FALSE;
954 #endif
955 }
956
957 /*
958  * Check whether the SSL backend supports false start.
959  */
960 bool Curl_ssl_false_start(void)
961 {
962 #ifdef curlssl_false_start
963   return curlssl_false_start();
964 #else
965   return FALSE;
966 #endif
967 }
968
969 #endif /* USE_SSL */