-
Notifications
You must be signed in to change notification settings - Fork 0
/
pflogentry.cc
3013 lines (2776 loc) · 92.6 KB
/
pflogentry.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
/***************************************************************************
* Copyright (c) 2021-22 *
* Volnei Cervi Puttini. All rights reserved. *
* vcputtini@gmail.com
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 4. Neither the name of the Author nor the names of its contributors *
* may be used to endorse or promote products derived from this software*
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS *
* BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS*
* INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING *
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OFSUCH DAMAGE. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "pflogentry.h"
namespace pflogentry {
/* Visitor ------------------------------------------------------------------ */
/*!
* \internal
* \brief After deducing the type of data stored in the var_t structure, it
* returns a corresponding integer value.
* \param t std::variant() structure with data stored for type deduction.
* \return int Variable type.
*/
Visitor::TypeVar
Visitor::varType(var_t t_) const
{
TypeVar typ = {};
std::visit(overloadedP{
[&typ]([[maybe_unused]] int arg) { typ = TypeVar::TInt; },
[&typ]([[maybe_unused]] long arg) { typ = TypeVar::TLong; },
[&typ]([[maybe_unused]] uint32_t arg) { typ = TypeVar::TUint; },
[&typ]([[maybe_unused]] const std::string& arg) {
typ = TypeVar::TString;
} },
t_);
return typ;
}
/* PFLogentry --------------------------------------------------------------- */
/*!
* \brief Constructs a PFLogentry object. (default)
*/
PFLogentry::PFLogentry(LogFormat fmt_, const int year_)
: re_id_rfc3164_(cp_id_rfc3164_)
, re_id_rfc5424_(cp_id_rfc5424_)
, re_time_rfc3164_(cp_time_rfc3164_)
, re_time_rfc5424_(cp_time_rfc5424_)
, pflError(PFLError::PFL_SUCCESS)
{
if (fmt_ == LogFormat::LogBSD) {
bsd_year_ = std::move(year_);
log_fmt_ = std::move(fmt_);
} else {
bsd_year_ = 0;
log_fmt_ = std::move(fmt_);
}
}
PFLogentry::~PFLogentry()
{
clear();
}
/*!
* \brief Appends the filter log entries to the system.
* \param raw__log_
*/
PFLogentry&
PFLogentry::append(const std::string& raw__log_)
{
raw_.resize(raw__log_.size());
raw_ = std::move(raw__log_);
if (parser() == PFLError::PFL_SUCCESS) {
filter_m.insert({ std::mktime(&log_data.header.tm_time), log_data });
}
return *this;
}
/*!
* \brief Erase all entries read.
*/
void
PFLogentry::clear()
{
filter_m.clear();
uniq_ip_src.clear();
uniq_ip_dst.clear();
pflError = PFLError::PFL_SUCCESS;
};
/*!
* \brief returns the number of log entries read.
* \return size_t Is an unsigned integral type.
*/
size_t
PFLogentry::size() const
{
return filter_m.size();
}
/*!
* \internal
* \brief Returns true or false if month name is corret
* \param s Month name abbreviation
* \return true|false
* \code{.cc}
* bool b = isMonth("Jan");
* \endcode
*/
bool
PFLogentry::isMonth(const std::string&& s_)
{
auto begin_ = std::cbegin(nmonths_);
auto end_ = std::cend(nmonths_);
auto f_ = std::find_if(begin_, end_, [&s_](const char* cptr_) {
if (std::strcmp(s_.c_str(), cptr_) == 0) {
return true;
}
return false;
});
return (f_ != end_);
}
/*!
* \internal
* \brief Converts the month name abbreviation to number.
* \param s
* \return
*/
int
PFLogentry::monthToNumber(const std::string&& s_) const
{
auto begin_ = std::cbegin(nmonths_);
auto end_ = std::cend(nmonths_);
auto f_ = std::find_if(begin_, end_, [&s_](const char* cptr_) {
if (std::strcmp(s_.c_str(), cptr_) == 0) {
return true;
}
return false;
});
if (f_ != end_) {
return std::distance(begin_, f_) + 1;
}
return 0;
}
/*!
* \internal
* \brief Try to ensure that the input is valid.
* \param s_ Entry line
* \return bool
* \note It doesn't check whether the entire line is empty.
* If the first character is blank then it considers the line invalid. But an
* entirely blank line should just be ignored and not be considered an error.
*/
bool
PFLogentry::isValidEntry(const std::string s_)
{
if (s_.find("filterlog") != std::string::npos) {
if (s_[0] == '<' && s_[4] == '>' && std::isdigit(s_[5])) { // <nnn>n
return true;
} else if (!std::isalpha(s_[0]) || std::isblank(s_[0])) {
return false;
}
return true;
}
return false;
};
/*!
* \brief Return a error code.
* \return
*/
PFLogentry::PFLError
PFLogentry::errorNum() const noexcept
{
return pflError;
}
/*!
* \brief Return the description of the error.
* \return std::string
*/
std::string
PFLogentry::getErrorText() const
{
if (auto it_ = mError.find(pflError); it_ != mError.cend()) {
return it_->second.data();
}
return mError.at(PFLError::PFL_ERR_UNKNOWN).data();
}
/*!
* \internal
* \brief Splits a string according to the entered separator.
* \param sv The string that should be split
* \param sep The type of separator
* \return A string vector
* \note The logic used to 'split' the CSV string, was based on:
* https://www.tutorialspoint.com/
* parsing-a-comma-delimited-std-string-in-cplusplus
*/
std::vector<std::string>
PFLogentry::split(const std::string&& s_, const char sep_)
{
std::vector<std::string> result;
std::stringstream ss(s_.data());
while (ss.good()) {
std::string tok{};
std::getline(ss, tok, sep_);
result.push_back(std::move(tok));
}
return result;
}
/*!
* \brief Converts log entries to XML format and writes to file.
* \param fn File name with path (Mandatory).
* \param Beginning date
* \param Beginning time
* \param End date
* \param End time
* \note If the user does not inform the '.xml' extension, the library will
* provide it. If another extension is informed, it will not be considered valid
* and the function will return -1.
* \warning Important: The PFRawToXML object will always erase the data read
* after writing the XML file.
*/
PFLogentry::PFLError
PFLogentry::toXML(const std::string&& fn_,
const std::string&& d0_,
const std::string&& t0_,
const std::string&& d1_,
const std::string&& t1_)
{
if (fn_.empty()) {
setError(PFLError::PFL_ERR_XML_FILE_NAME_INCONSISTENT);
return PFLError::PFL_ERR_XML_FILE_NAME_INCONSISTENT;
}
if ((pflError == PFLError::PFL_SUCCESS) && (filter_m.size() != 0)) {
PFRawToXML xml(log_fmt_);
if (xml.save(fn_) != PFLError::PFL_SUCCESS) {
setError(PFLError::PFL_ERR_XML_FILE_NAME_INCONSISTENT);
return PFLError::PFL_ERR_XML_FILE_NAME_INCONSISTENT;
}
if ((!d0_.empty() && !t0_.empty()) && (!d1_.empty() && !t1_.empty())) {
struct std::tm tm_begin = {};
struct std::tm tm_end = {};
tm_begin = mkTime(d0_, t0_);
tm_end = mkTime(d1_, t1_);
auto lower_ = filter_m.lower_bound(std::move(std::mktime(&tm_begin)));
auto upper_ = filter_m.upper_bound(std::move(std::mktime(&tm_end)));
for (auto& it_ = lower_; it_ != upper_; ++it_) {
if (!it_->second.hostname.empty()) {
xml.append(it_->second);
}
}
} else {
for (auto& a : filter_m) {
if (!a.second.hostname.empty()) {
xml.append(a.second);
};
}
}
if (xml.close() != PFLError::PFL_SUCCESS) {
setError(PFLError::PFL_ERR_XML_FILE_NOT_SAVE);
return PFLError::PFL_ERR_XML_FILE_NOT_SAVE;
}
}
return pflError;
}
/*!
* \internal
*/
PFLogentry::LogFormat
PFLogentry::logFormat()
{
return log_fmt_;
};
/*!
* \internal
* \brief Convert std::string to a long int. It differs from std::stol() in
* that it allows the first digit to be an alphanumeric. \param s \return long
* \note long l = toLong("# 10"); // OK
* \note long l = std::stol("# 10"); // std::invalid_argument
*/
long
PFLogentry::toLong(const std::string&& s_) const
{
std::string aux = {};
for (auto& a : s_) {
if (std::isdigit(static_cast<char>(a))) {
aux += std::move(a);
}
}
return std::stol(aux);
}
/*!
* \internal
* \brief PFLogentry::setError
* \param e_ Error code
*/
void
PFLogentry::setError(PFLError e_)
{
pflError = e_;
}
/*!
* \internal
*
* \note The constants below are defined in CMakeLists.txt
*
* DEBUG_PARSER
*
*/
/*!
* \internal
* \brief Parses the log line to internal format.
* \details Performs several checks on the log line to ensure that it is
* valid. \note (1) The basis of this parse logic is based on the script
* "/usr/local/bin/filterparse.php" which is used in pfSense(R). Since the
* logic used is good enough for the job to be done, we don't consider develop
* a new logic from scratch.
*/
PFLogentry::PFLError
PFLogentry::parser()
{
if (raw_.empty() ||
(raw_.find("newsyslog") != std::string::npos)) { // ignore empty lines
setError(PFLError::PFL_SUCCESS);
return PFLError::PFL_SUCCESS;
}
if (isValidEntry(raw_)) {
#ifdef DEBUG_PARSER
std::cout << raw_ << "\n\n";
#endif
try {
log_data = {};
boost::match_results<std::string::const_iterator> match;
switch (log_fmt_) {
case LogFormat::LogBSD:
boost::regex_match(raw_, match, re_id_rfc3164_);
break;
case LogFormat::LogSyslog:
boost::regex_match(raw_, match, re_id_rfc5424_);
}
#ifdef DEBUG_PARSER
std::cout << "-0 = " << match[0] << "\n"
<< "-1 = " << match[1] << "\n"
<< "-2 = " << match[2] << "\n"
<< "-3 = " << match[3] << "\n"
<< "-4 = " << match[4] << "\n"
<< "-5 = " << match[5] << "\n"
<< "max = " << match.size() << "\n";
#endif
if (raw_[0] == '<') { // RFC-5424 line starts with '<'
log_data.header.id = std::move(match[1]);
log_data.header.time = std::move(match[2]);
boost::smatch smatches;
boost::regex_match(log_data.header.time, smatches, re_time_rfc5424_);
log_data.header.tm_time.tm_year =
std::move(std::stoi(smatches[1]) - 1900);
log_data.header.tm_time.tm_mon = std::move(std::stoi(smatches[2]) - 1);
log_data.header.tm_time.tm_mday = std::move(std::stoi(smatches[3]));
log_data.header.tm_time.tm_hour = std::move(std::stoi(smatches[4]));
log_data.header.tm_time.tm_min = std::move(std::stoi(smatches[5]));
log_data.header.tm_time.tm_sec = std::move(std::stoi(smatches[6]));
log_data.header.day = std::move(std::stoi(smatches[3]));
log_data.header.month = std::move(std::stoi(smatches[2])); // real
log_data.hostname = std::move(match[3]);
} else { // RFC-3164
if (isMonth(match[1])) {
log_data.header.month = std::move(monthToNumber(match[1]));
} else {
setError(PFLError::PFL_ERR_PARSE_INVALID_LINE);
return PFLError::PFL_ERR_PARSE_INVALID_LINE;
}
log_data.header.day = std::move(std::stoi(match[2]));
log_data.header.tm_time.tm_mday = std::move(log_data.header.day);
log_data.header.tm_time.tm_mon = std::move(monthToNumber(match[1]) - 1);
log_data.header.tm_time.tm_year = bsd_year_ - 1900;
log_data.header.time = std::move(match[3]);
boost::smatch smatches;
boost::regex_match(log_data.header.time, smatches, re_time_rfc3164_);
log_data.header.tm_time.tm_hour = std::move(std::stoi(smatches[1]));
log_data.header.tm_time.tm_min = std::move(std::stoi(smatches[2]));
log_data.header.tm_time.tm_sec = std::move(std::stoi(smatches[3]));
log_data.hostname = std::move(match[4]);
}
#ifdef DEBUG_PARSER
std::cout << "---> " << log_data.header.id << "\n";
std::cout << "---> " << log_data.header.month << "\n";
std::cout << "---> " << log_data.header.day << "\n";
std::cout << "---> " << log_data.header.time << "\n";
std::cout << "struct tm -->\n";
std::cout << " year " << log_data.header.tm_time.tm_year << "\n";
std::cout << " mon " << log_data.header.tm_time.tm_mon << "\n";
std::cout << " day " << log_data.header.tm_time.tm_mday << "\n";
std::cout << " hour " << log_data.header.tm_time.tm_hour << "\n";
std::cout << " min " << log_data.header.tm_time.tm_min << "\n";
std::cout << " sec " << log_data.header.tm_time.tm_sec << "\n";
std::cout << "---> " << log_data.hostname << "\n";
#endif
std::string tmp = std::move(match[match.size() - 1]);
size_t pos = 0;
if (log_fmt_ == LogFormat::LogBSD) {
pos = std::string_view{ tmp }.find_first_of(": ");
}
#ifdef DEBUG_PARSER
std::cout << "\nPOS " << pos << "\n";
#endif
if (pos != std::string::npos) {
if (pos == 0) {
tmp = std::string_view{ tmp }.substr(pos, tmp.length());
} else {
tmp = std::string_view{ tmp }.substr(pos + 1, tmp.length());
}
#ifdef DEBUG_PARSER
std::cout << "tmp = " << tmp << "\n";
#endif
std::vector<std::string> v;
v = split(tmp.c_str(), ',');
#ifdef DEBUG_PARSER
for (size_t i = 0; i < v.size(); i++) {
std::cout << ">> " << i << ": " << v.at(i) << std::endl;
}
#endif
int inc = 0;
if (v[0] == " ") {
setError(PFLError::PFL_ERR_PARSE_INVALID_RULENUM);
return PFLError::PFL_ERR_PARSE_INVALID_LINE;
}
log_data.rule_number = std::stol(std::move(v[inc]));
++inc;
log_data.sub_rule_number =
(v[inc].length() == 0) ? 0 : std::stol(std::move(v[inc]));
log_data.anchor = std::move(v[++inc]);
++inc;
log_data.tracker =
(v[inc].length() == 0) ? 0 : std::stol(std::move(v[inc]));
log_data.real_iface = std::move(v[++inc]);
log_data.reason = std::move(v[++inc]);
log_data.action = std::move(v[++inc]);
log_data.direction = std::move(v[++inc]);
++inc;
if (v[inc] == "4" || v[inc] == "6") {
log_data.ip_version = std::stoi(std::move(v[inc]));
if (log_data.ip_version == 4) {
log_data.ipv4_data.tos = std::move(v[++inc]);
log_data.ipv4_data.ecn = std::move(v[++inc]);
log_data.ipv4_data.ttl = std::move(std::stoi(v[++inc]));
log_data.ipv4_data.packet_id = std::move(std::stoi(v[++inc]));
log_data.ipv4_data.offset = std::move(std::stoi(v[++inc]));
log_data.ipv4_data.flags = std::move(v[++inc]);
log_data.proto_id = std::move(std::stoi(v[++inc]));
log_data.proto_text = std::move(v[++inc]);
} else {
log_data.ipv6_data.class_data = std::move(v[++inc]);
log_data.ipv6_data.flow_label = std::move(v[++inc]);
log_data.ipv6_data.hop_limit = std::move(std::stoi(v[++inc]));
log_data.proto_text = std::move(v[++inc]);
log_data.proto_id = std::move(std::stoi(v[++inc]));
}
log_data.length_data = std::move(std::stoi(v[++inc]));
log_data.ip_src_addr = std::move(v[++inc]);
log_data.ip_dst_addr = std::move(v[++inc]);
uniq_ip_src.insert(log_data.ip_src_addr);
uniq_ip_dst.insert(log_data.ip_dst_addr);
if (log_data.proto_id == ProtoID::ProtoTCP ||
log_data.proto_id == ProtoID::ProtoUDP) {
log_data.src_port = std::move(std::stoi(v[++inc]));
log_data.dst_port = std::move(std::stoi(v[++inc]));
log_data.data_len = std::move(std::stol(v[++inc]));
if (log_data.proto_id == ProtoID::ProtoTCP) {
log_data.tcp.flags = std::move(v[++inc]);
++inc; // seq
if (v[inc].find(":") != std::string::npos) {
log_data.tcp.seq_s = std::move(v[inc]);
} else {
log_data.tcp.seq =
(v[inc].length() == 0 ? 0 : std::stol(v[inc]));
}
++inc; // ack
log_data.tcp.ack =
(v[inc].length() == 0 ? 0 : std::move(std::stol(v[inc])));
++inc; // win
log_data.tcp.window =
(v[inc].length() == 0 ? 0 : std::move(std::stol(v[inc])));
++inc; // urg
log_data.tcp.urg =
(v[inc].length() == 0 ? 0 : std::move(std::stol(v[inc])));
log_data.tcp.options = v[++inc];
}
} else if ((log_data.proto_id == ProtoID::ICMPv4 ||
log_data.proto_id == ProtoID::ICMPv6)) {
log_data.icmp.src_addr = log_data.ip_src_addr;
log_data.icmp.dst_addr = log_data.ip_dst_addr;
log_data.icmp.type = std::move(v[++inc]);
if (std::map<const std::string_view, ICMPType>::const_iterator it =
icmp_m.find(log_data.icmp.type);
it == icmp_m.end()) { // found
switch (it->second) {
case ICMPType::Request:
[[fallthrough]];
case ICMPType::Reply:
log_data.icmp.id = std::move(std::stoi(v[++inc]));
log_data.icmp.seq = std::move(std::stoi(v[++inc]));
break;
case ICMPType::UnReachProto:
log_data.icmp.dst_addr = std::move(v[++inc]);
log_data.icmp.proto_id = std::move(std::stoi(v[++inc]));
break;
case ICMPType::UnReachPort:
log_data.icmp.dst_addr = std::move(v[++inc]);
log_data.icmp.proto_id = std::move(std::stoi(v[++inc]));
log_data.icmp.port = std::move(std::stoi(v[++inc]));
break;
case ICMPType::UnReach:
[[fallthrough]];
case ICMPType::TimeExceed:
[[fallthrough]];
case ICMPType::ParamProb:
[[fallthrough]];
case ICMPType::Redirect:
[[fallthrough]];
case ICMPType::MaskReply:
log_data.icmp.descr = std::move(v[++inc]);
break;
case ICMPType::NeedFrag:
log_data.icmp.dst_addr = std::move(v[++inc]);
log_data.icmp.mtu = std::move(std::stoi(v[++inc]));
break;
case ICMPType::TStamp:
log_data.icmp.id = std::move(std::stoi(v[++inc]));
log_data.icmp.seq = std::move(std::stoi(v[++inc]));
break;
case ICMPType::TStampReply:
log_data.icmp.id = std::move(std::stoi(v[++inc]));
log_data.icmp.seq = std::move(std::stoi(v[++inc]));
log_data.icmp.otime = std::move(std::stoul(v[++inc]));
log_data.icmp.rtime = std::move(std::stoul(v[++inc]));
log_data.icmp.ttime = std::move(std::stoul(v[++inc]));
break;
default:
log_data.icmp.descr = std::move(v[++inc]);
} // switch
} else if (log_data.proto_id == ProtoID::ProtoIGMP) {
log_data.igmp.src = log_data.ip_src_addr;
log_data.igmp.dst = log_data.ip_dst_addr;
} else if (log_data.proto_id == ProtoID::ProtoCARP) {
log_data.carp.type = std::move(v[++inc]);
log_data.carp.ttl = std::move(std::stoi(v[++inc]));
log_data.carp.vhid = std::move(std::stoi(v[++inc]));
log_data.carp.version = std::move(std::stoi(v[++inc]));
log_data.carp.advbase = std::move(std::stoi(v[++inc]));
log_data.carp.advskew = std::move(std::stoi(v[++inc]));
}
}
(log_data.proto_id == ProtoID::ProtoTCP && log_data.ip_version == 4)
? acc_t.accTCP4++
: 0;
(log_data.proto_id == ProtoID::ProtoTCP && log_data.ip_version == 6)
? acc_t.accTCP6++
: 0;
(log_data.proto_id == ProtoID::ProtoHOPOPT &&
log_data.ip_version == 6)
? acc_t.accHopOpt++
: 0;
(log_data.proto_id == ProtoID::ProtoUDP) ? acc_t.accUDP++ : 0;
(log_data.proto_id == ProtoID::ProtoIGMP) ? acc_t.accIGMP++ : 0;
(log_data.proto_id == ProtoID::ProtoCARP) ? acc_t.accCARP++ : 0;
(log_data.proto_id == ProtoID::ICMPv4) ? acc_t.accICMP4++ : 0;
(log_data.proto_id == ProtoID::ICMPv6) ? acc_t.accICMP6++ : 0;
} else {
setError(PFLError::PFL_ERR_PARSE_INVALID_PROTOCOL);
return PFLError::PFL_ERR_PARSE_INVALID_LINE;
}
#ifdef DEBUG_PARSER
std::cout << "tos " << log_data.ipv4_data.tos << "\n"
<< "ecn " << log_data.ipv4_data.ecn << "\n"
<< "ttl " << log_data.ipv4_data.ttl << "\n"
<< "packet_id " << log_data.ipv4_data.packet_id << "\n"
<< "offset " << log_data.ipv4_data.offset << "\n"
<< "flags " << log_data.ipv4_data.flags << "\n"
<< "\n-------\nIPV6\n"
<< "v6 class_data " << log_data.ipv6_data.class_data << "\n"
<< "v6 flow_label " << log_data.ipv6_data.flow_label << "\n"
<< "v6 hop_limit " << log_data.ipv6_data.hop_limit
<< "\n\nProtos\n"
<< "proto_text" << log_data.proto_text << "\n"
<< "proto_id " << log_data.proto_id << "\n------\n\n"
<< "length_data " << log_data.length_data << "\n"
<< "src " << log_data.ip_src_addr << "\n"
<< "dst " << log_data.ip_dst_addr << "\n"
<< "srcp " << log_data.src_port << "\n"
<< "dstp " << log_data.dst_port << "\n"
<< "len " << log_data.data_len << "\n----------\nICMP\n"
<< "id " << log_data.icmp.id << "\n"
<< "seq " << log_data.icmp.seq << "\n"
<< "type " << log_data.icmp.type << "\n"
<< "echo_type " << log_data.icmp.echo_type << "\n"
<< "proto_id " << log_data.icmp.proto_id << "\n"
<< "port " << log_data.icmp.port << "\n"
<< "descr " << log_data.icmp.descr << "\n"
<< "mtu " << log_data.icmp.mtu << "\n"
<< "otime " << log_data.icmp.otime << "\n"
<< "rtime " << log_data.icmp.rtime << "\n"
<< "ttime " << log_data.icmp.ttime << "\n"
<< "src_addr " << log_data.icmp.src_addr << "\n"
<< "dst_addr " << log_data.icmp.dst_addr
<< "\n----------\nIGMP\n"
<< "src_addr " << log_data.igmp.src << "\n"
<< "dst_addr " << log_data.igmp.dst << "\n----------\nCARP\n"
<< "type " << log_data.carp.type << "\n"
<< "ttl " << log_data.carp.ttl << "\n"
<< "vhid " << log_data.carp.vhid << "\n"
<< "version " << log_data.carp.version << "\n"
<< "advbase " << log_data.carp.advbase << "\n"
<< "advskew " << log_data.carp.advskew << "\n";
#endif
} // npos
} catch (boost::regex_error& e_) {
std::cout << "Parser PFLogentry regex error = " << e_.what() << "\n";
setError(PFLError::PFL_ERR_PARSER_FAILED);
return PFLError::PFL_ERR_PARSER_FAILED;
} catch (const std::exception& e) {
std::cout << "[" << __LINE__ << "] "
<< __FILE__ ": An exception occurred: " << e.what() << "\n";
};
} else {
setError(PFLError::PFL_ERR_PARSE_INVALID_LINE);
return PFLError::PFL_ERR_PARSE_INVALID_LINE;
} // isValidEntry
return PFLError::PFL_SUCCESS;
}
/*!
* \internal
* \brief Checks if the date is in ISO format.
* \param d_ Valid format ISO yyyy-mm-dd
* \return bool true|false
*/
bool
PFLogentry::isValidDate(const std::string d_) const
{
if (!d_.empty()) {
boost::regex re_date_(re_date_fmt_);
boost::smatch smatches_;
if (boost::regex_match(d_, smatches_, re_date_)) {
auto [y_, m_, d_] = std::tuple(std::stoi(smatches_[1]),
std::stoi(smatches_[2]),
std::stoi(smatches_[3]));
if ((y_ > 1900 && y_ <= 2038) && (m_ >= 1 && m_ <= 12) &&
(d_ >= 1 && d_ <= 31)) {
return true;
}
}
}
return false;
}
/*!
* \internal
* \brief Checks if the time is in hh:mm:ss format.
* \param t_
* \return bool true|false
*/
bool
PFLogentry::isValidTime(const std::string t_) const
{
if (!t_.empty()) {
boost::regex re_time_(re_time_fmt_);
boost::smatch smatches_;
if (boost::regex_match(t_, smatches_, re_time_)) {
auto [h_, m_, s_] = std::tuple(std::stoi(smatches_[1]),
std::stoi(smatches_[2]),
std::stoi(smatches_[3]));
if ((h_ >= 0 && h_ <= 23) && (m_ >= 0 && m_ <= 59) &&
(s_ >= 0 && s_ <= 59)) {
return true;
}
}
}
return false;
}
/*!
* \internal
* \brief Parses date and time strings and save the values inside std::tm.
* \param d_ Date (yyyy-mm-dd)
* \param t_ Time (hh:mm:ss)
* \return std::tm
*/
std::tm
PFLogentry::mkTime(const std::string d_, const std::string t_) const
{
struct std::tm tm_tmp = {};
if (isValidDate(d_) && isValidTime(t_)) {
tm_tmp.tm_year = std::move(std::stoi(d_.substr(0, 4))) - 1900;
tm_tmp.tm_mon = std::move(std::stoi(d_.substr(5, 2))) - 1;
tm_tmp.tm_mday = std::move(std::stoi(d_.substr(8, 2)));
tm_tmp.tm_hour = std::move(std::stoi(t_.substr(0, 2)));
tm_tmp.tm_min = std::move(std::stoi(t_.substr(3, 2)));
tm_tmp.tm_sec = std::move(std::stoi(t_.substr(6, 2)));
}
return tm_tmp;
}
/*!
* \internal
* \brief Computes difference between two date/time.
* \param tm_end Date/time read from log entry.
* \param tm_beginning Date/time informed by the user for comparison.
* \return integer (-1 | 0 | 1)
* \code{.cc}
* // rfc-3164
* int i = compareDT("10:00:00", "10:01:00");
* //or
* // rfc-5424
* int ii = compareDT("2021-08-31T08:13:00.576185-03:00",
* "2021-09-01T09:13:00.772202-03:00");
* \endcode
*/
int
PFLogentry::compareDT(const std::string tm_end_,
const std::string tm_beginning_) const
{
std::time_t tm_lhs = {};
std::time_t tm_rhs = {};
struct tm tm1 = {};
struct tm tm2 = {};
if (log_fmt_ == LogFormat::LogBSD) {
::strptime(tm_end_.c_str(), "%H:%M:%S", &tm1);
::strptime(tm_beginning_.c_str(), "%H:%M:%S", &tm2);
} else {
::strptime(tm_end_.c_str(), "%Y-%m-%dT%H:%M:%S", &tm1);
::strptime(tm_beginning_.c_str(), "%Y-%m-%dT%H:%M:%S", &tm2);
}
tm_lhs = std::mktime(&tm1);
tm_rhs = std::mktime(&tm2);
float diff = std::difftime(tm_lhs, tm_rhs);
if (diff == 0) { // end == begining
return 0;
} else if (diff < 0) { // end < begining
return -1;
}
return 1; // end > begining
}
/*!
* \internal
* \brief Compute the logic: BETWEEN val_min AND|OR val_max. Where val_min is
* the beginning date/time and val_max is the end date/time.
* \param data The data value stored in the log entry.
* \param tm_min Beginning date.
* \param tm_max End date
* \param Comp Compare::BTWAND or Compare::BTWOR
* \return true|false
*/
bool
PFLogentry::compareDT1(const std::string data_,
const std::string tm_min_,
const std::string tm_max_,
Compare Comp_) const
{
std::time_t tm_data = {};
std::time_t tm_b = {};
std::time_t tm_e = {};
struct tm tm1 = {};
struct tm tm2 = {};
struct tm tm3 = {};
switch (log_fmt_) {
case LogFormat::LogBSD: {
::strptime(data_.c_str(), "%H:%M:%S", &tm1);
::strptime(tm_min_.c_str(), "%H:%M:%S", &tm2);
::strptime(tm_max_.c_str(), "%H:%M:%S", &tm3);
break;
}
default: {
::strptime(data_.c_str(), "%Y-%m-%dT%H:%M:%S", &tm1);
::strptime(tm_min_.c_str(), "%Y-%m-%dT%H:%M:%S", &tm2);
::strptime(tm_max_.c_str(), "%Y-%m-%dT%H:%M:%S", &tm3);
}
}
tm_data = std::mktime(&tm1);
tm_b = std::mktime(&tm2);
tm_e = std::mktime(&tm3);
return decision(tm_data, tm_b, tm_e, Comp_);
}
/*!
* \internal
* \brief This template function implements the logical AND and OR operations
* for functions like "between A AND B" or "between A OR B".
*
* \param data_ The data to be compared with its limits.
* \param min_ Lower value.
* \param max_ Highest value.
* \param cmp_ Type of logical operation: BTWAND | BTWOR
*
*/
template<typename TVarD, typename TMin, typename TMax, typename TCompare>
bool
PFLogentry::decision(TVarD&& data_,
TMin&& min_,
TMax&& max_,
TCompare&& cmp_) const
{
switch (cmp_) {
case Compare::BTWAND: {
return ((data_ >= min_) && (data_ <= max_));
}
case Compare::BTWOR: {
return ((data_ >= min_) || (data_ <= max_));
}
default: {
return false;
}
}
};
/*!
* \internal
* \brief Overloaded: This template function implements the logical
* operations:
* == < > <= >= !=
* \param lhs_ Argument 1
* \param rhs_ Argument 2
* \param cmp_ Type of logical operation. EQ, LT, GT, LE, GE, NE
*/
template<typename TVarS, typename TVarD, typename TCompare>
bool
PFLogentry::decision(TVarS&& lhs_, TVarD&& rhs_, TCompare&& cmp_) const
{
switch (cmp_) {
case Compare::EQ: {
return lhs_ == rhs_;
}
case Compare::LT: {
return lhs_ < rhs_;
}
case Compare::GT: {
return lhs_ > rhs_;
}
case Compare::LE: {
return lhs_ <= rhs_;
}
case Compare::GE: {
return lhs_ >= rhs_;
}
case Compare::NE: {
return lhs_ != rhs_;
}
default: {
return false;
}
}
};
/*!
* \internal
*/
template<typename Ta, typename Tb>
float
PFLogentry::percent(Ta lhs_, Tb rhs_) const
{
return (static_cast<float>(lhs_) / static_cast<float>(rhs_)) * 100;
}
/*!
* \internal
* \brief Returns the value of integer fields
* \param f_ Field Id
* \param d_ Data
* \return int
*/
constexpr int
PFLogentry::intFields(Fields f_, const LogData& d_) const
{
switch (f_) {
case Fields::HdrMonth:
return d_.header.month;
case Fields::HdrDay:
return d_.header.day;
case Fields::IpVersion:
return d_.ip_version;
case Fields::Ipv4DataTTL:
return d_.ipv4_data.ttl;
case Fields::Ipv4DataPKTID:
return d_.ipv4_data.packet_id;
case Fields::Ipv4DataOFFSET:
return d_.ipv4_data.offset;
case Fields::Ipv6DataHOPLIM:
return d_.ipv6_data.hop_limit;
case Fields::ProtoId:
return d_.proto_id;
case Fields::Length:
return d_.length_data;
case Fields::SrcPort:
return d_.src_port;
case Fields::DstPort:
return d_.dst_port;
case Fields::IcmpProtoId:
return d_.icmp.id;
case Fields::IcmpPort:
return d_.icmp.port;
case Fields::IcmpMTU:
return d_.icmp.mtu;
case Fields::CarpTTL:
return d_.carp.ttl;
case Fields::CarpVHID:
return d_.carp.vhid;
case Fields::CarpVersion:
return d_.carp.version;
case Fields::CarpAdvBase:
return d_.carp.advbase;
case Fields::CarpAdvSkew:
return d_.carp.advskew;
default:
return 0;
}
}
/*!
* \internal
* \brief Returns the value of long integer fields
* \param f_ Field Id
* \param d_ Data
* \return long
*/
constexpr long
PFLogentry::longFields(Fields f_, const LogData& d_) const
{
switch (f_) {
case Fields::RuleNumber:
return d_.rule_number;
case Fields::SubRuleNumber:
return d_.sub_rule_number;
case Fields::Tracker: