-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphantom_token.c
1503 lines (1260 loc) · 54.6 KB
/
phantom_token.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 2017 Curity AB
*
* 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 <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_string.h>
#include <stdbool.h>
#include <assert.h>
#define UNENCODED_CLIENT_CREDENTIALS_BUF_LEN 1024
typedef struct
{
ngx_str_t base64encoded_client_credential;
ngx_str_t introspection_endpoint;
ngx_str_t realm;
ngx_array_t *scopes;
ngx_str_t space_separated_scopes;
ngx_flag_t enable;
} phantom_token_configuration_t;
typedef struct
{
ngx_uint_t done;
ngx_uint_t status;
ngx_str_t jwt;
ngx_str_t original_accept_header;
ngx_str_t original_content_type_header;
ngx_str_t original_sec_websocket_key;
ngx_str_t original_sec_websocket_version;
} phantom_token_module_context_t;
static ngx_int_t post_configuration(ngx_conf_t *config);
static ngx_int_t handler(ngx_http_request_t *request);
static void *create_location_configuration(ngx_conf_t *config);
static char *merge_location_configuration(ngx_conf_t *main_config, void *parent, void *child);
static ngx_int_t introspection_response_handler(ngx_http_request_t *request, void *data,
ngx_int_t introspection_subrequest_status_code);
static ngx_int_t write_error_response(ngx_http_request_t *request, ngx_int_t status, phantom_token_configuration_t *module_location_config);
/**
* Adds a WWW-Authenticate header to the given request's output headers that conforms to <a href="https://tools.ietf.org/html/rfc6750">RFC 6750</>.
*
* After calling this method, a WWW-Authenticate header will be added that uses the Bearer scheme. If the realm and or
* scopes were also configured, then these too will be included. For instance, if scopes are configured, then the
* following output header will be added: <code> WWW-Authenticate: Bearer scope="scope1 scope2 scope3"</code>. If only
* realm is configured, then a response header like this one would be added:
* <code>WWW-Authenticate: Bearer realm="myGoodRealm"</code>. If both are configured, the two will be included and
* separated by a comma, like this: <code>WWW-Authenticate: Bearer realm="myGoodRealm", scope="scope1 scope2 scope3"</code>.
*
* @param request the current request
* @param realm the configured realm
* @param space_separated_scopes the space-separated list of configured scopes
* @param error an error code or NULL if none. Refer to
* <a href="https://tools.ietf.org/html/rfc6750#section-3.1">RFC 6750 § 3.1</a> for standard values.
*
* @return <code>NGX_HTTP_UNAUTHORIZED</code>
*
* @example <code>WWW-Authenticate: Bearer realm="myGoodRealm", scope="scope1 scope2 scope3"</code>
*
* @see <a href="https://tools.ietf.org/html/rfc6750">RFC 6750</a>
*/
static ngx_int_t set_www_authenticate_header(ngx_http_request_t *request, phantom_token_configuration_t *module_location_config, char *error_code);
/**
* Sets the base-64-encoded client ID and secret in the module's configuration setting structure.
*
* This method assumes the module's command where this setter function (<code>set</code>) is used has a
* configuration (<code>conf</code>) of <code>NGX_HTTP_LOC_CONF_OFFSET<code> and an <code>offset</code> of
* <code>base64encoded_client_credential</code>. If this is not the case, the result pointer <em>may</em> point to an
* unexpected location and the handler may not be able to use the configured values. Also, the command should have a
* type that includes <code>NGX_CONF_TAKE2</code>.
*
* @param config_setting the configuration setting that is being set
* @param command the module's command where this slot setter function is being used
* @param result a pointer to the location where the result will be stored; it should be a pointer to a
* <code>ngx_str_t</code>.
*
* @return <code>NGX_CONF_OK</code> upon success; some other character string on failure.
*/
static char* set_client_credential_configuration_slot(ngx_conf_t *config_setting, ngx_command_t *command, void *result);
/**
* Sets the base-64-encoded client ID and secret in the module's configuration
* setting structure from a file.
*
* This method assumes the module's command where this setter function
* (<code>set</code>) is used has a configuration (<code>conf</code>) of
* <code>NGX_HTTP_LOC_CONF_OFFSET<code> and an <code>offset</code> of
* <code>base64encoded_client_credential</code>. If this is not the case, the
* result pointer <em>may</em> point to an unexpected location and the handler
* may not be able to use the configured values. Also, the command should have a
* type that includes <code>NGX_CONF_TAKE2</code>.
*
* @param config_setting the configuration setting that is being set
* @param command the module's command where this slot setter function is being
* used
* @param result a pointer to the location where the result will be stored; it
* should be a pointer to a <code>ngx_str_t</code>.
*
* @return <code>NGX_CONF_OK</code> upon success; some other character string on
* failure.
*/
static char *set_client_credential_file_configuration_slot(
ngx_conf_t *config_setting, ngx_command_t *command, void *result);
static ngx_str_t BEARER = ngx_string("Bearer ");
static ngx_str_t BEARER_UNDERSCORE = ngx_string("Bearer_");
static ngx_command_t phantom_token_module_directives[] = {
{
ngx_string("phantom_token"),
NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF |
NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t, enable),
NULL,
},
{
ngx_string("phantom_token_client_credential"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
set_client_credential_configuration_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t,
base64encoded_client_credential),
NULL,
},
{
ngx_string("phantom_token_client_credential_file"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
set_client_credential_file_configuration_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t,
base64encoded_client_credential),
NULL,
},
{
ngx_string("phantom_token_introspection_endpoint"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t, introspection_endpoint),
NULL,
},
{
ngx_string("phantom_token_realm"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t, realm),
NULL,
},
{
ngx_string("phantom_token_scopes"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t, space_separated_scopes),
NULL,
},
{
ngx_string("phantom_token_scope"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_array_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(phantom_token_configuration_t, scopes),
NULL,
},
ngx_null_command /* command termination */
};
/* The module context. */
static ngx_http_module_t phantom_token_module_context =
{
NULL, /* pre-configuration */
post_configuration,
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
create_location_configuration,
merge_location_configuration
};
/* Module definition. */
ngx_module_t ngx_curity_http_phantom_token_module =
{
NGX_MODULE_V1,
&phantom_token_module_context,
phantom_token_module_directives,
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_table_elt_t *find_header_in(ngx_http_request_t *r, ngx_str_t key) {
ngx_list_part_t *part;
ngx_table_elt_t *h;
ngx_uint_t i;
part = &r->headers_in.headers.part;
h = part->elts;
for (i = 0;; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
// Walk next part
part = part->next;
h = part->elts;
i = 0;
}
if (h[i].key.len != key.len ||
ngx_strncasecmp(h[i].key.data, key.data, key.len) != 0) {
continue; // Continue if not matched
}
// Found
return &h[i];
}
return NULL;
}
/**
* Remove an element from the list and the part that contains it.
*
* Ref:
* https://github.com/openresty/headers-more-nginx-module/blob/84a65d68687c9de5166fd49ddbbd68c6962234eb/src/ngx_http_headers_more_util.c#L265-L382
*/
ngx_int_t ngx_http_headers_more_rm_header_helper(ngx_list_t *l,
ngx_list_part_t *cur,
ngx_uint_t i) {
ngx_table_elt_t *data;
ngx_list_part_t *new, *part;
data = cur->elts;
if (i == 0) {
cur->elts = (char *)cur->elts + l->size;
cur->nelts--;
if (cur == l->last) {
if (cur->nelts == 0) {
#if 1
part = &l->part;
if (part == cur) {
cur->elts = (char *)cur->elts - l->size;
/* do nothing */
} else {
while (part->next != cur) {
if (part->next == NULL) {
return NGX_ERROR;
}
part = part->next;
}
l->last = part;
part->next = NULL;
l->nalloc = part->nelts;
}
#endif
} else {
l->nalloc--;
}
return NGX_OK;
}
if (cur->nelts == 0) {
part = &l->part;
if (part == cur) {
assert(cur->next != NULL);
if (l->last == cur->next) {
l->part = *(cur->next);
l->last = part;
l->nalloc = part->nelts;
} else {
l->part = *(cur->next);
}
} else {
while (part->next != cur) {
if (part->next == NULL) {
return NGX_ERROR;
}
part = part->next;
}
part->next = cur->next;
}
return NGX_OK;
}
return NGX_OK;
}
if (i == cur->nelts - 1) {
cur->nelts--;
if (cur == l->last) {
l->nalloc = cur->nelts;
}
return NGX_OK;
}
new = ngx_palloc(l->pool, sizeof(ngx_list_part_t));
if (new == NULL) {
return NGX_ERROR;
}
new->elts = &data[i + 1];
new->nelts = cur->nelts - i - 1;
new->next = cur->next;
cur->nelts = i;
cur->next = new;
if (cur == l->last) {
l->last = new;
l->nalloc = new->nelts;
}
return NGX_OK;
}
/**
* Set the header with the given key from the list.
*
* Ref:
* https://github.com/nginx/nginx/blob/d31305653701bd99e8e5e6aa48094599a08f9f12/src/core/ngx_list.h#L55-L78
* https://github.com/openresty/headers-more-nginx-module/blob/84a65d68687c9de5166fd49ddbbd68c6962234eb/src/ngx_http_headers_more_headers_in.c#L220-L221
*/
static ngx_int_t set_header_helper(ngx_http_request_t *r, ngx_str_t key,
ngx_str_t value,
ngx_table_elt_t **output_header) {
ngx_list_part_t *part;
ngx_table_elt_t *h, *matched;
ngx_uint_t rc;
ngx_uint_t i;
matched = NULL;
retry:
part = &r->headers_in.headers.part;
h = part->elts;
// Replace logic
for (i = 0;; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
// Walk next part
part = part->next;
h = part->elts;
i = 0;
}
if (h[i].key.len == key.len &&
ngx_strncasecmp(h[i].key.data, key.data, key.len) == 0) {
goto matched;
}
/* not matched */
continue;
matched:
// If value is 0, remove the header. If there are duplicates, remove
// them all.
if (value.len == 0 || (matched && matched != &h[i])) {
rc = ngx_http_headers_more_rm_header_helper(&r->headers_in.headers,
part, i);
assert(
!(r->headers_in.headers.part.next == NULL &&
r->headers_in.headers.last != &r->headers_in.headers.part));
if (rc == NGX_OK) {
if (output_header) { // If output_header is set to old header,
// this clears it.
*output_header = NULL;
}
goto retry; // Make sure to clean all occurrences.
}
return NGX_ERROR;
}
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"Replacing header with the same key %V", &key);
h[i].value = value;
if (output_header) {
*output_header = &h[i];
}
if (matched == NULL) {
matched = &h[i];
}
}
if (matched) {
return NGX_OK;
}
if (value.len == 0) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"Removed header %V", &key);
return NGX_OK;
}
if (r->headers_in.headers.last == NULL) {
/* must be 400 bad request */
return NGX_OK;
}
// Add logic (field was not found)
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->hash = 1;
h->key = key;
h->value = value;
#if defined(nginx_version) && nginx_version >= 1023000
h->next = NULL;
#endif
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
if (output_header) {
*output_header = h;
}
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"Added header "
"with key %V",
&key);
return NGX_OK;
}
static void clear_header_helper(ngx_http_request_t *r, ngx_str_t key) {
ngx_str_t value = ngx_null_string;
set_header_helper(r, key, value, NULL);
}
/**
* Sets the request's Accept header to the given value.
*
* @param request the request to which the header value will be set
* @param value the value to set
* @return NGX_OK if no error has occurred; NGX_ERROR if an error occurs.
*/
static ngx_int_t set_accept_header_value(ngx_http_request_t *request,
ngx_str_t value) {
static ngx_str_t accept = ngx_string("Accept");
ngx_uint_t found =
set_header_helper(request, accept, value, &request->headers_in.accept);
if (found != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to set header accept: %V", &value);
return NGX_ERROR;
}
// If last == part, we need to update the number of elements
if (request->headers_in.headers.part.next == NULL) {
request->headers_in.headers.part.nelts =
request->headers_in.headers.last->nelts;
}
return NGX_OK;
}
static ngx_int_t handler(ngx_http_request_t *request)
{
phantom_token_configuration_t *module_location_config = ngx_http_get_module_loc_conf(
request, ngx_curity_http_phantom_token_module);
// Return OK if the module is not active
if (!module_location_config->enable)
{
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request->connection->log, 0, "Module disabled");
return NGX_DECLINED;
}
// OPTIONS requests from SPAs can never contain an authorization header so return a standard 204
if (request->method == NGX_HTTP_OPTIONS)
{
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request->connection->log, 0, "Not processing OPTIONS request");
return NGX_OK;
}
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request->connection->log, 0, "Handling request to convert token to JWT");
if (module_location_config->base64encoded_client_credential.len == 0)
{
ngx_log_error(NGX_LOG_WARN, request->connection->log, 0,
"Module not configured properly: missing client ID and secret");
return NGX_DECLINED;
}
ngx_str_t encoded_client_credentials = module_location_config->base64encoded_client_credential;
if (module_location_config->introspection_endpoint.len == 0)
{
ngx_log_error(NGX_LOG_WARN, request->connection->log, 0,
"Module not configured properly: missing introspection endpoint");
return NGX_DECLINED;
}
phantom_token_module_context_t *module_context = ngx_http_get_module_ctx(request, ngx_curity_http_phantom_token_module);
// On callback.
if (module_context != NULL)
{
if (module_context->done)
{
// return appropriate status
if (module_context->status == NGX_HTTP_OK)
{
// Introspection was successful. Replace the incoming Authorization header with one that has the JWT.
static ngx_str_t authorization = ngx_string("Authorization");
set_header_helper(request, authorization, module_context->jwt,
&request->headers_in.authorization);
ngx_log_error(NGX_LOG_NOTICE, request->connection->log, 0,
"Introspection request from %V succeeded",
&request->uri);
if (module_context->original_content_type_header.data == NULL)
{
static ngx_str_t ct = ngx_string("Content-Type");
clear_header_helper(request, ct);
// If last == part, we need to update the number of elements
if (request->headers_in.headers.part.next == NULL) {
request->headers_in.headers.part.nelts =
request->headers_in.headers.last->nelts;
}
}
else
{
request->headers_in.content_type->value = module_context->original_content_type_header;
}
if (request->headers_in.accept == NULL)
{
ngx_int_t result;
static ngx_str_t accept_value = ngx_string("*/*");
if ((result = set_accept_header_value(
request, accept_value) != NGX_OK)) {
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to set Accept header value");
return result;
}
}
else
{
request->headers_in.accept->value = module_context->original_accept_header;
}
if (module_context->original_sec_websocket_key.len > 0) {
ngx_int_t result;
static ngx_str_t sec_websocket_key =
ngx_string("Sec-WebSocket-Key");
if ((result = set_header_helper(
request, sec_websocket_key,
module_context->original_sec_websocket_key,
NULL)) != NGX_OK) {
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to set header Sec-WebSocket-Key: %V",
&module_context->original_sec_websocket_key);
return result;
}
}
if (module_context->original_sec_websocket_version.len > 0) {
ngx_int_t result;
static ngx_str_t sec_websocket_version =
ngx_string("Sec-WebSocket-Version");
if ((result = set_header_helper(
request, sec_websocket_version,
module_context->original_sec_websocket_version,
NULL)) != NGX_OK) {
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to set header Sec-WebSocket-Version: %V",
&module_context->original_sec_websocket_version);
return result;
}
}
return NGX_OK;
}
else if (module_context->status == NGX_HTTP_NO_CONTENT)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Introspection request from %V failed with no content: %d",
&request->connection->addr_text, module_context->status);
return set_www_authenticate_header(request, module_location_config, NULL);
}
else if (module_context->status == NGX_HTTP_SERVICE_UNAVAILABLE)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Introspection request failed with service unavailable: %d",
module_context->status);
return write_error_response(request, NGX_HTTP_SERVICE_UNAVAILABLE, module_location_config);
}
else if (module_context->status >= NGX_HTTP_INTERNAL_SERVER_ERROR || module_context->status == NGX_HTTP_NOT_FOUND
|| module_context->status == NGX_HTTP_UNAUTHORIZED || module_context->status == NGX_HTTP_FORBIDDEN)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Introspection request from %V failed with status code "
"(server responded): %d",
&request->connection->addr_text, module_context->status);
return write_error_response(request, NGX_HTTP_BAD_GATEWAY, module_location_config);
}
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Introspection request from %V failed with status code "
"(unknown error, see nginx error_logs): %d",
&request->connection->addr_text, module_context->status);
return write_error_response(request, NGX_HTTP_INTERNAL_SERVER_ERROR, module_location_config);
}
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request->connection->log, 0,
"Called again without having received the response from Curity");
return NGX_AGAIN;
}
ngx_str_t bearer_token = ngx_null_string;
// Check if it's websocket
if (request->headers_in.upgrade &&
request->headers_in.upgrade->value.len > 0 &&
!ngx_strncasecmp(request->headers_in.upgrade->value.data,
(u_char *)"websocket", 9)) {
ngx_log_error(NGX_LOG_NOTICE, request->connection->log, 0,
"GraphQL WebSocket introspection request from %V",
&request->uri);
// Get bearer from Sec-Websocket-Protocol header
static ngx_str_t sec_websocket_protocol =
ngx_string("Sec-WebSocket-Protocol");
ngx_table_elt_t *sec_websocket_protocol_header =
find_header_in(request, sec_websocket_protocol);
if (sec_websocket_protocol_header == NULL) {
// No Sec-WebSocket-Protocol header found
ngx_log_error(NGX_LOG_WARN, request->connection->log, 0,
"No Sec-WebSocket-Protocol header found, "
"not eligible for introspection");
return set_www_authenticate_header(request, module_location_config,
NULL);
}
if (sec_websocket_protocol_header->value.len == 0) {
// Empty Sec-WebSocket-Protocol header found
ngx_log_error(NGX_LOG_WARN, request->connection->log, 0,
"Empty Sec-WebSocket-Protocol header found, not eligible for introspection");
return set_www_authenticate_header(request, module_location_config,
NULL);
}
// Sec-WebSocket-Protocol is a multi value comma separated header, search for "Bearer_"
// Loop over the header value length
bearer_token.data = ngx_strcasestrn(
(u_char *)sec_websocket_protocol_header->value.data,
(char *)BEARER_UNDERSCORE.data, BEARER_UNDERSCORE.len - 1);
bearer_token.len =
sec_websocket_protocol_header->value.len -
(bearer_token.data - sec_websocket_protocol_header->value.data);
} else if (request->headers_in.authorization && request->headers_in.authorization->value.len > 0) {
bearer_token.data = ngx_strcasestrn(
(u_char *)request->headers_in.authorization->value.data,
(char *)BEARER.data, BEARER.len - 1);
bearer_token.len =
request->headers_in.authorization->value.len -
(bearer_token.data - request->headers_in.authorization->value.data);
}
if (bearer_token.data == NULL) {
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Authorization header does not contain a bearer token");
return set_www_authenticate_header(request, module_location_config,
NULL);
}
// Skip "Bearer "
bearer_token.data += BEARER.len;
bearer_token.len -= BEARER.len;
// Remove any extra whitespace after the "Bearer " part of the authorization request header
while (isspace(*bearer_token.data)) {
bearer_token.data++;
bearer_token.len--;
}
// Read until the next comma or space or nothing
ngx_uint_t i = 0;
while (i < bearer_token.len && !isspace(bearer_token.data[i]) &&
bearer_token.data[i] != ',') {
i++;
}
bearer_token.len = i;
module_context = ngx_pcalloc(request->pool, sizeof(phantom_token_module_context_t));
if (module_context == NULL)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for module context");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_http_post_subrequest_t *introspection_request_callback = ngx_pcalloc(request->pool, sizeof(ngx_http_post_subrequest_t));
if (introspection_request_callback == NULL)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection request callback");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
introspection_request_callback->handler = introspection_response_handler;
introspection_request_callback->data = module_context;
ngx_http_request_t *introspection_request;
if (ngx_http_subrequest(request, &module_location_config->introspection_endpoint, NULL, &introspection_request,
introspection_request_callback, NGX_HTTP_SUBREQUEST_WAITED) != NGX_OK)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to create subrequest to introspection endpoint");
write_error_response(request, NGX_HTTP_INTERNAL_SERVER_ERROR, module_location_config);
}
// extract access token from header
u_char *introspect_body_data =
ngx_pcalloc(request->pool,
6 + bearer_token.len); // len("token=") + bearer_token.len
if (introspect_body_data == NULL)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection body data");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_str_t *introspection_body = ngx_pcalloc(request->pool, sizeof(ngx_str_t));
if (introspection_body == NULL)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection body");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_snprintf(introspect_body_data, 6 + bearer_token.len, "token=%V",
&bearer_token);
introspection_body->data = introspect_body_data;
introspection_body->len = 6 + bearer_token.len;
introspection_request->request_body =
ngx_pcalloc(request->pool, sizeof(ngx_http_request_body_t));
if (introspection_request->request_body == NULL)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection request");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_http_request_body_t *introspection_request_body =
ngx_pcalloc(request->pool, sizeof(ngx_http_request_body_t));
if (introspection_request_body == NULL)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection request body");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_buf_t *introspection_request_body_buffer =
ngx_calloc_buf(request->pool);
if (introspection_request_body_buffer == NULL)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection request body buffer");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
introspection_request_body_buffer->start = introspection_request_body_buffer->pos = introspection_body->data;
introspection_request_body_buffer->end = introspection_request_body_buffer->last = introspection_body->data +
introspection_body->len;
introspection_request_body_buffer->temporary = true;
introspection_request_body->bufs = ngx_alloc_chain_link(request->pool);
if (introspection_request_body->bufs == NULL)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for introspection request "
"body chain link");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
introspection_request_body->bufs->buf = introspection_request_body_buffer;
introspection_request_body->bufs->next = NULL;
introspection_request_body->buf = introspection_request_body_buffer;
introspection_request->request_body = introspection_request_body;
introspection_request->headers_in.content_length_n = ngx_buf_size(introspection_request_body_buffer);
#if (NGX_HTTP_HEADERS)
if (request->headers_in.accept == NULL)
{
ngx_int_t result;
static ngx_str_t application_jwt = ngx_string("application/jwt");
if ((result = set_accept_header_value(introspection_request,
application_jwt) != NGX_OK)) {
return result;
}
}
else
{
module_context->original_accept_header = request->headers_in.accept->value;
}
ngx_str_set(&introspection_request->headers_in.accept->value, "application/jwt");
#endif
if (request->headers_in.content_type == NULL)
{
static ngx_str_t ct = ngx_string("Content-Type");
static ngx_str_t ct_value =
ngx_string("application/x-www-form-urlencoded");
ngx_uint_t found =
set_header_helper(introspection_request, ct, ct_value,
&introspection_request->headers_in.content_type);
if (found != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Failed to set header content-type: "
"application/x-www-form-urlencoded");
return NGX_ERROR;
}
// Update the number of headers
if (introspection_request->headers_in.headers.part.next == NULL) {
introspection_request->headers_in.headers.part.nelts =
introspection_request->headers_in.headers.last->nelts;
}
}
else
{
module_context->original_content_type_header = request->headers_in.content_type->value;
ngx_str_set(&request->headers_in.content_type->value, "application/x-www-form-urlencoded");
}
introspection_request->header_only = true;
// Change subrequest method to POST
introspection_request->method = NGX_HTTP_POST;
ngx_str_set(&introspection_request->method_name, "POST");
// set authorization credentials header to Basic base64encoded_client_credential
size_t authorization_header_data_len = encoded_client_credentials.len + sizeof("Basic ") - 1;
u_char *authorization_header_data =
ngx_pcalloc(request->pool, authorization_header_data_len);
if (authorization_header_data == NULL)
{
ngx_log_error(
NGX_LOG_ERR, request->connection->log, 0,
"Failed to allocate memory for authorization header data");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_snprintf(authorization_header_data, authorization_header_data_len,
"Basic %V", &encoded_client_credentials);
static ngx_str_t authorization = ngx_string("Authorization");
ngx_str_t authorization_value = {authorization_header_data_len,
authorization_header_data};
// Save related websocket headers to not lose after subrequest
static ngx_str_t sec_websocket_key = ngx_string("Sec-WebSocket-Key");
ngx_table_elt_t *elt;
if ((elt = find_header_in(request, sec_websocket_key)) != NULL) {
module_context->original_sec_websocket_key = elt->value;
}
static ngx_str_t sec_websocket_version =
ngx_string("Sec-WebSocket-Version");
if ((elt = find_header_in(request, sec_websocket_version)) != NULL) {
module_context->original_sec_websocket_version = elt->value;
}
set_header_helper(introspection_request, authorization, authorization_value,
&introspection_request->headers_in.authorization);
ngx_http_set_ctx(request, module_context,
ngx_curity_http_phantom_token_module);
return NGX_AGAIN;
}
static ngx_int_t introspection_response_handler(ngx_http_request_t *request, void *data,
ngx_int_t introspection_subrequest_status_code)
{
phantom_token_module_context_t *module_context = (phantom_token_module_context_t*)data;
ngx_str_t cache_data = ngx_null_string;
u_char *jwt_start = NULL;
size_t jwt_len = 0;
size_t bearer_jwt_len = 0;
u_char *p = NULL;
size_t body_buffer_size = 0;
bool read_response = false;
module_context->status = request->headers_out.status;
// fail early for not 200 response
if (request->headers_out.status != NGX_HTTP_OK)
{
ngx_log_error(NGX_LOG_ERR, request->connection->log, 0,
"Subrequest to %V failed with response code: %d",
&request->uri, request->headers_out.status);
module_context->done = 1;
return introspection_subrequest_status_code;
}
#if (NGX_HTTP_CACHE)
// When caching is enabled, the introspection response is read from the cache, including the first request with a new opaque access token
if (request->cache && !request->cache->buf)
{
// We have a cache but it's not primed
ngx_http_file_cache_open(request);
}
if (request->cache && request->cache->buf && request->cache->valid_sec > 0)
{
cache_data.len = request->cache->length;
cache_data.data = ngx_pnalloc(request->pool, cache_data.len);