[core] set REDIRECT_STATUS to error_handler_saved_status (fixes #1828)
[lighttpd.git] / src / mod_secdownload.c
blob86ce5b01ba101dd08981b64f79faab9f85b5f42d
1 #include "first.h"
3 #include "base.h"
4 #include "log.h"
5 #include "buffer.h"
6 #include "base64.h"
8 #include "plugin.h"
10 #include <ctype.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #if defined(USE_OPENSSL)
15 #include <openssl/evp.h>
16 #include <openssl/hmac.h>
17 #endif
19 #include "md5.h"
21 #define HASHLEN 16
22 typedef unsigned char HASH[HASHLEN];
23 #define HASHHEXLEN 32
24 typedef char HASHHEX[HASHHEXLEN+1];
27 * mod_secdownload verifies a checksum associated with a timestamp
28 * and a path.
30 * It takes an URL of the form:
31 * securl := <uri-prefix> <mac> <protected-path>
32 * uri-prefix := '/' any* # whatever was configured: must start with a '/')
33 * mac := [a-zA-Z0-9_-]{mac_len} # mac length depends on selected algorithm
34 * protected-path := '/' <timestamp> <rel-path>
35 * timestamp := [a-f0-9]{8} # timestamp when the checksum was calculated
36 * # to prevent access after timeout (active requests
37 * # will finish successfully even after the timeout)
38 * rel-path := '/' any* # the protected path; changing the path breaks the
39 * # checksum
41 * The timestamp is the `epoch` timestamp in hex, i.e. time in seconds
42 * since 00:00:00 UTC on 1 January 1970.
44 * mod_secdownload supports various MAC algorithms:
46 * # md5
47 * mac_len := 32 (and hex only)
48 * mac := md5-hex(<secrect><rel-path><timestamp>) # lowercase hex
49 * perl example:
50 use Digest::MD5 qw(md5_hex);
51 my $secret = "verysecret";
52 my $rel_path = "/index.html"
53 my $xtime = sprintf("%08x", time);
54 my $url = '/'. md5_hex($secret . $rel_path . $xtime) . '/' . $xtime . $rel_path;
56 * # hmac-sha1
57 * mac_len := 27 (no base64 padding)
58 * mac := base64-url(hmac-sha1(<secret>, <protected-path>))
59 * perl example:
60 use Digest::SHA qw(hmac_sha1);
61 use MIME::Base64 qw(encode_base64url);
62 my $secret = "verysecret";
63 my $rel_path = "/index.html"
64 my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
65 my $url = '/'. encode_base64url(hmac_sha1($protected_path, $secret)) . $protected_path;
67 * # hmac-256
68 * mac_len := 43 (no base64 padding)
69 * mac := base64-url(hmac-256(<secret>, <protected-path>))
70 use Digest::SHA qw(hmac_sha256);
71 use MIME::Base64 qw(encode_base64url);
72 my $secret = "verysecret";
73 my $rel_path = "/index.html"
74 my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
75 my $url = '/'. encode_base64url(hmac_sha256($protected_path, $secret)) . $protected_path;
79 /* plugin config for all request/connections */
81 typedef enum {
82 SECDL_INVALID = 0,
83 SECDL_MD5 = 1,
84 SECDL_HMAC_SHA1 = 2,
85 SECDL_HMAC_SHA256 = 3,
86 } secdl_algorithm;
88 typedef struct {
89 buffer *doc_root;
90 buffer *secret;
91 buffer *uri_prefix;
92 secdl_algorithm algorithm;
94 unsigned int timeout;
95 } plugin_config;
97 typedef struct {
98 PLUGIN_DATA;
100 plugin_config **config_storage;
102 plugin_config conf;
103 } plugin_data;
105 static int const_time_memeq(const char *a, const char *b, size_t len) {
106 /* constant time memory compare, unless the compiler figures it out */
107 char diff = 0;
108 size_t i;
109 for (i = 0; i < len; ++i) {
110 diff |= (a[i] ^ b[i]);
112 return 0 == diff;
115 static const char* secdl_algorithm_names[] = {
116 "invalid",
117 "md5",
118 "hmac-sha1",
119 "hmac-sha256",
122 static secdl_algorithm algorithm_from_string(buffer *name) {
123 size_t ndx;
125 if (buffer_string_is_empty(name)) return SECDL_INVALID;
127 for (ndx = 1; ndx < sizeof(secdl_algorithm_names)/sizeof(secdl_algorithm_names[0]); ++ndx) {
128 if (0 == strcmp(secdl_algorithm_names[ndx], name->ptr)) return (secdl_algorithm)ndx;
131 return SECDL_INVALID;
134 static size_t secdl_algorithm_mac_length(secdl_algorithm alg) {
135 switch (alg) {
136 case SECDL_INVALID:
137 break;
138 case SECDL_MD5:
139 return 32;
140 case SECDL_HMAC_SHA1:
141 return 27;
142 case SECDL_HMAC_SHA256:
143 return 43;
145 return 0;
148 static int secdl_verify_mac(server *srv, plugin_config *config, const char* protected_path, const char* mac, size_t maclen) {
149 if (0 == maclen || secdl_algorithm_mac_length(config->algorithm) != maclen) return 0;
151 switch (config->algorithm) {
152 case SECDL_INVALID:
153 break;
154 case SECDL_MD5:
156 li_MD5_CTX Md5Ctx;
157 HASH HA1;
158 char hexmd5[33];
159 const char *ts_str;
160 const char *rel_uri;
162 /* legacy message:
163 * protected_path := '/' <timestamp-hex> <rel-path>
164 * timestamp-hex := [0-9a-f]{8}
165 * rel-path := '/' any*
166 * (the protected path was already verified)
167 * message = <secret><rel-path><timestamp-hex>
169 ts_str = protected_path + 1;
170 rel_uri = ts_str + 8;
172 li_MD5_Init(&Md5Ctx);
173 li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(config->secret));
174 li_MD5_Update(&Md5Ctx, rel_uri, strlen(rel_uri));
175 li_MD5_Update(&Md5Ctx, ts_str, 8);
176 li_MD5_Final(HA1, &Md5Ctx);
178 li_tohex(hexmd5, sizeof(hexmd5), (const char *)HA1, 16);
180 return (32 == maclen) && const_time_memeq(mac, hexmd5, 32);
182 case SECDL_HMAC_SHA1:
183 #if defined(USE_OPENSSL)
185 unsigned char digest[20];
186 char base64_digest[27];
188 if (NULL == HMAC(
189 EVP_sha1(),
190 (unsigned char const*) CONST_BUF_LEN(config->secret),
191 (unsigned char const*) protected_path, strlen(protected_path),
192 digest, NULL)) {
193 log_error_write(srv, __FILE__, __LINE__, "s",
194 "hmac-sha1: HMAC() failed");
195 return 0;
198 li_to_base64_no_padding(base64_digest, 27, digest, 20, BASE64_URL);
200 return (27 == maclen) && const_time_memeq(mac, base64_digest, 27);
202 #endif
203 break;
204 case SECDL_HMAC_SHA256:
205 #if defined(USE_OPENSSL)
207 unsigned char digest[32];
208 char base64_digest[43];
210 if (NULL == HMAC(
211 EVP_sha256(),
212 (unsigned char const*) CONST_BUF_LEN(config->secret),
213 (unsigned char const*) protected_path, strlen(protected_path),
214 digest, NULL)) {
215 log_error_write(srv, __FILE__, __LINE__, "s",
216 "hmac-sha256: HMAC() failed");
217 return 0;
220 li_to_base64_no_padding(base64_digest, 43, digest, 32, BASE64_URL);
222 return (43 == maclen) && const_time_memeq(mac, base64_digest, 43);
224 #endif
225 break;
228 return 0;
231 /* init the plugin data */
232 INIT_FUNC(mod_secdownload_init) {
233 plugin_data *p;
235 p = calloc(1, sizeof(*p));
237 return p;
240 /* detroy the plugin data */
241 FREE_FUNC(mod_secdownload_free) {
242 plugin_data *p = p_d;
243 UNUSED(srv);
245 if (!p) return HANDLER_GO_ON;
247 if (p->config_storage) {
248 size_t i;
249 for (i = 0; i < srv->config_context->used; i++) {
250 plugin_config *s = p->config_storage[i];
252 if (NULL == s) continue;
254 buffer_free(s->secret);
255 buffer_free(s->doc_root);
256 buffer_free(s->uri_prefix);
258 free(s);
260 free(p->config_storage);
263 free(p);
265 return HANDLER_GO_ON;
268 /* handle plugin config and check values */
270 SETDEFAULTS_FUNC(mod_secdownload_set_defaults) {
271 plugin_data *p = p_d;
272 size_t i = 0;
274 config_values_t cv[] = {
275 { "secdownload.secret", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
276 { "secdownload.document-root", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
277 { "secdownload.uri-prefix", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
278 { "secdownload.timeout", NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
279 { "secdownload.algorithm", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
280 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
283 if (!p) return HANDLER_ERROR;
285 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
287 for (i = 0; i < srv->config_context->used; i++) {
288 data_config const* config = (data_config const*)srv->config_context->data[i];
289 plugin_config *s;
290 buffer *algorithm = buffer_init();
292 s = calloc(1, sizeof(plugin_config));
293 s->secret = buffer_init();
294 s->doc_root = buffer_init();
295 s->uri_prefix = buffer_init();
296 s->timeout = 60;
298 cv[0].destination = s->secret;
299 cv[1].destination = s->doc_root;
300 cv[2].destination = s->uri_prefix;
301 cv[3].destination = &(s->timeout);
302 cv[4].destination = algorithm;
304 p->config_storage[i] = s;
306 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
307 buffer_free(algorithm);
308 return HANDLER_ERROR;
311 if (!buffer_is_empty(algorithm)) {
312 s->algorithm = algorithm_from_string(algorithm);
313 switch (s->algorithm) {
314 case SECDL_INVALID:
315 log_error_write(srv, __FILE__, __LINE__, "sb",
316 "invalid secdownload.algorithm:",
317 algorithm);
318 buffer_free(algorithm);
319 return HANDLER_ERROR;
320 #if !defined(USE_OPENSSL)
321 case SECDL_HMAC_SHA1:
322 case SECDL_HMAC_SHA256:
323 log_error_write(srv, __FILE__, __LINE__, "sb",
324 "unsupported secdownload.algorithm:",
325 algorithm);
326 buffer_free(algorithm);
327 return HANDLER_ERROR;
328 #endif
329 default:
330 break;
334 buffer_free(algorithm);
337 return HANDLER_GO_ON;
341 * checks if the supplied string is a hex string
343 * @param str a possible hex string
344 * @return if the supplied string is a valid hex string 1 is returned otherwise 0
347 static int is_hex_len(const char *str, size_t len) {
348 size_t i;
350 if (NULL == str) return 0;
352 for (i = 0; i < len && *str; i++, str++) {
353 /* illegal characters */
354 if (!((*str >= '0' && *str <= '9') ||
355 (*str >= 'a' && *str <= 'f') ||
356 (*str >= 'A' && *str <= 'F'))
358 return 0;
362 return i == len;
366 * checks if the supplied string is a base64 (modified URL) string
368 * @param str a possible base64 (modified URL) string
369 * @return if the supplied string is a valid base64 (modified URL) string 1 is returned otherwise 0
372 static int is_base64_len(const char *str, size_t len) {
373 size_t i;
375 if (NULL == str) return 0;
377 for (i = 0; i < len && *str; i++, str++) {
378 /* illegal characters */
379 if (!((*str >= '0' && *str <= '9') ||
380 (*str >= 'a' && *str <= 'z') ||
381 (*str >= 'A' && *str <= 'Z') ||
382 (*str == '-') || (*str == '_'))
384 return 0;
388 return i == len;
391 #define PATCH(x) \
392 p->conf.x = s->x;
393 static int mod_secdownload_patch_connection(server *srv, connection *con, plugin_data *p) {
394 size_t i, j;
395 plugin_config *s = p->config_storage[0];
397 PATCH(secret);
398 PATCH(doc_root);
399 PATCH(uri_prefix);
400 PATCH(timeout);
401 PATCH(algorithm);
403 /* skip the first, the global context */
404 for (i = 1; i < srv->config_context->used; i++) {
405 data_config *dc = (data_config *)srv->config_context->data[i];
406 s = p->config_storage[i];
408 /* condition didn't match */
409 if (!config_check_cond(srv, con, dc)) continue;
411 /* merge config */
412 for (j = 0; j < dc->value->used; j++) {
413 data_unset *du = dc->value->data[j];
415 if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.secret"))) {
416 PATCH(secret);
417 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.document-root"))) {
418 PATCH(doc_root);
419 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.uri-prefix"))) {
420 PATCH(uri_prefix);
421 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.timeout"))) {
422 PATCH(timeout);
423 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.algorithm"))) {
424 PATCH(algorithm);
429 return 0;
431 #undef PATCH
434 URIHANDLER_FUNC(mod_secdownload_uri_handler) {
435 plugin_data *p = p_d;
436 const char *rel_uri, *ts_str, *mac_str, *protected_path;
437 time_t ts = 0;
438 size_t i, mac_len;
440 if (con->mode != DIRECT) return HANDLER_GO_ON;
442 if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON;
444 mod_secdownload_patch_connection(srv, con, p);
446 if (buffer_string_is_empty(p->conf.uri_prefix)) return HANDLER_GO_ON;
448 if (buffer_string_is_empty(p->conf.secret)) {
449 log_error_write(srv, __FILE__, __LINE__, "s",
450 "secdownload.secret has to be set");
451 con->http_status = 500;
452 return HANDLER_FINISHED;
455 if (buffer_string_is_empty(p->conf.doc_root)) {
456 log_error_write(srv, __FILE__, __LINE__, "s",
457 "secdownload.document-root has to be set");
458 con->http_status = 500;
459 return HANDLER_FINISHED;
462 if (SECDL_INVALID == p->conf.algorithm) {
463 log_error_write(srv, __FILE__, __LINE__, "s",
464 "secdownload.algorithm has to be set");
465 con->http_status = 500;
466 return HANDLER_FINISHED;
469 mac_len = secdl_algorithm_mac_length(p->conf.algorithm);
471 if (0 != strncmp(con->uri.path->ptr, p->conf.uri_prefix->ptr, buffer_string_length(p->conf.uri_prefix))) return HANDLER_GO_ON;
473 mac_str = con->uri.path->ptr + buffer_string_length(p->conf.uri_prefix);
475 if (!is_base64_len(mac_str, mac_len)) return HANDLER_GO_ON;
477 protected_path = mac_str + mac_len;
478 if (*protected_path != '/') return HANDLER_GO_ON;
480 ts_str = protected_path + 1;
481 if (!is_hex_len(ts_str, 8)) return HANDLER_GO_ON;
482 if (*(ts_str + 8) != '/') return HANDLER_GO_ON;
484 for (i = 0; i < 8; i++) {
485 ts = (ts << 4) + hex2int(ts_str[i]);
488 /* timed-out */
489 if ( (srv->cur_ts > ts && (unsigned int) (srv->cur_ts - ts) > p->conf.timeout) ||
490 (srv->cur_ts < ts && (unsigned int) (ts - srv->cur_ts) > p->conf.timeout) ) {
491 /* "Gone" as the url will never be valid again instead of "408 - Timeout" where the request may be repeated */
492 con->http_status = 410;
494 return HANDLER_FINISHED;
497 rel_uri = ts_str + 8;
499 if (!secdl_verify_mac(srv, &p->conf, protected_path, mac_str, mac_len)) {
500 con->http_status = 403;
502 if (con->conf.log_request_handling) {
503 log_error_write(srv, __FILE__, __LINE__, "sb",
504 "mac invalid:",
505 con->uri.path);
508 return HANDLER_FINISHED;
511 /* starting with the last / we should have relative-path to the docroot
514 buffer_copy_buffer(con->physical.doc_root, p->conf.doc_root);
515 buffer_copy_buffer(con->physical.basedir, p->conf.doc_root);
516 buffer_copy_string(con->physical.rel_path, rel_uri);
517 buffer_copy_buffer(con->physical.path, con->physical.doc_root);
518 buffer_append_string_buffer(con->physical.path, con->physical.rel_path);
520 return HANDLER_GO_ON;
523 /* this function is called at dlopen() time and inits the callbacks */
525 int mod_secdownload_plugin_init(plugin *p);
526 int mod_secdownload_plugin_init(plugin *p) {
527 p->version = LIGHTTPD_VERSION_ID;
528 p->name = buffer_init_string("secdownload");
530 p->init = mod_secdownload_init;
531 p->handle_physical = mod_secdownload_uri_handler;
532 p->set_defaults = mod_secdownload_set_defaults;
533 p->cleanup = mod_secdownload_free;
535 p->data = NULL;
537 return 0;