/
gnutls_ocsp.c
1338 lines (1180 loc) · 46.8 KB
/
gnutls_ocsp.c
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
/*
* Copyright 2016-2020 Fiona Klute
*
* Licensed 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.
*/
#include "gnutls_ocsp.h"
#include "mod_gnutls.h"
#include "gnutls_cache.h"
#include "gnutls_config.h"
#include "gnutls_util.h"
#include "gnutls_watchdog.h"
#include <apr_escape.h>
#include <apr_lib.h>
#include <apr_time.h>
#include <gnutls/crypto.h>
#include <gnutls/ocsp.h>
#include <mod_watchdog.h>
#include <string.h>
#include <time.h>
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(gnutls);
#endif
/** maximum supported OCSP response size, 8K should be plenty */
#define OCSP_RESP_SIZE_MAX (8 * 1024)
#define OCSP_REQ_TYPE "application/ocsp-request"
#define OCSP_RESP_TYPE "application/ocsp-response"
/** Dummy data for failure cache entries (one byte). */
#define OCSP_FAILURE_CACHE_DATA 0x0f
/** Macro to check if an OCSP reponse pointer contains a cached
* failure */
#define IS_FAILURE_RESPONSE(resp) \
(((resp)->size == sizeof(unsigned char)) && \
(*((unsigned char *) (resp)->data) == OCSP_FAILURE_CACHE_DATA))
#define _log_one_ocsp_fail(str, srv) \
ap_log_error(APLOG_MARK, APLOG_INFO, APR_EGENERAL, (srv), \
"Reason for failed OCSP response verification: %s", (str))
/**
* Log all matching reasons for verification failure
*/
static void _log_verify_fail_reason(const unsigned int verify, server_rec *s)
{
if (verify & GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND)
_log_one_ocsp_fail("Signer cert not found", s);
if (verify & GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR)
_log_one_ocsp_fail("Signer cert keyusage error", s);
if (verify & GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER)
_log_one_ocsp_fail("Signer cert is not trusted", s);
if (verify & GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM)
_log_one_ocsp_fail("Insecure algorithm", s);
if (verify & GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE)
_log_one_ocsp_fail("Signature failure", s);
if (verify & GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED)
_log_one_ocsp_fail("Signer cert not yet activated", s);
if (verify & GNUTLS_OCSP_VERIFY_CERT_EXPIRED)
_log_one_ocsp_fail("Signer cert expired", s);
}
const char *mgs_ocsp_stapling_enable(cmd_parms *parms,
void *dummy __attribute__((unused)),
const int arg)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(parms->server->module_config, &gnutls_module);
if (arg)
sc->ocsp_staple = GNUTLS_ENABLED_TRUE;
else
sc->ocsp_staple = GNUTLS_ENABLED_FALSE;
return NULL;
}
const char *mgs_set_ocsp_auto_refresh(cmd_parms *parms,
void *dummy __attribute__((unused)),
const int arg)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(parms->server->module_config, &gnutls_module);
if (arg)
sc->ocsp_auto_refresh = GNUTLS_ENABLED_TRUE;
else
sc->ocsp_auto_refresh = GNUTLS_ENABLED_FALSE;
return NULL;
}
const char *mgs_set_ocsp_check_nonce(cmd_parms *parms,
void *dummy __attribute__((unused)),
const int arg)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(parms->server->module_config, &gnutls_module);
if (arg)
sc->ocsp_check_nonce = GNUTLS_ENABLED_TRUE;
else
sc->ocsp_check_nonce = GNUTLS_ENABLED_FALSE;
return NULL;
}
const char *mgs_store_ocsp_response_path(cmd_parms *parms,
void *dummy __attribute__((unused)),
int argc, char *const *argv)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(parms->server->module_config, &gnutls_module);
sc->ocsp_response_file_num = argc;
sc->ocsp_response_file = apr_palloc(parms->pool, sizeof(char *) * argc);
for (int i = 0; i < argc; i++)
{
if (strcmp(argv[i], "") == 0)
sc->ocsp_response_file[i] = NULL;
else
sc->ocsp_response_file[i] =
ap_server_root_relative(parms->pool, argv[i]);
}
return NULL;
}
/**
* Create an OCSP request for the certificate of the given server. The
* DER encoded request is stored in 'req' (must be released with
* gnutls_free() when no longer needed), its nonce in 'nonce' (same,
* if not NULL).
*
* @param s server reference for logging
*
* @return GNUTLS_E_SUCCESS, or a GnuTLS error code.
*/
static int mgs_create_ocsp_request(server_rec *s,
mgs_ocsp_data_t req_data,
gnutls_datum_t *req,
gnutls_datum_t *nonce)
__attribute__((nonnull(1, 3)));
static int mgs_create_ocsp_request(server_rec *s,
mgs_ocsp_data_t req_data,
gnutls_datum_t *req,
gnutls_datum_t *nonce)
{
gnutls_ocsp_req_t r;
int ret = gnutls_ocsp_req_init(&r);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not initialize OCSP request structure: %s (%d)",
gnutls_strerror(ret), ret);
return ret;
}
/* issuer is set to a reference, so musn't be cleaned up */
gnutls_x509_crt_t issuer;
ret = gnutls_x509_trust_list_get_issuer(*req_data->trust, req_data->cert,
&issuer, 0);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not get issuer from trust list: %s (%d)",
gnutls_strerror(ret), ret);
gnutls_ocsp_req_deinit(r);
return ret;
}
/* Use SHA1 for issuer name hash and issuer key hash, for
* compliance with "lightweight" OCSP profile specified in RFC
* 5019. */
ret = gnutls_ocsp_req_add_cert(r, GNUTLS_DIG_SHA1,
issuer, req_data->cert);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Adding certificate to OCSP request for %s:%d "
"failed: %s (%d)",
s->server_hostname, s->addrs->host_port,
gnutls_strerror(ret), ret);
gnutls_ocsp_req_deinit(r);
return ret;
}
if (nonce != NULL)
{
ret = gnutls_ocsp_req_randomize_nonce(r);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP nonce creation failed: %s (%d)",
gnutls_strerror(ret), ret);
gnutls_ocsp_req_deinit(r);
return ret;
}
ret = gnutls_ocsp_req_get_nonce(r, NULL, nonce);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not get nonce: %s (%d)",
gnutls_strerror(ret), ret);
gnutls_free(nonce->data);
nonce->data = NULL;
nonce->size = 0;
gnutls_ocsp_req_deinit(r);
return ret;
}
}
ret = gnutls_ocsp_req_export(r, req);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP request export failed: %s (%d)",
gnutls_strerror(ret), ret);
gnutls_free(req->data);
req->data = NULL;
req->size = 0;
if (nonce != NULL)
{
gnutls_free(nonce->data);
nonce->data = NULL;
nonce->size = 0;
}
gnutls_ocsp_req_deinit(r);
return ret;
}
gnutls_ocsp_req_deinit(r);
return ret;
}
/**
* Check if the provided OCSP response is usable for stapling in
* connections to this server. Returns GNUTLS_E_SUCCESS if yes.
*
* Supports only one certificate status per response.
*
* If expiry is not NULL, it will be set to the nextUpdate time
* contained in the response, or zero if the response does not contain
* a nextUpdate field.
*
* If nonce is not NULL, the response must contain a matching nonce.
*/
int check_ocsp_response(server_rec *s, mgs_ocsp_data_t req_data,
const gnutls_datum_t *ocsp_response,
apr_time_t* expiry, const gnutls_datum_t *nonce)
__attribute__((nonnull(1, 3)));
int check_ocsp_response(server_rec *s, mgs_ocsp_data_t req_data,
const gnutls_datum_t *ocsp_response,
apr_time_t* expiry, const gnutls_datum_t *nonce)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(s->module_config, &gnutls_module);
if (req_data->trust == NULL)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"No OCSP trust list available for server \"%s\"!",
s->server_hostname);
return GNUTLS_E_NO_CERTIFICATE_FOUND;
}
gnutls_ocsp_resp_t resp;
int ret = gnutls_ocsp_resp_init(&resp);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not initialize OCSP response structure: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
ret = gnutls_ocsp_resp_import(resp, ocsp_response);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Importing OCSP response failed: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
ret = gnutls_ocsp_resp_check_crt(resp, 0, req_data->cert);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP response is not for server certificate: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
unsigned int verify;
ret = gnutls_ocsp_resp_verify(resp, *(req_data->trust), &verify, 0);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP response verification failed: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
else
{
/* verification worked, check the result */
if (verify != 0)
{
_log_verify_fail_reason(verify, s);
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
goto resp_cleanup;
}
else
ap_log_error(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, s,
"OCSP response signature is valid.");
}
/* Even some large CAs do not support nonces, probably because
* that way they can cache responses. :-/ */
if (nonce != NULL && sc->ocsp_check_nonce)
{
gnutls_datum_t resp_nonce;
ret = gnutls_ocsp_resp_get_nonce(resp, 0, &resp_nonce);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not get OCSP response nonce: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
if (resp_nonce.size != nonce->size
|| memcmp(resp_nonce.data, nonce->data, nonce->size))
{
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP response invalid: nonce mismatch");
gnutls_free(resp_nonce.data);
goto resp_cleanup;
}
ap_log_error(APLOG_MARK, APLOG_TRACE2, APR_SUCCESS, s,
"OCSP response: nonce match");
gnutls_free(resp_nonce.data);
}
/* OK, response is for our certificate and valid, let's get the
* actual response data. */
unsigned int cert_status;
time_t this_update;
time_t next_update;
ret = gnutls_ocsp_resp_get_single(resp, 0, NULL, NULL, NULL, NULL,
&cert_status, &this_update,
&next_update, NULL, NULL);
if (ret != GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Could not get OCSP response data: %s (%d)",
gnutls_strerror(ret), ret);
goto resp_cleanup;
}
apr_time_t now = apr_time_now();
apr_time_t valid_at;
apr_time_ansi_put(&valid_at, this_update);
/* Buffer for human-readable times produced by apr_rfc822_date,
* see apr_time.h */
char date_str[APR_RFC822_DATE_LEN];
apr_rfc822_date(date_str, valid_at);
if (now < valid_at)
{
/* We don't know if our clock or that of the OCSP responder is
* out of sync, so warn but continue. */
ap_log_error(APLOG_MARK, APLOG_WARNING, APR_EGENERAL, s,
"OSCP response claims to be from future (%s), check "
"time synchronization!", date_str);
}
if (next_update == (time_t) -1)
{
ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
"OSCP response does not contain nextUpdate info.");
if (expiry != NULL)
*expiry = 0;
}
else
{
apr_time_t valid_to;
apr_time_ansi_put(&valid_to, next_update);
if (expiry != NULL)
*expiry = valid_to;
if (now > valid_to)
{
apr_rfc822_date(date_str, valid_to);
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"OCSP response has expired at %s!", date_str);
/* Do not send a stale response */
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
goto resp_cleanup;
}
}
/* What's the actual status? Will be one of
* gnutls_ocsp_cert_status_t as defined in gnutls/ocsp.h. */
if (cert_status == GNUTLS_OCSP_CERT_GOOD)
{
/* Yay, everything's good! */
ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, s,
"CA flagged certificate as valid at %s.", date_str);
}
else
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"CA flagged certificate as %s at %s.",
cert_status == GNUTLS_OCSP_CERT_REVOKED ?
"revoked" : "unknown", date_str);
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
}
resp_cleanup:
gnutls_ocsp_resp_deinit(resp);
return ret;
}
/*
* Returns the certificate fingerprint, memory is allocated from p.
*/
static gnutls_datum_t mgs_get_cert_fingerprint(apr_pool_t *p,
gnutls_x509_crt_t cert)
{
gnutls_datum_t fingerprint = {NULL, 0};
size_t fplen = 0;
gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, NULL, &fplen);
unsigned char * fp = apr_palloc(p, fplen);
gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, fp, &fplen);
/* Safe integer type conversion: The types of fingerprint.size
* (unsigned int) and fplen (size_t) may have different
* lengths. */
#if defined(__GNUC__) && __GNUC__ < 5 && !defined(__clang__)
if (__builtin_expect(fplen <= UINT_MAX, 1))
{
fingerprint.size = (unsigned int) fplen;
fingerprint.data = fp;
}
#else
if (__builtin_add_overflow(fplen, 0, &fingerprint.size))
fingerprint.size = 0;
else
fingerprint.data = fp;
#endif
return fingerprint;
}
static apr_status_t do_ocsp_request(apr_pool_t *p, server_rec *s,
apr_uri_t *uri,
gnutls_datum_t *request,
gnutls_datum_t *response)
__attribute__((nonnull));
static apr_status_t do_ocsp_request(apr_pool_t *p, server_rec *s,
apr_uri_t *uri,
gnutls_datum_t *request,
gnutls_datum_t *response)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(s->module_config, &gnutls_module);
if (apr_strnatcmp(uri->scheme, "http"))
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Scheme \"%s\" is not supported for OCSP requests!",
uri->scheme);
return APR_EINVAL;
}
const char* header = http_post_header(p, uri,
OCSP_REQ_TYPE, OCSP_RESP_TYPE,
request->size);
ap_log_error(APLOG_MARK, APLOG_TRACE2, APR_SUCCESS, s,
"OCSP POST header: %s", header);
/* Find correct port */
apr_port_t port = uri->port ?
uri->port : apr_uri_port_of_scheme(uri->scheme);
apr_sockaddr_t *sa;
apr_status_t rv = apr_sockaddr_info_get(&sa, uri->hostname,
APR_UNSPEC, port, 0, p);
if (rv != APR_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Address resolution for OCSP responder %s failed.",
uri->hostinfo);
}
/* There may be multiple answers, try them in order until one
* works. */
apr_socket_t *sock;
while (sa)
{
rv = apr_socket_create(&sock, sa->family, SOCK_STREAM,
APR_PROTO_TCP, p);
if (rv == APR_SUCCESS)
{
apr_socket_timeout_set(sock, sc->ocsp_socket_timeout);
rv = apr_socket_connect(sock, sa);
if (rv == APR_SUCCESS)
/* Connected! */
break;
apr_socket_close(sock);
}
sa = sa->next;
}
/* If the socket is connected, 'sa' points at the matching
* address. */
if (sa == NULL)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Connecting to OCSP responder %s failed.",
uri->hostinfo);
return rv;
}
/* Header is generated locally, so strlen() is safe. */
rv = sock_send_buf(sock, header, strlen(header));
if (rv == APR_SUCCESS)
rv = sock_send_buf(sock, (char*) request->data, request->size);
/* catches errors from both header and request */
if (rv != APR_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Sending OCSP request failed.");
goto exit;
}
/* Prepare bucket brigades to read the response header. BBs make
* it easy to split the header into lines. */
apr_bucket_alloc_t *ba = apr_bucket_alloc_create(p);
apr_bucket_brigade *bb = apr_brigade_create(p, ba);
/* will carry split response headers */
apr_bucket_brigade *rh = apr_brigade_create(p, ba);
APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_socket_create(sock, ba));
/* The first line in the response header must be the status, check
* for OK status code. Line looks similar to "HTTP/1.0 200 OK". */
const char *h = read_line(p, bb, rh);
const char *code = 0;
if (h == NULL
|| strncmp(h, "HTTP/", 5)
|| (code = ap_strchr(h, ' ')) == NULL
|| apr_atoi64(code + 1) != HTTP_OK)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Invalid HTTP response status from %s: %s",
uri->hostinfo, h);
rv = APR_ECONNRESET;
goto exit;
}
/* Read remaining header lines */
for (h = read_line(p, bb, rh); h != NULL && apr_strnatcmp(h, "") != 0;
h = read_line(p, bb, rh))
{
ap_log_error(APLOG_MARK, APLOG_TRACE2, APR_SUCCESS, s,
"Received header: %s", h);
}
/* The last header line should be empty (""), NULL indicates an
* error. */
if (h == NULL)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Error while reading HTTP response header from %s",
uri->hostinfo);
rv = APR_ECONNRESET;
goto exit;
}
/* Headers have been consumed, the rest of the available data
* should be the actual response. */
apr_size_t len = OCSP_RESP_SIZE_MAX;
char buf[OCSP_RESP_SIZE_MAX];
/* apr_brigade_pflatten() can allocate directly from the pool, but
* the documentation does not describe a way to limit the size of
* the buffer, which is necessary here to prevent DoS by endless
* response. Use apr_brigade_flatten() to read to a stack pool,
* then create a copy to return. */
rv = apr_brigade_flatten(bb, buf, &len);
if (rv != APR_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Failed to read OCSP response.");
goto exit;
}
/* With the length restriction this really should not overflow. */
#if defined(__GNUC__) && __GNUC__ < 5 && !defined(__clang__)
if (__builtin_expect(len > UINT_MAX, 0))
#else
if (__builtin_add_overflow(len, 0, &response->size))
#endif
{
response->data = NULL;
rv = APR_ENOMEM;
}
else
{
#if defined(__GNUC__) && __GNUC__ < 5 && !defined(__clang__)
response->size = (unsigned int) len;
#endif
response->data = apr_pmemdup(p, buf, len);
}
exit:
apr_socket_close(sock);
return rv;
}
/**
* Get a fresh OCSP response and put it into the cache.
*
* @param s server that needs a new response
*
* @param req_data struct describing the certificate for which to
* cache a response
*
* @param cache_expiry If not `NULL`, this `apr_time_t` will be set to
* the expiration time of the cache entry. Remains unchanged on
* failure.
*
* @return APR_SUCCESS or an APR error code
*/
static apr_status_t mgs_cache_ocsp_response(server_rec *s,
mgs_ocsp_data_t req_data,
apr_time_t *cache_expiry)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(s->module_config, &gnutls_module);
if (sc->ocsp_cache == NULL)
{
/* OCSP caching requires a cache. */
return APR_ENOTIMPL;
}
apr_pool_t *tmp;
apr_status_t rv = apr_pool_create(&tmp, NULL);
if (rv != APR_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"could not create temporary pool for %s",
__func__);
return rv;
}
gnutls_datum_t resp;
gnutls_datum_t nonce = { NULL, 0 };
if (req_data->response_file != NULL)
{
ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, s,
"Loading OCSP response from %s",
req_data->response_file);
rv = datum_from_file(tmp, req_data->response_file, &resp);
if (rv != APR_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
"Loading OCSP response from %s failed!",
req_data->response_file);
apr_pool_destroy(tmp);
return rv;
}
}
else
{
gnutls_datum_t req;
int ret = mgs_create_ocsp_request(s, req_data, &req,
sc->ocsp_check_nonce ? &nonce : NULL);
if (ret == GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_TRACE2, APR_SUCCESS, s,
"created OCSP request for %s:%d: %s",
s->server_hostname, s->addrs->host_port,
apr_pescape_hex(tmp, req.data, req.size, 0));
}
else
{
gnutls_free(req.data);
gnutls_free(nonce.data);
apr_pool_destroy(tmp);
return APR_EGENERAL;
}
rv = do_ocsp_request(tmp, s, req_data->uri, &req, &resp);
gnutls_free(req.data);
if (rv != APR_SUCCESS)
{
/* do_ocsp_request() does its own error logging. */
gnutls_free(nonce.data);
apr_pool_destroy(tmp);
return rv;
}
}
apr_time_t next_update;
if (check_ocsp_response(s, req_data, &resp, &next_update,
nonce.size ? &nonce : NULL)
!= GNUTLS_E_SUCCESS)
{
ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_EGENERAL, s,
"OCSP response validation failed, cannot "
"update cache.");
apr_pool_destroy(tmp);
gnutls_free(nonce.data);
return APR_EGENERAL;
}
gnutls_free(nonce.data);
apr_time_t expiry = apr_time_now() + sc->ocsp_cache_time;
/* Make sure that a response is not cached beyond its nextUpdate
* time. If the variable next_update is zero, the response does
* not contain a nextUpdate field. */
if (next_update != 0 && next_update < expiry)
{
char date_str[APR_RFC822_DATE_LEN];
apr_rfc822_date(date_str, next_update);
ap_log_error(APLOG_MARK, APLOG_WARNING, APR_EGENERAL, s,
"OCSP response timeout restricted to nextUpdate time %s. "
"Check if GnuTLSOCSPCacheTimeout is appropriate.",
date_str);
expiry = next_update;
}
int r = mgs_cache_store(sc->ocsp_cache, s,
req_data->fingerprint, resp, expiry);
/* destroy pool, and original copy of the OCSP response with it */
apr_pool_destroy(tmp);
if (r != 0)
{
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Storing OCSP response in cache failed.");
return APR_EGENERAL;
}
if (cache_expiry != NULL)
*cache_expiry = expiry;
return APR_SUCCESS;
}
/**
* Retries after failed OCSP requests must be rate limited. If the
* responder is overloaded or buggy we don't want to add too much more
* load, and if a MITM is messing with requests a repetition loop
* might end up being a self-inflicted denial of service. This
* function writes a specially formed entry to the cache to indicate a
* recent failure.
*
* @param s the server for which an OCSP request failed
*
* @param req_data OCSP data structure for the certificate that could
* not be checked
*
* @param timeout lifetime of the cache entry
*/
static void mgs_cache_ocsp_failure(server_rec *s,
mgs_ocsp_data_t req_data,
apr_interval_time_t timeout)
{
mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
ap_get_module_config(s->module_config, &gnutls_module);
unsigned char c = OCSP_FAILURE_CACHE_DATA;
gnutls_datum_t dummy = {
.data = &c,
.size = sizeof(c)
};
apr_time_t expiry = apr_time_now() + timeout;
int r = mgs_cache_store(sc->ocsp_cache, s,
req_data->fingerprint, dummy, expiry);
if (r != 0)
ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, s,
"Caching OCSP failure failed.");
}
int mgs_get_ocsp_response(mgs_handle_t *ctxt,
mgs_ocsp_data_t req_data,
gnutls_datum_t *ocsp_response)
{
mgs_srvconf_rec *sc = ctxt->sc;
if (!sc->ocsp_staple || sc->ocsp_cache == NULL)
{
/* OCSP must be enabled and caching requires a cache. */
return GNUTLS_E_NO_CERTIFICATE_STATUS;
}
// TODO: Large allocation, and the pool system doesn't offer realloc
ocsp_response->data = apr_palloc(ctxt->c->pool, OCSP_RESP_SIZE_MAX);
ocsp_response->size = OCSP_RESP_SIZE_MAX;
apr_status_t rv = mgs_cache_fetch(sc->ocsp_cache,
ctxt->c->base_server,
req_data->fingerprint,
ocsp_response,
ctxt->c->pool);
if (rv != APR_SUCCESS)
{
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_EGENERAL, ctxt->c,
"Fetching OCSP response from cache failed.");
}
else if (IS_FAILURE_RESPONSE(ocsp_response))
{
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_EGENERAL, ctxt->c,
"Cached OCSP failure found for %s.",
ctxt->c->base_server->server_hostname);
goto fail_cleanup;
}
else
{
return GNUTLS_E_SUCCESS;
}
/* keep response buffer, reset size for reuse */
ocsp_response->size = OCSP_RESP_SIZE_MAX;
/* If the cache had no response or an invalid one, try to update. */
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ctxt->c,
"No valid OCSP response in cache, trying to update.");
rv = apr_global_mutex_trylock(sc->ocsp_mutex);
if (APR_STATUS_IS_EBUSY(rv))
{
/* Another thread is currently holding the mutex, wait. */
apr_global_mutex_lock(sc->ocsp_mutex);
/* Check if this other thread updated the response we need. It
* would be better to have a vhost specific mutex, but at the
* moment there's no good way to integrate that with the
* Apache Mutex directive. */
rv = mgs_cache_fetch(sc->ocsp_cache,
ctxt->c->base_server,
req_data->fingerprint,
ocsp_response,
ctxt->c->pool);
if (rv == APR_SUCCESS)
{
apr_global_mutex_unlock(sc->ocsp_mutex);
/* Check if the response is valid. */
if (IS_FAILURE_RESPONSE(ocsp_response))
{
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_EGENERAL, ctxt->c,
"Cached OCSP failure found for %s.",
ctxt->c->base_server->server_hostname);
goto fail_cleanup;
}
else
return GNUTLS_E_SUCCESS;
}
else
{
/* keep response buffer, reset size for reuse */
ocsp_response->size = OCSP_RESP_SIZE_MAX;
}
}
rv = mgs_cache_ocsp_response(ctxt->c->base_server, req_data, NULL);
if (rv != APR_SUCCESS)
{
ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, ctxt->c,
"Caching a fresh OCSP response failed");
/* cache failure to rate limit retries */
mgs_cache_ocsp_failure(ctxt->c->base_server,
req_data,
sc->ocsp_failure_timeout);
apr_global_mutex_unlock(sc->ocsp_mutex);
goto fail_cleanup;
}
apr_global_mutex_unlock(sc->ocsp_mutex);
/* retry reading from cache */
rv = mgs_cache_fetch(sc->ocsp_cache,
ctxt->c->base_server,
req_data->fingerprint,
ocsp_response,
ctxt->c->pool);
if (rv != APR_SUCCESS)
{
ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, ctxt->c,
"Fetching OCSP response from cache failed on retry.");
}
else
{
return GNUTLS_E_SUCCESS;
}
/* failure, reset struct, buffer will be released with the
* connection pool */
fail_cleanup:
ocsp_response->size = 0;
ocsp_response->data = NULL;
return GNUTLS_E_NO_CERTIFICATE_STATUS;
}
int mgs_create_ocsp_trust_list(gnutls_x509_trust_list_t *tl,
const gnutls_x509_crt_t *chain,
const int num)
{
int added = 0;
int ret = gnutls_x509_trust_list_init(tl, num);
if (ret == GNUTLS_E_SUCCESS)
added = gnutls_x509_trust_list_add_cas(*tl, chain, num, 0);
if (added != num)
ret = GNUTLS_E_CERTIFICATE_ERROR;
/* Clean up trust list in case of error */
if (ret != GNUTLS_E_SUCCESS)
gnutls_x509_trust_list_deinit(*tl, 0);
return ret;
}
apr_status_t mgs_cleanup_trust_list(void *data)
{
gnutls_x509_trust_list_t *tl = (gnutls_x509_trust_list_t *) data;
gnutls_x509_trust_list_deinit(*tl, 0);
return APR_SUCCESS;
}
apr_uri_t * mgs_cert_get_ocsp_uri(apr_pool_t *p, gnutls_x509_crt_t cert)
{
apr_pool_t *tmp;
apr_status_t rv = apr_pool_create(&tmp, p);
if (rv != APR_SUCCESS)
return NULL;
apr_uri_t *ocsp_uri = NULL;
int ret = GNUTLS_E_SUCCESS;
/* search authority info access for OCSP URI */
for (int seq = 0; ret != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; seq++)
{
gnutls_datum_t ocsp_access_data;
ret = gnutls_x509_crt_get_authority_info_access(cert, seq,
GNUTLS_IA_OCSP_URI,
&ocsp_access_data,
NULL);
if (ret == GNUTLS_E_SUCCESS)
{
/* create NULL terminated string */
char *ocsp_str =
apr_pstrndup(tmp, (const char*) ocsp_access_data.data,
ocsp_access_data.size);
gnutls_free(ocsp_access_data.data);
ocsp_uri = apr_palloc(p, sizeof(apr_uri_t));
rv = apr_uri_parse(p, ocsp_str, ocsp_uri);
if (rv == APR_SUCCESS)