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