1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, 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 "sslgen.h" /* generic SSL protos etc */
63 #include "ssluse.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;
200 #ifndef have_curlssl_random
204 Curl_ssl_random(data, (unsigned char *)&r, sizeof(r));
211 /* if there's a random file to read a seed from, use it */
212 int fd = open(RANDOM_FILE, O_RDONLY);
214 /* read random data into the randseed variable */
215 ssize_t nread = read(fd, &randseed, sizeof(randseed));
216 if(nread == sizeof(randseed))
224 struct timeval now = curlx_tvnow();
225 randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
226 randseed = randseed * 1103515245 + 12345;
227 randseed = randseed * 1103515245 + 12345;
228 randseed = randseed * 1103515245 + 12345;
232 /* Return an unsigned 32-bit pseudo-random number. */
233 r = randseed = randseed * 1103515245 + 12345;
234 return (r << 16) | ((r >> 16) & 0xFFFF);
239 /* "global" init done? */
240 static bool init_ssl=FALSE;
245 * @retval 0 error initializing SSL
246 * @retval 1 SSL initialized successfully
248 int Curl_ssl_init(void)
250 /* make sure this is only done once */
253 init_ssl = TRUE; /* never again */
255 return curlssl_init();
260 void Curl_ssl_cleanup(void)
263 /* only cleanup if we did a previous init */
270 Curl_ssl_connect(struct connectdata *conn, int sockindex)
273 /* mark this is being ssl-enabled from here on. */
274 conn->ssl[sockindex].use = TRUE;
275 conn->ssl[sockindex].state = ssl_connection_negotiating;
277 res = curlssl_connect(conn, sockindex);
280 Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
286 Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
290 /* mark this is being ssl requested from here on. */
291 conn->ssl[sockindex].use = TRUE;
292 #ifdef curlssl_connect_nonblocking
293 res = curlssl_connect_nonblocking(conn, sockindex, done);
295 *done = TRUE; /* fallback to BLOCKING */
296 res = curlssl_connect(conn, sockindex);
297 #endif /* non-blocking connect support */
299 Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
304 * Check if there's a session ID for the given connection in the cache, and if
305 * there's one suitable, it is provided. Returns TRUE when no entry matched.
307 int Curl_ssl_getsessionid(struct connectdata *conn,
308 void **ssl_sessionid,
309 size_t *idsize) /* set 0 if unknown */
311 struct curl_ssl_session *check;
312 struct SessionHandle *data = conn->data;
315 bool no_match = TRUE;
317 *ssl_sessionid = NULL;
319 if(!conn->ssl_config.sessionid)
320 /* session ID re-use is disabled */
324 if(SSLSESSION_SHARED(data)) {
325 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
326 general_age = &data->share->sessionage;
329 general_age = &data->state.sessionage;
331 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) {
332 check = &data->state.session[i];
333 if(!check->sessionid)
334 /* not session ID means blank entry */
336 if(Curl_raw_equal(conn->host.name, check->name) &&
337 (conn->remote_port == check->remote_port) &&
338 Curl_ssl_config_matches(&conn->ssl_config, &check->ssl_config)) {
339 /* yes, we have a session ID! */
340 (*general_age)++; /* increase general age */
341 check->age = *general_age; /* set this as used in this age */
342 *ssl_sessionid = check->sessionid;
344 *idsize = check->idsize;
351 if(SSLSESSION_SHARED(data))
352 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
358 * Kill a single session ID entry in the cache.
360 void Curl_ssl_kill_session(struct curl_ssl_session *session)
362 if(session->sessionid) {
363 /* defensive check */
365 /* free the ID the SSL-layer specific way */
366 curlssl_session_free(session->sessionid);
368 session->sessionid = NULL;
369 session->age = 0; /* fresh */
371 Curl_free_ssl_config(&session->ssl_config);
373 Curl_safefree(session->name);
378 * Delete the given session ID from the cache.
380 void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
383 struct SessionHandle *data=conn->data;
385 if(SSLSESSION_SHARED(data))
386 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
388 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++) {
389 struct curl_ssl_session *check = &data->state.session[i];
391 if(check->sessionid == ssl_sessionid) {
392 Curl_ssl_kill_session(check);
397 if(SSLSESSION_SHARED(data))
398 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
402 * Store session id in the session cache. The ID passed on to this function
403 * must already have been extracted and allocated the proper way for the SSL
404 * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
407 CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
412 struct SessionHandle *data=conn->data; /* the mother of all structs */
413 struct curl_ssl_session *store = &data->state.session[0];
414 long oldest_age=data->state.session[0].age; /* zero if unused */
418 /* Even though session ID re-use might be disabled, that only disables USING
419 IT. We still store it here in case the re-using is again enabled for an
422 clone_host = strdup(conn->host.name);
424 return CURLE_OUT_OF_MEMORY; /* bail out */
426 /* Now we should add the session ID and the host name to the cache, (remove
427 the oldest if necessary) */
429 /* If using shared SSL session, lock! */
430 if(SSLSESSION_SHARED(data)) {
431 Curl_share_lock(data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
432 general_age = &data->share->sessionage;
435 general_age = &data->state.sessionage;
438 /* find an empty slot for us, or find the oldest */
439 for(i = 1; (i < data->set.ssl.max_ssl_sessions) &&
440 data->state.session[i].sessionid; i++) {
441 if(data->state.session[i].age < oldest_age) {
442 oldest_age = data->state.session[i].age;
443 store = &data->state.session[i];
446 if(i == data->set.ssl.max_ssl_sessions)
447 /* cache is full, we must "kill" the oldest entry! */
448 Curl_ssl_kill_session(store);
450 store = &data->state.session[i]; /* use this slot */
452 /* now init the session struct wisely */
453 store->sessionid = ssl_sessionid;
454 store->idsize = idsize;
455 store->age = *general_age; /* set current age */
457 /* free it if there's one already present */
459 store->name = clone_host; /* clone host name */
460 store->remote_port = conn->remote_port; /* port number */
464 if(SSLSESSION_SHARED(data))
465 Curl_share_unlock(data, CURL_LOCK_DATA_SSL_SESSION);
467 if(!Curl_clone_ssl_config(&conn->ssl_config, &store->ssl_config)) {
468 store->sessionid = NULL; /* let caller free sessionid */
470 return CURLE_OUT_OF_MEMORY;
477 void Curl_ssl_close_all(struct SessionHandle *data)
480 /* kill the session ID cache if not shared */
481 if(data->state.session && !SSLSESSION_SHARED(data)) {
482 for(i = 0; i < data->set.ssl.max_ssl_sessions; i++)
483 /* the single-killer function handles empty table slots */
484 Curl_ssl_kill_session(&data->state.session[i]);
486 /* free the cache data */
487 Curl_safefree(data->state.session);
490 curlssl_close_all(data);
493 void Curl_ssl_close(struct connectdata *conn, int sockindex)
495 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
496 curlssl_close(conn, sockindex);
499 CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
501 if(curlssl_shutdown(conn, sockindex))
502 return CURLE_SSL_SHUTDOWN_FAILED;
504 conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
505 conn->ssl[sockindex].state = ssl_connection_none;
507 conn->recv[sockindex] = Curl_recv_plain;
508 conn->send[sockindex] = Curl_send_plain;
513 /* Selects an SSL crypto engine
515 CURLcode Curl_ssl_set_engine(struct SessionHandle *data, const char *engine)
517 return curlssl_set_engine(data, engine);
520 /* Selects the default SSL crypto engine
522 CURLcode Curl_ssl_set_engine_default(struct SessionHandle *data)
524 return curlssl_set_engine_default(data);
527 /* Return list of OpenSSL crypto engine names. */
528 struct curl_slist *Curl_ssl_engines_list(struct SessionHandle *data)
530 return curlssl_engines_list(data);
534 * This sets up a session ID cache to the specified size. Make sure this code
535 * is agnostic to what underlying SSL technology we use.
537 CURLcode Curl_ssl_initsessions(struct SessionHandle *data, size_t amount)
539 struct curl_ssl_session *session;
541 if(data->state.session)
542 /* this is just a precaution to prevent multiple inits */
545 session = calloc(amount, sizeof(struct curl_ssl_session));
547 return CURLE_OUT_OF_MEMORY;
549 /* store the info in the SSL section */
550 data->set.ssl.max_ssl_sessions = amount;
551 data->state.session = session;
552 data->state.sessionage = 1; /* this is brand new */
556 size_t Curl_ssl_version(char *buffer, size_t size)
558 return curlssl_version(buffer, size);
562 * This function tries to determine connection status.
565 * 1 means the connection is still in place
566 * 0 means the connection has been closed
567 * -1 means the connection status is unknown
569 int Curl_ssl_check_cxn(struct connectdata *conn)
571 return curlssl_check_cxn(conn);
574 bool Curl_ssl_data_pending(const struct connectdata *conn,
577 return curlssl_data_pending(conn, connindex);
580 void Curl_ssl_free_certinfo(struct SessionHandle *data)
583 struct curl_certinfo *ci = &data->info.certs;
584 if(ci->num_of_certs) {
585 /* free all individual lists used */
586 for(i=0; i<ci->num_of_certs; i++) {
587 curl_slist_free_all(ci->certinfo[i]);
588 ci->certinfo[i] = NULL;
590 free(ci->certinfo); /* free the actual array too */
592 ci->num_of_certs = 0;
596 int Curl_ssl_init_certinfo(struct SessionHandle * data,
599 struct curl_certinfo * ci = &data->info.certs;
600 struct curl_slist * * table;
602 /* Initialize the certificate information structures. Return 0 if OK, else 1.
604 Curl_ssl_free_certinfo(data);
605 ci->num_of_certs = num;
606 table = calloc((size_t) num, sizeof(struct curl_slist *));
610 ci->certinfo = table;
614 CURLcode Curl_ssl_push_certinfo_len(struct SessionHandle *data,
620 struct curl_certinfo * ci = &data->info.certs;
622 struct curl_slist * nl;
623 CURLcode res = CURLE_OK;
625 /* Add an information record for a particular certificate. */
626 output = curl_maprintf("%s:%.*s", label, valuelen, value);
628 return CURLE_OUT_OF_MEMORY;
630 nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
633 curl_slist_free_all(ci->certinfo[certnum]);
634 res = CURLE_OUT_OF_MEMORY;
637 ci->certinfo[certnum] = nl;
642 * This is a convenience function for push_certinfo_len that takes a zero
645 CURLcode Curl_ssl_push_certinfo(struct SessionHandle *data,
650 size_t valuelen = strlen(value);
652 return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
655 /* these functions are only provided by some SSL backends */
657 #ifdef have_curlssl_random
658 void Curl_ssl_random(struct SessionHandle *data,
659 unsigned char *entropy,
662 curlssl_random(data, entropy, length);
666 #ifdef have_curlssl_md5sum
667 void Curl_ssl_md5sum(unsigned char *tmp, /* input */
669 unsigned char *md5sum, /* output */
672 curlssl_md5sum(tmp, tmplen, md5sum, md5len);