blob: 772f0b2f1ea5b9aff156e8aa7bf226c92e3e47d8 [file] [log] [blame]
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001/*
2 * SSL/TLS interface functions for OpenSSL
Dmitry Shmidtc55524a2011-07-07 11:18:38 -07003 * Copyright (c) 2004-2011, Jouni Malinen <j@w1.fi>
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07004 *
Dmitry Shmidtc5ec7f52012-03-06 16:33:24 -08005 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07007 */
8
9#include "includes.h"
10
11#ifndef CONFIG_SMARTCARD
12#ifndef OPENSSL_NO_ENGINE
13#define OPENSSL_NO_ENGINE
14#endif
15#endif
16
17#include <openssl/ssl.h>
18#include <openssl/err.h>
19#include <openssl/pkcs12.h>
20#include <openssl/x509v3.h>
21#ifndef OPENSSL_NO_ENGINE
22#include <openssl/engine.h>
23#endif /* OPENSSL_NO_ENGINE */
24
25#ifdef ANDROID
26#include <openssl/pem.h>
27#include "keystore_get.h"
28#endif /* ANDROID */
29
30#include "common.h"
31#include "crypto.h"
32#include "tls.h"
33
34#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
35#define OPENSSL_d2i_TYPE const unsigned char **
36#else
37#define OPENSSL_d2i_TYPE unsigned char **
38#endif
39
40#ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
41#ifdef SSL_OP_NO_TICKET
42/*
43 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
44 * 2008-11-15. This version uses a bit different API compared to the old patch.
45 */
46#define CONFIG_OPENSSL_TICKET_OVERRIDE
47#endif
48#endif
49
50static int tls_openssl_ref_count = 0;
51
52struct tls_global {
53 void (*event_cb)(void *ctx, enum tls_event ev,
54 union tls_event_data *data);
55 void *cb_ctx;
Dmitry Shmidt1f69aa52012-01-24 16:10:04 -080056 int cert_in_cb;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070057};
58
59static struct tls_global *tls_global = NULL;
60
61
62struct tls_connection {
63 SSL *ssl;
64 BIO *ssl_in, *ssl_out;
65#ifndef OPENSSL_NO_ENGINE
66 ENGINE *engine; /* functional reference to the engine */
67 EVP_PKEY *private_key; /* the private key if using engine */
68#endif /* OPENSSL_NO_ENGINE */
69 char *subject_match, *altsubject_match;
70 int read_alerts, write_alerts, failed;
71
72 tls_session_ticket_cb session_ticket_cb;
73 void *session_ticket_cb_ctx;
74
75 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
76 u8 *session_ticket;
77 size_t session_ticket_len;
78
79 unsigned int ca_cert_verify:1;
80 unsigned int cert_probe:1;
81 unsigned int server_cert_only:1;
82
83 u8 srv_cert_hash[32];
Dmitry Shmidtc55524a2011-07-07 11:18:38 -070084
85 unsigned int flags;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070086};
87
88
89#ifdef CONFIG_NO_STDOUT_DEBUG
90
91static void _tls_show_errors(void)
92{
93 unsigned long err;
94
95 while ((err = ERR_get_error())) {
96 /* Just ignore the errors, since stdout is disabled */
97 }
98}
99#define tls_show_errors(l, f, t) _tls_show_errors()
100
101#else /* CONFIG_NO_STDOUT_DEBUG */
102
103static void tls_show_errors(int level, const char *func, const char *txt)
104{
105 unsigned long err;
106
107 wpa_printf(level, "OpenSSL: %s - %s %s",
108 func, txt, ERR_error_string(ERR_get_error(), NULL));
109
110 while ((err = ERR_get_error())) {
111 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
112 ERR_error_string(err, NULL));
113 }
114}
115
116#endif /* CONFIG_NO_STDOUT_DEBUG */
117
118
119#ifdef CONFIG_NATIVE_WINDOWS
120
121/* Windows CryptoAPI and access to certificate stores */
122#include <wincrypt.h>
123
124#ifdef __MINGW32_VERSION
125/*
126 * MinGW does not yet include all the needed definitions for CryptoAPI, so
127 * define here whatever extra is needed.
128 */
129#define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
130#define CERT_STORE_READONLY_FLAG 0x00008000
131#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
132
133#endif /* __MINGW32_VERSION */
134
135
136struct cryptoapi_rsa_data {
137 const CERT_CONTEXT *cert;
138 HCRYPTPROV crypt_prov;
139 DWORD key_spec;
140 BOOL free_crypt_prov;
141};
142
143
144static void cryptoapi_error(const char *msg)
145{
146 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
147 msg, (unsigned int) GetLastError());
148}
149
150
151static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
152 unsigned char *to, RSA *rsa, int padding)
153{
154 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
155 return 0;
156}
157
158
159static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
160 unsigned char *to, RSA *rsa, int padding)
161{
162 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
163 return 0;
164}
165
166
167static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
168 unsigned char *to, RSA *rsa, int padding)
169{
170 struct cryptoapi_rsa_data *priv =
171 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
172 HCRYPTHASH hash;
173 DWORD hash_size, len, i;
174 unsigned char *buf = NULL;
175 int ret = 0;
176
177 if (priv == NULL) {
178 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
179 ERR_R_PASSED_NULL_PARAMETER);
180 return 0;
181 }
182
183 if (padding != RSA_PKCS1_PADDING) {
184 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
185 RSA_R_UNKNOWN_PADDING_TYPE);
186 return 0;
187 }
188
189 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
190 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
191 __func__);
192 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
193 RSA_R_INVALID_MESSAGE_LENGTH);
194 return 0;
195 }
196
197 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
198 {
199 cryptoapi_error("CryptCreateHash failed");
200 return 0;
201 }
202
203 len = sizeof(hash_size);
204 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
205 0)) {
206 cryptoapi_error("CryptGetHashParam failed");
207 goto err;
208 }
209
210 if ((int) hash_size != flen) {
211 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
212 (unsigned) hash_size, flen);
213 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
214 RSA_R_INVALID_MESSAGE_LENGTH);
215 goto err;
216 }
217 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
218 cryptoapi_error("CryptSetHashParam failed");
219 goto err;
220 }
221
222 len = RSA_size(rsa);
223 buf = os_malloc(len);
224 if (buf == NULL) {
225 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
226 goto err;
227 }
228
229 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
230 cryptoapi_error("CryptSignHash failed");
231 goto err;
232 }
233
234 for (i = 0; i < len; i++)
235 to[i] = buf[len - i - 1];
236 ret = len;
237
238err:
239 os_free(buf);
240 CryptDestroyHash(hash);
241
242 return ret;
243}
244
245
246static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
247 unsigned char *to, RSA *rsa, int padding)
248{
249 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
250 return 0;
251}
252
253
254static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
255{
256 if (priv == NULL)
257 return;
258 if (priv->crypt_prov && priv->free_crypt_prov)
259 CryptReleaseContext(priv->crypt_prov, 0);
260 if (priv->cert)
261 CertFreeCertificateContext(priv->cert);
262 os_free(priv);
263}
264
265
266static int cryptoapi_finish(RSA *rsa)
267{
268 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
269 os_free((void *) rsa->meth);
270 rsa->meth = NULL;
271 return 1;
272}
273
274
275static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
276{
277 HCERTSTORE cs;
278 const CERT_CONTEXT *ret = NULL;
279
280 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
281 store | CERT_STORE_OPEN_EXISTING_FLAG |
282 CERT_STORE_READONLY_FLAG, L"MY");
283 if (cs == NULL) {
284 cryptoapi_error("Failed to open 'My system store'");
285 return NULL;
286 }
287
288 if (strncmp(name, "cert://", 7) == 0) {
289 unsigned short wbuf[255];
290 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
291 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
292 PKCS_7_ASN_ENCODING,
293 0, CERT_FIND_SUBJECT_STR,
294 wbuf, NULL);
295 } else if (strncmp(name, "hash://", 7) == 0) {
296 CRYPT_HASH_BLOB blob;
297 int len;
298 const char *hash = name + 7;
299 unsigned char *buf;
300
301 len = os_strlen(hash) / 2;
302 buf = os_malloc(len);
303 if (buf && hexstr2bin(hash, buf, len) == 0) {
304 blob.cbData = len;
305 blob.pbData = buf;
306 ret = CertFindCertificateInStore(cs,
307 X509_ASN_ENCODING |
308 PKCS_7_ASN_ENCODING,
309 0, CERT_FIND_HASH,
310 &blob, NULL);
311 }
312 os_free(buf);
313 }
314
315 CertCloseStore(cs, 0);
316
317 return ret;
318}
319
320
321static int tls_cryptoapi_cert(SSL *ssl, const char *name)
322{
323 X509 *cert = NULL;
324 RSA *rsa = NULL, *pub_rsa;
325 struct cryptoapi_rsa_data *priv;
326 RSA_METHOD *rsa_meth;
327
328 if (name == NULL ||
329 (strncmp(name, "cert://", 7) != 0 &&
330 strncmp(name, "hash://", 7) != 0))
331 return -1;
332
333 priv = os_zalloc(sizeof(*priv));
334 rsa_meth = os_zalloc(sizeof(*rsa_meth));
335 if (priv == NULL || rsa_meth == NULL) {
336 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
337 "for CryptoAPI RSA method");
338 os_free(priv);
339 os_free(rsa_meth);
340 return -1;
341 }
342
343 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
344 if (priv->cert == NULL) {
345 priv->cert = cryptoapi_find_cert(
346 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
347 }
348 if (priv->cert == NULL) {
349 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
350 "'%s'", name);
351 goto err;
352 }
353
354 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
355 priv->cert->cbCertEncoded);
356 if (cert == NULL) {
357 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
358 "encoding");
359 goto err;
360 }
361
362 if (!CryptAcquireCertificatePrivateKey(priv->cert,
363 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
364 NULL, &priv->crypt_prov,
365 &priv->key_spec,
366 &priv->free_crypt_prov)) {
367 cryptoapi_error("Failed to acquire a private key for the "
368 "certificate");
369 goto err;
370 }
371
372 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
373 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
374 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
375 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
376 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
377 rsa_meth->finish = cryptoapi_finish;
378 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
379 rsa_meth->app_data = (char *) priv;
380
381 rsa = RSA_new();
382 if (rsa == NULL) {
383 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
384 ERR_R_MALLOC_FAILURE);
385 goto err;
386 }
387
388 if (!SSL_use_certificate(ssl, cert)) {
389 RSA_free(rsa);
390 rsa = NULL;
391 goto err;
392 }
393 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
394 X509_free(cert);
395 cert = NULL;
396
397 rsa->n = BN_dup(pub_rsa->n);
398 rsa->e = BN_dup(pub_rsa->e);
399 if (!RSA_set_method(rsa, rsa_meth))
400 goto err;
401
402 if (!SSL_use_RSAPrivateKey(ssl, rsa))
403 goto err;
404 RSA_free(rsa);
405
406 return 0;
407
408err:
409 if (cert)
410 X509_free(cert);
411 if (rsa)
412 RSA_free(rsa);
413 else {
414 os_free(rsa_meth);
415 cryptoapi_free_data(priv);
416 }
417 return -1;
418}
419
420
421static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
422{
423 HCERTSTORE cs;
424 PCCERT_CONTEXT ctx = NULL;
425 X509 *cert;
426 char buf[128];
427 const char *store;
428#ifdef UNICODE
429 WCHAR *wstore;
430#endif /* UNICODE */
431
432 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
433 return -1;
434
435 store = name + 13;
436#ifdef UNICODE
437 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
438 if (wstore == NULL)
439 return -1;
440 wsprintf(wstore, L"%S", store);
441 cs = CertOpenSystemStore(0, wstore);
442 os_free(wstore);
443#else /* UNICODE */
444 cs = CertOpenSystemStore(0, store);
445#endif /* UNICODE */
446 if (cs == NULL) {
447 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
448 "'%s': error=%d", __func__, store,
449 (int) GetLastError());
450 return -1;
451 }
452
453 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
454 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
455 ctx->cbCertEncoded);
456 if (cert == NULL) {
457 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
458 "X509 DER encoding for CA cert");
459 continue;
460 }
461
462 X509_NAME_oneline(X509_get_subject_name(cert), buf,
463 sizeof(buf));
464 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
465 "system certificate store: subject='%s'", buf);
466
467 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
468 tls_show_errors(MSG_WARNING, __func__,
469 "Failed to add ca_cert to OpenSSL "
470 "certificate store");
471 }
472
473 X509_free(cert);
474 }
475
476 if (!CertCloseStore(cs, 0)) {
477 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
478 "'%s': error=%d", __func__, name + 13,
479 (int) GetLastError());
480 }
481
482 return 0;
483}
484
485
486#else /* CONFIG_NATIVE_WINDOWS */
487
488static int tls_cryptoapi_cert(SSL *ssl, const char *name)
489{
490 return -1;
491}
492
493#endif /* CONFIG_NATIVE_WINDOWS */
494
495
496static void ssl_info_cb(const SSL *ssl, int where, int ret)
497{
498 const char *str;
499 int w;
500
501 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
502 w = where & ~SSL_ST_MASK;
503 if (w & SSL_ST_CONNECT)
504 str = "SSL_connect";
505 else if (w & SSL_ST_ACCEPT)
506 str = "SSL_accept";
507 else
508 str = "undefined";
509
510 if (where & SSL_CB_LOOP) {
511 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
512 str, SSL_state_string_long(ssl));
513 } else if (where & SSL_CB_ALERT) {
514 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
515 where & SSL_CB_READ ?
516 "read (remote end reported an error)" :
517 "write (local SSL3 detected an error)",
518 SSL_alert_type_string_long(ret),
519 SSL_alert_desc_string_long(ret));
520 if ((ret >> 8) == SSL3_AL_FATAL) {
521 struct tls_connection *conn =
522 SSL_get_app_data((SSL *) ssl);
523 if (where & SSL_CB_READ)
524 conn->read_alerts++;
525 else
526 conn->write_alerts++;
527 }
528 } else if (where & SSL_CB_EXIT && ret <= 0) {
529 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
530 str, ret == 0 ? "failed" : "error",
531 SSL_state_string_long(ssl));
532 }
533}
534
535
536#ifndef OPENSSL_NO_ENGINE
537/**
538 * tls_engine_load_dynamic_generic - load any openssl engine
539 * @pre: an array of commands and values that load an engine initialized
540 * in the engine specific function
541 * @post: an array of commands and values that initialize an already loaded
542 * engine (or %NULL if not required)
543 * @id: the engine id of the engine to load (only required if post is not %NULL
544 *
545 * This function is a generic function that loads any openssl engine.
546 *
547 * Returns: 0 on success, -1 on failure
548 */
549static int tls_engine_load_dynamic_generic(const char *pre[],
550 const char *post[], const char *id)
551{
552 ENGINE *engine;
553 const char *dynamic_id = "dynamic";
554
555 engine = ENGINE_by_id(id);
556 if (engine) {
557 ENGINE_free(engine);
558 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
559 "available", id);
560 return 0;
561 }
562 ERR_clear_error();
563
564 engine = ENGINE_by_id(dynamic_id);
565 if (engine == NULL) {
566 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
567 dynamic_id,
568 ERR_error_string(ERR_get_error(), NULL));
569 return -1;
570 }
571
572 /* Perform the pre commands. This will load the engine. */
573 while (pre && pre[0]) {
574 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
575 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
576 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
577 "%s %s [%s]", pre[0], pre[1],
578 ERR_error_string(ERR_get_error(), NULL));
579 ENGINE_free(engine);
580 return -1;
581 }
582 pre += 2;
583 }
584
585 /*
586 * Free the reference to the "dynamic" engine. The loaded engine can
587 * now be looked up using ENGINE_by_id().
588 */
589 ENGINE_free(engine);
590
591 engine = ENGINE_by_id(id);
592 if (engine == NULL) {
593 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
594 id, ERR_error_string(ERR_get_error(), NULL));
595 return -1;
596 }
597
598 while (post && post[0]) {
599 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
600 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
601 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
602 " %s %s [%s]", post[0], post[1],
603 ERR_error_string(ERR_get_error(), NULL));
604 ENGINE_remove(engine);
605 ENGINE_free(engine);
606 return -1;
607 }
608 post += 2;
609 }
610 ENGINE_free(engine);
611
612 return 0;
613}
614
615
616/**
617 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
618 * @pkcs11_so_path: pksc11_so_path from the configuration
619 * @pcks11_module_path: pkcs11_module_path from the configuration
620 */
621static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
622 const char *pkcs11_module_path)
623{
624 char *engine_id = "pkcs11";
625 const char *pre_cmd[] = {
626 "SO_PATH", NULL /* pkcs11_so_path */,
627 "ID", NULL /* engine_id */,
628 "LIST_ADD", "1",
629 /* "NO_VCHECK", "1", */
630 "LOAD", NULL,
631 NULL, NULL
632 };
633 const char *post_cmd[] = {
634 "MODULE_PATH", NULL /* pkcs11_module_path */,
635 NULL, NULL
636 };
637
638 if (!pkcs11_so_path || !pkcs11_module_path)
639 return 0;
640
641 pre_cmd[1] = pkcs11_so_path;
642 pre_cmd[3] = engine_id;
643 post_cmd[1] = pkcs11_module_path;
644
645 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
646 pkcs11_so_path);
647
648 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
649}
650
651
652/**
653 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
654 * @opensc_so_path: opensc_so_path from the configuration
655 */
656static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
657{
658 char *engine_id = "opensc";
659 const char *pre_cmd[] = {
660 "SO_PATH", NULL /* opensc_so_path */,
661 "ID", NULL /* engine_id */,
662 "LIST_ADD", "1",
663 "LOAD", NULL,
664 NULL, NULL
665 };
666
667 if (!opensc_so_path)
668 return 0;
669
670 pre_cmd[1] = opensc_so_path;
671 pre_cmd[3] = engine_id;
672
673 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
674 opensc_so_path);
675
676 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
677}
678#endif /* OPENSSL_NO_ENGINE */
679
680
681void * tls_init(const struct tls_config *conf)
682{
683 SSL_CTX *ssl;
684
685 if (tls_openssl_ref_count == 0) {
686 tls_global = os_zalloc(sizeof(*tls_global));
687 if (tls_global == NULL)
688 return NULL;
689 if (conf) {
690 tls_global->event_cb = conf->event_cb;
691 tls_global->cb_ctx = conf->cb_ctx;
Dmitry Shmidt1f69aa52012-01-24 16:10:04 -0800692 tls_global->cert_in_cb = conf->cert_in_cb;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -0700693 }
694
695#ifdef CONFIG_FIPS
696#ifdef OPENSSL_FIPS
697 if (conf && conf->fips_mode) {
698 if (!FIPS_mode_set(1)) {
699 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
700 "mode");
701 ERR_load_crypto_strings();
702 ERR_print_errors_fp(stderr);
703 return NULL;
704 } else
705 wpa_printf(MSG_INFO, "Running in FIPS mode");
706 }
707#else /* OPENSSL_FIPS */
708 if (conf && conf->fips_mode) {
709 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
710 "supported");
711 return NULL;
712 }
713#endif /* OPENSSL_FIPS */
714#endif /* CONFIG_FIPS */
715 SSL_load_error_strings();
716 SSL_library_init();
717#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
718 EVP_add_digest(EVP_sha256());
719#endif /* OPENSSL_NO_SHA256 */
720 /* TODO: if /dev/urandom is available, PRNG is seeded
721 * automatically. If this is not the case, random data should
722 * be added here. */
723
724#ifdef PKCS12_FUNCS
725#ifndef OPENSSL_NO_RC2
726 /*
727 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
728 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
729 * versions, but it looks like OpenSSL 1.0.0 does not do that
730 * anymore.
731 */
732 EVP_add_cipher(EVP_rc2_40_cbc());
733#endif /* OPENSSL_NO_RC2 */
734 PKCS12_PBE_add();
735#endif /* PKCS12_FUNCS */
736 }
737 tls_openssl_ref_count++;
738
739 ssl = SSL_CTX_new(TLSv1_method());
740 if (ssl == NULL)
741 return NULL;
742
743 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
744
745#ifndef OPENSSL_NO_ENGINE
746 if (conf &&
747 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
748 conf->pkcs11_module_path)) {
749 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
750 ERR_load_ENGINE_strings();
751 ENGINE_load_dynamic();
752
753 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
754 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
755 conf->pkcs11_module_path)) {
756 tls_deinit(ssl);
757 return NULL;
758 }
759 }
760#endif /* OPENSSL_NO_ENGINE */
761
762 return ssl;
763}
764
765
766void tls_deinit(void *ssl_ctx)
767{
768 SSL_CTX *ssl = ssl_ctx;
769 SSL_CTX_free(ssl);
770
771 tls_openssl_ref_count--;
772 if (tls_openssl_ref_count == 0) {
773#ifndef OPENSSL_NO_ENGINE
774 ENGINE_cleanup();
775#endif /* OPENSSL_NO_ENGINE */
776 CRYPTO_cleanup_all_ex_data();
777 ERR_remove_state(0);
778 ERR_free_strings();
779 EVP_cleanup();
780 os_free(tls_global);
781 tls_global = NULL;
782 }
783}
784
785
786static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
787 const char *pin, const char *key_id,
788 const char *cert_id, const char *ca_cert_id)
789{
790#ifndef OPENSSL_NO_ENGINE
791 int ret = -1;
792 if (engine_id == NULL) {
793 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
794 return -1;
795 }
796 if (pin == NULL) {
797 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
798 return -1;
799 }
800 if (key_id == NULL) {
801 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
802 return -1;
803 }
804
805 ERR_clear_error();
806 conn->engine = ENGINE_by_id(engine_id);
807 if (!conn->engine) {
808 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
809 engine_id, ERR_error_string(ERR_get_error(), NULL));
810 goto err;
811 }
812 if (ENGINE_init(conn->engine) != 1) {
813 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
814 "(engine: %s) [%s]", engine_id,
815 ERR_error_string(ERR_get_error(), NULL));
816 goto err;
817 }
818 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
819
820 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
821 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
822 ERR_error_string(ERR_get_error(), NULL));
823 goto err;
824 }
825 /* load private key first in-case PIN is required for cert */
826 conn->private_key = ENGINE_load_private_key(conn->engine,
827 key_id, NULL, NULL);
828 if (!conn->private_key) {
829 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
830 " '%s' [%s]", key_id,
831 ERR_error_string(ERR_get_error(), NULL));
832 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
833 goto err;
834 }
835
836 /* handle a certificate and/or CA certificate */
837 if (cert_id || ca_cert_id) {
838 const char *cmd_name = "LOAD_CERT_CTRL";
839
840 /* test if the engine supports a LOAD_CERT_CTRL */
841 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
842 0, (void *)cmd_name, NULL)) {
843 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
844 " loading certificates");
845 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
846 goto err;
847 }
848 }
849
850 return 0;
851
852err:
853 if (conn->engine) {
854 ENGINE_free(conn->engine);
855 conn->engine = NULL;
856 }
857
858 if (conn->private_key) {
859 EVP_PKEY_free(conn->private_key);
860 conn->private_key = NULL;
861 }
862
863 return ret;
864#else /* OPENSSL_NO_ENGINE */
865 return 0;
866#endif /* OPENSSL_NO_ENGINE */
867}
868
869
870static void tls_engine_deinit(struct tls_connection *conn)
871{
872#ifndef OPENSSL_NO_ENGINE
873 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
874 if (conn->private_key) {
875 EVP_PKEY_free(conn->private_key);
876 conn->private_key = NULL;
877 }
878 if (conn->engine) {
879 ENGINE_finish(conn->engine);
880 conn->engine = NULL;
881 }
882#endif /* OPENSSL_NO_ENGINE */
883}
884
885
886int tls_get_errors(void *ssl_ctx)
887{
888 int count = 0;
889 unsigned long err;
890
891 while ((err = ERR_get_error())) {
892 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
893 ERR_error_string(err, NULL));
894 count++;
895 }
896
897 return count;
898}
899
900struct tls_connection * tls_connection_init(void *ssl_ctx)
901{
902 SSL_CTX *ssl = ssl_ctx;
903 struct tls_connection *conn;
904 long options;
905
906 conn = os_zalloc(sizeof(*conn));
907 if (conn == NULL)
908 return NULL;
909 conn->ssl = SSL_new(ssl);
910 if (conn->ssl == NULL) {
911 tls_show_errors(MSG_INFO, __func__,
912 "Failed to initialize new SSL connection");
913 os_free(conn);
914 return NULL;
915 }
916
917 SSL_set_app_data(conn->ssl, conn);
918 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
919 SSL_OP_SINGLE_DH_USE;
920#ifdef SSL_OP_NO_COMPRESSION
921 options |= SSL_OP_NO_COMPRESSION;
922#endif /* SSL_OP_NO_COMPRESSION */
923 SSL_set_options(conn->ssl, options);
924
925 conn->ssl_in = BIO_new(BIO_s_mem());
926 if (!conn->ssl_in) {
927 tls_show_errors(MSG_INFO, __func__,
928 "Failed to create a new BIO for ssl_in");
929 SSL_free(conn->ssl);
930 os_free(conn);
931 return NULL;
932 }
933
934 conn->ssl_out = BIO_new(BIO_s_mem());
935 if (!conn->ssl_out) {
936 tls_show_errors(MSG_INFO, __func__,
937 "Failed to create a new BIO for ssl_out");
938 SSL_free(conn->ssl);
939 BIO_free(conn->ssl_in);
940 os_free(conn);
941 return NULL;
942 }
943
944 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
945
946 return conn;
947}
948
949
950void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
951{
952 if (conn == NULL)
953 return;
954 SSL_free(conn->ssl);
955 tls_engine_deinit(conn);
956 os_free(conn->subject_match);
957 os_free(conn->altsubject_match);
958 os_free(conn->session_ticket);
959 os_free(conn);
960}
961
962
963int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
964{
965 return conn ? SSL_is_init_finished(conn->ssl) : 0;
966}
967
968
969int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
970{
971 if (conn == NULL)
972 return -1;
973
974 /* Shutdown previous TLS connection without notifying the peer
975 * because the connection was already terminated in practice
976 * and "close notify" shutdown alert would confuse AS. */
977 SSL_set_quiet_shutdown(conn->ssl, 1);
978 SSL_shutdown(conn->ssl);
979 return 0;
980}
981
982
983static int tls_match_altsubject_component(X509 *cert, int type,
984 const char *value, size_t len)
985{
986 GENERAL_NAME *gen;
987 void *ext;
988 int i, found = 0;
989
990 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
991
992 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
993 gen = sk_GENERAL_NAME_value(ext, i);
994 if (gen->type != type)
995 continue;
996 if (os_strlen((char *) gen->d.ia5->data) == len &&
997 os_memcmp(value, gen->d.ia5->data, len) == 0)
998 found++;
999 }
1000
1001 return found;
1002}
1003
1004
1005static int tls_match_altsubject(X509 *cert, const char *match)
1006{
1007 int type;
1008 const char *pos, *end;
1009 size_t len;
1010
1011 pos = match;
1012 do {
1013 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1014 type = GEN_EMAIL;
1015 pos += 6;
1016 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1017 type = GEN_DNS;
1018 pos += 4;
1019 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1020 type = GEN_URI;
1021 pos += 4;
1022 } else {
1023 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1024 "match '%s'", pos);
1025 return 0;
1026 }
1027 end = os_strchr(pos, ';');
1028 while (end) {
1029 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1030 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1031 os_strncmp(end + 1, "URI:", 4) == 0)
1032 break;
1033 end = os_strchr(end + 1, ';');
1034 }
1035 if (end)
1036 len = end - pos;
1037 else
1038 len = os_strlen(pos);
1039 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1040 return 1;
1041 pos = end + 1;
1042 } while (end);
1043
1044 return 0;
1045}
1046
1047
1048static enum tls_fail_reason openssl_tls_fail_reason(int err)
1049{
1050 switch (err) {
1051 case X509_V_ERR_CERT_REVOKED:
1052 return TLS_FAIL_REVOKED;
1053 case X509_V_ERR_CERT_NOT_YET_VALID:
1054 case X509_V_ERR_CRL_NOT_YET_VALID:
1055 return TLS_FAIL_NOT_YET_VALID;
1056 case X509_V_ERR_CERT_HAS_EXPIRED:
1057 case X509_V_ERR_CRL_HAS_EXPIRED:
1058 return TLS_FAIL_EXPIRED;
1059 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1060 case X509_V_ERR_UNABLE_TO_GET_CRL:
1061 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1062 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1063 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1064 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1065 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1066 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1067 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1068 case X509_V_ERR_INVALID_CA:
1069 return TLS_FAIL_UNTRUSTED;
1070 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1071 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1072 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1073 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1074 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1075 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1076 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1077 case X509_V_ERR_CERT_UNTRUSTED:
1078 case X509_V_ERR_CERT_REJECTED:
1079 return TLS_FAIL_BAD_CERTIFICATE;
1080 default:
1081 return TLS_FAIL_UNSPECIFIED;
1082 }
1083}
1084
1085
1086static struct wpabuf * get_x509_cert(X509 *cert)
1087{
1088 struct wpabuf *buf;
1089 u8 *tmp;
1090
1091 int cert_len = i2d_X509(cert, NULL);
1092 if (cert_len <= 0)
1093 return NULL;
1094
1095 buf = wpabuf_alloc(cert_len);
1096 if (buf == NULL)
1097 return NULL;
1098
1099 tmp = wpabuf_put(buf, cert_len);
1100 i2d_X509(cert, &tmp);
1101 return buf;
1102}
1103
1104
1105static void openssl_tls_fail_event(struct tls_connection *conn,
1106 X509 *err_cert, int err, int depth,
1107 const char *subject, const char *err_str,
1108 enum tls_fail_reason reason)
1109{
1110 union tls_event_data ev;
1111 struct wpabuf *cert = NULL;
1112
1113 if (tls_global->event_cb == NULL)
1114 return;
1115
1116 cert = get_x509_cert(err_cert);
1117 os_memset(&ev, 0, sizeof(ev));
1118 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1119 reason : openssl_tls_fail_reason(err);
1120 ev.cert_fail.depth = depth;
1121 ev.cert_fail.subject = subject;
1122 ev.cert_fail.reason_txt = err_str;
1123 ev.cert_fail.cert = cert;
1124 tls_global->event_cb(tls_global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1125 wpabuf_free(cert);
1126}
1127
1128
1129static void openssl_tls_cert_event(struct tls_connection *conn,
1130 X509 *err_cert, int depth,
1131 const char *subject)
1132{
1133 struct wpabuf *cert = NULL;
1134 union tls_event_data ev;
1135#ifdef CONFIG_SHA256
1136 u8 hash[32];
1137#endif /* CONFIG_SHA256 */
1138
1139 if (tls_global->event_cb == NULL)
1140 return;
1141
1142 os_memset(&ev, 0, sizeof(ev));
Dmitry Shmidt1f69aa52012-01-24 16:10:04 -08001143 if (conn->cert_probe || tls_global->cert_in_cb) {
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001144 cert = get_x509_cert(err_cert);
1145 ev.peer_cert.cert = cert;
1146 }
1147#ifdef CONFIG_SHA256
1148 if (cert) {
1149 const u8 *addr[1];
1150 size_t len[1];
1151 addr[0] = wpabuf_head(cert);
1152 len[0] = wpabuf_len(cert);
1153 if (sha256_vector(1, addr, len, hash) == 0) {
1154 ev.peer_cert.hash = hash;
1155 ev.peer_cert.hash_len = sizeof(hash);
1156 }
1157 }
1158#endif /* CONFIG_SHA256 */
1159 ev.peer_cert.depth = depth;
1160 ev.peer_cert.subject = subject;
1161 tls_global->event_cb(tls_global->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1162 wpabuf_free(cert);
1163}
1164
1165
1166static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1167{
1168 char buf[256];
1169 X509 *err_cert;
1170 int err, depth;
1171 SSL *ssl;
1172 struct tls_connection *conn;
1173 char *match, *altmatch;
1174 const char *err_str;
1175
1176 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1177 err = X509_STORE_CTX_get_error(x509_ctx);
1178 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1179 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1180 SSL_get_ex_data_X509_STORE_CTX_idx());
1181 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1182
1183 conn = SSL_get_app_data(ssl);
1184 if (conn == NULL)
1185 return 0;
1186 match = conn->subject_match;
1187 altmatch = conn->altsubject_match;
1188
1189 if (!preverify_ok && !conn->ca_cert_verify)
1190 preverify_ok = 1;
1191 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1192 preverify_ok = 1;
Dmitry Shmidtc55524a2011-07-07 11:18:38 -07001193 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1194 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1195 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1196 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1197 "time mismatch");
1198 preverify_ok = 1;
1199 }
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001200
1201 err_str = X509_verify_cert_error_string(err);
1202
1203#ifdef CONFIG_SHA256
1204 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1205 struct wpabuf *cert;
1206 cert = get_x509_cert(err_cert);
1207 if (!cert) {
1208 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1209 "server certificate data");
1210 preverify_ok = 0;
1211 } else {
1212 u8 hash[32];
1213 const u8 *addr[1];
1214 size_t len[1];
1215 addr[0] = wpabuf_head(cert);
1216 len[0] = wpabuf_len(cert);
1217 if (sha256_vector(1, addr, len, hash) < 0 ||
1218 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1219 err_str = "Server certificate mismatch";
1220 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1221 preverify_ok = 0;
1222 }
1223 wpabuf_free(cert);
1224 }
1225 }
1226#endif /* CONFIG_SHA256 */
1227
1228 if (!preverify_ok) {
1229 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1230 " error %d (%s) depth %d for '%s'", err, err_str,
1231 depth, buf);
1232 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1233 err_str, TLS_FAIL_UNSPECIFIED);
1234 return preverify_ok;
1235 }
1236
1237 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1238 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1239 preverify_ok, err, err_str,
1240 conn->ca_cert_verify, depth, buf);
1241 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1242 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1243 "match with '%s'", buf, match);
1244 preverify_ok = 0;
1245 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1246 "Subject mismatch",
1247 TLS_FAIL_SUBJECT_MISMATCH);
1248 } else if (depth == 0 && altmatch &&
1249 !tls_match_altsubject(err_cert, altmatch)) {
1250 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1251 "'%s' not found", altmatch);
1252 preverify_ok = 0;
1253 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1254 "AltSubject mismatch",
1255 TLS_FAIL_ALTSUBJECT_MISMATCH);
1256 } else
1257 openssl_tls_cert_event(conn, err_cert, depth, buf);
1258
1259 if (conn->cert_probe && preverify_ok && depth == 0) {
1260 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1261 "on probe-only run");
1262 preverify_ok = 0;
1263 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1264 "Server certificate chain probe",
1265 TLS_FAIL_SERVER_CHAIN_PROBE);
1266 }
1267
1268 return preverify_ok;
1269}
1270
1271
1272#ifndef OPENSSL_NO_STDIO
1273static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1274{
1275 SSL_CTX *ssl_ctx = _ssl_ctx;
1276 X509_LOOKUP *lookup;
1277 int ret = 0;
1278
1279 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1280 X509_LOOKUP_file());
1281 if (lookup == NULL) {
1282 tls_show_errors(MSG_WARNING, __func__,
1283 "Failed add lookup for X509 store");
1284 return -1;
1285 }
1286
1287 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1288 unsigned long err = ERR_peek_error();
1289 tls_show_errors(MSG_WARNING, __func__,
1290 "Failed load CA in DER format");
1291 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1292 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1293 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1294 "cert already in hash table error",
1295 __func__);
1296 } else
1297 ret = -1;
1298 }
1299
1300 return ret;
1301}
1302#endif /* OPENSSL_NO_STDIO */
1303
1304
1305#ifdef ANDROID
1306static BIO * BIO_from_keystore(const char *key)
1307{
1308 BIO *bio = NULL;
1309 char value[KEYSTORE_MESSAGE_SIZE];
1310 int length = keystore_get(key, strlen(key), value);
1311 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
1312 BIO_write(bio, value, length);
1313 return bio;
1314}
1315#endif /* ANDROID */
1316
1317
1318static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1319 const char *ca_cert, const u8 *ca_cert_blob,
1320 size_t ca_cert_blob_len, const char *ca_path)
1321{
1322 SSL_CTX *ssl_ctx = _ssl_ctx;
1323
1324 /*
1325 * Remove previously configured trusted CA certificates before adding
1326 * new ones.
1327 */
1328 X509_STORE_free(ssl_ctx->cert_store);
1329 ssl_ctx->cert_store = X509_STORE_new();
1330 if (ssl_ctx->cert_store == NULL) {
1331 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1332 "certificate store", __func__);
1333 return -1;
1334 }
1335
1336 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1337 conn->ca_cert_verify = 1;
1338
1339 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1340 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1341 "chain");
1342 conn->cert_probe = 1;
1343 conn->ca_cert_verify = 0;
1344 return 0;
1345 }
1346
1347 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1348#ifdef CONFIG_SHA256
1349 const char *pos = ca_cert + 7;
1350 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1351 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1352 "hash value '%s'", ca_cert);
1353 return -1;
1354 }
1355 pos += 14;
1356 if (os_strlen(pos) != 32 * 2) {
1357 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1358 "hash length in ca_cert '%s'", ca_cert);
1359 return -1;
1360 }
1361 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1362 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1363 "value in ca_cert '%s'", ca_cert);
1364 return -1;
1365 }
1366 conn->server_cert_only = 1;
1367 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1368 "certificate match");
1369 return 0;
1370#else /* CONFIG_SHA256 */
1371 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1372 "cannot validate server certificate hash");
1373 return -1;
1374#endif /* CONFIG_SHA256 */
1375 }
1376
1377 if (ca_cert_blob) {
1378 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1379 ca_cert_blob_len);
1380 if (cert == NULL) {
1381 tls_show_errors(MSG_WARNING, __func__,
1382 "Failed to parse ca_cert_blob");
1383 return -1;
1384 }
1385
1386 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1387 unsigned long err = ERR_peek_error();
1388 tls_show_errors(MSG_WARNING, __func__,
1389 "Failed to add ca_cert_blob to "
1390 "certificate store");
1391 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1392 ERR_GET_REASON(err) ==
1393 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1394 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1395 "cert already in hash table error",
1396 __func__);
1397 } else {
1398 X509_free(cert);
1399 return -1;
1400 }
1401 }
1402 X509_free(cert);
1403 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1404 "to certificate store", __func__);
1405 return 0;
1406 }
1407
1408#ifdef ANDROID
1409 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1410 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1411 STACK_OF(X509_INFO) *stack = NULL;
1412 int i;
1413
1414 if (bio) {
1415 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1416 BIO_free(bio);
1417 }
1418 if (!stack)
1419 return -1;
1420
1421 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1422 X509_INFO *info = sk_X509_INFO_value(stack, i);
1423 if (info->x509) {
1424 X509_STORE_add_cert(ssl_ctx->cert_store,
1425 info->x509);
1426 }
1427 if (info->crl) {
1428 X509_STORE_add_crl(ssl_ctx->cert_store,
1429 info->crl);
1430 }
1431 }
1432 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1433 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1434 return 0;
1435 }
1436#endif /* ANDROID */
1437
1438#ifdef CONFIG_NATIVE_WINDOWS
1439 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1440 0) {
1441 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1442 "system certificate store");
1443 return 0;
1444 }
1445#endif /* CONFIG_NATIVE_WINDOWS */
1446
1447 if (ca_cert || ca_path) {
1448#ifndef OPENSSL_NO_STDIO
1449 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1450 1) {
1451 tls_show_errors(MSG_WARNING, __func__,
1452 "Failed to load root certificates");
1453 if (ca_cert &&
1454 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1455 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1456 "DER format CA certificate",
1457 __func__);
1458 } else
1459 return -1;
1460 } else {
1461 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1462 "certificate(s) loaded");
1463 tls_get_errors(ssl_ctx);
1464 }
1465#else /* OPENSSL_NO_STDIO */
1466 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1467 __func__);
1468 return -1;
1469#endif /* OPENSSL_NO_STDIO */
1470 } else {
1471 /* No ca_cert configured - do not try to verify server
1472 * certificate */
1473 conn->ca_cert_verify = 0;
1474 }
1475
1476 return 0;
1477}
1478
1479
1480static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1481{
1482 if (ca_cert) {
1483 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1484 {
1485 tls_show_errors(MSG_WARNING, __func__,
1486 "Failed to load root certificates");
1487 return -1;
1488 }
1489
1490 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1491 "certificate(s) loaded");
1492
1493#ifndef OPENSSL_NO_STDIO
1494 /* Add the same CAs to the client certificate requests */
1495 SSL_CTX_set_client_CA_list(ssl_ctx,
1496 SSL_load_client_CA_file(ca_cert));
1497#endif /* OPENSSL_NO_STDIO */
1498 }
1499
1500 return 0;
1501}
1502
1503
1504int tls_global_set_verify(void *ssl_ctx, int check_crl)
1505{
1506 int flags;
1507
1508 if (check_crl) {
1509 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1510 if (cs == NULL) {
1511 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1512 "certificate store when enabling "
1513 "check_crl");
1514 return -1;
1515 }
1516 flags = X509_V_FLAG_CRL_CHECK;
1517 if (check_crl == 2)
1518 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1519 X509_STORE_set_flags(cs, flags);
1520 }
1521 return 0;
1522}
1523
1524
1525static int tls_connection_set_subject_match(struct tls_connection *conn,
1526 const char *subject_match,
1527 const char *altsubject_match)
1528{
1529 os_free(conn->subject_match);
1530 conn->subject_match = NULL;
1531 if (subject_match) {
1532 conn->subject_match = os_strdup(subject_match);
1533 if (conn->subject_match == NULL)
1534 return -1;
1535 }
1536
1537 os_free(conn->altsubject_match);
1538 conn->altsubject_match = NULL;
1539 if (altsubject_match) {
1540 conn->altsubject_match = os_strdup(altsubject_match);
1541 if (conn->altsubject_match == NULL)
1542 return -1;
1543 }
1544
1545 return 0;
1546}
1547
1548
1549int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1550 int verify_peer)
1551{
1552 static int counter = 0;
1553
1554 if (conn == NULL)
1555 return -1;
1556
1557 if (verify_peer) {
1558 conn->ca_cert_verify = 1;
1559 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1560 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1561 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1562 } else {
1563 conn->ca_cert_verify = 0;
1564 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1565 }
1566
1567 SSL_set_accept_state(conn->ssl);
1568
1569 /*
1570 * Set session id context in order to avoid fatal errors when client
1571 * tries to resume a session. However, set the context to a unique
1572 * value in order to effectively disable session resumption for now
1573 * since not all areas of the server code are ready for it (e.g.,
1574 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1575 * handshake).
1576 */
1577 counter++;
1578 SSL_set_session_id_context(conn->ssl,
1579 (const unsigned char *) &counter,
1580 sizeof(counter));
1581
1582 return 0;
1583}
1584
1585
1586static int tls_connection_client_cert(struct tls_connection *conn,
1587 const char *client_cert,
1588 const u8 *client_cert_blob,
1589 size_t client_cert_blob_len)
1590{
1591 if (client_cert == NULL && client_cert_blob == NULL)
1592 return 0;
1593
1594 if (client_cert_blob &&
1595 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1596 client_cert_blob_len) == 1) {
1597 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1598 "OK");
1599 return 0;
1600 } else if (client_cert_blob) {
1601 tls_show_errors(MSG_DEBUG, __func__,
1602 "SSL_use_certificate_ASN1 failed");
1603 }
1604
1605 if (client_cert == NULL)
1606 return -1;
1607
1608#ifdef ANDROID
1609 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1610 BIO *bio = BIO_from_keystore(&client_cert[11]);
1611 X509 *x509 = NULL;
1612 int ret = -1;
1613 if (bio) {
1614 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1615 BIO_free(bio);
1616 }
1617 if (x509) {
1618 if (SSL_use_certificate(conn->ssl, x509) == 1)
1619 ret = 0;
1620 X509_free(x509);
1621 }
1622 return ret;
1623 }
1624#endif /* ANDROID */
1625
1626#ifndef OPENSSL_NO_STDIO
1627 if (SSL_use_certificate_file(conn->ssl, client_cert,
1628 SSL_FILETYPE_ASN1) == 1) {
1629 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1630 " --> OK");
1631 return 0;
1632 }
1633
1634 if (SSL_use_certificate_file(conn->ssl, client_cert,
1635 SSL_FILETYPE_PEM) == 1) {
1636 ERR_clear_error();
1637 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1638 " --> OK");
1639 return 0;
1640 }
1641
1642 tls_show_errors(MSG_DEBUG, __func__,
1643 "SSL_use_certificate_file failed");
1644#else /* OPENSSL_NO_STDIO */
1645 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1646#endif /* OPENSSL_NO_STDIO */
1647
1648 return -1;
1649}
1650
1651
1652static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1653{
1654#ifndef OPENSSL_NO_STDIO
1655 if (client_cert == NULL)
1656 return 0;
1657
1658 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1659 SSL_FILETYPE_ASN1) != 1 &&
Dmitry Shmidt1f69aa52012-01-24 16:10:04 -08001660 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001661 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1662 SSL_FILETYPE_PEM) != 1) {
1663 tls_show_errors(MSG_INFO, __func__,
1664 "Failed to load client certificate");
1665 return -1;
1666 }
1667 return 0;
1668#else /* OPENSSL_NO_STDIO */
1669 if (client_cert == NULL)
1670 return 0;
1671 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1672 return -1;
1673#endif /* OPENSSL_NO_STDIO */
1674}
1675
1676
1677static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1678{
1679 if (password == NULL) {
1680 return 0;
1681 }
1682 os_strlcpy(buf, (char *) password, size);
1683 return os_strlen(buf);
1684}
1685
1686
1687#ifdef PKCS12_FUNCS
1688static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1689 const char *passwd)
1690{
1691 EVP_PKEY *pkey;
1692 X509 *cert;
1693 STACK_OF(X509) *certs;
1694 int res = 0;
1695 char buf[256];
1696
1697 pkey = NULL;
1698 cert = NULL;
1699 certs = NULL;
1700 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1701 tls_show_errors(MSG_DEBUG, __func__,
1702 "Failed to parse PKCS12 file");
1703 PKCS12_free(p12);
1704 return -1;
1705 }
1706 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1707
1708 if (cert) {
1709 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1710 sizeof(buf));
1711 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1712 "subject='%s'", buf);
1713 if (ssl) {
1714 if (SSL_use_certificate(ssl, cert) != 1)
1715 res = -1;
1716 } else {
1717 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1718 res = -1;
1719 }
1720 X509_free(cert);
1721 }
1722
1723 if (pkey) {
1724 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1725 if (ssl) {
1726 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1727 res = -1;
1728 } else {
1729 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1730 res = -1;
1731 }
1732 EVP_PKEY_free(pkey);
1733 }
1734
1735 if (certs) {
1736 while ((cert = sk_X509_pop(certs)) != NULL) {
1737 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1738 sizeof(buf));
1739 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1740 " from PKCS12: subject='%s'", buf);
1741 /*
1742 * There is no SSL equivalent for the chain cert - so
1743 * always add it to the context...
1744 */
1745 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1746 res = -1;
1747 break;
1748 }
1749 }
1750 sk_X509_free(certs);
1751 }
1752
1753 PKCS12_free(p12);
1754
1755 if (res < 0)
1756 tls_get_errors(ssl_ctx);
1757
1758 return res;
1759}
1760#endif /* PKCS12_FUNCS */
1761
1762
1763static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1764 const char *passwd)
1765{
1766#ifdef PKCS12_FUNCS
1767 FILE *f;
1768 PKCS12 *p12;
1769
1770 f = fopen(private_key, "rb");
1771 if (f == NULL)
1772 return -1;
1773
1774 p12 = d2i_PKCS12_fp(f, NULL);
1775 fclose(f);
1776
1777 if (p12 == NULL) {
1778 tls_show_errors(MSG_INFO, __func__,
1779 "Failed to use PKCS#12 file");
1780 return -1;
1781 }
1782
1783 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1784
1785#else /* PKCS12_FUNCS */
1786 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1787 "p12/pfx files");
1788 return -1;
1789#endif /* PKCS12_FUNCS */
1790}
1791
1792
1793static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1794 const u8 *blob, size_t len, const char *passwd)
1795{
1796#ifdef PKCS12_FUNCS
1797 PKCS12 *p12;
1798
1799 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1800 if (p12 == NULL) {
1801 tls_show_errors(MSG_INFO, __func__,
1802 "Failed to use PKCS#12 blob");
1803 return -1;
1804 }
1805
1806 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1807
1808#else /* PKCS12_FUNCS */
1809 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1810 "p12/pfx blobs");
1811 return -1;
1812#endif /* PKCS12_FUNCS */
1813}
1814
1815
1816#ifndef OPENSSL_NO_ENGINE
1817static int tls_engine_get_cert(struct tls_connection *conn,
1818 const char *cert_id,
1819 X509 **cert)
1820{
1821 /* this runs after the private key is loaded so no PIN is required */
1822 struct {
1823 const char *cert_id;
1824 X509 *cert;
1825 } params;
1826 params.cert_id = cert_id;
1827 params.cert = NULL;
1828
1829 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1830 0, &params, NULL, 1)) {
1831 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1832 " '%s' [%s]", cert_id,
1833 ERR_error_string(ERR_get_error(), NULL));
1834 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1835 }
1836 if (!params.cert) {
1837 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1838 " '%s'", cert_id);
1839 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1840 }
1841 *cert = params.cert;
1842 return 0;
1843}
1844#endif /* OPENSSL_NO_ENGINE */
1845
1846
1847static int tls_connection_engine_client_cert(struct tls_connection *conn,
1848 const char *cert_id)
1849{
1850#ifndef OPENSSL_NO_ENGINE
1851 X509 *cert;
1852
1853 if (tls_engine_get_cert(conn, cert_id, &cert))
1854 return -1;
1855
1856 if (!SSL_use_certificate(conn->ssl, cert)) {
1857 tls_show_errors(MSG_ERROR, __func__,
1858 "SSL_use_certificate failed");
1859 X509_free(cert);
1860 return -1;
1861 }
1862 X509_free(cert);
1863 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1864 "OK");
1865 return 0;
1866
1867#else /* OPENSSL_NO_ENGINE */
1868 return -1;
1869#endif /* OPENSSL_NO_ENGINE */
1870}
1871
1872
1873static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1874 struct tls_connection *conn,
1875 const char *ca_cert_id)
1876{
1877#ifndef OPENSSL_NO_ENGINE
1878 X509 *cert;
1879 SSL_CTX *ssl_ctx = _ssl_ctx;
1880
1881 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1882 return -1;
1883
1884 /* start off the same as tls_connection_ca_cert */
1885 X509_STORE_free(ssl_ctx->cert_store);
1886 ssl_ctx->cert_store = X509_STORE_new();
1887 if (ssl_ctx->cert_store == NULL) {
1888 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1889 "certificate store", __func__);
1890 X509_free(cert);
1891 return -1;
1892 }
1893 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1894 unsigned long err = ERR_peek_error();
1895 tls_show_errors(MSG_WARNING, __func__,
1896 "Failed to add CA certificate from engine "
1897 "to certificate store");
1898 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1899 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1900 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1901 " already in hash table error",
1902 __func__);
1903 } else {
1904 X509_free(cert);
1905 return -1;
1906 }
1907 }
1908 X509_free(cert);
1909 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1910 "to certificate store", __func__);
1911 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1912 return 0;
1913
1914#else /* OPENSSL_NO_ENGINE */
1915 return -1;
1916#endif /* OPENSSL_NO_ENGINE */
1917}
1918
1919
1920static int tls_connection_engine_private_key(struct tls_connection *conn)
1921{
1922#ifndef OPENSSL_NO_ENGINE
1923 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1924 tls_show_errors(MSG_ERROR, __func__,
1925 "ENGINE: cannot use private key for TLS");
1926 return -1;
1927 }
1928 if (!SSL_check_private_key(conn->ssl)) {
1929 tls_show_errors(MSG_INFO, __func__,
1930 "Private key failed verification");
1931 return -1;
1932 }
1933 return 0;
1934#else /* OPENSSL_NO_ENGINE */
1935 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1936 "engine support was not compiled in");
1937 return -1;
1938#endif /* OPENSSL_NO_ENGINE */
1939}
1940
1941
1942static int tls_connection_private_key(void *_ssl_ctx,
1943 struct tls_connection *conn,
1944 const char *private_key,
1945 const char *private_key_passwd,
1946 const u8 *private_key_blob,
1947 size_t private_key_blob_len)
1948{
1949 SSL_CTX *ssl_ctx = _ssl_ctx;
1950 char *passwd;
1951 int ok;
1952
1953 if (private_key == NULL && private_key_blob == NULL)
1954 return 0;
1955
1956 if (private_key_passwd) {
1957 passwd = os_strdup(private_key_passwd);
1958 if (passwd == NULL)
1959 return -1;
1960 } else
1961 passwd = NULL;
1962
1963 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1964 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1965
1966 ok = 0;
1967 while (private_key_blob) {
1968 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1969 (u8 *) private_key_blob,
1970 private_key_blob_len) == 1) {
1971 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1972 "ASN1(EVP_PKEY_RSA) --> OK");
1973 ok = 1;
1974 break;
1975 }
1976
1977 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1978 (u8 *) private_key_blob,
1979 private_key_blob_len) == 1) {
1980 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1981 "ASN1(EVP_PKEY_DSA) --> OK");
1982 ok = 1;
1983 break;
1984 }
1985
1986 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1987 (u8 *) private_key_blob,
1988 private_key_blob_len) == 1) {
1989 wpa_printf(MSG_DEBUG, "OpenSSL: "
1990 "SSL_use_RSAPrivateKey_ASN1 --> OK");
1991 ok = 1;
1992 break;
1993 }
1994
1995 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1996 private_key_blob_len, passwd) == 0) {
1997 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1998 "OK");
1999 ok = 1;
2000 break;
2001 }
2002
2003 break;
2004 }
2005
2006#ifdef ANDROID
2007 if (!ok && private_key &&
2008 os_strncmp("keystore://", private_key, 11) == 0) {
2009 BIO *bio = BIO_from_keystore(&private_key[11]);
2010 EVP_PKEY *pkey = NULL;
2011 if (bio) {
2012 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
2013 BIO_free(bio);
2014 }
2015 if (pkey) {
2016 if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
2017 wpa_printf(MSG_DEBUG, "OpenSSL: Private key "
2018 "from keystore");
2019 ok = 1;
2020 }
2021 EVP_PKEY_free(pkey);
2022 }
2023 }
2024#endif /* ANDROID */
2025
2026 while (!ok && private_key) {
2027#ifndef OPENSSL_NO_STDIO
2028 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2029 SSL_FILETYPE_ASN1) == 1) {
2030 wpa_printf(MSG_DEBUG, "OpenSSL: "
2031 "SSL_use_PrivateKey_File (DER) --> OK");
2032 ok = 1;
2033 break;
2034 }
2035
2036 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2037 SSL_FILETYPE_PEM) == 1) {
2038 wpa_printf(MSG_DEBUG, "OpenSSL: "
2039 "SSL_use_PrivateKey_File (PEM) --> OK");
2040 ok = 1;
2041 break;
2042 }
2043#else /* OPENSSL_NO_STDIO */
2044 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2045 __func__);
2046#endif /* OPENSSL_NO_STDIO */
2047
2048 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2049 == 0) {
2050 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2051 "--> OK");
2052 ok = 1;
2053 break;
2054 }
2055
2056 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2057 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2058 "access certificate store --> OK");
2059 ok = 1;
2060 break;
2061 }
2062
2063 break;
2064 }
2065
2066 if (!ok) {
2067 tls_show_errors(MSG_INFO, __func__,
2068 "Failed to load private key");
2069 os_free(passwd);
2070 return -1;
2071 }
2072 ERR_clear_error();
2073 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2074 os_free(passwd);
2075
2076 if (!SSL_check_private_key(conn->ssl)) {
2077 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2078 "verification");
2079 return -1;
2080 }
2081
2082 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2083 return 0;
2084}
2085
2086
2087static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2088 const char *private_key_passwd)
2089{
2090 char *passwd;
2091
2092 if (private_key == NULL)
2093 return 0;
2094
2095 if (private_key_passwd) {
2096 passwd = os_strdup(private_key_passwd);
2097 if (passwd == NULL)
2098 return -1;
2099 } else
2100 passwd = NULL;
2101
2102 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2103 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2104 if (
2105#ifndef OPENSSL_NO_STDIO
2106 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2107 SSL_FILETYPE_ASN1) != 1 &&
2108 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2109 SSL_FILETYPE_PEM) != 1 &&
2110#endif /* OPENSSL_NO_STDIO */
2111 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2112 tls_show_errors(MSG_INFO, __func__,
2113 "Failed to load private key");
2114 os_free(passwd);
2115 ERR_clear_error();
2116 return -1;
2117 }
2118 os_free(passwd);
2119 ERR_clear_error();
2120 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2121
2122 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2123 tls_show_errors(MSG_INFO, __func__,
2124 "Private key failed verification");
2125 return -1;
2126 }
2127
2128 return 0;
2129}
2130
2131
2132static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2133{
2134#ifdef OPENSSL_NO_DH
2135 if (dh_file == NULL)
2136 return 0;
2137 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2138 "dh_file specified");
2139 return -1;
2140#else /* OPENSSL_NO_DH */
2141 DH *dh;
2142 BIO *bio;
2143
2144 /* TODO: add support for dh_blob */
2145 if (dh_file == NULL)
2146 return 0;
2147 if (conn == NULL)
2148 return -1;
2149
2150 bio = BIO_new_file(dh_file, "r");
2151 if (bio == NULL) {
2152 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2153 dh_file, ERR_error_string(ERR_get_error(), NULL));
2154 return -1;
2155 }
2156 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2157 BIO_free(bio);
2158#ifndef OPENSSL_NO_DSA
2159 while (dh == NULL) {
2160 DSA *dsa;
2161 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2162 " trying to parse as DSA params", dh_file,
2163 ERR_error_string(ERR_get_error(), NULL));
2164 bio = BIO_new_file(dh_file, "r");
2165 if (bio == NULL)
2166 break;
2167 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2168 BIO_free(bio);
2169 if (!dsa) {
2170 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2171 "'%s': %s", dh_file,
2172 ERR_error_string(ERR_get_error(), NULL));
2173 break;
2174 }
2175
2176 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2177 dh = DSA_dup_DH(dsa);
2178 DSA_free(dsa);
2179 if (dh == NULL) {
2180 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2181 "params into DH params");
2182 break;
2183 }
2184 break;
2185 }
2186#endif /* !OPENSSL_NO_DSA */
2187 if (dh == NULL) {
2188 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2189 "'%s'", dh_file);
2190 return -1;
2191 }
2192
2193 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2194 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2195 "%s", dh_file,
2196 ERR_error_string(ERR_get_error(), NULL));
2197 DH_free(dh);
2198 return -1;
2199 }
2200 DH_free(dh);
2201 return 0;
2202#endif /* OPENSSL_NO_DH */
2203}
2204
2205
2206static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2207{
2208#ifdef OPENSSL_NO_DH
2209 if (dh_file == NULL)
2210 return 0;
2211 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2212 "dh_file specified");
2213 return -1;
2214#else /* OPENSSL_NO_DH */
2215 DH *dh;
2216 BIO *bio;
2217
2218 /* TODO: add support for dh_blob */
2219 if (dh_file == NULL)
2220 return 0;
2221 if (ssl_ctx == NULL)
2222 return -1;
2223
2224 bio = BIO_new_file(dh_file, "r");
2225 if (bio == NULL) {
2226 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2227 dh_file, ERR_error_string(ERR_get_error(), NULL));
2228 return -1;
2229 }
2230 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2231 BIO_free(bio);
2232#ifndef OPENSSL_NO_DSA
2233 while (dh == NULL) {
2234 DSA *dsa;
2235 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2236 " trying to parse as DSA params", dh_file,
2237 ERR_error_string(ERR_get_error(), NULL));
2238 bio = BIO_new_file(dh_file, "r");
2239 if (bio == NULL)
2240 break;
2241 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2242 BIO_free(bio);
2243 if (!dsa) {
2244 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2245 "'%s': %s", dh_file,
2246 ERR_error_string(ERR_get_error(), NULL));
2247 break;
2248 }
2249
2250 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2251 dh = DSA_dup_DH(dsa);
2252 DSA_free(dsa);
2253 if (dh == NULL) {
2254 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2255 "params into DH params");
2256 break;
2257 }
2258 break;
2259 }
2260#endif /* !OPENSSL_NO_DSA */
2261 if (dh == NULL) {
2262 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2263 "'%s'", dh_file);
2264 return -1;
2265 }
2266
2267 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2268 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2269 "%s", dh_file,
2270 ERR_error_string(ERR_get_error(), NULL));
2271 DH_free(dh);
2272 return -1;
2273 }
2274 DH_free(dh);
2275 return 0;
2276#endif /* OPENSSL_NO_DH */
2277}
2278
2279
2280int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2281 struct tls_keys *keys)
2282{
2283 SSL *ssl;
2284
2285 if (conn == NULL || keys == NULL)
2286 return -1;
2287 ssl = conn->ssl;
2288 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2289 return -1;
2290
2291 os_memset(keys, 0, sizeof(*keys));
2292 keys->master_key = ssl->session->master_key;
2293 keys->master_key_len = ssl->session->master_key_length;
2294 keys->client_random = ssl->s3->client_random;
2295 keys->client_random_len = SSL3_RANDOM_SIZE;
2296 keys->server_random = ssl->s3->server_random;
2297 keys->server_random_len = SSL3_RANDOM_SIZE;
2298
2299 return 0;
2300}
2301
2302
2303int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2304 const char *label, int server_random_first,
2305 u8 *out, size_t out_len)
2306{
2307 return -1;
2308}
2309
2310
2311static struct wpabuf *
2312openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2313 int server)
2314{
2315 int res;
2316 struct wpabuf *out_data;
2317
2318 /*
2319 * Give TLS handshake data from the server (if available) to OpenSSL
2320 * for processing.
2321 */
2322 if (in_data &&
2323 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2324 < 0) {
2325 tls_show_errors(MSG_INFO, __func__,
2326 "Handshake failed - BIO_write");
2327 return NULL;
2328 }
2329
2330 /* Initiate TLS handshake or continue the existing handshake */
2331 if (server)
2332 res = SSL_accept(conn->ssl);
2333 else
2334 res = SSL_connect(conn->ssl);
2335 if (res != 1) {
2336 int err = SSL_get_error(conn->ssl, res);
2337 if (err == SSL_ERROR_WANT_READ)
2338 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2339 "more data");
2340 else if (err == SSL_ERROR_WANT_WRITE)
2341 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2342 "write");
2343 else {
2344 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2345 conn->failed++;
2346 }
2347 }
2348
2349 /* Get the TLS handshake data to be sent to the server */
2350 res = BIO_ctrl_pending(conn->ssl_out);
2351 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2352 out_data = wpabuf_alloc(res);
2353 if (out_data == NULL) {
2354 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2355 "handshake output (%d bytes)", res);
2356 if (BIO_reset(conn->ssl_out) < 0) {
2357 tls_show_errors(MSG_INFO, __func__,
2358 "BIO_reset failed");
2359 }
2360 return NULL;
2361 }
2362 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2363 res);
2364 if (res < 0) {
2365 tls_show_errors(MSG_INFO, __func__,
2366 "Handshake failed - BIO_read");
2367 if (BIO_reset(conn->ssl_out) < 0) {
2368 tls_show_errors(MSG_INFO, __func__,
2369 "BIO_reset failed");
2370 }
2371 wpabuf_free(out_data);
2372 return NULL;
2373 }
2374 wpabuf_put(out_data, res);
2375
2376 return out_data;
2377}
2378
2379
2380static struct wpabuf *
2381openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2382{
2383 struct wpabuf *appl_data;
2384 int res;
2385
2386 appl_data = wpabuf_alloc(max_len + 100);
2387 if (appl_data == NULL)
2388 return NULL;
2389
2390 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2391 wpabuf_size(appl_data));
2392 if (res < 0) {
2393 int err = SSL_get_error(conn->ssl, res);
2394 if (err == SSL_ERROR_WANT_READ ||
2395 err == SSL_ERROR_WANT_WRITE) {
2396 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2397 "included");
2398 } else {
2399 tls_show_errors(MSG_INFO, __func__,
2400 "Failed to read possible "
2401 "Application Data");
2402 }
2403 wpabuf_free(appl_data);
2404 return NULL;
2405 }
2406
2407 wpabuf_put(appl_data, res);
2408 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2409 "message", appl_data);
2410
2411 return appl_data;
2412}
2413
2414
2415static struct wpabuf *
2416openssl_connection_handshake(struct tls_connection *conn,
2417 const struct wpabuf *in_data,
2418 struct wpabuf **appl_data, int server)
2419{
2420 struct wpabuf *out_data;
2421
2422 if (appl_data)
2423 *appl_data = NULL;
2424
2425 out_data = openssl_handshake(conn, in_data, server);
2426 if (out_data == NULL)
2427 return NULL;
2428
2429 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2430 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2431
2432 return out_data;
2433}
2434
2435
2436struct wpabuf *
2437tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2438 const struct wpabuf *in_data,
2439 struct wpabuf **appl_data)
2440{
2441 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2442}
2443
2444
2445struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2446 struct tls_connection *conn,
2447 const struct wpabuf *in_data,
2448 struct wpabuf **appl_data)
2449{
2450 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2451}
2452
2453
2454struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2455 struct tls_connection *conn,
2456 const struct wpabuf *in_data)
2457{
2458 int res;
2459 struct wpabuf *buf;
2460
2461 if (conn == NULL)
2462 return NULL;
2463
2464 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2465 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2466 (res = BIO_reset(conn->ssl_out)) < 0) {
2467 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2468 return NULL;
2469 }
2470 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2471 if (res < 0) {
2472 tls_show_errors(MSG_INFO, __func__,
2473 "Encryption failed - SSL_write");
2474 return NULL;
2475 }
2476
2477 /* Read encrypted data to be sent to the server */
2478 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2479 if (buf == NULL)
2480 return NULL;
2481 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2482 if (res < 0) {
2483 tls_show_errors(MSG_INFO, __func__,
2484 "Encryption failed - BIO_read");
2485 wpabuf_free(buf);
2486 return NULL;
2487 }
2488 wpabuf_put(buf, res);
2489
2490 return buf;
2491}
2492
2493
2494struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2495 struct tls_connection *conn,
2496 const struct wpabuf *in_data)
2497{
2498 int res;
2499 struct wpabuf *buf;
2500
2501 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2502 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2503 wpabuf_len(in_data));
2504 if (res < 0) {
2505 tls_show_errors(MSG_INFO, __func__,
2506 "Decryption failed - BIO_write");
2507 return NULL;
2508 }
2509 if (BIO_reset(conn->ssl_out) < 0) {
2510 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2511 return NULL;
2512 }
2513
2514 /* Read decrypted data for further processing */
2515 /*
2516 * Even though we try to disable TLS compression, it is possible that
2517 * this cannot be done with all TLS libraries. Add extra buffer space
2518 * to handle the possibility of the decrypted data being longer than
2519 * input data.
2520 */
2521 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2522 if (buf == NULL)
2523 return NULL;
2524 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2525 if (res < 0) {
2526 tls_show_errors(MSG_INFO, __func__,
2527 "Decryption failed - SSL_read");
2528 wpabuf_free(buf);
2529 return NULL;
2530 }
2531 wpabuf_put(buf, res);
2532
2533 return buf;
2534}
2535
2536
2537int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2538{
2539 return conn ? conn->ssl->hit : 0;
2540}
2541
2542
2543int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2544 u8 *ciphers)
2545{
2546 char buf[100], *pos, *end;
2547 u8 *c;
2548 int ret;
2549
2550 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2551 return -1;
2552
2553 buf[0] = '\0';
2554 pos = buf;
2555 end = pos + sizeof(buf);
2556
2557 c = ciphers;
2558 while (*c != TLS_CIPHER_NONE) {
2559 const char *suite;
2560
2561 switch (*c) {
2562 case TLS_CIPHER_RC4_SHA:
2563 suite = "RC4-SHA";
2564 break;
2565 case TLS_CIPHER_AES128_SHA:
2566 suite = "AES128-SHA";
2567 break;
2568 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2569 suite = "DHE-RSA-AES128-SHA";
2570 break;
2571 case TLS_CIPHER_ANON_DH_AES128_SHA:
2572 suite = "ADH-AES128-SHA";
2573 break;
2574 default:
2575 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2576 "cipher selection: %d", *c);
2577 return -1;
2578 }
2579 ret = os_snprintf(pos, end - pos, ":%s", suite);
2580 if (ret < 0 || ret >= end - pos)
2581 break;
2582 pos += ret;
2583
2584 c++;
2585 }
2586
2587 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2588
2589 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2590 tls_show_errors(MSG_INFO, __func__,
2591 "Cipher suite configuration failed");
2592 return -1;
2593 }
2594
2595 return 0;
2596}
2597
2598
2599int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2600 char *buf, size_t buflen)
2601{
2602 const char *name;
2603 if (conn == NULL || conn->ssl == NULL)
2604 return -1;
2605
2606 name = SSL_get_cipher(conn->ssl);
2607 if (name == NULL)
2608 return -1;
2609
2610 os_strlcpy(buf, name, buflen);
2611 return 0;
2612}
2613
2614
2615int tls_connection_enable_workaround(void *ssl_ctx,
2616 struct tls_connection *conn)
2617{
2618 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2619
2620 return 0;
2621}
2622
2623
2624#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2625/* ClientHello TLS extensions require a patch to openssl, so this function is
2626 * commented out unless explicitly needed for EAP-FAST in order to be able to
2627 * build this file with unmodified openssl. */
2628int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2629 int ext_type, const u8 *data,
2630 size_t data_len)
2631{
2632 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2633 return -1;
2634
2635#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2636 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2637 data_len) != 1)
2638 return -1;
2639#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2640 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2641 data_len) != 1)
2642 return -1;
2643#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2644
2645 return 0;
2646}
2647#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2648
2649
2650int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2651{
2652 if (conn == NULL)
2653 return -1;
2654 return conn->failed;
2655}
2656
2657
2658int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2659{
2660 if (conn == NULL)
2661 return -1;
2662 return conn->read_alerts;
2663}
2664
2665
2666int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2667{
2668 if (conn == NULL)
2669 return -1;
2670 return conn->write_alerts;
2671}
2672
2673
2674int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2675 const struct tls_connection_params *params)
2676{
2677 int ret;
2678 unsigned long err;
2679
2680 if (conn == NULL)
2681 return -1;
2682
2683 while ((err = ERR_get_error())) {
2684 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2685 __func__, ERR_error_string(err, NULL));
2686 }
2687
2688 if (params->engine) {
2689 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2690 ret = tls_engine_init(conn, params->engine_id, params->pin,
2691 params->key_id, params->cert_id,
2692 params->ca_cert_id);
2693 if (ret)
2694 return ret;
2695 }
2696 if (tls_connection_set_subject_match(conn,
2697 params->subject_match,
2698 params->altsubject_match))
2699 return -1;
2700
2701 if (params->engine && params->ca_cert_id) {
2702 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2703 params->ca_cert_id))
2704 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2705 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2706 params->ca_cert_blob,
2707 params->ca_cert_blob_len,
2708 params->ca_path))
2709 return -1;
2710
2711 if (params->engine && params->cert_id) {
2712 if (tls_connection_engine_client_cert(conn, params->cert_id))
2713 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2714 } else if (tls_connection_client_cert(conn, params->client_cert,
2715 params->client_cert_blob,
2716 params->client_cert_blob_len))
2717 return -1;
2718
2719 if (params->engine && params->key_id) {
2720 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2721 if (tls_connection_engine_private_key(conn))
2722 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2723 } else if (tls_connection_private_key(tls_ctx, conn,
2724 params->private_key,
2725 params->private_key_passwd,
2726 params->private_key_blob,
2727 params->private_key_blob_len)) {
2728 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2729 params->private_key);
2730 return -1;
2731 }
2732
2733 if (tls_connection_dh(conn, params->dh_file)) {
2734 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2735 params->dh_file);
2736 return -1;
2737 }
2738
Dmitry Shmidtc55524a2011-07-07 11:18:38 -07002739 conn->flags = params->flags;
2740
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07002741 tls_get_errors(tls_ctx);
2742
2743 return 0;
2744}
2745
2746
2747int tls_global_set_params(void *tls_ctx,
2748 const struct tls_connection_params *params)
2749{
2750 SSL_CTX *ssl_ctx = tls_ctx;
2751 unsigned long err;
2752
2753 while ((err = ERR_get_error())) {
2754 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2755 __func__, ERR_error_string(err, NULL));
2756 }
2757
2758 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2759 return -1;
2760
2761 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2762 return -1;
2763
2764 if (tls_global_private_key(ssl_ctx, params->private_key,
2765 params->private_key_passwd))
2766 return -1;
2767
2768 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2769 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2770 params->dh_file);
2771 return -1;
2772 }
2773
2774 return 0;
2775}
2776
2777
2778int tls_connection_get_keyblock_size(void *tls_ctx,
2779 struct tls_connection *conn)
2780{
2781 const EVP_CIPHER *c;
2782 const EVP_MD *h;
2783
2784 if (conn == NULL || conn->ssl == NULL ||
2785 conn->ssl->enc_read_ctx == NULL ||
2786 conn->ssl->enc_read_ctx->cipher == NULL ||
2787 conn->ssl->read_hash == NULL)
2788 return -1;
2789
2790 c = conn->ssl->enc_read_ctx->cipher;
2791#if OPENSSL_VERSION_NUMBER >= 0x00909000L
2792 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2793#else
2794 h = conn->ssl->read_hash;
2795#endif
2796
2797 return 2 * (EVP_CIPHER_key_length(c) +
2798 EVP_MD_size(h) +
2799 EVP_CIPHER_iv_length(c));
2800}
2801
2802
2803unsigned int tls_capabilities(void *tls_ctx)
2804{
2805 return 0;
2806}
2807
2808
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07002809#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2810/* Pre-shared secred requires a patch to openssl, so this function is
2811 * commented out unless explicitly needed for EAP-FAST in order to be able to
2812 * build this file with unmodified openssl. */
2813
2814static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2815 STACK_OF(SSL_CIPHER) *peer_ciphers,
2816 SSL_CIPHER **cipher, void *arg)
2817{
2818 struct tls_connection *conn = arg;
2819 int ret;
2820
2821 if (conn == NULL || conn->session_ticket_cb == NULL)
2822 return 0;
2823
2824 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2825 conn->session_ticket,
2826 conn->session_ticket_len,
2827 s->s3->client_random,
2828 s->s3->server_random, secret);
2829 os_free(conn->session_ticket);
2830 conn->session_ticket = NULL;
2831
2832 if (ret <= 0)
2833 return 0;
2834
2835 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2836 return 1;
2837}
2838
2839
2840#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2841static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2842 int len, void *arg)
2843{
2844 struct tls_connection *conn = arg;
2845
2846 if (conn == NULL || conn->session_ticket_cb == NULL)
2847 return 0;
2848
2849 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2850
2851 os_free(conn->session_ticket);
2852 conn->session_ticket = NULL;
2853
2854 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2855 "extension", data, len);
2856
2857 conn->session_ticket = os_malloc(len);
2858 if (conn->session_ticket == NULL)
2859 return 0;
2860
2861 os_memcpy(conn->session_ticket, data, len);
2862 conn->session_ticket_len = len;
2863
2864 return 1;
2865}
2866#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2867#ifdef SSL_OP_NO_TICKET
2868static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2869 unsigned char *data, int len, void *arg)
2870{
2871 struct tls_connection *conn = arg;
2872
2873 if (conn == NULL || conn->session_ticket_cb == NULL)
2874 return;
2875
2876 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2877 type, len);
2878
2879 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2880 os_free(conn->session_ticket);
2881 conn->session_ticket = NULL;
2882
2883 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2884 "extension", data, len);
2885 conn->session_ticket = os_malloc(len);
2886 if (conn->session_ticket == NULL)
2887 return;
2888
2889 os_memcpy(conn->session_ticket, data, len);
2890 conn->session_ticket_len = len;
2891 }
2892}
2893#else /* SSL_OP_NO_TICKET */
2894static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2895{
2896 struct tls_connection *conn = arg;
2897
2898 if (conn == NULL || conn->session_ticket_cb == NULL)
2899 return 0;
2900
2901 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2902 ext->type, ext->length);
2903
2904 os_free(conn->session_ticket);
2905 conn->session_ticket = NULL;
2906
2907 if (ext->type == 35) {
2908 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2909 "extension", ext->data, ext->length);
2910 conn->session_ticket = os_malloc(ext->length);
2911 if (conn->session_ticket == NULL)
2912 return SSL_AD_INTERNAL_ERROR;
2913
2914 os_memcpy(conn->session_ticket, ext->data, ext->length);
2915 conn->session_ticket_len = ext->length;
2916 }
2917
2918 return 0;
2919}
2920#endif /* SSL_OP_NO_TICKET */
2921#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2922#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2923
2924
2925int tls_connection_set_session_ticket_cb(void *tls_ctx,
2926 struct tls_connection *conn,
2927 tls_session_ticket_cb cb,
2928 void *ctx)
2929{
2930#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2931 conn->session_ticket_cb = cb;
2932 conn->session_ticket_cb_ctx = ctx;
2933
2934 if (cb) {
2935 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2936 conn) != 1)
2937 return -1;
2938#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2939 SSL_set_session_ticket_ext_cb(conn->ssl,
2940 tls_session_ticket_ext_cb, conn);
2941#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2942#ifdef SSL_OP_NO_TICKET
2943 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2944 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2945#else /* SSL_OP_NO_TICKET */
2946 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2947 conn) != 1)
2948 return -1;
2949#endif /* SSL_OP_NO_TICKET */
2950#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2951 } else {
2952 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2953 return -1;
2954#ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2955 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
2956#else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2957#ifdef SSL_OP_NO_TICKET
2958 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2959 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2960#else /* SSL_OP_NO_TICKET */
2961 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2962 return -1;
2963#endif /* SSL_OP_NO_TICKET */
2964#endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2965 }
2966
2967 return 0;
2968#else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2969 return -1;
2970#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2971}