Line data Source code
1 : #ifndef DDEBUG
2 : #define DDEBUG 0
3 : #endif
4 : #include "ddebug.h"
5 :
6 :
7 : #include <ndk.h>
8 : #include "ngx_http_set_secure_random.h"
9 : #include <stdlib.h>
10 :
11 :
12 : enum {
13 : MAX_RANDOM_STRING = 64,
14 : ALPHANUM = 1,
15 : LCALPHA = 2
16 : };
17 :
18 :
19 : static ngx_int_t
20 : ngx_http_set_misc_set_secure_random_common(int alphabet_type,
21 : ngx_http_request_t *r, ngx_str_t *res, ngx_http_variable_value_t *v);
22 :
23 :
24 : ngx_int_t
25 0 : ngx_http_set_misc_set_secure_random_alphanum(ngx_http_request_t *r,
26 : ngx_str_t *res, ngx_http_variable_value_t *v)
27 : {
28 0 : return ngx_http_set_misc_set_secure_random_common(ALPHANUM, r, res, v);
29 : }
30 :
31 :
32 : ngx_int_t
33 0 : ngx_http_set_misc_set_secure_random_lcalpha(ngx_http_request_t *r,
34 : ngx_str_t *res, ngx_http_variable_value_t *v)
35 : {
36 0 : return ngx_http_set_misc_set_secure_random_common(LCALPHA, r, res, v);
37 : }
38 :
39 :
40 : static ngx_int_t
41 0 : ngx_http_set_misc_set_secure_random_common(int alphabet_type,
42 : ngx_http_request_t *r, ngx_str_t *res, ngx_http_variable_value_t *v)
43 : {
44 : static u_char alphabet[] = "abcdefghijklmnopqrstuvwxyz"
45 : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
46 :
47 : u_char entropy[MAX_RANDOM_STRING];
48 : u_char output[MAX_RANDOM_STRING];
49 : ngx_int_t length, i;
50 : ngx_fd_t fd;
51 : ssize_t n;
52 :
53 0 : length = ngx_atoi(v->data, v->len);
54 :
55 0 : if (length == NGX_ERROR || length < 1 || length > MAX_RANDOM_STRING) {
56 0 : ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
57 : "set_random: bad \"length\" argument: %v", v);
58 0 : return NGX_ERROR;
59 : }
60 :
61 0 : fd = ngx_open_file((u_char *) "/dev/urandom", NGX_FILE_RDONLY,
62 : NGX_FILE_OPEN, 0);
63 0 : if (fd == NGX_INVALID_FILE) {
64 0 : ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
65 : "set_secure_random: could not open /dev/urandom");
66 0 : return NGX_ERROR;
67 : }
68 :
69 0 : n = ngx_read_fd(fd, entropy, length);
70 0 : if (n != length) {
71 0 : ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
72 : "set_secure_random: could not read all %i byte(s) from "
73 : "/dev/urandom", length);
74 0 : return NGX_ERROR;
75 : }
76 :
77 0 : ngx_close_file(fd);
78 :
79 0 : for (i = 0; i < length; i++) {
80 0 : if (alphabet_type == LCALPHA) {
81 0 : output[i] = entropy[i] % 26 + 'a';
82 :
83 : } else {
84 0 : output[i] = alphabet[ entropy[i] % (sizeof alphabet - 1) ];
85 : }
86 : }
87 :
88 0 : res->data = ngx_palloc(r->pool, length);
89 0 : if (res->data == NULL) {
90 0 : return NGX_ERROR;
91 : }
92 :
93 0 : ngx_memcpy(res->data, output, length);
94 :
95 0 : res->len = length;
96 :
97 : /* set all required params */
98 0 : v->valid = 1;
99 0 : v->no_cacheable = 0;
100 0 : v->not_found = 0;
101 :
102 0 : return NGX_OK;
103 : }
|