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