OSDN Git Service

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