-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnescaengine.cc
1772 lines (1510 loc) · 52.7 KB
/
nescaengine.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) 2024, oldteam. All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* 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 OF SUCH DAMAGE.
*/
#include "include/nescaengine.h"
#include "libncsnet/ncsnet/ip.h"
#include "libncsnet/ncsnet/ip4addr.h"
#include "libncsnet/ncsnet/tcp.h"
#include <cstdlib>
/* мутэкс для остановки приема */
static std::mutex stoprecv;
/*
* Получает максимально возможное число открытых сокетов, возвращает его.
*/
static int maxfds(void)
{
struct rlimit limit;
getrlimit(RLIMIT_NOFILE, &limit);
return limit.rlim_cur;
}
/*
* Получает DNS у ip4 или ip6 и добавляет его к цели.
*/
bool NESCARESOLV_try(NESCATARGET *target, NESCADATA *ncsdata)
{
char host[NI_MAXHOST], service[NI_MAXSERV];
struct sockaddr_storage addr={0};
struct sockaddr_in6 *sa6=NULL;
struct sockaddr_in *sa=NULL;
int len=0, ret=0;
const char *ip;
memset(&addr, 0, sizeof(addr));
ip=target->get_mainip().c_str();
if (target->is_ip6host()) {
sa6=(struct sockaddr_in6*)&addr;
sa6->sin6_family=AF_INET6;
inet_pton(AF_INET6, ip,
&sa6->sin6_addr);
len=sizeof(struct sockaddr_in6);
}
else {
sa=(struct sockaddr_in*)&addr;
sa->sin_family=AF_INET;
sa->sin_addr.s_addr=inet_addr(ip);
len=sizeof(struct sockaddr_in);
}
ret=getnameinfo((struct sockaddr*)&addr, len,
host, sizeof(host), service, sizeof(service), 0);
if (ret!=0)
return 0;
stoprecv.lock();
target->add_dns(host);
stoprecv.unlock();
return 1;
}
/*
* Запускает в пуле потоков функцю NESCARESOLV_try, выводит информацию о
* своем запуске, если стоит stats.
*/
bool _NESCARESOLV_(std::vector<NESCATARGET*> targets, NESCADATA *ncsdata)
{
std::vector<std::future<bool>> futures;
size_t threads=targets.size();
bool success=1;
size_t i=0;
if (ncsdata->opts.check_stats_flag()) {
std::cout << "NESCARESOLV ";
std::cout << "for " << targets.size() << " targets ";
std::cout << " (and ..., \?\?\?)";
std::cout << std::endl;
}
futures.reserve(threads);
NESCAPOOL pool(threads);
for (;i<threads;++i) {
futures.emplace_back(pool.enqueue(
[&, i]() {
return NESCARESOLV_try(targets[i], ncsdata);
}
));
}
for (auto&future:futures)
if (!future.get())
success=0;
return success;
}
/*
* Пул потоков взятый из chatgpt, и который она всем дает.
*/
NESCAPOOL::NESCAPOOL(size_t numthreads) : stop(false)
{
size_t i;
for (i=0;i<numthreads;++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()>task;{
std::unique_lock<std::mutex> lock(queuemutex);
condition.wait(lock,[this]{return stop||!tasks.empty();});
if (stop&&tasks.empty()) {return;}
task=std::move(tasks.front());
tasks.pop();
}
task();
}
}
);
}
}
/* Завершает этот пул потоков */
NESCAPOOL::~NESCAPOOL()
{
{
std::unique_lock<std::mutex> lock(queuemutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker:workers){worker.join();}
}
/*
* Фильтр для ICMP4 ошибок, в случае dstunreach возвращает код
* ошибки, поскольку для некоторых типов сканирования и пинга
* это может повлиять на статус
*/
static int __received_icmp4_error(u8 *frame, size_t frmlen, void *arg, int *skip, int *proto)
{
struct __arg_ *a=(struct __arg_*)arg;
icmph_t *icmp=NULL;
ip4h_t *ip=NULL;
/*
* Получает сдвиг до дополнительного протокола в ICMP ошибке. Т.е,
* [mac]+[ip]+[icmp & msg]+[ip] = [то что нужно]
*/
*skip=(14+sizeof(ip4h_t)+(sizeof(icmph_t)+4)+sizeof(ip4h_t));
/* ICMP заголовок ошибки */
icmp=(icmph_t*)(frame+(14+sizeof(ip4h_t)));
if (icmp->type==ICMP4_REDIRECT||icmp->type==ICMP4_SRCQUENCH||
icmp->type==ICMP4_PARAMPROB||icmp->type==ICMP4_TIMEXCEED||
icmp->type==ICMP4_UNREACH) {
/* IP заголовок внутри ICMP ошибки */
ip=(ip4h_t*)(frame+((14+sizeof(ip4h_t)+sizeof(icmph_t)+4)));
*proto=ip->proto;
/*
* Сначала сравнивает сходится ли ip получателя с нашим ip в IP
* заголовке в ICMP ошибке. Если не сходится, то тогда делаем тоже
* самое только уже в основном IP заголовке.
*/
if (!ip4t_compare(a->addr.ip4, ip->dst)) {
ip=(ip4h_t*)(frame+14);
if (!ip4t_compare(a->addr.ip4, ip->src))
return 0;
}
if (icmp->type==ICMP4_UNREACH&&
(icmp->code==ICMP4_UNREACH_PORT
||icmp->code==ICMP4_UNREACH_PROTO))
return icmp->code;
}
return 0;
}
/*
* Фильтр для ICMP6 ошибок, в случае dstunreach возвращает код ошибки,
* поскольку для некоторых типов сканирования и пинга это может повлиять
* на статус
*/
static int __received_icmp6_error(u8 *frame, size_t frmlen, void *arg, int *skip, int *proto)
{
struct __arg_ *a=(struct __arg_*)arg;
icmph_t *icmp=NULL;
ip6h_t *ip=NULL;
/*
* Получает сдвиг до дополнительного протокола в ICMP ошибке. Т.е,
* [mac]+[ip6]+[icmp & msg]+[ip6] = [то что нужно]
*/
*skip=(14+sizeof(ip6h_t)+(sizeof(icmph_t)+4)+sizeof(ip6h_t));
/* ICMP заголовок ошибки */
icmp=(icmph_t*)(frame+(14+sizeof(ip6h_t)));
if (icmp->type==ICMP6_UNREACH||
icmp->type==ICMP6_PARAMPROBLEM
||icmp->type==2/* pkt too big*/||
icmp->type==ICMP6_TIMEXCEED) {
/* IP заголовок внутри ICMP ошибки */
ip=(ip6h_t*)(frame+((14+sizeof(ip6h_t)+sizeof(icmph_t)+4)));
*proto=ip->nxt;
/*
* Сначала сравнивает сходится ли ip получателя с нашим ip в
* IP заголовке в ICMP ошибке. Если не сходится, то тогда
* делаем тоже самое только уже в основном IP заголовке.
*/
if (!ip6t_compare(a->addr.ip6, ip->dst)) {
ip=(ip6h_t*)(frame+14);
if (!ip6t_compare(a->addr.ip6, ip->src))
return 0;
}
if (icmp->type==ICMP6_UNREACH&&
icmp->code==ICMP6_UNREACH_PORT)
return icmp->code;
}
return 0;
}
/*
* Фильтр для ICMP4 и ICMP6 ошибок.
*/
static int __received_icmp_error(u8 *frame, size_t frmlen, void *arg, int icmpv)
{
struct filter_ { u16 srcport; u16 dstport; union{u16 icmpid; u32 vtagseq;}; };
int ret=0, skip=0, proto=0;
struct __arg_ *a=(struct __arg_*)arg;
/* Проверяем полезна ли нам эта ошибка */
if (icmpv==PR_ICMP)
ret=__received_icmp4_error(frame, frmlen, arg, &skip, &proto);
if (a->addrtype==PR_ICMPV6)
ret=__received_icmp6_error(frame, frmlen, arg, &skip, &proto);
if (!ret)
return ret;
/*
* Протокол внутри IP заголовка внтури ICMP ошибки не сходится
* с нашим протоколом.
*/
if (proto!=a->proto)
return 0;
/*
* Проверка наш ли это пакет, для ICMP это id, для TCP,UDP,SCTP
* это порт получателя и отправителя, а также, для TCP - seq,
* для SCTP - vtag
*/
if (a->proto==PR_TCP||a->proto==PR_UDP||a->proto==PR_SCTP||
a->proto==PR_ICMP) {
struct filter_ *f=(struct filter_*)(frame+skip);
if (a->proto==PR_ICMP&&(a->chk!=ntohs(f->icmpid)))
return 0;
if (a->proto==PR_TCP&&((a->chk!=ntohl(f->vtagseq))||
(a->port!=ntohs(f->dstport))||a->srcport!=ntohs(f->srcport)))
return 0;
if (a->proto==PR_SCTP&&((a->chk!=ntohl(f->vtagseq))||
(a->port!=ntohs(f->dstport))||a->srcport!=ntohs(f->srcport)))
return 0;
if (a->proto==PR_UDP&&(a->port!=ntohs(f->dstport)||
a->srcport!=ntohs(f->srcport)))
return 0;
}
return ret;
}
/*
* Фильтр для приема ARP пакетов, проверяет много всего, например,
* операцию, заголовок, протокол, мак ли адреса и ip4 адреса ли, и
* т.д.
*/
static bool __received_arp_ping_callback(u8 *frame, size_t frmlen, void *arg)
{
struct __arg_ *a=(struct __arg_*)arg;
arp_op_hdr_request_ethip *arpreq;
arph_t *arp;
arp=(arph_t*)(frame+sizeof(mach_t));
if (ntohs(arp->op)!=ARP_OP_REPLY)
return 0;
if (ntohs(arp->hdr)!=ARP_HDR_ETH)
return 0;
if (ntohs(arp->hdr)==ARP_HDR_AX25||
ntohs(arp->hdr)==ARP_HDR_RESERVED) {
if (ntohs(arp->pro)!=AX25_PRO_IP)
return 0;
}
else if (ntohs(arp->pro)!=ARP_PRO_IP)
return 0;
if (arp->pln!=4) /* только ipv4 */
return 0;
if (arp->hln!=6) /* только mac адреса
длинной в 6 байт */
return 0;
/*
* Ip4-адрес получателя внутри ARP-запроса должен совпадать с
* локальным ip4 адресам, иначе пакет не был адресован нам.
*/
arpreq=(arp_op_request_ethip*)((frame)+(sizeof(mach_t)+sizeof(arph_t)));
if (!ip4t_compare(arpreq->spa, a->addr.ip4))
return 0;
return 1;
}
/*
* Фильтр для пинг сканирования, обрабатывает ARP, IP, ICMP4,
* ICMP6, TCP, UDP, SCTP.
*/
static bool __ping_callback(u8 *frame, size_t frmlen, void *arg)
{
struct __arg_ *a=(struct __arg_*)arg;
int skip=0, proto=0;
mach_t *datalink;
ip6_t cmp6;
ip4_t cmp4;
if (frmlen<14)
return 0;
datalink=(mach_t*)frame;
skip=0;
/* Это ARP пинг а значит вызываем его callback */
if (a->method==M_ARP_PING) {
if (ntohs(datalink->type)!=ETH_TYPE_ARP)
return 0;
return __received_arp_ping_callback(frame,
frmlen, arg);
}
/* Это не IP пакет, и не наш ARP */
if ((a->addrtype==4&&ntohs(datalink->type)!=ETH_TYPE_IPV4)||
(a->addrtype==6&&ntohs(datalink->type)!=ETH_TYPE_IPV6))
return 0;
/*
* Проверяем наличие IP4 или IP6 заголовка, и сохраняем, во первых
* сдвиг до следующего протокола, затем IP адрес отправителя для
* дальнейшего сравнения, и следующий проткол.
*/
if (a->addrtype==4) {
if ((frmlen-14)<sizeof(ip4h_t))
return 0;
ip4h_t *iph=(ip4h_t*)(frame+14);
cmp4=iph->src;
skip=sizeof(ip4h_t);
proto=iph->proto;
}
else if (a->addrtype==6) {
if ((frmlen-14)<sizeof(ip6h_t))
return 0;
ip6h_t *iph=(ip6h_t*)(frame+14);
cmp6=iph->src;
skip=sizeof(ip6h_t);
proto=iph->nxt;
}
/*
* Если протокол это ICMP то проверяем его на ошибки которые
* могут быть нам полезны.
*/
if (proto==PR_ICMP||proto==PR_ICMPV6) {
icmph_t *icmp=(icmph_t*)((frame+(14+skip)));
/*
* Проверяем ошибка ли это вообще, конечно внутри этих функций тоже
* есть проверка, но если они вернут 0, то эта тоже завершится, хотя
* это мог быть пинг например.
*/
if (proto==PR_ICMP&&icmp->type!=ICMP4_ECHOREPLY&&
icmp->type!=ICMP4_TSTAMPREPLY
&&icmp->type!=ICMP4_INFOREPLY)
return (bool)__received_icmp_error(frame, frmlen, arg, proto);
if (proto==PR_ICMPV6&&icmp->type!=ICMP6_ECHOREPLY)
return (bool)__received_icmp_error(frame, frmlen, arg, proto);
}
/*
* Проверяем сходится ли протокол с нашим, и сходятся ли IP.
*/
if (proto!=a->proto)
return 0;
if (a->addrtype==6&&!ip6t_compare(a->addr.ip6, cmp6))
return 0;
if (a->addrtype==4&&!ip4t_compare(a->addr.ip4, cmp4))
return 0;
/*
* Фильтрация ICMP4 пинга, echo, tstamp, info. Если это ECHO пинг то в
* ответ мы ждем ICMP пакет с ICMPECHOREPLY типом, если TSTAMP то в ответ
* TSTAMPREPLY, если INFO, то в ответ INFOREPLY
*/
if (proto==PR_ICMP) {
icmph_t *icmp=(icmph_t*)((frame+(14+skip)));
if ((icmp->type!=ICMP4_ECHOREPLY&&a->method==M_ICMP_PING_ECHO)||
(icmp->type!=ICMP4_TSTAMPREPLY&&a->method==M_ICMP_PING_TIME)||
(icmp->type!=ICMP4_INFOREPLY &&a->method==M_ICMP_PING_INFO))
return 0;
}
/*
* Фильтрация ICMP6 ECHO пинга, в ответ мы ждем ICMP6 пакет с типом
* ECHOREPLY
*/
if (proto==PR_ICMPV6) {
icmph_t *icmp=(icmph_t*)((frame+(14+skip)));
if (icmp->type!=ICMP6_ECHOREPLY&&a->method==M_ICMP_PING_ECHO)
return 0;
}
/*
* Фильтрация TCP пинга, ACK, SYN. В ответ на ACK запрос мы ждем TCP
* пакет с флагом RST, в ответ на SYN, мы ждем пакет с флагами
* SYN+ACK, или RST ???, порты тоже должны сходится.
*/
if (proto==PR_TCP) {
tcph_t *tcp=(tcph_t*)(frame+(14+skip));
if ((ntohs(tcp->th_sport)!=a->port||ntohs(tcp->th_dport)!=a->srcport)||
(a->method==M_TCP_PING_ACK&&!(tcp->th_flags&TCP_FLAG_RST))||
(a->method==M_TCP_PING_SYN&&!(tcp->th_flags&TCP_FLAG_RST)&&
(tcp->th_flags&!(TCP_FLAG_SYN|TCP_FLAG_ACK))))
return 0;
}
/*
* Фильтрация UDP пинга, тут особо нечего делать, ведь просто само
* обстоятельство когда на UDP пакет пришел UDP пакет уже удивительно,
* проверяем сходство портов
*/
if (proto==PR_UDP) {
udph_t *udp=(udph_t*)(((frame+14)+skip));
if (ntohs(udp->srcport)!=a->port||
ntohs(udp->dstport)!=a->srcport)
return 0;
}
/*
* Фильтрация SCTP пинга, тут проверяем тоже только порты.
*/
if (proto==PR_SCTP) {
sctph_t *sctp=(sctph_t*)(((frame+14)+skip));
if (ntohs(sctp->srcport)!=a->port||
ntohs(sctp->dstport)!=a->srcport)
return 0;
}
return 1;
}
/*
* Фильтр для сканирования портов, подходит для, TCP, SCTP, UDP
* сканирований, всех их подтипов.
*/
static bool __scan_callback(u8 *frame, size_t frmlen, void *arg)
{
struct __arg_ *a=(struct __arg_*)arg;
int skip=0, proto=0, ret=0;
mach_t *datalink;
ip6_t cmp6;
ip4_t cmp4;
if (frmlen<14)
return 0;
datalink=(mach_t*)frame;
skip=0;
/* Убеждаемся что это IP пакет */
if ((a->addrtype==4&&ntohs(datalink->type)!=ETH_TYPE_IPV4)||
(a->addrtype==6&&ntohs(datalink->type)!=ETH_TYPE_IPV6))
return 0;
/*
* Проверяем наличие IP4 или IP6 заголовка, и сохраняем, во первых
* сдвиг до следующего протокола, затем IP адрес отправителя для
* дальнейшего сравнения, и следующий проткол.
*/
if (a->addrtype==4) {
if ((frmlen-14)<sizeof(ip4h_t))
return 0;
ip4h_t *iph=(ip4h_t*)(frame+14);
cmp4=iph->src;
skip=sizeof(ip4h_t);
proto=iph->proto;
}
else if (a->addrtype==6) {
if ((frmlen-14)<sizeof(ip6h_t))
return 0;
ip6h_t *iph=(ip6h_t*)(frame+14);
cmp6=iph->src;
skip=sizeof(ip6h_t);
proto=iph->nxt;
}
/*
* Если пришел ICMP и это ошибка, то если метод сканирования это
* UDP, значит порт имеет статус закрытого (closed), в ином случае,
* порт имеет статус фильтрации (filtered)
*/
if (proto==PR_ICMP||proto==PR_ICMPV6) {
icmph_t *icmp=(icmph_t*)((frame+(14+skip)));
if (proto==PR_ICMP&&icmp->type!=ICMP4_ECHOREPLY&&
icmp->type!=ICMP4_TSTAMPREPLY
&&icmp->type!=ICMP4_INFOREPLY)
ret=__received_icmp_error(frame, frmlen, arg, proto);
if (proto==PR_ICMPV6&&icmp->type!=ICMP6_ECHOREPLY)
ret=__received_icmp_error(frame, frmlen, arg, proto);
if (ret) {
a->state=(ret==ICMP4_UNREACH_PORT&&a->method==M_UDP_SCAN)
?PORT_CLOSED:PORT_FILTER;
return 1;
}
return 0;
}
/*
* Проверяем сходится ли протокол с нашим, и сходятся ли IP.
*/
if (proto!=a->proto)
return 0;
if (a->addrtype==6)
if (!ip6t_compare(a->addr.ip6, cmp6))
return 0;
if (a->addrtype==4)
if (!ip4t_compare(a->addr.ip4, cmp4))
return 0;
/*
* TCP сканирование портов
* ack, syn, null, fin, xmas, maimon, window, psh
*
* https://github.com/nmap/nmap/blob/master/scan_engine_raw.cc
*/
if (proto==PR_TCP) {
tcph_t *tcp=(tcph_t*)(frame+(14+skip));
if (ntohs(tcp->th_sport)!=a->port||
ntohs(tcp->th_dport)!=a->srcport)
return 0;
if (a->method==M_TCP_SYN_SCAN) {
if ((tcp->th_flags&(TCP_FLAG_SYN|TCP_FLAG_ACK))
==(TCP_FLAG_SYN|TCP_FLAG_ACK))
a->state=PORT_OPEN;
else if (tcp->th_flags&TCP_FLAG_RST)
a->state=PORT_CLOSED;
}
if (a->method==M_TCP_WINDOW_SCAN)
if (tcp->th_flags&TCP_FLAG_RST)
a->state=(tcp->th_win)?PORT_OPEN:PORT_CLOSED;
if (a->method==M_TCP_XMAS_SCAN||
a->method==M_TCP_NULL_SCAN||
a->method==M_TCP_PSH_SCAN||
a->method==M_TCP_MAIMON_SCAN||
a->method==M_TCP_FIN_SCAN)
if (tcp->th_flags&TCP_FLAG_RST)
a->state=PORT_CLOSED;
if (a->method==M_TCP_ACK_SCAN)
if (tcp->th_flags&TCP_FLAG_RST)
a->state=PORT_NO_FILTER;
}
/*
* UDP сканирование портов
* https://nmap.org/book/scan-methods-udp-scan.html
*/
if (proto==PR_UDP) {
udph_t *udp=(udph_t*)(((frame+14)+skip));
if (ntohs(udp->srcport)!=a->port||
ntohs(udp->dstport)!=a->srcport)
return 0;
a->state=PORT_OPEN;
}
/*
* SCTP сканирование портов
* init, cookie
*
* https://nmap.org/book/man-port-scanning-techniques.html
* https://github.com/nmap/nmap/blob/master/scan_engine_raw.cc
*/
if (proto==PR_SCTP) {
sctph_t *sctp=(sctph_t*)(((frame+14)+skip));
sctp_chunk *chunk=(sctp_chunk*)(((frame+14)+(skip+sizeof(sctph_t))));
if (ntohs(sctp->srcport)!=a->port||
ntohs(sctp->dstport)!=a->srcport)
return 0;
if (a->method==M_SCTP_INIT_SCAN) {
if (chunk->type==SCTP_INIT_ACK)
a->state=PORT_OPEN;
else if (chunk->type==SCTP_ABORT)
a->state=PORT_CLOSED;
}
if (a->method==M_SCTP_COOKIE_SCAN)
if (chunk->type==SCTP_ABORT)
a->state=PORT_CLOSED;
}
return 1;
}
/*
* Иницилизируем иницилизацию, получаем сокет для отправки и
* методы, обнуляем переменные, получаем общее число пакетов.
*/
NESCAINIT::NESCAINIT(NESCADATA *ncsdata, bool ping)
{
ni_initsendfd(&ncsdata->dev);
ni_initmethods(&ncsdata->opts, ping);
total=last_target=last_method=last_num=0;
num=NI_NUM(ncsdata->targets);
}
/*
* Возвращает общее количество пакетов, для этого считаем
* все методы, и количество проб для этих методов не считая
* уже сами методы, и умножаем это на общее количество целей.
*/
size_t NESCAINIT::NI_NUM(std::vector<NESCATARGET*> targets)
{
size_t res=0;
res+=ni_methods.size();
for (auto&m:ni_methods)
res+=m.numprobes-1;
res*=targets.size();
return res;
}
/*
* Сносим нахуй иницилизацию, закрываем сокет для отправки,
* и очищая удаляем все что она создала.
*/
NESCAINIT::~NESCAINIT(void)
{
if (this->sendfd)
eth_close(this->sendfd);
NI_CLEAR();
}
/*
* Очищает и почти удаляет все что было сделано классом
* NESCAINIT, пробы, результаты, сокеты для приема.
*/
void NESCAINIT::NI_CLEAR(void)
{
std::vector<std::thread> threads;
for (auto p:probes) {
if (p->probe)
free(p->probe);
delete p;
}
probes.clear();
for (auto res:results) {
if (res->frame)
free(res->frame);
delete res;
}
results.clear();
for (lr_t *lr:recvfds)
if (lr) threads.emplace_back(lr_close, lr);
for (auto&th:threads)
th.join();
recvfds.clear();
}
/*
* Иницилизируем сокет для отправки, на наш
* интерфейс.
*/
void NESCAINIT::ni_initsendfd(NESCADEVICE *ncsdev)
{
this->sendfd=eth_open(ncsdev->get_device().c_str());
}
/*
* Иницилизируем сокет для приема, для этого получаем или
* считаем таймаут, устанавливаем фильтр, либо сканирование
* либо пинг, и добавляем сокет в вектор сокетов для приема.
*/
void NESCAINIT::ni_initrecvfd(NESCATARGET *target, NESCADEVICE *ncsdev,
NESCAOPTS *ncsopts, bool ping)
{
long long timeout=0;
lr_t *lr=NULL;
size_t mtpl;
if (ncsopts->check_mtpl_scan_flag()&&!ping&&target->get_num_time()>0) {
mtpl=atoll(ncsopts->get_mtpl_scan_param().c_str());
timeout=(target->get_time_ns(0))*mtpl;
}
if (ncsopts->check_wait_scan_flag()&&!ping)
timeout=(delayconv(ncsopts->get_wait_scan_param().c_str()));
if (ncsopts->check_wait_ping_flag()&&ping)
timeout=delayconv(ncsopts->get_wait_ping_param().c_str());
/* Прорицаем примерную задержку отправки, оно не работает
* даже когда работает */
timeout+=ncsdev->get_send_at();
lr=lr_open(ncsdev->get_device().c_str(), timeout);
if (ping)
lr_callback(lr, __ping_callback);
else
lr_callback(lr, __scan_callback);
this->recvfds.push_back(lr);
}
/*
* Иницилизируем метод и число проб на этот метод, что бы
* получить количество проб если указаны еще и порты, нужно
* их перемножить.
*/
void NESCAINIT::ni_initmethod(size_t numprobes, int method,
std::vector<int> ports)
{
int proto;
proto=((method>=1&&method<=3)?PR_ICMP
:(method>=4&&method<=13)?PR_TCP
:(method>=14&&method<=16)?PR_SCTP
:(method>=17&&method<=18)?PR_UDP
:ETH_TYPE_ARP);
NESCAMETHOD m={(((numprobes>0)?numprobes:1))*
((ports.empty())?1:ports.size()), 0, method,
proto, ports};
this->ni_methods.push_back(m);
}
/*
* Иницилизирует методы сканирования и пинга, вначале собирает
* порты, затем количество проб, и иницилизирует вызывая
* функцию выше.
*/
void NESCAINIT::ni_initmethods(NESCAOPTS *ncsopts, bool ping)
{
std::vector<int> tcports, udports, sctports;
size_t numtmp=0, numscan=0;
if (ping)
goto ping;
for (const auto&port:ncsopts->get_p_param()) {
if (port.proto==PR_TCP)
tcports.push_back(port.port);
if (port.proto==PR_UDP)
udports.push_back(port.port);
if (port.proto==PR_SCTP)
sctports.push_back(port.port);
}
numscan=atoll(ncsopts->get_num_scan_param().c_str());
if (ncsopts->check_syn_flag())
ni_initmethod(numscan, M_TCP_SYN_SCAN, tcports);
if (ncsopts->check_xmas_flag())
ni_initmethod(numscan, M_TCP_XMAS_SCAN, tcports);
if (ncsopts->check_fin_flag())
ni_initmethod(numscan, M_TCP_FIN_SCAN, tcports);
if (ncsopts->check_null_flag())
ni_initmethod(numscan, M_TCP_NULL_SCAN, tcports);
if (ncsopts->check_psh_flag())
ni_initmethod(numscan, M_TCP_PSH_SCAN, tcports);
if (ncsopts->check_window_flag())
ni_initmethod(numscan, M_TCP_WINDOW_SCAN, tcports);
if (ncsopts->check_ack_flag())
ni_initmethod(numscan, M_TCP_ACK_SCAN, tcports);
if (ncsopts->check_maimon_flag())
ni_initmethod(numscan, M_TCP_MAIMON_SCAN, tcports);
if (ncsopts->check_init_flag())
ni_initmethod(numscan, M_SCTP_INIT_SCAN, sctports);
if (ncsopts->check_cookie_flag())
ni_initmethod(numscan, M_SCTP_COOKIE_SCAN, sctports);
if (ncsopts->check_udp_flag())
ni_initmethod(numscan, M_UDP_SCAN, udports);
/* ..., */
return;
ping:
numtmp=atoll(ncsopts->get_num_ping_param().c_str());
if (ncsopts->check_pe_flag())
ni_initmethod(numtmp, M_ICMP_PING_ECHO, {});
if (ncsopts->check_pm_flag())
ni_initmethod(numtmp, M_ICMP_PING_TIME, {});
if (ncsopts->check_pi_flag())
ni_initmethod(numtmp, M_ICMP_PING_INFO, {});
if (ncsopts->check_pu_flag())
ni_initmethod(numtmp, M_UDP_PING, ncsopts->get_pu_param());
if (ncsopts->check_ps_flag())
ni_initmethod(numtmp, M_TCP_PING_SYN, ncsopts->get_ps_param());
if (ncsopts->check_pa_flag())
ni_initmethod(numtmp, M_TCP_PING_ACK, ncsopts->get_pa_param());
if (ncsopts->check_py_flag())
ni_initmethod(numtmp, M_SCTP_INIT_PING, ncsopts->get_py_param());
if (ncsopts->check_pr_flag())
ni_initmethod(numtmp, M_ARP_PING, {});
/* ..., */
}
/*
* Получает payload сразу с трех источников, и объеденяет в один,
* и возвращает его в unsigned char *.
*/
static u8 *get_payload(NESCAOPTS *ncsopts, size_t *reslen)
{
size_t hexlen=0, strlen_=0, randlen=0, skip=0;
u8 *res=NULL, *hex=NULL, *rand=NULL, *str=NULL;
if (!ncsopts->check_dhex_flag()&&!ncsopts->check_dlen_flag()&&!ncsopts->check_dstr_flag())
return NULL;
if (ncsopts->check_dhex_flag()) {
hex=hex_ahtoh(ncsopts->get_dhex_param().data(), &hexlen);
*reslen+=hexlen;
}
if (ncsopts->check_dlen_flag()) {
randlen=std::stoi(ncsopts->get_dlen_param());
rand=(u8*)random_str(randlen, DEFAULT_DICTIONARY);
*reslen+=randlen;
}
if (ncsopts->check_dstr_flag()) {
strlen_=strlen(ncsopts->get_dstr_param().c_str());
str=(u8*)ncsopts->get_dstr_param().c_str();
*reslen+=strlen_;
}
/* Создаем один буфер */
res=(u8*)calloc(1,*reslen);
if (!res)
return NULL;
/* Собираем их в один буфер */
if (hex) { memcpy(res+skip, hex, hexlen); skip+=hexlen; }
if (str) { memcpy(res+skip, str, strlen_); skip+=strlen_; }
if (rand) { memcpy(res+skip, rand, randlen); skip+=strlen_; }
return res;
}
/*
* Создает заголовок 802.3, и клеет к нему все что было
* получено до и иницилизует некоторые вещи в probe.
*/
void NESCAINIT::ni_ethprobe(NESCAPROBE *probe, NESCATARGET *target,
NESCADATA *ncsdata, NESCAMETHOD *ncsmethod)
{
mac_t dst={0},src={0};
u8 *res=NULL;
int type=0;
switch (ncsmethod->method) {
/* Для ARP нам не нужен получатель, мы ебашим это
* в broadcast. */
case M_ARP_PING:
type=ETH_TYPE_ARP;
mact_fill(&dst, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
break;
/* Если не ARP то получатель неизбежен, получаем его. */
default:
type=(((target->is_ip6host())?ETH_TYPE_IPV6
:ETH_TYPE_IPV4));
dst=ncsdata->dev.get_dstmac();
break;
}
src=ncsdata->dev.get_srcmac();
res=eth_build(src, dst, type, probe->probe,
probe->probelen, &probe->probelen);
if (probe->probe)
/* Воздаем очистку, поскольку, у нас новый пакет. */
free(probe->probe);
probe->probe=res;
probe->method=ncsmethod->method;
probe->filter.method=probe->method;
}
/*
* Создает IP заголовок 4 версии, и дополняет probe
* значениями.
*/
void NESCAINIT::ni_iprobe(NESCAPROBE *probe, NESCATARGET *target,
NESCADATA *ncsdata, NESCAMETHOD *ncsmethod)
{
u8 *res=NULL, *ipopts=NULL;
size_t ipoptslen=0;
std::string tmp,tok;
ip4_t src, dst;
u16 off=IP4_DF;
int ttl;
ip4t_pton(target->get_mainip().c_str(), &dst);
src=ncsdata->dev.get_srcip4();
ipopts=(ncsdata->opts.check_ipopt_flag())?
hex_ahtoh(ncsdata->opts.get_ipopt_param().data(),
&ipoptslen):NULL;
ttl=(ncsdata->opts.check_ttl_flag())?std::stoi(ncsdata->opts.get_ttl_param())
:random_num_u32(121, 255);
/* Пользователь решил что он умнее и укажет свой флаг,
* но это дойстойно. */
if (ncsdata->opts.check_off_flag()) {
off=0;
tmp=ncsdata->opts.get_off_param();
std::stringstream ss(tmp);
for (;std::getline(ss, tok, '/');) {
if (tok=="df"||tok=="DF")
off|=IP4_DF;
else if (tok=="mf"||tok=="MF")
off|=IP4_MF;
else if (tok=="rf"||tok=="RF"||
tok=="evil"||tok=="EVIL")
off|=IP4_RF;
}