-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmod_auth_ticket.c
614 lines (516 loc) · 18.7 KB
/
mod_auth_ticket.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
//
// mod_auth_ticket - Authentication based on signed cookie
//
// This module protects webpage from clients without valid
// cookie. By redirecting not-yet-valid clients to certain
// "logon page", you can protect any webapp without adding
// any auth code to webapp itself.
//
// Unlike mod_authcookie for Apache, this DOES NOT work
// with mod_auth_* modules due to lighttpd limitation (there's
// no way to turn 401 response into page redirection).
// This module solely relies on external "logon page" for
// authentication, and expect it to provide a valid cookie as a
// ticket for authenticated access.
//
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "plugin.h"
#include "log.h"
#include "response.h"
#include "md5.h"
#define VER_ID(major, minor, relno) ((major) << 16 | (minor) << 8 | (relno))
// Compatibility macros to use this module with older lighttpd versions.
// With svn commit r2788, MD5* APIs were renamed to li_MD5*.
#if LIGHTTPD_VERSION_ID < VER_ID(1, 4, 29)
#define li_MD5_CTX MD5_CTX
#define li_MD5_Init MD5_Init
#define li_MD5_Update MD5_Update
#define li_MD5_Final MD5_Final
#endif
#include "base64.h"
#define LOG(level, ...) \
if (pc->loglevel >= level) { \
log_error_write(srv, __FILE__, __LINE__, __VA_ARGS__); \
}
#define FATAL(...) LOG(0, __VA_ARGS__)
#define ERROR(...) LOG(1, __VA_ARGS__)
#define WARN(...) LOG(2, __VA_ARGS__)
#define INFO(...) LOG(3, __VA_ARGS__)
#define DEBUG(...) LOG(4, __VA_ARGS__)
#define HEADER(con, key) \
(data_string *)array_get_element((con)->request.headers, (key))
#define MD5_LEN 16
/**********************************************************************
* data strutures
**********************************************************************/
// module configuration
typedef struct {
int loglevel;
buffer *name; // cookie name to extract auth info
int override; // how to handle incoming Auth header
buffer *authurl; // page to go when unauthorized
buffer *key; // key for cookie verification
int timeout; // life duration of last-stage auth token
buffer *options; // options for last-stage auth token cookie
} plugin_config;
// top-level module structure
typedef struct {
PLUGIN_DATA;
plugin_config **config;
plugin_config conf;
array *users;
} plugin_data;
/**********************************************************************
* supporting functions
**********************************************************************/
//
// helper to generate "configuration in current context".
//
static plugin_config *
merge_config(server *srv, connection *con, plugin_data *pd) {
#define PATCH(x) pd->conf.x = pc->x
#define MATCH(k) if (buffer_is_equal_string(du->key, CONST_STR_LEN(k)))
#define MERGE(k, x) MATCH(k) PATCH(x)
size_t i, j;
plugin_config *pc = pd->config[0]; // start from global context
// load initial config in global context
PATCH(loglevel);
PATCH(name);
PATCH(override);
PATCH(authurl);
PATCH(key);
PATCH(timeout);
PATCH(options);
// merge config from sub-contexts
for (i = 1; i < srv->config_context->used; i++) {
data_config *dc = (data_config *)srv->config_context->data[i];
// condition didn't match
if (! config_check_cond(srv, con, dc)) continue;
// merge config
pc = pd->config[i];
for (j = 0; j < dc->value->used; j++) {
data_unset *du = dc->value->data[j];
// describe your merge-policy here...
MERGE("auth-ticket.loglevel", loglevel);
MERGE("auth-ticket.name", name);
MERGE("auth-ticket.override", override);
MERGE("auth-ticket.authurl", authurl);
MERGE("auth-ticket.key", key);
MERGE("auth-ticket.timeout", timeout);
MERGE("auth-ticket.options", options);
}
}
return &(pd->conf);
#undef PATCH
#undef MATCH
#undef MERGE
}
//
// fills (appends) given buffer with "current" URL.
//
static buffer *
self_url(connection *con, buffer *url, buffer_encoding_t enc) {
buffer_append_string_encoded(url, CONST_BUF_LEN(con->uri.scheme), enc);
buffer_append_string_encoded(url, CONST_STR_LEN("://"), enc);
buffer_append_string_encoded(url, CONST_BUF_LEN(con->uri.authority), enc);
buffer_append_string_encoded(url, CONST_BUF_LEN(con->request.uri), enc);
return url;
}
//
// Generates appropriate response depending on policy.
//
static handler_t
endauth(server *srv, connection *con, plugin_config *pc) {
// pass through if no redirect target is specified
if (buffer_is_empty(pc->authurl)) {
DEBUG("s", "endauth - continuing");
return HANDLER_GO_ON;
}
DEBUG("sb", "endauth - redirecting:", pc->authurl);
// prepare redirection header
buffer *url = buffer_init_buffer(pc->authurl);
buffer_append_string(url, strchr(url->ptr, '?') ? "&url=" : "?url=");
self_url(con, url, ENCODING_REL_URI);
response_header_insert(srv, con,
CONST_STR_LEN("Location"), CONST_BUF_LEN(url));
buffer_free(url);
// prepare response
con->http_status = 307;
con->mode = DIRECT;
con->file_finished = 1;
return HANDLER_FINISHED;
}
inline static int
min(int a, int b) {
return a > b ? b : a;
}
// generate hex-encoded random string
static int
gen_random(buffer *b, int len) {
buffer_prepare_append(b, len);
while (len--) {
char c = int2hex(rand() >> 24);
buffer_append_memory(b, &c, 1);
}
return 0;
}
// encode bytes into hexstring
static int
hex_encode(buffer *b, const uint8_t *s, int len) {
return buffer_copy_string_hex(b, (const char *)s, len);
}
// decode hexstring into bytes
static int
hex_decode(buffer *b, const char *s) {
char c0, c1;
buffer_prepare_append(b, strlen(s) >> 1);
while ((c0 = *s++) && (c1 = *s++)) {
char v = (hex2int(c0) << 4) | hex2int(c1);
buffer_append_memory(b, &v, 1);
}
return 0;
}
#if 0
// XOR-based decryption
// This is not used in this module - it is only provided as an
// example of supported encryption.
static int __attribute__((unused))
encrypt(buffer *buf, uint8_t *key, int keylen) {
unsigned int i;
for (i = 0; i < buf->used; i++) {
buf->ptr[i] ^= (i > 0 ? buf->ptr[i - 1] : 0) ^ key[i % keylen];
}
return 0;
}
#endif
// XOR-based encryption
static int
decrypt(buffer *buf, uint8_t *key, int keylen) {
int i;
for (i = buf->used - 1; i >= 0; i--) {
buf->ptr[i] ^= (i > 0 ? buf->ptr[i - 1] : 0) ^ key[i % keylen];
// sanity check - result should be base64-encoded authinfo
if (! isprint(buf->ptr[i])) {
return -1;
}
}
return 0;
}
//
// update header using (verified) authentication info.
//
static void
update_header(server *srv, connection *con,
plugin_data *pd, plugin_config *pc, buffer *authinfo) {
buffer *field, *token;
//DEBUG("sb", "decrypted authinfo:", authinfo);
// insert auth header
field = buffer_init_string("Basic ");
//rescbr: bugfix: authinfo does not end with \0
buffer_append_string_len(field, authinfo->ptr, authinfo->used);
array_set_key_value(con->request.headers,
CONST_STR_LEN("Authorization"), CONST_BUF_LEN(field));
// generate random token and relate it with authinfo
gen_random(token = buffer_init(), MD5_LEN * 2); // length in hex string
DEBUG("sb", "pairing authinfo with token:", token);
buffer_copy_long(field, time(NULL));
buffer_append_string(field, ":");
//rescbr: bugfix: authinfo does not end with \0
buffer_append_string_len(field, authinfo->ptr, authinfo->used);
array_set_key_value(pd->users, CONST_BUF_LEN(token), CONST_BUF_LEN(field));
// insert opaque auth token
buffer_copy_string_buffer(field, pc->name);
buffer_append_string(field, "=token:");
buffer_append_string_buffer(field, token);
buffer_append_string(field, "; ");
buffer_append_string_buffer(field, pc->options);
DEBUG("sb", "generating token cookie:", field);
response_header_append(srv, con,
CONST_STR_LEN("Set-Cookie"), CONST_BUF_LEN(field));
// update REMOTE_USER field
base64_decode(field, authinfo->ptr);
char *pw = strchr(field->ptr, ':'); *pw = '\0';
DEBUG("ss", "identified username:", field->ptr);
#if LIGHTTPD_VERSION_ID < VER_ID(1, 4, 33)
buffer_copy_string_len(con->authed_user, field->ptr, strlen(field->ptr));
#else
data_string *ds;
if (NULL == (ds = (data_string *)array_get_element(con->environment, "REMOTE_USER"))) {
if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
ds = data_string_init();
}
buffer_copy_string(ds->key, "REMOTE_USER");
array_insert_unique(con->environment, (data_unset *)ds);
}
buffer_copy_string_len(ds->value, field->ptr, strlen(field->ptr));
#endif
buffer_free(field);
buffer_free(token);
}
//
// Handle token given in cookie.
//
// Expected Cookie Format:
// <name>=token:<random-token-to-be-verified>
//
static handler_t
handle_token(server *srv, connection *con,
plugin_data *pd, plugin_config *pc, char *token) {
data_string *entry =
(data_string *)array_get_element(pd->users, token);
// Check for existence
if (! entry) return endauth(srv, con, pc);
DEBUG("sb", "found token entry:", entry->value);
// Check for timeout
time_t t0 = time(NULL);
time_t t1 = strtol(entry->value->ptr, NULL, 10);
DEBUG("sdsdsd", "t0:", t0, ", t1:", t1, ", timeout:", pc->timeout);
if (t0 - t1 > pc->timeout) return endauth(srv, con, pc);
// Check for existence of actual authinfo
char *authinfo = strchr(entry->value->ptr, ':');
if (! authinfo) return endauth(srv, con, pc);
// All passed. Inject as BasicAuth header
buffer *field = buffer_init_string("Basic ");
buffer_append_string(field, authinfo + 1);
array_set_key_value(con->request.headers,
CONST_STR_LEN("Authorization"), CONST_BUF_LEN(field));
// update REMOTE_USER field
base64_decode(field, authinfo + 1);
char *pw = strchr(field->ptr, ':'); *pw = '\0';
DEBUG("ss", "identified user:", field->ptr);
#if LIGHTTPD_VERSION_ID < VER_ID(1, 4, 33)
buffer_copy_string_len(con->authed_user, field->ptr, strlen(field->ptr));
#else
data_string *ds;
if (NULL == (ds = (data_string *)array_get_element(con->environment, "REMOTE_USER"))) {
if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
ds = data_string_init();
}
buffer_copy_string(ds->key, "REMOTE_USER");
array_insert_unique(con->environment, (data_unset *)ds);
}
buffer_copy_string_len(ds->value, field->ptr, strlen(field->ptr));
#endif
buffer_free(field);
DEBUG("s", "all check passed");
return HANDLER_GO_ON;
}
//
// Check for redirected auth request in cookie.
//
// Expected Cookie Format:
// <name>=crypt:<hash>:<data>
//
// hash = hex(MD5(key + timesegment + data))
// data = hex(encrypt(MD5(timesegment + key), payload))
// payload = base64(username + ":" + password)
//
static handler_t
handle_crypt(server *srv, connection *con,
plugin_data *pd, plugin_config *pc, char *line) {
li_MD5_CTX ctx;
uint8_t hash[MD5_LEN];
char tmp[256];
// Check for existence of data part
char *data = strchr(line, ':');
if (! data) return endauth(srv, con, pc);
DEBUG("s", "verifying crypt cookie...");
// Verify signature.
// Also, find time segment when this auth request was encrypted.
time_t t1, t0 = time(NULL);
buffer *buf = buffer_init();
for (t1 = t0 - (t0 % 5); t0 - t1 < 10; t1 -= 5) {
DEBUG("sdsd", "t0:", t0, ", t1:", t1);
// compute hash for this time segment
sprintf(tmp, "%lu", t1);
li_MD5_Init(&ctx);
li_MD5_Update(&ctx, CONST_BUF_LEN(pc->key));
li_MD5_Update(&ctx, tmp, strlen(tmp));
li_MD5_Update(&ctx, data + 1, strlen(data + 1));
li_MD5_Final(hash, &ctx);
hex_encode(buf, hash, sizeof(hash));
DEBUG("sb", "computed hash:", buf);
// verify by comparing hash
if (strncasecmp(buf->ptr, line, data - line) == 0) {
break; // hash verified and time segment found
}
}
buffer_free(buf);
// Has this found time segment expired?
if (! (t0 - t1 < 10)) {
DEBUG("s", "timeout detected");
return endauth(srv, con, pc);
}
DEBUG("s", "timeout check passed");
// compute temporal encryption key (= MD5(t1, key))
sprintf(tmp, "%lu", t1);
li_MD5_Init(&ctx);
li_MD5_Update(&ctx, tmp, strlen(tmp));
li_MD5_Update(&ctx, CONST_BUF_LEN(pc->key));
li_MD5_Final(hash, &ctx);
// decrypt
hex_decode(buf = buffer_init(), data + 1);
if (decrypt(buf, hash, sizeof(hash)) != 0) {
WARN("s", "decryption error");
buffer_free(buf);
return endauth(srv, con, pc);
}
// update header using decrypted authinfo
update_header(srv, con, pd, pc, buf);
buffer_free(buf);
return HANDLER_GO_ON;
}
/**********************************************************************
* module interface
**********************************************************************/
INIT_FUNC(module_init) {
plugin_data *pd;
pd = calloc(1, sizeof(*pd));
pd->users = array_init();
return pd;
}
FREE_FUNC(module_free) {
plugin_data *pd = p_d;
if (! pd) return HANDLER_GO_ON;
// Free plugin data
array_free(pd->users);
// Free configuration data.
// This must be done for each context.
if (pd->config) {
size_t i;
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *pc = pd->config[i];
if (! pc) continue;
// free configuration
buffer_free(pc->name);
buffer_free(pc->authurl);
buffer_free(pc->key);
free(pc);
}
free(pd->config);
}
free(pd);
return HANDLER_GO_ON;
}
//
// authorization handler
//
URIHANDLER_FUNC(module_uri_handler) {
plugin_data *pd = p_d;
plugin_config *pc = merge_config(srv, con, pd);
data_string *ds;
char buf[1024]; // cookie content
char key[32]; // <AuthName> key
char *cs; // pointer to (some part of) <AuthName> key
// skip if not enabled
if (buffer_is_empty(pc->name)) return HANDLER_GO_ON;
// decide how to handle incoming Auth header
if ((ds = HEADER(con, "Authorization")) != NULL) {
switch (pc->override) {
case 0: return HANDLER_GO_ON; // just use it if supplied
case 1: break; // use CookieAuth if exists
case 2:
default: buffer_reset(ds->key); // use CookieAuth only
}
}
// check for cookie
if ((ds = HEADER(con, "Cookie")) == NULL) return endauth(srv, con, pc);
DEBUG("sb", "parsing cookie:", ds->value);
// prepare cstring for processing
memset(key, 0, sizeof(key));
memset(buf, 0, sizeof(buf));
strncpy(key, pc->name->ptr, min(sizeof(key) - 1, pc->name->used));
strncpy(buf, ds->value->ptr, min(sizeof(buf) - 1, ds->value->used));
DEBUG("ss", "parsing for key:", key);
// check for "<AuthName>=" entry in a cookie
for (cs = buf; (cs = strstr(cs, key)) != NULL; ) {
DEBUG("ss", "checking cookie entry:", cs);
// check if found entry matches exactly for "KEY=" part.
cs += pc->name->used - 1; // jump to the end of "KEY" part
while (isspace(*cs)) cs++; // whitespace can be skipped
// break forward if this was an exact match
if (*cs++ == '=') {
char *eot = strchr(cs, ';');
if (eot) *eot = '\0';
break;
}
}
if (! cs) return endauth(srv, con, pc); // not found - rejecting
// unescape payload
buffer *tmp = buffer_init_string(cs);
buffer_urldecode_path(tmp);
memset(buf, 0, sizeof(buf));
strncpy(buf, tmp->ptr, min(sizeof(buf) - 1, tmp->used));
buffer_free(tmp);
cs = buf;
// Allow access if client already has an "authorized" token.
if (strncmp(cs, "token:", 6) == 0) {
return handle_token(srv, con, pd, pc, cs + 6);
}
// Verify "non-authorized" CookieAuth request in encrypted format.
// Once verified, give out authorized token ("token:..." cookie).
if (strncmp(cs, "crypt:", 6) == 0) {
return handle_crypt(srv, con, pd, pc, cs + 6);
}
DEBUG("ss", "unrecognied cookie auth format:", cs);
return endauth(srv, con, pc);
}
SETDEFAULTS_FUNC(module_set_defaults) {
plugin_data *pd = p_d;
size_t i;
config_values_t cv[] = {
{ "auth-ticket.loglevel",
NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.name",
NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.override",
NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.authurl",
NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.key",
NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.timeout",
NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION },
{ "auth-ticket.options",
NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
};
pd->config = calloc(1,
srv->config_context->used * sizeof(specific_config *));
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *pc;
pc = pd->config[i] = calloc(1, sizeof(plugin_config));
pc->loglevel = 1;
pc->name = buffer_init();
pc->override = 2;
pc->authurl = buffer_init();
pc->key = buffer_init();
pc->timeout = 86400;
pc->options = buffer_init();
cv[0].destination = &(pc->loglevel);
cv[1].destination = pc->name;
cv[2].destination = &(pc->override);
cv[3].destination = pc->authurl;
cv[4].destination = pc->key;
cv[5].destination = &(pc->timeout);
cv[6].destination = pc->options;
array *ca = ((data_config *)srv->config_context->data[i])->value;
if (config_insert_values_global(srv, ca, cv) != 0) {
return HANDLER_ERROR;
}
}
return HANDLER_GO_ON;
}
int
mod_auth_ticket_plugin_init(plugin *p) {
p->version = LIGHTTPD_VERSION_ID;
p->name = buffer_init_string("auth_ticket");
p->init = module_init;
p->set_defaults = module_set_defaults;
p->cleanup = module_free;
p->handle_uri_clean = module_uri_handler;
p->data = NULL;
return 0;
}