1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
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 http://curl.haxx.se/docs/copyright.html.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
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
27 SSL-functions in libcurl should call functions in this source file, and not
28 to any specific SSL-layer.
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_qssl_ - prefix for QsoSSL ones
35 Curl_gskit_ - prefix for GSKit ones
36 Curl_polarssl_ - prefix for PolarSSL ones
37 Curl_cyassl_ - prefix for CyaSSL ones
38 Curl_schannel_ - prefix for Schannel SSPI ones
39 Curl_darwinssl_ - prefix for SecureTransport (Darwin) ones
41 Note that this source code uses curlssl_* functions, and they are all
42 defines/macros #defined by the lib-specific header files.
44 "SSL/TLS Strong Encryption: An Introduction"
45 http://httpd.apache.org/docs-2.0/ssl/ssl_intro.html
48 #include "curl_setup.h"
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
53 #ifdef HAVE_SYS_STAT_H
62 #include "vtls.h" /* generic SSL protos etc */
63 #include "openssl.h" /* OpenSSL versions */
64 #include "gtls.h" /* GnuTLS versions */
65 #include "nssg.h" /* NSS versions */
66 #include "qssl.h" /* QSOSSL versions */
67 #include "gskit.h" /* Global Secure ToolKit versions */
68 #include "polarssl.h" /* PolarSSL versions */
69 #include "axtls.h" /* axTLS versions */
70 #include "cyassl.h" /* CyaSSL versions */
71 #include "curl_schannel.h" /* Schannel SSPI version */
72 #include "curl_darwinssl.h" /* SecureTransport (Darwin) version */
77 #include "curl_memory.h"
82 #define _MPRINTF_REPLACE /* use our functions only */
83 #include <curl/mprintf.h>
85 /* The last #include file should be: */
88 /* convenience macro to check if this handle is using a shared SSL session */
89 #define SSLSESSION_SHARED(data) (data->share && \
90 (data->share->specifier & \
91 (1<<CURL_LOCK_DATA_SSL_SESSION)))
93 static bool safe_strequal(char* str1, char* str2)
96 /* both pointers point to something then compare them */
97 return (0 != Curl_raw_equal(str1, str2)) ? TRUE : FALSE;
99 /* if both pointers are NULL then treat them as equal */
100 return (!str1 && !str2) ? TRUE : FALSE;
104 Curl_ssl_config_matches(struct ssl_config_data* data,
105 struct ssl_config_data* needle)
107 if((data->version == needle->version) &&
108 (data->verifypeer == needle->verifypeer) &&
109 (data->verifyhost == needle->verifyhost) &&
110 safe_strequal(data->CApath, needle->CApath) &&
111 safe_strequal(data->CAfile, needle->CAfile) &&
112 safe_strequal(data->random_file, needle->random_file) &&
113 safe_strequal(data->egdsocket, needle->egdsocket) &&
114 safe_strequal(data->cipher_list, needle->cipher_list))
121 Curl_clone_ssl_config(struct ssl_config_data *source,
122 struct ssl_config_data *dest)
124 dest->sessionid = source->sessionid;
125 dest->verifyhost = source->verifyhost;
126 dest->verifypeer = source->verifypeer;
127 dest->version = source->version;
130 dest->CAfile = strdup(source->CAfile);
138 dest->CApath = strdup(source->CApath);
145 if(source->cipher_list) {
146 dest->cipher_list = strdup(source->cipher_list);
147 if(!dest->cipher_list)
151 dest->cipher_list = NULL;
153 if(source->egdsocket) {
154 dest->egdsocket = strdup(source->egdsocket);
159 dest->egdsocket = NULL;
161 if(source->random_file) {
162 dest->random_file = strdup(source->random_file);
163 if(!dest->random_file)
167 dest->random_file = NULL;
172 void Curl_free_ssl_config(struct ssl_config_data* sslc)
174 Curl_safefree(sslc->CAfile);
175 Curl_safefree(sslc->CApath);
176 Curl_safefree(sslc->cipher_list);
177 Curl_safefree(sslc->egdsocket);
178 Curl_safefree(sslc->random_file);
183 * Curl_rand() returns a random unsigned integer, 32bit.
185 * This non-SSL function is put here only because this file is the only one
186 * with knowledge of what the underlying SSL libraries provide in terms of
189 * NOTE: 'data' may be passed in as NULL when coming from external API without
194 unsigned int Curl_rand(struct SessionHandle *data)
197 static unsigned int randseed;
198 static bool seeded = FALSE;
201 char *force_entropy = getenv("CURL_ENTROPY");
204 size_t elen = strlen(force_entropy);
205 size_t clen = sizeof(randseed);
206 size_t min = elen < clen ? elen : clen;
207 memcpy((char *)&randseed, force_entropy, min);
216 #ifndef have_curlssl_random
220 curlssl_random(data, (unsigned char *)&r, sizeof(r));
227 /* if there's a random file to read a seed from, use it */
228 int fd = open(RANDOM_FILE, O_RDONLY);
230 /* read random data into the randseed variable */
231 ssize_t nread = read(fd, &randseed, sizeof(randseed));
232 if(nread == sizeof(randseed))
240 struct timeval now = curlx_tvnow();
241 randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
242 randseed = randseed * 1103515245 + 12345;
243 randseed = randseed * 1103515245 + 12345;
244 randseed = randseed * 1103515245 + 12345;
248 /* Return an unsigned 32-bit pseudo-random number. */
249 r = randseed = randseed * 1103515245 + 12345;
250 return (r << 16) | ((r >> 16) & 0xFFFF);
255 /* "global" init done? */
256 static bool init_ssl=FALSE;
261 * @retval 0 error initializing SSL
262 * @retval 1 SSL initialized successfully
264 int Curl_ssl_init(void)
266 /* make sure this is only done once */
269 init_ssl = TRUE; /* never again */
271 return curlssl_init();
276 void Curl_ssl_cleanup(void)
279 /* only cleanup if we did a previous init */
286 Curl_ssl_connect(struct connectdata *conn, int sockindex)
289 /* mark this is being ssl-enabled from here on. */
290 conn->ssl[sockindex].use = TRUE;
291 conn->ssl[sockindex].state = ssl_connection_negotiating;
293 res = curlssl_connect(conn, sockindex);
296 Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
302 Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
306 /* mark this is being ssl requested from here on. */
307 conn->ssl[sockindex].use = TRUE;
308 #ifdef curlssl_connect_nonblocking
309 res = curlssl_connect_nonblocking(conn, sockindex, done);
311 *done = TRUE; /* fallback to BLOCKING */
312 res = curlssl_connect(conn, sockindex);
313 #endif /* non-blocking connect support */
315 Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
320 * Check if there's a session ID for the given connection in the cache, and if
321 * there's one suitable, it is provided. Returns TRUE when no entry matched.
323 int Curl_ssl_getsessionid(struct connectdata *conn,
324 void **ssl_sessionid,
325 size_t *idsize) /* set 0 if unknown */
327 struct curl_ssl_session *check;
328 struct SessionHandle *data = conn->data;
331 bool no_match = TRUE;
333 *ssl_sessionid = NULL;
335 if(!conn->ssl_config.sessionid)
336 /* session ID re-use is disabled */
340 if(SSLSESSION_SHARED(data)) {
341 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
342 general_age = &data->share->sessionage;
345 general_age = &data->state.sessionage;
347 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) {
348 check = &data->state.session[i];
349 if(!check->sessionid)
350 /* not session ID means blank entry */
352 if(Curl_raw_equal(conn->host.name, check->name) &&
353 (conn->remote_port == check->remote_port) &&
354 Curl_ssl_config_matches(&conn->ssl_config, &check->ssl_config)) {
355 /* yes, we have a session ID! */
356 (*general_age)++; /* increase general age */
357 check->age = *general_age; /* set this as used in this age */
358 *ssl_sessionid = check->sessionid;
360 *idsize = check->idsize;
367 if(SSLSESSION_SHARED(data))
368 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
374 * Kill a single session ID entry in the cache.
376 void Curl_ssl_kill_session(struct curl_ssl_session *session)
378 if(session->sessionid) {
379 /* defensive check */
381 /* free the ID the SSL-layer specific way */
382 curlssl_session_free(session->sessionid);
384 session->sessionid = NULL;
385 session->age = 0; /* fresh */
387 Curl_free_ssl_config(&session->ssl_config);
389 Curl_safefree(session->name);
394 * Delete the given session ID from the cache.
396 void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
399 struct SessionHandle *data=conn->data;
401 if(SSLSESSION_SHARED(data))
402 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
404 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) {
405 struct curl_ssl_session *check = &data->state.session[i];
407 if(check->sessionid == ssl_sessionid) {
408 Curl_ssl_kill_session(check);
413 if(SSLSESSION_SHARED(data))
414 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
418 * Store session id in the session cache. The ID passed on to this function
419 * must already have been extracted and allocated the proper way for the SSL
420 * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
423 CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
428 struct SessionHandle *data=conn->data; /* the mother of all structs */
429 struct curl_ssl_session *store = &data->state.session[0];
430 long oldest_age=data->state.session[0].age; /* zero if unused */
434 /* Even though session ID re-use might be disabled, that only disables USING
435 IT. We still store it here in case the re-using is again enabled for an
438 clone_host = strdup(conn->host.name);
440 return CURLE_OUT_OF_MEMORY; /* bail out */
442 /* Now we should add the session ID and the host name to the cache, (remove
443 the oldest if necessary) */
445 /* If using shared SSL session, lock! */
446 if(SSLSESSION_SHARED(data)) {
447 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
448 general_age = &data->share->sessionage;
451 general_age = &data->state.sessionage;
454 /* find an empty slot for us, or find the oldest */
455 for(i = 1; (i < data->set.ssl.max_ssl_sessions) &&
456 data->state.session[i].sessionid; i++) {
457 if(data->state.session[i].age < oldest_age) {
458 oldest_age = data->state.session[i].age;
459 store = &data->state.session[i];
462 if(i == data->set.ssl.max_ssl_sessions)
463 /* cache is full, we must "kill" the oldest entry! */
464 Curl_ssl_kill_session(store);
466 store = &data->state.session[i]; /* use this slot */
468 /* now init the session struct wisely */
469 store->sessionid = ssl_sessionid;
470 store->idsize = idsize;
471 store->age = *general_age; /* set current age */
473 /* free it if there's one already present */
475 store->name = clone_host; /* clone host name */
476 store->remote_port = conn->remote_port; /* port number */
480 if(SSLSESSION_SHARED(data))
481 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
483 if(!Curl_clone_ssl_config(&conn->ssl_config, &store->ssl_config)) {
484 store->sessionid = NULL; /* let caller free sessionid */
486 return CURLE_OUT_OF_MEMORY;
493 void Curl_ssl_close_all(struct SessionHandle *data)
496 /* kill the session ID cache if not shared */
497 if(data->state.session && !SSLSESSION_SHARED(data)) {
498 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++)
499 /* the single-killer function handles empty table slots */
500 Curl_ssl_kill_session(&data->state.session[i]);
502 /* free the cache data */
503 Curl_safefree(data->state.session);
506 curlssl_close_all(data);
509 void Curl_ssl_close(struct connectdata *conn, int sockindex)
511 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
512 curlssl_close(conn, sockindex);
515 CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
517 if(curlssl_shutdown(conn, sockindex))
518 return CURLE_SSL_SHUTDOWN_FAILED;
520 conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
521 conn->ssl[sockindex].state = ssl_connection_none;
523 conn->recv[sockindex] = Curl_recv_plain;
524 conn->send[sockindex] = Curl_send_plain;
529 /* Selects an SSL crypto engine
531 CURLcode Curl_ssl_set_engine(struct SessionHandle *data, const char *engine)
533 return curlssl_set_engine(data, engine);
536 /* Selects the default SSL crypto engine
538 CURLcode Curl_ssl_set_engine_default(struct SessionHandle *data)
540 return curlssl_set_engine_default(data);
543 /* Return list of OpenSSL crypto engine names. */
544 struct curl_slist *Curl_ssl_engines_list(struct SessionHandle *data)
546 return curlssl_engines_list(data);
550 * This sets up a session ID cache to the specified size. Make sure this code
551 * is agnostic to what underlying SSL technology we use.
553 CURLcode Curl_ssl_initsessions(struct SessionHandle *data, size_t amount)
555 struct curl_ssl_session *session;
557 if(data->state.session)
558 /* this is just a precaution to prevent multiple inits */
561 session = calloc(amount, sizeof(struct curl_ssl_session));
563 return CURLE_OUT_OF_MEMORY;
565 /* store the info in the SSL section */
566 data->set.ssl.max_ssl_sessions = amount;
567 data->state.session = session;
568 data->state.sessionage = 1; /* this is brand new */
572 size_t Curl_ssl_version(char *buffer, size_t size)
574 return curlssl_version(buffer, size);
578 * This function tries to determine connection status.
581 * 1 means the connection is still in place
582 * 0 means the connection has been closed
583 * -1 means the connection status is unknown
585 int Curl_ssl_check_cxn(struct connectdata *conn)
587 return curlssl_check_cxn(conn);
590 bool Curl_ssl_data_pending(const struct connectdata *conn,
593 return curlssl_data_pending(conn, connindex);
596 void Curl_ssl_free_certinfo(struct SessionHandle *data)
599 struct curl_certinfo *ci = &data->info.certs;
600 if(ci->num_of_certs) {
601 /* free all individual lists used */
602 for(i=0; i<ci->num_of_certs; i++) {
603 curl_slist_free_all(ci->certinfo[i]);
604 ci->certinfo[i] = NULL;
606 free(ci->certinfo); /* free the actual array too */
608 ci->num_of_certs = 0;
612 int Curl_ssl_init_certinfo(struct SessionHandle * data,
615 struct curl_certinfo * ci = &data->info.certs;
616 struct curl_slist * * table;
618 /* Initialize the certificate information structures. Return 0 if OK, else 1.
620 Curl_ssl_free_certinfo(data);
621 ci->num_of_certs = num;
622 table = calloc((size_t) num, sizeof(struct curl_slist *));
626 ci->certinfo = table;
631 * 'value' is NOT a zero terminated string
633 CURLcode Curl_ssl_push_certinfo_len(struct SessionHandle *data,
639 struct curl_certinfo * ci = &data->info.certs;
641 struct curl_slist * nl;
642 CURLcode res = CURLE_OK;
643 size_t labellen = strlen(label);
644 size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
646 output = malloc(outlen);
648 return CURLE_OUT_OF_MEMORY;
650 /* sprintf the label and colon */
651 snprintf(output, outlen, "%s:", label);
653 /* memcpy the value (it might not be zero terminated) */
654 memcpy(&output[labellen+1], value, valuelen);
656 /* zero terminate the output */
657 output[labellen + 1 + valuelen] = 0;
659 nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
662 curl_slist_free_all(ci->certinfo[certnum]);
663 res = CURLE_OUT_OF_MEMORY;
666 ci->certinfo[certnum] = nl;
671 * This is a convenience function for push_certinfo_len that takes a zero
674 CURLcode Curl_ssl_push_certinfo(struct SessionHandle *data,
679 size_t valuelen = strlen(value);
681 return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
684 #ifdef have_curlssl_md5sum
685 void Curl_ssl_md5sum(unsigned char *tmp, /* input */
687 unsigned char *md5sum, /* output */
690 curlssl_md5sum(tmp, tmplen, md5sum, md5len);