curl: Fix memory leak in subjectAltName parsing
[mech_eap.git] / src / utils / http_curl.c
1 /*
2  * HTTP wrapper for libcurl
3  * Copyright (c) 2012-2014, Qualcomm Atheros, Inc.
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 #include <curl/curl.h>
11 #ifdef EAP_TLS_OPENSSL
12 #include <openssl/ssl.h>
13 #include <openssl/asn1.h>
14 #include <openssl/asn1t.h>
15 #include <openssl/x509v3.h>
16
17 #ifdef SSL_set_tlsext_status_type
18 #ifndef OPENSSL_NO_TLSEXT
19 #define HAVE_OCSP
20 #include <openssl/err.h>
21 #include <openssl/ocsp.h>
22 #endif /* OPENSSL_NO_TLSEXT */
23 #endif /* SSL_set_tlsext_status_type */
24 #endif /* EAP_TLS_OPENSSL */
25
26 #include "common.h"
27 #include "xml-utils.h"
28 #include "http-utils.h"
29 #ifdef EAP_TLS_OPENSSL
30 #include "crypto/tls_openssl.h"
31 #endif /* EAP_TLS_OPENSSL */
32
33
34 struct http_ctx {
35         void *ctx;
36         struct xml_node_ctx *xml;
37         CURL *curl;
38         struct curl_slist *curl_hdr;
39         char *svc_address;
40         char *svc_ca_fname;
41         char *svc_username;
42         char *svc_password;
43         char *svc_client_cert;
44         char *svc_client_key;
45         char *curl_buf;
46         size_t curl_buf_len;
47
48         int (*cert_cb)(void *ctx, struct http_cert *cert);
49         void *cert_cb_ctx;
50
51         enum {
52                 NO_OCSP, OPTIONAL_OCSP, MANDATORY_OCSP
53         } ocsp;
54         X509 *peer_cert;
55         X509 *peer_issuer;
56         X509 *peer_issuer_issuer;
57
58         const char *last_err;
59 };
60
61
62 static void clear_curl(struct http_ctx *ctx)
63 {
64         if (ctx->curl) {
65                 curl_easy_cleanup(ctx->curl);
66                 ctx->curl = NULL;
67         }
68         if (ctx->curl_hdr) {
69                 curl_slist_free_all(ctx->curl_hdr);
70                 ctx->curl_hdr = NULL;
71         }
72 }
73
74
75 static void clone_str(char **dst, const char *src)
76 {
77         os_free(*dst);
78         if (src)
79                 *dst = os_strdup(src);
80         else
81                 *dst = NULL;
82 }
83
84
85 static void debug_dump(struct http_ctx *ctx, const char *title,
86                        const char *buf, size_t len)
87 {
88         char *txt;
89         size_t i;
90
91         for (i = 0; i < len; i++) {
92                 if (buf[i] < 32 && buf[i] != '\t' && buf[i] != '\n' &&
93                     buf[i] != '\r') {
94                         wpa_hexdump_ascii(MSG_MSGDUMP, title, buf, len);
95                         return;
96                 }
97         }
98
99         txt = os_malloc(len + 1);
100         if (txt == NULL)
101                 return;
102         os_memcpy(txt, buf, len);
103         txt[len] = '\0';
104         while (len > 0) {
105                 len--;
106                 if (txt[len] == '\n' || txt[len] == '\r')
107                         txt[len] = '\0';
108                 else
109                         break;
110         }
111         wpa_printf(MSG_MSGDUMP, "%s[%s]", title, txt);
112         os_free(txt);
113 }
114
115
116 static int curl_cb_debug(CURL *curl, curl_infotype info, char *buf, size_t len,
117                          void *userdata)
118 {
119         struct http_ctx *ctx = userdata;
120         switch (info) {
121         case CURLINFO_TEXT:
122                 debug_dump(ctx, "CURLINFO_TEXT", buf, len);
123                 break;
124         case CURLINFO_HEADER_IN:
125                 debug_dump(ctx, "CURLINFO_HEADER_IN", buf, len);
126                 break;
127         case CURLINFO_HEADER_OUT:
128                 debug_dump(ctx, "CURLINFO_HEADER_OUT", buf, len);
129                 break;
130         case CURLINFO_DATA_IN:
131                 debug_dump(ctx, "CURLINFO_DATA_IN", buf, len);
132                 break;
133         case CURLINFO_DATA_OUT:
134                 debug_dump(ctx, "CURLINFO_DATA_OUT", buf, len);
135                 break;
136         case CURLINFO_SSL_DATA_IN:
137                 wpa_printf(MSG_DEBUG, "debug - CURLINFO_SSL_DATA_IN - %d",
138                            (int) len);
139                 break;
140         case CURLINFO_SSL_DATA_OUT:
141                 wpa_printf(MSG_DEBUG, "debug - CURLINFO_SSL_DATA_OUT - %d",
142                            (int) len);
143                 break;
144         case CURLINFO_END:
145                 wpa_printf(MSG_DEBUG, "debug - CURLINFO_END - %d",
146                            (int) len);
147                 break;
148         }
149         return 0;
150 }
151
152
153 static size_t curl_cb_write(void *ptr, size_t size, size_t nmemb,
154                             void *userdata)
155 {
156         struct http_ctx *ctx = userdata;
157         char *n;
158         n = os_realloc(ctx->curl_buf, ctx->curl_buf_len + size * nmemb + 1);
159         if (n == NULL)
160                 return 0;
161         ctx->curl_buf = n;
162         os_memcpy(n + ctx->curl_buf_len, ptr, size * nmemb);
163         n[ctx->curl_buf_len + size * nmemb] = '\0';
164         ctx->curl_buf_len += size * nmemb;
165         return size * nmemb;
166 }
167
168
169 #ifdef EAP_TLS_OPENSSL
170
171 static void debug_dump_cert(const char *title, X509 *cert)
172 {
173         BIO *out;
174         char *txt;
175         size_t rlen;
176
177         out = BIO_new(BIO_s_mem());
178         if (!out)
179                 return;
180
181         X509_print_ex(out, cert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
182         rlen = BIO_ctrl_pending(out);
183         txt = os_malloc(rlen + 1);
184         if (txt) {
185                 int res = BIO_read(out, txt, rlen);
186                 if (res > 0) {
187                         txt[res] = '\0';
188                         wpa_printf(MSG_MSGDUMP, "%s:\n%s", title, txt);
189                 }
190                 os_free(txt);
191         }
192         BIO_free(out);
193 }
194
195
196 static void add_alt_name_othername(struct http_ctx *ctx, struct http_cert *cert,
197                                    OTHERNAME *o)
198 {
199         char txt[100];
200         int res;
201         struct http_othername *on;
202         ASN1_TYPE *val;
203
204         on = os_realloc_array(cert->othername, cert->num_othername + 1,
205                               sizeof(struct http_othername));
206         if (on == NULL)
207                 return;
208         cert->othername = on;
209         on = &on[cert->num_othername];
210         os_memset(on, 0, sizeof(*on));
211
212         res = OBJ_obj2txt(txt, sizeof(txt), o->type_id, 1);
213         if (res < 0 || res >= (int) sizeof(txt))
214                 return;
215
216         on->oid = os_strdup(txt);
217         if (on->oid == NULL)
218                 return;
219
220         val = o->value;
221         on->data = val->value.octet_string->data;
222         on->len = val->value.octet_string->length;
223
224         cert->num_othername++;
225 }
226
227
228 static void add_alt_name_dns(struct http_ctx *ctx, struct http_cert *cert,
229                              ASN1_STRING *name)
230 {
231         char *buf;
232         char **n;
233
234         buf = NULL;
235         if (ASN1_STRING_to_UTF8((unsigned char **) &buf, name) < 0)
236                 return;
237
238         n = os_realloc_array(cert->dnsname, cert->num_dnsname + 1,
239                              sizeof(char *));
240         if (n == NULL)
241                 return;
242
243         cert->dnsname = n;
244         n[cert->num_dnsname] = buf;
245         cert->num_dnsname++;
246 }
247
248
249 static void add_alt_name(struct http_ctx *ctx, struct http_cert *cert,
250                          const GENERAL_NAME *name)
251 {
252         switch (name->type) {
253         case GEN_OTHERNAME:
254                 add_alt_name_othername(ctx, cert, name->d.otherName);
255                 break;
256         case GEN_DNS:
257                 add_alt_name_dns(ctx, cert, name->d.dNSName);
258                 break;
259         }
260 }
261
262
263 static void add_alt_names(struct http_ctx *ctx, struct http_cert *cert,
264                           GENERAL_NAMES *names)
265 {
266         int num, i;
267
268         num = sk_GENERAL_NAME_num(names);
269         for (i = 0; i < num; i++) {
270                 const GENERAL_NAME *name;
271                 name = sk_GENERAL_NAME_value(names, i);
272                 add_alt_name(ctx, cert, name);
273         }
274 }
275
276
277 /* RFC 3709 */
278
279 typedef struct {
280         X509_ALGOR *hashAlg;
281         ASN1_OCTET_STRING *hashValue;
282 } HashAlgAndValue;
283
284 typedef struct {
285         STACK_OF(HashAlgAndValue) *refStructHash;
286         STACK_OF(ASN1_IA5STRING) *refStructURI;
287 } LogotypeReference;
288
289 typedef struct {
290         ASN1_IA5STRING *mediaType;
291         STACK_OF(HashAlgAndValue) *logotypeHash;
292         STACK_OF(ASN1_IA5STRING) *logotypeURI;
293 } LogotypeDetails;
294
295 typedef struct {
296         int type;
297         union {
298                 ASN1_INTEGER *numBits;
299                 ASN1_INTEGER *tableSize;
300         } d;
301 } LogotypeImageResolution;
302
303 typedef struct {
304         ASN1_INTEGER *type; /* LogotypeImageType ::= INTEGER */
305         ASN1_INTEGER *fileSize;
306         ASN1_INTEGER *xSize;
307         ASN1_INTEGER *ySize;
308         LogotypeImageResolution *resolution;
309         ASN1_IA5STRING *language;
310 } LogotypeImageInfo;
311
312 typedef struct {
313         LogotypeDetails *imageDetails;
314         LogotypeImageInfo *imageInfo;
315 } LogotypeImage;
316
317 typedef struct {
318         ASN1_INTEGER *fileSize;
319         ASN1_INTEGER *playTime;
320         ASN1_INTEGER *channels;
321         ASN1_INTEGER *sampleRate;
322         ASN1_IA5STRING *language;
323 } LogotypeAudioInfo;
324
325 typedef struct {
326         LogotypeDetails *audioDetails;
327         LogotypeAudioInfo *audioInfo;
328 } LogotypeAudio;
329
330 typedef struct {
331         STACK_OF(LogotypeImage) *image;
332         STACK_OF(LogotypeAudio) *audio;
333 } LogotypeData;
334
335 typedef struct {
336         int type;
337         union {
338                 LogotypeData *direct;
339                 LogotypeReference *indirect;
340         } d;
341 } LogotypeInfo;
342
343 typedef struct {
344         ASN1_OBJECT *logotypeType;
345         LogotypeInfo *info;
346 } OtherLogotypeInfo;
347
348 typedef struct {
349         STACK_OF(LogotypeInfo) *communityLogos;
350         LogotypeInfo *issuerLogo;
351         LogotypeInfo *subjectLogo;
352         STACK_OF(OtherLogotypeInfo) *otherLogos;
353 } LogotypeExtn;
354
355 ASN1_SEQUENCE(HashAlgAndValue) = {
356         ASN1_SIMPLE(HashAlgAndValue, hashAlg, X509_ALGOR),
357         ASN1_SIMPLE(HashAlgAndValue, hashValue, ASN1_OCTET_STRING)
358 } ASN1_SEQUENCE_END(HashAlgAndValue);
359
360 ASN1_SEQUENCE(LogotypeReference) = {
361         ASN1_SEQUENCE_OF(LogotypeReference, refStructHash, HashAlgAndValue),
362         ASN1_SEQUENCE_OF(LogotypeReference, refStructURI, ASN1_IA5STRING)
363 } ASN1_SEQUENCE_END(LogotypeReference);
364
365 ASN1_SEQUENCE(LogotypeDetails) = {
366         ASN1_SIMPLE(LogotypeDetails, mediaType, ASN1_IA5STRING),
367         ASN1_SEQUENCE_OF(LogotypeDetails, logotypeHash, HashAlgAndValue),
368         ASN1_SEQUENCE_OF(LogotypeDetails, logotypeURI, ASN1_IA5STRING)
369 } ASN1_SEQUENCE_END(LogotypeDetails);
370
371 ASN1_CHOICE(LogotypeImageResolution) = {
372         ASN1_IMP(LogotypeImageResolution, d.numBits, ASN1_INTEGER, 1),
373         ASN1_IMP(LogotypeImageResolution, d.tableSize, ASN1_INTEGER, 2)
374 } ASN1_CHOICE_END(LogotypeImageResolution);
375
376 ASN1_SEQUENCE(LogotypeImageInfo) = {
377         ASN1_IMP_OPT(LogotypeImageInfo, type, ASN1_INTEGER, 0),
378         ASN1_SIMPLE(LogotypeImageInfo, fileSize, ASN1_INTEGER),
379         ASN1_SIMPLE(LogotypeImageInfo, xSize, ASN1_INTEGER),
380         ASN1_SIMPLE(LogotypeImageInfo, ySize, ASN1_INTEGER),
381         ASN1_OPT(LogotypeImageInfo, resolution, LogotypeImageResolution),
382         ASN1_IMP_OPT(LogotypeImageInfo, language, ASN1_IA5STRING, 4),
383 } ASN1_SEQUENCE_END(LogotypeImageInfo);
384
385 ASN1_SEQUENCE(LogotypeImage) = {
386         ASN1_SIMPLE(LogotypeImage, imageDetails, LogotypeDetails),
387         ASN1_OPT(LogotypeImage, imageInfo, LogotypeImageInfo)
388 } ASN1_SEQUENCE_END(LogotypeImage);
389
390 ASN1_SEQUENCE(LogotypeAudioInfo) = {
391         ASN1_SIMPLE(LogotypeAudioInfo, fileSize, ASN1_INTEGER),
392         ASN1_SIMPLE(LogotypeAudioInfo, playTime, ASN1_INTEGER),
393         ASN1_SIMPLE(LogotypeAudioInfo, channels, ASN1_INTEGER),
394         ASN1_IMP_OPT(LogotypeAudioInfo, sampleRate, ASN1_INTEGER, 3),
395         ASN1_IMP_OPT(LogotypeAudioInfo, language, ASN1_IA5STRING, 4)
396 } ASN1_SEQUENCE_END(LogotypeAudioInfo);
397
398 ASN1_SEQUENCE(LogotypeAudio) = {
399         ASN1_SIMPLE(LogotypeAudio, audioDetails, LogotypeDetails),
400         ASN1_OPT(LogotypeAudio, audioInfo, LogotypeAudioInfo)
401 } ASN1_SEQUENCE_END(LogotypeAudio);
402
403 ASN1_SEQUENCE(LogotypeData) = {
404         ASN1_SEQUENCE_OF_OPT(LogotypeData, image, LogotypeImage),
405         ASN1_IMP_SEQUENCE_OF_OPT(LogotypeData, audio, LogotypeAudio, 1)
406 } ASN1_SEQUENCE_END(LogotypeData);
407
408 ASN1_CHOICE(LogotypeInfo) = {
409         ASN1_IMP(LogotypeInfo, d.direct, LogotypeData, 0),
410         ASN1_IMP(LogotypeInfo, d.indirect, LogotypeReference, 1)
411 } ASN1_CHOICE_END(LogotypeInfo);
412
413 ASN1_SEQUENCE(OtherLogotypeInfo) = {
414         ASN1_SIMPLE(OtherLogotypeInfo, logotypeType, ASN1_OBJECT),
415         ASN1_SIMPLE(OtherLogotypeInfo, info, LogotypeInfo)
416 } ASN1_SEQUENCE_END(OtherLogotypeInfo);
417
418 ASN1_SEQUENCE(LogotypeExtn) = {
419         ASN1_EXP_SEQUENCE_OF_OPT(LogotypeExtn, communityLogos, LogotypeInfo, 0),
420         ASN1_EXP_OPT(LogotypeExtn, issuerLogo, LogotypeInfo, 1),
421         ASN1_EXP_OPT(LogotypeExtn, issuerLogo, LogotypeInfo, 2),
422         ASN1_EXP_SEQUENCE_OF_OPT(LogotypeExtn, otherLogos, OtherLogotypeInfo, 3)
423 } ASN1_SEQUENCE_END(LogotypeExtn);
424
425 IMPLEMENT_ASN1_FUNCTIONS(LogotypeExtn);
426
427 #ifdef OPENSSL_IS_BORINGSSL
428 #define sk_LogotypeInfo_num(st) \
429 sk_num(CHECKED_CAST(_STACK *, STACK_OF(LogotypeInfo) *, (st)))
430 #define sk_LogotypeInfo_value(st, i) (LogotypeInfo *) \
431 sk_value(CHECKED_CAST(_STACK *, const STACK_OF(LogotypeInfo) *, (st)), (i))
432 #define sk_LogotypeImage_num(st) \
433 sk_num(CHECKED_CAST(_STACK *, STACK_OF(LogotypeImage) *, (st)))
434 #define sk_LogotypeImage_value(st, i) (LogotypeImage *) \
435 sk_value(CHECKED_CAST(_STACK *, const STACK_OF(LogotypeImage) *, (st)), (i))
436 #define sk_LogotypeAudio_num(st) \
437 sk_num(CHECKED_CAST(_STACK *, STACK_OF(LogotypeAudio) *, (st)))
438 #define sk_LogotypeAudio_value(st, i) (LogotypeAudio *) \
439 sk_value(CHECK_CAST(_STACK *, const STACK_OF(LogotypeAudio) *, (st)), (i))
440 #define sk_HashAlgAndValue_num(st) \
441 sk_num(CHECKED_CAST(_STACK *, STACK_OF(HashAlgAndValue) *, (st)))
442 #define sk_HashAlgAndValue_value(st, i) (HashAlgAndValue *) \
443 sk_value(CHECKED_CAST(_STACK *, const STACK_OF(HashAlgAndValue) *, (st)), (i))
444 #define sk_ASN1_IA5STRING_num(st) \
445 sk_num(CHECKED_CAST(_STACK *, STACK_OF(ASN1_IA5STRING) *, (st)))
446 #define sk_ASN1_IA5STRING_value(st, i) (ASN1_IA5STRING *) \
447 sk_value(CHECKED_CAST(_STACK *, const STACK_OF(ASN1_IA5STRING) *, (st)), (i))
448 #else /* OPENSSL_IS_BORINGSSL */
449 #define sk_LogotypeInfo_num(st) SKM_sk_num(LogotypeInfo, (st))
450 #define sk_LogotypeInfo_value(st, i) SKM_sk_value(LogotypeInfo, (st), (i))
451 #define sk_LogotypeImage_num(st) SKM_sk_num(LogotypeImage, (st))
452 #define sk_LogotypeImage_value(st, i) SKM_sk_value(LogotypeImage, (st), (i))
453 #define sk_LogotypeAudio_num(st) SKM_sk_num(LogotypeAudio, (st))
454 #define sk_LogotypeAudio_value(st, i) SKM_sk_value(LogotypeAudio, (st), (i))
455 #define sk_HashAlgAndValue_num(st) SKM_sk_num(HashAlgAndValue, (st))
456 #define sk_HashAlgAndValue_value(st, i) SKM_sk_value(HashAlgAndValue, (st), (i))
457 #define sk_ASN1_IA5STRING_num(st) SKM_sk_num(ASN1_IA5STRING, (st))
458 #define sk_ASN1_IA5STRING_value(st, i) SKM_sk_value(ASN1_IA5STRING, (st), (i))
459 #endif /* OPENSSL_IS_BORINGSSL */
460
461
462 static void add_logo(struct http_ctx *ctx, struct http_cert *hcert,
463                      HashAlgAndValue *hash, ASN1_IA5STRING *uri)
464 {
465         char txt[100];
466         int res, len;
467         struct http_logo *n;
468
469         if (hash == NULL || uri == NULL)
470                 return;
471
472         res = OBJ_obj2txt(txt, sizeof(txt), hash->hashAlg->algorithm, 1);
473         if (res < 0 || res >= (int) sizeof(txt))
474                 return;
475
476         n = os_realloc_array(hcert->logo, hcert->num_logo + 1,
477                              sizeof(struct http_logo));
478         if (n == NULL)
479                 return;
480         hcert->logo = n;
481         n = &hcert->logo[hcert->num_logo];
482         os_memset(n, 0, sizeof(*n));
483
484         n->alg_oid = os_strdup(txt);
485         if (n->alg_oid == NULL)
486                 return;
487
488         n->hash_len = ASN1_STRING_length(hash->hashValue);
489         n->hash = os_malloc(n->hash_len);
490         if (n->hash == NULL) {
491                 os_free(n->alg_oid);
492                 return;
493         }
494         os_memcpy(n->hash, ASN1_STRING_data(hash->hashValue), n->hash_len);
495
496         len = ASN1_STRING_length(uri);
497         n->uri = os_malloc(len + 1);
498         if (n->uri == NULL) {
499                 os_free(n->alg_oid);
500                 os_free(n->hash);
501                 return;
502         }
503         os_memcpy(n->uri, ASN1_STRING_data(uri), len);
504         n->uri[len] = '\0';
505
506         hcert->num_logo++;
507 }
508
509
510 static void add_logo_direct(struct http_ctx *ctx, struct http_cert *hcert,
511                             LogotypeData *data)
512 {
513         int i, num;
514
515         if (data->image == NULL)
516                 return;
517
518         num = sk_LogotypeImage_num(data->image);
519         for (i = 0; i < num; i++) {
520                 LogotypeImage *image;
521                 LogotypeDetails *details;
522                 int j, hash_num, uri_num;
523                 HashAlgAndValue *found_hash = NULL;
524
525                 image = sk_LogotypeImage_value(data->image, i);
526                 if (image == NULL)
527                         continue;
528
529                 details = image->imageDetails;
530                 if (details == NULL)
531                         continue;
532
533                 hash_num = sk_HashAlgAndValue_num(details->logotypeHash);
534                 for (j = 0; j < hash_num; j++) {
535                         HashAlgAndValue *hash;
536                         char txt[100];
537                         int res;
538                         hash = sk_HashAlgAndValue_value(details->logotypeHash,
539                                                         j);
540                         if (hash == NULL)
541                                 continue;
542                         res = OBJ_obj2txt(txt, sizeof(txt),
543                                           hash->hashAlg->algorithm, 1);
544                         if (res < 0 || res >= (int) sizeof(txt))
545                                 continue;
546                         if (os_strcmp(txt, "2.16.840.1.101.3.4.2.1") == 0) {
547                                 found_hash = hash;
548                                 break;
549                         }
550                 }
551
552                 if (!found_hash) {
553                         wpa_printf(MSG_DEBUG, "OpenSSL: No SHA256 hash found for the logo");
554                         continue;
555                 }
556
557                 uri_num = sk_ASN1_IA5STRING_num(details->logotypeURI);
558                 for (j = 0; j < uri_num; j++) {
559                         ASN1_IA5STRING *uri;
560                         uri = sk_ASN1_IA5STRING_value(details->logotypeURI, j);
561                         add_logo(ctx, hcert, found_hash, uri);
562                 }
563         }
564 }
565
566
567 static void add_logo_indirect(struct http_ctx *ctx, struct http_cert *hcert,
568                               LogotypeReference *ref)
569 {
570         int j, hash_num, uri_num;
571
572         hash_num = sk_HashAlgAndValue_num(ref->refStructHash);
573         uri_num = sk_ASN1_IA5STRING_num(ref->refStructURI);
574         if (hash_num != uri_num) {
575                 wpa_printf(MSG_INFO, "Unexpected LogotypeReference array size difference %d != %d",
576                            hash_num, uri_num);
577                 return;
578         }
579
580         for (j = 0; j < hash_num; j++) {
581                 HashAlgAndValue *hash;
582                 ASN1_IA5STRING *uri;
583                 hash = sk_HashAlgAndValue_value(ref->refStructHash, j);
584                 uri = sk_ASN1_IA5STRING_value(ref->refStructURI, j);
585                 add_logo(ctx, hcert, hash, uri);
586         }
587 }
588
589
590 static void i2r_HashAlgAndValue(HashAlgAndValue *hash, BIO *out, int indent)
591 {
592         int i;
593         const unsigned char *data;
594
595         BIO_printf(out, "%*shashAlg: ", indent, "");
596         i2a_ASN1_OBJECT(out, hash->hashAlg->algorithm);
597         BIO_printf(out, "\n");
598
599         BIO_printf(out, "%*shashValue: ", indent, "");
600         data = hash->hashValue->data;
601         for (i = 0; i < hash->hashValue->length; i++)
602                 BIO_printf(out, "%s%02x", i > 0 ? ":" : "", data[i]);
603         BIO_printf(out, "\n");
604 }
605
606 static void i2r_LogotypeDetails(LogotypeDetails *details, BIO *out, int indent)
607 {
608         int i, num;
609
610         BIO_printf(out, "%*sLogotypeDetails\n", indent, "");
611         if (details->mediaType) {
612                 BIO_printf(out, "%*smediaType: ", indent, "");
613                 ASN1_STRING_print(out, details->mediaType);
614                 BIO_printf(out, "\n");
615         }
616
617         num = details->logotypeHash ?
618                 sk_HashAlgAndValue_num(details->logotypeHash) : 0;
619         for (i = 0; i < num; i++) {
620                 HashAlgAndValue *hash;
621                 hash = sk_HashAlgAndValue_value(details->logotypeHash, i);
622                 i2r_HashAlgAndValue(hash, out, indent);
623         }
624
625         num = details->logotypeURI ?
626                 sk_ASN1_IA5STRING_num(details->logotypeURI) : 0;
627         for (i = 0; i < num; i++) {
628                 ASN1_IA5STRING *uri;
629                 uri = sk_ASN1_IA5STRING_value(details->logotypeURI, i);
630                 BIO_printf(out, "%*slogotypeURI: ", indent, "");
631                 ASN1_STRING_print(out, uri);
632                 BIO_printf(out, "\n");
633         }
634 }
635
636 static void i2r_LogotypeImageInfo(LogotypeImageInfo *info, BIO *out, int indent)
637 {
638         long val;
639
640         BIO_printf(out, "%*sLogotypeImageInfo\n", indent, "");
641         if (info->type) {
642                 val = ASN1_INTEGER_get(info->type);
643                 BIO_printf(out, "%*stype: %ld\n", indent, "", val);
644         } else {
645                 BIO_printf(out, "%*stype: default (1)\n", indent, "");
646         }
647         val = ASN1_INTEGER_get(info->fileSize);
648         BIO_printf(out, "%*sfileSize: %ld\n", indent, "", val);
649         val = ASN1_INTEGER_get(info->xSize);
650         BIO_printf(out, "%*sxSize: %ld\n", indent, "", val);
651         val = ASN1_INTEGER_get(info->ySize);
652         BIO_printf(out, "%*sySize: %ld\n", indent, "", val);
653         if (info->resolution) {
654                 BIO_printf(out, "%*sresolution [%d]\n", indent, "",
655                            info->resolution->type);
656                 switch (info->resolution->type) {
657                 case 0:
658                         val = ASN1_INTEGER_get(info->resolution->d.numBits);
659                         BIO_printf(out, "%*snumBits: %ld\n", indent, "", val);
660                         break;
661                 case 1:
662                         val = ASN1_INTEGER_get(info->resolution->d.tableSize);
663                         BIO_printf(out, "%*stableSize: %ld\n", indent, "", val);
664                         break;
665                 }
666         }
667         if (info->language) {
668                 BIO_printf(out, "%*slanguage: ", indent, "");
669                 ASN1_STRING_print(out, info->language);
670                 BIO_printf(out, "\n");
671         }
672 }
673
674 static void i2r_LogotypeImage(LogotypeImage *image, BIO *out, int indent)
675 {
676         BIO_printf(out, "%*sLogotypeImage\n", indent, "");
677         if (image->imageDetails) {
678                 i2r_LogotypeDetails(image->imageDetails, out, indent + 4);
679         }
680         if (image->imageInfo) {
681                 i2r_LogotypeImageInfo(image->imageInfo, out, indent + 4);
682         }
683 }
684
685 static void i2r_LogotypeData(LogotypeData *data, const char *title, BIO *out,
686                              int indent)
687 {
688         int i, num;
689
690         BIO_printf(out, "%*s%s - LogotypeData\n", indent, "", title);
691
692         num = data->image ? sk_LogotypeImage_num(data->image) : 0;
693         for (i = 0; i < num; i++) {
694                 LogotypeImage *image = sk_LogotypeImage_value(data->image, i);
695                 i2r_LogotypeImage(image, out, indent + 4);
696         }
697
698         num = data->audio ? sk_LogotypeAudio_num(data->audio) : 0;
699         for (i = 0; i < num; i++) {
700                 BIO_printf(out, "%*saudio: TODO\n", indent, "");
701         }
702 }
703
704 static void i2r_LogotypeReference(LogotypeReference *ref, const char *title,
705                                   BIO *out, int indent)
706 {
707         int i, hash_num, uri_num;
708
709         BIO_printf(out, "%*s%s - LogotypeReference\n", indent, "", title);
710
711         hash_num = ref->refStructHash ?
712                 sk_HashAlgAndValue_num(ref->refStructHash) : 0;
713         uri_num = ref->refStructURI ?
714                 sk_ASN1_IA5STRING_num(ref->refStructURI) : 0;
715         if (hash_num != uri_num) {
716                 BIO_printf(out, "%*sUnexpected LogotypeReference array size difference %d != %d\n",
717                            indent, "", hash_num, uri_num);
718                 return;
719         }
720
721         for (i = 0; i < hash_num; i++) {
722                 HashAlgAndValue *hash;
723                 ASN1_IA5STRING *uri;
724
725                 hash = sk_HashAlgAndValue_value(ref->refStructHash, i);
726                 i2r_HashAlgAndValue(hash, out, indent);
727
728                 uri = sk_ASN1_IA5STRING_value(ref->refStructURI, i);
729                 BIO_printf(out, "%*srefStructURI: ", indent, "");
730                 ASN1_STRING_print(out, uri);
731                 BIO_printf(out, "\n");
732         }
733 }
734
735 static void i2r_LogotypeInfo(LogotypeInfo *info, const char *title, BIO *out,
736                              int indent)
737 {
738         switch (info->type) {
739         case 0:
740                 i2r_LogotypeData(info->d.direct, title, out, indent);
741                 break;
742         case 1:
743                 i2r_LogotypeReference(info->d.indirect, title, out, indent);
744                 break;
745         }
746 }
747
748 static void debug_print_logotypeext(LogotypeExtn *logo)
749 {
750         BIO *out;
751         int i, num;
752         int indent = 0;
753
754         out = BIO_new_fp(stdout, BIO_NOCLOSE);
755         if (out == NULL)
756                 return;
757
758         if (logo->communityLogos) {
759                 num = sk_LogotypeInfo_num(logo->communityLogos);
760                 for (i = 0; i < num; i++) {
761                         LogotypeInfo *info;
762                         info = sk_LogotypeInfo_value(logo->communityLogos, i);
763                         i2r_LogotypeInfo(info, "communityLogo", out, indent);
764                 }
765         }
766
767         if (logo->issuerLogo) {
768                 i2r_LogotypeInfo(logo->issuerLogo, "issuerLogo", out, indent );
769         }
770
771         if (logo->subjectLogo) {
772                 i2r_LogotypeInfo(logo->subjectLogo, "subjectLogo", out, indent);
773         }
774
775         if (logo->otherLogos) {
776                 BIO_printf(out, "%*sotherLogos - TODO\n", indent, "");
777         }
778
779         BIO_free(out);
780 }
781
782
783 static void add_logotype_ext(struct http_ctx *ctx, struct http_cert *hcert,
784                              X509 *cert)
785 {
786         ASN1_OBJECT *obj;
787         int pos;
788         X509_EXTENSION *ext;
789         ASN1_OCTET_STRING *os;
790         LogotypeExtn *logo;
791         const unsigned char *data;
792         int i, num;
793
794         obj = OBJ_txt2obj("1.3.6.1.5.5.7.1.12", 0);
795         if (obj == NULL)
796                 return;
797
798         pos = X509_get_ext_by_OBJ(cert, obj, -1);
799         if (pos < 0) {
800                 wpa_printf(MSG_INFO, "No logotype extension included");
801                 return;
802         }
803
804         wpa_printf(MSG_INFO, "Parsing logotype extension");
805         ext = X509_get_ext(cert, pos);
806         if (!ext) {
807                 wpa_printf(MSG_INFO, "Could not get logotype extension");
808                 return;
809         }
810
811         os = X509_EXTENSION_get_data(ext);
812         if (os == NULL) {
813                 wpa_printf(MSG_INFO, "Could not get logotype extension data");
814                 return;
815         }
816
817         wpa_hexdump(MSG_DEBUG, "logotypeExtn",
818                     ASN1_STRING_data(os), ASN1_STRING_length(os));
819
820         data = ASN1_STRING_data(os);
821         logo = d2i_LogotypeExtn(NULL, &data, ASN1_STRING_length(os));
822         if (logo == NULL) {
823                 wpa_printf(MSG_INFO, "Failed to parse logotypeExtn");
824                 return;
825         }
826
827         if (wpa_debug_level < MSG_INFO)
828                 debug_print_logotypeext(logo);
829
830         if (!logo->communityLogos) {
831                 wpa_printf(MSG_INFO, "No communityLogos included");
832                 LogotypeExtn_free(logo);
833                 return;
834         }
835
836         num = sk_LogotypeInfo_num(logo->communityLogos);
837         for (i = 0; i < num; i++) {
838                 LogotypeInfo *info;
839                 info = sk_LogotypeInfo_value(logo->communityLogos, i);
840                 switch (info->type) {
841                 case 0:
842                         add_logo_direct(ctx, hcert, info->d.direct);
843                         break;
844                 case 1:
845                         add_logo_indirect(ctx, hcert, info->d.indirect);
846                         break;
847                 }
848         }
849
850         LogotypeExtn_free(logo);
851 }
852
853
854 static void parse_cert(struct http_ctx *ctx, struct http_cert *hcert,
855                        X509 *cert, GENERAL_NAMES **names)
856 {
857         os_memset(hcert, 0, sizeof(*hcert));
858
859         *names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
860         if (*names) {
861                 add_alt_names(ctx, hcert, *names);
862                 sk_GENERAL_NAME_pop_free(*names, GENERAL_NAME_free);
863         }
864
865         add_logotype_ext(ctx, hcert, cert);
866 }
867
868
869 static void parse_cert_free(struct http_cert *hcert, GENERAL_NAMES *names)
870 {
871         unsigned int i;
872
873         for (i = 0; i < hcert->num_dnsname; i++)
874                 OPENSSL_free(hcert->dnsname[i]);
875         os_free(hcert->dnsname);
876
877         for (i = 0; i < hcert->num_othername; i++)
878                 os_free(hcert->othername[i].oid);
879         os_free(hcert->othername);
880
881         for (i = 0; i < hcert->num_logo; i++) {
882                 os_free(hcert->logo[i].alg_oid);
883                 os_free(hcert->logo[i].hash);
884                 os_free(hcert->logo[i].uri);
885         }
886         os_free(hcert->logo);
887
888         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
889 }
890
891
892 static int validate_server_cert(struct http_ctx *ctx, X509 *cert)
893 {
894         GENERAL_NAMES *names;
895         struct http_cert hcert;
896         int ret;
897
898         if (ctx->cert_cb == NULL) {
899                 wpa_printf(MSG_DEBUG, "%s: no cert_cb configured", __func__);
900                 return 0;
901         }
902
903         if (0) {
904                 BIO *out;
905                 out = BIO_new_fp(stdout, BIO_NOCLOSE);
906                 X509_print_ex(out, cert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
907                 BIO_free(out);
908         }
909
910         parse_cert(ctx, &hcert, cert, &names);
911         ret = ctx->cert_cb(ctx->cert_cb_ctx, &hcert);
912         parse_cert_free(&hcert, names);
913
914         return ret;
915 }
916
917
918 void http_parse_x509_certificate(struct http_ctx *ctx, const char *fname)
919 {
920         BIO *in, *out;
921         X509 *cert;
922         GENERAL_NAMES *names;
923         struct http_cert hcert;
924         unsigned int i;
925
926         in = BIO_new_file(fname, "r");
927         if (in == NULL) {
928                 wpa_printf(MSG_ERROR, "Could not read '%s'", fname);
929                 return;
930         }
931
932         cert = d2i_X509_bio(in, NULL);
933         BIO_free(in);
934
935         if (cert == NULL) {
936                 wpa_printf(MSG_ERROR, "Could not parse certificate");
937                 return;
938         }
939
940         out = BIO_new_fp(stdout, BIO_NOCLOSE);
941         if (out) {
942                 X509_print_ex(out, cert, XN_FLAG_COMPAT,
943                               X509_FLAG_COMPAT);
944                 BIO_free(out);
945         }
946
947         wpa_printf(MSG_INFO, "Additional parsing information:");
948         parse_cert(ctx, &hcert, cert, &names);
949         for (i = 0; i < hcert.num_othername; i++) {
950                 if (os_strcmp(hcert.othername[i].oid,
951                               "1.3.6.1.4.1.40808.1.1.1") == 0) {
952                         char *name = os_zalloc(hcert.othername[i].len + 1);
953                         if (name) {
954                                 os_memcpy(name, hcert.othername[i].data,
955                                           hcert.othername[i].len);
956                                 wpa_printf(MSG_INFO,
957                                            "id-wfa-hotspot-friendlyName: %s",
958                                            name);
959                                 os_free(name);
960                         }
961                         wpa_hexdump_ascii(MSG_INFO,
962                                           "id-wfa-hotspot-friendlyName",
963                                           hcert.othername[i].data,
964                                           hcert.othername[i].len);
965                 } else {
966                         wpa_printf(MSG_INFO, "subjAltName[othername]: oid=%s",
967                                    hcert.othername[i].oid);
968                         wpa_hexdump_ascii(MSG_INFO, "unknown othername",
969                                           hcert.othername[i].data,
970                                           hcert.othername[i].len);
971                 }
972         }
973         parse_cert_free(&hcert, names);
974
975         X509_free(cert);
976 }
977
978
979 static int curl_cb_ssl_verify(int preverify_ok, X509_STORE_CTX *x509_ctx)
980 {
981         struct http_ctx *ctx;
982         X509 *cert;
983         int err, depth;
984         char buf[256];
985         X509_NAME *name;
986         const char *err_str;
987         SSL *ssl;
988         SSL_CTX *ssl_ctx;
989
990         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
991                                          SSL_get_ex_data_X509_STORE_CTX_idx());
992         ssl_ctx = ssl->ctx;
993         ctx = SSL_CTX_get_app_data(ssl_ctx);
994
995         wpa_printf(MSG_DEBUG, "curl_cb_ssl_verify, preverify_ok: %d",
996                    preverify_ok);
997
998         err = X509_STORE_CTX_get_error(x509_ctx);
999         err_str = X509_verify_cert_error_string(err);
1000         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1001         cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1002         if (!cert) {
1003                 wpa_printf(MSG_INFO, "No server certificate available");
1004                 ctx->last_err = "No server certificate available";
1005                 return 0;
1006         }
1007
1008         if (depth == 0)
1009                 ctx->peer_cert = cert;
1010         else if (depth == 1)
1011                 ctx->peer_issuer = cert;
1012         else if (depth == 2)
1013                 ctx->peer_issuer_issuer = cert;
1014
1015         name = X509_get_subject_name(cert);
1016         X509_NAME_oneline(name, buf, sizeof(buf));
1017         wpa_printf(MSG_INFO, "Server certificate chain - depth=%d err=%d (%s) subject=%s",
1018                    depth, err, err_str, buf);
1019         debug_dump_cert("Server certificate chain - certificate", cert);
1020
1021         if (depth == 0 && preverify_ok && validate_server_cert(ctx, cert) < 0)
1022                 return 0;
1023
1024 #ifdef OPENSSL_IS_BORINGSSL
1025         if (depth == 0 && ctx->ocsp != NO_OCSP && preverify_ok) {
1026                 enum ocsp_result res;
1027
1028                 res = check_ocsp_resp(ssl_ctx, ssl, cert, ctx->peer_issuer,
1029                                       ctx->peer_issuer_issuer);
1030                 if (res == OCSP_REVOKED) {
1031                         preverify_ok = 0;
1032                         wpa_printf(MSG_INFO, "OCSP: certificate revoked");
1033                         if (err == X509_V_OK)
1034                                 X509_STORE_CTX_set_error(
1035                                         x509_ctx, X509_V_ERR_CERT_REVOKED);
1036                 } else if (res != OCSP_GOOD && (ctx->ocsp == MANDATORY_OCSP)) {
1037                         preverify_ok = 0;
1038                         wpa_printf(MSG_INFO,
1039                                    "OCSP: bad certificate status response");
1040                 }
1041         }
1042 #endif /* OPENSSL_IS_BORINGSSL */
1043
1044         if (!preverify_ok)
1045                 ctx->last_err = "TLS validation failed";
1046
1047         return preverify_ok;
1048 }
1049
1050
1051 #ifdef HAVE_OCSP
1052
1053 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
1054 {
1055         BIO *out;
1056         size_t rlen;
1057         char *txt;
1058         int res;
1059
1060         out = BIO_new(BIO_s_mem());
1061         if (!out)
1062                 return;
1063
1064         OCSP_RESPONSE_print(out, rsp, 0);
1065         rlen = BIO_ctrl_pending(out);
1066         txt = os_malloc(rlen + 1);
1067         if (!txt) {
1068                 BIO_free(out);
1069                 return;
1070         }
1071
1072         res = BIO_read(out, txt, rlen);
1073         if (res > 0) {
1074                 txt[res] = '\0';
1075                 wpa_printf(MSG_MSGDUMP, "OpenSSL: OCSP Response\n%s", txt);
1076         }
1077         os_free(txt);
1078         BIO_free(out);
1079 }
1080
1081
1082 static void tls_show_errors(const char *func, const char *txt)
1083 {
1084         unsigned long err;
1085
1086         wpa_printf(MSG_DEBUG, "OpenSSL: %s - %s %s",
1087                    func, txt, ERR_error_string(ERR_get_error(), NULL));
1088
1089         while ((err = ERR_get_error())) {
1090                 wpa_printf(MSG_DEBUG, "OpenSSL: pending error: %s",
1091                            ERR_error_string(err, NULL));
1092         }
1093 }
1094
1095
1096 static int ocsp_resp_cb(SSL *s, void *arg)
1097 {
1098         struct http_ctx *ctx = arg;
1099         const unsigned char *p;
1100         int len, status, reason;
1101         OCSP_RESPONSE *rsp;
1102         OCSP_BASICRESP *basic;
1103         OCSP_CERTID *id;
1104         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
1105         X509_STORE *store;
1106         STACK_OF(X509) *certs = NULL;
1107
1108         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1109         if (!p) {
1110                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
1111                 if (ctx->ocsp == MANDATORY_OCSP)
1112                         ctx->last_err = "No OCSP response received";
1113                 return (ctx->ocsp == MANDATORY_OCSP) ? 0 : 1;
1114         }
1115
1116         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
1117
1118         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1119         if (!rsp) {
1120                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
1121                 ctx->last_err = "Failed to parse OCSP response";
1122                 return 0;
1123         }
1124
1125         ocsp_debug_print_resp(rsp);
1126
1127         status = OCSP_response_status(rsp);
1128         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1129                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
1130                            status, OCSP_response_status_str(status));
1131                 ctx->last_err = "OCSP responder error";
1132                 return 0;
1133         }
1134
1135         basic = OCSP_response_get1_basic(rsp);
1136         if (!basic) {
1137                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
1138                 ctx->last_err = "Could not find BasicOCSPResponse";
1139                 return 0;
1140         }
1141
1142         store = SSL_CTX_get_cert_store(s->ctx);
1143         if (ctx->peer_issuer) {
1144                 wpa_printf(MSG_DEBUG, "OpenSSL: Add issuer");
1145                 debug_dump_cert("OpenSSL: Issuer certificate",
1146                                 ctx->peer_issuer);
1147
1148                 if (X509_STORE_add_cert(store, ctx->peer_issuer) != 1) {
1149                         tls_show_errors(__func__,
1150                                         "OpenSSL: Could not add issuer to certificate store");
1151                 }
1152                 certs = sk_X509_new_null();
1153                 if (certs) {
1154                         X509 *cert;
1155                         cert = X509_dup(ctx->peer_issuer);
1156                         if (cert && !sk_X509_push(certs, cert)) {
1157                                 tls_show_errors(
1158                                         __func__,
1159                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
1160                                 X509_free(cert);
1161                                 sk_X509_free(certs);
1162                                 certs = NULL;
1163                         }
1164                         if (certs && ctx->peer_issuer_issuer) {
1165                                 cert = X509_dup(ctx->peer_issuer_issuer);
1166                                 if (cert && !sk_X509_push(certs, cert)) {
1167                                         tls_show_errors(
1168                                                 __func__,
1169                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
1170                                         X509_free(cert);
1171                                 }
1172                         }
1173                 }
1174         }
1175
1176         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
1177         sk_X509_pop_free(certs, X509_free);
1178         if (status <= 0) {
1179                 tls_show_errors(__func__,
1180                                 "OpenSSL: OCSP response failed verification");
1181                 OCSP_BASICRESP_free(basic);
1182                 OCSP_RESPONSE_free(rsp);
1183                 ctx->last_err = "OCSP response failed verification";
1184                 return 0;
1185         }
1186
1187         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
1188
1189         if (!ctx->peer_cert) {
1190                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
1191                 OCSP_BASICRESP_free(basic);
1192                 OCSP_RESPONSE_free(rsp);
1193                 ctx->last_err = "Peer certificate not available for OCSP status check";
1194                 return 0;
1195         }
1196
1197         if (!ctx->peer_issuer) {
1198                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
1199                 OCSP_BASICRESP_free(basic);
1200                 OCSP_RESPONSE_free(rsp);
1201                 ctx->last_err = "Peer issuer certificate not available for OCSP status check";
1202                 return 0;
1203         }
1204
1205         id = OCSP_cert_to_id(NULL, ctx->peer_cert, ctx->peer_issuer);
1206         if (!id) {
1207                 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
1208                 OCSP_BASICRESP_free(basic);
1209                 OCSP_RESPONSE_free(rsp);
1210                 ctx->last_err = "Could not create OCSP certificate identifier";
1211                 return 0;
1212         }
1213
1214         if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
1215                                    &this_update, &next_update)) {
1216                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
1217                            (ctx->ocsp == MANDATORY_OCSP) ? "" :
1218                            " (OCSP not required)");
1219                 OCSP_BASICRESP_free(basic);
1220                 OCSP_RESPONSE_free(rsp);
1221                 if (ctx->ocsp == MANDATORY_OCSP)
1222
1223                         ctx->last_err = "Could not find current server certificate from OCSP response";
1224                 return (ctx->ocsp == MANDATORY_OCSP) ? 0 : 1;
1225         }
1226
1227         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
1228                 tls_show_errors(__func__, "OpenSSL: OCSP status times invalid");
1229                 OCSP_BASICRESP_free(basic);
1230                 OCSP_RESPONSE_free(rsp);
1231                 ctx->last_err = "OCSP status times invalid";
1232                 return 0;
1233         }
1234
1235         OCSP_BASICRESP_free(basic);
1236         OCSP_RESPONSE_free(rsp);
1237
1238         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
1239                    OCSP_cert_status_str(status));
1240
1241         if (status == V_OCSP_CERTSTATUS_GOOD)
1242                 return 1;
1243         if (status == V_OCSP_CERTSTATUS_REVOKED) {
1244                 ctx->last_err = "Server certificate has been revoked";
1245                 return 0;
1246         }
1247         if (ctx->ocsp == MANDATORY_OCSP) {
1248                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
1249                 ctx->last_err = "OCSP status unknown";
1250                 return 0;
1251         }
1252         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
1253         return 1;
1254 }
1255
1256
1257 static SSL_METHOD patch_ssl_method;
1258 static const SSL_METHOD *real_ssl_method;
1259
1260 static int curl_patch_ssl_new(SSL *s)
1261 {
1262         SSL_CTX *ssl = s->ctx;
1263         int ret;
1264
1265         ssl->method = real_ssl_method;
1266         s->method = real_ssl_method;
1267
1268         ret = s->method->ssl_new(s);
1269         SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp);
1270
1271         return ret;
1272 }
1273
1274 #endif /* HAVE_OCSP */
1275
1276
1277 static CURLcode curl_cb_ssl(CURL *curl, void *sslctx, void *parm)
1278 {
1279         struct http_ctx *ctx = parm;
1280         SSL_CTX *ssl = sslctx;
1281
1282         wpa_printf(MSG_DEBUG, "curl_cb_ssl");
1283         SSL_CTX_set_app_data(ssl, ctx);
1284         SSL_CTX_set_verify(ssl, SSL_VERIFY_PEER, curl_cb_ssl_verify);
1285
1286 #ifdef HAVE_OCSP
1287         if (ctx->ocsp != NO_OCSP) {
1288                 SSL_CTX_set_tlsext_status_cb(ssl, ocsp_resp_cb);
1289                 SSL_CTX_set_tlsext_status_arg(ssl, ctx);
1290
1291                 /*
1292                  * Use a temporary SSL_METHOD to get a callback on SSL_new()
1293                  * from libcurl since there is no proper callback registration
1294                  * available for this.
1295                  */
1296                 os_memset(&patch_ssl_method, 0, sizeof(patch_ssl_method));
1297                 patch_ssl_method.ssl_new = curl_patch_ssl_new;
1298                 real_ssl_method = ssl->method;
1299                 ssl->method = &patch_ssl_method;
1300         }
1301 #endif /* HAVE_OCSP */
1302
1303         return CURLE_OK;
1304 }
1305
1306 #endif /* EAP_TLS_OPENSSL */
1307
1308
1309 static CURL * setup_curl_post(struct http_ctx *ctx, const char *address,
1310                               const char *ca_fname, const char *username,
1311                               const char *password, const char *client_cert,
1312                               const char *client_key)
1313 {
1314         CURL *curl;
1315 #ifdef EAP_TLS_OPENSSL
1316         const char *extra = " tls=openssl";
1317 #else /* EAP_TLS_OPENSSL */
1318         const char *extra = "";
1319 #endif /* EAP_TLS_OPENSSL */
1320
1321         wpa_printf(MSG_DEBUG, "Start HTTP client: address=%s ca_fname=%s "
1322                    "username=%s%s", address, ca_fname, username, extra);
1323
1324         curl = curl_easy_init();
1325         if (curl == NULL)
1326                 return NULL;
1327
1328         curl_easy_setopt(curl, CURLOPT_URL, address);
1329         curl_easy_setopt(curl, CURLOPT_POST, 1L);
1330         if (ca_fname) {
1331                 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_fname);
1332                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
1333 #ifdef EAP_TLS_OPENSSL
1334                 curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, curl_cb_ssl);
1335                 curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, ctx);
1336 #ifdef OPENSSL_IS_BORINGSSL
1337                 /* For now, using the CURLOPT_SSL_VERIFYSTATUS option only
1338                  * with BoringSSL since the OpenSSL specific callback hack to
1339                  * enable OCSP is not available with BoringSSL. The OCSP
1340                  * implementation within libcurl is not sufficient for the
1341                  * Hotspot 2.0 OSU needs, so cannot use this with OpenSSL.
1342                  */
1343                 if (ctx->ocsp != NO_OCSP)
1344                         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1L);
1345 #endif /* OPENSSL_IS_BORINGSSL */
1346 #endif /* EAP_TLS_OPENSSL */
1347         } else {
1348                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1349         }
1350         if (client_cert && client_key) {
1351                 curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert);
1352                 curl_easy_setopt(curl, CURLOPT_SSLKEY, client_key);
1353         }
1354         /* TODO: use curl_easy_getinfo() with CURLINFO_CERTINFO to fetch
1355          * information about the server certificate */
1356         curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L);
1357         curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_cb_debug);
1358         curl_easy_setopt(curl, CURLOPT_DEBUGDATA, ctx);
1359         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_cb_write);
1360         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ctx);
1361         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
1362         if (username) {
1363                 curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
1364                 curl_easy_setopt(curl, CURLOPT_USERNAME, username);
1365                 curl_easy_setopt(curl, CURLOPT_PASSWORD, password);
1366         }
1367
1368         return curl;
1369 }
1370
1371
1372 static int post_init_client(struct http_ctx *ctx, const char *address,
1373                             const char *ca_fname, const char *username,
1374                             const char *password, const char *client_cert,
1375                             const char *client_key)
1376 {
1377         char *pos;
1378         int count;
1379
1380         clone_str(&ctx->svc_address, address);
1381         clone_str(&ctx->svc_ca_fname, ca_fname);
1382         clone_str(&ctx->svc_username, username);
1383         clone_str(&ctx->svc_password, password);
1384         clone_str(&ctx->svc_client_cert, client_cert);
1385         clone_str(&ctx->svc_client_key, client_key);
1386
1387         /*
1388          * Workaround for Apache "Hostname 'FOO' provided via SNI and hostname
1389          * 'foo' provided via HTTP are different.
1390          */
1391         for (count = 0, pos = ctx->svc_address; count < 3 && pos && *pos;
1392              pos++) {
1393                 if (*pos == '/')
1394                         count++;
1395                 *pos = tolower(*pos);
1396         }
1397
1398         ctx->curl = setup_curl_post(ctx, ctx->svc_address, ca_fname, username,
1399                                     password, client_cert, client_key);
1400         if (ctx->curl == NULL)
1401                 return -1;
1402
1403         return 0;
1404 }
1405
1406
1407 int soap_init_client(struct http_ctx *ctx, const char *address,
1408                      const char *ca_fname, const char *username,
1409                      const char *password, const char *client_cert,
1410                      const char *client_key)
1411 {
1412         if (post_init_client(ctx, address, ca_fname, username, password,
1413                              client_cert, client_key) < 0)
1414                 return -1;
1415
1416         ctx->curl_hdr = curl_slist_append(ctx->curl_hdr,
1417                                           "Content-Type: application/soap+xml");
1418         ctx->curl_hdr = curl_slist_append(ctx->curl_hdr, "SOAPAction: ");
1419         ctx->curl_hdr = curl_slist_append(ctx->curl_hdr, "Expect:");
1420         curl_easy_setopt(ctx->curl, CURLOPT_HTTPHEADER, ctx->curl_hdr);
1421
1422         return 0;
1423 }
1424
1425
1426 int soap_reinit_client(struct http_ctx *ctx)
1427 {
1428         char *address = NULL;
1429         char *ca_fname = NULL;
1430         char *username = NULL;
1431         char *password = NULL;
1432         char *client_cert = NULL;
1433         char *client_key = NULL;
1434         int ret;
1435
1436         clear_curl(ctx);
1437
1438         clone_str(&address, ctx->svc_address);
1439         clone_str(&ca_fname, ctx->svc_ca_fname);
1440         clone_str(&username, ctx->svc_username);
1441         clone_str(&password, ctx->svc_password);
1442         clone_str(&client_cert, ctx->svc_client_cert);
1443         clone_str(&client_key, ctx->svc_client_key);
1444
1445         ret = soap_init_client(ctx, address, ca_fname, username, password,
1446                                client_cert, client_key);
1447         os_free(address);
1448         os_free(ca_fname);
1449         str_clear_free(username);
1450         str_clear_free(password);
1451         os_free(client_cert);
1452         os_free(client_key);
1453         return ret;
1454 }
1455
1456
1457 static void free_curl_buf(struct http_ctx *ctx)
1458 {
1459         os_free(ctx->curl_buf);
1460         ctx->curl_buf = NULL;
1461         ctx->curl_buf_len = 0;
1462 }
1463
1464
1465 xml_node_t * soap_send_receive(struct http_ctx *ctx, xml_node_t *node)
1466 {
1467         char *str;
1468         xml_node_t *envelope, *ret, *resp, *n;
1469         CURLcode res;
1470         long http = 0;
1471
1472         ctx->last_err = NULL;
1473
1474         wpa_printf(MSG_DEBUG, "SOAP: Sending message");
1475         envelope = soap_build_envelope(ctx->xml, node);
1476         str = xml_node_to_str(ctx->xml, envelope);
1477         xml_node_free(ctx->xml, envelope);
1478         wpa_printf(MSG_MSGDUMP, "SOAP[%s]", str);
1479
1480         curl_easy_setopt(ctx->curl, CURLOPT_POSTFIELDS, str);
1481         free_curl_buf(ctx);
1482
1483         res = curl_easy_perform(ctx->curl);
1484         if (res != CURLE_OK) {
1485                 if (!ctx->last_err)
1486                         ctx->last_err = curl_easy_strerror(res);
1487                 wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
1488                            ctx->last_err);
1489                 os_free(str);
1490                 free_curl_buf(ctx);
1491                 return NULL;
1492         }
1493         os_free(str);
1494
1495         curl_easy_getinfo(ctx->curl, CURLINFO_RESPONSE_CODE, &http);
1496         wpa_printf(MSG_DEBUG, "SOAP: Server response code %ld", http);
1497         if (http != 200) {
1498                 ctx->last_err = "HTTP download failed";
1499                 wpa_printf(MSG_INFO, "HTTP download failed - code %ld", http);
1500                 free_curl_buf(ctx);
1501                 return NULL;
1502         }
1503
1504         if (ctx->curl_buf == NULL)
1505                 return NULL;
1506
1507         wpa_printf(MSG_MSGDUMP, "Server response:\n%s", ctx->curl_buf);
1508         resp = xml_node_from_buf(ctx->xml, ctx->curl_buf);
1509         free_curl_buf(ctx);
1510         if (resp == NULL) {
1511                 wpa_printf(MSG_INFO, "Could not parse SOAP response");
1512                 ctx->last_err = "Could not parse SOAP response";
1513                 return NULL;
1514         }
1515
1516         ret = soap_get_body(ctx->xml, resp);
1517         if (ret == NULL) {
1518                 wpa_printf(MSG_INFO, "Could not get SOAP body");
1519                 ctx->last_err = "Could not get SOAP body";
1520                 return NULL;
1521         }
1522
1523         wpa_printf(MSG_DEBUG, "SOAP body localname: '%s'",
1524                    xml_node_get_localname(ctx->xml, ret));
1525         n = xml_node_copy(ctx->xml, ret);
1526         xml_node_free(ctx->xml, resp);
1527
1528         return n;
1529 }
1530
1531
1532 struct http_ctx * http_init_ctx(void *upper_ctx, struct xml_node_ctx *xml_ctx)
1533 {
1534         struct http_ctx *ctx;
1535
1536         ctx = os_zalloc(sizeof(*ctx));
1537         if (ctx == NULL)
1538                 return NULL;
1539         ctx->ctx = upper_ctx;
1540         ctx->xml = xml_ctx;
1541         ctx->ocsp = OPTIONAL_OCSP;
1542
1543         curl_global_init(CURL_GLOBAL_ALL);
1544
1545         return ctx;
1546 }
1547
1548
1549 void http_ocsp_set(struct http_ctx *ctx, int val)
1550 {
1551         if (val == 0)
1552                 ctx->ocsp = NO_OCSP;
1553         else if (val == 1)
1554                 ctx->ocsp = OPTIONAL_OCSP;
1555         if (val == 2)
1556                 ctx->ocsp = MANDATORY_OCSP;
1557 }
1558
1559
1560 void http_deinit_ctx(struct http_ctx *ctx)
1561 {
1562         clear_curl(ctx);
1563         os_free(ctx->curl_buf);
1564         curl_global_cleanup();
1565
1566         os_free(ctx->svc_address);
1567         os_free(ctx->svc_ca_fname);
1568         str_clear_free(ctx->svc_username);
1569         str_clear_free(ctx->svc_password);
1570         os_free(ctx->svc_client_cert);
1571         os_free(ctx->svc_client_key);
1572
1573         os_free(ctx);
1574 }
1575
1576
1577 int http_download_file(struct http_ctx *ctx, const char *url,
1578                        const char *fname, const char *ca_fname)
1579 {
1580         CURL *curl;
1581         FILE *f;
1582         CURLcode res;
1583         long http = 0;
1584
1585         ctx->last_err = NULL;
1586
1587         wpa_printf(MSG_DEBUG, "curl: Download file from %s to %s (ca=%s)",
1588                    url, fname, ca_fname);
1589         curl = curl_easy_init();
1590         if (curl == NULL)
1591                 return -1;
1592
1593         f = fopen(fname, "wb");
1594         if (f == NULL) {
1595                 curl_easy_cleanup(curl);
1596                 return -1;
1597         }
1598
1599         curl_easy_setopt(curl, CURLOPT_URL, url);
1600         if (ca_fname) {
1601                 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_fname);
1602                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
1603                 curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L);
1604         } else {
1605                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1606         }
1607         curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_cb_debug);
1608         curl_easy_setopt(curl, CURLOPT_DEBUGDATA, ctx);
1609         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
1610         curl_easy_setopt(curl, CURLOPT_WRITEDATA, f);
1611         curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
1612
1613         res = curl_easy_perform(curl);
1614         if (res != CURLE_OK) {
1615                 if (!ctx->last_err)
1616                         ctx->last_err = curl_easy_strerror(res);
1617                 wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
1618                            ctx->last_err);
1619                 curl_easy_cleanup(curl);
1620                 fclose(f);
1621                 return -1;
1622         }
1623
1624         curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http);
1625         wpa_printf(MSG_DEBUG, "curl: Server response code %ld", http);
1626         if (http != 200) {
1627                 ctx->last_err = "HTTP download failed";
1628                 wpa_printf(MSG_INFO, "HTTP download failed - code %ld", http);
1629                 curl_easy_cleanup(curl);
1630                 fclose(f);
1631                 return -1;
1632         }
1633
1634         curl_easy_cleanup(curl);
1635         fclose(f);
1636
1637         return 0;
1638 }
1639
1640
1641 char * http_post(struct http_ctx *ctx, const char *url, const char *data,
1642                  const char *content_type, const char *ext_hdr,
1643                  const char *ca_fname,
1644                  const char *username, const char *password,
1645                  const char *client_cert, const char *client_key,
1646                  size_t *resp_len)
1647 {
1648         long http = 0;
1649         CURLcode res;
1650         char *ret;
1651         CURL *curl;
1652         struct curl_slist *curl_hdr = NULL;
1653
1654         ctx->last_err = NULL;
1655         wpa_printf(MSG_DEBUG, "curl: HTTP POST to %s", url);
1656         curl = setup_curl_post(ctx, url, ca_fname, username, password,
1657                                client_cert, client_key);
1658         if (curl == NULL)
1659                 return NULL;
1660
1661         if (content_type) {
1662                 char ct[200];
1663                 snprintf(ct, sizeof(ct), "Content-Type: %s", content_type);
1664                 curl_hdr = curl_slist_append(curl_hdr, ct);
1665         }
1666         if (ext_hdr)
1667                 curl_hdr = curl_slist_append(curl_hdr, ext_hdr);
1668         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_hdr);
1669
1670         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
1671         free_curl_buf(ctx);
1672
1673         res = curl_easy_perform(curl);
1674         if (res != CURLE_OK) {
1675                 if (!ctx->last_err)
1676                         ctx->last_err = curl_easy_strerror(res);
1677                 wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
1678                            ctx->last_err);
1679                 free_curl_buf(ctx);
1680                 return NULL;
1681         }
1682
1683         curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http);
1684         wpa_printf(MSG_DEBUG, "curl: Server response code %ld", http);
1685         if (http != 200) {
1686                 ctx->last_err = "HTTP POST failed";
1687                 wpa_printf(MSG_INFO, "HTTP POST failed - code %ld", http);
1688                 free_curl_buf(ctx);
1689                 return NULL;
1690         }
1691
1692         if (ctx->curl_buf == NULL)
1693                 return NULL;
1694
1695         ret = ctx->curl_buf;
1696         if (resp_len)
1697                 *resp_len = ctx->curl_buf_len;
1698         ctx->curl_buf = NULL;
1699         ctx->curl_buf_len = 0;
1700
1701         wpa_printf(MSG_MSGDUMP, "Server response:\n%s", ret);
1702
1703         return ret;
1704 }
1705
1706
1707 void http_set_cert_cb(struct http_ctx *ctx,
1708                       int (*cb)(void *ctx, struct http_cert *cert),
1709                       void *cb_ctx)
1710 {
1711         ctx->cert_cb = cb;
1712         ctx->cert_cb_ctx = cb_ctx;
1713 }
1714
1715
1716 const char * http_get_err(struct http_ctx *ctx)
1717 {
1718         return ctx->last_err;
1719 }