forked from atomx/nginx-http-auth-digest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngx_http_auth_digest_module.c
1867 lines (1553 loc) · 53.1 KB
/
ngx_http_auth_digest_module.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 (c) Erik Dubbelboer
* fork from nginx-http-auth-digest (c) samizdat drafting co.
* derived from http_auth_basic (c) igor sysoev
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_md5.h>
#include "ngx_http_auth_digest_module.h"
//#include "auth.h"
#if _WIN32
#include <Windows.h>
#include <LMCons.h>
#endif
static void* ngx_http_auth_digest_create_loc_conf(ngx_conf_t* cf) {
ngx_http_auth_digest_loc_conf_t* conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_auth_digest_loc_conf_t));
if (conf == NULL) {
return NULL;
}
conf->timeout = NGX_CONF_UNSET_UINT;
conf->expires = NGX_CONF_UNSET_UINT;
conf->drop_time = NGX_CONF_UNSET_UINT;
conf->replays = NGX_CONF_UNSET_UINT;
conf->evasion_time = NGX_CONF_UNSET_UINT;
conf->maxtries = NGX_CONF_UNSET_UINT;
return conf;
}
static char* ngx_http_auth_digest_merge_loc_conf(ngx_conf_t* cf, void* parent, void* child) {
ngx_http_auth_digest_loc_conf_t* prev = parent;
ngx_http_auth_digest_loc_conf_t* conf = child;
ngx_conf_merge_sec_value(conf->timeout, prev->timeout, 60);
ngx_conf_merge_sec_value(conf->expires, prev->expires, 10);
ngx_conf_merge_sec_value(conf->drop_time, prev->drop_time, 300);
ngx_conf_merge_value(conf->replays, prev->replays, 20);
ngx_conf_merge_sec_value(conf->evasion_time, prev->evasion_time, 300);
ngx_conf_merge_value(conf->maxtries, prev->maxtries, 5);
ngx_conf_merge_str_value(conf->allow_localhost, prev->allow_localhost, "off");
ngx_conf_merge_str_value(conf->user_agents_allow_basic, prev->user_agents_allow_basic, "");
ngx_conf_merge_str_value(conf->use_basic, prev->use_basic, "off");
if (conf->user_file.value.len == 0) {
conf->user_file = prev->user_file;
}
if (conf->realm.value.len == 0) {
conf->realm = prev->realm;
}
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_auth_digest_init(ngx_conf_t* cf) {
ngx_http_handler_pt* h;
ngx_http_core_main_conf_t* cmcf;
ngx_str_t* shm_name;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_ACCESS_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_auth_digest_handler;
ngx_http_auth_digest_cleanup_timer = ngx_pcalloc(cf->pool, sizeof(ngx_event_t));
if (ngx_http_auth_digest_cleanup_timer == NULL) {
return NGX_ERROR;
}
shm_name = ngx_palloc(cf->pool, sizeof * shm_name);
shm_name->len = sizeof("auth_digest");
shm_name->data = (unsigned char*)"auth_digest";
if (ngx_http_auth_digest_shm_size == 0) {
ngx_http_auth_digest_shm_size = 4 * 256 * ngx_pagesize; // default to 4mb
}
ngx_http_auth_digest_shm_zone = ngx_shared_memory_add(cf, shm_name, ngx_http_auth_digest_shm_size, &ngx_http_auth_digest_module);
if (ngx_http_auth_digest_shm_zone == NULL) {
return NGX_ERROR;
}
ngx_http_auth_digest_shm_zone->init = ngx_http_auth_digest_init_shm_zone;
return NGX_OK;
}
static ngx_int_t ngx_http_auth_digest_worker_init(ngx_cycle_t* cycle) {
if (ngx_process != NGX_PROCESS_WORKER) {
return NGX_OK;
}
// create a cleanup queue big enough for the max number of tree nodes in the
// shm
ngx_http_auth_digest_cleanup_list = ngx_array_create(cycle->pool, NGX_HTTP_AUTH_DIGEST_CLEANUP_BATCH_SIZE, sizeof(ngx_rbtree_node_t*));
if (ngx_http_auth_digest_cleanup_list == NULL) {
ngx_log_error(NGX_LOG_EMERG, cycle->log, 0, "Could not allocate shared memory for auth_digest");
return NGX_ERROR;
}
ngx_connection_t* dummy = ngx_pcalloc(cycle->pool, sizeof(ngx_connection_t));
if (dummy == NULL) {
return NGX_ERROR;
}
dummy->fd = (ngx_socket_t)-1;
dummy->data = cycle;
ngx_http_auth_digest_cleanup_timer->log = ngx_cycle->log;
ngx_http_auth_digest_cleanup_timer->data = dummy;
ngx_http_auth_digest_cleanup_timer->handler = ngx_http_auth_digest_cleanup;
ngx_add_timer(ngx_http_auth_digest_cleanup_timer, NGX_HTTP_AUTH_DIGEST_CLEANUP_INTERVAL);
return NGX_OK;
}
static ngx_int_t DoBasic(ngx_http_request_t* r) {
ngx_str_t realm;
realm.len = 0;
realm.data = (u_char*)"";
if (ngx_http_auth_os_handler(r) == NGX_OK) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_handler-> Allowing %s past", r->headers_in.user_agent);
//ngx_free(whitelist);
return NGX_OK;
}
else {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_handler-> About to challenge %s basic auth", r->headers_in.user_agent);
return ngx_http_auth_os_set_realm(r, &realm);
}
}
static ngx_int_t ngx_http_auth_digest_handler(ngx_http_request_t* r) {
off_t offset;
ssize_t n;
ngx_fd_t fd;
ngx_int_t rc;
ngx_err_t err;
ngx_str_t user_file, passwd_line, realm;
ngx_file_t file;
ngx_uint_t i, begin, tail, idle;
ngx_http_auth_digest_loc_conf_t* alcf;
ngx_http_auth_digest_cred_t* auth_fields;
u_char buf[NGX_HTTP_AUTH_DIGEST_BUF_SIZE];
u_char line[NGX_HTTP_AUTH_DIGEST_BUF_SIZE];
u_char* p;
if (r->internal) {
return NGX_DECLINED;
}
// if digest auth is disabled for this location, bail out immediately
alcf = ngx_http_get_module_loc_conf(r, ngx_http_auth_digest_module);
// if localhost bypass, bail out immediately
const int isLocalHost = ngx_http_auth_digest_is_loopback(&(r->headers_in.server)) == 0;
if (isLocalHost) {
const int isLocalHostBypass = ngx_strcmp(alcf->allow_localhost.data, "on") == 0;
if (isLocalHostBypass) {
return NGX_DECLINED;
}
}
if (ngx_http_auth_digest_is_sending_basic(r)) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_handler-> about to validate preauth basic header :(");
return ngx_http_auth_os_handler(r);
}
const int useBasic = ngx_strcmp(alcf->use_basic.data, "on") == 0;
if (useBasic) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "using basic");
return DoBasic(r);
}
else if (r->headers_in.user_agent != NULL) {
u_char* whitelist = (u_char*)ngx_calloc(alcf->user_agents_allow_basic.len, r->connection->log);
ngx_cpystrn(whitelist, alcf->user_agents_allow_basic.data, alcf->user_agents_allow_basic.len + 1);
char* token = strtok((char*)whitelist, ",");
while (token != NULL) {
if (ngx_strstr(r->headers_in.user_agent->value.data, token)) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_handler-> is %s", r->headers_in.user_agent);
return DoBasic(r);
}
token = strtok(NULL, ",");
}
}
if (alcf->realm.value.len == 0) {
return NGX_DECLINED;
}
if (ngx_http_complex_value(r, &alcf->realm, &realm) != NGX_OK) {
return NGX_ERROR;
}
if (realm.len == 0 || alcf->user_file.value.len == 0) {
return NGX_DECLINED;
}
if (ngx_strcmp(realm.data, "off") == 0) {
return NGX_DECLINED;
}
if (ngx_http_auth_digest_evading(r, alcf)) {
return NGX_HTTP_UNAUTHORIZED;
}
// unpack the Authorization header (if any) and verify that it contains all
// required fields. otherwise send a challenge
auth_fields = ngx_pcalloc(r->pool, sizeof(ngx_http_auth_digest_cred_t));
rc = ngx_http_auth_digest_check_credentials(r, auth_fields);
if (rc == NGX_DECLINED) {
return ngx_http_auth_digest_send_challenge(r, &realm, 0);
}
else if (rc == NGX_ERROR) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
// check for the existence of a passwd file and attempt to open it
if (ngx_http_complex_value(r, &alcf->user_file, &user_file) != NGX_OK) {
return NGX_ERROR;
}
fd = ngx_open_file(user_file.data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0);
if (fd == NGX_INVALID_FILE) {
ngx_uint_t level;
err = ngx_errno;
if (err == NGX_ENOENT) {
level = NGX_LOG_ERR;
rc = NGX_HTTP_FORBIDDEN;
}
else {
level = NGX_LOG_CRIT;
rc = NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_log_error(level, r->connection->log, err,
ngx_open_file_n " \"%s\" failed", user_file.data);
return rc;
}
ngx_memzero(&file, sizeof(ngx_file_t));
file.fd = fd;
file.name = user_file;
file.log = r->connection->log;
// step through the passwd file and find the individual lines, then pass them
// off to be compared against the values in the authorization header
passwd_line.data = line;
offset = begin = tail = 0;
idle = 1;
ngx_memzero(buf, NGX_HTTP_AUTH_DIGEST_BUF_SIZE);
ngx_memzero(passwd_line.data, NGX_HTTP_AUTH_DIGEST_BUF_SIZE);
while (1) {
n = ngx_read_file(&file, buf + tail, NGX_HTTP_AUTH_DIGEST_BUF_SIZE - tail, offset);
if (n == NGX_ERROR) {
ngx_http_auth_digest_close(&file);
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
begin = 0;
for (i = 0; i < n + tail; i++) {
if (buf[i] == '\n' || buf[i] == '\r') {
if (!idle && i - begin > 36) { // 36 is the min length with a single-char name and realm
p = ngx_cpymem(passwd_line.data, &buf[begin], i - begin);
p[0] = '\0';
passwd_line.len = i - begin;
rc = ngx_http_auth_digest_verify_user(r, auth_fields, &passwd_line);
if (rc == NGX_HTTP_AUTH_DIGEST_USERNOTFOUND) {
rc = NGX_DECLINED;
}
if (rc != NGX_DECLINED) {
ngx_http_auth_digest_close(&file);
ngx_http_auth_digest_evasion_tracking(r, alcf, NGX_HTTP_AUTH_DIGEST_STATUS_SUCCESS);
return rc;
}
}
idle = 1;
begin = i;
}
else if (idle) {
idle = 0;
begin = i;
}
}
if (!idle) {
tail = n + tail - begin;
if (n == 0 && tail > 36) {
p = ngx_cpymem(passwd_line.data, &buf[begin], tail);
p[0] = '\0';
passwd_line.len = i - begin;
rc = ngx_http_auth_digest_verify_user(r, auth_fields, &passwd_line);
if (rc == NGX_HTTP_AUTH_DIGEST_USERNOTFOUND) {
rc = NGX_DECLINED;
}
if (rc != NGX_DECLINED) {
ngx_http_auth_digest_close(&file);
ngx_http_auth_digest_evasion_tracking(
r, alcf, NGX_HTTP_AUTH_DIGEST_STATUS_SUCCESS);
return rc;
}
}
else {
ngx_memmove(buf, &buf[begin], tail);
}
}
if (n == 0) {
break;
}
offset += n;
}
ngx_http_auth_digest_close(&file);
// log only wrong username/password,
// not expired hash
int nc = ngx_hextoi(auth_fields->nc.data, auth_fields->nc.len);
if (nc == 1) {
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid username or password for %*s", auth_fields->username.len, auth_fields->username.data);
}
ngx_http_auth_digest_evasion_tracking(r, alcf, NGX_HTTP_AUTH_DIGEST_STATUS_FAILURE);
// since no match was found based on the fields in the authorization header,
// send a new challenge and let the client retry
return ngx_http_auth_digest_send_challenge(r, &realm, auth_fields->stale);
}
static ngx_int_t ngx_http_auth_digest_is_sending_basic(ngx_http_request_t* r) {
return (r->headers_in.authorization != NULL && ngx_strstr(r->headers_in.authorization->value.data, "Basic"));
}
ngx_int_t ngx_http_auth_digest_check_credentials(ngx_http_request_t* r, ngx_http_auth_digest_cred_t* ctx) {
if (r->headers_in.authorization == NULL) {
return NGX_DECLINED;
}
/*
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
*/
static uint32_t token_char[] = {
0x00000000, /* 0000 0000 0000 0000 0000 0000 0000 0000 */
/* ?>=< ;:98 7654 3210 /.-, +*)( '&%$ #"! */
0x03ff6cf8, /* 0000 0011 1111 1111 0110 1100 1111 1000 */
/* _^]\ [ZYX WVUT SRQP ONML KJIH GFED CBA@ */
0xc7fffffe, /* 1100 0111 1111 1111 1111 1111 1111 1110 */
/* ~}| {zyx wvut srqp onml kjih gfed cba` */
0x57ffffff, /* 0101 0111 1111 1111 1111 1111 1111 1111 */
0x00000000, /* 0000 0000 0000 0000 0000 0000 0000 0000 */
0x00000000, /* 0000 0000 0000 0000 0000 0000 0000 0000 */
0x00000000, /* 0000 0000 0000 0000 0000 0000 0000 0000 */
0x00000000, /* 0000 0000 0000 0000 0000 0000 0000 0000 */
};
uint32_t in_value;
u_char ch, * p, * last, * start = 0, * end;
ngx_str_t name, value;
ngx_int_t comma_count = 0, quoted_pair_count = 0;
name.data = 0;
name.len = 0;
value.data = 0;
value.len = 0;
enum
{
sw_start = 0,
sw_scheme,
sw_scheme_end,
sw_lws_start,
sw_lws,
sw_param_name_start,
sw_param_name,
sw_param_value_start,
sw_param_value,
sw_param_quoted_value,
sw_param_end,
sw_error,
} state;
ngx_str_t encoded = r->headers_in.authorization->value;
state = sw_start;
p = encoded.data;
last = encoded.data + encoded.len;
ch = *p++;
while (p <= last) {
switch (state) {
default:
case sw_error:
return NGX_DECLINED;
/* first char */
case sw_start:
if (ch == CR || ch == LF || ch == ' ' || ch == '\t') {
ch = *p++;
}
else if (token_char[ch >> 5] & (1 << (ch & 0x1f))) {
start = p - 1;
state = sw_scheme;
}
else {
state = sw_error;
}
break;
case sw_scheme:
if (token_char[ch >> 5] & (1 << (ch & 0x1f))) {
ch = *p++;
}
else if (ch == ' ') {
end = p - 1;
state = sw_scheme_end;
ctx->auth_scheme.data = start;
ctx->auth_scheme.len = end - start;
if (ngx_strncasecmp(ctx->auth_scheme.data, (u_char*)"Digest", ctx->auth_scheme.len) != 0) {
state = sw_error;
}
}
else {
state = sw_error;
}
break;
case sw_scheme_end:
if (ch == ' ') {
ch = *p++;
}
else {
state = sw_param_name_start;
}
break;
case sw_lws_start:
comma_count = 0;
state = sw_lws;
/* fall through */
case sw_lws:
if (comma_count > 0 && (token_char[ch >> 5] & (1 << (ch & 0x1f)))) {
state = sw_param_name_start;
}
else if (ch == ',') {
comma_count++;
ch = *p++;
}
else if (ch == CR || ch == LF || ch == ' ' || ch == '\t') {
ch = *p++;
}
else {
state = sw_error;
}
break;
case sw_param_name_start:
if (token_char[ch >> 5] & (1 << (ch & 0x1f))) {
start = p - 1;
state = sw_param_name;
ch = *p++;
}
else {
state = sw_error;
}
break;
case sw_param_name:
if (token_char[ch >> 5] & (1 << (ch & 0x1f))) {
ch = *p++;
}
else if (ch == '=') {
end = p - 1;
state = sw_param_value_start;
name.data = start;
name.len = end - start;
ch = *p++;
}
else {
state = sw_error;
}
break;
case sw_param_value_start:
if (token_char[ch >> 5] & (1 << (ch & 0x1f))) {
start = p - 1;
state = sw_param_value;
ch = *p++;
}
else if (ch == '\"') {
start = p;
quoted_pair_count = 0;
state = sw_param_quoted_value;
ch = *p++;
}
else {
state = sw_error;
}
break;
case sw_param_value:
in_value = token_char[ch >> 5] & (1 << (ch & 0x1f));
if (in_value) {
ch = *p++;
}
if (!in_value || p > last) {
end = p - 1;
value.data = start;
value.len = end - start;
state = sw_param_end;
goto param_end;
}
break;
case sw_param_quoted_value:
if (ch < 0x20 || ch == 0x7f) {
state = sw_error;
}
else if (ch == '\\' && *p <= 0x7f) {
quoted_pair_count++;
/* Skip the next char, even if it's a \ */
ch = *(p += 2);
}
else if (ch == '\"') {
end = p - 1;
ch = *p++;
value.data = start;
value.len = end - start - quoted_pair_count;
if (quoted_pair_count > 0) {
value.data = ngx_palloc(r->pool, value.len);
u_char* d = value.data;
u_char* s = start;
for (; s < end; s++) {
ch = *s;
if (ch == '\\') {
/* Make sure to add the next character
* even if it's a \
*/
s++;
if (s < end) {
*d++ = ch;
}
continue;
}
*d++ = ch;
}
}
state = sw_param_end;
goto param_end;
}
else {
ch = *p++;
}
break;
param_end:
case sw_param_end:
if (ngx_strncasecmp(name.data, (u_char*)"username", name.len) == 0) {
ctx->username = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"qop", name.len) == 0) {
ctx->qop = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"realm", name.len) == 0) {
ctx->realm = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"nonce", name.len) == 0) {
ctx->nonce = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"nc", name.len) == 0) {
ctx->nc = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"uri", name.len) == 0) {
ctx->uri = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"cnonce", name.len) ==
0) {
ctx->cnonce = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"response", name.len) ==
0) {
ctx->response = value;
}
else if (ngx_strncasecmp(name.data, (u_char*)"opaque", name.len) ==
0) {
ctx->opaque = value;
}
state = sw_lws_start;
break;
}
}
if (state != sw_lws_start && state != sw_lws) {
return NGX_DECLINED;
}
// bail out if anything but the opaque field is missing from the request
// header
if (!(ctx->username.len > 0 && ctx->qop.len > 0 && ctx->realm.len > 0 &&
ctx->nonce.len > 0 && ctx->nc.len > 0 && ctx->uri.len > 0 &&
ctx->cnonce.len > 0 && ctx->response.len > 0) ||
ctx->nonce.len != 16) {
return NGX_DECLINED;
}
return NGX_OK;
}
static ngx_int_t ngx_http_auth_digest_verify_user(ngx_http_request_t* r, ngx_http_auth_digest_cred_t* fields, ngx_str_t* line) {
ngx_uint_t i, from, nomatch;
enum
{
sw_login,
sw_ha1,
sw_realm
} state;
state = sw_login;
from = 0;
nomatch = 0;
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_user %*s", fields->username.len, fields->username.data);
// step through a single line (of the passwd file), matching the username and
// realm
// character-by-character against the request's Authorization header fields
u_char* buf = line->data;
for (i = 0; i <= line->len; i++) {
u_char ch = buf[i];
switch (state) {
case sw_login:
if (ch == '#')
nomatch = 1;
if (ch == ':') {
if (fields->username.len != i)
nomatch = 1;
state = sw_realm;
from = i + 1;
}
else if (i > fields->username.len || ch != fields->username.data[i]) {
nomatch = 1;
}
break;
case sw_realm:
if (ch == '#')
nomatch = 1;
if (ch == ':') {
if (fields->realm.len != i - from)
nomatch = 1;
state = sw_ha1;
from = i + 1;
}
else if (ch != fields->realm.data[i - from]) {
nomatch = 1;
}
break;
case sw_ha1:
if (ch == '\0' || ch == ':' || ch == '#' || ch == CR || ch == LF) {
if (i - from != 32)
nomatch = 1;
}
break;
}
}
if (nomatch) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_user => NGX_HTTP_AUTH_DIGEST_USERNOTFOUND %*s", fields->username.len, fields->username.data);
return NGX_HTTP_AUTH_DIGEST_USERNOTFOUND;
}
return ngx_http_auth_digest_verify_hash(r, fields, &buf[from]);
}
static ngx_int_t ngx_http_auth_digest_verify_hash(ngx_http_request_t* r, ngx_http_auth_digest_cred_t* fields, u_char* hashed_pw) {
u_char* p;
ngx_str_t http_method;
ngx_str_t HA1, HA2, ha2_key;
ngx_str_t digest, digest_key;
ngx_md5_t md5;
u_char hash[16];
// The .net Http library sends the incorrect URI as part of the Authorization
// response. Instead of the complete URI including the query parameters it
// sends only the basic URI without the query parameters. It also uses this
// value in the calculations.
// To be compatible with the .net library the following change is made to this
// module:
// - Compare the URI in the Authorization (A-URI) with the request URI (R-URI).
// - If A-URI and R-URI are identical verify is executed.
// - If A-URI and R-URI are identical up to the '?' verify is executed
// - Otherwise the check is not executed and authorization is declined
if (!((r->unparsed_uri.len == fields->uri.len) &&
(ngx_strncmp(r->unparsed_uri.data, fields->uri.data, fields->uri.len) == 0))) {
if (!((r->unparsed_uri.len > fields->uri.len) &&
(ngx_strncmp(r->unparsed_uri.data, fields->uri.data, fields->uri.len) == 0) &&
(r->unparsed_uri.data[fields->uri.len] == '?'))) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash->.NET check NGX_DECLINED %*s", fields->username.len, fields->username.data);
return NGX_DECLINED;
}
}
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash %*s", fields->username.len, fields->username.data);
// the hashing scheme:
// digest:
// MD5(MD5(username:realm:password):nonce:nc:cnonce:qop:MD5(method:uri))
// ^- HA1 ^- HA2
// verify: fields->response ==
// MD5($hashed_pw:nonce:nc:cnonce:qop:MD5(method:uri))
// ha1 was precalculated and saved to the passwd file:
// md5(username:realm:password)
HA1.len = 33;
HA1.data = ngx_pcalloc(r->pool, HA1.len);
p = ngx_cpymem(HA1.data, hashed_pw, 32);
// calculate ha2: md5(method:uri)
http_method.len = r->method_name.len + 1;
http_method.data = ngx_pcalloc(r->pool, http_method.len);
if (http_method.data == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
p = ngx_cpymem(http_method.data, r->method_name.data, r->method_name.len);
ha2_key.len = http_method.len + fields->uri.len + 1;
ha2_key.data = ngx_pcalloc(r->pool, ha2_key.len);
if (ha2_key.data == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
p = ngx_cpymem(ha2_key.data, http_method.data, http_method.len - 1);
*p++ = ':';
p = ngx_cpymem(p, fields->uri.data, fields->uri.len);
HA2.len = 33;
HA2.data = ngx_pcalloc(r->pool, HA2.len);
ngx_md5_init(&md5);
ngx_md5_update(&md5, ha2_key.data, ha2_key.len - 1);
ngx_md5_final(hash, &md5);
ngx_hex_dump(HA2.data, hash, 16);
// calculate digest: md5(ha1:nonce:nc:cnonce:qop:ha2)
digest_key.len = HA1.len - 1 + fields->nonce.len + fields->nc.len +
fields->cnonce.len + fields->qop.len + HA2.len - 1 + 5 + 1;
digest_key.data = ngx_pcalloc(r->pool, digest_key.len);
if (digest_key.data == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
p = ngx_cpymem(digest_key.data, HA1.data, HA1.len - 1);
*p++ = ':';
p = ngx_cpymem(p, fields->nonce.data, fields->nonce.len);
*p++ = ':';
p = ngx_cpymem(p, fields->nc.data, fields->nc.len);
*p++ = ':';
p = ngx_cpymem(p, fields->cnonce.data, fields->cnonce.len);
*p++ = ':';
p = ngx_cpymem(p, fields->qop.data, fields->qop.len);
*p++ = ':';
p = ngx_cpymem(p, HA2.data, HA2.len - 1);
digest.len = 33;
digest.data = ngx_pcalloc(r->pool, 33);
if (digest.data == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_md5_init(&md5);
ngx_md5_update(&md5, digest_key.data, digest_key.len - 1);
ngx_md5_final(hash, &md5);
ngx_hex_dump(digest.data, hash, 16);
// compare the hash of the full digest string to the response field of the
// auth header
// and bail out if they don't match
if (fields->response.len != digest.len - 1 ||
ngx_memcmp(digest.data, fields->response.data, fields->response.len) != 0) {
return NGX_DECLINED;
}
ngx_http_auth_digest_nonce_t nonce;
ngx_uint_t key;
ngx_http_auth_digest_node_t* found;
ngx_slab_pool_t* shpool;
ngx_http_auth_digest_loc_conf_t* alcf;
ngx_table_elt_t* info_header;
ngx_str_t hkey, hval;
shpool = (ngx_slab_pool_t*)ngx_http_auth_digest_shm_zone->shm.addr;
alcf = ngx_http_get_module_loc_conf(r, ngx_http_auth_digest_module);
nonce.rnd = ngx_hextoi(fields->nonce.data, 8);
nonce.t = ngx_hextoi(&fields->nonce.data[8], 8);
key = ngx_crc32_short((u_char*)&nonce.rnd, sizeof nonce.rnd) ^
ngx_crc32_short((u_char*)&nonce.t, sizeof(nonce.t));
int nc = ngx_hextoi(fields->nc.data, fields->nc.len);
if (nc < 0 || nc >= alcf->replays) {
fields->stale = 1;
return NGX_DECLINED;
}
// make sure nonce and nc are both valid
ngx_shmtx_lock(&shpool->mutex);
found = (ngx_http_auth_digest_node_t*)ngx_http_auth_digest_rbtree_find(key, ngx_http_auth_digest_rbtree->root, ngx_http_auth_digest_rbtree->sentinel);
if (found != NULL) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash nonce and nc are both valid");
if (found->expires <= ngx_time()) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash, failed (found->expires <= ngx_time())");
fields->stale = 1;
goto invalid;
}
if (!ngx_bitvector_test(found->nc, nc)) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash, failed-> (ngx_bitvector_test(found->nc, nc))");
goto invalid;
}
if (ngx_bitvector_test(found->nc, 0)) {
// if this is the first use of this nonce, switch the expiration time from
// the timeout
// param to now+expires. using the 0th element of the nc vector to flag
// this...
ngx_bitvector_set(found->nc, 0);
found->expires = ngx_time() + alcf->expires;
found->drop_time = ngx_time() + alcf->drop_time;
}
// mark this nc as ‘used’ to prevent replays
ngx_bitvector_set(found->nc, nc);
// todo: if the bitvector is now ‘full’, could preemptively expire the node
// from the rbtree
// ngx_rbtree_delete(ngx_http_auth_digest_rbtree, found);
// ngx_slab_free_locked(shpool, found);
ngx_shmtx_unlock(&shpool->mutex);
// recalculate the digest with a modified HA2 value (for rspauth) and emit
// the
// Authentication-Info header
ngx_memset(ha2_key.data, 0, ha2_key.len);
p = ngx_snprintf(ha2_key.data, 1 + fields->uri.len, ":%s", fields->uri.data);
ngx_memset(HA2.data, 0, HA2.len);
ngx_md5_init(&md5);
ngx_md5_update(&md5, ha2_key.data, 1 + fields->uri.len);
ngx_md5_final(hash, &md5);
ngx_hex_dump(HA2.data, hash, 16);
ngx_memset(digest_key.data, 0, digest_key.len);
p = ngx_cpymem(digest_key.data, HA1.data, HA1.len - 1);
*p++ = ':';
p = ngx_cpymem(p, fields->nonce.data, fields->nonce.len);
*p++ = ':';
p = ngx_cpymem(p, fields->nc.data, fields->nc.len);
*p++ = ':';
p = ngx_cpymem(p, fields->cnonce.data, fields->cnonce.len);
*p++ = ':';
p = ngx_cpymem(p, fields->qop.data, fields->qop.len);
*p++ = ':';
p = ngx_cpymem(p, HA2.data, HA2.len - 1);
ngx_md5_init(&md5);
ngx_md5_update(&md5, digest_key.data, digest_key.len - 1);
ngx_md5_final(hash, &md5);
ngx_hex_dump(digest.data, hash, 16);
ngx_str_set(&hkey, "Authentication-Info");
// sizeof() includes the null terminator, and digest.len also counts its
// null terminator
hval.len = sizeof("qop=\"auth\", rspauth=\"\", cnonce=\"\", nc=") +
fields->cnonce.len + fields->nc.len + digest.len - 2;
hval.data = ngx_pcalloc(r->pool, hval.len + 1);
if (hval.data == NULL) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash (hval.data == NULL) NGX_HTTP_INTERNAL_SERVER_ERROR");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
p = ngx_snprintf(hval.data, hval.len, "qop=\"auth\", rspauth=\"%*s\", cnonce=\"%*s\", nc=%*s", digest.len - 1, digest.data, fields->cnonce.len, fields->cnonce.data, fields->nc.len, fields->nc.data);
info_header = ngx_list_push(&r->headers_out.headers);
if (info_header == NULL) {
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ngx_http_auth_digest_verify_hash (info_header == null) NGX_HTTP_INTERNAL_SERVER_ERROR");
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
info_header->key = hkey;
info_header->value = hval;
info_header->hash = 1;
return NGX_OK;
}
else {
invalid:
// nonce is invalid/expired or client reused an nc value. suspicious...
ngx_shmtx_unlock(&shpool->mutex);
return NGX_DECLINED;
}
}
// send digest challenge, this is what will trigger the browser prompt
static ngx_int_t ngx_http_auth_digest_send_challenge(ngx_http_request_t* r, ngx_str_t* realm, ngx_uint_t is_stale) {
ngx_str_t challenge;
u_char* p;
size_t realm_len = strnlen((const char*)realm->data, realm->len);
r->headers_out.www_authenticate = ngx_list_push(&r->headers_out.headers);
if (r->headers_out.www_authenticate == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
r->headers_out.www_authenticate->hash = 1;
ngx_str_set(&r->headers_out.www_authenticate->key, "WWW-Authenticate");
challenge.len = sizeof("Digest algorithm=\"MD5\", qop=\"auth\", realm=\"\", nonce=\"\"") - 1 + realm_len + 16;
if (is_stale) {
challenge.len += sizeof(", stale=\"true\"") - 1;
}
challenge.data = ngx_pnalloc(r->pool, challenge.len);
if (challenge.data == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_http_auth_digest_nonce_t nonce = ngx_http_auth_digest_next_nonce(r);
if (nonce.t == 0 && nonce.rnd == 0) {
// oom error when allocating nonce session in rbtree
return NGX_HTTP_SERVICE_UNAVAILABLE;
}
p = ngx_cpymem(challenge.data, "Digest algorithm=\"MD5\", qop=\"auth\", realm=\"", sizeof("Digest algorithm=\"MD5\", qop=\"auth\", realm=\"") - 1);
p = ngx_cpymem(p, realm->data, realm_len);
p = ngx_cpymem(p, "\", nonce=\"", sizeof("\", nonce=\"") - 1);
p = ngx_sprintf(p, "%08xl%08xl", nonce.rnd, nonce.t);
if (is_stale) {
p = ngx_cpymem(p, "\", stale=\"true\"", sizeof("\", stale=\"true\""));
}
else {
p = ngx_cpymem(p, "\"", sizeof("\""));
}
r->headers_out.www_authenticate->value = challenge;
return NGX_HTTP_UNAUTHORIZED;
}
static void ngx_http_auth_digest_close(ngx_file_t* file) {
if (ngx_close_file(file->fd) == NGX_FILE_ERROR) {
ngx_log_error(NGX_LOG_ALERT, file->log, ngx_errno, ngx_close_file_n " \"%s\" failed", file->name.data);
}
}