forked from apache/serf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssl_buckets.c
More file actions
3448 lines (2838 loc) · 101 KB
/
ssl_buckets.c
File metadata and controls
3448 lines (2838 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* ----
*
* Originally developed by Aaron Bannert and Justin Erenkrantz, eBuilt.
*/
#define APR_WANT_MEMFUNC
#include <apr_want.h>
#include <apr_pools.h>
#include <apr_network_io.h>
#include <apr_portable.h>
#include <apr_strings.h>
#include <apr_base64.h>
#include <apr_version.h>
#include <apr_atomic.h>
#include "serf.h"
#include "serf_private.h"
#include "serf_bucket_util.h"
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#ifndef OPENSSL_NO_OCSP /* requires openssl 0.9.7 or later */
#include <openssl/ocsp.h>
#endif
#if defined(SERF_HAVE_OSSL_STORE_OPEN_EX)
#include <openssl/store.h>
#include <openssl/evp.h>
#include <openssl/safestack.h>
#include <openssl/ui.h>
#ifndef sk_EVP_PKEY_new_null
DEFINE_STACK_OF(EVP_PKEY)
#endif
#endif
#ifndef APR_ARRAY_PUSH
#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary)))
#endif
#ifdef SERF_NO_SSL_X509_STORE_WRAPPERS
#define X509_STORE_get0_param(store) ((store)->param)
#endif
#ifdef SERF_NO_SSL_X509_GET0_NOTBEFORE
#define X509_get0_notBefore(cert) (X509_get_notBefore(cert))
#endif
#ifdef SERF_NO_SSL_X509_GET0_NOTAFTER
#define X509_get0_notAfter(cert) (X509_get_notAfter(cert))
#endif
#ifdef SERF_NO_SSL_X509_GET0_CHAIN
#define X509_STORE_CTX_get0_chain(store) (X509_STORE_CTX_get_chain(store))
#endif
#ifdef SERF_NO_SSL_ASN1_STRING_GET0_DATA
#define ASN1_STRING_get0_data(asn1string) (ASN1_STRING_data(asn1string))
#endif
/*
* Here's an overview of the SSL bucket's relationship to OpenSSL and serf.
*
* HTTP request: SSLENCRYPT(REQUEST)
* [context.c reads from SSLENCRYPT and writes out to the socket]
* HTTP response: RESPONSE(SSLDECRYPT(SOCKET))
* [handler function reads from RESPONSE which in turn reads from SSLDECRYPT]
*
* HTTP request read call path:
*
* write_to_connection
* |- serf_bucket_read on SSLENCRYPT
* |- serf_ssl_read
* |- serf_databuf_read
* |- common_databuf_prep
* |- ssl_encrypt
* |- 1. Try to read pending encrypted data; If available, return.
* |- 2. Try to read from ctx->stream [REQUEST bucket]
* |- 3. Call SSL_write with read data
* |- ...
* |- bio_bucket_read can be called
* |- read data from ctx->decrypt.stream
* |- bio_bucket_write with encrypted data
* |- store in sink
* |- 4. If successful, read pending encrypted data and return.
* |- 5. If fails, place read data back in ctx->stream
*
* HTTP response read call path:
*
* read_from_connection
* |- acceptor
* |- handler
* |- ...
* |- serf_bucket_read(SSLDECRYPT)
* |- serf_ssl_read
* |- serf_databuf_read
* |- ssl_decrypt
* |- Call SSL_read()
* |- ...
* |- bio_bucket_read
* |- read data from ctx->decrypt.stream
* |- bio_bucket_write can be called
* |- store in sink
* |- If data read, return it.
* |- If an error, set the STATUS value and return.
*
*/
static int ssl_x509_ex_data_idx = -1;
typedef struct bucket_list {
serf_bucket_t *bucket;
struct bucket_list *next;
} bucket_list_t;
typedef struct serf_ssl_stream_t {
/* Helper to read data. Wraps stream. */
serf_databuf_t databuf;
/* Our source for more data. */
serf_bucket_t *stream;
/* The next set of buckets */
bucket_list_t *stream_next;
} serf_ssl_stream_t;
struct serf_ssl_context_t {
/* How many open buckets refer to this context. */
int refcount;
/* The pool that this context uses. */
apr_pool_t *pool;
/* The allocator associated with the above pool. */
serf_bucket_alloc_t *allocator;
/* Internal OpenSSL parameters */
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
BIO_METHOD *biom;
serf_ssl_stream_t encrypt;
serf_ssl_stream_t decrypt;
/* The status of the last thing we read or wrote. */
apr_status_t crypt_status;
/* Encrypted data waiting to be written. */
serf_bucket_t *encrypt_pending;
/* Should we read before we can write again? */
int want_read;
int handshake_done;
/* OpenSSL 1.1.1e introduced BIO_FLAGS_IN_EOF, but we implement
our own hit eof to support versions < 1.1.1e. */
int hit_eof;
/* Client cert callbacks */
serf_ssl_need_client_cert_t cert_callback;
void *cert_userdata;
apr_pool_t *cert_cache_pool;
const char *cert_file_success;
/* Client cert PW callbacks */
serf_ssl_need_cert_password_t cert_pw_callback;
void *cert_pw_userdata;
apr_pool_t *cert_pw_cache_pool;
const char *cert_pw_success;
/* Cert uri callbacks */
serf_ssl_need_cert_uri_t cert_uri_callback;
void *cert_uri_userdata;
apr_pool_t *cert_uri_cache_pool;
const char *cert_uri_success;
/* Server cert callbacks */
serf_ssl_need_server_cert_t server_cert_callback;
serf_ssl_server_cert_chain_cb_t server_cert_chain_callback;
void *server_cert_userdata;
const char *cert_path;
const char *cert_uri;
const char *cert_pw;
X509 *cached_cert;
EVP_PKEY *cached_cert_pw;
/* Error callback */
serf_ssl_error_cb_t error_callback;
void *error_baton;
apr_status_t pending_err;
/* Status of a fatal error, returned on subsequent encrypt or decrypt
requests. */
apr_status_t fatal_err;
/* Flag is set to 1 when a renegotiation is in progress. */
int renegotiation;
int handshake_finished; /* True after SSL internal connection is through
the handshake */
const char *selected_protocol; /* Cached protocol value once available */
/* Protocol callback */
serf_ssl_protocol_result_cb_t protocol_callback;
void *protocol_userdata;
serf_config_t *config;
};
typedef struct ssl_context_t {
/* The bucket-independent ssl context that this bucket is associated with */
serf_ssl_context_t *ssl_ctx;
/* Pointer to the 'right' databuf. */
serf_databuf_t *databuf;
/* Pointer to our stream, so we can find it later. */
serf_bucket_t **our_stream;
} ssl_context_t;
struct serf_ssl_certificate_t {
X509 *ssl_cert;
int depth;
};
static void disable_compression(serf_ssl_context_t *ssl_ctx);
static char *
pstrdup_escape_nul_bytes(const char *buf, int len, apr_pool_t *pool);
static const char *ssl_get_selected_protocol(serf_ssl_context_t *context);
#ifdef SERF_LOGGING_ENABLED
/* Log all ssl alerts that we receive from the server. */
static void
apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
serf_ssl_context_t *ctx;
int w;
int in_write = (where & SSL_CB_WRITE);
const char *read_write_str = (in_write ? "write" : "read");
int ssl_error = SSL_get_error(s, ret);
ctx = SSL_get_app_data(s);
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT)
str = "SSL_connect";
else if (w & SSL_ST_ACCEPT)
str = "SSL_accept";
else
str = "undefined";
if (where & SSL_CB_LOOP) {
serf__log(LOGLVL_DEBUG, LOGCOMP_SSL, __FILE__, ctx->config,
"%s:%s\n", str, SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT) {
serf__log(LOGLVL_WARNING, LOGCOMP_SSL, __FILE__, ctx->config,
"SSL %s alert: %s: %s\n",
read_write_str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT) {
int level;
const char *how = (ret == 0) ? "failed" : "error";
if (ret < 0 && ssl_error != SSL_ERROR_WANT_READ)
level = LOGLVL_ERROR;
else if (ret == 0)
level = LOGLVL_WARNING;
else if (ssl_error != SSL_ERROR_WANT_READ)
level = LOGLVL_INFO;
else
level = LOGLVL_DEBUG;
if (ret > 0) {
/* ret > 0: Just a state change; not an error */
serf__log(level, LOGCOMP_SSL, __FILE__, ctx->config,
"%s: %s (%d)\n",
str, SSL_state_string_long(s),
ctx->crypt_status);
}
else if (ssl_error == 0) {
serf__log(level, LOGCOMP_SSL, __FILE__, ctx->config,
"%s:%s %s in %s, status=%d\n",
str, read_write_str, how, SSL_state_string_long(s),
ctx->crypt_status);
}
else if (ssl_error != SSL_ERROR_SYSCALL) {
serf__log(level, LOGCOMP_SSL, __FILE__, ctx->config,
"%s:%s %s in %s: ssl_error=%d, status=%d\n",
str, read_write_str, how, SSL_state_string_long(s),
ssl_error, ctx->crypt_status);
}
else {
serf__log(level, LOGCOMP_SSL, __FILE__, ctx->config,
"%s:%s %s in %s: status=%d\n",
str, read_write_str, how, SSL_state_string_long(s),
ctx->crypt_status);
}
}
}
#endif
/* Listens for the SSL renegotiate ciphers alert and report it back to the
serf context. */
static void
detect_renegotiate(const SSL *s, int where, int ret)
{
/* This callback overrides the SSL state logging callback, so call it here
(if logging is compiled in). */
#ifdef SERF_LOGGING_ENABLED
apps_ssl_info_callback(s, where, ret);
#endif
/* The server asked to renegotiate the SSL session. */
#ifdef SERF_HAVE_OSSL_HANDSHAKE_STATE
if (SSL_get_state(s) == TLS_ST_SW_HELLO_REQ) {
#elif defined(SSL_ST_RENEGOTIATE)
if (SSL_state(s) == SSL_ST_RENEGOTIATE) {
#else
#error "neither TLS_ST_SW_HELLO_REQ nor SSL_ST_RENEGOTIATE is available"
{
#endif
serf_ssl_context_t *ssl_ctx = SSL_get_app_data(s);
ssl_ctx->renegotiation = 1;
ssl_ctx->fatal_err = SERF_ERROR_SSL_NEGOTIATE_IN_PROGRESS;
}
}
static void log_ssl_error(serf_ssl_context_t *ctx)
{
unsigned long err;
while ((err = ERR_get_error())) {
if (err && ctx->error_callback) {
char ebuf[256];
ERR_error_string_n(err, ebuf, sizeof(ebuf));
ctx->error_callback(ctx->error_baton, ctx->fatal_err, ebuf);
}
}
}
static void bio_set_data(BIO *bio, void *data)
{
#ifndef SERF_NO_SSL_BIO_WRAPPERS
BIO_set_data(bio, data);
#else
bio->ptr = data;
#endif
}
static void *bio_get_data(BIO *bio)
{
#ifndef SERF_NO_SSL_BIO_WRAPPERS
return BIO_get_data(bio);
#else
return bio->ptr;
#endif
}
/* Returns the amount read. */
static int bio_bucket_read(BIO *bio, char *in, int inlen)
{
serf_ssl_context_t *ctx = bio_get_data(bio);
const char *data;
apr_status_t status;
apr_size_t len;
serf__log(LOGLVL_DEBUG, LOGCOMP_SSL, __FILE__, ctx->config,
"bio_bucket_read called for %d bytes\n", inlen);
BIO_clear_retry_flags(bio); /* Clear retry hints */
/* The server initiated a renegotiation and we were instructed to report
that as an error asap. */
if (ctx->renegotiation) {
ctx->crypt_status = SERF_ERROR_SSL_NEGOTIATE_IN_PROGRESS;
return -1;
}
status = serf_bucket_read(ctx->decrypt.stream, inlen, &data, &len);
ctx->crypt_status = status;
ctx->want_read = FALSE;
if (SERF_BUCKET_READ_ERROR(status)) {
return -1; /* Raises: SSL_ERROR_SYSCALL; caller reads crypt_status */
}
if (APR_STATUS_IS_EOF(status)) {
ctx->hit_eof = TRUE;
} else if (status) {
BIO_set_retry_read(bio); /* Signal SSL: Retry later */
}
if (! len) {
return -1; /* Raises: SSL_ERROR_SYSCALL; caller reads crypt_status */
}
serf__log(LOGLVL_DEBUG, LOGCOMP_SSL, __FILE__, ctx->config,
"bio_bucket_read received %"APR_SIZE_T_FMT" bytes (%d)\n", len, status);
memcpy(in, data, len);
return len;
}
/* Returns the amount written. */
static int bio_bucket_write(BIO *bio, const char *in, int inl)
{
serf_ssl_context_t *ctx = bio_get_data(bio);
serf_bucket_t *tmp;
serf__log(LOGLVL_DEBUG, LOGCOMP_SSL, __FILE__, ctx->config,
"bio_bucket_write called for %d bytes\n", inl);
BIO_clear_retry_flags(bio); /* Clear retry hints */
/* The server initiated a renegotiation and we were instructed to report
that as an error asap. */
if (ctx->renegotiation) {
ctx->crypt_status = SERF_ERROR_SSL_NEGOTIATE_IN_PROGRESS;
return -1;
}
ctx->crypt_status = APR_SUCCESS;
tmp = serf_bucket_simple_copy_create(in, inl,
ctx->encrypt_pending->allocator);
serf_bucket_aggregate_append(ctx->encrypt_pending, tmp);
return inl;
}
/* Returns the amount read. */
static int bio_file_read(BIO *bio, char *in, int inlen)
{
apr_file_t *file = bio_get_data(bio);
apr_status_t status;
apr_size_t len;
len = inlen;
status = apr_file_read(file, in, &len);
if (!SERF_BUCKET_READ_ERROR(status)) {
/* Oh suck. */
if (APR_STATUS_IS_EOF(status)) {
return -1;
} else {
return len;
}
}
return -1;
}
/* Returns the amount written. */
static int bio_file_write(BIO *bio, const char *in, int inl)
{
apr_file_t *file = bio_get_data(bio);
apr_size_t nbytes;
BIO_clear_retry_flags(bio);
nbytes = inl;
apr_file_write(file, in, &nbytes);
return nbytes;
}
static int bio_file_gets(BIO *bio, char *in, int inlen)
{
apr_file_t *file = bio_get_data(bio);
apr_status_t status;
status = apr_file_gets(in, inlen, file);
if (! status) {
return (int)strlen(in);
} else if (APR_STATUS_IS_EOF(status)) {
return 0;
} else {
return -1; /* Signal generic error */
}
}
static int bio_bucket_create(BIO *bio)
{
#ifndef SERF_NO_SSL_BIO_WRAPPERS
BIO_set_shutdown(bio, 1);
BIO_set_init(bio, 1);
BIO_set_data(bio, NULL);
#else
bio->shutdown = 1;
bio->init = 1;
bio->num = -1;
bio->ptr = NULL;
#endif
return 1;
}
static int bio_bucket_destroy(BIO *bio)
{
/* Did we already free this? */
if (bio == NULL) {
return 0;
}
return 1;
}
static long bio_bucket_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
serf_ssl_context_t *ctx = bio_get_data(bio);
switch (cmd) {
case BIO_CTRL_FLUSH:
/* At this point we can't force a flush. */
return 1;
case BIO_CTRL_PUSH:
case BIO_CTRL_POP:
return 0;
case BIO_CTRL_EOF:
return ctx->hit_eof;
default:
/* abort(); */
return 0;
}
}
static long bio_file_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
apr_file_t *file = bio_get_data(bio);
switch (cmd) {
case BIO_CTRL_FLUSH:
/* At this point we can't force a flush. */
return 1;
case BIO_CTRL_PUSH:
case BIO_CTRL_POP:
return 0;
case BIO_CTRL_EOF:
if (apr_file_eof(file) == APR_EOF)
return 1;
else
return 0;
default:
/* abort(); */
return 0;
}
}
#ifdef SERF_NO_SSL_BIO_WRAPPERS
static BIO_METHOD bio_bucket_method = {
BIO_TYPE_MEM,
"Serf SSL encryption and decryption buckets",
bio_bucket_write,
bio_bucket_read,
NULL, /* Is this called? */
NULL, /* Is this called? */
bio_bucket_ctrl,
bio_bucket_create,
bio_bucket_destroy,
#ifdef OPENSSL_VERSION_NUMBER
NULL /* sslc does not have the callback_ctrl field */
#endif
};
static BIO_METHOD bio_file_method = {
BIO_TYPE_FILE,
"Wrapper around APR file structures",
bio_file_write,
bio_file_read,
NULL, /* Is this called? */
bio_file_gets, /* Is this called? */
bio_file_ctrl,
bio_bucket_create,
bio_bucket_destroy,
#ifdef OPENSSL_VERSION_NUMBER
NULL /* sslc does not have the callback_ctrl field */
#endif
};
#endif
static BIO_METHOD *bio_meth_bucket_new(void)
{
BIO_METHOD *biom = NULL;
#ifndef SERF_NO_SSL_BIO_WRAPPERS
biom = BIO_meth_new(BIO_TYPE_MEM,
"Serf SSL encryption and decryption buckets");
if (biom) {
BIO_meth_set_write(biom, bio_bucket_write);
BIO_meth_set_read(biom, bio_bucket_read);
BIO_meth_set_ctrl(biom, bio_bucket_ctrl);
BIO_meth_set_create(biom, bio_bucket_create);
BIO_meth_set_destroy(biom, bio_bucket_destroy);
}
#else
biom = &bio_bucket_method;
#endif
return biom;
}
static BIO_METHOD *bio_meth_file_new(void)
{
BIO_METHOD *biom = NULL;
#ifndef SERF_NO_SSL_BIO_WRAPPERS
biom = BIO_meth_new(BIO_TYPE_FILE, "Wrapper around APR file structures");
if (biom) {
BIO_meth_set_write(biom, bio_file_write);
BIO_meth_set_read(biom, bio_file_read);
BIO_meth_set_gets(biom, bio_file_gets);
BIO_meth_set_ctrl(biom, bio_file_ctrl);
BIO_meth_set_create(biom, bio_bucket_create);
BIO_meth_set_destroy(biom, bio_bucket_destroy);
}
#else
biom = &bio_file_method;
#endif
return biom;
}
static void bio_meth_free(BIO_METHOD *biom)
{
#ifndef SERF_NO_SSL_BIO_WRAPPERS
BIO_meth_free(biom);
#endif
}
#ifndef OPENSSL_NO_OCSP
static int ocsp_response_status(int failures, OCSP_RESPONSE *response)
{
long resp_status = OCSP_response_status(response);
switch (resp_status) {
case OCSP_RESPONSE_STATUS_SUCCESSFUL:
break;
case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
case OCSP_RESPONSE_STATUS_INTERNALERROR:
case OCSP_RESPONSE_STATUS_SIGREQUIRED:
case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
failures |= SERF_SSL_OCSP_RESPONDER_ERROR;
break;
case OCSP_RESPONSE_STATUS_TRYLATER:
failures |= SERF_SSL_OCSP_RESPONDER_TRYLATER;
break;
default:
failures |= SERF_SSL_OCSP_RESPONDER_UNKNOWN_FAILURE;
break;
}
return failures;
}
# ifndef OPENSSL_NO_TLSEXT
/* Callback called when the server response has some OCSP info.
Returns 1 if the application accepts the OCSP response as successful,
0 in case of error.
*/
static int ocsp_callback(SSL *ssl, void *baton)
{
serf_ssl_context_t *ctx = (serf_ssl_context_t*)baton;
OCSP_RESPONSE *response;
const unsigned char *resp_der;
int len;
int failures = 0;
int cert_valid = 0;
serf__log(LOGLVL_DEBUG, LOGCOMP_SSL, __FILE__, ctx->config,
"OCSP callback called.\n");
len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp_der);
if (!resp_der) {
/* TODO: hard fail vs soft fail */
/* No response sent */
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
response = d2i_OCSP_RESPONSE(NULL, &resp_der, len);
if (!response) {
/* Error parsing OCSP response - tell the app? */
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
/* Did the server get a valid response from the OCSP responder */
failures = ocsp_response_status(failures, response);
/* TODO: check certificate status */
OCSP_RESPONSE_free(response);
if (ctx->server_cert_callback && failures) {
apr_status_t status;
/* TODO: try to find which certificate this is about. */
/* Callback for further verification. */
status = ctx->server_cert_callback(ctx->server_cert_userdata,
failures, NULL);
if (status == APR_SUCCESS)
cert_valid = 1;
else {
/* The application is not happy with the OCSP response status. */
cert_valid = 0;
/* Pass the error back to the caller through the context-run. */
ctx->pending_err = status;
}
}
/* If OCSP stapling was enabled, an error was reported but no callback set,
fail with an error. */
if (!cert_valid &&
!ctx->server_cert_chain_callback &&
!ctx->server_cert_callback)
{
ctx->pending_err = SERF_ERROR_SSL_CERT_FAILED;
}
return cert_valid;
}
# endif /* OPENSSL_NO_TLSEXT */
#endif /* OPENSSL_NO_OCSP */
typedef enum san_copy_t {
EscapeNulAndCopy = 0,
ErrorOnNul = 1
} san_copy_t;
/* get_subject_alt_names can run in two modes:
COPY_ACTION = ErrorOnNul: return an error status if the san's (if any) contain
\0 chars. In this mode, SAN_ARR and POOL aren't used and can be NULL.
COPY_ACTION = EscapeNulAndCopy: copy the san's to the SAN_ARR array. Any \0
chars are escaped as '\00', the memory is allocated in pool POOL.
*/
static apr_status_t
get_subject_alt_names(apr_array_header_t **san_arr, X509 *ssl_cert,
san_copy_t copy_action, apr_pool_t *pool)
{
STACK_OF(GENERAL_NAME) *names;
/* assert: copy_action == ErrorOnNul || (san_arr && pool) */
if (san_arr) {
*san_arr = NULL;
}
/* Get subjectAltNames */
names = X509_get_ext_d2i(ssl_cert, NID_subject_alt_name, NULL, NULL);
if (names) {
int names_count = sk_GENERAL_NAME_num(names);
int name_idx;
if (san_arr)
*san_arr = apr_array_make(pool, names_count, sizeof(char*));
for (name_idx = 0; name_idx < names_count; name_idx++) {
char *p = NULL;
GENERAL_NAME *nm = sk_GENERAL_NAME_value(names, name_idx);
switch (nm->type) {
case GEN_DNS:
if (copy_action == ErrorOnNul &&
strlen((const char *)nm->d.ia5->data) != nm->d.ia5->length)
return SERF_ERROR_SSL_CERT_FAILED;
if (san_arr && *san_arr)
p = pstrdup_escape_nul_bytes((const char *)nm->d.ia5->data,
nm->d.ia5->length,
pool);
break;
default:
/* Don't know what to do - skip. */
break;
}
if (p) {
APR_ARRAY_PUSH(*san_arr, char*) = p;
}
}
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
}
return APR_SUCCESS;
}
static apr_status_t
get_ocsp_responders(apr_array_header_t **ocsp_arr, X509 *ssl_cert,
apr_pool_t *pool)
{
/* assert: (ocsp_arr && pool) */
if (ocsp_arr) {
STACK_OF(OPENSSL_STRING) *uris;
*ocsp_arr = NULL;
uris = X509_get1_ocsp(ssl_cert);
if (uris) {
int uris_count = sk_OPENSSL_STRING_num(uris);
int uri_idx;
*ocsp_arr = apr_array_make(pool, uris_count, sizeof(char*));
for (uri_idx = 0; uri_idx < uris_count; ++uri_idx) {
OPENSSL_STRING uri = sk_OPENSSL_STRING_value(uris, uri_idx);
if (uri) {
char *p = apr_pstrdup(pool, uri);
if (p) {
APR_ARRAY_PUSH(*ocsp_arr, char*) = p;
}
}
}
}
X509_email_free(uris);
}
return APR_SUCCESS;
}
static apr_status_t validate_cert_hostname(X509 *server_cert, apr_pool_t *pool)
{
char buf[1024];
int length;
apr_status_t ret;
ret = get_subject_alt_names(NULL, server_cert, ErrorOnNul, NULL);
if (ret) {
return ret;
} else {
/* Fail if the subject's CN field contains \0 characters. */
X509_NAME *subject = X509_get_subject_name(server_cert);
if (!subject)
return SERF_ERROR_SSL_CERT_FAILED;
length = X509_NAME_get_text_by_NID(subject, NID_commonName, buf, 1024);
if (length != -1)
if (strlen(buf) != length)
return SERF_ERROR_SSL_CERT_FAILED;
}
return APR_SUCCESS;
}
static int
validate_server_certificate(int cert_valid, X509_STORE_CTX *store_ctx)
{
SSL *ssl;
serf_ssl_context_t *ctx;
X509 *server_cert;
int depth;
int failures = 0;
apr_status_t status;
ssl = X509_STORE_CTX_get_ex_data(store_ctx,
SSL_get_ex_data_X509_STORE_CTX_idx());
ctx = SSL_get_app_data(ssl);
server_cert = X509_STORE_CTX_get_current_cert(store_ctx);
depth = X509_STORE_CTX_get_error_depth(store_ctx);
/* If the certification was found invalid, get the error and convert it to
something our caller will understand. */
if (! cert_valid) {
int err = X509_STORE_CTX_get_error(store_ctx);
switch(err) {
case X509_V_ERR_CERT_NOT_YET_VALID:
failures |= SERF_SSL_CERT_NOTYETVALID;
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
failures |= SERF_SSL_CERT_EXPIRED;
break;
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
failures |= SERF_SSL_CERT_SELF_SIGNED;
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case X509_V_ERR_CERT_UNTRUSTED:
case X509_V_ERR_INVALID_CA:
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
failures |= SERF_SSL_CERT_UNKNOWNCA;
break;
case X509_V_ERR_CERT_REVOKED:
failures |= SERF_SSL_CERT_REVOKED;
break;
case X509_V_ERR_UNABLE_TO_GET_CRL:
failures |= SERF_SSL_CERT_UNABLE_TO_GET_CRL;
break;
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
failures |= SERF_SSL_SIGNATURE_FAILURE;
break;
default:
serf__log(LOGLVL_WARNING, LOGCOMP_SSL, __FILE__,
ctx->config,
"validate_server_certificate, unknown cert "
"failure %d at depth %d.\n", err, depth);
failures |= SERF_SSL_CERT_UNKNOWN_FAILURE;
break;
}
}
/* Validate hostname */
status = validate_cert_hostname(server_cert, ctx->pool);
if (status)
failures |= SERF_SSL_CERT_INVALID_HOST;
/* Check certificate expiry dates. */
if (X509_cmp_current_time(X509_get0_notBefore(server_cert)) >= 0) {
failures |= SERF_SSL_CERT_NOTYETVALID;
}
else if (X509_cmp_current_time(X509_get0_notAfter(server_cert)) <= 0) {
failures |= SERF_SSL_CERT_EXPIRED;
}
if (ctx->server_cert_callback &&
(depth == 0 || failures)) {
serf_ssl_certificate_t *cert;
apr_pool_t *subpool;
apr_pool_create(&subpool, ctx->pool);
cert = apr_palloc(subpool, sizeof(serf_ssl_certificate_t));
cert->ssl_cert = server_cert;
cert->depth = depth;
/* Callback for further verification. */
status = ctx->server_cert_callback(ctx->server_cert_userdata,
failures, cert);
if (status == APR_SUCCESS)
cert_valid = 1;
else {
/* Even if openssl found the certificate valid, the application
told us to reject it. */
cert_valid = 0;
/* Pass the error back to the caller through the context-run. */
ctx->pending_err = status;
}
apr_pool_destroy(subpool);
}
if (ctx->server_cert_chain_callback
&& (depth == 0 || failures)) {
STACK_OF(X509) *chain;
const serf_ssl_certificate_t **certs;
int certs_len;
apr_pool_t *subpool;
apr_pool_create(&subpool, ctx->pool);
/* Borrow the chain to pass to the callback. */
chain = X509_STORE_CTX_get0_chain(store_ctx);
/* If the chain can't be retrieved, just pass the current
certificate. */
/* ### can this actually happen with _get_chain() ? */
if (!chain) {
serf_ssl_certificate_t *cert = apr_palloc(subpool, sizeof(*cert));
cert->ssl_cert = server_cert;
cert->depth = depth;
/* Room for the server_cert and a trailing NULL. */
certs = apr_palloc(subpool, sizeof(*certs) * 2);
certs[0] = cert;