lighttpd 1.4.x https://www.lighttpd.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

721 lines
22 KiB

  1. #include "first.h"
  2. #include "base.h"
  3. #include "log.h"
  4. #include "buffer.h"
  5. #include "base64.h"
  6. #include "http_auth.h"
  7. #include "plugin.h"
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "sys-crypto-md.h"
  11. #ifdef USE_LIB_CRYPTO
  12. #if defined(USE_NETTLE_CRYPTO)
  13. #include <nettle/hmac.h>
  14. #elif defined(USE_MBEDTLS_CRYPTO)
  15. #include <mbedtls/md.h>
  16. #elif defined(USE_WOLFSSL_CRYPTO)
  17. #include <wolfssl/wolfcrypt/hmac.h>
  18. #elif defined(USE_OPENSSL_CRYPTO)
  19. #include <openssl/evp.h>
  20. #include <openssl/hmac.h>
  21. #elif defined(USE_GNUTLS_CRYPTO)
  22. #include <gnutls/crypto.h>
  23. #elif defined(USE_NSS_CRYPTO)
  24. #if 0 /*(nss/alghmac.h might not be present)*/
  25. #ifdef NSS_VER_INCLUDE
  26. #include <nss3/alghmac.h>
  27. #else
  28. #include <nss/alghmac.h>
  29. #endif
  30. #endif
  31. #endif
  32. #endif
  33. #if defined(USE_OPENSSL_CRYPTO) && OPENSSL_VERSION_NUMBER >= 0x30000000L
  34. #define HMAC EVP_HMAC
  35. static unsigned char *
  36. EVP_HMAC (const EVP_MD *evp_md, const void *key,
  37. int key_len, const unsigned char *d, int n,
  38. unsigned char *md, size_t *md_len)
  39. {
  40. EVP_PKEY * const pkey =
  41. EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, key, key_len);
  42. if (NULL == pkey) return NULL;
  43. EVP_MD_CTX * const ctx = EVP_MD_CTX_new();
  44. if (NULL == ctx) {
  45. EVP_PKEY_free(pkey);
  46. return NULL;
  47. }
  48. int rc = (1 == EVP_DigestSignInit(ctx, NULL, evp_md, NULL, pkey))
  49. && (1 == EVP_DigestSignUpdate(ctx, d, n))
  50. && (1 == EVP_DigestSignFinal(ctx, md, md_len));
  51. EVP_MD_CTX_free(ctx);
  52. EVP_PKEY_free(pkey);
  53. return (1 == rc) ? md : NULL;
  54. }
  55. #endif
  56. /*
  57. * mod_secdownload verifies a checksum associated with a timestamp
  58. * and a path.
  59. *
  60. * It takes an URL of the form:
  61. * securl := <uri-prefix> <mac> <protected-path>
  62. * uri-prefix := '/' any* # whatever was configured: must start with a '/')
  63. * mac := [a-zA-Z0-9_-]{mac_len} # mac length depends on selected algorithm
  64. * protected-path := '/' <timestamp> <rel-path>
  65. * timestamp := [a-f0-9]{8} # timestamp when the checksum was calculated
  66. * # to prevent access after timeout (active requests
  67. * # will finish successfully even after the timeout)
  68. * rel-path := '/' any* # the protected path; changing the path breaks the
  69. * # checksum
  70. *
  71. * The timestamp is the `epoch` timestamp in hex, i.e. time in seconds
  72. * since 00:00:00 UTC on 1 January 1970.
  73. *
  74. * mod_secdownload supports various MAC algorithms:
  75. *
  76. * # md5
  77. * mac_len := 32 (and hex only)
  78. * mac := md5-hex(<secrect><rel-path><timestamp>) # lowercase hex
  79. * perl example:
  80. use Digest::MD5 qw(md5_hex);
  81. my $secret = "verysecret";
  82. my $rel_path = "/index.html"
  83. my $xtime = sprintf("%08x", time);
  84. my $url = '/'. md5_hex($secret . $rel_path . $xtime) . '/' . $xtime . $rel_path;
  85. *
  86. * # hmac-sha1
  87. * mac_len := 27 (no base64 padding)
  88. * mac := base64-url(hmac-sha1(<secret>, <protected-path>))
  89. * perl example:
  90. use Digest::SHA qw(hmac_sha1);
  91. use MIME::Base64 qw(encode_base64url);
  92. my $secret = "verysecret";
  93. my $rel_path = "/index.html"
  94. my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
  95. my $url = '/'. encode_base64url(hmac_sha1($protected_path, $secret)) . $protected_path;
  96. *
  97. * # hmac-sha256
  98. * mac_len := 43 (no base64 padding)
  99. * mac := base64-url(hmac-sha256(<secret>, <protected-path>))
  100. use Digest::SHA qw(hmac_sha256);
  101. use MIME::Base64 qw(encode_base64url);
  102. my $secret = "verysecret";
  103. my $rel_path = "/index.html"
  104. my $protected_path = '/' . sprintf("%08x", time) . $rel_path;
  105. my $url = '/'. encode_base64url(hmac_sha256($protected_path, $secret)) . $protected_path;
  106. *
  107. */
  108. /* plugin config for all request/connections */
  109. typedef enum {
  110. SECDL_INVALID = 0,
  111. SECDL_MD5 = 1,
  112. SECDL_HMAC_SHA1 = 2,
  113. SECDL_HMAC_SHA256 = 3,
  114. } secdl_algorithm;
  115. typedef struct {
  116. const buffer *doc_root;
  117. const buffer *secret;
  118. const buffer *uri_prefix;
  119. secdl_algorithm algorithm;
  120. unsigned int timeout;
  121. unsigned short path_segments;
  122. unsigned short hash_querystr;
  123. } plugin_config;
  124. typedef struct {
  125. PLUGIN_DATA;
  126. plugin_config defaults;
  127. plugin_config conf;
  128. } plugin_data;
  129. static int const_time_memeq(const char *a, const char *b, size_t len) {
  130. /* constant time memory compare, unless the compiler figures it out */
  131. char diff = 0;
  132. size_t i;
  133. for (i = 0; i < len; ++i) {
  134. diff |= (a[i] ^ b[i]);
  135. }
  136. return 0 == diff;
  137. }
  138. static const char* secdl_algorithm_names[] = {
  139. "invalid",
  140. "md5",
  141. "hmac-sha1",
  142. "hmac-sha256",
  143. };
  144. static secdl_algorithm algorithm_from_string(const buffer *name) {
  145. size_t ndx;
  146. if (buffer_string_is_empty(name)) return SECDL_INVALID;
  147. for (ndx = 1; ndx < sizeof(secdl_algorithm_names)/sizeof(secdl_algorithm_names[0]); ++ndx) {
  148. if (0 == strcmp(secdl_algorithm_names[ndx], name->ptr)) return (secdl_algorithm)ndx;
  149. }
  150. return SECDL_INVALID;
  151. }
  152. static size_t secdl_algorithm_mac_length(secdl_algorithm alg) {
  153. switch (alg) {
  154. case SECDL_INVALID:
  155. break;
  156. case SECDL_MD5:
  157. return 32;
  158. case SECDL_HMAC_SHA1:
  159. return 27;
  160. case SECDL_HMAC_SHA256:
  161. return 43;
  162. }
  163. return 0;
  164. }
  165. static int secdl_verify_mac(plugin_config *config, const char* protected_path, const char* mac, size_t maclen, log_error_st *errh) {
  166. UNUSED(errh);
  167. if (0 == maclen || secdl_algorithm_mac_length(config->algorithm) != maclen) return 0;
  168. switch (config->algorithm) {
  169. case SECDL_INVALID:
  170. break;
  171. case SECDL_MD5:
  172. {
  173. li_MD5_CTX Md5Ctx;
  174. const char *ts_str;
  175. const char *rel_uri;
  176. unsigned char HA1[16];
  177. unsigned char md5bin[16];
  178. if (0 != http_auth_digest_hex2bin(mac, maclen, md5bin, sizeof(md5bin))) return 0;
  179. /* legacy message:
  180. * protected_path := '/' <timestamp-hex> <rel-path>
  181. * timestamp-hex := [0-9a-f]{8}
  182. * rel-path := '/' any*
  183. * (the protected path was already verified)
  184. * message = <secret><rel-path><timestamp-hex>
  185. */
  186. ts_str = protected_path + 1;
  187. rel_uri = ts_str + 8;
  188. li_MD5_Init(&Md5Ctx);
  189. li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(config->secret));
  190. li_MD5_Update(&Md5Ctx, rel_uri, strlen(rel_uri));
  191. li_MD5_Update(&Md5Ctx, ts_str, 8);
  192. li_MD5_Final(HA1, &Md5Ctx);
  193. return const_time_memeq((char *)HA1, (char *)md5bin, sizeof(md5bin));
  194. }
  195. #ifdef USE_LIB_CRYPTO
  196. case SECDL_HMAC_SHA1:
  197. {
  198. unsigned char digest[20];
  199. char base64_digest[27];
  200. #if defined(USE_NETTLE_CRYPTO)
  201. struct hmac_sha1_ctx ctx;
  202. hmac_sha1_set_key(&ctx, buffer_string_length(config->secret), (const uint8_t *)config->secret->ptr);
  203. hmac_sha1_update(&ctx, strlen(protected_path), (const uint8_t *)protected_path);
  204. hmac_sha1_digest(&ctx, sizeof(digest), (uint8_t *)digest);
  205. #elif defined(USE_MBEDTLS_CRYPTO) && defined(MBEDTLS_MD_C) && defined(MBEDTLS_SHA1_C)
  206. int rc =
  207. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
  208. (const unsigned char *)config->secret->ptr,
  209. buffer_string_length(config->secret),
  210. (const unsigned char *)protected_path,
  211. strlen(protected_path), digest);
  212. if (0 != rc) {
  213. log_error(errh, __FILE__, __LINE__,
  214. "hmac-sha1: HMAC() failed");
  215. return 0;
  216. }
  217. #elif defined(USE_WOLFSSL_CRYPTO)
  218. Hmac hmac;
  219. if (0 != wc_HmacInit(&hmac, NULL, INVALID_DEVID)
  220. || wc_HmacSetKey(&hmac, WC_SHA, (const byte *)config->secret->ptr,
  221. (word32)buffer_string_length(config->secret)) < 0
  222. || wc_HmacUpdate(&hmac, (const byte *)protected_path,
  223. (word32)strlen(protected_path)) < 0
  224. || wc_HmacFinal(&hmac, (byte *)digest) < 0) {
  225. log_error(errh, __FILE__, __LINE__,
  226. "hmac-sha1: HMAC() failed");
  227. return 0;
  228. }
  229. #elif defined(USE_OPENSSL_CRYPTO)
  230. if (NULL == HMAC(
  231. EVP_sha1(),
  232. (unsigned char const*) config->secret->ptr, buffer_string_length(config->secret),
  233. (unsigned char const*) protected_path, strlen(protected_path),
  234. digest, NULL)) {
  235. log_error(errh, __FILE__, __LINE__,
  236. "hmac-sha1: HMAC() failed");
  237. return 0;
  238. }
  239. #elif defined(USE_GNUTLS_CRYPTO)
  240. int rc =
  241. gnutls_hmac_fast(GNUTLS_MAC_SHA1,
  242. (const unsigned char *)config->secret->ptr,
  243. buffer_string_length(config->secret),
  244. (const unsigned char *)protected_path,
  245. strlen(protected_path), digest);
  246. if (0 != rc) {
  247. log_error(errh, __FILE__, __LINE__,
  248. "hmac-sha1: HMAC() failed");
  249. return 0;
  250. }
  251. #elif defined(USE_NSS_CRYPTO)
  252. /*(HMAC* funcs not public export of libfreebl3.so,
  253. * even though nss3/alghmac.h is public (WTH?!))*/
  254. #if 0
  255. HMACContext *hmac =
  256. HMAC_Create(HASH_GetHashObject(HASH_AlgSHA1),
  257. (const unsigned char *)config->secret->ptr,
  258. buffer_string_length(config->secret), PR_FALSE);
  259. int rc;
  260. if ((rc = (NULL != hmac) ? SECSuccess : SECFailure)) {
  261. HMAC_Begin(hmac);
  262. HMAC_Update(hmac, (const unsigned char *)protected_path,
  263. strlen(protected_path));
  264. unsigned int len;
  265. rc = HMAC_Finish(hmac, digest, &len, sizeof(digest));
  266. HMAC_Destroy(hmac, PR_TRUE);
  267. }
  268. if (SECSuccess != rc) {
  269. log_error(errh, __FILE__, __LINE__,
  270. "hmac-sha1: HMAC() failed");
  271. return 0;
  272. }
  273. #else
  274. return 0;
  275. #endif
  276. #else
  277. #error "unexpected; crypto lib not configured for use by mod_secdownload"
  278. #endif
  279. li_to_base64_no_padding(base64_digest, 27, digest, 20, BASE64_URL);
  280. return (27 == maclen) && const_time_memeq(mac, base64_digest, 27);
  281. }
  282. break;
  283. case SECDL_HMAC_SHA256:
  284. {
  285. unsigned char digest[32];
  286. char base64_digest[43];
  287. #if defined(USE_NETTLE_CRYPTO)
  288. struct hmac_sha256_ctx ctx;
  289. hmac_sha256_set_key(&ctx, buffer_string_length(config->secret), (const uint8_t *)config->secret->ptr);
  290. hmac_sha256_update(&ctx, strlen(protected_path), (const uint8_t *)protected_path);
  291. hmac_sha256_digest(&ctx, sizeof(digest), (uint8_t *)digest);
  292. #elif defined(USE_MBEDTLS_CRYPTO) && defined(MBEDTLS_MD_C) && defined(MBEDTLS_SHA256_C)
  293. int rc =
  294. mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
  295. (const unsigned char *)config->secret->ptr,
  296. buffer_string_length(config->secret),
  297. (const unsigned char *)protected_path,
  298. strlen(protected_path), digest);
  299. if (0 != rc) {
  300. log_error(errh, __FILE__, __LINE__,
  301. "hmac-sha256: HMAC() failed");
  302. return 0;
  303. }
  304. #elif defined(USE_WOLFSSL_CRYPTO)
  305. Hmac hmac;
  306. if (0 != wc_HmacInit(&hmac, NULL, INVALID_DEVID)
  307. || wc_HmacSetKey(&hmac, WC_SHA256, (const byte *)config->secret->ptr,
  308. (word32)buffer_string_length(config->secret)) < 0
  309. || wc_HmacUpdate(&hmac, (const byte *)protected_path,
  310. (word32)strlen(protected_path)) < 0
  311. || wc_HmacFinal(&hmac, (byte *)digest) < 0) {
  312. log_error(errh, __FILE__, __LINE__,
  313. "hmac-sha256: HMAC() failed");
  314. return 0;
  315. }
  316. #elif defined(USE_OPENSSL_CRYPTO)
  317. if (NULL == HMAC(
  318. EVP_sha256(),
  319. (unsigned char const*) config->secret->ptr, buffer_string_length(config->secret),
  320. (unsigned char const*) protected_path, strlen(protected_path),
  321. digest, NULL)) {
  322. log_error(errh, __FILE__, __LINE__,
  323. "hmac-sha256: HMAC() failed");
  324. return 0;
  325. }
  326. #elif defined(USE_GNUTLS_CRYPTO)
  327. int rc =
  328. gnutls_hmac_fast(GNUTLS_MAC_SHA256,
  329. (const unsigned char *)config->secret->ptr,
  330. buffer_string_length(config->secret),
  331. (const unsigned char *)protected_path,
  332. strlen(protected_path), digest);
  333. if (0 != rc) {
  334. log_error(errh, __FILE__, __LINE__,
  335. "hmac-sha256: HMAC() failed");
  336. return 0;
  337. }
  338. #elif defined(USE_NSS_CRYPTO)
  339. /*(HMAC* funcs not public export of libfreebl3.so,
  340. * even though nss3/alghmac.h is public (WTH?!))*/
  341. #if 0
  342. HMACContext *hmac =
  343. HMAC_Create(HASH_GetHashObject(HASH_AlgSHA256),
  344. (const unsigned char *)config->secret->ptr,
  345. buffer_string_length(config->secret), PR_FALSE);
  346. int rc;
  347. if ((rc = (NULL != hmac) ? SECSuccess : SECFailure)) {
  348. HMAC_Begin(hmac);
  349. HMAC_Update(hmac, (const unsigned char *)protected_path,
  350. strlen(protected_path));
  351. unsigned int len;
  352. rc = HMAC_Finish(hmac, digest, &len, sizeof(digest));
  353. HMAC_Destroy(hmac, PR_TRUE);
  354. }
  355. if (SECSuccess != rc) {
  356. log_error(errh, __FILE__, __LINE__,
  357. "hmac-sha256: HMAC() failed");
  358. return 0;
  359. }
  360. #else
  361. return 0;
  362. #endif
  363. #else
  364. #error "unexpected; crypto lib not configured for use by mod_secdownload"
  365. #endif
  366. li_to_base64_no_padding(base64_digest, 43, digest, 32, BASE64_URL);
  367. return (43 == maclen) && const_time_memeq(mac, base64_digest, 43);
  368. }
  369. break;
  370. #endif
  371. default:
  372. break;
  373. }
  374. return 0;
  375. }
  376. INIT_FUNC(mod_secdownload_init) {
  377. return calloc(1, sizeof(plugin_data));
  378. }
  379. static int mod_secdownload_parse_algorithm(config_plugin_value_t * const cpv, log_error_st * const errh) {
  380. secdl_algorithm algorithm = algorithm_from_string(cpv->v.b);
  381. switch (algorithm) {
  382. case SECDL_INVALID:
  383. log_error(errh, __FILE__, __LINE__,
  384. "invalid secdownload.algorithm: %s", cpv->v.b->ptr);
  385. return 0;
  386. #ifndef USE_LIB_CRYPTO
  387. case SECDL_HMAC_SHA1:
  388. case SECDL_HMAC_SHA256:
  389. log_error(errh, __FILE__, __LINE__,
  390. "unsupported secdownload.algorithm: %s", cpv->v.b->ptr);
  391. /*return 0;*/
  392. /* proceed to allow config to load for other tests */
  393. /* (use of unsupported algorithm will result in failure at runtime) */
  394. break;
  395. #endif
  396. default:
  397. break;
  398. }
  399. cpv->vtype = T_CONFIG_INT;
  400. cpv->v.u = algorithm;
  401. return 1;
  402. }
  403. static void mod_secdownload_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
  404. switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
  405. case 0: /* secdownload.secret */
  406. pconf->secret = cpv->v.b;
  407. break;
  408. case 1: /* secdownload.document-root */
  409. pconf->doc_root = cpv->v.b;
  410. break;
  411. case 2: /* secdownload.uri-prefix */
  412. pconf->uri_prefix = cpv->v.b;
  413. break;
  414. case 3: /* secdownload.timeout */
  415. pconf->timeout = cpv->v.u;
  416. break;
  417. case 4: /* secdownload.algorithm */
  418. pconf->algorithm = cpv->v.u; /* mod_secdownload_parse_algorithm() */
  419. break;
  420. case 5: /* secdownload.path-segments */
  421. pconf->path_segments = cpv->v.shrt;
  422. break;
  423. case 6: /* secdownload.hash-querystr */
  424. pconf->hash_querystr = cpv->v.u;
  425. break;
  426. default:/* should not happen */
  427. return;
  428. }
  429. }
  430. static void mod_secdownload_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
  431. do {
  432. mod_secdownload_merge_config_cpv(pconf, cpv);
  433. } while ((++cpv)->k_id != -1);
  434. }
  435. static void mod_secdownload_patch_config(request_st * const r, plugin_data * const p) {
  436. memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
  437. for (int i = 1, used = p->nconfig; i < used; ++i) {
  438. if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
  439. mod_secdownload_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
  440. }
  441. }
  442. SETDEFAULTS_FUNC(mod_secdownload_set_defaults) {
  443. static const config_plugin_keys_t cpk[] = {
  444. { CONST_STR_LEN("secdownload.secret"),
  445. T_CONFIG_STRING,
  446. T_CONFIG_SCOPE_CONNECTION }
  447. ,{ CONST_STR_LEN("secdownload.document-root"),
  448. T_CONFIG_STRING,
  449. T_CONFIG_SCOPE_CONNECTION }
  450. ,{ CONST_STR_LEN("secdownload.uri-prefix"),
  451. T_CONFIG_STRING,
  452. T_CONFIG_SCOPE_CONNECTION }
  453. ,{ CONST_STR_LEN("secdownload.timeout"),
  454. T_CONFIG_INT,
  455. T_CONFIG_SCOPE_CONNECTION }
  456. ,{ CONST_STR_LEN("secdownload.algorithm"),
  457. T_CONFIG_STRING,
  458. T_CONFIG_SCOPE_CONNECTION }
  459. ,{ CONST_STR_LEN("secdownload.path-segments"),
  460. T_CONFIG_SHORT,
  461. T_CONFIG_SCOPE_CONNECTION }
  462. ,{ CONST_STR_LEN("secdownload.hash-querystr"),
  463. T_CONFIG_BOOL,
  464. T_CONFIG_SCOPE_CONNECTION }
  465. ,{ NULL, 0,
  466. T_CONFIG_UNSET,
  467. T_CONFIG_SCOPE_UNSET }
  468. };
  469. plugin_data * const p = p_d;
  470. if (!config_plugin_values_init(srv, p, cpk, "mod_secdownload"))
  471. return HANDLER_ERROR;
  472. /* process and validate config directives
  473. * (init i to 0 if global context; to 1 to skip empty global context) */
  474. for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
  475. config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
  476. for (; -1 != cpv->k_id; ++cpv) {
  477. switch (cpv->k_id) {
  478. case 0: /* secdownload.secret */
  479. case 1: /* secdownload.document-root */
  480. case 2: /* secdownload.uri-prefix */
  481. case 3: /* secdownload.timeout */
  482. break;
  483. case 4: /* secdownload.algorithm */
  484. if (!mod_secdownload_parse_algorithm(cpv, srv->errh))
  485. return HANDLER_ERROR;
  486. break;
  487. case 5: /* secdownload.path-segments */
  488. case 6: /* secdownload.hash-querystr */
  489. break;
  490. default:/* should not happen */
  491. break;
  492. }
  493. }
  494. }
  495. p->defaults.timeout = 60;
  496. /* initialize p->defaults from global config context */
  497. if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
  498. const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
  499. if (-1 != cpv->k_id)
  500. mod_secdownload_merge_config(&p->defaults, cpv);
  501. }
  502. return HANDLER_GO_ON;
  503. }
  504. /**
  505. * checks if the supplied string is a hex string
  506. *
  507. * @param str a possible hex string
  508. * @return if the supplied string is a valid hex string 1 is returned otherwise 0
  509. */
  510. static int is_hex_len(const char *str, size_t len) {
  511. size_t i;
  512. if (NULL == str) return 0;
  513. for (i = 0; i < len && *str; i++, str++) {
  514. /* illegal characters */
  515. if (!light_isxdigit(*str))
  516. return 0;
  517. }
  518. return i == len;
  519. }
  520. /**
  521. * checks if the supplied string is a base64 (modified URL) string
  522. *
  523. * @param str a possible base64 (modified URL) string
  524. * @return if the supplied string is a valid base64 (modified URL) string 1 is returned otherwise 0
  525. */
  526. static int is_base64_len(const char *str, size_t len) {
  527. size_t i;
  528. if (NULL == str) return 0;
  529. for (i = 0; i < len && *str; i++, str++) {
  530. /* illegal characters */
  531. if (!(light_isalnum(*str) || *str == '-' || *str == '_'))
  532. return 0;
  533. }
  534. return i == len;
  535. }
  536. URIHANDLER_FUNC(mod_secdownload_uri_handler) {
  537. plugin_data *p = p_d;
  538. const char *rel_uri, *ts_str, *mac_str, *protected_path;
  539. time_t ts = 0;
  540. size_t i, mac_len;
  541. if (NULL != r->handler_module) return HANDLER_GO_ON;
  542. #ifdef __COVERITY__
  543. if (buffer_is_empty(&r->uri.path)) return HANDLER_GO_ON;
  544. #endif
  545. mod_secdownload_patch_config(r, p);
  546. if (buffer_string_is_empty(p->conf.uri_prefix)) return HANDLER_GO_ON;
  547. if (buffer_string_is_empty(p->conf.secret)) {
  548. log_error(r->conf.errh, __FILE__, __LINE__,
  549. "secdownload.secret has to be set");
  550. r->http_status = 500;
  551. return HANDLER_FINISHED;
  552. }
  553. if (buffer_string_is_empty(p->conf.doc_root)) {
  554. log_error(r->conf.errh, __FILE__, __LINE__,
  555. "secdownload.document-root has to be set");
  556. r->http_status = 500;
  557. return HANDLER_FINISHED;
  558. }
  559. if (SECDL_INVALID == p->conf.algorithm) {
  560. log_error(r->conf.errh, __FILE__, __LINE__,
  561. "secdownload.algorithm has to be set");
  562. r->http_status = 500;
  563. return HANDLER_FINISHED;
  564. }
  565. mac_len = secdl_algorithm_mac_length(p->conf.algorithm);
  566. if (0 != strncmp(r->uri.path.ptr, p->conf.uri_prefix->ptr, buffer_string_length(p->conf.uri_prefix))) return HANDLER_GO_ON;
  567. mac_str = r->uri.path.ptr + buffer_string_length(p->conf.uri_prefix);
  568. if (!is_base64_len(mac_str, mac_len)) return HANDLER_GO_ON;
  569. protected_path = mac_str + mac_len;
  570. if (*protected_path != '/') return HANDLER_GO_ON;
  571. ts_str = protected_path + 1;
  572. if (!is_hex_len(ts_str, 8)) return HANDLER_GO_ON;
  573. if (*(ts_str + 8) != '/') return HANDLER_GO_ON;
  574. for (i = 0; i < 8; i++) {
  575. ts = (ts << 4) + hex2int(ts_str[i]);
  576. }
  577. const time_t cur_ts = log_epoch_secs;
  578. /* timed-out */
  579. if ( (cur_ts > ts && (unsigned int) (cur_ts - ts) > p->conf.timeout) ||
  580. (cur_ts < ts && (unsigned int) (ts - cur_ts) > p->conf.timeout) ) {
  581. /* "Gone" as the url will never be valid again instead of "408 - Timeout" where the request may be repeated */
  582. r->http_status = 410;
  583. return HANDLER_FINISHED;
  584. }
  585. rel_uri = ts_str + 8;
  586. buffer * const tb = r->tmp_buf;
  587. if (p->conf.path_segments) {
  588. const char *rel_uri_end = rel_uri;
  589. unsigned int count = p->conf.path_segments;
  590. do {
  591. rel_uri_end = strchr(rel_uri_end+1, '/');
  592. } while (rel_uri_end && --count);
  593. if (rel_uri_end) {
  594. buffer_copy_string_len(tb, protected_path,
  595. rel_uri_end - protected_path);
  596. protected_path = tb->ptr;
  597. }
  598. }
  599. if (p->conf.hash_querystr && !buffer_is_empty(&r->uri.query)) {
  600. if (protected_path != tb->ptr) {
  601. buffer_copy_string(tb, protected_path);
  602. }
  603. buffer_append_string_len(tb, CONST_STR_LEN("?"));
  604. buffer_append_string_buffer(tb, &r->uri.query);
  605. /* assign last in case tb->ptr is reallocated */
  606. protected_path = tb->ptr;
  607. }
  608. if (!secdl_verify_mac(&p->conf, protected_path, mac_str, mac_len,
  609. r->conf.errh)) {
  610. r->http_status = 403;
  611. if (r->conf.log_request_handling) {
  612. log_error(r->conf.errh, __FILE__, __LINE__,
  613. "mac invalid: %s", r->uri.path.ptr);
  614. }
  615. return HANDLER_FINISHED;
  616. }
  617. /* starting with the last / we should have relative-path to the docroot
  618. */
  619. buffer_copy_buffer(&r->physical.doc_root, p->conf.doc_root);
  620. buffer_copy_buffer(&r->physical.basedir, p->conf.doc_root);
  621. buffer_copy_string(&r->physical.rel_path, rel_uri);
  622. buffer_copy_buffer(&r->physical.path, &r->physical.doc_root);
  623. buffer_append_string_buffer(&r->physical.path, &r->physical.rel_path);
  624. return HANDLER_GO_ON;
  625. }
  626. int mod_secdownload_plugin_init(plugin *p);
  627. int mod_secdownload_plugin_init(plugin *p) {
  628. p->version = LIGHTTPD_VERSION_ID;
  629. p->name = "secdownload";
  630. p->init = mod_secdownload_init;
  631. p->handle_physical = mod_secdownload_uri_handler;
  632. p->set_defaults = mod_secdownload_set_defaults;
  633. return 0;
  634. }