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