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