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