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