17a63cffad8b5e31d796e8afd1511f967b4f3877
[mech_eap.git] / src / crypto / tls_openssl.c
1 /*
2  * SSL/TLS interface functions for OpenSSL
3  * Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8
9 #include "includes.h"
10
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
13 #ifndef ANDROID
14 #define OPENSSL_NO_ENGINE
15 #endif
16 #endif
17 #endif
18
19 #include <openssl/ssl.h>
20 #include <openssl/err.h>
21 #include <openssl/pkcs12.h>
22 #include <openssl/x509v3.h>
23 #ifndef OPENSSL_NO_ENGINE
24 #include <openssl/engine.h>
25 #endif /* OPENSSL_NO_ENGINE */
26
27 #include "common.h"
28 #include "crypto.h"
29 #include "sha1.h"
30 #include "tls.h"
31
32 #if OPENSSL_VERSION_NUMBER < 0x10000000L
33 /* ERR_remove_thread_state replaces ERR_remove_state and the latter is
34  * deprecated. However, OpenSSL 0.9.8 doesn't include
35  * ERR_remove_thread_state. */
36 #define ERR_remove_thread_state(tid) ERR_remove_state(0)
37 #endif
38
39 #if defined(OPENSSL_IS_BORINGSSL)
40 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
41 typedef size_t stack_index_t;
42 #else
43 typedef int stack_index_t;
44 #endif
45
46 #ifdef SSL_set_tlsext_status_type
47 #ifndef OPENSSL_NO_TLSEXT
48 #define HAVE_OCSP
49 #include <openssl/ocsp.h>
50 #endif /* OPENSSL_NO_TLSEXT */
51 #endif /* SSL_set_tlsext_status_type */
52
53 #ifdef ANDROID
54 #include <openssl/pem.h>
55 #include <keystore/keystore_get.h>
56
57 static BIO * BIO_from_keystore(const char *key)
58 {
59         BIO *bio = NULL;
60         uint8_t *value = NULL;
61         int length = keystore_get(key, strlen(key), &value);
62         if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
63                 BIO_write(bio, value, length);
64         free(value);
65         return bio;
66 }
67 #endif /* ANDROID */
68
69 static int tls_openssl_ref_count = 0;
70
71 struct tls_context {
72         void (*event_cb)(void *ctx, enum tls_event ev,
73                          union tls_event_data *data);
74         void *cb_ctx;
75         int cert_in_cb;
76         char *ocsp_stapling_response;
77 };
78
79 static struct tls_context *tls_global = NULL;
80
81
82 struct tls_connection {
83         struct tls_context *context;
84         SSL_CTX *ssl_ctx;
85         SSL *ssl;
86         BIO *ssl_in, *ssl_out;
87 #ifndef OPENSSL_NO_ENGINE
88         ENGINE *engine;        /* functional reference to the engine */
89         EVP_PKEY *private_key; /* the private key if using engine */
90 #endif /* OPENSSL_NO_ENGINE */
91         char *subject_match, *altsubject_match, *suffix_match, *domain_match;
92         int read_alerts, write_alerts, failed;
93
94         tls_session_ticket_cb session_ticket_cb;
95         void *session_ticket_cb_ctx;
96
97         /* SessionTicket received from OpenSSL hello_extension_cb (server) */
98         u8 *session_ticket;
99         size_t session_ticket_len;
100
101         unsigned int ca_cert_verify:1;
102         unsigned int cert_probe:1;
103         unsigned int server_cert_only:1;
104         unsigned int invalid_hb_used:1;
105
106         u8 srv_cert_hash[32];
107
108         unsigned int flags;
109
110         X509 *peer_cert;
111         X509 *peer_issuer;
112         X509 *peer_issuer_issuer;
113 };
114
115
116 static struct tls_context * tls_context_new(const struct tls_config *conf)
117 {
118         struct tls_context *context = os_zalloc(sizeof(*context));
119         if (context == NULL)
120                 return NULL;
121         if (conf) {
122                 context->event_cb = conf->event_cb;
123                 context->cb_ctx = conf->cb_ctx;
124                 context->cert_in_cb = conf->cert_in_cb;
125         }
126         return context;
127 }
128
129
130 #ifdef CONFIG_NO_STDOUT_DEBUG
131
132 static void _tls_show_errors(void)
133 {
134         unsigned long err;
135
136         while ((err = ERR_get_error())) {
137                 /* Just ignore the errors, since stdout is disabled */
138         }
139 }
140 #define tls_show_errors(l, f, t) _tls_show_errors()
141
142 #else /* CONFIG_NO_STDOUT_DEBUG */
143
144 static void tls_show_errors(int level, const char *func, const char *txt)
145 {
146         unsigned long err;
147
148         wpa_printf(level, "OpenSSL: %s - %s %s",
149                    func, txt, ERR_error_string(ERR_get_error(), NULL));
150
151         while ((err = ERR_get_error())) {
152                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
153                            ERR_error_string(err, NULL));
154         }
155 }
156
157 #endif /* CONFIG_NO_STDOUT_DEBUG */
158
159
160 #ifdef CONFIG_NATIVE_WINDOWS
161
162 /* Windows CryptoAPI and access to certificate stores */
163 #include <wincrypt.h>
164
165 #ifdef __MINGW32_VERSION
166 /*
167  * MinGW does not yet include all the needed definitions for CryptoAPI, so
168  * define here whatever extra is needed.
169  */
170 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
171 #define CERT_STORE_READONLY_FLAG 0x00008000
172 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
173
174 #endif /* __MINGW32_VERSION */
175
176
177 struct cryptoapi_rsa_data {
178         const CERT_CONTEXT *cert;
179         HCRYPTPROV crypt_prov;
180         DWORD key_spec;
181         BOOL free_crypt_prov;
182 };
183
184
185 static void cryptoapi_error(const char *msg)
186 {
187         wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
188                    msg, (unsigned int) GetLastError());
189 }
190
191
192 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
193                                  unsigned char *to, RSA *rsa, int padding)
194 {
195         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
196         return 0;
197 }
198
199
200 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
201                                  unsigned char *to, RSA *rsa, int padding)
202 {
203         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
204         return 0;
205 }
206
207
208 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
209                                   unsigned char *to, RSA *rsa, int padding)
210 {
211         struct cryptoapi_rsa_data *priv =
212                 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
213         HCRYPTHASH hash;
214         DWORD hash_size, len, i;
215         unsigned char *buf = NULL;
216         int ret = 0;
217
218         if (priv == NULL) {
219                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
220                        ERR_R_PASSED_NULL_PARAMETER);
221                 return 0;
222         }
223
224         if (padding != RSA_PKCS1_PADDING) {
225                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
226                        RSA_R_UNKNOWN_PADDING_TYPE);
227                 return 0;
228         }
229
230         if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
231                 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
232                            __func__);
233                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
234                        RSA_R_INVALID_MESSAGE_LENGTH);
235                 return 0;
236         }
237
238         if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
239         {
240                 cryptoapi_error("CryptCreateHash failed");
241                 return 0;
242         }
243
244         len = sizeof(hash_size);
245         if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
246                                0)) {
247                 cryptoapi_error("CryptGetHashParam failed");
248                 goto err;
249         }
250
251         if ((int) hash_size != flen) {
252                 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
253                            (unsigned) hash_size, flen);
254                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
255                        RSA_R_INVALID_MESSAGE_LENGTH);
256                 goto err;
257         }
258         if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
259                 cryptoapi_error("CryptSetHashParam failed");
260                 goto err;
261         }
262
263         len = RSA_size(rsa);
264         buf = os_malloc(len);
265         if (buf == NULL) {
266                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
267                 goto err;
268         }
269
270         if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
271                 cryptoapi_error("CryptSignHash failed");
272                 goto err;
273         }
274
275         for (i = 0; i < len; i++)
276                 to[i] = buf[len - i - 1];
277         ret = len;
278
279 err:
280         os_free(buf);
281         CryptDestroyHash(hash);
282
283         return ret;
284 }
285
286
287 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
288                                   unsigned char *to, RSA *rsa, int padding)
289 {
290         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
291         return 0;
292 }
293
294
295 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
296 {
297         if (priv == NULL)
298                 return;
299         if (priv->crypt_prov && priv->free_crypt_prov)
300                 CryptReleaseContext(priv->crypt_prov, 0);
301         if (priv->cert)
302                 CertFreeCertificateContext(priv->cert);
303         os_free(priv);
304 }
305
306
307 static int cryptoapi_finish(RSA *rsa)
308 {
309         cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
310         os_free((void *) rsa->meth);
311         rsa->meth = NULL;
312         return 1;
313 }
314
315
316 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
317 {
318         HCERTSTORE cs;
319         const CERT_CONTEXT *ret = NULL;
320
321         cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
322                            store | CERT_STORE_OPEN_EXISTING_FLAG |
323                            CERT_STORE_READONLY_FLAG, L"MY");
324         if (cs == NULL) {
325                 cryptoapi_error("Failed to open 'My system store'");
326                 return NULL;
327         }
328
329         if (strncmp(name, "cert://", 7) == 0) {
330                 unsigned short wbuf[255];
331                 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
332                 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
333                                                  PKCS_7_ASN_ENCODING,
334                                                  0, CERT_FIND_SUBJECT_STR,
335                                                  wbuf, NULL);
336         } else if (strncmp(name, "hash://", 7) == 0) {
337                 CRYPT_HASH_BLOB blob;
338                 int len;
339                 const char *hash = name + 7;
340                 unsigned char *buf;
341
342                 len = os_strlen(hash) / 2;
343                 buf = os_malloc(len);
344                 if (buf && hexstr2bin(hash, buf, len) == 0) {
345                         blob.cbData = len;
346                         blob.pbData = buf;
347                         ret = CertFindCertificateInStore(cs,
348                                                          X509_ASN_ENCODING |
349                                                          PKCS_7_ASN_ENCODING,
350                                                          0, CERT_FIND_HASH,
351                                                          &blob, NULL);
352                 }
353                 os_free(buf);
354         }
355
356         CertCloseStore(cs, 0);
357
358         return ret;
359 }
360
361
362 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
363 {
364         X509 *cert = NULL;
365         RSA *rsa = NULL, *pub_rsa;
366         struct cryptoapi_rsa_data *priv;
367         RSA_METHOD *rsa_meth;
368
369         if (name == NULL ||
370             (strncmp(name, "cert://", 7) != 0 &&
371              strncmp(name, "hash://", 7) != 0))
372                 return -1;
373
374         priv = os_zalloc(sizeof(*priv));
375         rsa_meth = os_zalloc(sizeof(*rsa_meth));
376         if (priv == NULL || rsa_meth == NULL) {
377                 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
378                            "for CryptoAPI RSA method");
379                 os_free(priv);
380                 os_free(rsa_meth);
381                 return -1;
382         }
383
384         priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
385         if (priv->cert == NULL) {
386                 priv->cert = cryptoapi_find_cert(
387                         name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
388         }
389         if (priv->cert == NULL) {
390                 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
391                            "'%s'", name);
392                 goto err;
393         }
394
395         cert = d2i_X509(NULL,
396                         (const unsigned char **) &priv->cert->pbCertEncoded,
397                         priv->cert->cbCertEncoded);
398         if (cert == NULL) {
399                 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
400                            "encoding");
401                 goto err;
402         }
403
404         if (!CryptAcquireCertificatePrivateKey(priv->cert,
405                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
406                                                NULL, &priv->crypt_prov,
407                                                &priv->key_spec,
408                                                &priv->free_crypt_prov)) {
409                 cryptoapi_error("Failed to acquire a private key for the "
410                                 "certificate");
411                 goto err;
412         }
413
414         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
415         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
416         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
417         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
418         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
419         rsa_meth->finish = cryptoapi_finish;
420         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
421         rsa_meth->app_data = (char *) priv;
422
423         rsa = RSA_new();
424         if (rsa == NULL) {
425                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
426                        ERR_R_MALLOC_FAILURE);
427                 goto err;
428         }
429
430         if (!SSL_use_certificate(ssl, cert)) {
431                 RSA_free(rsa);
432                 rsa = NULL;
433                 goto err;
434         }
435         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
436         X509_free(cert);
437         cert = NULL;
438
439         rsa->n = BN_dup(pub_rsa->n);
440         rsa->e = BN_dup(pub_rsa->e);
441         if (!RSA_set_method(rsa, rsa_meth))
442                 goto err;
443
444         if (!SSL_use_RSAPrivateKey(ssl, rsa))
445                 goto err;
446         RSA_free(rsa);
447
448         return 0;
449
450 err:
451         if (cert)
452                 X509_free(cert);
453         if (rsa)
454                 RSA_free(rsa);
455         else {
456                 os_free(rsa_meth);
457                 cryptoapi_free_data(priv);
458         }
459         return -1;
460 }
461
462
463 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
464 {
465         HCERTSTORE cs;
466         PCCERT_CONTEXT ctx = NULL;
467         X509 *cert;
468         char buf[128];
469         const char *store;
470 #ifdef UNICODE
471         WCHAR *wstore;
472 #endif /* UNICODE */
473
474         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
475                 return -1;
476
477         store = name + 13;
478 #ifdef UNICODE
479         wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
480         if (wstore == NULL)
481                 return -1;
482         wsprintf(wstore, L"%S", store);
483         cs = CertOpenSystemStore(0, wstore);
484         os_free(wstore);
485 #else /* UNICODE */
486         cs = CertOpenSystemStore(0, store);
487 #endif /* UNICODE */
488         if (cs == NULL) {
489                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
490                            "'%s': error=%d", __func__, store,
491                            (int) GetLastError());
492                 return -1;
493         }
494
495         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
496                 cert = d2i_X509(NULL,
497                                 (const unsigned char **) &ctx->pbCertEncoded,
498                                 ctx->cbCertEncoded);
499                 if (cert == NULL) {
500                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
501                                    "X509 DER encoding for CA cert");
502                         continue;
503                 }
504
505                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
506                                   sizeof(buf));
507                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
508                            "system certificate store: subject='%s'", buf);
509
510                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
511                         tls_show_errors(MSG_WARNING, __func__,
512                                         "Failed to add ca_cert to OpenSSL "
513                                         "certificate store");
514                 }
515
516                 X509_free(cert);
517         }
518
519         if (!CertCloseStore(cs, 0)) {
520                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
521                            "'%s': error=%d", __func__, name + 13,
522                            (int) GetLastError());
523         }
524
525         return 0;
526 }
527
528
529 #else /* CONFIG_NATIVE_WINDOWS */
530
531 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
532 {
533         return -1;
534 }
535
536 #endif /* CONFIG_NATIVE_WINDOWS */
537
538
539 static void ssl_info_cb(const SSL *ssl, int where, int ret)
540 {
541         const char *str;
542         int w;
543
544         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
545         w = where & ~SSL_ST_MASK;
546         if (w & SSL_ST_CONNECT)
547                 str = "SSL_connect";
548         else if (w & SSL_ST_ACCEPT)
549                 str = "SSL_accept";
550         else
551                 str = "undefined";
552
553         if (where & SSL_CB_LOOP) {
554                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
555                            str, SSL_state_string_long(ssl));
556         } else if (where & SSL_CB_ALERT) {
557                 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
558                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
559                            where & SSL_CB_READ ?
560                            "read (remote end reported an error)" :
561                            "write (local SSL3 detected an error)",
562                            SSL_alert_type_string_long(ret),
563                            SSL_alert_desc_string_long(ret));
564                 if ((ret >> 8) == SSL3_AL_FATAL) {
565                         if (where & SSL_CB_READ)
566                                 conn->read_alerts++;
567                         else
568                                 conn->write_alerts++;
569                 }
570                 if (conn->context->event_cb != NULL) {
571                         union tls_event_data ev;
572                         struct tls_context *context = conn->context;
573                         os_memset(&ev, 0, sizeof(ev));
574                         ev.alert.is_local = !(where & SSL_CB_READ);
575                         ev.alert.type = SSL_alert_type_string_long(ret);
576                         ev.alert.description = SSL_alert_desc_string_long(ret);
577                         context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
578                 }
579         } else if (where & SSL_CB_EXIT && ret <= 0) {
580                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
581                            str, ret == 0 ? "failed" : "error",
582                            SSL_state_string_long(ssl));
583         }
584 }
585
586
587 #ifndef OPENSSL_NO_ENGINE
588 /**
589  * tls_engine_load_dynamic_generic - load any openssl engine
590  * @pre: an array of commands and values that load an engine initialized
591  *       in the engine specific function
592  * @post: an array of commands and values that initialize an already loaded
593  *        engine (or %NULL if not required)
594  * @id: the engine id of the engine to load (only required if post is not %NULL
595  *
596  * This function is a generic function that loads any openssl engine.
597  *
598  * Returns: 0 on success, -1 on failure
599  */
600 static int tls_engine_load_dynamic_generic(const char *pre[],
601                                            const char *post[], const char *id)
602 {
603         ENGINE *engine;
604         const char *dynamic_id = "dynamic";
605
606         engine = ENGINE_by_id(id);
607         if (engine) {
608                 ENGINE_free(engine);
609                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
610                            "available", id);
611                 return 0;
612         }
613         ERR_clear_error();
614
615         engine = ENGINE_by_id(dynamic_id);
616         if (engine == NULL) {
617                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
618                            dynamic_id,
619                            ERR_error_string(ERR_get_error(), NULL));
620                 return -1;
621         }
622
623         /* Perform the pre commands. This will load the engine. */
624         while (pre && pre[0]) {
625                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
626                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
627                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
628                                    "%s %s [%s]", pre[0], pre[1],
629                                    ERR_error_string(ERR_get_error(), NULL));
630                         ENGINE_free(engine);
631                         return -1;
632                 }
633                 pre += 2;
634         }
635
636         /*
637          * Free the reference to the "dynamic" engine. The loaded engine can
638          * now be looked up using ENGINE_by_id().
639          */
640         ENGINE_free(engine);
641
642         engine = ENGINE_by_id(id);
643         if (engine == NULL) {
644                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
645                            id, ERR_error_string(ERR_get_error(), NULL));
646                 return -1;
647         }
648
649         while (post && post[0]) {
650                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
651                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
652                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
653                                 " %s %s [%s]", post[0], post[1],
654                                    ERR_error_string(ERR_get_error(), NULL));
655                         ENGINE_remove(engine);
656                         ENGINE_free(engine);
657                         return -1;
658                 }
659                 post += 2;
660         }
661         ENGINE_free(engine);
662
663         return 0;
664 }
665
666
667 /**
668  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
669  * @pkcs11_so_path: pksc11_so_path from the configuration
670  * @pcks11_module_path: pkcs11_module_path from the configuration
671  */
672 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
673                                           const char *pkcs11_module_path)
674 {
675         char *engine_id = "pkcs11";
676         const char *pre_cmd[] = {
677                 "SO_PATH", NULL /* pkcs11_so_path */,
678                 "ID", NULL /* engine_id */,
679                 "LIST_ADD", "1",
680                 /* "NO_VCHECK", "1", */
681                 "LOAD", NULL,
682                 NULL, NULL
683         };
684         const char *post_cmd[] = {
685                 "MODULE_PATH", NULL /* pkcs11_module_path */,
686                 NULL, NULL
687         };
688
689         if (!pkcs11_so_path)
690                 return 0;
691
692         pre_cmd[1] = pkcs11_so_path;
693         pre_cmd[3] = engine_id;
694         if (pkcs11_module_path)
695                 post_cmd[1] = pkcs11_module_path;
696         else
697                 post_cmd[0] = NULL;
698
699         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
700                    pkcs11_so_path);
701
702         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
703 }
704
705
706 /**
707  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
708  * @opensc_so_path: opensc_so_path from the configuration
709  */
710 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
711 {
712         char *engine_id = "opensc";
713         const char *pre_cmd[] = {
714                 "SO_PATH", NULL /* opensc_so_path */,
715                 "ID", NULL /* engine_id */,
716                 "LIST_ADD", "1",
717                 "LOAD", NULL,
718                 NULL, NULL
719         };
720
721         if (!opensc_so_path)
722                 return 0;
723
724         pre_cmd[1] = opensc_so_path;
725         pre_cmd[3] = engine_id;
726
727         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
728                    opensc_so_path);
729
730         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
731 }
732 #endif /* OPENSSL_NO_ENGINE */
733
734
735 void * tls_init(const struct tls_config *conf)
736 {
737         SSL_CTX *ssl;
738         struct tls_context *context;
739         const char *ciphers;
740
741         if (tls_openssl_ref_count == 0) {
742                 tls_global = context = tls_context_new(conf);
743                 if (context == NULL)
744                         return NULL;
745 #ifdef CONFIG_FIPS
746 #ifdef OPENSSL_FIPS
747                 if (conf && conf->fips_mode) {
748                         if (!FIPS_mode_set(1)) {
749                                 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
750                                            "mode");
751                                 ERR_load_crypto_strings();
752                                 ERR_print_errors_fp(stderr);
753                                 os_free(tls_global);
754                                 tls_global = NULL;
755                                 return NULL;
756                         } else
757                                 wpa_printf(MSG_INFO, "Running in FIPS mode");
758                 }
759 #else /* OPENSSL_FIPS */
760                 if (conf && conf->fips_mode) {
761                         wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
762                                    "supported");
763                         os_free(tls_global);
764                         tls_global = NULL;
765                         return NULL;
766                 }
767 #endif /* OPENSSL_FIPS */
768 #endif /* CONFIG_FIPS */
769                 SSL_load_error_strings();
770                 SSL_library_init();
771 #ifndef OPENSSL_NO_SHA256
772                 EVP_add_digest(EVP_sha256());
773 #endif /* OPENSSL_NO_SHA256 */
774                 /* TODO: if /dev/urandom is available, PRNG is seeded
775                  * automatically. If this is not the case, random data should
776                  * be added here. */
777
778 #ifdef PKCS12_FUNCS
779 #ifndef OPENSSL_NO_RC2
780                 /*
781                  * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
782                  * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
783                  * versions, but it looks like OpenSSL 1.0.0 does not do that
784                  * anymore.
785                  */
786                 EVP_add_cipher(EVP_rc2_40_cbc());
787 #endif /* OPENSSL_NO_RC2 */
788                 PKCS12_PBE_add();
789 #endif  /* PKCS12_FUNCS */
790         } else {
791                 context = tls_context_new(conf);
792                 if (context == NULL)
793                         return NULL;
794         }
795         tls_openssl_ref_count++;
796
797         ssl = SSL_CTX_new(SSLv23_method());
798         if (ssl == NULL) {
799                 tls_openssl_ref_count--;
800                 if (context != tls_global)
801                         os_free(context);
802                 if (tls_openssl_ref_count == 0) {
803                         os_free(tls_global);
804                         tls_global = NULL;
805                 }
806                 return NULL;
807         }
808
809         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
810         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
811
812         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
813         SSL_CTX_set_app_data(ssl, context);
814
815 #ifndef OPENSSL_NO_ENGINE
816         wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
817         ERR_load_ENGINE_strings();
818         ENGINE_load_dynamic();
819
820         if (conf &&
821             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
822              conf->pkcs11_module_path)) {
823                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
824                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
825                                                    conf->pkcs11_module_path)) {
826                         tls_deinit(ssl);
827                         return NULL;
828                 }
829         }
830 #endif /* OPENSSL_NO_ENGINE */
831
832         if (conf && conf->openssl_ciphers)
833                 ciphers = conf->openssl_ciphers;
834         else
835                 ciphers = "DEFAULT:!EXP:!LOW";
836         if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
837                 wpa_printf(MSG_ERROR,
838                            "OpenSSL: Failed to set cipher string '%s'",
839                            ciphers);
840                 tls_deinit(ssl);
841                 return NULL;
842         }
843
844         return ssl;
845 }
846
847
848 void tls_deinit(void *ssl_ctx)
849 {
850         SSL_CTX *ssl = ssl_ctx;
851         struct tls_context *context = SSL_CTX_get_app_data(ssl);
852         if (context != tls_global)
853                 os_free(context);
854         SSL_CTX_free(ssl);
855
856         tls_openssl_ref_count--;
857         if (tls_openssl_ref_count == 0) {
858 #ifndef OPENSSL_NO_ENGINE
859                 ENGINE_cleanup();
860 #endif /* OPENSSL_NO_ENGINE */
861                 CRYPTO_cleanup_all_ex_data();
862                 ERR_remove_thread_state(NULL);
863                 ERR_free_strings();
864                 EVP_cleanup();
865                 os_free(tls_global->ocsp_stapling_response);
866                 tls_global->ocsp_stapling_response = NULL;
867                 os_free(tls_global);
868                 tls_global = NULL;
869         }
870 }
871
872
873 #ifndef OPENSSL_NO_ENGINE
874
875 /* Cryptoki return values */
876 #define CKR_PIN_INCORRECT 0x000000a0
877 #define CKR_PIN_INVALID 0x000000a1
878 #define CKR_PIN_LEN_RANGE 0x000000a2
879
880 /* libp11 */
881 #define ERR_LIB_PKCS11  ERR_LIB_USER
882
883 static int tls_is_pin_error(unsigned int err)
884 {
885         return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
886                 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
887                  ERR_GET_REASON(err) == CKR_PIN_INVALID ||
888                  ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
889 }
890
891 #endif /* OPENSSL_NO_ENGINE */
892
893
894 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
895                            const char *pin, const char *key_id,
896                            const char *cert_id, const char *ca_cert_id)
897 {
898 #ifndef OPENSSL_NO_ENGINE
899         int ret = -1;
900         if (engine_id == NULL) {
901                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
902                 return -1;
903         }
904
905         ERR_clear_error();
906 #ifdef ANDROID
907         ENGINE_load_dynamic();
908 #endif
909         conn->engine = ENGINE_by_id(engine_id);
910         if (!conn->engine) {
911                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
912                            engine_id, ERR_error_string(ERR_get_error(), NULL));
913                 goto err;
914         }
915         if (ENGINE_init(conn->engine) != 1) {
916                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
917                            "(engine: %s) [%s]", engine_id,
918                            ERR_error_string(ERR_get_error(), NULL));
919                 goto err;
920         }
921         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
922
923 #ifndef ANDROID
924         if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
925                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
926                            ERR_error_string(ERR_get_error(), NULL));
927                 goto err;
928         }
929 #endif
930         if (key_id) {
931                 /*
932                  * Ensure that the ENGINE does not attempt to use the OpenSSL
933                  * UI system to obtain a PIN, if we didn't provide one.
934                  */
935                 struct {
936                         const void *password;
937                         const char *prompt_info;
938                 } key_cb = { "", NULL };
939
940                 /* load private key first in-case PIN is required for cert */
941                 conn->private_key = ENGINE_load_private_key(conn->engine,
942                                                             key_id, NULL,
943                                                             &key_cb);
944                 if (!conn->private_key) {
945                         unsigned long err = ERR_get_error();
946
947                         wpa_printf(MSG_ERROR,
948                                    "ENGINE: cannot load private key with id '%s' [%s]",
949                                    key_id,
950                                    ERR_error_string(err, NULL));
951                         if (tls_is_pin_error(err))
952                                 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
953                         else
954                                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
955                         goto err;
956                 }
957         }
958
959         /* handle a certificate and/or CA certificate */
960         if (cert_id || ca_cert_id) {
961                 const char *cmd_name = "LOAD_CERT_CTRL";
962
963                 /* test if the engine supports a LOAD_CERT_CTRL */
964                 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
965                                  0, (void *)cmd_name, NULL)) {
966                         wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
967                                    " loading certificates");
968                         ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
969                         goto err;
970                 }
971         }
972
973         return 0;
974
975 err:
976         if (conn->engine) {
977                 ENGINE_free(conn->engine);
978                 conn->engine = NULL;
979         }
980
981         if (conn->private_key) {
982                 EVP_PKEY_free(conn->private_key);
983                 conn->private_key = NULL;
984         }
985
986         return ret;
987 #else /* OPENSSL_NO_ENGINE */
988         return 0;
989 #endif /* OPENSSL_NO_ENGINE */
990 }
991
992
993 static void tls_engine_deinit(struct tls_connection *conn)
994 {
995 #ifndef OPENSSL_NO_ENGINE
996         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
997         if (conn->private_key) {
998                 EVP_PKEY_free(conn->private_key);
999                 conn->private_key = NULL;
1000         }
1001         if (conn->engine) {
1002                 ENGINE_finish(conn->engine);
1003                 conn->engine = NULL;
1004         }
1005 #endif /* OPENSSL_NO_ENGINE */
1006 }
1007
1008
1009 int tls_get_errors(void *ssl_ctx)
1010 {
1011         int count = 0;
1012         unsigned long err;
1013
1014         while ((err = ERR_get_error())) {
1015                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1016                            ERR_error_string(err, NULL));
1017                 count++;
1018         }
1019
1020         return count;
1021 }
1022
1023
1024 static void tls_msg_cb(int write_p, int version, int content_type,
1025                        const void *buf, size_t len, SSL *ssl, void *arg)
1026 {
1027         struct tls_connection *conn = arg;
1028         const u8 *pos = buf;
1029
1030         wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1031                    write_p ? "TX" : "RX", version, content_type);
1032         wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1033         if (content_type == 24 && len >= 3 && pos[0] == 1) {
1034                 size_t payload_len = WPA_GET_BE16(pos + 1);
1035                 if (payload_len + 3 > len) {
1036                         wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1037                         conn->invalid_hb_used = 1;
1038                 }
1039         }
1040 }
1041
1042
1043 struct tls_connection * tls_connection_init(void *ssl_ctx)
1044 {
1045         SSL_CTX *ssl = ssl_ctx;
1046         struct tls_connection *conn;
1047         long options;
1048         struct tls_context *context = SSL_CTX_get_app_data(ssl);
1049
1050         conn = os_zalloc(sizeof(*conn));
1051         if (conn == NULL)
1052                 return NULL;
1053         conn->ssl_ctx = ssl_ctx;
1054         conn->ssl = SSL_new(ssl);
1055         if (conn->ssl == NULL) {
1056                 tls_show_errors(MSG_INFO, __func__,
1057                                 "Failed to initialize new SSL connection");
1058                 os_free(conn);
1059                 return NULL;
1060         }
1061
1062         conn->context = context;
1063         SSL_set_app_data(conn->ssl, conn);
1064         SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1065         SSL_set_msg_callback_arg(conn->ssl, conn);
1066         options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1067                 SSL_OP_SINGLE_DH_USE;
1068 #ifdef SSL_OP_NO_COMPRESSION
1069         options |= SSL_OP_NO_COMPRESSION;
1070 #endif /* SSL_OP_NO_COMPRESSION */
1071         SSL_set_options(conn->ssl, options);
1072
1073         conn->ssl_in = BIO_new(BIO_s_mem());
1074         if (!conn->ssl_in) {
1075                 tls_show_errors(MSG_INFO, __func__,
1076                                 "Failed to create a new BIO for ssl_in");
1077                 SSL_free(conn->ssl);
1078                 os_free(conn);
1079                 return NULL;
1080         }
1081
1082         conn->ssl_out = BIO_new(BIO_s_mem());
1083         if (!conn->ssl_out) {
1084                 tls_show_errors(MSG_INFO, __func__,
1085                                 "Failed to create a new BIO for ssl_out");
1086                 SSL_free(conn->ssl);
1087                 BIO_free(conn->ssl_in);
1088                 os_free(conn);
1089                 return NULL;
1090         }
1091
1092         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1093
1094         return conn;
1095 }
1096
1097
1098 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1099 {
1100         if (conn == NULL)
1101                 return;
1102         SSL_free(conn->ssl);
1103         tls_engine_deinit(conn);
1104         os_free(conn->subject_match);
1105         os_free(conn->altsubject_match);
1106         os_free(conn->suffix_match);
1107         os_free(conn->domain_match);
1108         os_free(conn->session_ticket);
1109         os_free(conn);
1110 }
1111
1112
1113 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1114 {
1115         return conn ? SSL_is_init_finished(conn->ssl) : 0;
1116 }
1117
1118
1119 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1120 {
1121         if (conn == NULL)
1122                 return -1;
1123
1124         /* Shutdown previous TLS connection without notifying the peer
1125          * because the connection was already terminated in practice
1126          * and "close notify" shutdown alert would confuse AS. */
1127         SSL_set_quiet_shutdown(conn->ssl, 1);
1128         SSL_shutdown(conn->ssl);
1129         return 0;
1130 }
1131
1132
1133 static int tls_match_altsubject_component(X509 *cert, int type,
1134                                           const char *value, size_t len)
1135 {
1136         GENERAL_NAME *gen;
1137         void *ext;
1138         int found = 0;
1139         stack_index_t i;
1140
1141         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1142
1143         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1144                 gen = sk_GENERAL_NAME_value(ext, i);
1145                 if (gen->type != type)
1146                         continue;
1147                 if (os_strlen((char *) gen->d.ia5->data) == len &&
1148                     os_memcmp(value, gen->d.ia5->data, len) == 0)
1149                         found++;
1150         }
1151
1152         return found;
1153 }
1154
1155
1156 static int tls_match_altsubject(X509 *cert, const char *match)
1157 {
1158         int type;
1159         const char *pos, *end;
1160         size_t len;
1161
1162         pos = match;
1163         do {
1164                 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1165                         type = GEN_EMAIL;
1166                         pos += 6;
1167                 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1168                         type = GEN_DNS;
1169                         pos += 4;
1170                 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1171                         type = GEN_URI;
1172                         pos += 4;
1173                 } else {
1174                         wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1175                                    "match '%s'", pos);
1176                         return 0;
1177                 }
1178                 end = os_strchr(pos, ';');
1179                 while (end) {
1180                         if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1181                             os_strncmp(end + 1, "DNS:", 4) == 0 ||
1182                             os_strncmp(end + 1, "URI:", 4) == 0)
1183                                 break;
1184                         end = os_strchr(end + 1, ';');
1185                 }
1186                 if (end)
1187                         len = end - pos;
1188                 else
1189                         len = os_strlen(pos);
1190                 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1191                         return 1;
1192                 pos = end + 1;
1193         } while (end);
1194
1195         return 0;
1196 }
1197
1198
1199 #ifndef CONFIG_NATIVE_WINDOWS
1200 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1201                                int full)
1202 {
1203         size_t i, match_len;
1204
1205         /* Check for embedded nuls that could mess up suffix matching */
1206         for (i = 0; i < len; i++) {
1207                 if (val[i] == '\0') {
1208                         wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1209                         return 0;
1210                 }
1211         }
1212
1213         match_len = os_strlen(match);
1214         if (match_len > len || (full && match_len != len))
1215                 return 0;
1216
1217         if (os_strncasecmp((const char *) val + len - match_len, match,
1218                            match_len) != 0)
1219                 return 0; /* no match */
1220
1221         if (match_len == len)
1222                 return 1; /* exact match */
1223
1224         if (val[len - match_len - 1] == '.')
1225                 return 1; /* full label match completes suffix match */
1226
1227         wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1228         return 0;
1229 }
1230 #endif /* CONFIG_NATIVE_WINDOWS */
1231
1232
1233 static int tls_match_suffix(X509 *cert, const char *match, int full)
1234 {
1235 #ifdef CONFIG_NATIVE_WINDOWS
1236         /* wincrypt.h has conflicting X509_NAME definition */
1237         return -1;
1238 #else /* CONFIG_NATIVE_WINDOWS */
1239         GENERAL_NAME *gen;
1240         void *ext;
1241         int i;
1242         stack_index_t j;
1243         int dns_name = 0;
1244         X509_NAME *name;
1245
1246         wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1247                    full ? "": "suffix ", match);
1248
1249         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1250
1251         for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1252                 gen = sk_GENERAL_NAME_value(ext, j);
1253                 if (gen->type != GEN_DNS)
1254                         continue;
1255                 dns_name++;
1256                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1257                                   gen->d.dNSName->data,
1258                                   gen->d.dNSName->length);
1259                 if (domain_suffix_match(gen->d.dNSName->data,
1260                                         gen->d.dNSName->length, match, full) ==
1261                     1) {
1262                         wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1263                                    full ? "Match" : "Suffix match");
1264                         return 1;
1265                 }
1266         }
1267
1268         if (dns_name) {
1269                 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1270                 return 0;
1271         }
1272
1273         name = X509_get_subject_name(cert);
1274         i = -1;
1275         for (;;) {
1276                 X509_NAME_ENTRY *e;
1277                 ASN1_STRING *cn;
1278
1279                 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1280                 if (i == -1)
1281                         break;
1282                 e = X509_NAME_get_entry(name, i);
1283                 if (e == NULL)
1284                         continue;
1285                 cn = X509_NAME_ENTRY_get_data(e);
1286                 if (cn == NULL)
1287                         continue;
1288                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1289                                   cn->data, cn->length);
1290                 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1291                 {
1292                         wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1293                                    full ? "Match" : "Suffix match");
1294                         return 1;
1295                 }
1296         }
1297
1298         wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1299                    full ? "": "suffix ");
1300         return 0;
1301 #endif /* CONFIG_NATIVE_WINDOWS */
1302 }
1303
1304
1305 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1306 {
1307         switch (err) {
1308         case X509_V_ERR_CERT_REVOKED:
1309                 return TLS_FAIL_REVOKED;
1310         case X509_V_ERR_CERT_NOT_YET_VALID:
1311         case X509_V_ERR_CRL_NOT_YET_VALID:
1312                 return TLS_FAIL_NOT_YET_VALID;
1313         case X509_V_ERR_CERT_HAS_EXPIRED:
1314         case X509_V_ERR_CRL_HAS_EXPIRED:
1315                 return TLS_FAIL_EXPIRED;
1316         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1317         case X509_V_ERR_UNABLE_TO_GET_CRL:
1318         case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1319         case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1320         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1321         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1322         case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1323         case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1324         case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1325         case X509_V_ERR_INVALID_CA:
1326                 return TLS_FAIL_UNTRUSTED;
1327         case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1328         case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1329         case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1330         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1331         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1332         case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1333         case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1334         case X509_V_ERR_CERT_UNTRUSTED:
1335         case X509_V_ERR_CERT_REJECTED:
1336                 return TLS_FAIL_BAD_CERTIFICATE;
1337         default:
1338                 return TLS_FAIL_UNSPECIFIED;
1339         }
1340 }
1341
1342
1343 static struct wpabuf * get_x509_cert(X509 *cert)
1344 {
1345         struct wpabuf *buf;
1346         u8 *tmp;
1347
1348         int cert_len = i2d_X509(cert, NULL);
1349         if (cert_len <= 0)
1350                 return NULL;
1351
1352         buf = wpabuf_alloc(cert_len);
1353         if (buf == NULL)
1354                 return NULL;
1355
1356         tmp = wpabuf_put(buf, cert_len);
1357         i2d_X509(cert, &tmp);
1358         return buf;
1359 }
1360
1361
1362 static void openssl_tls_fail_event(struct tls_connection *conn,
1363                                    X509 *err_cert, int err, int depth,
1364                                    const char *subject, const char *err_str,
1365                                    enum tls_fail_reason reason)
1366 {
1367         union tls_event_data ev;
1368         struct wpabuf *cert = NULL;
1369         struct tls_context *context = conn->context;
1370
1371         if (context->event_cb == NULL)
1372                 return;
1373
1374         cert = get_x509_cert(err_cert);
1375         os_memset(&ev, 0, sizeof(ev));
1376         ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1377                 reason : openssl_tls_fail_reason(err);
1378         ev.cert_fail.depth = depth;
1379         ev.cert_fail.subject = subject;
1380         ev.cert_fail.reason_txt = err_str;
1381         ev.cert_fail.cert = cert;
1382         context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1383         wpabuf_free(cert);
1384 }
1385
1386
1387 static void openssl_tls_cert_event(struct tls_connection *conn,
1388                                    X509 *err_cert, int depth,
1389                                    const char *subject)
1390 {
1391         struct wpabuf *cert = NULL;
1392         union tls_event_data ev;
1393         struct tls_context *context = conn->context;
1394         char *altsubject[TLS_MAX_ALT_SUBJECT];
1395         int alt, num_altsubject = 0;
1396         GENERAL_NAME *gen;
1397         void *ext;
1398         stack_index_t i;
1399 #ifdef CONFIG_SHA256
1400         u8 hash[32];
1401 #endif /* CONFIG_SHA256 */
1402
1403         if (context->event_cb == NULL)
1404                 return;
1405
1406         os_memset(&ev, 0, sizeof(ev));
1407         if (conn->cert_probe || context->cert_in_cb) {
1408                 cert = get_x509_cert(err_cert);
1409                 ev.peer_cert.cert = cert;
1410         }
1411 #ifdef CONFIG_SHA256
1412         if (cert) {
1413                 const u8 *addr[1];
1414                 size_t len[1];
1415                 addr[0] = wpabuf_head(cert);
1416                 len[0] = wpabuf_len(cert);
1417                 if (sha256_vector(1, addr, len, hash) == 0) {
1418                         ev.peer_cert.hash = hash;
1419                         ev.peer_cert.hash_len = sizeof(hash);
1420                 }
1421         }
1422 #endif /* CONFIG_SHA256 */
1423         ev.peer_cert.depth = depth;
1424         ev.peer_cert.subject = subject;
1425
1426         ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1427         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1428                 char *pos;
1429
1430                 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1431                         break;
1432                 gen = sk_GENERAL_NAME_value(ext, i);
1433                 if (gen->type != GEN_EMAIL &&
1434                     gen->type != GEN_DNS &&
1435                     gen->type != GEN_URI)
1436                         continue;
1437
1438                 pos = os_malloc(10 + gen->d.ia5->length + 1);
1439                 if (pos == NULL)
1440                         break;
1441                 altsubject[num_altsubject++] = pos;
1442
1443                 switch (gen->type) {
1444                 case GEN_EMAIL:
1445                         os_memcpy(pos, "EMAIL:", 6);
1446                         pos += 6;
1447                         break;
1448                 case GEN_DNS:
1449                         os_memcpy(pos, "DNS:", 4);
1450                         pos += 4;
1451                         break;
1452                 case GEN_URI:
1453                         os_memcpy(pos, "URI:", 4);
1454                         pos += 4;
1455                         break;
1456                 }
1457
1458                 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1459                 pos += gen->d.ia5->length;
1460                 *pos = '\0';
1461         }
1462
1463         for (alt = 0; alt < num_altsubject; alt++)
1464                 ev.peer_cert.altsubject[alt] = altsubject[alt];
1465         ev.peer_cert.num_altsubject = num_altsubject;
1466
1467         context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1468         wpabuf_free(cert);
1469         for (alt = 0; alt < num_altsubject; alt++)
1470                 os_free(altsubject[alt]);
1471 }
1472
1473
1474 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1475 {
1476         char buf[256];
1477         X509 *err_cert;
1478         int err, depth;
1479         SSL *ssl;
1480         struct tls_connection *conn;
1481         struct tls_context *context;
1482         char *match, *altmatch, *suffix_match, *domain_match;
1483         const char *err_str;
1484
1485         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1486         if (!err_cert)
1487                 return 0;
1488
1489         err = X509_STORE_CTX_get_error(x509_ctx);
1490         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1491         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1492                                          SSL_get_ex_data_X509_STORE_CTX_idx());
1493         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1494
1495         conn = SSL_get_app_data(ssl);
1496         if (conn == NULL)
1497                 return 0;
1498
1499         if (depth == 0)
1500                 conn->peer_cert = err_cert;
1501         else if (depth == 1)
1502                 conn->peer_issuer = err_cert;
1503         else if (depth == 2)
1504                 conn->peer_issuer_issuer = err_cert;
1505
1506         context = conn->context;
1507         match = conn->subject_match;
1508         altmatch = conn->altsubject_match;
1509         suffix_match = conn->suffix_match;
1510         domain_match = conn->domain_match;
1511
1512         if (!preverify_ok && !conn->ca_cert_verify)
1513                 preverify_ok = 1;
1514         if (!preverify_ok && depth > 0 && conn->server_cert_only)
1515                 preverify_ok = 1;
1516         if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1517             (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1518              err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1519                 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1520                            "time mismatch");
1521                 preverify_ok = 1;
1522         }
1523
1524         err_str = X509_verify_cert_error_string(err);
1525
1526 #ifdef CONFIG_SHA256
1527         /*
1528          * Do not require preverify_ok so we can explicity allow otherwise
1529          * invalid pinned server certificates.
1530          */
1531         if (depth == 0 && conn->server_cert_only) {
1532                 struct wpabuf *cert;
1533                 cert = get_x509_cert(err_cert);
1534                 if (!cert) {
1535                         wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1536                                    "server certificate data");
1537                         preverify_ok = 0;
1538                 } else {
1539                         u8 hash[32];
1540                         const u8 *addr[1];
1541                         size_t len[1];
1542                         addr[0] = wpabuf_head(cert);
1543                         len[0] = wpabuf_len(cert);
1544                         if (sha256_vector(1, addr, len, hash) < 0 ||
1545                             os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1546                                 err_str = "Server certificate mismatch";
1547                                 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1548                                 preverify_ok = 0;
1549                         } else if (!preverify_ok) {
1550                                 /*
1551                                  * Certificate matches pinned certificate, allow
1552                                  * regardless of other problems.
1553                                  */
1554                                 wpa_printf(MSG_DEBUG,
1555                                            "OpenSSL: Ignore validation issues for a pinned server certificate");
1556                                 preverify_ok = 1;
1557                         }
1558                         wpabuf_free(cert);
1559                 }
1560         }
1561 #endif /* CONFIG_SHA256 */
1562
1563         if (!preverify_ok) {
1564                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1565                            " error %d (%s) depth %d for '%s'", err, err_str,
1566                            depth, buf);
1567                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1568                                        err_str, TLS_FAIL_UNSPECIFIED);
1569                 return preverify_ok;
1570         }
1571
1572         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1573                    "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1574                    preverify_ok, err, err_str,
1575                    conn->ca_cert_verify, depth, buf);
1576         if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1577                 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1578                            "match with '%s'", buf, match);
1579                 preverify_ok = 0;
1580                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1581                                        "Subject mismatch",
1582                                        TLS_FAIL_SUBJECT_MISMATCH);
1583         } else if (depth == 0 && altmatch &&
1584                    !tls_match_altsubject(err_cert, altmatch)) {
1585                 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1586                            "'%s' not found", altmatch);
1587                 preverify_ok = 0;
1588                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1589                                        "AltSubject mismatch",
1590                                        TLS_FAIL_ALTSUBJECT_MISMATCH);
1591         } else if (depth == 0 && suffix_match &&
1592                    !tls_match_suffix(err_cert, suffix_match, 0)) {
1593                 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1594                            suffix_match);
1595                 preverify_ok = 0;
1596                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1597                                        "Domain suffix mismatch",
1598                                        TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1599         } else if (depth == 0 && domain_match &&
1600                    !tls_match_suffix(err_cert, domain_match, 1)) {
1601                 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1602                            domain_match);
1603                 preverify_ok = 0;
1604                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1605                                        "Domain mismatch",
1606                                        TLS_FAIL_DOMAIN_MISMATCH);
1607         } else
1608                 openssl_tls_cert_event(conn, err_cert, depth, buf);
1609
1610         if (conn->cert_probe && preverify_ok && depth == 0) {
1611                 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1612                            "on probe-only run");
1613                 preverify_ok = 0;
1614                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1615                                        "Server certificate chain probe",
1616                                        TLS_FAIL_SERVER_CHAIN_PROBE);
1617         }
1618
1619         if (preverify_ok && context->event_cb != NULL)
1620                 context->event_cb(context->cb_ctx,
1621                                   TLS_CERT_CHAIN_SUCCESS, NULL);
1622
1623         return preverify_ok;
1624 }
1625
1626
1627 #ifndef OPENSSL_NO_STDIO
1628 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1629 {
1630         SSL_CTX *ssl_ctx = _ssl_ctx;
1631         X509_LOOKUP *lookup;
1632         int ret = 0;
1633
1634         lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
1635                                        X509_LOOKUP_file());
1636         if (lookup == NULL) {
1637                 tls_show_errors(MSG_WARNING, __func__,
1638                                 "Failed add lookup for X509 store");
1639                 return -1;
1640         }
1641
1642         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1643                 unsigned long err = ERR_peek_error();
1644                 tls_show_errors(MSG_WARNING, __func__,
1645                                 "Failed load CA in DER format");
1646                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1647                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1648                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1649                                    "cert already in hash table error",
1650                                    __func__);
1651                 } else
1652                         ret = -1;
1653         }
1654
1655         return ret;
1656 }
1657 #endif /* OPENSSL_NO_STDIO */
1658
1659
1660 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1661                                   const char *ca_cert, const u8 *ca_cert_blob,
1662                                   size_t ca_cert_blob_len, const char *ca_path)
1663 {
1664         SSL_CTX *ssl_ctx = _ssl_ctx;
1665         X509_STORE *store;
1666
1667         /*
1668          * Remove previously configured trusted CA certificates before adding
1669          * new ones.
1670          */
1671         store = X509_STORE_new();
1672         if (store == NULL) {
1673                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1674                            "certificate store", __func__);
1675                 return -1;
1676         }
1677         SSL_CTX_set_cert_store(ssl_ctx, store);
1678
1679         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1680         conn->ca_cert_verify = 1;
1681
1682         if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1683                 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1684                            "chain");
1685                 conn->cert_probe = 1;
1686                 conn->ca_cert_verify = 0;
1687                 return 0;
1688         }
1689
1690         if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1691 #ifdef CONFIG_SHA256
1692                 const char *pos = ca_cert + 7;
1693                 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1694                         wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1695                                    "hash value '%s'", ca_cert);
1696                         return -1;
1697                 }
1698                 pos += 14;
1699                 if (os_strlen(pos) != 32 * 2) {
1700                         wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1701                                    "hash length in ca_cert '%s'", ca_cert);
1702                         return -1;
1703                 }
1704                 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1705                         wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1706                                    "value in ca_cert '%s'", ca_cert);
1707                         return -1;
1708                 }
1709                 conn->server_cert_only = 1;
1710                 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1711                            "certificate match");
1712                 return 0;
1713 #else /* CONFIG_SHA256 */
1714                 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1715                            "cannot validate server certificate hash");
1716                 return -1;
1717 #endif /* CONFIG_SHA256 */
1718         }
1719
1720         if (ca_cert_blob) {
1721                 X509 *cert = d2i_X509(NULL,
1722                                       (const unsigned char **) &ca_cert_blob,
1723                                       ca_cert_blob_len);
1724                 if (cert == NULL) {
1725                         tls_show_errors(MSG_WARNING, __func__,
1726                                         "Failed to parse ca_cert_blob");
1727                         return -1;
1728                 }
1729
1730                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1731                                          cert)) {
1732                         unsigned long err = ERR_peek_error();
1733                         tls_show_errors(MSG_WARNING, __func__,
1734                                         "Failed to add ca_cert_blob to "
1735                                         "certificate store");
1736                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1737                             ERR_GET_REASON(err) ==
1738                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1739                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1740                                            "cert already in hash table error",
1741                                            __func__);
1742                         } else {
1743                                 X509_free(cert);
1744                                 return -1;
1745                         }
1746                 }
1747                 X509_free(cert);
1748                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1749                            "to certificate store", __func__);
1750                 return 0;
1751         }
1752
1753 #ifdef ANDROID
1754         if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1755                 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1756                 STACK_OF(X509_INFO) *stack = NULL;
1757                 stack_index_t i;
1758
1759                 if (bio) {
1760                         stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1761                         BIO_free(bio);
1762                 }
1763                 if (!stack)
1764                         return -1;
1765
1766                 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1767                         X509_INFO *info = sk_X509_INFO_value(stack, i);
1768                         if (info->x509) {
1769                                 X509_STORE_add_cert(ssl_ctx->cert_store,
1770                                                     info->x509);
1771                         }
1772                         if (info->crl) {
1773                                 X509_STORE_add_crl(ssl_ctx->cert_store,
1774                                                    info->crl);
1775                         }
1776                 }
1777                 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1778                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1779                 return 0;
1780         }
1781 #endif /* ANDROID */
1782
1783 #ifdef CONFIG_NATIVE_WINDOWS
1784         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1785             0) {
1786                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1787                            "system certificate store");
1788                 return 0;
1789         }
1790 #endif /* CONFIG_NATIVE_WINDOWS */
1791
1792         if (ca_cert || ca_path) {
1793 #ifndef OPENSSL_NO_STDIO
1794                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1795                     1) {
1796                         tls_show_errors(MSG_WARNING, __func__,
1797                                         "Failed to load root certificates");
1798                         if (ca_cert &&
1799                             tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1800                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1801                                            "DER format CA certificate",
1802                                            __func__);
1803                         } else
1804                                 return -1;
1805                 } else {
1806                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1807                                    "certificate(s) loaded");
1808                         tls_get_errors(ssl_ctx);
1809                 }
1810 #else /* OPENSSL_NO_STDIO */
1811                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1812                            __func__);
1813                 return -1;
1814 #endif /* OPENSSL_NO_STDIO */
1815         } else {
1816                 /* No ca_cert configured - do not try to verify server
1817                  * certificate */
1818                 conn->ca_cert_verify = 0;
1819         }
1820
1821         return 0;
1822 }
1823
1824
1825 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1826 {
1827         if (ca_cert) {
1828                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1829                 {
1830                         tls_show_errors(MSG_WARNING, __func__,
1831                                         "Failed to load root certificates");
1832                         return -1;
1833                 }
1834
1835                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1836                            "certificate(s) loaded");
1837
1838 #ifndef OPENSSL_NO_STDIO
1839                 /* Add the same CAs to the client certificate requests */
1840                 SSL_CTX_set_client_CA_list(ssl_ctx,
1841                                            SSL_load_client_CA_file(ca_cert));
1842 #endif /* OPENSSL_NO_STDIO */
1843         }
1844
1845         return 0;
1846 }
1847
1848
1849 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1850 {
1851         int flags;
1852
1853         if (check_crl) {
1854                 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1855                 if (cs == NULL) {
1856                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
1857                                         "certificate store when enabling "
1858                                         "check_crl");
1859                         return -1;
1860                 }
1861                 flags = X509_V_FLAG_CRL_CHECK;
1862                 if (check_crl == 2)
1863                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
1864                 X509_STORE_set_flags(cs, flags);
1865         }
1866         return 0;
1867 }
1868
1869
1870 static int tls_connection_set_subject_match(struct tls_connection *conn,
1871                                             const char *subject_match,
1872                                             const char *altsubject_match,
1873                                             const char *suffix_match,
1874                                             const char *domain_match)
1875 {
1876         os_free(conn->subject_match);
1877         conn->subject_match = NULL;
1878         if (subject_match) {
1879                 conn->subject_match = os_strdup(subject_match);
1880                 if (conn->subject_match == NULL)
1881                         return -1;
1882         }
1883
1884         os_free(conn->altsubject_match);
1885         conn->altsubject_match = NULL;
1886         if (altsubject_match) {
1887                 conn->altsubject_match = os_strdup(altsubject_match);
1888                 if (conn->altsubject_match == NULL)
1889                         return -1;
1890         }
1891
1892         os_free(conn->suffix_match);
1893         conn->suffix_match = NULL;
1894         if (suffix_match) {
1895                 conn->suffix_match = os_strdup(suffix_match);
1896                 if (conn->suffix_match == NULL)
1897                         return -1;
1898         }
1899
1900         os_free(conn->domain_match);
1901         conn->domain_match = NULL;
1902         if (domain_match) {
1903                 conn->domain_match = os_strdup(domain_match);
1904                 if (conn->domain_match == NULL)
1905                         return -1;
1906         }
1907
1908         return 0;
1909 }
1910
1911
1912 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1913                               int verify_peer)
1914 {
1915         static int counter = 0;
1916
1917         if (conn == NULL)
1918                 return -1;
1919
1920         if (verify_peer) {
1921                 conn->ca_cert_verify = 1;
1922                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1923                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1924                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1925         } else {
1926                 conn->ca_cert_verify = 0;
1927                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1928         }
1929
1930         SSL_set_accept_state(conn->ssl);
1931
1932         /*
1933          * Set session id context in order to avoid fatal errors when client
1934          * tries to resume a session. However, set the context to a unique
1935          * value in order to effectively disable session resumption for now
1936          * since not all areas of the server code are ready for it (e.g.,
1937          * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1938          * handshake).
1939          */
1940         counter++;
1941         SSL_set_session_id_context(conn->ssl,
1942                                    (const unsigned char *) &counter,
1943                                    sizeof(counter));
1944
1945         return 0;
1946 }
1947
1948
1949 static int tls_connection_client_cert(struct tls_connection *conn,
1950                                       const char *client_cert,
1951                                       const u8 *client_cert_blob,
1952                                       size_t client_cert_blob_len)
1953 {
1954         if (client_cert == NULL && client_cert_blob == NULL)
1955                 return 0;
1956
1957         if (client_cert_blob &&
1958             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1959                                      client_cert_blob_len) == 1) {
1960                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1961                            "OK");
1962                 return 0;
1963         } else if (client_cert_blob) {
1964                 tls_show_errors(MSG_DEBUG, __func__,
1965                                 "SSL_use_certificate_ASN1 failed");
1966         }
1967
1968         if (client_cert == NULL)
1969                 return -1;
1970
1971 #ifdef ANDROID
1972         if (os_strncmp("keystore://", client_cert, 11) == 0) {
1973                 BIO *bio = BIO_from_keystore(&client_cert[11]);
1974                 X509 *x509 = NULL;
1975                 int ret = -1;
1976                 if (bio) {
1977                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1978                         BIO_free(bio);
1979                 }
1980                 if (x509) {
1981                         if (SSL_use_certificate(conn->ssl, x509) == 1)
1982                                 ret = 0;
1983                         X509_free(x509);
1984                 }
1985                 return ret;
1986         }
1987 #endif /* ANDROID */
1988
1989 #ifndef OPENSSL_NO_STDIO
1990         if (SSL_use_certificate_file(conn->ssl, client_cert,
1991                                      SSL_FILETYPE_ASN1) == 1) {
1992                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1993                            " --> OK");
1994                 return 0;
1995         }
1996
1997         if (SSL_use_certificate_file(conn->ssl, client_cert,
1998                                      SSL_FILETYPE_PEM) == 1) {
1999                 ERR_clear_error();
2000                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2001                            " --> OK");
2002                 return 0;
2003         }
2004
2005         tls_show_errors(MSG_DEBUG, __func__,
2006                         "SSL_use_certificate_file failed");
2007 #else /* OPENSSL_NO_STDIO */
2008         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2009 #endif /* OPENSSL_NO_STDIO */
2010
2011         return -1;
2012 }
2013
2014
2015 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
2016 {
2017 #ifndef OPENSSL_NO_STDIO
2018         if (client_cert == NULL)
2019                 return 0;
2020
2021         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2022                                          SSL_FILETYPE_ASN1) != 1 &&
2023             SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2024             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2025                                          SSL_FILETYPE_PEM) != 1) {
2026                 tls_show_errors(MSG_INFO, __func__,
2027                                 "Failed to load client certificate");
2028                 return -1;
2029         }
2030         return 0;
2031 #else /* OPENSSL_NO_STDIO */
2032         if (client_cert == NULL)
2033                 return 0;
2034         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2035         return -1;
2036 #endif /* OPENSSL_NO_STDIO */
2037 }
2038
2039
2040 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2041 {
2042         if (password == NULL) {
2043                 return 0;
2044         }
2045         os_strlcpy(buf, (char *) password, size);
2046         return os_strlen(buf);
2047 }
2048
2049
2050 #ifdef PKCS12_FUNCS
2051 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
2052                             const char *passwd)
2053 {
2054         EVP_PKEY *pkey;
2055         X509 *cert;
2056         STACK_OF(X509) *certs;
2057         int res = 0;
2058         char buf[256];
2059
2060         pkey = NULL;
2061         cert = NULL;
2062         certs = NULL;
2063         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2064                 tls_show_errors(MSG_DEBUG, __func__,
2065                                 "Failed to parse PKCS12 file");
2066                 PKCS12_free(p12);
2067                 return -1;
2068         }
2069         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2070
2071         if (cert) {
2072                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2073                                   sizeof(buf));
2074                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2075                            "subject='%s'", buf);
2076                 if (ssl) {
2077                         if (SSL_use_certificate(ssl, cert) != 1)
2078                                 res = -1;
2079                 } else {
2080                         if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
2081                                 res = -1;
2082                 }
2083                 X509_free(cert);
2084         }
2085
2086         if (pkey) {
2087                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2088                 if (ssl) {
2089                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
2090                                 res = -1;
2091                 } else {
2092                         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
2093                                 res = -1;
2094                 }
2095                 EVP_PKEY_free(pkey);
2096         }
2097
2098         if (certs) {
2099                 while ((cert = sk_X509_pop(certs)) != NULL) {
2100                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
2101                                           sizeof(buf));
2102                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2103                                    " from PKCS12: subject='%s'", buf);
2104                         /*
2105                          * There is no SSL equivalent for the chain cert - so
2106                          * always add it to the context...
2107                          */
2108                         if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
2109                                 res = -1;
2110                                 break;
2111                         }
2112                 }
2113                 sk_X509_free(certs);
2114         }
2115
2116         PKCS12_free(p12);
2117
2118         if (res < 0)
2119                 tls_get_errors(ssl_ctx);
2120
2121         return res;
2122 }
2123 #endif  /* PKCS12_FUNCS */
2124
2125
2126 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
2127                            const char *passwd)
2128 {
2129 #ifdef PKCS12_FUNCS
2130         FILE *f;
2131         PKCS12 *p12;
2132
2133         f = fopen(private_key, "rb");
2134         if (f == NULL)
2135                 return -1;
2136
2137         p12 = d2i_PKCS12_fp(f, NULL);
2138         fclose(f);
2139
2140         if (p12 == NULL) {
2141                 tls_show_errors(MSG_INFO, __func__,
2142                                 "Failed to use PKCS#12 file");
2143                 return -1;
2144         }
2145
2146         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2147
2148 #else /* PKCS12_FUNCS */
2149         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2150                    "p12/pfx files");
2151         return -1;
2152 #endif  /* PKCS12_FUNCS */
2153 }
2154
2155
2156 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
2157                                 const u8 *blob, size_t len, const char *passwd)
2158 {
2159 #ifdef PKCS12_FUNCS
2160         PKCS12 *p12;
2161
2162         p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2163         if (p12 == NULL) {
2164                 tls_show_errors(MSG_INFO, __func__,
2165                                 "Failed to use PKCS#12 blob");
2166                 return -1;
2167         }
2168
2169         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2170
2171 #else /* PKCS12_FUNCS */
2172         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2173                    "p12/pfx blobs");
2174         return -1;
2175 #endif  /* PKCS12_FUNCS */
2176 }
2177
2178
2179 #ifndef OPENSSL_NO_ENGINE
2180 static int tls_engine_get_cert(struct tls_connection *conn,
2181                                const char *cert_id,
2182                                X509 **cert)
2183 {
2184         /* this runs after the private key is loaded so no PIN is required */
2185         struct {
2186                 const char *cert_id;
2187                 X509 *cert;
2188         } params;
2189         params.cert_id = cert_id;
2190         params.cert = NULL;
2191
2192         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2193                              0, &params, NULL, 1)) {
2194                 unsigned long err = ERR_get_error();
2195
2196                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2197                            " '%s' [%s]", cert_id,
2198                            ERR_error_string(err, NULL));
2199                 if (tls_is_pin_error(err))
2200                         return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2201                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2202         }
2203         if (!params.cert) {
2204                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2205                            " '%s'", cert_id);
2206                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2207         }
2208         *cert = params.cert;
2209         return 0;
2210 }
2211 #endif /* OPENSSL_NO_ENGINE */
2212
2213
2214 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2215                                              const char *cert_id)
2216 {
2217 #ifndef OPENSSL_NO_ENGINE
2218         X509 *cert;
2219
2220         if (tls_engine_get_cert(conn, cert_id, &cert))
2221                 return -1;
2222
2223         if (!SSL_use_certificate(conn->ssl, cert)) {
2224                 tls_show_errors(MSG_ERROR, __func__,
2225                                 "SSL_use_certificate failed");
2226                 X509_free(cert);
2227                 return -1;
2228         }
2229         X509_free(cert);
2230         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2231                    "OK");
2232         return 0;
2233
2234 #else /* OPENSSL_NO_ENGINE */
2235         return -1;
2236 #endif /* OPENSSL_NO_ENGINE */
2237 }
2238
2239
2240 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
2241                                          struct tls_connection *conn,
2242                                          const char *ca_cert_id)
2243 {
2244 #ifndef OPENSSL_NO_ENGINE
2245         X509 *cert;
2246         SSL_CTX *ssl_ctx = _ssl_ctx;
2247         X509_STORE *store;
2248
2249         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2250                 return -1;
2251
2252         /* start off the same as tls_connection_ca_cert */
2253         store = X509_STORE_new();
2254         if (store == NULL) {
2255                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2256                            "certificate store", __func__);
2257                 X509_free(cert);
2258                 return -1;
2259         }
2260         SSL_CTX_set_cert_store(ssl_ctx, store);
2261         if (!X509_STORE_add_cert(store, cert)) {
2262                 unsigned long err = ERR_peek_error();
2263                 tls_show_errors(MSG_WARNING, __func__,
2264                                 "Failed to add CA certificate from engine "
2265                                 "to certificate store");
2266                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2267                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2268                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2269                                    " already in hash table error",
2270                                    __func__);
2271                 } else {
2272                         X509_free(cert);
2273                         return -1;
2274                 }
2275         }
2276         X509_free(cert);
2277         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2278                    "to certificate store", __func__);
2279         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2280         conn->ca_cert_verify = 1;
2281
2282         return 0;
2283
2284 #else /* OPENSSL_NO_ENGINE */
2285         return -1;
2286 #endif /* OPENSSL_NO_ENGINE */
2287 }
2288
2289
2290 static int tls_connection_engine_private_key(struct tls_connection *conn)
2291 {
2292 #ifndef OPENSSL_NO_ENGINE
2293         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2294                 tls_show_errors(MSG_ERROR, __func__,
2295                                 "ENGINE: cannot use private key for TLS");
2296                 return -1;
2297         }
2298         if (!SSL_check_private_key(conn->ssl)) {
2299                 tls_show_errors(MSG_INFO, __func__,
2300                                 "Private key failed verification");
2301                 return -1;
2302         }
2303         return 0;
2304 #else /* OPENSSL_NO_ENGINE */
2305         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2306                    "engine support was not compiled in");
2307         return -1;
2308 #endif /* OPENSSL_NO_ENGINE */
2309 }
2310
2311
2312 static int tls_connection_private_key(void *_ssl_ctx,
2313                                       struct tls_connection *conn,
2314                                       const char *private_key,
2315                                       const char *private_key_passwd,
2316                                       const u8 *private_key_blob,
2317                                       size_t private_key_blob_len)
2318 {
2319         SSL_CTX *ssl_ctx = _ssl_ctx;
2320         char *passwd;
2321         int ok;
2322
2323         if (private_key == NULL && private_key_blob == NULL)
2324                 return 0;
2325
2326         if (private_key_passwd) {
2327                 passwd = os_strdup(private_key_passwd);
2328                 if (passwd == NULL)
2329                         return -1;
2330         } else
2331                 passwd = NULL;
2332
2333         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2334         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2335
2336         ok = 0;
2337         while (private_key_blob) {
2338                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2339                                             (u8 *) private_key_blob,
2340                                             private_key_blob_len) == 1) {
2341                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2342                                    "ASN1(EVP_PKEY_RSA) --> OK");
2343                         ok = 1;
2344                         break;
2345                 }
2346
2347                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2348                                             (u8 *) private_key_blob,
2349                                             private_key_blob_len) == 1) {
2350                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2351                                    "ASN1(EVP_PKEY_DSA) --> OK");
2352                         ok = 1;
2353                         break;
2354                 }
2355
2356                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2357                                                (u8 *) private_key_blob,
2358                                                private_key_blob_len) == 1) {
2359                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2360                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
2361                         ok = 1;
2362                         break;
2363                 }
2364
2365                 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2366                                          private_key_blob_len, passwd) == 0) {
2367                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2368                                    "OK");
2369                         ok = 1;
2370                         break;
2371                 }
2372
2373                 break;
2374         }
2375
2376         while (!ok && private_key) {
2377 #ifndef OPENSSL_NO_STDIO
2378                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2379                                             SSL_FILETYPE_ASN1) == 1) {
2380                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2381                                    "SSL_use_PrivateKey_File (DER) --> OK");
2382                         ok = 1;
2383                         break;
2384                 }
2385
2386                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2387                                             SSL_FILETYPE_PEM) == 1) {
2388                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2389                                    "SSL_use_PrivateKey_File (PEM) --> OK");
2390                         ok = 1;
2391                         break;
2392                 }
2393 #else /* OPENSSL_NO_STDIO */
2394                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2395                            __func__);
2396 #endif /* OPENSSL_NO_STDIO */
2397
2398                 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2399                     == 0) {
2400                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2401                                    "--> OK");
2402                         ok = 1;
2403                         break;
2404                 }
2405
2406                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2407                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2408                                    "access certificate store --> OK");
2409                         ok = 1;
2410                         break;
2411                 }
2412
2413                 break;
2414         }
2415
2416         if (!ok) {
2417                 tls_show_errors(MSG_INFO, __func__,
2418                                 "Failed to load private key");
2419                 os_free(passwd);
2420                 return -1;
2421         }
2422         ERR_clear_error();
2423         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2424         os_free(passwd);
2425
2426         if (!SSL_check_private_key(conn->ssl)) {
2427                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2428                                 "verification");
2429                 return -1;
2430         }
2431
2432         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2433         return 0;
2434 }
2435
2436
2437 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2438                                   const char *private_key_passwd)
2439 {
2440         char *passwd;
2441
2442         if (private_key == NULL)
2443                 return 0;
2444
2445         if (private_key_passwd) {
2446                 passwd = os_strdup(private_key_passwd);
2447                 if (passwd == NULL)
2448                         return -1;
2449         } else
2450                 passwd = NULL;
2451
2452         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2453         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2454         if (
2455 #ifndef OPENSSL_NO_STDIO
2456             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2457                                         SSL_FILETYPE_ASN1) != 1 &&
2458             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2459                                         SSL_FILETYPE_PEM) != 1 &&
2460 #endif /* OPENSSL_NO_STDIO */
2461             tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2462                 tls_show_errors(MSG_INFO, __func__,
2463                                 "Failed to load private key");
2464                 os_free(passwd);
2465                 ERR_clear_error();
2466                 return -1;
2467         }
2468         os_free(passwd);
2469         ERR_clear_error();
2470         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2471
2472         if (!SSL_CTX_check_private_key(ssl_ctx)) {
2473                 tls_show_errors(MSG_INFO, __func__,
2474                                 "Private key failed verification");
2475                 return -1;
2476         }
2477
2478         return 0;
2479 }
2480
2481
2482 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2483 {
2484 #ifdef OPENSSL_NO_DH
2485         if (dh_file == NULL)
2486                 return 0;
2487         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2488                    "dh_file specified");
2489         return -1;
2490 #else /* OPENSSL_NO_DH */
2491         DH *dh;
2492         BIO *bio;
2493
2494         /* TODO: add support for dh_blob */
2495         if (dh_file == NULL)
2496                 return 0;
2497         if (conn == NULL)
2498                 return -1;
2499
2500         bio = BIO_new_file(dh_file, "r");
2501         if (bio == NULL) {
2502                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2503                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2504                 return -1;
2505         }
2506         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2507         BIO_free(bio);
2508 #ifndef OPENSSL_NO_DSA
2509         while (dh == NULL) {
2510                 DSA *dsa;
2511                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2512                            " trying to parse as DSA params", dh_file,
2513                            ERR_error_string(ERR_get_error(), NULL));
2514                 bio = BIO_new_file(dh_file, "r");
2515                 if (bio == NULL)
2516                         break;
2517                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2518                 BIO_free(bio);
2519                 if (!dsa) {
2520                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2521                                    "'%s': %s", dh_file,
2522                                    ERR_error_string(ERR_get_error(), NULL));
2523                         break;
2524                 }
2525
2526                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2527                 dh = DSA_dup_DH(dsa);
2528                 DSA_free(dsa);
2529                 if (dh == NULL) {
2530                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2531                                    "params into DH params");
2532                         break;
2533                 }
2534                 break;
2535         }
2536 #endif /* !OPENSSL_NO_DSA */
2537         if (dh == NULL) {
2538                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2539                            "'%s'", dh_file);
2540                 return -1;
2541         }
2542
2543         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2544                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2545                            "%s", dh_file,
2546                            ERR_error_string(ERR_get_error(), NULL));
2547                 DH_free(dh);
2548                 return -1;
2549         }
2550         DH_free(dh);
2551         return 0;
2552 #endif /* OPENSSL_NO_DH */
2553 }
2554
2555
2556 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2557 {
2558 #ifdef OPENSSL_NO_DH
2559         if (dh_file == NULL)
2560                 return 0;
2561         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2562                    "dh_file specified");
2563         return -1;
2564 #else /* OPENSSL_NO_DH */
2565         DH *dh;
2566         BIO *bio;
2567
2568         /* TODO: add support for dh_blob */
2569         if (dh_file == NULL)
2570                 return 0;
2571         if (ssl_ctx == NULL)
2572                 return -1;
2573
2574         bio = BIO_new_file(dh_file, "r");
2575         if (bio == NULL) {
2576                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2577                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2578                 return -1;
2579         }
2580         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2581         BIO_free(bio);
2582 #ifndef OPENSSL_NO_DSA
2583         while (dh == NULL) {
2584                 DSA *dsa;
2585                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2586                            " trying to parse as DSA params", dh_file,
2587                            ERR_error_string(ERR_get_error(), NULL));
2588                 bio = BIO_new_file(dh_file, "r");
2589                 if (bio == NULL)
2590                         break;
2591                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2592                 BIO_free(bio);
2593                 if (!dsa) {
2594                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2595                                    "'%s': %s", dh_file,
2596                                    ERR_error_string(ERR_get_error(), NULL));
2597                         break;
2598                 }
2599
2600                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2601                 dh = DSA_dup_DH(dsa);
2602                 DSA_free(dsa);
2603                 if (dh == NULL) {
2604                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2605                                    "params into DH params");
2606                         break;
2607                 }
2608                 break;
2609         }
2610 #endif /* !OPENSSL_NO_DSA */
2611         if (dh == NULL) {
2612                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2613                            "'%s'", dh_file);
2614                 return -1;
2615         }
2616
2617         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2618                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2619                            "%s", dh_file,
2620                            ERR_error_string(ERR_get_error(), NULL));
2621                 DH_free(dh);
2622                 return -1;
2623         }
2624         DH_free(dh);
2625         return 0;
2626 #endif /* OPENSSL_NO_DH */
2627 }
2628
2629
2630 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2631                             struct tls_keys *keys)
2632 {
2633 #ifdef CONFIG_FIPS
2634         wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2635                    "mode");
2636         return -1;
2637 #else /* CONFIG_FIPS */
2638         SSL *ssl;
2639
2640         if (conn == NULL || keys == NULL)
2641                 return -1;
2642         ssl = conn->ssl;
2643         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2644                 return -1;
2645
2646         os_memset(keys, 0, sizeof(*keys));
2647         keys->client_random = ssl->s3->client_random;
2648         keys->client_random_len = SSL3_RANDOM_SIZE;
2649         keys->server_random = ssl->s3->server_random;
2650         keys->server_random_len = SSL3_RANDOM_SIZE;
2651
2652         return 0;
2653 #endif /* CONFIG_FIPS */
2654 }
2655
2656
2657 static int openssl_get_keyblock_size(SSL *ssl)
2658 {
2659         const EVP_CIPHER *c;
2660         const EVP_MD *h;
2661         int md_size;
2662
2663         if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2664             ssl->read_hash == NULL)
2665                 return -1;
2666
2667         c = ssl->enc_read_ctx->cipher;
2668 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2669         h = EVP_MD_CTX_md(ssl->read_hash);
2670 #else
2671         h = ssl->read_hash;
2672 #endif
2673         if (h)
2674                 md_size = EVP_MD_size(h);
2675 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2676         else if (ssl->s3)
2677                 md_size = ssl->s3->tmp.new_mac_secret_size;
2678 #endif
2679         else
2680                 return -1;
2681
2682         wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2683                    "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2684                    EVP_CIPHER_iv_length(c));
2685         return 2 * (EVP_CIPHER_key_length(c) +
2686                     md_size +
2687                     EVP_CIPHER_iv_length(c));
2688 }
2689
2690
2691 static int openssl_tls_prf(void *tls_ctx, struct tls_connection *conn,
2692                            const char *label, int server_random_first,
2693                            int skip_keyblock, u8 *out, size_t out_len)
2694 {
2695 #ifdef CONFIG_FIPS
2696         wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2697                    "mode");
2698         return -1;
2699 #else /* CONFIG_FIPS */
2700         SSL *ssl;
2701         u8 *rnd;
2702         int ret = -1;
2703         int skip = 0;
2704         u8 *tmp_out = NULL;
2705         u8 *_out = out;
2706
2707         /*
2708          * TLS library did not support key generation, so get the needed TLS
2709          * session parameters and use an internal implementation of TLS PRF to
2710          * derive the key.
2711          */
2712
2713         if (conn == NULL)
2714                 return -1;
2715         ssl = conn->ssl;
2716         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2717             ssl->session->master_key_length <= 0)
2718                 return -1;
2719
2720         if (skip_keyblock) {
2721                 skip = openssl_get_keyblock_size(ssl);
2722                 if (skip < 0)
2723                         return -1;
2724                 tmp_out = os_malloc(skip + out_len);
2725                 if (!tmp_out)
2726                         return -1;
2727                 _out = tmp_out;
2728         }
2729
2730         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2731         if (!rnd) {
2732                 os_free(tmp_out);
2733                 return -1;
2734         }
2735
2736         if (server_random_first) {
2737                 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2738                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2739                         SSL3_RANDOM_SIZE);
2740         } else {
2741                 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2742                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2743                         SSL3_RANDOM_SIZE);
2744         }
2745
2746         /* TODO: TLSv1.2 may need another PRF. This could use something closer
2747          * to SSL_export_keying_material() design. */
2748         if (tls_prf_sha1_md5(ssl->session->master_key,
2749                              ssl->session->master_key_length,
2750                              label, rnd, 2 * SSL3_RANDOM_SIZE,
2751                              _out, skip + out_len) == 0)
2752                 ret = 0;
2753         os_free(rnd);
2754         if (ret == 0 && skip_keyblock)
2755                 os_memcpy(out, _out + skip, out_len);
2756         bin_clear_free(tmp_out, skip);
2757
2758         return ret;
2759 #endif /* CONFIG_FIPS */
2760 }
2761
2762
2763 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2764                        const char *label, int server_random_first,
2765                        int skip_keyblock, u8 *out, size_t out_len)
2766 {
2767 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2768         SSL *ssl;
2769         if (conn == NULL)
2770                 return -1;
2771         if (server_random_first || skip_keyblock)
2772                 return openssl_tls_prf(tls_ctx, conn, label,
2773                                        server_random_first, skip_keyblock,
2774                                        out, out_len);
2775         ssl = conn->ssl;
2776         if (SSL_export_keying_material(ssl, out, out_len, label,
2777                                        os_strlen(label), NULL, 0, 0) == 1) {
2778                 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2779                 return 0;
2780         }
2781 #endif
2782         return openssl_tls_prf(tls_ctx, conn, label, server_random_first,
2783                                skip_keyblock, out, out_len);
2784 }
2785
2786
2787 static struct wpabuf *
2788 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2789                   int server)
2790 {
2791         int res;
2792         struct wpabuf *out_data;
2793
2794         /*
2795          * Give TLS handshake data from the server (if available) to OpenSSL
2796          * for processing.
2797          */
2798         if (in_data &&
2799             BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2800             < 0) {
2801                 tls_show_errors(MSG_INFO, __func__,
2802                                 "Handshake failed - BIO_write");
2803                 return NULL;
2804         }
2805
2806         /* Initiate TLS handshake or continue the existing handshake */
2807         if (server)
2808                 res = SSL_accept(conn->ssl);
2809         else
2810                 res = SSL_connect(conn->ssl);
2811         if (res != 1) {
2812                 int err = SSL_get_error(conn->ssl, res);
2813                 if (err == SSL_ERROR_WANT_READ)
2814                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2815                                    "more data");
2816                 else if (err == SSL_ERROR_WANT_WRITE)
2817                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2818                                    "write");
2819                 else {
2820                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2821                         conn->failed++;
2822                 }
2823         }
2824
2825         /* Get the TLS handshake data to be sent to the server */
2826         res = BIO_ctrl_pending(conn->ssl_out);
2827         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2828         out_data = wpabuf_alloc(res);
2829         if (out_data == NULL) {
2830                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2831                            "handshake output (%d bytes)", res);
2832                 if (BIO_reset(conn->ssl_out) < 0) {
2833                         tls_show_errors(MSG_INFO, __func__,
2834                                         "BIO_reset failed");
2835                 }
2836                 return NULL;
2837         }
2838         res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2839                                       res);
2840         if (res < 0) {
2841                 tls_show_errors(MSG_INFO, __func__,
2842                                 "Handshake failed - BIO_read");
2843                 if (BIO_reset(conn->ssl_out) < 0) {
2844                         tls_show_errors(MSG_INFO, __func__,
2845                                         "BIO_reset failed");
2846                 }
2847                 wpabuf_free(out_data);
2848                 return NULL;
2849         }
2850         wpabuf_put(out_data, res);
2851
2852         return out_data;
2853 }
2854
2855
2856 static struct wpabuf *
2857 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2858 {
2859         struct wpabuf *appl_data;
2860         int res;
2861
2862         appl_data = wpabuf_alloc(max_len + 100);
2863         if (appl_data == NULL)
2864                 return NULL;
2865
2866         res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2867                        wpabuf_size(appl_data));
2868         if (res < 0) {
2869                 int err = SSL_get_error(conn->ssl, res);
2870                 if (err == SSL_ERROR_WANT_READ ||
2871                     err == SSL_ERROR_WANT_WRITE) {
2872                         wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2873                                    "included");
2874                 } else {
2875                         tls_show_errors(MSG_INFO, __func__,
2876                                         "Failed to read possible "
2877                                         "Application Data");
2878                 }
2879                 wpabuf_free(appl_data);
2880                 return NULL;
2881         }
2882
2883         wpabuf_put(appl_data, res);
2884         wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2885                             "message", appl_data);
2886
2887         return appl_data;
2888 }
2889
2890
2891 static struct wpabuf *
2892 openssl_connection_handshake(struct tls_connection *conn,
2893                              const struct wpabuf *in_data,
2894                              struct wpabuf **appl_data, int server)
2895 {
2896         struct wpabuf *out_data;
2897
2898         if (appl_data)
2899                 *appl_data = NULL;
2900
2901         out_data = openssl_handshake(conn, in_data, server);
2902         if (out_data == NULL)
2903                 return NULL;
2904         if (conn->invalid_hb_used) {
2905                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2906                 wpabuf_free(out_data);
2907                 return NULL;
2908         }
2909
2910         if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2911                 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2912
2913         if (conn->invalid_hb_used) {
2914                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2915                 if (appl_data) {
2916                         wpabuf_free(*appl_data);
2917                         *appl_data = NULL;
2918                 }
2919                 wpabuf_free(out_data);
2920                 return NULL;
2921         }
2922
2923         return out_data;
2924 }
2925
2926
2927 struct wpabuf *
2928 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2929                          const struct wpabuf *in_data,
2930                          struct wpabuf **appl_data)
2931 {
2932         return openssl_connection_handshake(conn, in_data, appl_data, 0);
2933 }
2934
2935
2936 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2937                                                 struct tls_connection *conn,
2938                                                 const struct wpabuf *in_data,
2939                                                 struct wpabuf **appl_data)
2940 {
2941         return openssl_connection_handshake(conn, in_data, appl_data, 1);
2942 }
2943
2944
2945 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2946                                        struct tls_connection *conn,
2947                                        const struct wpabuf *in_data)
2948 {
2949         int res;
2950         struct wpabuf *buf;
2951
2952         if (conn == NULL)
2953                 return NULL;
2954
2955         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2956         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2957             (res = BIO_reset(conn->ssl_out)) < 0) {
2958                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2959                 return NULL;
2960         }
2961         res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2962         if (res < 0) {
2963                 tls_show_errors(MSG_INFO, __func__,
2964                                 "Encryption failed - SSL_write");
2965                 return NULL;
2966         }
2967
2968         /* Read encrypted data to be sent to the server */
2969         buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2970         if (buf == NULL)
2971                 return NULL;
2972         res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2973         if (res < 0) {
2974                 tls_show_errors(MSG_INFO, __func__,
2975                                 "Encryption failed - BIO_read");
2976                 wpabuf_free(buf);
2977                 return NULL;
2978         }
2979         wpabuf_put(buf, res);
2980
2981         return buf;
2982 }
2983
2984
2985 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2986                                        struct tls_connection *conn,
2987                                        const struct wpabuf *in_data)
2988 {
2989         int res;
2990         struct wpabuf *buf;
2991
2992         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2993         res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2994                         wpabuf_len(in_data));
2995         if (res < 0) {
2996                 tls_show_errors(MSG_INFO, __func__,
2997                                 "Decryption failed - BIO_write");
2998                 return NULL;
2999         }
3000         if (BIO_reset(conn->ssl_out) < 0) {
3001                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3002                 return NULL;
3003         }
3004
3005         /* Read decrypted data for further processing */
3006         /*
3007          * Even though we try to disable TLS compression, it is possible that
3008          * this cannot be done with all TLS libraries. Add extra buffer space
3009          * to handle the possibility of the decrypted data being longer than
3010          * input data.
3011          */
3012         buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3013         if (buf == NULL)
3014                 return NULL;
3015         res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3016         if (res < 0) {
3017                 tls_show_errors(MSG_INFO, __func__,
3018                                 "Decryption failed - SSL_read");
3019                 wpabuf_free(buf);
3020                 return NULL;
3021         }
3022         wpabuf_put(buf, res);
3023
3024         if (conn->invalid_hb_used) {
3025                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3026                 wpabuf_free(buf);
3027                 return NULL;
3028         }
3029
3030         return buf;
3031 }
3032
3033
3034 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3035 {
3036 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3037         return conn ? SSL_cache_hit(conn->ssl) : 0;
3038 #else
3039         return conn ? conn->ssl->hit : 0;
3040 #endif
3041 }
3042
3043
3044 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3045                                    u8 *ciphers)
3046 {
3047         char buf[100], *pos, *end;
3048         u8 *c;
3049         int ret;
3050
3051         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3052                 return -1;
3053
3054         buf[0] = '\0';
3055         pos = buf;
3056         end = pos + sizeof(buf);
3057
3058         c = ciphers;
3059         while (*c != TLS_CIPHER_NONE) {
3060                 const char *suite;
3061
3062                 switch (*c) {
3063                 case TLS_CIPHER_RC4_SHA:
3064                         suite = "RC4-SHA";
3065                         break;
3066                 case TLS_CIPHER_AES128_SHA:
3067                         suite = "AES128-SHA";
3068                         break;
3069                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3070                         suite = "DHE-RSA-AES128-SHA";
3071                         break;
3072                 case TLS_CIPHER_ANON_DH_AES128_SHA:
3073                         suite = "ADH-AES128-SHA";
3074                         break;
3075                 default:
3076                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3077                                    "cipher selection: %d", *c);
3078                         return -1;
3079                 }
3080                 ret = os_snprintf(pos, end - pos, ":%s", suite);
3081                 if (os_snprintf_error(end - pos, ret))
3082                         break;
3083                 pos += ret;
3084
3085                 c++;
3086         }
3087
3088         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3089
3090         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3091                 tls_show_errors(MSG_INFO, __func__,
3092                                 "Cipher suite configuration failed");
3093                 return -1;
3094         }
3095
3096         return 0;
3097 }
3098
3099
3100 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3101                    char *buf, size_t buflen)
3102 {
3103         const char *name;
3104         if (conn == NULL || conn->ssl == NULL)
3105                 return -1;
3106
3107         name = SSL_get_cipher(conn->ssl);
3108         if (name == NULL)
3109                 return -1;
3110
3111         os_strlcpy(buf, name, buflen);
3112         return 0;
3113 }
3114
3115
3116 int tls_connection_enable_workaround(void *ssl_ctx,
3117                                      struct tls_connection *conn)
3118 {
3119         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3120
3121         return 0;
3122 }
3123
3124
3125 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3126 /* ClientHello TLS extensions require a patch to openssl, so this function is
3127  * commented out unless explicitly needed for EAP-FAST in order to be able to
3128  * build this file with unmodified openssl. */
3129 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3130                                     int ext_type, const u8 *data,
3131                                     size_t data_len)
3132 {
3133         if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3134                 return -1;
3135
3136         if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3137                                        data_len) != 1)
3138                 return -1;
3139
3140         return 0;
3141 }
3142 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3143
3144
3145 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3146 {
3147         if (conn == NULL)
3148                 return -1;
3149         return conn->failed;
3150 }
3151
3152
3153 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3154 {
3155         if (conn == NULL)
3156                 return -1;
3157         return conn->read_alerts;
3158 }
3159
3160
3161 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3162 {
3163         if (conn == NULL)
3164                 return -1;
3165         return conn->write_alerts;
3166 }
3167
3168
3169 #ifdef HAVE_OCSP
3170
3171 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3172 {
3173 #ifndef CONFIG_NO_STDOUT_DEBUG
3174         BIO *out;
3175         size_t rlen;
3176         char *txt;
3177         int res;
3178
3179         if (wpa_debug_level > MSG_DEBUG)
3180                 return;
3181
3182         out = BIO_new(BIO_s_mem());
3183         if (!out)
3184                 return;
3185
3186         OCSP_RESPONSE_print(out, rsp, 0);
3187         rlen = BIO_ctrl_pending(out);
3188         txt = os_malloc(rlen + 1);
3189         if (!txt) {
3190                 BIO_free(out);
3191                 return;
3192         }
3193
3194         res = BIO_read(out, txt, rlen);
3195         if (res > 0) {
3196                 txt[res] = '\0';
3197                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3198         }
3199         os_free(txt);
3200         BIO_free(out);
3201 #endif /* CONFIG_NO_STDOUT_DEBUG */
3202 }
3203
3204
3205 static void debug_print_cert(X509 *cert, const char *title)
3206 {
3207 #ifndef CONFIG_NO_STDOUT_DEBUG
3208         BIO *out;
3209         size_t rlen;
3210         char *txt;
3211         int res;
3212
3213         if (wpa_debug_level > MSG_DEBUG)
3214                 return;
3215
3216         out = BIO_new(BIO_s_mem());
3217         if (!out)
3218                 return;
3219
3220         X509_print(out, cert);
3221         rlen = BIO_ctrl_pending(out);
3222         txt = os_malloc(rlen + 1);
3223         if (!txt) {
3224                 BIO_free(out);
3225                 return;
3226         }
3227
3228         res = BIO_read(out, txt, rlen);
3229         if (res > 0) {
3230                 txt[res] = '\0';
3231                 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3232         }
3233         os_free(txt);
3234
3235         BIO_free(out);
3236 #endif /* CONFIG_NO_STDOUT_DEBUG */
3237 }
3238
3239
3240 static int ocsp_resp_cb(SSL *s, void *arg)
3241 {
3242         struct tls_connection *conn = arg;
3243         const unsigned char *p;
3244         int len, status, reason;
3245         OCSP_RESPONSE *rsp;
3246         OCSP_BASICRESP *basic;
3247         OCSP_CERTID *id;
3248         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3249         X509_STORE *store;
3250         STACK_OF(X509) *certs = NULL;
3251
3252         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3253         if (!p) {
3254                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3255                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3256         }
3257
3258         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3259
3260         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3261         if (!rsp) {
3262                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3263                 return 0;
3264         }
3265
3266         ocsp_debug_print_resp(rsp);
3267
3268         status = OCSP_response_status(rsp);
3269         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3270                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3271                            status, OCSP_response_status_str(status));
3272                 return 0;
3273         }
3274
3275         basic = OCSP_response_get1_basic(rsp);
3276         if (!basic) {
3277                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3278                 return 0;
3279         }
3280
3281         store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3282         if (conn->peer_issuer) {
3283                 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3284
3285                 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3286                         tls_show_errors(MSG_INFO, __func__,
3287                                         "OpenSSL: Could not add issuer to certificate store");
3288                 }
3289                 certs = sk_X509_new_null();
3290                 if (certs) {
3291                         X509 *cert;
3292                         cert = X509_dup(conn->peer_issuer);
3293                         if (cert && !sk_X509_push(certs, cert)) {
3294                                 tls_show_errors(
3295                                         MSG_INFO, __func__,
3296                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
3297                                 X509_free(cert);
3298                                 sk_X509_free(certs);
3299                                 certs = NULL;
3300                         }
3301                         if (certs && conn->peer_issuer_issuer) {
3302                                 cert = X509_dup(conn->peer_issuer_issuer);
3303                                 if (cert && !sk_X509_push(certs, cert)) {
3304                                         tls_show_errors(
3305                                                 MSG_INFO, __func__,
3306                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3307                                         X509_free(cert);
3308                                 }
3309                         }
3310                 }
3311         }
3312
3313         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3314         sk_X509_pop_free(certs, X509_free);
3315         if (status <= 0) {
3316                 tls_show_errors(MSG_INFO, __func__,
3317                                 "OpenSSL: OCSP response failed verification");
3318                 OCSP_BASICRESP_free(basic);
3319                 OCSP_RESPONSE_free(rsp);
3320                 return 0;
3321         }
3322
3323         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3324
3325         if (!conn->peer_cert) {
3326                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3327                 OCSP_BASICRESP_free(basic);
3328                 OCSP_RESPONSE_free(rsp);
3329                 return 0;
3330         }
3331
3332         if (!conn->peer_issuer) {
3333                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3334                 OCSP_BASICRESP_free(basic);
3335                 OCSP_RESPONSE_free(rsp);
3336                 return 0;
3337         }
3338
3339         id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3340         if (!id) {
3341                 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3342                 OCSP_BASICRESP_free(basic);
3343                 OCSP_RESPONSE_free(rsp);
3344                 return 0;
3345         }
3346
3347         if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3348                                    &this_update, &next_update)) {
3349                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3350                            (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3351                            " (OCSP not required)");
3352                 OCSP_BASICRESP_free(basic);
3353                 OCSP_RESPONSE_free(rsp);
3354                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3355         }
3356
3357         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3358                 tls_show_errors(MSG_INFO, __func__,
3359                                 "OpenSSL: OCSP status times invalid");
3360                 OCSP_BASICRESP_free(basic);
3361                 OCSP_RESPONSE_free(rsp);
3362                 return 0;
3363         }
3364
3365         OCSP_BASICRESP_free(basic);
3366         OCSP_RESPONSE_free(rsp);
3367
3368         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3369                    OCSP_cert_status_str(status));
3370
3371         if (status == V_OCSP_CERTSTATUS_GOOD)
3372                 return 1;
3373         if (status == V_OCSP_CERTSTATUS_REVOKED)
3374                 return 0;
3375         if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3376                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3377                 return 0;
3378         }
3379         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3380         return 1;
3381 }
3382
3383
3384 static int ocsp_status_cb(SSL *s, void *arg)
3385 {
3386         char *tmp;
3387         char *resp;
3388         size_t len;
3389
3390         if (tls_global->ocsp_stapling_response == NULL) {
3391                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3392                 return SSL_TLSEXT_ERR_OK;
3393         }
3394
3395         resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3396         if (resp == NULL) {
3397                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3398                 /* TODO: Build OCSPResponse with responseStatus = internalError
3399                  */
3400                 return SSL_TLSEXT_ERR_OK;
3401         }
3402         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3403         tmp = OPENSSL_malloc(len);
3404         if (tmp == NULL) {
3405                 os_free(resp);
3406                 return SSL_TLSEXT_ERR_ALERT_FATAL;
3407         }
3408
3409         os_memcpy(tmp, resp, len);
3410         os_free(resp);
3411         SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3412
3413         return SSL_TLSEXT_ERR_OK;
3414 }
3415
3416 #endif /* HAVE_OCSP */
3417
3418
3419 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3420                               const struct tls_connection_params *params)
3421 {
3422         int ret;
3423         unsigned long err;
3424         int can_pkcs11 = 0;
3425         const char *key_id = params->key_id;
3426         const char *cert_id = params->cert_id;
3427         const char *ca_cert_id = params->ca_cert_id;
3428         const char *engine_id = params->engine ? params->engine_id : NULL;
3429
3430         if (conn == NULL)
3431                 return -1;
3432
3433         /*
3434          * If the engine isn't explicitly configured, and any of the
3435          * cert/key fields are actually PKCS#11 URIs, then automatically
3436          * use the PKCS#11 ENGINE.
3437          */
3438         if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3439                 can_pkcs11 = 1;
3440
3441         if (!key_id && params->private_key && can_pkcs11 &&
3442             os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3443                 can_pkcs11 = 2;
3444                 key_id = params->private_key;
3445         }
3446
3447         if (!cert_id && params->client_cert && can_pkcs11 &&
3448             os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3449                 can_pkcs11 = 2;
3450                 cert_id = params->client_cert;
3451         }
3452
3453         if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3454             os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3455                 can_pkcs11 = 2;
3456                 ca_cert_id = params->ca_cert;
3457         }
3458
3459         /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3460         if (can_pkcs11 == 2 && !engine_id)
3461                 engine_id = "pkcs11";
3462
3463         if (params->flags & TLS_CONN_EAP_FAST) {
3464                 wpa_printf(MSG_DEBUG,
3465                            "OpenSSL: Use TLSv1_method() for EAP-FAST");
3466                 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3467                         tls_show_errors(MSG_INFO, __func__,
3468                                         "Failed to set TLSv1_method() for EAP-FAST");
3469                         return -1;
3470                 }
3471         }
3472
3473         while ((err = ERR_get_error())) {
3474                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3475                            __func__, ERR_error_string(err, NULL));
3476         }
3477
3478         if (engine_id) {
3479                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3480                 ret = tls_engine_init(conn, engine_id, params->pin,
3481                                       key_id, cert_id, ca_cert_id);
3482                 if (ret)
3483                         return ret;
3484         }
3485         if (tls_connection_set_subject_match(conn,
3486                                              params->subject_match,
3487                                              params->altsubject_match,
3488                                              params->suffix_match,
3489                                              params->domain_match))
3490                 return -1;
3491
3492         if (engine_id && ca_cert_id) {
3493                 if (tls_connection_engine_ca_cert(tls_ctx, conn,
3494                                                   ca_cert_id))
3495                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3496         } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
3497                                           params->ca_cert_blob,
3498                                           params->ca_cert_blob_len,
3499                                           params->ca_path))
3500                 return -1;
3501
3502         if (engine_id && cert_id) {
3503                 if (tls_connection_engine_client_cert(conn, cert_id))
3504                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3505         } else if (tls_connection_client_cert(conn, params->client_cert,
3506                                               params->client_cert_blob,
3507                                               params->client_cert_blob_len))
3508                 return -1;
3509
3510         if (engine_id && key_id) {
3511                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3512                 if (tls_connection_engine_private_key(conn))
3513                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3514         } else if (tls_connection_private_key(tls_ctx, conn,
3515                                               params->private_key,
3516                                               params->private_key_passwd,
3517                                               params->private_key_blob,
3518                                               params->private_key_blob_len)) {
3519                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3520                            params->private_key);
3521                 return -1;
3522         }
3523
3524         if (tls_connection_dh(conn, params->dh_file)) {
3525                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3526                            params->dh_file);
3527                 return -1;
3528         }
3529
3530         if (params->openssl_ciphers &&
3531             SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3532                 wpa_printf(MSG_INFO,
3533                            "OpenSSL: Failed to set cipher string '%s'",
3534                            params->openssl_ciphers);
3535                 return -1;
3536         }
3537
3538 #ifdef SSL_OP_NO_TICKET
3539         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3540                 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3541 #ifdef SSL_clear_options
3542         else
3543                 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3544 #endif /* SSL_clear_options */
3545 #endif /*  SSL_OP_NO_TICKET */
3546
3547 #ifdef SSL_OP_NO_TLSv1_1
3548         if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3549                 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3550         else
3551                 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3552 #endif /* SSL_OP_NO_TLSv1_1 */
3553 #ifdef SSL_OP_NO_TLSv1_2
3554         if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3555                 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3556         else
3557                 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3558 #endif /* SSL_OP_NO_TLSv1_2 */
3559
3560 #ifdef HAVE_OCSP
3561         if (params->flags & TLS_CONN_REQUEST_OCSP) {
3562                 SSL_CTX *ssl_ctx = tls_ctx;
3563                 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3564                 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3565                 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3566         }
3567 #endif /* HAVE_OCSP */
3568
3569         conn->flags = params->flags;
3570
3571         tls_get_errors(tls_ctx);
3572
3573         return 0;
3574 }
3575
3576
3577 int tls_global_set_params(void *tls_ctx,
3578                           const struct tls_connection_params *params)
3579 {
3580         SSL_CTX *ssl_ctx = tls_ctx;
3581         unsigned long err;
3582
3583         while ((err = ERR_get_error())) {
3584                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3585                            __func__, ERR_error_string(err, NULL));
3586         }
3587
3588         if (tls_global_ca_cert(ssl_ctx, params->ca_cert) ||
3589             tls_global_client_cert(ssl_ctx, params->client_cert) ||
3590             tls_global_private_key(ssl_ctx, params->private_key,
3591                                    params->private_key_passwd) ||
3592             tls_global_dh(ssl_ctx, params->dh_file)) {
3593                 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3594                 return -1;
3595         }
3596
3597         if (params->openssl_ciphers &&
3598             SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3599                 wpa_printf(MSG_INFO,
3600                            "OpenSSL: Failed to set cipher string '%s'",
3601                            params->openssl_ciphers);
3602                 return -1;
3603         }
3604
3605 #ifdef SSL_OP_NO_TICKET
3606         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3607                 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3608 #ifdef SSL_CTX_clear_options
3609         else
3610                 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3611 #endif /* SSL_clear_options */
3612 #endif /*  SSL_OP_NO_TICKET */
3613
3614 #ifdef HAVE_OCSP
3615         SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3616         SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3617         os_free(tls_global->ocsp_stapling_response);
3618         if (params->ocsp_stapling_response)
3619                 tls_global->ocsp_stapling_response =
3620                         os_strdup(params->ocsp_stapling_response);
3621         else
3622                 tls_global->ocsp_stapling_response = NULL;
3623 #endif /* HAVE_OCSP */
3624
3625         return 0;
3626 }
3627
3628
3629 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3630 /* Pre-shared secred requires a patch to openssl, so this function is
3631  * commented out unless explicitly needed for EAP-FAST in order to be able to
3632  * build this file with unmodified openssl. */
3633
3634 #ifdef OPENSSL_IS_BORINGSSL
3635 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3636                            STACK_OF(SSL_CIPHER) *peer_ciphers,
3637                            const SSL_CIPHER **cipher, void *arg)
3638 #else /* OPENSSL_IS_BORINGSSL */
3639 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3640                            STACK_OF(SSL_CIPHER) *peer_ciphers,
3641                            SSL_CIPHER **cipher, void *arg)
3642 #endif /* OPENSSL_IS_BORINGSSL */
3643 {
3644         struct tls_connection *conn = arg;
3645         int ret;
3646
3647         if (conn == NULL || conn->session_ticket_cb == NULL)
3648                 return 0;
3649
3650         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3651                                       conn->session_ticket,
3652                                       conn->session_ticket_len,
3653                                       s->s3->client_random,
3654                                       s->s3->server_random, secret);
3655         os_free(conn->session_ticket);
3656         conn->session_ticket = NULL;
3657
3658         if (ret <= 0)
3659                 return 0;
3660
3661         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3662         return 1;
3663 }
3664
3665
3666 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3667                                      int len, void *arg)
3668 {
3669         struct tls_connection *conn = arg;
3670
3671         if (conn == NULL || conn->session_ticket_cb == NULL)
3672                 return 0;
3673
3674         wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3675
3676         os_free(conn->session_ticket);
3677         conn->session_ticket = NULL;
3678
3679         wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3680                     "extension", data, len);
3681
3682         conn->session_ticket = os_malloc(len);
3683         if (conn->session_ticket == NULL)
3684                 return 0;
3685
3686         os_memcpy(conn->session_ticket, data, len);
3687         conn->session_ticket_len = len;
3688
3689         return 1;
3690 }
3691 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3692
3693
3694 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3695                                          struct tls_connection *conn,
3696                                          tls_session_ticket_cb cb,
3697                                          void *ctx)
3698 {
3699 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3700         conn->session_ticket_cb = cb;
3701         conn->session_ticket_cb_ctx = ctx;
3702
3703         if (cb) {
3704                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3705                                               conn) != 1)
3706                         return -1;
3707                 SSL_set_session_ticket_ext_cb(conn->ssl,
3708                                               tls_session_ticket_ext_cb, conn);
3709         } else {
3710                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3711                         return -1;
3712                 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3713         }
3714
3715         return 0;
3716 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3717         return -1;
3718 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3719 }
3720
3721
3722 int tls_get_library_version(char *buf, size_t buf_len)
3723 {
3724         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
3725                            OPENSSL_VERSION_TEXT,
3726                            SSLeay_version(SSLEAY_VERSION));
3727 }