forked from kismetwireless/kismet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
devicetracker.cc
1836 lines (1383 loc) · 57.7 KB
/
devicetracker.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
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
/*
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 <memory>
#include <stdio.h>
#include <time.h>
#include <list>
#include <map>
#include <vector>
#include "kismet_algorithm.h"
#include <string>
#include <sstream>
#include "globalregistry.h"
#include "util.h"
#include "configfile.h"
#include "messagebus.h"
#include "packetchain.h"
#include "devicetracker.h"
#include "packet.h"
#include "gpstracker.h"
#include "alertracker.h"
#include "manuf.h"
#include "entrytracker.h"
#include "devicetracker_component.h"
#include "json_adapter.h"
#include "structured.h"
#include "kismet_json.h"
#include "storageloader.h"
#include "base64.h"
#include "kis_datasource.h"
#include "kis_databaselogfile.h"
#include "zstr.hpp"
int Devicetracker_packethook_commontracker(CHAINCALL_PARMS) {
return ((Devicetracker *) auxdata)->CommonTracker(in_pack);
}
Devicetracker::Devicetracker(GlobalRegistry *in_globalreg) :
Kis_Net_Httpd_Chain_Stream_Handler(),
KisDatabase(in_globalreg, "devicetracker") {
globalreg = in_globalreg;
// create a vector
immutable_tracked_vec = std::make_shared<TrackerElementVector>();
// Create the pcap httpd
httpd_pcap = std::make_shared<Devicetracker_Httpd_Pcap>();
entrytracker =
Globalreg::FetchMandatoryGlobalAs<EntryTracker>("ENTRYTRACKER");
device_base_id =
entrytracker->RegisterField("kismet.device.base",
TrackerElementFactory<kis_tracked_device_base>(),
"core device record");
device_list_base_id =
entrytracker->RegisterField("kismet.device.list",
TrackerElementFactory<TrackerElementVector>(),
"list of devices");
phy_base_id =
entrytracker->RegisterField("kismet.phy.list",
TrackerElementFactory<TrackerElementVector>(),
"list of phys");
phy_entry_id =
entrytracker->RegisterField("kismet.phy.entry",
TrackerElementFactory<TrackerElementMap>(),
"phy entry");
device_summary_base_id =
entrytracker->RegisterField("kismet.device.summary_list",
TrackerElementFactory<TrackerElementVector>(),
"summary list of devices");
device_update_required_id =
entrytracker->RegisterField("kismet.devicelist.refresh",
TrackerElementFactory<TrackerElementUInt8>(),
"device list refresh recommended");
device_update_timestamp_id =
entrytracker->RegisterField("kismet.devicelist.timestamp",
TrackerElementFactory<TrackerElementUInt64>(),
"device list timestamp");
// These need unique IDs to be put in the map for serialization.
// They also need unique field names, we can rename them with setlocalname
dt_length_id =
entrytracker->RegisterField("kismet.datatables.recordsTotal",
TrackerElementFactory<TrackerElementUInt64>(),
"datatable records total");
dt_filter_id =
entrytracker->RegisterField("kismet.datatables.recordsFiltered",
TrackerElementFactory<TrackerElementUInt64>(),
"datatable records filtered");
dt_draw_id =
entrytracker->RegisterField("kismet.datatables.draw",
TrackerElementFactory<TrackerElementUInt64>(),
"Datatable records draw ID");
// Generate the system-wide packet RRD
packets_rrd =
entrytracker->RegisterAndGetFieldAs<kis_tracked_rrd<>>("kismet.device.packets_rrd",
TrackerElementFactory<kis_tracked_rrd<>>(), "Packets seen RRD");
num_packets = num_datapackets = num_errorpackets =
num_filterpackets = 0;
next_phy_id = 0;
std::shared_ptr<Packetchain> packetchain =
Globalreg::FetchMandatoryGlobalAs<Packetchain>(globalreg, "PACKETCHAIN");
// Register global packet components used by the device tracker and
// subsequent parts
pack_comp_device = _PCM(PACK_COMP_DEVICE) =
packetchain->RegisterPacketComponent("DEVICE");
pack_comp_common = _PCM(PACK_COMP_COMMON) =
packetchain->RegisterPacketComponent("COMMON");
pack_comp_basicdata = _PCM(PACK_COMP_BASICDATA) =
packetchain->RegisterPacketComponent("BASICDATA");
_PCM(PACK_COMP_MANGLEFRAME) =
packetchain->RegisterPacketComponent("MANGLEDATA");
pack_comp_radiodata =
packetchain->RegisterPacketComponent("RADIODATA");
pack_comp_gps =
packetchain->RegisterPacketComponent("GPS");
pack_comp_datasrc =
packetchain->RegisterPacketComponent("KISDATASRC");
// Common tracker, very early in the tracker chain
packetchain->RegisterHandler(&Devicetracker_packethook_commontracker,
this, CHAINPOS_TRACKER, -100);
std::shared_ptr<Timetracker> timetracker =
Globalreg::FetchMandatoryGlobalAs<Timetracker>(globalreg, "TIMETRACKER");
// Always disable persistent storage for now
persistent_storage = false;
persistent_mode = MODE_ONSTART;
persistent_compression = false;
statestore = NULL;
persistent_storage_timeout = 0;
#if 0
if (!globalreg->kismet_config->FetchOptBoolean("persistent_config_present", false)) {
_MSG("Kismet has recently added persistent device storage; it looks like you "
"need to update your Kismet configs; install the latest configs with "
"'make forceconfigs' from the Kismet source directory.",
MSGFLAG_ERROR);
std::shared_ptr<Alertracker> alertracker =
Globalreg::FetchMandatoryGlobalAs<Alertracker>(globalreg, "ALERTTRACKER");
alertracker->RaiseOneShot("CONFIGERROR",
"Kismet has recently added persistent device storage; it looks like "
"kismet_storage.conf is missing; You should install the latest Kismet "
"configs with 'make forceconfigs' from the Kismet source directory, or "
"manually reconcile the new configs.", -1);
persistent_storage = false;
persistent_mode = MODE_ONSTART;
persistent_compression = false;
statestore = NULL;
persistent_storage_timeout = 0;
} else {
persistent_storage =
globalreg->kismet_config->FetchOptBoolean("persistent_state", false);
if (!persistent_storage) {
_MSG("Persistent storage has been disabled. Kismet will not remember devices "
"between launches.", MSGFLAG_INFO);
statestore = NULL;
} else {
statestore = new DevicetrackerStateStore(globalreg, this);
unsigned int storerate =
globalreg->kismet_config->FetchOptUInt("persistent_storage_rate", 60);
_MSG("Persistent device storage enabled. Kismet will remember devices and "
"other information between launches. Kismet will store devices "
"every " + UIntToString(storerate) + " seconds and on exit.",
MSGFLAG_INFO);
devices_storing = false;
device_storage_timer =
timetracker->RegisterTimer(SERVER_TIMESLICES_SEC * storerate, NULL, 1,
[this](int) -> int {
local_locker l(&storing_mutex);
if (devices_storing) {
_MSG("Attempting to save persistent devices, but devices "
"are still being saved from a previous storage "
"attempt. It's possible your system is slow, or you "
"have a very large log of devices. Try increasing "
"the delay in 'persistent_storage_rate' in your "
"kismet_storage.conf file.", MSGFLAG_ERROR);
return 1;
}
devices_storing = true;
// Run the device storage in its own thread
std::thread t([this] {
store_devices(immutable_tracked_vec);
{
local_locker l(&storing_mutex);
devices_storing = false;
}
});
// Detatch the thread, we don't care about it
t.detach();
return 1;
});
std::string pertype =
StrLower(globalreg->kismet_config->FetchOpt("persistent_load"));
if (pertype == "onstart") {
persistent_mode = MODE_ONSTART;
} else if (pertype == "ondemand") {
persistent_mode = MODE_ONDEMAND;
} else {
_MSG("Persistent load mode missing from config, assuming 'onstart'",
MSGFLAG_ERROR);
persistent_mode = MODE_ONSTART;
}
persistent_compression =
globalreg->kismet_config->FetchOptBoolean("persistent_compression", true);
persistent_storage_timeout =
globalreg->kismet_config->FetchOptULong("persistent_timeout", 86400);
}
}
#endif
if (!globalreg->kismet_config->FetchOptBoolean("track_device_rrds", true)) {
_MSG("Not tracking historical packet data to save RAM", MSGFLAG_INFO);
ram_no_rrd = true;
} else {
ram_no_rrd = false;
}
if (globalreg->kismet_config->FetchOptBoolean("kis_log_devices", true)) {
unsigned int lograte =
globalreg->kismet_config->FetchOptUInt("kis_log_device_rate", 30);
_MSG("Saving devices to the Kismet database log every " + UIntToString(lograte) +
" seconds.", MSGFLAG_INFO);
databaselog_logging = false;
databaselog_timer =
timetracker->RegisterTimer(SERVER_TIMESLICES_SEC * lograte, NULL, 1,
[this](int) -> int {
local_locker l(&databaselog_mutex);
if (databaselog_logging) {
_MSG("Attempting to log devices, but devices are still being "
"saved from the last logging attempt. It's possible your "
"system is slow or you have a very large number of devices "
"to log. Try increasing the delay in 'kis_log_storage_rate' "
"in kismet_logging.conf", MSGFLAG_ERROR);
return 1;
}
databaselog_logging = true;
// Run the device storage in its own thread
std::thread t([this] {
databaselog_write_devices();
{
local_locker l(&databaselog_mutex);
databaselog_logging = false;
}
});
// Detatch the thread, we don't care about it
t.detach();
return 1;
});
} else {
databaselog_timer = -1;
}
last_devicelist_saved = 0;
last_database_logged = 0;
// Preload the vector for speed
unsigned int preload_sz =
globalreg->kismet_config->FetchOptUInt("tracker_device_presize", 1000);
tracked_vec.reserve(preload_sz);
immutable_tracked_vec->reserve(preload_sz);
// Set up the device timeout
device_idle_expiration =
globalreg->kismet_config->FetchOptInt("tracker_device_timeout", 0);
if (device_idle_expiration != 0) {
device_idle_min_packets =
globalreg->kismet_config->FetchOptUInt("tracker_device_packets", 0);
std::stringstream ss;
ss << "Removing tracked devices which have been inactive for more than " <<
device_idle_expiration << " seconds";
if (device_idle_min_packets > 2)
ss << " and fewer than " << device_idle_min_packets << " packets";
_MSG(ss.str(), MSGFLAG_INFO);
// Schedule device idle reaping every minute
device_idle_timer =
timetracker->RegisterTimer(SERVER_TIMESLICES_SEC * 60, NULL, 1, this);
} else {
device_idle_timer = -1;
}
max_num_devices =
globalreg->kismet_config->FetchOptUInt("tracker_max_devices", 0);
if (max_num_devices > 0) {
_MSG_INFO("Limiting maximum number of devices to {}, older devices will be "
"removed from tracking when this limit is reached.", max_num_devices);
// Schedule max device reaping every 5 seconds
max_devices_timer =
timetracker->RegisterTimer(SERVER_TIMESLICES_SEC * 5, NULL, 1, this);
} else {
max_devices_timer = -1;
}
full_refresh_time = globalreg->timestamp.tv_sec;
track_history_cloud =
globalreg->kismet_config->FetchOptBoolean("keep_location_cloud_history", true);
if (!track_history_cloud) {
_MSG("Location history cloud tracking disabled. This may prevent some plugins "
"from working. This can be re-enabled by setting "
"keep_datasource_signal_history=true", MSGFLAG_INFO);
}
track_persource_history =
globalreg->kismet_config->FetchOptBoolean("keep_datasource_signal_history", true);
if (!track_persource_history) {
_MSG("Per-source signal history tracking disabled. This may prevent some plugins "
"from working. This can be re-enabled by setting "
"keep_datasource_signal_history=true", MSGFLAG_INFO);
}
// Open and upgrade the DB, default path
Database_Open("");
Database_UpgradeDB();
}
Devicetracker::~Devicetracker() {
local_locker lock(&devicelist_mutex);
if (statestore != NULL) {
delete(statestore);
statestore = NULL;
}
globalreg->devicetracker = NULL;
globalreg->RemoveGlobal("DEVICETRACKER");
std::shared_ptr<Packetchain> packetchain =
Globalreg::FetchMandatoryGlobalAs<Packetchain>(globalreg, "PACKETCHAIN");
if (packetchain != NULL) {
packetchain->RemoveHandler(&Devicetracker_packethook_commontracker,
CHAINPOS_TRACKER);
}
std::shared_ptr<Timetracker> timetracker =
Globalreg::FetchGlobalAs<Timetracker>(globalreg, "TIMETRACKER");
if (timetracker != NULL) {
timetracker->RemoveTimer(device_idle_timer);
timetracker->RemoveTimer(max_devices_timer);
timetracker->RemoveTimer(device_storage_timer);
}
// TODO broken for now
/*
if (track_filter != NULL)
delete track_filter;
*/
for (auto p = phy_handler_map.begin(); p != phy_handler_map.end(); ++p) {
delete p->second;
}
tracked_vec.clear();
immutable_tracked_vec->clear();
tracked_mac_multimap.clear();
}
Kis_Phy_Handler *Devicetracker::FetchPhyHandler(int in_phy) {
std::map<int, Kis_Phy_Handler *>::iterator i = phy_handler_map.find(in_phy);
if (i == phy_handler_map.end())
return NULL;
return i->second;
}
Kis_Phy_Handler *Devicetracker::FetchPhyHandlerByName(std::string in_name) {
for (auto i = phy_handler_map.begin(); i != phy_handler_map.end(); ++i) {
if (i->second->FetchPhyName() == in_name) {
return i->second;
}
}
return NULL;
}
std::string Devicetracker::FetchPhyName(int in_phy) {
if (in_phy == KIS_PHY_ANY) {
return "ANY";
}
Kis_Phy_Handler *phyh = FetchPhyHandler(in_phy);
if (phyh == NULL) {
return "UNKNOWN";
}
return phyh->FetchPhyName();
}
int Devicetracker::FetchNumDevices() {
local_locker lock(&devicelist_mutex);
return tracked_map.size();
}
int Devicetracker::FetchNumPackets() {
return num_packets;
}
int Devicetracker::RegisterPhyHandler(Kis_Phy_Handler *in_weak_handler) {
int num = next_phy_id++;
Kis_Phy_Handler *strongphy =
in_weak_handler->CreatePhyHandler(globalreg, this, num);
phy_handler_map[num] = strongphy;
phy_packets[num] = 0;
phy_datapackets[num] = 0;
phy_errorpackets[num] = 0;
phy_filterpackets[num] = 0;
_MSG("Registered PHY handler '" + strongphy->FetchPhyName() + "' as ID " +
IntToString(num), MSGFLAG_INFO);
return num;
}
void Devicetracker::UpdateFullRefresh() {
full_refresh_time = globalreg->timestamp.tv_sec;
}
std::shared_ptr<kis_tracked_device_base> Devicetracker::FetchDevice(device_key in_key) {
local_locker lock(&devicelist_mutex);
device_itr i = tracked_map.find(in_key);
if (i != tracked_map.end())
return i->second;
return NULL;
}
int Devicetracker::CommonTracker(kis_packet *in_pack) {
local_locker lock(&devicelist_mutex);
if (in_pack->error) {
// and bail
num_errorpackets++;
return 0;
}
kis_common_info *pack_common =
(kis_common_info *) in_pack->fetch(pack_comp_common);
if (!ram_no_rrd)
packets_rrd->add_sample(1, globalreg->timestamp.tv_sec);
num_packets++;
// If we can't figure it out at all (no common layer) just bail
if (pack_common == NULL)
return 0;
if (pack_common->error) {
// If we couldn't get any common data consider it an error
// and bail
num_errorpackets++;
if (phy_handler_map.find(pack_common->phyid) != phy_handler_map.end()) {
phy_errorpackets[pack_common->phyid]++;
}
return 0;
}
if (in_pack->filtered) {
num_filterpackets++;
}
// Make sure our PHY is sane
if (phy_handler_map.find(pack_common->phyid) == phy_handler_map.end()) {
_MSG("Invalid phy id " + IntToString(pack_common->phyid) + " in packet "
"something is wrong.", MSGFLAG_ERROR);
return 0;
}
phy_packets[pack_common->phyid]++;
if (in_pack->error || pack_common->error) {
phy_errorpackets[pack_common->phyid]++;
}
if (in_pack->filtered) {
phy_filterpackets[pack_common->phyid]++;
num_filterpackets++;
} else {
if (pack_common->type == packet_basic_data) {
num_datapackets++;
phy_datapackets[pack_common->phyid]++;
}
}
return 1;
}
// This function handles populating the base common info about a device, transforming a
// kis_common_info record into a full kis_tracked_device_base (or updating an existing
// kis_tracked_device_base record);
//
// Because a phy can create multiple devices from a single packet (such as WiFi creating
// the access point, source, and destination devices), only the specific common device
// being passed will be updated.
std::shared_ptr<kis_tracked_device_base>
Devicetracker::UpdateCommonDevice(kis_common_info *pack_common,
mac_addr in_mac, Kis_Phy_Handler *in_phy, kis_packet *in_pack,
unsigned int in_flags, std::string in_basic_type) {
// We must protect the device list to determine if the device is 'new'
local_locker list_locker(&devicelist_mutex);
std::stringstream sstr;
bool new_device = false;
kis_layer1_packinfo *pack_l1info =
(kis_layer1_packinfo *) in_pack->fetch(pack_comp_radiodata);
kis_gps_packinfo *pack_gpsinfo =
(kis_gps_packinfo *) in_pack->fetch(pack_comp_gps);
packetchain_comp_datasource *pack_datasrc =
(packetchain_comp_datasource *) in_pack->fetch(pack_comp_datasrc);
std::shared_ptr<kis_tracked_device_base> device = NULL;
device_key key;
key = device_key(globalreg->server_uuid_hash, in_phy->FetchPhynameHash(), in_mac);
if ((device = FetchDevice(key)) == NULL) {
if (in_flags & UCD_UPDATE_EXISTING_ONLY)
return NULL;
device =
std::make_shared<kis_tracked_device_base>(device_base_id);
// Device ID is the size of the vector so a new device always gets put
// in it's numbered slot
device->set_kis_internal_id(immutable_tracked_vec->size());
device->set_key(key);
device->set_macaddr(in_mac);
device->set_phyname(in_phy->FetchPhyName());
device->set_server_uuid(globalreg->server_uuid);
device->set_first_time(in_pack->ts.tv_sec);
device->set_type_string(in_basic_type);
if (globalreg->manufdb != NULL)
device->set_manuf(globalreg->manufdb->LookupOUI(in_mac));
load_stored_username(device);
load_stored_tags(device);
new_device = true;
}
// Lock the device itself for updating, now that it's part of the list
local_locker devlocker(&(device->device_mutex));
// Tag the packet with the base device
kis_tracked_device_info *devinfo =
(kis_tracked_device_info *) in_pack->fetch(pack_comp_device);
if (devinfo == NULL) {
devinfo = new kis_tracked_device_info;
in_pack->insert(pack_comp_device, devinfo);
}
devinfo->devrefs[in_mac] = device;
// Update the mod data
device->update_modtime();
if (device->get_last_time() < in_pack->ts.tv_sec)
device->set_last_time(in_pack->ts.tv_sec);
if (in_flags & UCD_UPDATE_PACKETS) {
device->inc_packets();
if (!ram_no_rrd)
device->get_packets_rrd()->add_sample(1, globalreg->timestamp.tv_sec);
if (pack_common != NULL) {
if (pack_common->error)
device->inc_error_packets();
if (pack_common->type == packet_basic_data) {
// TODO fix directional data
device->inc_data_packets();
device->inc_datasize(pack_common->datasize);
if (!ram_no_rrd) {
device->get_data_rrd()->add_sample(pack_common->datasize,
globalreg->timestamp.tv_sec);
if (pack_common->datasize <= 250)
device->get_packet_rrd_bin_250()->add_sample(1,
globalreg->timestamp.tv_sec);
else if (pack_common->datasize <= 500)
device->get_packet_rrd_bin_500()->add_sample(1,
globalreg->timestamp.tv_sec);
else if (pack_common->datasize <= 1000)
device->get_packet_rrd_bin_1000()->add_sample(1,
globalreg->timestamp.tv_sec);
else if (pack_common->datasize <= 1500)
device->get_packet_rrd_bin_1500()->add_sample(1,
globalreg->timestamp.tv_sec);
else
device->get_packet_rrd_bin_jumbo()->add_sample(1,
globalreg->timestamp.tv_sec);
}
} else if (pack_common->type == packet_basic_mgmt ||
pack_common->type == packet_basic_phy) {
device->inc_llc_packets();
}
}
}
if ((in_flags & UCD_UPDATE_FREQUENCIES)) {
if (pack_l1info != NULL) {
if (pack_l1info->channel != "0" && pack_l1info->channel != "") {
device->set_channel(pack_l1info->channel);
}
if (pack_l1info->freq_khz != 0)
device->set_frequency(pack_l1info->freq_khz);
Packinfo_Sig_Combo *sc = new Packinfo_Sig_Combo(pack_l1info, pack_gpsinfo);
device->get_signal_data()->append_signal(*sc, !ram_no_rrd);
delete(sc);
device->inc_frequency_count((int) pack_l1info->freq_khz);
} else if (pack_common != NULL) {
if (pack_common->channel != "0" && pack_common->channel != "") {
device->set_channel(pack_common->channel);
}
if (pack_common->freq_khz != 0)
device->set_frequency(pack_common->freq_khz);
device->inc_frequency_count((int) pack_common->freq_khz);
}
}
if (((in_flags & UCD_UPDATE_LOCATION) ||
((in_flags & UCD_UPDATE_EMPTY_LOCATION) && !device->has_location_cloud())) &&
pack_gpsinfo != NULL) {
device->get_location()->add_loc(pack_gpsinfo->lat, pack_gpsinfo->lon,
pack_gpsinfo->alt, pack_gpsinfo->fix);
// Throttle history cloud to one update per second to prevent floods of
// data from swamping the cloud
if (track_history_cloud && pack_gpsinfo->fix >= 2 &&
in_pack->ts.tv_sec - device->get_location_cloud()->get_last_sample_ts() >= 1) {
auto histloc = std::make_shared<kis_historic_location>();
histloc->set_lat(pack_gpsinfo->lat);
histloc->set_lon(pack_gpsinfo->lon);
histloc->set_alt(pack_gpsinfo->alt);
histloc->set_speed(pack_gpsinfo->speed);
histloc->set_heading(pack_gpsinfo->heading);
histloc->set_time_sec(in_pack->ts.tv_sec);
if (pack_l1info != NULL) {
histloc->set_frequency(pack_l1info->freq_khz);
if (pack_l1info->signal_dbm != 0)
histloc->set_signal(pack_l1info->signal_dbm);
else
histloc->set_signal(pack_l1info->signal_rssi);
}
device->get_location_cloud()->add_sample(histloc);
}
}
// Update seenby records for time, frequency, packets
if ((in_flags & UCD_UPDATE_SEENBY) && pack_datasrc != NULL) {
double f = -1;
Packinfo_Sig_Combo *sc = NULL;
if (pack_l1info != NULL)
f = pack_l1info->freq_khz;
// Generate a signal record if we're following per-source signal
if (track_persource_history) {
sc = new Packinfo_Sig_Combo(pack_l1info, pack_gpsinfo);
}
device->inc_seenby_count(pack_datasrc->ref_source, in_pack->ts.tv_sec, f, sc, !ram_no_rrd);
if (sc != NULL)
delete(sc);
}
if (pack_common != NULL)
device->add_basic_crypt(pack_common->basic_crypt_set);
// Add the new device at the end once we've populated it
if (new_device) {
tracked_map[key] = device;
tracked_vec.push_back(device);
immutable_tracked_vec->push_back(device);
auto mm_pair = std::make_pair(in_mac, device);
tracked_mac_multimap.insert(mm_pair);
}
return device;
}
// Sort based on internal kismet ID
bool devicetracker_sort_internal_id(std::shared_ptr<kis_tracked_device_base> a,
std::shared_ptr<kis_tracked_device_base> b) {
return a->get_kis_internal_id() < b->get_kis_internal_id();
}
void Devicetracker::MatchOnDevices(std::shared_ptr<DevicetrackerFilterWorker> worker,
std::shared_ptr<TrackerElementVector> vec, bool batch) {
kismet__for_each(vec->begin(), vec->end(), [&](SharedTrackerElement val) {
if (val == nullptr)
return;
std::shared_ptr<kis_tracked_device_base> v =
std::static_pointer_cast<kis_tracked_device_base>(val);
bool m;
// Lock the device itself inside the worker op
{
local_locker devlocker(&(v->device_mutex));
m = worker->MatchDevice(this, v);
}
if (m)
worker->MatchedDevice(v);
});
worker->Finalize(this);
}
void Devicetracker::MatchOnDevices(std::shared_ptr<DevicetrackerFilterWorker> worker, bool batch) {
auto immutable_copy = std::make_shared<TrackerElementVector>(immutable_tracked_vec);
MatchOnDevices(worker, immutable_copy, batch);
}
// Simple std::sort comparison function to order by the least frequently
// seen devices
bool devicetracker_sort_lastseen(std::shared_ptr<kis_tracked_device_base> a,
std::shared_ptr<kis_tracked_device_base> b) {
return a->get_last_time() < b->get_last_time();
}
int Devicetracker::timetracker_event(int eventid) {
if (eventid == device_idle_timer) {
local_locker lock(&devicelist_mutex);
time_t ts_now = globalreg->timestamp.tv_sec;
bool purged = false;
// Find all eligible devices, remove them from the tracked vec
tracked_vec.erase(std::remove_if(tracked_vec.begin(), tracked_vec.end(),
[&](std::shared_ptr<kis_tracked_device_base> d) {
// Lock the device itself
local_locker devlocker(&(d->device_mutex));
if (ts_now - d->get_last_time() > device_idle_expiration &&
(d->get_packets() < device_idle_min_packets ||
device_idle_min_packets <= 0)) {
device_itr mi = tracked_map.find(d->get_key());
if (mi != tracked_map.end())
tracked_map.erase(mi);
// Erase it from the multimap
auto mmp = tracked_mac_multimap.equal_range(d->get_macaddr());
for (auto mmpi = mmp.first; mmpi != mmp.second; ++mmpi) {
if (mmpi->second->get_key() == d->get_key()) {
tracked_mac_multimap.erase(mmpi);
break;
}
}
// Forget it from the immutable vec, but keep its
// position; we need to have vecpos = devid
auto iti = immutable_tracked_vec->begin() + d->get_kis_internal_id();
(*iti).reset();
purged = true;
return true;
}
return false;
}), tracked_vec.end());
if (purged)
UpdateFullRefresh();
} else if (eventid == max_devices_timer) {
local_locker lock(&devicelist_mutex);
// Do nothing if we don't care
if (max_num_devices <= 0)
return 1;
// Do nothing if the number of devices is less than the max
if (tracked_vec.size() <= max_num_devices)
return 1;
// Do an update since we're trimming something
UpdateFullRefresh();
// Now things start getting expensive. Start by sorting the
// vector of devices - anything else that has to sort the entire list
// has to sort it themselves
kismet__stable_sort(tracked_vec.begin(), tracked_vec.end(),
devicetracker_sort_lastseen);
tracked_vec.erase(std::remove_if(tracked_vec.begin() + max_num_devices, tracked_vec.end(),
[&](std::shared_ptr<kis_tracked_device_base> d) {
// Lock the device itself
local_locker devlocker(&(d->device_mutex));
device_itr mi = tracked_map.find(d->get_key());
if (mi != tracked_map.end())
tracked_map.erase(mi);
// Erase it from the multimap
auto mmp = tracked_mac_multimap.equal_range(d->get_macaddr());
for (auto mmpi = mmp.first; mmpi != mmp.second; ++mmpi) {
if (mmpi->second->get_key() == d->get_key()) {
tracked_mac_multimap.erase(mmpi);
break;
}
}
// Forget it from the immutable vec, but keep its
// position; we need to have vecpos = devid
auto iti = immutable_tracked_vec->begin() + d->get_kis_internal_id();
(*iti).reset();
return true;
}), tracked_vec.end());
}
// Loop
return 1;
}
void Devicetracker::usage(const char *name __attribute__((unused))) {
printf("\n");
printf(" *** Device Tracking Options ***\n");
printf(" --device-timeout=n Expire devices after N seconds\n"
);
}
void Devicetracker::lock_devicelist() {
local_eol_locker lock(&devicelist_mutex);
}
void Devicetracker::unlock_devicelist() {
local_unlocker unlock(&devicelist_mutex);
}
int Devicetracker::Database_UpgradeDB() {
local_locker dblock(&ds_mutex);
unsigned int dbv = Database_GetDBVersion();
std::string sql;
int r;
char *sErrMsg = NULL;
if (db == NULL)
return -1;
if (dbv < 2) {
// Define a simple table for custom device names, and a similar simple table
// for notes; we store them outside the device record so that we have an
// architecture available for saving them without requiring device snapshotting
//
// Names and tags are saved in both the custom tables AND the stored device
// record; stored devices retain their internal state, only new devices query
// these tables.
}
if (dbv < 3) {
sql =
"DROP TABLE device_storage";
sqlite3_exec(db, sql.c_str(),
[] (void *, int, char **, char **) -> int { return 0; }, NULL, &sErrMsg);
}
if (dbv < 4) {
sql =
"DROP TABLE device_names";
sqlite3_exec(db, sql.c_str(),
[] (void *, int, char **, char **) -> int { return 0; }, NULL, &sErrMsg);
sql =
"DROP TABLE device_tags";
sqlite3_exec(db, sql.c_str(),
[] (void *, int, char **, char **) -> int { return 0; }, NULL, &sErrMsg);
sql =
"CREATE TABLE device_names ("
"key TEXT, "