-
Notifications
You must be signed in to change notification settings - Fork 62
/
awssig.rs
349 lines (311 loc) · 10.9 KB
/
awssig.rs
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
use std::ffi::{c_char, c_void};
use std::ptr::addr_of;
use http::HeaderMap;
use ngx::core;
use ngx::ffi::{
nginx_version, ngx_array_push, ngx_command_t, ngx_conf_t, ngx_http_core_module, ngx_http_handler_pt,
ngx_http_module_t, ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t,
NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_MODULE, NGX_HTTP_SRV_CONF, NGX_RS_HTTP_LOC_CONF_OFFSET,
NGX_RS_MODULE_SIGNATURE,
};
use ngx::http::*;
use ngx::{http_request_handler, ngx_log_debug_http, ngx_null_command, ngx_string};
struct Module;
impl HTTPModule for Module {
type MainConf = ();
type SrvConf = ();
type LocConf = ModuleConfig;
unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
let cmcf = ngx_http_conf_get_module_main_conf(cf, &*addr_of!(ngx_http_core_module));
let h = ngx_array_push(&mut (*cmcf).phases[ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE as usize].handlers)
as *mut ngx_http_handler_pt;
if h.is_null() {
return core::Status::NGX_ERROR.into();
}
// set an phase handler
*h = Some(awssigv4_header_handler);
core::Status::NGX_OK.into()
}
}
#[derive(Debug, Default)]
struct ModuleConfig {
enable: bool,
access_key: String,
secret_key: String,
s3_bucket: String,
s3_endpoint: String,
}
#[no_mangle]
static mut ngx_http_awssigv4_commands: [ngx_command_t; 6] = [
ngx_command_t {
name: ngx_string!("awssigv4"),
type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(ngx_http_awssigv4_commands_set_enable),
conf: NGX_RS_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: std::ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("awssigv4_access_key"),
type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(ngx_http_awssigv4_commands_set_access_key),
conf: NGX_RS_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: std::ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("awssigv4_secret_key"),
type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(ngx_http_awssigv4_commands_set_secret_key),
conf: NGX_RS_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: std::ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("awssigv4_s3_bucket"),
type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(ngx_http_awssigv4_commands_set_s3_bucket),
conf: NGX_RS_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: std::ptr::null_mut(),
},
ngx_command_t {
name: ngx_string!("awssigv4_s3_endpoint"),
type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
set: Some(ngx_http_awssigv4_commands_set_s3_endpoint),
conf: NGX_RS_HTTP_LOC_CONF_OFFSET,
offset: 0,
post: std::ptr::null_mut(),
},
ngx_null_command!(),
];
#[no_mangle]
static ngx_http_awssigv4_module_ctx: ngx_http_module_t = ngx_http_module_t {
preconfiguration: Some(Module::preconfiguration),
postconfiguration: Some(Module::postconfiguration),
create_main_conf: Some(Module::create_main_conf),
init_main_conf: Some(Module::init_main_conf),
create_srv_conf: Some(Module::create_srv_conf),
merge_srv_conf: Some(Module::merge_srv_conf),
create_loc_conf: Some(Module::create_loc_conf),
merge_loc_conf: Some(Module::merge_loc_conf),
};
// Generate the `ngx_modules` table with exported modules.
// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem.
#[cfg(feature = "export-modules")]
ngx::ngx_modules!(ngx_http_awssigv4_module);
#[no_mangle]
#[used]
pub static mut ngx_http_awssigv4_module: ngx_module_t = ngx_module_t {
ctx_index: ngx_uint_t::MAX,
index: ngx_uint_t::MAX,
name: std::ptr::null_mut(),
spare0: 0,
spare1: 0,
version: nginx_version as ngx_uint_t,
signature: NGX_RS_MODULE_SIGNATURE.as_ptr() as *const c_char,
ctx: &ngx_http_awssigv4_module_ctx as *const _ as *mut _,
commands: unsafe { &ngx_http_awssigv4_commands[0] as *const _ as *mut _ },
type_: NGX_HTTP_MODULE as ngx_uint_t,
init_master: None,
init_module: None,
init_process: None,
init_thread: None,
exit_thread: None,
exit_process: None,
exit_master: None,
spare_hook0: 0,
spare_hook1: 0,
spare_hook2: 0,
spare_hook3: 0,
spare_hook4: 0,
spare_hook5: 0,
spare_hook6: 0,
spare_hook7: 0,
};
impl Merge for ModuleConfig {
fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> {
if prev.enable {
self.enable = true;
};
if self.access_key.is_empty() {
self.access_key = String::from(if !prev.access_key.is_empty() {
&prev.access_key
} else {
""
});
}
if self.enable && self.access_key.is_empty() {
return Err(MergeConfigError::NoValue);
}
if self.secret_key.is_empty() {
self.secret_key = String::from(if !prev.secret_key.is_empty() {
&prev.secret_key
} else {
""
});
}
if self.enable && self.secret_key.is_empty() {
return Err(MergeConfigError::NoValue);
}
if self.s3_bucket.is_empty() {
self.s3_bucket = String::from(if !prev.s3_bucket.is_empty() {
&prev.s3_bucket
} else {
""
});
}
if self.enable && self.s3_bucket.is_empty() {
return Err(MergeConfigError::NoValue);
}
if self.s3_endpoint.is_empty() {
self.s3_endpoint = String::from(if !prev.s3_endpoint.is_empty() {
&prev.s3_endpoint
} else {
"s3.amazonaws.com"
});
}
Ok(())
}
}
#[no_mangle]
extern "C" fn ngx_http_awssigv4_commands_set_enable(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
unsafe {
let conf = &mut *(conf as *mut ModuleConfig);
let args = (*(*cf).args).elts as *mut ngx_str_t;
let val = (*args.add(1)).to_str();
// set default value optionally
conf.enable = false;
if val.len() == 2 && val.eq_ignore_ascii_case("on") {
conf.enable = true;
} else if val.len() == 3 && val.eq_ignore_ascii_case("off") {
conf.enable = false;
}
};
std::ptr::null_mut()
}
#[no_mangle]
extern "C" fn ngx_http_awssigv4_commands_set_access_key(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
unsafe {
let conf = &mut *(conf as *mut ModuleConfig);
let args = (*(*cf).args).elts as *mut ngx_str_t;
conf.access_key = (*args.add(1)).to_string();
};
std::ptr::null_mut()
}
#[no_mangle]
extern "C" fn ngx_http_awssigv4_commands_set_secret_key(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
unsafe {
let conf = &mut *(conf as *mut ModuleConfig);
let args = (*(*cf).args).elts as *mut ngx_str_t;
conf.secret_key = (*args.add(1)).to_string();
};
std::ptr::null_mut()
}
#[no_mangle]
extern "C" fn ngx_http_awssigv4_commands_set_s3_bucket(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
unsafe {
let conf = &mut *(conf as *mut ModuleConfig);
let args = (*(*cf).args).elts as *mut ngx_str_t;
conf.s3_bucket = (*args.add(1)).to_string();
if conf.s3_bucket.len() == 1 {
println!("Validation failed");
return ngx::core::NGX_CONF_ERROR as _;
}
};
std::ptr::null_mut()
}
#[no_mangle]
extern "C" fn ngx_http_awssigv4_commands_set_s3_endpoint(
cf: *mut ngx_conf_t,
_cmd: *mut ngx_command_t,
conf: *mut c_void,
) -> *mut c_char {
unsafe {
let conf = &mut *(conf as *mut ModuleConfig);
let args = (*(*cf).args).elts as *mut ngx_str_t;
conf.s3_endpoint = (*args.add(1)).to_string();
};
std::ptr::null_mut()
}
http_request_handler!(awssigv4_header_handler, |request: &mut Request| {
// get Module Config from request
let conf = unsafe { request.get_module_loc_conf::<ModuleConfig>(&*addr_of!(ngx_http_awssigv4_module)) };
let conf = conf.unwrap();
ngx_log_debug_http!(request, "AWS signature V4 module {}", {
if conf.enable {
"enabled"
} else {
"disabled"
}
});
if !conf.enable {
return core::Status::NGX_DECLINED;
}
// TODO: build url properly from the original URL from client
let method = request.method();
if !matches!(method, ngx::http::Method::HEAD | ngx::http::Method::GET) {
return HTTPStatus::FORBIDDEN.into();
}
let datetime = chrono::Utc::now();
let uri = match request.unparsed_uri().to_str() {
Ok(v) => format!("https://{}.{}{}", conf.s3_bucket, conf.s3_endpoint, v),
Err(_) => return core::Status::NGX_DECLINED,
};
let datetime_now = datetime.format("%Y%m%dT%H%M%SZ");
let datetime_now = datetime_now.to_string();
let signature = {
// NOTE: aws_sign_v4::AwsSign::new() implementation requires a HeaderMap.
// Iterate over requests headers_in and copy into HeaderMap
// Copy only headers that will be used to sign the request
let mut headers = HeaderMap::new();
for (name, value) in request.headers_in_iterator() {
if name.to_lowercase() == "host" {
headers.insert(http::header::HOST, value.parse().unwrap());
}
}
headers.insert("X-Amz-Date", datetime_now.parse().unwrap());
ngx_log_debug_http!(request, "headers {:?}", headers);
ngx_log_debug_http!(request, "method {:?}", method);
ngx_log_debug_http!(request, "uri {:?}", uri);
ngx_log_debug_http!(request, "datetime_now {:?}", datetime_now);
let s = aws_sign_v4::AwsSign::new(
method.as_str(),
&uri,
&datetime,
&headers,
"us-east-1",
conf.access_key.as_str(),
conf.secret_key.as_str(),
"s3",
"",
);
s.sign()
};
request.add_header_in("authorization", signature.as_str());
request.add_header_in("X-Amz-Date", datetime_now.as_str());
// done signing, let's print values we have in request.headers_out, request.headers_in
for (name, value) in request.headers_out_iterator() {
ngx_log_debug_http!(request, "headers_out {}: {}", name, value);
}
for (name, value) in request.headers_in_iterator() {
ngx_log_debug_http!(request, "headers_in {}: {}", name, value);
}
core::Status::NGX_OK
});