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