-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcontext.cpp
More file actions
1807 lines (1545 loc) · 60.7 KB
/
Copy pathcontext.cpp
File metadata and controls
1807 lines (1545 loc) · 60.7 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "context.h"
#include <atomic>
#include <charconv>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include "../datadog_conf.h"
#include "../datadog_handler.h"
#include "../ngx_http_datadog_module.h"
#include "blocking.h"
#include "body_parse/body_parsing.h"
#include "client_ip.h"
#include "collection.h"
#include "datadog_context.h"
#include "ddwaf_obj.h"
#include "header_tags.h"
#include "library.h"
#include "util.h"
extern "C" {
#include <ngx_buf.h>
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event_posted.h>
#include <ngx_files.h>
#include <ngx_hash.h>
#include <ngx_http.h>
#include <ngx_http_core_module.h>
#include <ngx_http_request.h>
#include <ngx_http_v2.h>
#include <ngx_log.h>
#include <ngx_regex.h>
#include <ngx_stream.h>
#include <ngx_string.h>
#include <ngx_thread_pool.h>
}
#include <datadog/span.h>
#include <datadog/trace_segment.h>
#include <ddwaf.h>
#include <rapidjson/document.h>
#include <rapidjson/encodings.h>
#include <rapidjson/prettywriter.h>
using namespace std::literals;
namespace {
namespace dnsec = datadog::nginx::security;
std::size_t chain_length(ngx_chain_t const *ch) {
std::size_t len = 0;
for (ngx_chain_t const *cl = ch; cl; cl = cl->next) {
len++;
}
return len;
}
std::size_t chain_size(ngx_chain_t const *ch) {
std::size_t size = 0;
for (ngx_chain_t const *cl = ch; cl; cl = cl->next) {
size += ngx_buf_size(cl->buf);
}
return size;
}
std::size_t has_special(ngx_chain_t const *ch) {
for (ngx_chain_t const *cl = ch; cl; cl = cl->next) {
return ngx_buf_special(cl->buf);
}
return false;
}
std::size_t has_last(ngx_chain_t const *ch) {
for (ngx_chain_t const *cl = ch; cl; cl = cl->next) {
if (cl->buf->last) {
return true;
}
}
return false;
}
class JsonWriter : public rapidjson::Writer<rapidjson::StringBuffer> {
using rapidjson::Writer<rapidjson::StringBuffer>::Writer;
public:
// NOLINTNEXTLINE(readability-identifier-naming)
bool ConstLiteralKey(std::string_view sv) {
return String(sv.data(), sv.length(), false);
}
};
void ddwaf_object_to_json(JsonWriter &w, const ddwaf_object &dobj);
void report_match(const ngx_http_request_t &req, dd::TraceSegment &seg,
dd::Span &span,
std::vector<dnsec::OwnedDdwafResult> &results) {
if (results.empty()) {
return;
}
seg.override_sampling_priority(2); // USER-KEEP
span.set_tag("appsec.event"sv, "true");
rapidjson::StringBuffer buffer;
JsonWriter w(buffer);
w.StartObject();
w.ConstLiteralKey("triggers"sv);
w.StartArray();
for (auto &&result : results) {
auto events = dnsec::ddwaf_arr_obj{(*result).events};
for (auto &&evt : events) {
ddwaf_object_to_json(w, evt);
}
}
w.EndArray(results.size());
w.EndObject(1);
w.Flush();
std::string_view const json{buffer.GetString(), buffer.GetLength()};
ngx_str_t json_ns{dnsec::ngx_stringv(json)};
ngx_log_error(NGX_LOG_INFO, req.connection->log, 0, "appsec event: %V",
&json_ns);
span.set_tag("_dd.appsec.json"sv, json);
}
// NOLINTNEXTLINE(misc-no-recursion)
void ddwaf_object_to_json(JsonWriter &w, const ddwaf_object &dobj) {
switch (dobj.type) {
case DDWAF_OBJ_MAP:
w.StartObject();
for (std::size_t i = 0; i < dobj.nbEntries; i++) {
auto &&e = dobj.array[i];
w.Key(e.parameterName, e.parameterNameLength, false);
ddwaf_object_to_json(w, e);
}
w.EndObject(dobj.nbEntries);
break;
case DDWAF_OBJ_ARRAY:
w.StartArray();
for (std::size_t i = 0; i < dobj.nbEntries; i++) {
auto &&e = dobj.array[i];
ddwaf_object_to_json(w, e);
}
w.EndArray(dobj.nbEntries);
break;
case DDWAF_OBJ_STRING:
w.String(dobj.stringValue, dobj.nbEntries, false);
break;
case DDWAF_OBJ_SIGNED:
w.Int64(dobj.intValue);
break;
case DDWAF_OBJ_UNSIGNED:
w.Uint64(dobj.uintValue);
break;
case DDWAF_OBJ_FLOAT:
w.Double(dobj.f64);
break;
case DDWAF_OBJ_BOOL:
w.Bool(dobj.boolean);
break;
case DDWAF_OBJ_INVALID:
case DDWAF_OBJ_NULL:
w.Null();
break;
}
}
template <
typename Callable, typename Ret = decltype(std::declval<Callable>()()),
typename DefType = // can't have void arguments. Have a dummy parameter for
// this case to avoid having to write a specialization
std::conditional_t<std::is_same_v<Ret, void>, std::nullptr_t, Ret>>
auto catch_exceptions(std::string_view name, const ngx_http_request_t &req,
Callable &&f, DefType err_ret = {}) noexcept -> Ret {
try {
return std::invoke(std::forward<Callable>(f));
} catch (const std::exception &e) {
ngx_log_error(NGX_LOG_ERR, req.connection->log, 0,
"security_context::%.*s: %s", static_cast<int>(name.size()),
name.data(), e.what());
} catch (...) {
ngx_log_error(NGX_LOG_ERR, req.connection->log, 0,
"security_context::%.*s: unknown exception",
static_cast<int>(name.size()), name.data());
}
if constexpr (!std::is_same_v<Ret, void>) {
return err_ret;
}
}
} // namespace
namespace datadog::nginx::security {
Context::Context(std::shared_ptr<OwnedDdwafHandle> handle,
bool apm_tracing_enabled)
: stage_{new std::atomic<stage>{}},
waf_handle_{std::move(handle)},
apm_tracing_enabled_{apm_tracing_enabled} {
if (!waf_handle_) {
return;
}
ddwaf_handle ddwaf_h = waf_handle_->get();
ctx_ = ddwaf_context_init(ddwaf_h);
stage_->store(stage::START, std::memory_order_relaxed);
}
std::unique_ptr<Context> Context::maybe_create(
std::optional<std::size_t> max_saved_output_data,
bool apm_tracing_enabled) {
std::shared_ptr<OwnedDdwafHandle> handle = Library::get_handle();
if (!handle) {
return {};
}
auto res = std::unique_ptr<Context>{
new Context{std::move(handle), apm_tracing_enabled}};
if (max_saved_output_data) {
res->max_saved_output_data_ = *max_saved_output_data;
}
return res;
}
template <typename Self>
class PolTaskCtx {
PolTaskCtx(ngx_http_request_t &req, Context &ctx, dd::Span &span)
: req_{req},
ctx_{ctx},
span_{span},
prev_read_evt_handler_{req.read_event_handler},
prev_write_evt_handler_{req.write_event_handler} {}
public:
// the returned reference is request pool allocated and must have its
// destructor explicitly called if not submitted
template <typename... Args>
static Self &create(ngx_http_request_t &req, Context &ctx, dd::Span &span,
Args &&...extra_args) {
ngx_thread_task_t *task = ngx_thread_task_alloc(req.pool, sizeof(Self));
if (!task) {
throw std::runtime_error{"failed to allocate task"};
}
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
auto *task_ctx =
new (task->ctx) Self{req, ctx, span, std::forward<Args>(extra_args)...};
task->handler = &PolTaskCtx::handler;
task->event.handler = &PolTaskCtx::completion_handler;
task->event.data = task_ctx;
return *task_ctx;
}
bool submit(ngx_thread_pool_t *pool) noexcept {
as_self().replace_handlers();
req_.main->count++;
if (ngx_thread_task_post(pool, &get_task()) != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, req_.connection->log, 0,
"failed to post task %p", &get_task());
req_.main->count--;
as_self().restore_handlers();
as_self().~Self();
return false;
}
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"task %p submitted. Request refcount: %d", &get_task(),
req_.main->count);
return true;
}
private:
ngx_thread_task_t &get_task() noexcept {
// ngx_thread_task_alloc allocates space for the context right after the
// ngx_thread_task_t structure
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
return *reinterpret_cast<ngx_thread_task_t *>(
reinterpret_cast<char *>(this) - sizeof(ngx_thread_task_t));
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
}
ngx_log_t *req_log() const noexcept { return req_.connection->log; }
static void handler(void *self, ngx_log_t *tp_log) noexcept {
static_cast<Self *>(self)->handle(tp_log);
}
// runs on the thread pool
void handle(ngx_log_t *tp_log) noexcept {
try {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_log(), 0, "before task %p main",
this);
block_spec_ = as_self().do_handle(*tp_log);
// test long libddwaf call
// ::usleep(2000000);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_log(), 0, "after task %p main",
this);
ran_on_thread_.store(true, std::memory_order_release);
} catch (std::exception &e) {
ngx_log_error(NGX_LOG_ERR, tp_log, 0, "task %p failed: %s", this,
e.what());
} catch (...) {
ngx_log_error(NGX_LOG_ERR, tp_log, 0, "task %p failed: unknown failure",
this);
}
}
// define in subclasses
std::optional<BlockSpecification> do_handle(ngx_log_t &log) = delete;
// runs on the main thread
static void completion_handler(ngx_event_t *evt) noexcept {
auto *self = static_cast<Self *>(evt->data);
self->completion_handler_impl();
}
void completion_handler_impl() noexcept {
as_self().restore_handlers();
auto count = req_.main->count;
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_log(), 0,
"refcount before decrement upon task %p completion: %d", this,
count);
if (count > 1) {
// ngx_del_event(connection->read, NGX_READ_EVENT, 0) may've been called
// by ngx_http_block_reading
if (ngx_handle_read_event(req_.connection->read, 0) != NGX_OK) {
ngx_http_finalize_request(&req_, NGX_HTTP_INTERNAL_SERVER_ERROR);
ngx_log_error(NGX_LOG_ERR, req_log(), 0,
"failed to re-enable read event after task %p", this);
} else {
req_.main->count--;
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, req_log(), 0,
"calling complete on task %p", this);
as_self().complete();
// req_ may be invalid at this point
}
} else {
ngx_log_debug1(
NGX_LOG_DEBUG_HTTP, req_log(), 0,
"skipping run of completion handler for task %p because "
"we're the only reference to the request; finalizing instead",
this);
ngx_http_finalize_request(&req_, NGX_DONE);
}
as_self().~Self();
}
// define in subclasses
void complete() noexcept = delete;
void replace_handlers() noexcept {
req_.read_event_handler = ngx_http_block_reading;
req_.write_event_handler = PolTaskCtx<Self>::empty_write_handler;
}
void restore_handlers() noexcept {
if (req_.read_event_handler == ngx_http_block_reading) {
req_.read_event_handler = prev_read_evt_handler_;
} else {
ngx_log_error(NGX_LOG_ERR, req_log(), 0,
"unexpected read event handler %p; not restoring",
req_.read_event_handler);
}
if (req_.write_event_handler == PolTaskCtx<Self>::empty_write_handler) {
req_.write_event_handler = prev_write_evt_handler_;
} else {
ngx_log_error(NGX_LOG_ERR, req_log(), 0,
"unexpected write event handler %p; not restoring",
req_.write_event_handler);
}
}
Self &as_self() { return *static_cast<Self *>(this); }
static void empty_write_handler(ngx_http_request_t *req) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, req->connection->log, 0,
"task wait empty handler");
ngx_event_t *wev = req->connection->write;
if (ngx_handle_write_event(wev, 0) != NGX_OK) {
ngx_http_finalize_request(req, NGX_HTTP_INTERNAL_SERVER_ERROR);
}
}
friend Self;
ngx_http_request_t &req_;
Context &ctx_;
dd::Span &span_;
std::optional<BlockSpecification> block_spec_;
ngx_http_event_handler_pt prev_read_evt_handler_;
ngx_http_event_handler_pt prev_write_evt_handler_;
std::atomic<bool> ran_on_thread_{false};
};
class Pol1stWafCtx : public PolTaskCtx<Pol1stWafCtx> {
using PolTaskCtx::PolTaskCtx;
std::optional<BlockSpecification> do_handle(ngx_log_t &tp_log) {
return ctx_.run_waf_start(req_, span_);
}
void complete() noexcept {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf start task: start");
bool const ran = ran_on_thread_.load(std::memory_order_acquire);
if (ran && block_spec_) {
span_.set_tag("appsec.blocked"sv, "true"sv);
auto *service = BlockingService::get_instance();
assert(service != nullptr);
ngx_int_t rc;
try {
rc = service->block(*block_spec_, req_);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf start task: sent blocking "
"response (rc: %d, c: %d)",
rc, req_.main->count);
} catch (const std::exception &e) {
ngx_log_error(NGX_LOG_ERR, req_.connection->log, 0,
"failed to block request: %s", e.what());
rc = NGX_ERROR;
}
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf start task: finish: calling "
"ngx_http_finalize_request with %d",
rc);
ngx_http_finalize_request(&req_, rc);
// the request may have been destroyed at this point
} else {
req_.phase_handler++; // move past us
ngx_post_event(req_.connection->write, &ngx_posted_events);
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf start task: normal finish");
}
}
friend PolTaskCtx;
};
bool Context::on_request_start(ngx_http_request_t &request,
dd::Span &span) noexcept {
return catch_exceptions("on_request_start"sv, request, [&]() {
return Context::do_on_request_start(request, span);
});
}
bool Context::do_on_request_start(ngx_http_request_t &request, dd::Span &span) {
if (ctx_.resource == nullptr) {
return false;
}
stage st = stage_->load(std::memory_order_relaxed);
if (st != stage::START) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"WAF context is not in the start stage. Internal redirect?");
return false;
}
auto *conf = static_cast<datadog_loc_conf_t *>(
ngx_http_get_module_loc_conf(&request, ngx_http_datadog_module));
if (conf->waf_pool == nullptr) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"no waf pool name defined for this location (uri: %V)",
&request.uri);
transition_to_stage(stage::DISABLED);
return false;
}
if (!stage_->compare_exchange_strong(st, stage::ENTERED_ON_START,
std::memory_order_release,
std::memory_order_relaxed)) {
ngx_log_error(NGX_LOG_ERR, request.connection->log, 0,
"Unexpected concurrent change of stage_");
return false;
}
auto &task_ctx = Pol1stWafCtx::create(request, *this, span);
if (task_ctx.submit(conf->waf_pool)) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"posted initial waf task");
return true;
}
return false;
}
namespace {
class Action {
public:
enum class type : unsigned char {
BLOCK_REQUEST,
REDIRECT_REQUEST,
GENERATE_STACK,
GENERATE_SCHEMA,
UNKNOWN,
};
Action(ddwaf_map_obj action) : action_{action} {}
auto type() const {
auto key = action_.key();
if (key == "block_request"sv) {
return type::BLOCK_REQUEST;
} else if (key == "redirect_request"sv) {
return type::REDIRECT_REQUEST;
} else if (key == "generate_stack"sv) {
return type::GENERATE_STACK;
} else if (key == "generate_schema"sv) {
return type::GENERATE_SCHEMA;
} else {
return type::UNKNOWN;
}
}
auto raw_type() const { return action_.key(); }
int get_int_param(std::string_view k) const {
ddwaf_obj v = action_.get(k);
if (v.is_numeric()) {
return v.numeric_val<int>();
}
if (!v.is_string()) {
throw std::runtime_error{"expected numeric value for action parameter " +
std::string{k}};
}
// try to convert to number
std::string_view const sv{v.string_val_unchecked()};
int n;
auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), n);
if (ec == std::errc{} && ptr == sv.data() + sv.size()) {
return n;
}
throw std::runtime_error{"expected numeric value for action parameter " +
std::string{k} + ", got " + std::string{sv}};
}
std::string_view get_string_param(std::string_view k) const {
ddwaf_obj v = action_.get(k);
if (v.is_string()) {
return v.string_val_unchecked();
}
throw std::runtime_error{"expected string value for action parameter " +
std::string{k}};
}
private:
ddwaf_map_obj action_;
};
class ActionsResult {
public:
ActionsResult(ddwaf_map_obj actions) : actions_{actions} {}
class Iterator {
public:
using difference_type = ddwaf_obj::nb_entries_t; // NOLINT
using value_type = Action; // NOLINT
using pointer = value_type *; // NOLINT
using reference = value_type &; // NOLINT
using iterator_category = std::forward_iterator_tag; // NOLINT
Iterator(ddwaf_map_obj actions, ddwaf_obj::nb_entries_t i)
: actions_{actions}, i_{i} {}
Iterator &operator++() {
++i_;
return *this;
}
bool operator!=(const Iterator &other) const { return i_ != other.i_; }
Action operator*() const {
return Action{actions_.at_unchecked<ddwaf_map_obj>(i_)};
}
private:
ddwaf_map_obj actions_;
ddwaf_obj::nb_entries_t i_;
};
Iterator begin() const { return Iterator{ddwaf_map_obj{actions_}, 0}; }
Iterator end() const {
return Iterator{ddwaf_map_obj{actions_}, actions_.size()};
}
private:
ddwaf_map_obj actions_;
};
BlockSpecification create_block_request_action(const Action &action) {
enum BlockSpecification::ContentType ct{
BlockSpecification::ContentType::AUTO};
int status = action.get_int_param("status_code"sv);
std::string_view const ct_sv = action.get_string_param("type"sv);
if (ct_sv == "auto"sv) {
ct = BlockSpecification::ContentType::AUTO;
} else if (ct_sv == "html"sv) {
ct = BlockSpecification::ContentType::HTML;
} else if (ct_sv == "json"sv) {
ct = BlockSpecification::ContentType::JSON;
} else if (ct_sv == "none"sv) {
ct = BlockSpecification::ContentType::NONE;
}
return BlockSpecification{status, ct};
}
BlockSpecification create_redirect_request_action(const Action &action) {
int status = action.get_int_param("status_code"sv);
std::string_view const loc = action.get_string_param("location"sv);
return {status, BlockSpecification::ContentType::NONE, loc};
}
std::optional<BlockSpecification> resolve_block_spec(
const ActionsResult &actions, ngx_log_t &log) {
for (Action act : actions) {
auto type = act.type();
if (type == Action::type::UNKNOWN) {
std::string_view raw_type = act.raw_type();
ngx_str_t raw_type_ns{dnsec::ngx_stringv(raw_type)};
ngx_log_error(NGX_LOG_WARN, &log, 0,
"WAF indicated action %V, but such action id is unknown",
&raw_type_ns);
continue;
}
if (type == Action::type::GENERATE_STACK ||
type == Action::type::GENERATE_SCHEMA) {
std::string_view raw_type = act.raw_type();
ngx_str_t raw_type_ns{dnsec::ngx_stringv(raw_type)};
ngx_log_error(NGX_LOG_NOTICE, &log, 0,
"WAF indicated action %V, but this action is "
"not supported. Ignoring.",
&raw_type_ns);
continue;
}
if (type == Action::type::BLOCK_REQUEST) {
return {create_block_request_action(act)};
}
if (type == Action::type::REDIRECT_REQUEST) {
return {create_redirect_request_action(act)};
}
}
return std::nullopt;
}
} // namespace
std::optional<BlockSpecification> Context::run_waf_start(
ngx_http_request_t &req, dd::Span &span) {
auto st = stage_->load(std::memory_order_acquire);
if (st != stage::ENTERED_ON_START) {
return std::nullopt;
}
span.set_metric("_dd.appsec.enabled"sv, 1.0);
span.set_tag("_dd.runtime_family", "cpp"sv);
static const std::string_view libddwaf_version{ddwaf_get_version()};
span.set_tag("_dd.appsec.waf.version", libddwaf_version);
dnsec::ClientIp ip_resolver{dnsec::Library::custom_ip_header(), req};
auto client_ip = ip_resolver.resolve();
ddwaf_object *data = collect_request_data(req, client_ip, memres_);
client_ip_ = std::move(client_ip);
ddwaf_result result;
auto code =
ddwaf_run(ctx_.resource, data, nullptr, &result, Library::waf_timeout());
std::optional<BlockSpecification> block_spec;
if (code == DDWAF_MATCH) {
results_.emplace_back(result);
ddwaf_map_obj actions_arr{result.actions};
if (!actions_arr.empty()) {
ActionsResult actions_res{actions_arr};
block_spec = resolve_block_spec(actions_arr, *req.connection->log);
}
} else {
ddwaf_result_free(&result);
}
if (block_spec) {
stage_->store(stage::AFTER_BEGIN_WAF_BLOCK, std::memory_order_release);
} else {
stage_->store(stage::AFTER_BEGIN_WAF, std::memory_order_release);
}
return block_spec;
}
ngx_int_t Context::header_filter(ngx_http_request_t &request,
dd::Span &span) noexcept {
return catch_exceptions(
"header_filter"sv, request,
[&]() { return Context::do_header_filter(request, span); },
static_cast<ngx_int_t>(NGX_ERROR));
}
ngx_int_t Context::request_body_filter(ngx_http_request_t &request,
ngx_chain_t *chain,
dd::Span &span) noexcept {
return catch_exceptions(
"request_body_filter"sv, request,
[&]() { return Context::do_request_body_filter(request, chain, span); },
static_cast<ngx_int_t>(NGX_ERROR));
}
ngx_int_t Context::output_body_filter(ngx_http_request_t &request,
ngx_chain_t *chain,
dd::Span &span) noexcept {
return catch_exceptions(
"output_body_filter"sv, request,
[&]() { return Context::do_output_body_filter(request, chain, span); },
static_cast<ngx_int_t>(NGX_ERROR));
}
class PolReqBodyWafCtx : public PolTaskCtx<PolReqBodyWafCtx> {
using PolTaskCtx::PolTaskCtx;
std::optional<BlockSpecification> do_handle(ngx_log_t &tp_log) {
return ctx_.run_waf_req_post(req_, span_);
}
void complete() noexcept {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req post task: start");
bool const ran = ran_on_thread_.load(std::memory_order_acquire);
if (ran && block_spec_) {
span_.set_tag("appsec.blocked"sv, "true"sv);
ctx_.waf_req_post_done(req_, true);
auto *service = BlockingService::get_instance();
assert(service != nullptr);
ngx_int_t rc;
try {
rc = service->block(*block_spec_, req_);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req post task: sent "
"blocking response (rc: %d, c: %d)",
rc, req_.main->count);
} catch (const std::exception &e) {
ngx_log_error(NGX_LOG_ERR, req_.connection->log, 0,
"failed to block request: %s", e.what());
rc = NGX_ERROR;
}
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf start task: finish: calling "
"ngx_http_finalize_request with %d",
rc);
ngx_http_finalize_request(&req_, rc);
// the request may have been destroyed at this point
} else {
ctx_.waf_req_post_done(req_, false);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"not blocking after request body waf run; "
"triggering read event on connection");
ngx_post_event(req_.connection->read, &ngx_posted_events);
}
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req post task: finish");
}
friend PolTaskCtx;
};
class PolFinalWafCtx : public PolTaskCtx<PolFinalWafCtx> {
using PolTaskCtx::PolTaskCtx;
std::optional<BlockSpecification> do_handle(ngx_log_t &tp_log) {
return ctx_.run_waf_end(req_, span_);
}
void complete() noexcept {
bool const ran = ran_on_thread_.load(std::memory_order_acquire);
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req final task (ran: %s, "
"blocked: %s): start",
ran ? "true" : "false", block_spec_ ? "true" : "false");
if (ran && block_spec_) {
span_.set_tag("appsec.blocked"sv, "true"sv);
ctx_.waf_final_done(req_, true);
auto *service = BlockingService::get_instance();
assert(service != nullptr);
ngx_int_t rc;
try {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req final task: sending "
"blocking response");
rc = service->block(*block_spec_, req_);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req final task: sent blocking "
"response (rc: %d, c: %d)",
rc, req_.main->count);
} catch (const std::exception &e) {
ngx_log_error(NGX_LOG_ERR, req_.connection->log, 0,
"failed to block request: %s", e.what());
rc = NGX_ERROR;
}
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"completion handler of waf req final task: calling "
"ngx_http_finalize_request with %d",
rc);
const auto count_before = req_.count;
ngx_http_finalize_request(&req_, rc);
// if count_before == 1, the request has likely been destroyed at this
// point, although we cannot be sure (e.g. there may be a post action)
if (count_before > 1) {
ngx_post_event(req_.connection->write, &ngx_posted_events);
}
// req_ may be invalid at this point
} else {
ctx_.waf_final_done(req_, false);
ngx_post_event(req_.connection->write, &ngx_posted_events);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, req_.connection->log, 0,
"not blocking after final waf run; triggering write event "
"on connection");
if (req_.upstream) {
// it may be that the body filter is never called again, so we have
// no chance to send the buffered data.
ctx_.prepare_drain_buffered_header(req_);
}
}
}
ngx_event_handler_pt orig_conn_write_handler_{};
void replace_handlers() noexcept {
auto &handler = req_.connection->write->handler;
orig_conn_write_handler_ = handler;
handler = ngx_http_empty_handler;
}
void restore_handlers() noexcept {
req_.connection->write->handler = orig_conn_write_handler_;
}
friend PolTaskCtx;
public:
bool submit(ngx_thread_pool_t *pool) noexcept {
bool submitted =
static_cast<PolTaskCtx<PolFinalWafCtx> *>(this)->submit(pool);
if (submitted) {
req_.header_sent = 1; // skip/alert when attempting to sent headers
}
return submitted;
}
};
ngx_int_t Context::do_request_body_filter(ngx_http_request_t &request,
ngx_chain_t *in, dd::Span &span) {
auto st = stage_->load(std::memory_order_acquire);
ngx_log_debug4(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"waf request body filter %s in chain. accumulated=%uz, "
"copied=%uz, Stage: %d",
in ? "with" : "without", filter_ctx_.out_total,
filter_ctx_.copied_total, st);
if (st == stage::AFTER_BEGIN_WAF) {
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"first filter call, req refcount=%d", request.main->count);
// buffer the request body during reading
// https://github.com/nginx/nginx/commit/67d160bf25e02ba6679bb6c3b9cbdfeb29b759de
// https://nginx.org/en/docs/dev/development_guide.html#http_request_body_filters
// this essentially avoids early req termination if buffers are not read
// (position advanced) by the filters. However, nginx doesn't keep calling
// the filters in that case. We use it to avoid synchronous calls to the
// filter after we collected enough data to call the WAF. Asynchronous calls
// are avoided by swapping the handlers before starting the WAF task.
request.request_body->filter_need_buffering = true;
if (in && in->buf->pos ==
request.header_in->pos - (in->buf->last - in->buf->pos)) {
// preread call by ngx_http_read_client_request_body.
// read and write handlers were not set yet, so don't launch the
// waf now. We'll do it on the next call.
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"1st preread call, no waf task submission yet");
st = transition_to_stage(stage::COLLECTING_ON_REQ_DATA_PREREAD);
} else {
st = transition_to_stage(stage::COLLECTING_ON_REQ_DATA);
}
}
if (st == stage::COLLECTING_ON_REQ_DATA_PREREAD) {
// we're guaranteed to be called again synchronously, so we shouldn't
// call the WAF at this point
if (buffer_chain(filter_ctx_, *request.pool, in, true) != NGX_OK) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
st = transition_to_stage(stage::COLLECTING_ON_REQ_DATA);
} else if (st == stage::COLLECTING_ON_REQ_DATA) {
// check if we have enough data to run the WAF
size_t new_size = filter_ctx_.out_total;
bool is_last = filter_ctx_.found_last;
for (auto *cl = in; cl; cl = cl->next) {
new_size += cl->buf->last - cl->buf->pos;
is_last = is_last || cl->buf->last_buf;
}
bool run_waf = is_last || new_size >= kMaxFilterData;
if (run_waf) {
// do not consume the buffer so that this filter is not called again
if (buffer_chain(filter_ctx_, *request.pool, in, false) != NGX_OK) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
if (filter_ctx_.out_total == 0) {
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"no data to run WAF on");
transition_to_stage(stage::AFTER_ON_REQ_WAF);
goto pass_downstream;
}
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"running WAF on %lu bytes of data (found last: %s)",
new_size, is_last ? "true" : "false");
PolReqBodyWafCtx &task_ctx =
PolReqBodyWafCtx::create(request, *this, span);
transition_to_stage(stage::SUSPENDED_ON_REQ_WAF);
auto *conf = static_cast<datadog_loc_conf_t *>(
ngx_http_get_module_loc_conf(&request, ngx_http_datadog_module));
if (task_ctx.submit(conf->waf_pool)) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"posted request body waf req post task");
} else {
transition_to_stage(stage::AFTER_ON_REQ_WAF);
ngx_log_error(NGX_LOG_NOTICE, request.connection->log, 0,
"posted request body waf req post task failed. Passing "
"data to downstream filters immediately");
goto pass_downstream;
}
} else { // !run_waf; we need more data
if (buffer_chain(filter_ctx_, *request.pool, in, true) != NGX_OK) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
}
} else if (st == stage::AFTER_ON_REQ_WAF ||
st == stage::AFTER_ON_REQ_WAF_BLOCK) {
if (filter_ctx_.out) { // first call after WAF ended
ngx_log_debug1(NGX_LOG_DEBUG_HTTP, request.connection->log, 0,
"first filter call after WAF ended, req refcount=%d",
request.main->count);
if (buffer_chain(filter_ctx_, *request.pool, in, false) != NGX_OK) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
pass_downstream:
// pass saved buffers downstream
auto rc = ngx_http_next_request_body_filter(&request, filter_ctx_.out);
filter_ctx_.clear(*request.pool);
return rc;
}
return ngx_http_next_request_body_filter(&request, in);
} else if (st == stage::SUSPENDED_ON_REQ_WAF) {