1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2009, 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 http://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 * $Id: ssluse.c,v 1.215 2009-01-26 14:36:22 bagder Exp $
22 ***************************************************************************/
23
24 /*
25 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
26 * but sslgen.c should ever call or use these functions.
27 */
28
29 /*
30 * The original SSLeay-using code for curl was written by Linas Vepstas and
31 * Sampo Kellomaki 1998.
32 */
33
34 #include "setup.h"
35
36 #include <string.h>
37 #include <stdlib.h>
38 #include <ctype.h>
39 #ifdef HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
42
43 #include "urldata.h"
44 #include "sendf.h"
45 #include "formdata.h" /* for the boundary function */
46 #include "url.h" /* for the ssl config check function */
47 #include "inet_pton.h"
48 #include "ssluse.h"
49 #include "connect.h"
50 #include "strequal.h"
51 #include "select.h"
52 #include "sslgen.h"
53 #include "rawstr.h"
54
55 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
56 #include <curl/mprintf.h>
57
58 #ifdef USE_SSLEAY
59
60 #ifdef USE_OPENSSL
61 #include <openssl/rand.h>
62 #include <openssl/x509v3.h>
63 #else
64 #include <rand.h>
65 #include <x509v3.h>
66 #endif
67
68 #include "memory.h"
69 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
70
71 /* The last #include file should be: */
72 #include "memdebug.h"
73
74 #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
75 #define HAVE_SSL_GET1_SESSION 1
76 #else
77 #undef HAVE_SSL_GET1_SESSION
78 #endif
79
80 #if OPENSSL_VERSION_NUMBER >= 0x00904100L
81 #define HAVE_USERDATA_IN_PWD_CALLBACK 1
82 #else
83 #undef HAVE_USERDATA_IN_PWD_CALLBACK
84 #endif
85
86 #if OPENSSL_VERSION_NUMBER >= 0x00907001L
87 /* ENGINE_load_private_key() takes four arguments */
88 #define HAVE_ENGINE_LOAD_FOUR_ARGS
89 #else
90 /* ENGINE_load_private_key() takes three arguments */
91 #undef HAVE_ENGINE_LOAD_FOUR_ARGS
92 #endif
93
94 #if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
95 /* OpenSSL has PKCS 12 support */
96 #define HAVE_PKCS12_SUPPORT
97 #else
98 /* OpenSSL/SSLEay does not have PKCS12 support */
99 #undef HAVE_PKCS12_SUPPORT
100 #endif
101
102 #if OPENSSL_VERSION_NUMBER >= 0x00906001L
103 #define HAVE_ERR_ERROR_STRING_N 1
104 #endif
105
106 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
107 #define SSL_METHOD_QUAL const
108 #else
109 #define SSL_METHOD_QUAL
110 #endif
111
112 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
113 /* 0.9.6 didn't have X509_STORE_set_flags() */
114 #define HAVE_X509_STORE_SET_FLAGS 1
115 #else
116 #define X509_STORE_set_flags(x,y)
117 #endif
118
119 /*
120 * Number of bytes to read from the random number seed file. This must be
121 * a finite value (because some entropy "files" like /dev/urandom have
122 * an infinite length), but must be large enough to provide enough
123 * entopy to properly seed OpenSSL's PRNG.
124 */
125 #define RAND_LOAD_LENGTH 1024
126
127 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
128 static char global_passwd[64];
129 #endif
130
passwd_callback(char * buf,int num,int verify,void * global_passwd)131 static int passwd_callback(char *buf, int num, int verify
132 #ifdef HAVE_USERDATA_IN_PWD_CALLBACK
133 /* This was introduced in 0.9.4, we can set this
134 using SSL_CTX_set_default_passwd_cb_userdata()
135 */
136 , void *global_passwd
137 #endif
138 )
139 {
140 if(verify)
141 fprintf(stderr, "%s\n", buf);
142 else {
143 if(num > (int)strlen((char *)global_passwd)) {
144 strcpy(buf, global_passwd);
145 return (int)strlen(buf);
146 }
147 }
148 return 0;
149 }
150
151 /*
152 * rand_enough() is a function that returns TRUE if we have seeded the random
153 * engine properly. We use some preprocessor magic to provide a seed_enough()
154 * macro to use, just to prevent a compiler warning on this function if we
155 * pass in an argument that is never used.
156 */
157
158 #ifdef HAVE_RAND_STATUS
159 #define seed_enough(x) rand_enough()
rand_enough(void)160 static bool rand_enough(void)
161 {
162 return (bool)(0 != RAND_status());
163 }
164 #else
165 #define seed_enough(x) rand_enough(x)
rand_enough(int nread)166 static bool rand_enough(int nread)
167 {
168 /* this is a very silly decision to make */
169 return (bool)(nread > 500);
170 }
171 #endif
172
ossl_seed(struct SessionHandle * data)173 static int ossl_seed(struct SessionHandle *data)
174 {
175 char *buf = data->state.buffer; /* point to the big buffer */
176 int nread=0;
177
178 /* Q: should we add support for a random file name as a libcurl option?
179 A: Yes, it is here */
180
181 #ifndef RANDOM_FILE
182 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
183 us to! */
184 if(data->set.ssl.random_file)
185 #define RANDOM_FILE "" /* doesn't matter won't be used */
186 #endif
187 {
188 /* let the option override the define */
189 nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
190 data->set.str[STRING_SSL_RANDOM_FILE]:
191 RANDOM_FILE),
192 RAND_LOAD_LENGTH);
193 if(seed_enough(nread))
194 return nread;
195 }
196
197 #if defined(HAVE_RAND_EGD)
198 /* only available in OpenSSL 0.9.5 and later */
199 /* EGD_SOCKET is set at configure time or not at all */
200 #ifndef EGD_SOCKET
201 /* If we don't have the define set, we only do this if the egd-option
202 is set */
203 if(data->set.str[STRING_SSL_EGDSOCKET])
204 #define EGD_SOCKET "" /* doesn't matter won't be used */
205 #endif
206 {
207 /* If there's an option and a define, the option overrides the
208 define */
209 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
210 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
211 if(-1 != ret) {
212 nread += ret;
213 if(seed_enough(nread))
214 return nread;
215 }
216 }
217 #endif
218
219 /* If we get here, it means we need to seed the PRNG using a "silly"
220 approach! */
221 #ifdef HAVE_RAND_SCREEN
222 /* This one gets a random value by reading the currently shown screen */
223 RAND_screen();
224 nread = 100; /* just a value */
225 #else
226 {
227 int len;
228 char *area;
229
230 /* Changed call to RAND_seed to use the underlying RAND_add implementation
231 * directly. Do this in a loop, with the amount of additional entropy
232 * being dependent upon the algorithm used by Curl_FormBoundary(): N bytes
233 * of a 7-bit ascii set. -- Richard Gorton, March 11 2003.
234 */
235
236 do {
237 area = Curl_FormBoundary();
238 if(!area)
239 return 3; /* out of memory */
240
241 len = (int)strlen(area);
242 RAND_add(area, len, (len >> 1));
243
244 free(area); /* now remove the random junk */
245 } while(!RAND_status());
246 }
247 #endif
248
249 /* generates a default path for the random seed file */
250 buf[0]=0; /* blank it first */
251 RAND_file_name(buf, BUFSIZE);
252 if(buf[0]) {
253 /* we got a file name to try */
254 nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
255 if(seed_enough(nread))
256 return nread;
257 }
258
259 infof(data, "libcurl is now using a weak random seed!\n");
260 return nread;
261 }
262
Curl_ossl_seed(struct SessionHandle * data)263 int Curl_ossl_seed(struct SessionHandle *data)
264 {
265 /* we have the "SSL is seeded" boolean static to prevent multiple
266 time-consuming seedings in vain */
267 static bool ssl_seeded = FALSE;
268
269 if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
270 data->set.str[STRING_SSL_EGDSOCKET]) {
271 ossl_seed(data);
272 ssl_seeded = TRUE;
273 }
274 return 0;
275 }
276
277
278 #ifndef SSL_FILETYPE_ENGINE
279 #define SSL_FILETYPE_ENGINE 42
280 #endif
281 #ifndef SSL_FILETYPE_PKCS12
282 #define SSL_FILETYPE_PKCS12 43
283 #endif
do_file_type(const char * type)284 static int do_file_type(const char *type)
285 {
286 if(!type || !type[0])
287 return SSL_FILETYPE_PEM;
288 if(Curl_raw_equal(type, "PEM"))
289 return SSL_FILETYPE_PEM;
290 if(Curl_raw_equal(type, "DER"))
291 return SSL_FILETYPE_ASN1;
292 if(Curl_raw_equal(type, "ENG"))
293 return SSL_FILETYPE_ENGINE;
294 if(Curl_raw_equal(type, "P12"))
295 return SSL_FILETYPE_PKCS12;
296 return -1;
297 }
298
299 static
cert_stuff(struct connectdata * conn,SSL_CTX * ctx,char * cert_file,const char * cert_type,char * key_file,const char * key_type)300 int cert_stuff(struct connectdata *conn,
301 SSL_CTX* ctx,
302 char *cert_file,
303 const char *cert_type,
304 char *key_file,
305 const char *key_type)
306 {
307 struct SessionHandle *data = conn->data;
308 int file_type;
309
310 if(cert_file != NULL) {
311 SSL *ssl;
312 X509 *x509;
313 int cert_done = 0;
314
315 if(data->set.str[STRING_KEY_PASSWD]) {
316 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
317 /*
318 * If password has been given, we store that in the global
319 * area (*shudder*) for a while:
320 */
321 size_t len = strlen(data->set.key_passwd);
322 if(len < sizeof(global_passwd))
323 memcpy(global_passwd, data->set.key_passwd, len+1);
324 #else
325 /*
326 * We set the password in the callback userdata
327 */
328 SSL_CTX_set_default_passwd_cb_userdata(ctx,
329 data->set.str[STRING_KEY_PASSWD]);
330 #endif
331 /* Set passwd callback: */
332 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
333 }
334
335 file_type = do_file_type(cert_type);
336
337 #define SSL_CLIENT_CERT_ERR \
338 "unable to use client certificate (no key found or wrong pass phrase?)"
339
340 switch(file_type) {
341 case SSL_FILETYPE_PEM:
342 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
343 if(SSL_CTX_use_certificate_chain_file(ctx,
344 cert_file) != 1) {
345 failf(data, SSL_CLIENT_CERT_ERR);
346 return 0;
347 }
348 break;
349
350 case SSL_FILETYPE_ASN1:
351 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
352 we use the case above for PEM so this can only be performed with
353 ASN1 files. */
354 if(SSL_CTX_use_certificate_file(ctx,
355 cert_file,
356 file_type) != 1) {
357 failf(data, SSL_CLIENT_CERT_ERR);
358 return 0;
359 }
360 break;
361 case SSL_FILETYPE_ENGINE:
362 failf(data, "file type ENG for certificate not implemented");
363 return 0;
364
365 case SSL_FILETYPE_PKCS12:
366 {
367 #ifdef HAVE_PKCS12_SUPPORT
368 FILE *f;
369 PKCS12 *p12;
370 EVP_PKEY *pri;
371 STACK_OF(X509) *ca = NULL;
372 int i;
373
374 f = fopen(cert_file,"rb");
375 if(!f) {
376 failf(data, "could not open PKCS12 file '%s'", cert_file);
377 return 0;
378 }
379 p12 = d2i_PKCS12_fp(f, NULL);
380 fclose(f);
381
382 if(!p12) {
383 failf(data, "error reading PKCS12 file '%s'", cert_file );
384 return 0;
385 }
386
387 PKCS12_PBE_add();
388
389 if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509,
390 &ca)) {
391 failf(data,
392 "could not parse PKCS12 file, check password, OpenSSL error %s",
393 ERR_error_string(ERR_get_error(), NULL) );
394 PKCS12_free(p12);
395 return 0;
396 }
397
398 PKCS12_free(p12);
399
400 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
401 failf(data, SSL_CLIENT_CERT_ERR);
402 EVP_PKEY_free(pri);
403 X509_free(x509);
404 return 0;
405 }
406
407 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
408 failf(data, "unable to use private key from PKCS12 file '%s'",
409 cert_file);
410 EVP_PKEY_free(pri);
411 X509_free(x509);
412 return 0;
413 }
414
415 if (!SSL_CTX_check_private_key (ctx)) {
416 failf(data, "private key from PKCS12 file '%s' "
417 "does not match certificate in same file", cert_file);
418 EVP_PKEY_free(pri);
419 X509_free(x509);
420 return 0;
421 }
422 /* Set Certificate Verification chain */
423 if (ca && sk_num(ca)) {
424 for (i = 0; i < sk_X509_num(ca); i++) {
425 if (!SSL_CTX_add_extra_chain_cert(ctx,sk_X509_value(ca, i))) {
426 failf(data, "cannot add certificate to certificate chain");
427 EVP_PKEY_free(pri);
428 X509_free(x509);
429 return 0;
430 }
431 if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i))) {
432 failf(data, "cannot add certificate to client CA list",
433 cert_file);
434 EVP_PKEY_free(pri);
435 X509_free(x509);
436 return 0;
437 }
438 }
439 }
440
441 EVP_PKEY_free(pri);
442 X509_free(x509);
443 cert_done = 1;
444 break;
445 #else
446 failf(data, "file type P12 for certificate not supported");
447 return 0;
448 #endif
449 }
450 default:
451 failf(data, "not supported file type '%s' for certificate", cert_type);
452 return 0;
453 }
454
455 file_type = do_file_type(key_type);
456
457 switch(file_type) {
458 case SSL_FILETYPE_PEM:
459 if(cert_done)
460 break;
461 if(key_file == NULL)
462 /* cert & key can only be in PEM case in the same file */
463 key_file=cert_file;
464 case SSL_FILETYPE_ASN1:
465 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
466 failf(data, "unable to set private key file: '%s' type %s",
467 key_file, key_type?key_type:"PEM");
468 return 0;
469 }
470 break;
471 case SSL_FILETYPE_ENGINE:
472 #ifdef HAVE_OPENSSL_ENGINE_H
473 { /* XXXX still needs some work */
474 EVP_PKEY *priv_key = NULL;
475 if(data->state.engine) {
476 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
477 UI_METHOD *ui_method = UI_OpenSSL();
478 #endif
479 if(!key_file || !key_file[0]) {
480 failf(data, "no key set to load from crypto engine");
481 return 0;
482 }
483 /* the typecast below was added to please mingw32 */
484 priv_key = (EVP_PKEY *)
485 ENGINE_load_private_key(data->state.engine,key_file,
486 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
487 ui_method,
488 #endif
489 data->set.str[STRING_KEY_PASSWD]);
490 if(!priv_key) {
491 failf(data, "failed to load private key from crypto engine");
492 return 0;
493 }
494 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
495 failf(data, "unable to set private key");
496 EVP_PKEY_free(priv_key);
497 return 0;
498 }
499 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
500 }
501 else {
502 failf(data, "crypto engine not set, can't load private key");
503 return 0;
504 }
505 }
506 break;
507 #else
508 failf(data, "file type ENG for private key not supported");
509 return 0;
510 #endif
511 case SSL_FILETYPE_PKCS12:
512 if(!cert_done) {
513 failf(data, "file type P12 for private key not supported");
514 return 0;
515 }
516 break;
517 default:
518 failf(data, "not supported file type for private key");
519 return 0;
520 }
521
522 ssl=SSL_new(ctx);
523 if(NULL == ssl) {
524 failf(data,"unable to create an SSL structure");
525 return 0;
526 }
527
528 x509=SSL_get_certificate(ssl);
529
530 /* This version was provided by Evan Jordan and is supposed to not
531 leak memory as the previous version: */
532 if(x509 != NULL) {
533 EVP_PKEY *pktmp = X509_get_pubkey(x509);
534 EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
535 EVP_PKEY_free(pktmp);
536 }
537
538 SSL_free(ssl);
539
540 /* If we are using DSA, we can copy the parameters from
541 * the private key */
542
543
544 /* Now we know that a key and cert have been set against
545 * the SSL context */
546 if(!SSL_CTX_check_private_key(ctx)) {
547 failf(data, "Private key does not match the certificate public key");
548 return(0);
549 }
550 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
551 /* erase it now */
552 memset(global_passwd, 0, sizeof(global_passwd));
553 #endif
554 }
555 return(1);
556 }
557
558 /* returns non-zero on failure */
x509_name_oneline(X509_NAME * a,char * buf,size_t size)559 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
560 {
561 #if 0
562 return X509_NAME_oneline(a, buf, size);
563 #else
564 BIO *bio_out = BIO_new(BIO_s_mem());
565 BUF_MEM *biomem;
566 int rc;
567
568 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_CPLUS_SPC);
569 BIO_get_mem_ptr(bio_out, &biomem);
570
571 if((size_t)biomem->length < size)
572 size = biomem->length;
573 else
574 size--; /* don't overwrite the buffer end */
575
576 memcpy(buf, biomem->data, size);
577 buf[size]=0;
578
579 BIO_free(bio_out);
580
581 return !rc;
582 #endif
583 }
584
585 static
cert_verify_callback(int ok,X509_STORE_CTX * ctx)586 int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
587 {
588 X509 *err_cert;
589 char buf[256];
590
591 err_cert=X509_STORE_CTX_get_current_cert(ctx);
592 (void)x509_name_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
593 return ok;
594 }
595
596 /* Return error string for last OpenSSL error
597 */
SSL_strerror(unsigned long error,char * buf,size_t size)598 static char *SSL_strerror(unsigned long error, char *buf, size_t size)
599 {
600 #ifdef HAVE_ERR_ERROR_STRING_N
601 /* OpenSSL 0.9.6 and later has a function named
602 ERRO_error_string_n() that takes the size of the buffer as a
603 third argument */
604 ERR_error_string_n(error, buf, size);
605 #else
606 (void) size;
607 ERR_error_string(error, buf);
608 #endif
609 return (buf);
610 }
611
612 #endif /* USE_SSLEAY */
613
614 #ifdef USE_SSLEAY
615 /**
616 * Global SSL init
617 *
618 * @retval 0 error initializing SSL
619 * @retval 1 SSL initialized successfully
620 */
Curl_ossl_init(void)621 int Curl_ossl_init(void)
622 {
623 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
624 ENGINE_load_builtin_engines();
625 #endif
626
627 /* Lets get nice error messages */
628 SSL_load_error_strings();
629
630 /* Setup all the global SSL stuff */
631 if(!SSLeay_add_ssl_algorithms())
632 return 0;
633
634 return 1;
635 }
636
637 #endif /* USE_SSLEAY */
638
639 #ifdef USE_SSLEAY
640
641 /* Global cleanup */
Curl_ossl_cleanup(void)642 void Curl_ossl_cleanup(void)
643 {
644 /* Free the SSL error strings */
645 ERR_free_strings();
646
647 /* EVP_cleanup() removes all ciphers and digests from the
648 table. */
649 EVP_cleanup();
650
651 #ifdef HAVE_ENGINE_cleanup
652 ENGINE_cleanup();
653 #endif
654
655 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
656 /* this function was not present in 0.9.6b, but was added sometimes
657 later */
658 CRYPTO_cleanup_all_ex_data();
659 #endif
660 }
661
662 /*
663 * This function uses SSL_peek to determine connection status.
664 *
665 * Return codes:
666 * 1 means the connection is still in place
667 * 0 means the connection has been closed
668 * -1 means the connection status is unknown
669 */
Curl_ossl_check_cxn(struct connectdata * conn)670 int Curl_ossl_check_cxn(struct connectdata *conn)
671 {
672 int rc;
673 char buf;
674
675 rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1);
676 if(rc > 0)
677 return 1; /* connection still in place */
678
679 if(rc == 0)
680 return 0; /* connection has been closed */
681
682 return -1; /* connection status unknown */
683 }
684
685 /* Selects an OpenSSL crypto engine
686 */
Curl_ossl_set_engine(struct SessionHandle * data,const char * engine)687 CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
688 {
689 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
690 ENGINE *e = ENGINE_by_id(engine);
691
692 if(!e) {
693 failf(data, "SSL Engine '%s' not found", engine);
694 return (CURLE_SSL_ENGINE_NOTFOUND);
695 }
696
697 if(data->state.engine) {
698 ENGINE_finish(data->state.engine);
699 ENGINE_free(data->state.engine);
700 data->state.engine = NULL;
701 }
702 if(!ENGINE_init(e)) {
703 char buf[256];
704
705 ENGINE_free(e);
706 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
707 engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
708 return (CURLE_SSL_ENGINE_INITFAILED);
709 }
710 data->state.engine = e;
711 return (CURLE_OK);
712 #else
713 (void)engine;
714 failf(data, "SSL Engine not supported");
715 return (CURLE_SSL_ENGINE_NOTFOUND);
716 #endif
717 }
718
719 /* Sets engine as default for all SSL operations
720 */
Curl_ossl_set_engine_default(struct SessionHandle * data)721 CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
722 {
723 #ifdef HAVE_OPENSSL_ENGINE_H
724 if(data->state.engine) {
725 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
726 infof(data,"set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine));
727 }
728 else {
729 failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine));
730 return CURLE_SSL_ENGINE_SETFAILED;
731 }
732 }
733 #else
734 (void) data;
735 #endif
736 return CURLE_OK;
737 }
738
739 /* Return list of OpenSSL crypto engine names.
740 */
Curl_ossl_engines_list(struct SessionHandle * data)741 struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
742 {
743 struct curl_slist *list = NULL;
744 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
745 struct curl_slist *beg = NULL;
746 ENGINE *e;
747
748 for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
749 list = curl_slist_append(list, ENGINE_get_id(e));
750 if(list == NULL) {
751 curl_slist_free_all(beg);
752 return NULL;
753 }
754 else if(beg == NULL) {
755 beg = list;
756 }
757 }
758 #endif
759 (void) data;
760 return (list);
761 }
762
763
764 /*
765 * This function is called when an SSL connection is closed.
766 */
Curl_ossl_close(struct connectdata * conn,int sockindex)767 void Curl_ossl_close(struct connectdata *conn, int sockindex)
768 {
769 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
770
771 if(connssl->handle) {
772 (void)SSL_shutdown(connssl->handle);
773 SSL_set_connect_state(connssl->handle);
774
775 SSL_free (connssl->handle);
776 connssl->handle = NULL;
777 }
778 if(connssl->ctx) {
779 SSL_CTX_free (connssl->ctx);
780 connssl->ctx = NULL;
781 }
782 }
783
784 /*
785 * This function is called to shut down the SSL layer but keep the
786 * socket open (CCC - Clear Command Channel)
787 */
Curl_ossl_shutdown(struct connectdata * conn,int sockindex)788 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
789 {
790 int retval = 0;
791 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
792 struct SessionHandle *data = conn->data;
793 char buf[120]; /* We will use this for the OpenSSL error buffer, so it has
794 to be at least 120 bytes long. */
795 unsigned long sslerror;
796 ssize_t nread;
797 int err;
798 int done = 0;
799
800 /* This has only been tested on the proftpd server, and the mod_tls code
801 sends a close notify alert without waiting for a close notify alert in
802 response. Thus we wait for a close notify alert from the server, but
803 we do not send one. Let's hope other servers do the same... */
804
805 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
806 (void)SSL_shutdown(connssl->handle);
807
808 if(connssl->handle) {
809 while(!done) {
810 int what = Curl_socket_ready(conn->sock[sockindex],
811 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
812 if(what > 0) {
813 /* Something to read, let's do it and hope that it is the close
814 notify alert from the server */
815 nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
816 sizeof(buf));
817 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
818
819 switch(err) {
820 case SSL_ERROR_NONE: /* this is not an error */
821 case SSL_ERROR_ZERO_RETURN: /* no more data */
822 /* This is the expected response. There was no data but only
823 the close notify alert */
824 done = 1;
825 break;
826 case SSL_ERROR_WANT_READ:
827 /* there's data pending, re-invoke SSL_read() */
828 infof(data, "SSL_ERROR_WANT_READ\n");
829 break;
830 case SSL_ERROR_WANT_WRITE:
831 /* SSL wants a write. Really odd. Let's bail out. */
832 infof(data, "SSL_ERROR_WANT_WRITE\n");
833 done = 1;
834 break;
835 default:
836 /* openssl/ssl.h says "look at error stack/return value/errno" */
837 sslerror = ERR_get_error();
838 failf(conn->data, "SSL read: %s, errno %d",
839 ERR_error_string(sslerror, buf),
840 SOCKERRNO);
841 done = 1;
842 break;
843 }
844 }
845 else if(0 == what) {
846 /* timeout */
847 failf(data, "SSL shutdown timeout");
848 done = 1;
849 break;
850 }
851 else {
852 /* anything that gets here is fatally bad */
853 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
854 retval = -1;
855 done = 1;
856 }
857 } /* while()-loop for the select() */
858
859 if(data->set.verbose) {
860 #ifdef HAVE_SSL_GET_SHUTDOWN
861 switch(SSL_get_shutdown(connssl->handle)) {
862 case SSL_SENT_SHUTDOWN:
863 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
864 break;
865 case SSL_RECEIVED_SHUTDOWN:
866 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
867 break;
868 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
869 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
870 "SSL_RECEIVED__SHUTDOWN\n");
871 break;
872 }
873 #endif
874 }
875
876 SSL_free (connssl->handle);
877 connssl->handle = NULL;
878 }
879 return retval;
880 }
881
Curl_ossl_session_free(void * ptr)882 void Curl_ossl_session_free(void *ptr)
883 {
884 /* free the ID */
885 SSL_SESSION_free(ptr);
886 }
887
888 /*
889 * This function is called when the 'data' struct is going away. Close
890 * down everything and free all resources!
891 */
Curl_ossl_close_all(struct SessionHandle * data)892 int Curl_ossl_close_all(struct SessionHandle *data)
893 {
894 /*
895 ERR_remove_state() frees the error queue associated with
896 thread pid. If pid == 0, the current thread will have its
897 error queue removed.
898
899 Since error queue data structures are allocated
900 automatically for new threads, they must be freed when
901 threads are terminated in oder to avoid memory leaks.
902 */
903 ERR_remove_state(0);
904
905 #ifdef HAVE_OPENSSL_ENGINE_H
906 if(data->state.engine) {
907 ENGINE_finish(data->state.engine);
908 ENGINE_free(data->state.engine);
909 data->state.engine = NULL;
910 }
911 #else
912 (void)data;
913 #endif
914 return 0;
915 }
916
asn1_output(const ASN1_UTCTIME * tm,char * buf,size_t sizeofbuf)917 static int asn1_output(const ASN1_UTCTIME *tm,
918 char *buf,
919 size_t sizeofbuf)
920 {
921 const char *asn1_string;
922 int gmt=FALSE;
923 int i;
924 int year=0,month=0,day=0,hour=0,minute=0,second=0;
925
926 i=tm->length;
927 asn1_string=(const char *)tm->data;
928
929 if(i < 10)
930 return 1;
931 if(asn1_string[i-1] == 'Z')
932 gmt=TRUE;
933 for (i=0; i<10; i++)
934 if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
935 return 2;
936
937 year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
938 if(year < 50)
939 year+=100;
940
941 month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
942 if((month > 12) || (month < 1))
943 return 3;
944
945 day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
946 hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
947 minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
948
949 if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
950 (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
951 second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
952
953 snprintf(buf, sizeofbuf,
954 "%04d-%02d-%02d %02d:%02d:%02d %s",
955 year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
956
957 return 0;
958 }
959
960 /* ====================================================== */
961
962 /*
963 * Match a hostname against a wildcard pattern.
964 * E.g.
965 * "foo.host.com" matches "*.host.com".
966 *
967 * We are a bit more liberal than RFC2818 describes in that we
968 * accept multiple "*" in pattern (similar to what some other browsers do).
969 * E.g.
970 * "abc.def.domain.com" should strickly not match "*.domain.com", but we
971 * don't consider "." to be important in CERT checking.
972 */
973 #define HOST_NOMATCH 0
974 #define HOST_MATCH 1
975
hostmatch(const char * hostname,const char * pattern)976 static int hostmatch(const char *hostname, const char *pattern)
977 {
978 while(1) {
979 char c = *pattern++;
980
981 if(c == '\0')
982 return (*hostname ? HOST_NOMATCH : HOST_MATCH);
983
984 if(c == '*') {
985 c = *pattern;
986 if(c == '\0') /* "*\0" matches anything remaining */
987 return HOST_MATCH;
988
989 while(*hostname) {
990 /* The only recursive function in libcurl! */
991 if(hostmatch(hostname++,pattern) == HOST_MATCH)
992 return HOST_MATCH;
993 }
994 break;
995 }
996
997 if(Curl_raw_toupper(c) != Curl_raw_toupper(*hostname++))
998 break;
999 }
1000 return HOST_NOMATCH;
1001 }
1002
1003 static int
cert_hostcheck(const char * match_pattern,const char * hostname)1004 cert_hostcheck(const char *match_pattern, const char *hostname)
1005 {
1006 if(!match_pattern || !*match_pattern ||
1007 !hostname || !*hostname) /* sanity check */
1008 return 0;
1009
1010 if(Curl_raw_equal(hostname, match_pattern)) /* trivial case */
1011 return 1;
1012
1013 if(hostmatch(hostname,match_pattern) == HOST_MATCH)
1014 return 1;
1015 return 0;
1016 }
1017
1018 /* Quote from RFC2818 section 3.1 "Server Identity"
1019
1020 If a subjectAltName extension of type dNSName is present, that MUST
1021 be used as the identity. Otherwise, the (most specific) Common Name
1022 field in the Subject field of the certificate MUST be used. Although
1023 the use of the Common Name is existing practice, it is deprecated and
1024 Certification Authorities are encouraged to use the dNSName instead.
1025
1026 Matching is performed using the matching rules specified by
1027 [RFC2459]. If more than one identity of a given type is present in
1028 the certificate (e.g., more than one dNSName name, a match in any one
1029 of the set is considered acceptable.) Names may contain the wildcard
1030 character * which is considered to match any single domain name
1031 component or component fragment. E.g., *.a.com matches foo.a.com but
1032 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1033
1034 In some cases, the URI is specified as an IP address rather than a
1035 hostname. In this case, the iPAddress subjectAltName must be present
1036 in the certificate and must exactly match the IP in the URI.
1037
1038 */
verifyhost(struct connectdata * conn,X509 * server_cert)1039 static CURLcode verifyhost(struct connectdata *conn,
1040 X509 *server_cert)
1041 {
1042 bool matched = FALSE; /* no alternative match yet */
1043 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1044 int addrlen = 0;
1045 struct SessionHandle *data = conn->data;
1046 STACK_OF(GENERAL_NAME) *altnames;
1047 #ifdef ENABLE_IPV6
1048 struct in6_addr addr;
1049 #else
1050 struct in_addr addr;
1051 #endif
1052 CURLcode res = CURLE_OK;
1053
1054 #ifdef ENABLE_IPV6
1055 if(conn->bits.ipv6_ip &&
1056 Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
1057 target = GEN_IPADD;
1058 addrlen = sizeof(struct in6_addr);
1059 }
1060 else
1061 #endif
1062 if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
1063 target = GEN_IPADD;
1064 addrlen = sizeof(struct in_addr);
1065 }
1066
1067 /* get a "list" of alternative names */
1068 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1069
1070 if(altnames) {
1071 int numalts;
1072 int i;
1073
1074 /* get amount of alternatives, RFC2459 claims there MUST be at least
1075 one, but we don't depend on it... */
1076 numalts = sk_GENERAL_NAME_num(altnames);
1077
1078 /* loop through all alternatives while none has matched */
1079 for (i=0; (i<numalts) && !matched; i++) {
1080 /* get a handle to alternative name number i */
1081 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1082
1083 /* only check alternatives of the same type the target is */
1084 if(check->type == target) {
1085 /* get data and length */
1086 const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
1087 int altlen;
1088
1089 switch(target) {
1090 case GEN_DNS: /* name/pattern comparison */
1091 /* The OpenSSL man page explicitly says: "In general it cannot be
1092 assumed that the data returned by ASN1_STRING_data() is null
1093 terminated or does not contain embedded nulls." But also that
1094 "The actual format of the data will depend on the actual string
1095 type itself: for example for and IA5String the data will be ASCII"
1096
1097 Gisle researched the OpenSSL sources:
1098 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1099 it always 0-terminates an IA5String."
1100 */
1101 if(cert_hostcheck(altptr, conn->host.name))
1102 matched = TRUE;
1103 break;
1104
1105 case GEN_IPADD: /* IP address comparison */
1106 /* compare alternative IP address if the data chunk is the same size
1107 our server IP address is */
1108 altlen = ASN1_STRING_length(check->d.ia5);
1109 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen))
1110 matched = TRUE;
1111 break;
1112 }
1113 }
1114 }
1115 GENERAL_NAMES_free(altnames);
1116 }
1117
1118 if(matched)
1119 /* an alternative name matched the server hostname */
1120 infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
1121 else {
1122 /* we have to look to the last occurence of a commonName in the
1123 distinguished one to get the most significant one. */
1124 int j,i=-1 ;
1125
1126 /* The following is done because of a bug in 0.9.6b */
1127
1128 unsigned char *nulstr = (unsigned char *)"";
1129 unsigned char *peer_CN = nulstr;
1130
1131 X509_NAME *name = X509_get_subject_name(server_cert) ;
1132 if(name)
1133 while((j=X509_NAME_get_index_by_NID(name,NID_commonName,i))>=0)
1134 i=j;
1135
1136 /* we have the name entry and we will now convert this to a string
1137 that we can use for comparison. Doing this we support BMPstring,
1138 UTF8 etc. */
1139
1140 if(i>=0) {
1141 ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
1142
1143 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1144 is already UTF-8 encoded. We check for this case and copy the raw
1145 string manually to avoid the problem. This code can be made
1146 conditional in the future when OpenSSL has been fixed. Work-around
1147 brought by Alexis S. L. Carvalho. */
1148 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1149 j = ASN1_STRING_length(tmp);
1150 if(j >= 0) {
1151 peer_CN = OPENSSL_malloc(j+1);
1152 if(peer_CN) {
1153 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
1154 peer_CN[j] = '\0';
1155 }
1156 }
1157 }
1158 else /* not a UTF8 name */
1159 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1160 }
1161
1162 if(peer_CN == nulstr)
1163 peer_CN = NULL;
1164 #ifdef CURL_DOES_CONVERSIONS
1165 else {
1166 /* convert peer_CN from UTF8 */
1167 size_t rc;
1168 rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
1169 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1170 if(rc != CURLE_OK) {
1171 OPENSSL_free(peer_CN);
1172 return rc;
1173 }
1174 }
1175 #endif /* CURL_DOES_CONVERSIONS */
1176
1177 if(!peer_CN) {
1178 failf(data,
1179 "SSL: unable to obtain common name from peer certificate");
1180 return CURLE_PEER_FAILED_VERIFICATION;
1181 }
1182 else if(!cert_hostcheck((const char *)peer_CN, conn->host.name)) {
1183 if(data->set.ssl.verifyhost > 1) {
1184 failf(data, "SSL: certificate subject name '%s' does not match "
1185 "target host name '%s'", peer_CN, conn->host.dispname);
1186 res = CURLE_PEER_FAILED_VERIFICATION;
1187 }
1188 else
1189 infof(data, "\t common name: %s (does not match '%s')\n",
1190 peer_CN, conn->host.dispname);
1191 }
1192 else {
1193 infof(data, "\t common name: %s (matched)\n", peer_CN);
1194 }
1195 if(peer_CN)
1196 OPENSSL_free(peer_CN);
1197 }
1198 return res;
1199 }
1200 #endif /* USE_SSLEAY */
1201
1202 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1203 and thus this cannot be done there. */
1204 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1205
ssl_msg_type(int ssl_ver,int msg)1206 static const char *ssl_msg_type(int ssl_ver, int msg)
1207 {
1208 if(ssl_ver == SSL2_VERSION_MAJOR) {
1209 switch (msg) {
1210 case SSL2_MT_ERROR:
1211 return "Error";
1212 case SSL2_MT_CLIENT_HELLO:
1213 return "Client hello";
1214 case SSL2_MT_CLIENT_MASTER_KEY:
1215 return "Client key";
1216 case SSL2_MT_CLIENT_FINISHED:
1217 return "Client finished";
1218 case SSL2_MT_SERVER_HELLO:
1219 return "Server hello";
1220 case SSL2_MT_SERVER_VERIFY:
1221 return "Server verify";
1222 case SSL2_MT_SERVER_FINISHED:
1223 return "Server finished";
1224 case SSL2_MT_REQUEST_CERTIFICATE:
1225 return "Request CERT";
1226 case SSL2_MT_CLIENT_CERTIFICATE:
1227 return "Client CERT";
1228 }
1229 }
1230 else if(ssl_ver == SSL3_VERSION_MAJOR) {
1231 switch (msg) {
1232 case SSL3_MT_HELLO_REQUEST:
1233 return "Hello request";
1234 case SSL3_MT_CLIENT_HELLO:
1235 return "Client hello";
1236 case SSL3_MT_SERVER_HELLO:
1237 return "Server hello";
1238 case SSL3_MT_CERTIFICATE:
1239 return "CERT";
1240 case SSL3_MT_SERVER_KEY_EXCHANGE:
1241 return "Server key exchange";
1242 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1243 return "Client key exchange";
1244 case SSL3_MT_CERTIFICATE_REQUEST:
1245 return "Request CERT";
1246 case SSL3_MT_SERVER_DONE:
1247 return "Server finished";
1248 case SSL3_MT_CERTIFICATE_VERIFY:
1249 return "CERT verify";
1250 case SSL3_MT_FINISHED:
1251 return "Finished";
1252 }
1253 }
1254 return "Unknown";
1255 }
1256
tls_rt_type(int type)1257 static const char *tls_rt_type(int type)
1258 {
1259 return (
1260 type == SSL3_RT_CHANGE_CIPHER_SPEC ? "TLS change cipher, " :
1261 type == SSL3_RT_ALERT ? "TLS alert, " :
1262 type == SSL3_RT_HANDSHAKE ? "TLS handshake, " :
1263 type == SSL3_RT_APPLICATION_DATA ? "TLS app data, " :
1264 "TLS Unknown, ");
1265 }
1266
1267
1268 /*
1269 * Our callback from the SSL/TLS layers.
1270 */
ssl_tls_trace(int direction,int ssl_ver,int content_type,const void * buf,size_t len,const SSL * ssl,struct connectdata * conn)1271 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1272 const void *buf, size_t len, const SSL *ssl,
1273 struct connectdata *conn)
1274 {
1275 struct SessionHandle *data;
1276 const char *msg_name, *tls_rt_name;
1277 char ssl_buf[1024];
1278 int ver, msg_type, txt_len;
1279
1280 if(!conn || !conn->data || !conn->data->set.fdebug ||
1281 (direction != 0 && direction != 1))
1282 return;
1283
1284 data = conn->data;
1285 ssl_ver >>= 8;
1286 ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
1287 ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
1288
1289 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1290 * always pass-up content-type as 0. But the interesting message-type
1291 * is at 'buf[0]'.
1292 */
1293 if(ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
1294 tls_rt_name = tls_rt_type(content_type);
1295 else
1296 tls_rt_name = "";
1297
1298 msg_type = *(char*)buf;
1299 msg_name = ssl_msg_type(ssl_ver, msg_type);
1300
1301 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n",
1302 ver, tls_rt_name, msg_name, msg_type);
1303 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1304
1305 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1306 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1307 (void) ssl;
1308 }
1309 #endif
1310
1311 #ifdef USE_SSLEAY
1312 /* ====================================================== */
1313
1314 static CURLcode
ossl_connect_step1(struct connectdata * conn,int sockindex)1315 ossl_connect_step1(struct connectdata *conn,
1316 int sockindex)
1317 {
1318 CURLcode retcode = CURLE_OK;
1319
1320 struct SessionHandle *data = conn->data;
1321 SSL_METHOD_QUAL SSL_METHOD *req_method=NULL;
1322 void *ssl_sessionid=NULL;
1323 X509_LOOKUP *lookup=NULL;
1324 curl_socket_t sockfd = conn->sock[sockindex];
1325 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1326 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1327 #ifdef ENABLE_IPV6
1328 struct in6_addr addr;
1329 #else
1330 struct in_addr addr;
1331 #endif
1332 #endif
1333
1334 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
1335
1336 /* Make funny stuff to get random input */
1337 Curl_ossl_seed(data);
1338
1339 /* check to see if we've been told to use an explicit SSL/TLS version */
1340 switch(data->set.ssl.version) {
1341 default:
1342 case CURL_SSLVERSION_DEFAULT:
1343 /* we try to figure out version */
1344 req_method = SSLv23_client_method();
1345 break;
1346 case CURL_SSLVERSION_TLSv1:
1347 req_method = TLSv1_client_method();
1348 break;
1349 case CURL_SSLVERSION_SSLv2:
1350 req_method = SSLv2_client_method();
1351 break;
1352 case CURL_SSLVERSION_SSLv3:
1353 req_method = SSLv3_client_method();
1354 break;
1355 }
1356
1357 if(connssl->ctx)
1358 SSL_CTX_free(connssl->ctx);
1359 connssl->ctx = SSL_CTX_new(req_method);
1360
1361 if(!connssl->ctx) {
1362 failf(data, "SSL: couldn't create a context!");
1363 return CURLE_OUT_OF_MEMORY;
1364 }
1365
1366 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1367 if(data->set.fdebug && data->set.verbose) {
1368 /* the SSL trace callback is only used for verbose logging so we only
1369 inform about failures of setting it */
1370 if(!SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK,
1371 (void (*)(void))ssl_tls_trace)) {
1372 infof(data, "SSL: couldn't set callback!\n");
1373 }
1374 else if(!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0,
1375 conn)) {
1376 infof(data, "SSL: couldn't set callback argument!\n");
1377 }
1378 }
1379 #endif
1380
1381 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1382 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1383 work-arounds. The man page for this option states that SSL_OP_ALL enables
1384 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1385 enable the bug workaround options if compatibility with somewhat broken
1386 implementations is desired."
1387
1388 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
1389 disable "rfc4507bis session ticket support". rfc4507bis was later turned
1390 into the proper RFC5077 it seems: http://tools.ietf.org/html/rfc5077
1391
1392 The enabled extension concerns the session management. I wonder how often
1393 libcurl stops a connection and then resumes a TLS session. also, sending
1394 the session data is some overhead. .I suggest that you just use your
1395 proposed patch (which explicitly disables TICKET).
1396
1397 If someone writes an application with libcurl and openssl who wants to
1398 enable the feature, one can do this in the SSL callback.
1399
1400 */
1401 #ifdef SSL_OP_NO_TICKET
1402 /* expect older openssl releases to not have this define so only use it if
1403 present */
1404 #define CURL_CTX_OPTIONS SSL_OP_ALL|SSL_OP_NO_TICKET
1405 #else
1406 #define CURL_CTX_OPTIONS SSL_OP_ALL
1407 #endif
1408
1409 SSL_CTX_set_options(connssl->ctx, CURL_CTX_OPTIONS);
1410
1411 /* disable SSLv2 in the default case (i.e. allow SSLv3 and TLSv1) */
1412 if(data->set.ssl.version == CURL_SSLVERSION_DEFAULT)
1413 SSL_CTX_set_options(connssl->ctx, SSL_OP_NO_SSLv2);
1414
1415 #if 0
1416 /*
1417 * Not sure it's needed to tell SSL_connect() that socket is
1418 * non-blocking. It doesn't seem to care, but just return with
1419 * SSL_ERROR_WANT_x.
1420 */
1421 if(data->state.used_interface == Curl_if_multi)
1422 SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL);
1423 #endif
1424
1425 if(data->set.str[STRING_CERT]) {
1426 if(!cert_stuff(conn,
1427 connssl->ctx,
1428 data->set.str[STRING_CERT],
1429 data->set.str[STRING_CERT_TYPE],
1430 data->set.str[STRING_KEY],
1431 data->set.str[STRING_KEY_TYPE])) {
1432 /* failf() is already done in cert_stuff() */
1433 return CURLE_SSL_CERTPROBLEM;
1434 }
1435 }
1436
1437 if(data->set.str[STRING_SSL_CIPHER_LIST]) {
1438 if(!SSL_CTX_set_cipher_list(connssl->ctx,
1439 data->set.str[STRING_SSL_CIPHER_LIST])) {
1440 failf(data, "failed setting cipher list");
1441 return CURLE_SSL_CIPHER;
1442 }
1443 }
1444
1445 if(data->set.str[STRING_SSL_CAFILE] || data->set.str[STRING_SSL_CAPATH]) {
1446 /* tell SSL where to find CA certificates that are used to verify
1447 the servers certificate. */
1448 if(!SSL_CTX_load_verify_locations(connssl->ctx,
1449 data->set.str[STRING_SSL_CAFILE],
1450 data->set.str[STRING_SSL_CAPATH])) {
1451 if(data->set.ssl.verifypeer) {
1452 /* Fail if we insist on successfully verifying the server. */
1453 failf(data,"error setting certificate verify locations:\n"
1454 " CAfile: %s\n CApath: %s\n",
1455 data->set.str[STRING_SSL_CAFILE]?
1456 data->set.str[STRING_SSL_CAFILE]: "none",
1457 data->set.str[STRING_SSL_CAPATH]?
1458 data->set.str[STRING_SSL_CAPATH] : "none");
1459 return CURLE_SSL_CACERT_BADFILE;
1460 }
1461 else {
1462 /* Just continue with a warning if no strict certificate verification
1463 is required. */
1464 infof(data, "error setting certificate verify locations,"
1465 " continuing anyway:\n");
1466 }
1467 }
1468 else {
1469 /* Everything is fine. */
1470 infof(data, "successfully set certificate verify locations:\n");
1471 }
1472 infof(data,
1473 " CAfile: %s\n"
1474 " CApath: %s\n",
1475 data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]:
1476 "none",
1477 data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]:
1478 "none");
1479 }
1480
1481 if (data->set.str[STRING_SSL_CRLFILE]) {
1482 /* tell SSL where to find CRL file that is used to check certificate
1483 * revocation */
1484 lookup=X509_STORE_add_lookup(connssl->ctx->cert_store,X509_LOOKUP_file());
1485 if ( !lookup ||
1486 (X509_load_crl_file(lookup,data->set.str[STRING_SSL_CRLFILE],
1487 X509_FILETYPE_PEM)!=1) ) {
1488 failf(data,"error loading CRL file :\n"
1489 " CRLfile: %s\n",
1490 data->set.str[STRING_SSL_CRLFILE]?
1491 data->set.str[STRING_SSL_CRLFILE]: "none");
1492 return CURLE_SSL_CRL_BADFILE;
1493 }
1494 else {
1495 /* Everything is fine. */
1496 infof(data, "successfully load CRL file:\n");
1497 X509_STORE_set_flags(connssl->ctx->cert_store,
1498 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1499 }
1500 infof(data,
1501 " CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ?
1502 data->set.str[STRING_SSL_CRLFILE]: "none");
1503 }
1504
1505 /* SSL always tries to verify the peer, this only says whether it should
1506 * fail to connect if the verification fails, or if it should continue
1507 * anyway. In the latter case the result of the verification is checked with
1508 * SSL_get_verify_result() below. */
1509 SSL_CTX_set_verify(connssl->ctx,
1510 data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
1511 cert_verify_callback);
1512
1513 /* give application a chance to interfere with SSL set up. */
1514 if(data->set.ssl.fsslctx) {
1515 retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx,
1516 data->set.ssl.fsslctxp);
1517 if(retcode) {
1518 failf(data,"error signaled by ssl ctx callback");
1519 return retcode;
1520 }
1521 }
1522
1523 /* Lets make an SSL structure */
1524 if(connssl->handle)
1525 SSL_free(connssl->handle);
1526 connssl->handle = SSL_new(connssl->ctx);
1527 if(!connssl->handle) {
1528 failf(data, "SSL: couldn't create a context (handle)!");
1529 return CURLE_OUT_OF_MEMORY;
1530 }
1531 SSL_set_connect_state(connssl->handle);
1532
1533 connssl->server_cert = 0x0;
1534
1535 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1536 if ((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
1537 #ifdef ENABLE_IPV6
1538 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
1539 #endif
1540 !SSL_set_tlsext_host_name(connssl->handle, conn->host.name))
1541 infof(data, "WARNING: failed to configure server name indication (SNI) "
1542 "TLS extension\n");
1543 #endif
1544
1545 /* Check if there's a cached ID we can/should use here! */
1546 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
1547 /* we got a session id, use it! */
1548 if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
1549 failf(data, "SSL: SSL_set_session failed: %s",
1550 ERR_error_string(ERR_get_error(),NULL));
1551 return CURLE_SSL_CONNECT_ERROR;
1552 }
1553 /* Informational message */
1554 infof (data, "SSL re-using session ID\n");
1555 }
1556
1557 /* pass the raw socket into the SSL layers */
1558 if(!SSL_set_fd(connssl->handle, sockfd)) {
1559 failf(data, "SSL: SSL_set_fd failed: %s",
1560 ERR_error_string(ERR_get_error(),NULL));
1561 return CURLE_SSL_CONNECT_ERROR;
1562 }
1563
1564 connssl->connecting_state = ssl_connect_2;
1565 return CURLE_OK;
1566 }
1567
1568 static CURLcode
ossl_connect_step2(struct connectdata * conn,int sockindex)1569 ossl_connect_step2(struct connectdata *conn, int sockindex)
1570 {
1571 struct SessionHandle *data = conn->data;
1572 int err;
1573 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1574
1575 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
1576 || ssl_connect_2_reading == connssl->connecting_state
1577 || ssl_connect_2_writing == connssl->connecting_state);
1578
1579 err = SSL_connect(connssl->handle);
1580
1581 /* 1 is fine
1582 0 is "not successful but was shut down controlled"
1583 <0 is "handshake was not successful, because a fatal error occurred" */
1584 if(1 != err) {
1585 int detail = SSL_get_error(connssl->handle, err);
1586
1587 if(SSL_ERROR_WANT_READ == detail) {
1588 connssl->connecting_state = ssl_connect_2_reading;
1589 return CURLE_OK;
1590 }
1591 else if(SSL_ERROR_WANT_WRITE == detail) {
1592 connssl->connecting_state = ssl_connect_2_writing;
1593 return CURLE_OK;
1594 }
1595 else {
1596 /* untreated error */
1597 unsigned long errdetail;
1598 char error_buffer[256]; /* OpenSSL documents that this must be at least
1599 256 bytes long. */
1600 CURLcode rc;
1601 const char *cert_problem = NULL;
1602
1603 connssl->connecting_state = ssl_connect_2; /* the connection failed,
1604 we're not waiting for
1605 anything else. */
1606
1607 errdetail = ERR_get_error(); /* Gets the earliest error code from the
1608 thread's error queue and removes the
1609 entry. */
1610
1611 switch(errdetail) {
1612 case 0x1407E086:
1613 /* 1407E086:
1614 SSL routines:
1615 SSL2_SET_CERTIFICATE:
1616 certificate verify failed */
1617 /* fall-through */
1618 case 0x14090086:
1619 /* 14090086:
1620 SSL routines:
1621 SSL3_GET_SERVER_CERTIFICATE:
1622 certificate verify failed */
1623 cert_problem = "SSL certificate problem, verify that the CA cert is"
1624 " OK. Details:\n";
1625 rc = CURLE_SSL_CACERT;
1626 break;
1627 default:
1628 rc = CURLE_SSL_CONNECT_ERROR;
1629 break;
1630 }
1631
1632 /* detail is already set to the SSL error above */
1633
1634 /* If we e.g. use SSLv2 request-method and the server doesn't like us
1635 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
1636 * the SO_ERROR is also lost.
1637 */
1638 if(CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) {
1639 failf(data, "Unknown SSL protocol error in connection to %s:%d ",
1640 conn->host.name, conn->port);
1641 return rc;
1642 }
1643 /* Could be a CERT problem */
1644
1645 SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
1646 failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
1647 return rc;
1648 }
1649 }
1650 else {
1651 /* we have been connected fine, we're not waiting for anything else. */
1652 connssl->connecting_state = ssl_connect_3;
1653
1654 /* Informational message */
1655 infof (data, "SSL connection using %s\n",
1656 SSL_get_cipher(connssl->handle));
1657
1658 return CURLE_OK;
1659 }
1660 }
1661
asn1_object_dump(ASN1_OBJECT * a,char * buf,size_t len)1662 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
1663 {
1664 int i, ilen;
1665
1666 if((ilen = (int)len) < 0)
1667 return 1; /* buffer too big */
1668
1669 i = i2t_ASN1_OBJECT(buf, ilen, a);
1670
1671 if(i >= ilen)
1672 return 1; /* buffer too small */
1673
1674 return 0;
1675 }
1676
push_certinfo_len(struct SessionHandle * data,int certnum,const char * label,const char * value,size_t valuelen)1677 static CURLcode push_certinfo_len(struct SessionHandle *data,
1678 int certnum,
1679 const char *label,
1680 const char *value,
1681 size_t valuelen)
1682 {
1683 struct curl_certinfo *ci = &data->info.certs;
1684 char *outp;
1685 struct curl_slist *nl;
1686 CURLcode res = CURLE_OK;
1687 size_t labellen = strlen(label);
1688 size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
1689
1690 outp = malloc(outlen);
1691 if(!outp)
1692 return CURLE_OUT_OF_MEMORY;
1693
1694 /* sprintf the label and colon */
1695 snprintf(outp, outlen, "%s:", label);
1696
1697 /* memcpy the value (it might not be zero terminated) */
1698 memcpy(&outp[labellen+1], value, valuelen);
1699
1700 /* zero terminate the output */
1701 outp[labellen + 1 + valuelen] = 0;
1702
1703 /* TODO: we should rather introduce an internal API that can do the
1704 equivalent of curl_slist_append but doesn't strdup() the given data as
1705 like in this place the extra malloc/free is totally pointless */
1706 nl = curl_slist_append(ci->certinfo[certnum], outp);
1707 if(!nl) {
1708 curl_slist_free_all(ci->certinfo[certnum]);
1709 res = CURLE_OUT_OF_MEMORY;
1710 }
1711 else
1712 ci->certinfo[certnum] = nl;
1713
1714 free(outp);
1715
1716 return res;
1717 }
1718
1719 /* this is a convenience function for push_certinfo_len that takes a zero
1720 terminated value */
push_certinfo(struct SessionHandle * data,int certnum,const char * label,const char * value)1721 static CURLcode push_certinfo(struct SessionHandle *data,
1722 int certnum,
1723 const char *label,
1724 const char *value)
1725 {
1726 size_t valuelen = strlen(value);
1727
1728 return push_certinfo_len(data, certnum, label, value, valuelen);
1729 }
1730
pubkey_show(struct SessionHandle * data,int num,const char * type,const char * name,unsigned char * raw,int len)1731 static void pubkey_show(struct SessionHandle *data,
1732 int num,
1733 const char *type,
1734 const char *name,
1735 unsigned char *raw,
1736 int len)
1737 {
1738 char buffer[1024];
1739 size_t left = sizeof(buffer);
1740 int i;
1741 char *ptr=buffer;
1742 char namebuf[32];
1743
1744 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
1745
1746 for(i=0; i< len; i++) {
1747 snprintf(ptr, left, "%02x:", raw[i]);
1748 ptr += 3;
1749 left -= 3;
1750 }
1751 infof(data, " %s: %s\n", namebuf, buffer);
1752 push_certinfo(data, num, namebuf, buffer);
1753 }
1754
1755 #define print_pubkey_BN(_type, _name, _num) \
1756 do { \
1757 if (pubkey->pkey._type->_name != NULL) { \
1758 int len = BN_num_bytes(pubkey->pkey._type->_name); \
1759 if(len < (int)sizeof(buf)) { \
1760 BN_bn2bin(pubkey->pkey._type->_name, (unsigned char*)buf); \
1761 buf[len] = 0; \
1762 pubkey_show(data, _num, #_type, #_name, (unsigned char*)buf, len); \
1763 } \
1764 } \
1765 } while (0)
1766
X509V3_ext(struct SessionHandle * data,int certnum,STACK_OF (X509_EXTENSION)* exts)1767 static int X509V3_ext(struct SessionHandle *data,
1768 int certnum,
1769 STACK_OF(X509_EXTENSION) *exts)
1770 {
1771 int i;
1772 size_t j;
1773
1774 if(sk_X509_EXTENSION_num(exts) <= 0)
1775 /* no extensions, bail out */
1776 return 1;
1777
1778 for (i=0; i<sk_X509_EXTENSION_num(exts); i++) {
1779 ASN1_OBJECT *obj;
1780 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1781 BIO *bio_out = BIO_new(BIO_s_mem());
1782 BUF_MEM *biomem;
1783 char buf[512];
1784 char *ptr=buf;
1785 char namebuf[128];
1786
1787 obj = X509_EXTENSION_get_object(ext);
1788
1789 asn1_object_dump(obj, namebuf, sizeof(namebuf));
1790
1791 infof(data, "%s: %s\n", namebuf,
1792 X509_EXTENSION_get_critical(ext)?"(critical)":"");
1793
1794 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
1795 M_ASN1_OCTET_STRING_print(bio_out, ext->value);
1796
1797 BIO_get_mem_ptr(bio_out, &biomem);
1798
1799 /* biomem->length bytes at biomem->data, this little loop here is only
1800 done for the infof() call, we send the "raw" data to the certinfo
1801 function */
1802 for(j=0; j<(size_t)biomem->length; j++) {
1803 const char *sep="";
1804 if(biomem->data[j] == '\n') {
1805 sep=", ";
1806 j++; /* skip the newline */
1807 };
1808 while((biomem->data[j] == ' ') && (j<(size_t)biomem->length))
1809 j++;
1810 if(j<(size_t)biomem->length)
1811 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep, biomem->data[j]);
1812 }
1813 infof(data, " %s\n", buf);
1814
1815 push_certinfo(data, certnum, namebuf, buf);
1816
1817 BIO_free(bio_out);
1818
1819 }
1820 return 0; /* all is fine */
1821 }
1822
1823
X509_signature(struct SessionHandle * data,int numcert,ASN1_STRING * sig)1824 static void X509_signature(struct SessionHandle *data,
1825 int numcert,
1826 ASN1_STRING *sig)
1827 {
1828 char buf[1024];
1829 char *ptr = buf;
1830 int i;
1831 for (i=0; i<sig->length; i++)
1832 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%02x:", sig->data[i]);
1833
1834 infof(data, " Signature: %s\n", buf);
1835 push_certinfo(data, numcert, "Signature", buf);
1836 }
1837
dumpcert(struct SessionHandle * data,X509 * x,int numcert)1838 static void dumpcert(struct SessionHandle *data, X509 *x, int numcert)
1839 {
1840 BIO *bio_out = BIO_new(BIO_s_mem());
1841 BUF_MEM *biomem;
1842
1843 /* this outputs the cert in this 64 column wide style with newlines and
1844 -----BEGIN CERTIFICATE----- texts and more */
1845 PEM_write_bio_X509(bio_out, x);
1846
1847 BIO_get_mem_ptr(bio_out, &biomem);
1848
1849 infof(data, "%s\n", biomem->data);
1850
1851 push_certinfo_len(data, numcert, "Cert", biomem->data, biomem->length);
1852
1853 BIO_free(bio_out);
1854
1855 }
1856
1857
init_certinfo(struct SessionHandle * data,int num)1858 static int init_certinfo(struct SessionHandle *data,
1859 int num)
1860 {
1861 struct curl_certinfo *ci = &data->info.certs;
1862 struct curl_slist **table;
1863
1864 Curl_ssl_free_certinfo(data);
1865
1866 ci->num_of_certs = num;
1867 table = calloc(sizeof(struct curl_slist *) * num, 1);
1868 if(!table)
1869 return 1;
1870
1871 ci->certinfo = table;
1872 return 0;
1873 }
1874
get_cert_chain(struct connectdata * conn,struct ssl_connect_data * connssl)1875 static CURLcode get_cert_chain(struct connectdata *conn,
1876 struct ssl_connect_data *connssl)
1877
1878 {
1879 STACK_OF(X509) *sk;
1880 int i;
1881 char buf[512];
1882 struct SessionHandle *data = conn->data;
1883 int numcerts;
1884
1885 sk = SSL_get_peer_cert_chain(connssl->handle);
1886
1887 if(!sk)
1888 return CURLE_OUT_OF_MEMORY;
1889
1890 numcerts = sk_X509_num(sk);
1891
1892 if(init_certinfo(data, numcerts))
1893 return CURLE_OUT_OF_MEMORY;
1894
1895 infof(data, "--- Certificate chain\n");
1896 for (i=0; i<numcerts; i++) {
1897 long value;
1898 ASN1_INTEGER *num;
1899 ASN1_TIME *certdate;
1900
1901 /* get the certs in "importance order" */
1902 #if 0
1903 X509 *x = sk_X509_value(sk, numcerts - i - 1);
1904 #else
1905 X509 *x = sk_X509_value(sk, i);
1906 #endif
1907
1908 X509_CINF *cinf;
1909 EVP_PKEY *pubkey=NULL;
1910 int j;
1911 char *ptr;
1912
1913 (void)x509_name_oneline(X509_get_subject_name(x), buf, sizeof(buf));
1914 infof(data, "%2d Subject: %s\n",i,buf);
1915 push_certinfo(data, i, "Subject", buf);
1916
1917 (void)x509_name_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
1918 infof(data, " Issuer: %s\n",buf);
1919 push_certinfo(data, i, "Issuer", buf);
1920
1921 value = X509_get_version(x);
1922 infof(data, " Version: %lu (0x%lx)\n", value+1, value);
1923 snprintf(buf, sizeof(buf), "%lx", value);
1924 push_certinfo(data, i, "Version", buf); /* hex */
1925
1926 num=X509_get_serialNumber(x);
1927 if (num->length <= 4) {
1928 value = ASN1_INTEGER_get(num);
1929 infof(data," Serial Number: %ld (0x%lx)\n", value, value);
1930 snprintf(buf, sizeof(buf), "%lx", value);
1931 }
1932 else {
1933
1934 ptr = buf;
1935 *ptr++ = 0;
1936 if(num->type == V_ASN1_NEG_INTEGER)
1937 *ptr++='-';
1938
1939 for (j=0; j<num->length; j++) {
1940 /* TODO: length restrictions */
1941 snprintf(ptr, 3, "%02x%c",num->data[j],
1942 ((j+1 == num->length)?'\n':':'));
1943 ptr += 3;
1944 }
1945 if(num->length)
1946 infof(data," Serial Number: %s\n", buf);
1947 else
1948 buf[0]=0;
1949 }
1950 if(buf[0])
1951 push_certinfo(data, i, "Serial Number", buf); /* hex */
1952
1953 cinf = x->cert_info;
1954
1955 j = asn1_object_dump(cinf->signature->algorithm, buf, sizeof(buf));
1956 if(!j) {
1957 infof(data, " Signature Algorithm: %s\n", buf);
1958 push_certinfo(data, i, "Signature Algorithm", buf);
1959 }
1960
1961 certdate = X509_get_notBefore(x);
1962 asn1_output(certdate, buf, sizeof(buf));
1963 infof(data, " Start date: %s\n", buf);
1964 push_certinfo(data, i, "Start date", buf);
1965
1966 certdate = X509_get_notAfter(x);
1967 asn1_output(certdate, buf, sizeof(buf));
1968 infof(data, " Expire date: %s\n", buf);
1969 push_certinfo(data, i, "Expire date", buf);
1970
1971 j = asn1_object_dump(cinf->key->algor->algorithm, buf, sizeof(buf));
1972 if(!j) {
1973 infof(data, " Public Key Algorithm: %s\n", buf);
1974 push_certinfo(data, i, "Public Key Algorithm", buf);
1975 }
1976
1977 pubkey = X509_get_pubkey(x);
1978 if(!pubkey)
1979 infof(data, " Unable to load public key\n");
1980 else {
1981 switch(pubkey->type) {
1982 case EVP_PKEY_RSA:
1983 infof(data, " RSA Public Key (%d bits)\n",
1984 BN_num_bits(pubkey->pkey.rsa->n));
1985 snprintf(buf, sizeof(buf), "%d", BN_num_bits(pubkey->pkey.rsa->n));
1986 push_certinfo(data, i, "RSA Public Key", buf);
1987
1988 print_pubkey_BN(rsa, n, i);
1989 print_pubkey_BN(rsa, e, i);
1990 print_pubkey_BN(rsa, d, i);
1991 print_pubkey_BN(rsa, p, i);
1992 print_pubkey_BN(rsa, q, i);
1993 print_pubkey_BN(rsa, dmp1, i);
1994 print_pubkey_BN(rsa, dmq1, i);
1995 print_pubkey_BN(rsa, iqmp, i);
1996 break;
1997 case EVP_PKEY_DSA:
1998 print_pubkey_BN(dsa, p, i);
1999 print_pubkey_BN(dsa, q, i);
2000 print_pubkey_BN(dsa, g, i);
2001 print_pubkey_BN(dsa, priv_key, i);
2002 print_pubkey_BN(dsa, pub_key, i);
2003 break;
2004 case EVP_PKEY_DH:
2005 print_pubkey_BN(dh, p, i);
2006 print_pubkey_BN(dh, g, i);
2007 print_pubkey_BN(dh, priv_key, i);
2008 print_pubkey_BN(dh, pub_key, i);
2009 break;
2010 #if 0
2011 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2012 /* left TODO */
2013 break;
2014 #endif
2015 }
2016 }
2017
2018 X509V3_ext(data, i, cinf->extensions);
2019
2020 X509_signature(data, i, x->signature);
2021
2022 dumpcert(data, x, i);
2023 }
2024
2025 return CURLE_OK;
2026 }
2027
2028 /*
2029 * Get the server cert, verify it and show it etc, only call failf() if the
2030 * 'strict' argument is TRUE as otherwise all this is for informational
2031 * purposes only!
2032 *
2033 * We check certificates to authenticate the server; otherwise we risk
2034 * man-in-the-middle attack.
2035 */
servercert(struct connectdata * conn,struct ssl_connect_data * connssl,bool strict)2036 static CURLcode servercert(struct connectdata *conn,
2037 struct ssl_connect_data *connssl,
2038 bool strict)
2039 {
2040 CURLcode retcode = CURLE_OK;
2041 int rc;
2042 long lerr;
2043 ASN1_TIME *certdate;
2044 struct SessionHandle *data = conn->data;
2045 X509 *issuer;
2046 FILE *fp;
2047 char buffer[256];
2048
2049 if(data->set.ssl.certinfo)
2050 /* we've been asked to gather certificate info! */
2051 (void)get_cert_chain(conn, connssl);
2052
2053 data->set.ssl.certverifyresult = !X509_V_OK;
2054
2055 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
2056 if(!connssl->server_cert) {
2057 if(strict)
2058 failf(data, "SSL: couldn't get peer certificate!");
2059 return CURLE_PEER_FAILED_VERIFICATION;
2060 }
2061 infof (data, "Server certificate:\n");
2062
2063 rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
2064 buffer, sizeof(buffer));
2065 if(rc) {
2066 if(strict)
2067 failf(data, "SSL: couldn't get X509-subject!");
2068 X509_free(connssl->server_cert);
2069 connssl->server_cert = NULL;
2070 return CURLE_SSL_CONNECT_ERROR;
2071 }
2072 infof(data, "\t subject: %s\n", buffer);
2073
2074 certdate = X509_get_notBefore(connssl->server_cert);
2075 asn1_output(certdate, buffer, sizeof(buffer));
2076 infof(data, "\t start date: %s\n", buffer);
2077
2078 certdate = X509_get_notAfter(connssl->server_cert);
2079 asn1_output(certdate, buffer, sizeof(buffer));
2080 infof(data, "\t expire date: %s\n", buffer);
2081
2082 if(data->set.ssl.verifyhost) {
2083 retcode = verifyhost(conn, connssl->server_cert);
2084 if(retcode) {
2085 X509_free(connssl->server_cert);
2086 connssl->server_cert = NULL;
2087 return retcode;
2088 }
2089 }
2090
2091 rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
2092 buffer, sizeof(buffer));
2093 if(rc) {
2094 if(strict)
2095 failf(data, "SSL: couldn't get X509-issuer name!");
2096 retcode = CURLE_SSL_CONNECT_ERROR;
2097 }
2098 else {
2099 infof(data, "\t issuer: %s\n", buffer);
2100
2101 /* We could do all sorts of certificate verification stuff here before
2102 deallocating the certificate. */
2103
2104 /* e.g. match issuer name with provided issuer certificate */
2105 if (data->set.str[STRING_SSL_ISSUERCERT]) {
2106 if (! (fp=fopen(data->set.str[STRING_SSL_ISSUERCERT],"r"))) {
2107 if (strict)
2108 failf(data, "SSL: Unable to open issuer cert (%s)\n",
2109 data->set.str[STRING_SSL_ISSUERCERT]);
2110 X509_free(connssl->server_cert);
2111 connssl->server_cert = NULL;
2112 return CURLE_SSL_ISSUER_ERROR;
2113 }
2114 issuer = PEM_read_X509(fp,NULL,ZERO_NULL,NULL);
2115 if (!issuer) {
2116 if (strict)
2117 failf(data, "SSL: Unable to read issuer cert (%s)\n",
2118 data->set.str[STRING_SSL_ISSUERCERT]);
2119 X509_free(connssl->server_cert);
2120 X509_free(issuer);
2121 fclose(fp);
2122 return CURLE_SSL_ISSUER_ERROR;
2123 }
2124 fclose(fp);
2125 if (X509_check_issued(issuer,connssl->server_cert) != X509_V_OK) {
2126 if (strict)
2127 failf(data, "SSL: Certificate issuer check failed (%s)\n",
2128 data->set.str[STRING_SSL_ISSUERCERT]);
2129 X509_free(connssl->server_cert);
2130 X509_free(issuer);
2131 connssl->server_cert = NULL;
2132 return CURLE_SSL_ISSUER_ERROR;
2133 }
2134 infof(data, "\t SSL certificate issuer check ok (%s)\n",
2135 data->set.str[STRING_SSL_ISSUERCERT]);
2136 X509_free(issuer);
2137 }
2138
2139 lerr = data->set.ssl.certverifyresult=
2140 SSL_get_verify_result(connssl->handle);
2141 if(data->set.ssl.certverifyresult != X509_V_OK) {
2142 if(data->set.ssl.verifypeer) {
2143 /* We probably never reach this, because SSL_connect() will fail
2144 and we return earlier if verifypeer is set? */
2145 if(strict)
2146 failf(data, "SSL certificate verify result: %s (%ld)",
2147 X509_verify_cert_error_string(lerr), lerr);
2148 retcode = CURLE_PEER_FAILED_VERIFICATION;
2149 }
2150 else
2151 infof(data, "\t SSL certificate verify result: %s (%ld),"
2152 " continuing anyway.\n",
2153 X509_verify_cert_error_string(lerr), lerr);
2154 }
2155 else
2156 infof(data, "\t SSL certificate verify ok.\n");
2157 }
2158
2159 X509_free(connssl->server_cert);
2160 connssl->server_cert = NULL;
2161 connssl->connecting_state = ssl_connect_done;
2162
2163 return retcode;
2164 }
2165
2166
2167 static CURLcode
ossl_connect_step3(struct connectdata * conn,int sockindex)2168 ossl_connect_step3(struct connectdata *conn,
2169 int sockindex)
2170 {
2171 CURLcode retcode = CURLE_OK;
2172 void *ssl_sessionid=NULL;
2173 struct SessionHandle *data = conn->data;
2174 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2175
2176 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
2177
2178 if(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
2179 /* Since this is not a cached session ID, then we want to stach this one
2180 in the cache! */
2181 SSL_SESSION *our_ssl_sessionid;
2182 #ifdef HAVE_SSL_GET1_SESSION
2183 our_ssl_sessionid = SSL_get1_session(connssl->handle);
2184
2185 /* SSL_get1_session() will increment the reference
2186 count and the session will stay in memory until explicitly freed with
2187 SSL_SESSION_free(3), regardless of its state.
2188 This function was introduced in openssl 0.9.5a. */
2189 #else
2190 our_ssl_sessionid = SSL_get_session(connssl->handle);
2191
2192 /* if SSL_get1_session() is unavailable, use SSL_get_session().
2193 This is an inferior option because the session can be flushed
2194 at any time by openssl. It is included only so curl compiles
2195 under versions of openssl < 0.9.5a.
2196
2197 WARNING: How curl behaves if it's session is flushed is
2198 untested.
2199 */
2200 #endif
2201 retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
2202 0 /* unknown size */);
2203 if(retcode) {
2204 failf(data, "failed to store ssl session");
2205 return retcode;
2206 }
2207 }
2208
2209
2210 /*
2211 * We check certificates to authenticate the server; otherwise we risk
2212 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
2213 * verify the peer ignore faults and failures from the server cert
2214 * operations.
2215 */
2216
2217 if(!data->set.ssl.verifypeer)
2218 (void)servercert(conn, connssl, FALSE);
2219 else
2220 retcode = servercert(conn, connssl, TRUE);
2221
2222 if(CURLE_OK == retcode)
2223 connssl->connecting_state = ssl_connect_done;
2224 return retcode;
2225 }
2226
2227 static CURLcode
ossl_connect_common(struct connectdata * conn,int sockindex,bool nonblocking,bool * done)2228 ossl_connect_common(struct connectdata *conn,
2229 int sockindex,
2230 bool nonblocking,
2231 bool *done)
2232 {
2233 CURLcode retcode;
2234 struct SessionHandle *data = conn->data;
2235 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2236 curl_socket_t sockfd = conn->sock[sockindex];
2237 long timeout_ms;
2238
2239 if(ssl_connect_1==connssl->connecting_state) {
2240 /* Find out how much more time we're allowed */
2241 timeout_ms = Curl_timeleft(conn, NULL, TRUE);
2242
2243 if(timeout_ms < 0) {
2244 /* no need to continue if time already is up */
2245 failf(data, "SSL connection timeout");
2246 return CURLE_OPERATION_TIMEDOUT;
2247 }
2248 retcode = ossl_connect_step1(conn, sockindex);
2249 if(retcode)
2250 return retcode;
2251 }
2252
2253 timeout_ms = 0;
2254 while(ssl_connect_2 == connssl->connecting_state ||
2255 ssl_connect_2_reading == connssl->connecting_state ||
2256 ssl_connect_2_writing == connssl->connecting_state) {
2257
2258 /* check allowed time left */
2259 timeout_ms = Curl_timeleft(conn, NULL, TRUE);
2260
2261 if(timeout_ms < 0) {
2262 /* no need to continue if time already is up */
2263 failf(data, "SSL connection timeout");
2264 return CURLE_OPERATION_TIMEDOUT;
2265 }
2266
2267 /* if ssl is expecting something, check if it's available. */
2268 if(connssl->connecting_state == ssl_connect_2_reading
2269 || connssl->connecting_state == ssl_connect_2_writing) {
2270
2271 curl_socket_t writefd = ssl_connect_2_writing==
2272 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
2273 curl_socket_t readfd = ssl_connect_2_reading==
2274 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
2275
2276 while(1) {
2277 int what = Curl_socket_ready(readfd, writefd,
2278 nonblocking?0:(int)timeout_ms);
2279 if(what > 0)
2280 /* readable or writable, go loop in the outer loop */
2281 break;
2282 else if(0 == what) {
2283 if(nonblocking) {
2284 *done = FALSE;
2285 return CURLE_OK;
2286 }
2287 else {
2288 /* timeout */
2289 failf(data, "SSL connection timeout");
2290 return CURLE_OPERATION_TIMEDOUT;
2291 }
2292 }
2293 else {
2294 /* anything that gets here is fatally bad */
2295 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
2296 return CURLE_SSL_CONNECT_ERROR;
2297 }
2298 } /* while()-loop for the select() */
2299 }
2300
2301 /* get the timeout from step2 to avoid computing it twice. */
2302 retcode = ossl_connect_step2(conn, sockindex);
2303 if(retcode)
2304 return retcode;
2305
2306 } /* repeat step2 until all transactions are done. */
2307
2308
2309 if(ssl_connect_3==connssl->connecting_state) {
2310 retcode = ossl_connect_step3(conn, sockindex);
2311 if(retcode)
2312 return retcode;
2313 }
2314
2315 if(ssl_connect_done==connssl->connecting_state) {
2316 connssl->state = ssl_connection_complete;
2317 *done = TRUE;
2318 }
2319 else
2320 *done = FALSE;
2321
2322 /* Reset our connect state machine */
2323 connssl->connecting_state = ssl_connect_1;
2324
2325 return CURLE_OK;
2326 }
2327
2328 CURLcode
Curl_ossl_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)2329 Curl_ossl_connect_nonblocking(struct connectdata *conn,
2330 int sockindex,
2331 bool *done)
2332 {
2333 return ossl_connect_common(conn, sockindex, TRUE, done);
2334 }
2335
2336 CURLcode
Curl_ossl_connect(struct connectdata * conn,int sockindex)2337 Curl_ossl_connect(struct connectdata *conn,
2338 int sockindex)
2339 {
2340 CURLcode retcode;
2341 bool done = FALSE;
2342
2343 retcode = ossl_connect_common(conn, sockindex, FALSE, &done);
2344 if(retcode)
2345 return retcode;
2346
2347 DEBUGASSERT(done);
2348
2349 return CURLE_OK;
2350 }
2351
Curl_ossl_data_pending(const struct connectdata * conn,int connindex)2352 bool Curl_ossl_data_pending(const struct connectdata *conn,
2353 int connindex)
2354 {
2355 if(conn->ssl[connindex].handle)
2356 /* SSL is in use */
2357 return (bool)(0 != SSL_pending(conn->ssl[connindex].handle));
2358 else
2359 return FALSE;
2360 }
2361
2362 /* return number of sent (non-SSL) bytes */
Curl_ossl_send(struct connectdata * conn,int sockindex,const void * mem,size_t len)2363 ssize_t Curl_ossl_send(struct connectdata *conn,
2364 int sockindex,
2365 const void *mem,
2366 size_t len)
2367 {
2368 /* SSL_write() is said to return 'int' while write() and send() returns
2369 'size_t' */
2370 int err;
2371 char error_buffer[120]; /* OpenSSL documents that this must be at least 120
2372 bytes long. */
2373 unsigned long sslerror;
2374 int rc = SSL_write(conn->ssl[sockindex].handle, mem, (int)len);
2375
2376 if(rc < 0) {
2377 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
2378
2379 switch(err) {
2380 case SSL_ERROR_WANT_READ:
2381 case SSL_ERROR_WANT_WRITE:
2382 /* The operation did not complete; the same TLS/SSL I/O function
2383 should be called again later. This is basicly an EWOULDBLOCK
2384 equivalent. */
2385 return 0;
2386 case SSL_ERROR_SYSCALL:
2387 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
2388 SOCKERRNO);
2389 return -1;
2390 case SSL_ERROR_SSL:
2391 /* A failure in the SSL library occurred, usually a protocol error.
2392 The OpenSSL error queue contains more information on the error. */
2393 sslerror = ERR_get_error();
2394 failf(conn->data, "SSL_write() error: %s",
2395 ERR_error_string(sslerror, error_buffer));
2396 return -1;
2397 }
2398 /* a true error */
2399 failf(conn->data, "SSL_write() return error %d", err);
2400 return -1;
2401 }
2402 return (ssize_t)rc; /* number of bytes */
2403 }
2404
2405 /*
2406 * If the read would block we return -1 and set 'wouldblock' to TRUE.
2407 * Otherwise we return the amount of data read. Other errors should return -1
2408 * and set 'wouldblock' to FALSE.
2409 */
Curl_ossl_recv(struct connectdata * conn,int num,char * buf,size_t buffersize,bool * wouldblock)2410 ssize_t Curl_ossl_recv(struct connectdata *conn, /* connection data */
2411 int num, /* socketindex */
2412 char *buf, /* store read data here */
2413 size_t buffersize, /* max amount to read */
2414 bool *wouldblock)
2415 {
2416 char error_buffer[120]; /* OpenSSL documents that this must be at
2417 least 120 bytes long. */
2418 unsigned long sslerror;
2419 ssize_t nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf,
2420 (int)buffersize);
2421 *wouldblock = FALSE;
2422 if(nread < 0) {
2423 /* failed SSL_read */
2424 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
2425
2426 switch(err) {
2427 case SSL_ERROR_NONE: /* this is not an error */
2428 case SSL_ERROR_ZERO_RETURN: /* no more data */
2429 break;
2430 case SSL_ERROR_WANT_READ:
2431 case SSL_ERROR_WANT_WRITE:
2432 /* there's data pending, re-invoke SSL_read() */
2433 *wouldblock = TRUE;
2434 return -1; /* basically EWOULDBLOCK */
2435 default:
2436 /* openssl/ssl.h says "look at error stack/return value/errno" */
2437 sslerror = ERR_get_error();
2438 failf(conn->data, "SSL read: %s, errno %d",
2439 ERR_error_string(sslerror, error_buffer),
2440 SOCKERRNO);
2441 return -1;
2442 }
2443 }
2444 return nread;
2445 }
2446
Curl_ossl_version(char * buffer,size_t size)2447 size_t Curl_ossl_version(char *buffer, size_t size)
2448 {
2449 #ifdef YASSL_VERSION
2450 /* yassl provides an OpenSSL API compatiblity layer so it looks identical
2451 to OpenSSL in all other aspects */
2452 return snprintf(buffer, size, "yassl/%s", YASSL_VERSION);
2453 #else /* YASSL_VERSION */
2454
2455 #if(SSLEAY_VERSION_NUMBER >= 0x905000)
2456 {
2457 char sub[2];
2458 unsigned long ssleay_value;
2459 sub[1]='\0';
2460 ssleay_value=SSLeay();
2461 if(ssleay_value < 0x906000) {
2462 ssleay_value=SSLEAY_VERSION_NUMBER;
2463 sub[0]='\0';
2464 }
2465 else {
2466 if(ssleay_value&0xff0) {
2467 sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
2468 }
2469 else
2470 sub[0]='\0';
2471 }
2472
2473 return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx%s",
2474 (ssleay_value>>28)&0xf,
2475 (ssleay_value>>20)&0xff,
2476 (ssleay_value>>12)&0xff,
2477 sub);
2478 }
2479
2480 #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2481
2482 #if(SSLEAY_VERSION_NUMBER >= 0x900000)
2483 return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx",
2484 (SSLEAY_VERSION_NUMBER>>28)&0xff,
2485 (SSLEAY_VERSION_NUMBER>>20)&0xff,
2486 (SSLEAY_VERSION_NUMBER>>12)&0xf);
2487
2488 #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2489 {
2490 char sub[2];
2491 sub[1]='\0';
2492 if(SSLEAY_VERSION_NUMBER&0x0f) {
2493 sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
2494 }
2495 else
2496 sub[0]='\0';
2497
2498 return snprintf(buffer, size, "SSL/%x.%x.%x%s",
2499 (SSLEAY_VERSION_NUMBER>>12)&0xff,
2500 (SSLEAY_VERSION_NUMBER>>8)&0xf,
2501 (SSLEAY_VERSION_NUMBER>>4)&0xf, sub);
2502 }
2503 #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2504 #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2505
2506 #endif /* YASSL_VERSION */
2507 }
2508 #endif /* USE_SSLEAY */
2509