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