forked from kismetwireless/kismet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
alertracker.cc
843 lines (646 loc) · 24.6 KB
/
alertracker.cc
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
/*
This file is part of Kismet
Kismet is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kismet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Kismet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <string>
#include <vector>
#include <sstream>
#include "alertracker.h"
#include "devicetracker.h"
#include "configfile.h"
#include "json_adapter.h"
#include "structured.h"
#include "kismet_json.h"
#include "base64.h"
#include "kis_databaselogfile.h"
Alertracker::Alertracker(GlobalRegistry *in_globalreg) :
Kis_Net_Httpd_CPPStream_Handler() {
globalreg = in_globalreg;
next_alert_id = 0;
if (globalreg->kismet_config == NULL) {
fprintf(stderr, "FATAL OOPS: Alertracker called with null config\n");
exit(1);
}
#ifdef PRELUDE
// Start client Prelude
int ret;
ret = prelude_init(0, NULL);
if (ret < 0) {
_MSG("Alertracker - Failed to initialize Prelude SIEM connection", MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
PreludeInitClient(PRELUDE_ANALYZER_MODEL);
#endif
packetchain = Globalreg::FetchMandatoryGlobalAs<Packetchain>(globalreg, "PACKETCHAIN");
entrytracker = Globalreg::FetchMandatoryGlobalAs<EntryTracker>(globalreg, "ENTRYTRACKER");
if (globalreg->kismet_config->FetchOpt("alertbacklog") != "") {
int scantmp;
if (sscanf(globalreg->kismet_config->FetchOpt("alertbacklog").c_str(),
"%d", &scantmp) != 1 || scantmp < 0) {
globalreg->messagebus->InjectMessage("Illegal value for 'alertbacklog' "
"in config file", MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
num_backlog = scantmp;
}
// Parse config file vector of all alerts
if (ParseAlertConfig(globalreg->kismet_config) < 0) {
_MSG("Failed to parse alert values from Kismet config file", MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
alert_vec_id =
entrytracker->RegisterField("kismet.alert.list",
TrackerElementFactory<TrackerElementVector>(),
"list of alerts");
alert_timestamp_id =
entrytracker->RegisterField("kismet.alert.timestamp",
TrackerElementFactory<TrackerElementDouble>(),
"alert update timestamp");
alert_entry_id =
entrytracker->RegisterField("kismet.alert.alert",
TrackerElementFactory<tracked_alert>(),
"Kismet alert");
alert_defs_vec =
entrytracker->RegisterAndGetFieldAs<TrackerElementVector>("kismet.alert.definition_list",
TrackerElementFactory<TrackerElementVector>(),
"Kismet alert definitions");
alert_def_id =
entrytracker->RegisterField("kismet.alert.alert_definition",
TrackerElementFactory<tracked_alert_definition>(),
"Kismet alert definition");
// Register the alert component
_PCM(PACK_COMP_ALERT) =
packetchain->RegisterPacketComponent("alert");
// Register a KISMET alert type with no rate restrictions
_ARM(ALERT_REF_KISMET) =
RegisterAlert("KISMET", "Server events", sat_day, 0, sat_day, 0, KIS_PHY_ANY);
log_alerts = globalreg->kismet_config->FetchOptBoolean("kis_log_alerts", true);
}
Alertracker::~Alertracker() {
local_locker lock(&alert_mutex);
globalreg->RemoveGlobal("ALERTTRACKER");
globalreg->alertracker = NULL;
#ifdef PRELUDE
prelude_deinit();
delete prelude_client;
#endif
}
void Alertracker::PreludeInitClient(const char *analyzer_name) {
#ifdef PRELUDE
try {
string version =
globalreg->version_major + "." +
globalreg->version_minor + "." +
globalreg->version_tiny;
prelude_client =
new Prelude::ClientEasy(analyzer_name, 4, PRELUDE_ANALYZER_MODEL,
PRELUDE_ANALYZER_CLASS, PRELUDE_ANALYZER_MANUFACTURER, version.c_str());
prelude_client->start();
} catch (Prelude::PreludeError const & error) {
_MSG(std::string("Alertracker failed to initialize connection to Prelude: ") +
error.what(), MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
#endif
}
int Alertracker::RegisterAlert(std::string in_header, std::string in_description,
alert_time_unit in_unit, int in_rate, alert_time_unit in_burstunit,
int in_burst, int in_phy) {
local_locker lock(&alert_mutex);
// Bail if this header is registered
if (alert_name_map.find(in_header) != alert_name_map.end()) {
_MSG("Tried to re-register duplicate alert " + in_header, MSGFLAG_ERROR);
return -1;
}
// Make sure we're not going to overstep our range
if ((unsigned int) in_burstunit > sat_day)
in_burstunit = sat_day;
if ((unsigned int) in_unit > sat_day)
in_unit = sat_day;
// Bail if the rates are impossible
if (in_burstunit > in_unit) {
_MSG("Failed to register alert " + in_header + ", time unit for "
"burst rate must be less than or equal to the time unit "
"for the max rate", MSGFLAG_ERROR);
return -1;
}
auto arec =
std::make_shared<tracked_alert_definition>(alert_def_id);
arec->set_alert_ref(next_alert_id++);
arec->set_header(StrUpper(in_header));
arec->set_description(in_description);
arec->set_limit_unit(in_unit);
arec->set_limit_rate(in_rate);
arec->set_burst_unit(in_burstunit);
arec->set_limit_burst(in_burst);
arec->set_phy(in_phy);
arec->set_time_last(0);
alert_name_map[arec->get_header()] = arec->get_alert_ref();
alert_ref_map[arec->get_alert_ref()] = arec;
alert_defs_vec->push_back(arec);
return arec->get_alert_ref();
}
int Alertracker::FetchAlertRef(std::string in_header) {
local_locker lock(&alert_mutex);
if (alert_name_map.find(in_header) != alert_name_map.end())
return alert_name_map[in_header];
return -1;
}
int Alertracker::CheckTimes(shared_alert_def arec) {
// Alerts limited to 0 are squelched
if (arec->get_limit_rate() == 0) {
return 0;
}
struct timeval now;
gettimeofday(&now, NULL);
// If the last time we sent anything was longer than the main rate limit,
// then we reset back to empty
if (arec->get_time_last() < (now.tv_sec -
alert_time_unit_conv[arec->get_limit_unit()])) {
arec->set_total_sent(0);
arec->set_burst_sent(0);
return 1;
}
// If the last time we sent anything was longer than the burst rate, we can
// reset the burst to 0
if (arec->get_time_last() < (now.tv_sec -
alert_time_unit_conv[arec->get_burst_unit()])) {
arec->set_burst_sent(0);
}
// If we're under the limit on both, we're good to go
if (arec->get_burst_sent() < arec->get_limit_burst() &&
arec->get_total_sent() < arec->get_limit_rate())
return 1;
return 0;
}
int Alertracker::PotentialAlert(int in_ref) {
local_locker lock(&alert_mutex);
std::map<int, shared_alert_def>::iterator aritr = alert_ref_map.find(in_ref);
if (aritr == alert_ref_map.end())
return 0;
shared_alert_def arec = aritr->second;
return CheckTimes(arec);
}
int Alertracker::RaiseAlert(int in_ref, kis_packet *in_pack,
mac_addr bssid, mac_addr source, mac_addr dest,
mac_addr other, std::string in_channel, std::string in_text) {
local_demand_locker lock(&alert_mutex);
lock.lock();
std::map<int, shared_alert_def>::iterator aritr = alert_ref_map.find(in_ref);
if (aritr == alert_ref_map.end())
return -1;
shared_alert_def arec = aritr->second;
if (CheckTimes(arec) != 1)
return 0;
lock.unlock();
kis_alert_info *info = new kis_alert_info;
info->header = arec->get_header();
info->phy = arec->get_phy();
gettimeofday(&(info->tm), NULL);
info->bssid = bssid;
info->source = source;
info->dest = dest;
info->other = other;
info->channel = in_channel;
info->text = in_text;
// Increment and set the timers
arec->inc_burst_sent(1);
arec->inc_total_sent(1);
arec->set_time_last(ts_to_double(info->tm));
lock.lock();
alert_backlog.push_back(info);
if ((int) alert_backlog.size() > num_backlog) {
delete alert_backlog[0];
alert_backlog.erase(alert_backlog.begin());
}
lock.unlock();
// Try to get the existing alert info
if (in_pack != NULL) {
kis_alert_component *acomp =
(kis_alert_component *) in_pack->fetch(_PCM(PACK_COMP_ALERT));
// if we don't have an alert container, make one on this packet
if (acomp == NULL) {
acomp = new kis_alert_component;
in_pack->insert(_PCM(PACK_COMP_ALERT), acomp);
}
// Attach it to the packet
acomp->alert_vec.push_back(info);
}
#ifdef PRELUDE
// Send alert to Prelude
RaisePreludeAlert(in_ref, in_pack, info->bssid, info->source,
info->dest, info->other, info->channel, info->text);
#endif
// Send the text info
_MSG(info->header + " " + info->text, MSGFLAG_ALERT);
if (log_alerts) {
std::shared_ptr<KisDatabaseLogfile> dbf =
Globalreg::FetchGlobalAs<KisDatabaseLogfile>(globalreg, "DATABASELOG");
if (dbf != NULL) {
auto ta = std::make_shared<tracked_alert>(alert_entry_id);
ta->from_alert_info(info);
dbf->log_alert(ta);
}
}
return 1;
}
int Alertracker::RaiseOneShot(std::string in_header, std::string in_text, int in_phy) {
local_demand_locker lock(&alert_mutex);
kis_alert_info *info = new kis_alert_info;
info->header = in_header;
info->phy = in_phy;
gettimeofday(&(info->tm), NULL);
info->bssid = mac_addr(0);
info->source = mac_addr(0);
info->dest = mac_addr(0);
info->other = mac_addr(0);
info->channel = "";
info->text = in_text;
lock.lock();
alert_backlog.push_back(info);
if ((int) alert_backlog.size() > num_backlog) {
delete alert_backlog[0];
alert_backlog.erase(alert_backlog.begin());
}
lock.unlock();
#ifdef PRELUDE
// Send alert to Prelude
RaisePreludeOneShot(in_header, in_text);
#endif
// Send the text info
_MSG(info->header + " " + info->text, MSGFLAG_ALERT);
if (log_alerts) {
std::shared_ptr<KisDatabaseLogfile> dbf =
Globalreg::FetchGlobalAs<KisDatabaseLogfile>(globalreg, "DATABASELOG");
if (dbf != NULL) {
auto ta = std::make_shared<tracked_alert>(alert_entry_id);
ta->from_alert_info(info);
dbf->log_alert(ta);
}
}
return 1;
}
int Alertracker::RaisePreludeAlert(int in_ref, kis_packet *in_pack,
mac_addr bssid, mac_addr source, mac_addr dest,
mac_addr other, std::string in_channel, std::string in_text) {
#ifdef PRELUDE
mac_addr emptymac = mac_addr(0);
Prelude::IDMEF idmef;
// Classification
idmef.set("alert.classification.text", "Suspicious network detected");
// Source
if (source != emptymac) {
idmef.set("alert.source(0).node.address(0).category", "mac");
idmef.set("alert.source(0).node.address(0).address", source.Mac2String().c_str());
}
// Target
if (dest != emptymac) {
idmef.set("alert.target(0).node.address(0).category", "mac");
idmef.set("alert.target(0).node.address(0).address", dest.Mac2String().c_str());
}
// Assessment
idmef.set("alert.assessment.impact.severity", "high");
idmef.set("alert.assessment.impact.completion", "succeeded");
idmef.set("alert.assessment.impact.description", in_text);
// Additional Data
if (bssid != emptymac) {
idmef.set("alert.additional_data(>>).meaning", "BSSID");
idmef.set("alert.additional_data(-1).data", bssid.Mac2String().c_str());
}
if (other != emptymac) {
idmef.set("alert.additional_data(>>).meaning", "Other");
idmef.set("alert.additional_data(-1).data", other.Mac2String().c_str());
}
idmef.set("alert.additional_data(>>).meaning", "Channel");
idmef.set("alert.additional_data(-1).data", in_channel);
idmef.set("alert.additional_data(>>).meaning", "in_ref");
idmef.set("alert.additional_data(-1).data", in_ref);
prelude_client->sendIDMEF(idmef);
#endif
return 0;
}
int Alertracker::RaisePreludeOneShot(std::string in_header, std::string in_text) {
#ifdef PRELUDE
mac_addr emptymac = mac_addr(0);
Prelude::IDMEF idmef;
// Classification
idmef.set("alert.classification.text", "Suspicious network detected");
// Assessment
idmef.set("alert.assessment.impact.severity", "high");
idmef.set("alert.assessment.impact.completion", "succeeded");
idmef.set("alert.assessment.impact.description", in_text);
idmef.set("alert.additional_data(>>).alert_type", "in_ref");
idmef.set("alert.additional_data(-1).data", in_header);
prelude_client->sendIDMEF(idmef);
#endif
return 0;
}
int Alertracker::ParseAlertStr(std::string alert_str, std::string *ret_name,
alert_time_unit *ret_limit_unit, int *ret_limit_rate,
alert_time_unit *ret_limit_burst,
int *ret_burst_rate) {
char err[1024];
std::vector<std::string> tokens = StrTokenize(alert_str, ",");
if (tokens.size() != 3) {
snprintf(err, 1024, "Malformed limits for alert '%s'", alert_str.c_str());
globalreg->messagebus->InjectMessage(err, MSGFLAG_ERROR);
return -1;
}
(*ret_name) = StrLower(tokens[0]);
if (ParseRateUnit(StrLower(tokens[1]), ret_limit_unit, ret_limit_rate) != 1 ||
ParseRateUnit(StrLower(tokens[2]), ret_limit_burst, ret_burst_rate) != 1) {
snprintf(err, 1024, "Malformed limits for alert '%s'", alert_str.c_str());
globalreg->messagebus->InjectMessage(err, MSGFLAG_ERROR);
return -1;
}
return 1;
}
// Split up a rate/unit string into real values
int Alertracker::ParseRateUnit(std::string in_ru, alert_time_unit *ret_unit,
int *ret_rate) {
std::vector<std::string> units = StrTokenize(in_ru, "/");
if (units.size() == 1) {
// Unit is per minute if not specified
(*ret_unit) = sat_minute;
} else {
// Parse the string unit
if (units[1] == "sec" || units[1] == "second") {
(*ret_unit) = sat_second;
} else if (units[1] == "min" || units[1] == "minute") {
(*ret_unit) = sat_minute;
} else if (units[1] == "hr" || units[1] == "hour") {
(*ret_unit) = sat_hour;
} else if (units[1] == "day") {
(*ret_unit) = sat_day;
} else {
_MSG("Invalid time unit for alert rate '" + units[1] + "'",
MSGFLAG_ERROR);
return -1;
}
}
// Get the number
if (sscanf(units[0].c_str(), "%d", ret_rate) != 1) {
_MSG("Invalid rate '" + units[0] + "' for alert", MSGFLAG_ERROR);
return -1;
}
return 1;
}
int Alertracker::ParseAlertConfig(ConfigFile *in_conf) {
std::vector<std::string> clines = in_conf->FetchOptVec("alert");
for (unsigned int x = 0; x < clines.size(); x++) {
alert_conf_rec *rec = new alert_conf_rec;
if (ParseAlertStr(clines[x], &(rec->header), &(rec->limit_unit),
&(rec->limit_rate), &(rec->burst_unit),
&(rec->limit_burst)) < 0) {
_MSG("Invalid alert line in config file: " + clines[x], MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
delete rec;
return -1;
}
alert_conf_map[StrLower(rec->header)] = rec;
}
return 1;
}
int Alertracker::DefineAlert(std::string name, alert_time_unit limit_unit, int limit_rate,
alert_time_unit burst_unit, int burst_rate) {
local_locker lock(&alert_mutex);
for (auto i = alert_conf_map.begin(); i != alert_conf_map.end(); ++i) {
if (StrLower(name) == i->first) {
_MSG("Tried to define alert '" + name + "' twice.", MSGFLAG_ERROR);
return -1;
}
}
alert_conf_rec *rec = new alert_conf_rec;
rec->header = name;
rec->limit_unit = limit_unit;
rec->limit_rate = limit_rate;
rec->burst_unit = burst_unit;
rec->limit_burst = burst_rate;
alert_conf_map[StrLower(rec->header)] = rec;
return 1;
}
int Alertracker::ActivateConfiguredAlert(std::string in_header, std::string in_desc) {
return ActivateConfiguredAlert(in_header, in_desc, KIS_PHY_UNKNOWN);
}
int Alertracker::ActivateConfiguredAlert(std::string in_header, std::string in_desc, int in_phy) {
alert_conf_rec *rec;
{
local_locker lock(&alert_mutex);
std::string hdr = StrLower(in_header);
if (alert_conf_map.find(hdr) == alert_conf_map.end()) {
_MSG("Using default rates (10/min,1/sec) for alert '" + in_header + "'",
MSGFLAG_INFO);
DefineAlert(in_header, sat_minute, 10, sat_second, 1);
}
rec = alert_conf_map[hdr];
}
return RegisterAlert(rec->header, in_desc, rec->limit_unit, rec->limit_rate,
rec->burst_unit, rec->limit_burst, in_phy);
}
int Alertracker::FindActivatedAlert(std::string in_header) {
local_locker lock(&alert_mutex);
for (auto x : alert_ref_map) {
if (x.second->get_header() == in_header)
return x.first;
}
return -1;
}
bool Alertracker::Httpd_VerifyPath(const char *path, const char *method) {
if (!Httpd_CanSerialize(path))
return false;
if (strcmp(method, "GET") == 0) {
// Split URL and process
std::vector<std::string> tokenurl = StrTokenize(path, "/");
if (tokenurl.size() < 3)
return false;
if (tokenurl[1] == "alerts") {
if (Httpd_StripSuffix(tokenurl[2]) == "definitions") {
return true;
} else if (Httpd_StripSuffix(tokenurl[2]) == "all_alerts") {
return true;
} else if (tokenurl[2] == "last-time") {
if (tokenurl.size() < 5)
return false;
if (Httpd_CanSerialize(tokenurl[4]))
return true;
return false;
}
}
return false;
}
if (strcmp(method, "POST") == 0) {
std::string stripped = httpd->StripSuffix(path);
if (stripped == "/alerts/definitions/define_alert")
return true;
if (stripped == "/alerts/raise_alert")
return true;
return false;
}
return false;
}
void Alertracker::Httpd_CreateStreamResponse(
Kis_Net_Httpd *httpd __attribute__((unused)),
Kis_Net_Httpd_Connection *connection,
const char *path, const char *method, const char *upload_data,
size_t *upload_data_size, std::stringstream &stream) {
double since_time = 0;
bool wrap = false;
if (strcmp(method, "GET") != 0) {
return;
}
if (!Httpd_CanSerialize(path))
return;
// Split URL and process
std::vector<std::string> tokenurl = StrTokenize(path, "/");
if (tokenurl.size() < 3)
return;
if (tokenurl[1] == "alerts") {
if (Httpd_StripSuffix(tokenurl[2]) == "definitions") {
Httpd_Serialize(path, stream, alert_defs_vec);
return;
} else if (tokenurl[2] == "last-time") {
if (tokenurl.size() < 5)
return;
std::stringstream ss(tokenurl[3]);
ss >> since_time;
wrap = true;
}
}
std::shared_ptr<TrackerElement> transmit;
std::shared_ptr<TrackerElementMap> wrapper;
std::shared_ptr<TrackerElementVector> msgvec = std::make_shared<TrackerElementVector>(alert_vec_id);
// If we're doing a time-since, wrap the vector
if (wrap) {
wrapper = std::make_shared<TrackerElementMap>();
wrapper->insert(msgvec);
auto ts = std::make_shared<TrackerElementDouble>(alert_timestamp_id, ts_now_to_double());
wrapper->insert(ts);
transmit = wrapper;
} else {
transmit = msgvec;
}
{
local_locker lock(&alert_mutex);
for (auto i : alert_backlog) {
if (since_time < ts_to_double((i)->tm)) {
auto ta = std::make_shared<tracked_alert>(alert_entry_id);
ta->from_alert_info(i);
msgvec->push_back(ta);
}
}
}
Httpd_Serialize(path, stream, transmit);
}
int Alertracker::Httpd_PostComplete(Kis_Net_Httpd_Connection *concls) {
std::string stripped = Httpd_StripSuffix(concls->url);
if (!Httpd_CanSerialize(concls->url) ||
(stripped != "/alerts/definitions/define_alert" &&
stripped != "/alerts/raise_alert")) {
concls->response_stream << "Invalid request";
concls->httpcode = 400;
return 1;
}
if (!httpd->HasValidSession(concls, true)) {
concls->httpcode = 503;
return MHD_NO;
}
SharedStructured structdata;
try {
if (concls->variable_cache.find("json") != concls->variable_cache.end()) {
structdata.reset(new StructuredJson(concls->variable_cache["json"]->str()));
} else {
throw std::runtime_error("could not find data");
}
if (stripped == "/alerts/definitions/define_alert") {
std::string name = structdata->getKeyAsString("name");
std::string desc = structdata->getKeyAsString("description");
alert_time_unit limit_unit;
int limit_rate;
alert_time_unit burst_unit;
int burst_rate;
if (ParseRateUnit(StrLower(structdata->getKeyAsString("throttle", "")),
&limit_unit, &limit_rate) < 0) {
throw std::runtime_error("could not parse throttle limits");
}
if (ParseRateUnit(StrLower(structdata->getKeyAsString("burst", "")),
&burst_unit, &burst_rate) < 0) {
throw std::runtime_error("could not parse burst limits");
}
int phyid = KIS_PHY_ANY;
std::string phyname = structdata->getKeyAsString("phyname", "");
if (phyname != "any" && phyname != "") {
std::shared_ptr<Devicetracker> devicetracker =
Globalreg::FetchMandatoryGlobalAs<Devicetracker>(globalreg, "DEVICETRACKER");
Kis_Phy_Handler *phyh = devicetracker->FetchPhyHandlerByName(phyname);
if (phyh == NULL)
throw std::runtime_error("could not find phy");
phyid = phyh->FetchPhyId();
}
if (DefineAlert(name, limit_unit, limit_rate, burst_unit, burst_rate) < 0) {
concls->httpcode = 503;
throw std::runtime_error("could not add alert");
}
if (ActivateConfiguredAlert(name, desc, phyid) < 0) {
concls->httpcode = 504;
throw std::runtime_error("could not activate alert");
}
concls->response_stream << "Added alert";
return 1;
} else if (stripped == "/alerts/raise_alert") {
std::string name = structdata->getKeyAsString("name");
int aref = FetchAlertRef(name);
if (aref < 0)
throw std::runtime_error("unknown alert type");
std::string text = structdata->getKeyAsString("text");
std::string bssid = structdata->getKeyAsString("bssid", "");
std::string source = structdata->getKeyAsString("source", "");
std::string dest = structdata->getKeyAsString("dest", "");
std::string other = structdata->getKeyAsString("other", "");
std::string channel = structdata->getKeyAsString("channel", "");
mac_addr bssid_mac, source_mac, dest_mac, other_mac;
if (bssid.length() != 0) {
bssid_mac = mac_addr(bssid);
}
if (source.length() != 0) {
source_mac = mac_addr(source);
}
if (dest.length() != 0) {
dest_mac = mac_addr(dest);
}
if (other.length() != 0) {
other_mac = mac_addr(other);
}
if (bssid_mac.error || source_mac.error ||
dest_mac.error || other_mac.error) {
throw std::runtime_error("invalid mac");
}
if (!PotentialAlert(aref))
throw std::runtime_error("alert limit reached");
RaiseAlert(aref, NULL, bssid_mac, source_mac, dest_mac, other_mac,
channel, text);
concls->response_stream << "alert raised";
return 1;
}
} catch (const std::exception& e) {
concls->response_stream << "Invalid request " << e.what();
if (concls->httpcode != 200)
concls->httpcode = 400;
return 1;
}
return MHD_NO;
}