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