-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathservice_scan.cc
2868 lines (2521 loc) · 104 KB
/
service_scan.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
/***************************************************************************
* service_scan.cc -- Routines used for service fingerprinting to determine *
* what application-level protocol is listening on a given port *
* (e.g. snmp, http, ftp, smtp, etc.) *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
*
* The Nmap Security Scanner is (C) 1996-2024 Nmap Software LLC ("The Nmap
* Project"). Nmap is also a registered trademark of the Nmap Project.
*
* This program is distributed under the terms of the Nmap Public Source
* License (NPSL). The exact license text applying to a particular Nmap
* release or source code control revision is contained in the LICENSE
* file distributed with that version of Nmap or source code control
* revision. More Nmap copyright/legal information is available from
* https://nmap.org/book/man-legal.html, and further information on the
* NPSL license itself can be found at https://nmap.org/npsl/ . This
* header summarizes some key points from the Nmap license, but is no
* substitute for the actual license text.
*
* Nmap is generally free for end users to download and use themselves,
* including commercial use. It is available from https://nmap.org.
*
* The Nmap license generally prohibits companies from using and
* redistributing Nmap in commercial products, but we sell a special Nmap
* OEM Edition with a more permissive license and special features for
* this purpose. See https://nmap.org/oem/
*
* If you have received a written Nmap license agreement or contract
* stating terms other than these (such as an Nmap OEM license), you may
* choose to use and redistribute Nmap under those terms instead.
*
* The official Nmap Windows builds include the Npcap software
* (https://npcap.com) for packet capture and transmission. It is under
* separate license terms which forbid redistribution without special
* permission. So the official Nmap Windows builds may not be redistributed
* without special permission (such as an Nmap OEM license).
*
* Source is provided to this software because we believe users have a
* right to know exactly what a program is going to do before they run it.
* This also allows you to audit the software for security holes.
*
* Source code also allows you to port Nmap to new platforms, fix bugs, and
* add new features. You are highly encouraged to submit your changes as a
* Github PR or by email to the dev@nmap.org mailing list for possible
* incorporation into the main distribution. Unless you specify otherwise, it
* is understood that you are offering us very broad rights to use your
* submissions as described in the Nmap Public Source License Contributor
* Agreement. This is important because we fund the project by selling licenses
* with various terms, and also because the inability to relicense code has
* caused devastating problems for other Free Software projects (such as KDE
* and NASM).
*
* The free version of Nmap 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. Warranties,
* indemnification and commercial support are all available through the
* Npcap OEM program--see https://nmap.org/oem/
*
***************************************************************************/
/* $Id$ */
#include "service_scan.h"
#include "timing.h"
#include "NmapOps.h"
#include "nsock.h"
#include "Target.h"
#include "utils.h"
#include "nmap_error.h"
#include "payload.h"
#include "protocols.h"
#include "scan_lists.h"
#include "charpool.h"
#include "nmap_tty.h"
#include <errno.h>
#if HAVE_OPENSSL
/* OpenSSL 1.0.0 needs _WINSOCKAPI_ to be defined, otherwise it loads
<windows.h> (through openssl/dtls1.h), which is incompatible with the
<winsock2.h> that we use. (It creates errors with the redefinition of struct
timeval, for example.) _WINSOCKAPI_ should be defined by our inclusion of
<winsock2.h>, but it appears to be undefined somewhere, possibly in
libpcap. */
#define _WINSOCKAPI_
#include <openssl/ssl.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifndef IPPROTO_SCTP
#include "libnetutil/netutil.h"
#endif
#include <algorithm>
#include <list>
extern NmapOps o;
#define SERVICE_FIELD_LEN 80
#define SERVICE_EXTRA_LEN 256
#define SERVICE_TYPE_LEN 32
// Details on a particular service (open port) we are trying to match
class ServiceNFO {
public:
ServiceNFO(AllProbes *AP);
~ServiceNFO();
// If a service response to a given probeName, this function adds
// the response the fingerprint for that service. The
// fingerprint can be printed when nothing matches the service. You
// can obtain the fingerprint (if any) via getServiceFingerprint();
void addToServiceFingerprint(const char *probeName, const u8 *resp,
int resplen);
// Get the service fingerprint. It is NULL if there is none, such
// as if there was a match before any other probes were finished (or
// if no probes gave back data). Note that this is plain
// NUL-terminated ASCII data, although the length is optionally
// available anyway. This function terminates the service fingerprint
// with a semi-colon
const char *getServiceFingerprint(int *flen);
// Note that the next 2 members are for convenience and are not destroyed w/the ServiceNFO
Target *target; // the port belongs to this target host
// if a match is found, it is placed here. Otherwise NULL
const char *probe_matched;
// If a match is found, any product/version/info/hostname/ostype/devicetype
// is placed in these 6 strings. Otherwise the string will be 0 length.
char product_matched[SERVICE_FIELD_LEN];
char version_matched[SERVICE_FIELD_LEN];
char extrainfo_matched[SERVICE_EXTRA_LEN];
char hostname_matched[SERVICE_FIELD_LEN];
char ostype_matched[SERVICE_TYPE_LEN];
char devicetype_matched[SERVICE_TYPE_LEN];
char cpe_a_matched[SERVICE_FIELD_LEN];
char cpe_h_matched[SERVICE_FIELD_LEN];
char cpe_o_matched[SERVICE_FIELD_LEN];
enum service_tunnel_type tunnel; /* SERVICE_TUNNEL_NONE, SERVICE_TUNNEL_SSL */
// This stores our SSL session id, which will help speed up subsequent
// SSL connections. It's overwritten each time. void* is used so we don't
// need to #ifdef HAVE_OPENSSL all over. We'll cast later as needed.
void *ssl_session;
// if a match was found (see above), this tells whether it was a "soft"
// or hard match. It is always false if no match has been found.
bool softMatchFound;
// most recent probe executed (or in progress). If there has been a match
// (probe_matched != NULL), this will be the corresponding ServiceProbe.
ServiceProbe *currentProbe();
// computes the next probe to test, and ALSO CHANGES currentProbe() to
// that! If newresp is true, the old response info will be lost and
// invalidated. Otherwise it remains as if it had been received by
// the current probe (useful after a NULL probe).
ServiceProbe *nextProbe(bool newresp);
// Resets the probes back to the first one. One case where this is useful is
// when SSL is detected -- we redo all probes through SSL. If freeFP, any
// service fingerprint is freed too.
void resetProbes(bool freefp);
// Number of milliseconds used so far to complete the present probe. Timeval
// can omitted, it is just there as an optimization in case you have it handy.
int probe_timemsused(const ServiceProbe *probe, const struct timeval *now = NULL);
// Number of milliseconds left to complete the present probe, or 0 if
// the probe is already expired. Timeval can omitted, it is just there
// as an optimization in case you have it handy.
int probe_timemsleft(const ServiceProbe *probe, const struct timeval *now = NULL);
enum serviceprobestate probe_state; // defined in portlist.h
nsock_iod niod; // The IO Descriptor being used in this probe (or NULL)
u16 portno; // in host byte order
u8 proto; // IPPROTO_TCP or IPPROTO_UDP
// The time that the current probe was executed (meaning TCP connection
// made or first UDP packet sent
struct timeval currentprobe_exec_time;
// Append newly-received data to the current response string (if any)
void appendtocurrentproberesponse(const u8 *respstr, int respstrlen);
// Get the full current response string. Note that this pointer is
// INVALIDATED if you call appendtocurrentproberesponse() or nextProbe()
u8 *getcurrentproberesponse(int *respstrlen);
AllProbes *AP;
// Is it possible this service is tcpwrapped? Not if a probe times out or
// gets a real response.
bool tcpwrap_possible;
private:
// Adds a character to servicefp. Takes care of word wrapping if
// necessary at the given (wrapat) column. Chars will only be
// written if there is enough space. Otherwise it exits.
void addServiceChar(char c, int wrapat);
// Like addServiceChar, but for a whole zero-terminated string
void addServiceString(const char *s, int wrapat);
std::vector<ServiceProbe *>::iterator current_probe;
u8 *currentresp;
int currentresplen;
char *servicefp;
int servicefplen;
int servicefpalloc;
};
// This holds the service information for a group of Targets being service scanned.
class ServiceGroup {
public:
ServiceGroup(std::vector<Target *> &Targets, AllProbes *AP);
~ServiceGroup();
std::list<ServiceNFO *> services_finished; // Services finished (discovered or not)
std::list<ServiceNFO *> services_in_progress; // Services currently being probed
std::list<ServiceNFO *> services_remaining; // Probes not started yet
unsigned int ideal_parallelism; // Max (and desired) number of probes out at once.
ScanProgressMeter *SPM;
int num_hosts_timedout; // # of hosts timed out during (or before) scan
};
#define SUBSTARGS_MAX_ARGS 5
#define SUBSTARGS_STRLEN 128
#define SUBSTARGS_ARGTYPE_NONE 0
#define SUBSTARGS_ARGTYPE_STRING 1
#define SUBSTARGS_ARGTYPE_INT 2
struct substargs {
int num_args; // Total number of arguments found
char str_args[SUBSTARGS_MAX_ARGS][SUBSTARGS_STRLEN];
// This is the length of each string arg, since they can contain zeros.
// The str_args[] are zero-terminated for convenience in the cases where
// you know they won't contain zero.
int str_args_len[SUBSTARGS_MAX_ARGS];
int int_args[SUBSTARGS_MAX_ARGS];
// The type of each argument -- see #define's above.
int arg_types[SUBSTARGS_MAX_ARGS];
};
/******************** PROTOTYPES *******************/
static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *mydata);
static void servicescan_write_handler(nsock_pool nsp, nsock_event nse, void *mydata);
static void servicescan_connect_handler(nsock_pool nsp, nsock_event nse, void *mydata);
static void end_svcprobe(enum serviceprobestate probe_state, ServiceGroup *SG, ServiceNFO *svc, nsock_iod nsi);
static int scanThroughTunnel(ServiceNFO *svc);
static bool processMatch(const struct MatchDetails *MD, ServiceNFO *svc,
const char *probeName, const char *fallbackName);
ServiceProbeMatch::ServiceProbeMatch() {
deflineno = -1;
servicename = NULL;
matchstr = NULL;
product_template = version_template = info_template = NULL;
hostname_template = ostype_template = devicetype_template = NULL;
regex_compiled = NULL;
match_data = NULL;
isInitialized = false;
matchops_ignorecase = false;
matchops_dotall = false;
isSoft = false;
}
ServiceProbeMatch::~ServiceProbeMatch() {
std::vector<char *>::iterator it;
if (!isInitialized) return;
if (matchstr) free(matchstr);
if (product_template) free(product_template);
if (version_template) free(version_template);
if (info_template) free(info_template);
if (hostname_template) free(hostname_template);
if (ostype_template) free(ostype_template);
if (devicetype_template) free(devicetype_template);
for (it = cpe_templates.begin(); it != cpe_templates.end(); it++)
free(*it);
if (regex_compiled)
{
pcre2_code_free(regex_compiled);
regex_compiled=NULL;
}
if (match_data)
{
pcre2_match_data_free(match_data);
match_data=NULL;
}
if (match_context)
{
pcre2_match_context_free(match_context);
match_context=NULL;
}
isInitialized = false;
}
/* Read the next tmplt from *matchtext and update *matchtext. Return true iff
a template was read. modestr and flags must each point to a char[4]. For example, after
matchtext = "p/123/ d/456/";
next_template(&matchtext, modestr, flags, &tmplt);
then
matchtext == " d/456/"
modestr == "p"
tmplt == "123"
flags == ""
*tmplt must be freed if the return value is true.
Special handling for cpe:/txt/ => modestr == "cpe" tmplt == "cpe:/txt" */
static bool next_template(const char **matchtext, char modestr[4], char **tmplt,
char flags[4], int lineno) {
const char *p, *q;
char delimchar;
int i;
p = *matchtext;
while(isspace((int) (unsigned char) *p))
p++;
if (*p == '\0')
return false;
for (i=0; i < 3 && isalpha(p[i]); i++)
modestr[i] = p[i];
q = p + i;
modestr[i] = '\0';
if (*q == ':' && 0 == strcmp(modestr, "cpe")) {
q++;
if (*q != '/')
fatal("%s: parse error (cpe delimiter not '/') on line %d of nmap-service-probes", __func__, lineno);
// p == "cpe:/..."
}
else {
if (*q == '\0' || isspace(*q))
fatal("%s: parse error (bare word) on line %d of nmap-service-probes", __func__, lineno);
// p == start of template
p = q + 1;
}
delimchar = *q;
q = strchr(q + 1, delimchar);
if (q == NULL)
fatal("%s: parse error (missing end delimiter) on line %d of nmap-service-probes", __func__, lineno);
*tmplt = mkstr(p, q);
// *q == delimchar;
p = q + 1;
for (i=0; i < 3 && isalpha(p[i]); i++)
flags[i] = p[i];
flags[i] = '\0';
q = p + i;
if (!isspace(*q))
fatal("%s: parse error (flags too long) on line %d of nmap-service-probes", __func__, lineno);
/* Update pointer for caller. */
*matchtext = q;
return true;
}
// match text from the nmap-service-probes file. This must be called
// before you try and do anything with this match. This function
// should be passed the whole line starting with "match" or
// "softmatch" in nmap-service-probes. The line number that the text
// is provided so that it can be reported in error messages. This
// function will abort the program if there is a syntax problem.
void ServiceProbeMatch::InitMatch(const char *matchtext, int lineno) {
const char *p;
char *tmptemplate;
char modestr[4];
char flags[4];
int pcre2_compile_ops = 0;
int pcre2_errcode;
PCRE2_SIZE pcre2_erroffset;
char **curr_tmp = NULL;
if (isInitialized) fatal("Sorry ... %s does not yet support reinitializion", __func__);
if (!matchtext || !*matchtext)
fatal("%s: no matchtext passed in (line %d of nmap-service-probes)", __func__, lineno);
isInitialized = true;
deflineno = lineno;
while(isspace((int) (unsigned char) *matchtext)) matchtext++;
// first we find whether this is a "soft" or normal match
if (strncmp(matchtext, "softmatch ", 10) == 0) {
isSoft = true;
matchtext += 10;
} else if (strncmp(matchtext, "match ", 6) == 0) {
isSoft = false;
matchtext += 6;
} else
fatal("%s: parse error on line %d of nmap-service-probes - must begin with \"match\" or \"softmatch\"", __func__, lineno);
// next comes the service name
p = strchr(matchtext, ' ');
if (!p) fatal("%s: parse error on line %d of nmap-service-probes: could not find service name", __func__, lineno);
servicename = cp_strndup(matchtext, p - matchtext);
// The next part is a perl style regular expression specifier, like:
// m/^220 .*smtp/i Where 'm' means a normal regular expressions is
// used, the char after m can be anything (within reason, slash in
// this case) and tells us what delineates the end of the regex.
// After the delineating character are any single-character
// options. ('i' means "case insensitive", 's' means that . matches
// newlines (both are just as in perl)
matchtext = p;
if (!next_template(&matchtext, modestr, &matchstr, flags, lineno))
fatal("%s: parse error on line %d of nmap-service-probes", __func__, lineno);
if (strcmp(modestr, "m") != 0)
fatal("%s: parse error on line %d of nmap-service-probes: matchtext must begin with 'm'", __func__, lineno);
// any options?
for (p = flags; *p != '\0'; p++) {
if (*p == 'i')
matchops_ignorecase = true;
else if (*p == 's')
matchops_dotall = true;
else
fatal("%s: illegal regexp option on line %d of nmap-service-probes", __func__, lineno);
}
// Next we compile and study the regular expression to match
if (matchops_ignorecase)
pcre2_compile_ops |= PCRE2_CASELESS;
if (matchops_dotall)
pcre2_compile_ops |= PCRE2_DOTALL;
regex_compiled = pcre2_compile((PCRE2_SPTR)matchstr,PCRE2_ZERO_TERMINATED, pcre2_compile_ops, &pcre2_errcode,
&pcre2_erroffset, NULL);
if (regex_compiled == NULL)
fatal("%s: illegal regexp on line %d of nmap-service-probes (at regexp offset %ld): %d\n", __func__, lineno, pcre2_erroffset, pcre2_errcode);
// creates a new match data block for holding the result of a match
match_data = pcre2_match_data_create_from_pattern(
regex_compiled,NULL
);
if (!match_data) {
fatal("%s: failed to allocate match_data\n", __func__);
}
match_context = pcre2_match_context_create(NULL);
if (!match_context) {
fatal("%s: failed to allocate match_context\n", __func__);
}
// Set some limits to avoid evil match cases.
// These are flexible; if they cause problems, increase them.
pcre2_set_match_limit(match_context, 100000);
#ifdef pcre2_set_depth_limit
// Changed name in PCRE2 10.30. PCRE2 uses macro definitions for function
// names, so we don't have to add this to configure.ac.
pcre2_set_depth_limit(match_context, 10000);
#else
pcre2_set_recursion_limit(match_context, 10000);
#endif
/* OK! Now we look for any templates of the form ?/.../
* where ? is either p, v, i, h, o, or d. / is any
* delimiter character and ... is a template */
while (next_template(&matchtext, modestr, &tmptemplate, flags, lineno)) {
switch (modestr[0] + (modestr[1] << 8)) {
case 'p':
curr_tmp = &product_template;
break;
case 'v':
curr_tmp = &version_template;
break;
case 'i':
curr_tmp = &info_template;
break;
case 'h':
curr_tmp = &hostname_template;
break;
case 'o':
curr_tmp = &ostype_template;
break;
case 'd':
curr_tmp = &devicetype_template;
break;
case 'c' + ('p' << 8):
if (modestr[2] == 'e' && modestr[3] == '\0') {
cpe_templates.push_back(NULL);
curr_tmp = &cpe_templates.back();
break;
}
default:
fatal("%s: Unknown template specifier '%s' on line %d of nmap-service-probes", __func__, modestr, lineno);
break;
}
/* This one already defined? */
if (*curr_tmp) {
if (o.debugging) {
error("WARNING: Template \"%s/%s/\" replaced with \"%s/%s/\" on line %d of nmap-service-probes",
modestr, *curr_tmp, modestr, tmptemplate, lineno);
}
free(*curr_tmp);
}
*curr_tmp = tmptemplate;
}
isInitialized = 1;
}
// If the buf (of length buflen) match the regex in this
// ServiceProbeMatch, returns the details of the match (service
// name, version number if applicable, and whether this is a "soft"
// match. If the buf doesn't match, the serviceName field in the
// structure will be NULL. The MatchDetails structure returned is
// only valid until the next time this function is called. The only
// exception is that the serviceName field can be saved throughout
// program execution. If no version matched, that field will be
// NULL.
const struct MatchDetails *ServiceProbeMatch::testMatch(const u8 *buf, int buflen) {
int rc;
static char product[SERVICE_FIELD_LEN];
static char version[SERVICE_FIELD_LEN];
static char info[SERVICE_EXTRA_LEN]; /* We will truncate with ... later */
static char hostname[SERVICE_FIELD_LEN];
static char ostype[SERVICE_TYPE_LEN];
static char devicetype[SERVICE_TYPE_LEN];
static char cpe_a[SERVICE_FIELD_LEN], cpe_h[SERVICE_FIELD_LEN], cpe_o[SERVICE_FIELD_LEN];
char *bufc = (char *) buf;
assert(isInitialized);
// Clear out the output struct
memset(&MD_return, 0, sizeof(MD_return));
MD_return.isSoft = isSoft;
rc = pcre2_match(regex_compiled, (PCRE2_SPTR8)bufc, buflen, 0, 0, match_data, match_context);
if (rc < 0) {
// Probably just didn't match. However, PCRE2 errors may happen with bad
// patterns. We want to know, but don't abandon the whole scan.
if (rc != PCRE2_ERROR_NOMATCH) {
if (o.verbose || o.debugging) {
error("Warning: PCRE2 error %d when probing for service %s with the regex '%s'", rc, servicename, matchstr);
}
if (o.debugging) {
pcre2_get_error_message(rc, (unsigned char *)info, SERVICE_EXTRA_LEN);
error("PCRE2 error message: %s", info);
if (o.debugging > 1) {
error("Service data: \n%s", hexdump(buf, buflen));
}
}
}
} else {
// Yeah! Match apparently succeeded.
// Now lets get the version number if available
getVersionStr(buf, buflen, product, sizeof(product), version, sizeof(version), info, sizeof(info),
hostname, sizeof(hostname), ostype, sizeof(ostype), devicetype, sizeof(devicetype),
cpe_a, sizeof(cpe_a), cpe_h, sizeof(cpe_h), cpe_o, sizeof(cpe_o));
if (*product) MD_return.product = product;
if (*version) MD_return.version = version;
if (*info) MD_return.info = info;
if (*hostname) MD_return.hostname = hostname;
if (*ostype) MD_return.ostype = ostype;
if (*devicetype) MD_return.devicetype = devicetype;
if (*cpe_a) MD_return.cpe_a = cpe_a;
if (*cpe_h) MD_return.cpe_h = cpe_h;
if (*cpe_o) MD_return.cpe_o = cpe_o;
MD_return.serviceName = servicename;
MD_return.lineno = getLineNo();
}
return &MD_return;
}
// This simple function parses arguments out of a string. The string
// starts with the first argument. Each argument can be a string or
// an integer. Strings must be enclosed in double quotes (""). Most
// standard C-style escapes are supported. If this is successful, the
// number of args found is returned, args is filled appropriately, and
// args_end (if non-null) is set to the character after the closing
// ')'. Otherwise we return -1 and the values of args and args_end
// are undefined.
static int getsubstcommandargs(struct substargs *args, char *args_start,
char **args_end) {
char *p;
unsigned int len;
if (!args || !args_start) return -1;
memset(args, 0, sizeof(*args));
while(*args_start && *args_start != ')') {
// Find the next argument.
while(isspace((int) (unsigned char) *args_start)) args_start++;
if (*args_start == ')')
break;
else if (*args_start == '"') {
// OK - it is a string
// Do we have space for another arg?
if (args->num_args == SUBSTARGS_MAX_ARGS)
return -1;
do {
args_start++;
if (*args_start == '"' && (*(args_start - 1) != '\\' || *(args_start - 2) == '\\'))
break;
len = args->str_args_len[args->num_args];
if (len >= SUBSTARGS_STRLEN - 1)
return -1;
args->str_args[args->num_args][len] = *args_start;
args->str_args_len[args->num_args]++;
} while(*args_start);
len = args->str_args_len[args->num_args];
args->str_args[args->num_args][len] = '\0';
// Now handle escaped characters and such
if (!cstring_unescape(args->str_args[args->num_args], &len))
return -1;
args->str_args_len[args->num_args] = len;
args->arg_types[args->num_args] = SUBSTARGS_ARGTYPE_STRING;
args->num_args++;
args_start++;
args_start = strpbrk(args_start, ",)");
if (!args_start) return -1;
if (*args_start == ',') args_start++;
} else {
// Must be an integer argument
args->int_args[args->num_args] = (int) strtol(args_start, &p, 0);
if (p <= args_start) return -1;
args_start = p;
args->arg_types[args->num_args] = SUBSTARGS_ARGTYPE_INT;
args->num_args++;
args_start = strpbrk(args_start, ",)");
if (!args_start) return -1;
if (*args_start == ',') args_start++;
}
}
if (*args_start == ')') args_start++;
if (args_end) *args_end = args_start;
return args->num_args;
}
/* These three functions manage a growing string buffer, appended to at the end.
Begin with strbuf_init, follow with any number of strbuf_append, and end with
strbuf_finish. */
static void strbuf_init(char **buf, size_t *n, size_t *len) {
*buf = NULL;
*n = 0;
*len = 0;
}
static void strbuf_append(char **buf, size_t *n, size_t *len,
const char *from, size_t fromlen) {
/* Double the size of the buffer if necessary. */
if (*len == 0 || *len + fromlen > *n) {
*n = (*len + fromlen) * 2;
*buf = (char *) safe_realloc(*buf, *n + 1);
}
memcpy(*buf + *len, from, fromlen);
*len += fromlen;
}
/* Trim to length. (Also does initial allocation when *buf is empty.) */
static void strbuf_finish(char **buf, size_t *n, size_t *len) {
*buf = (char *) safe_realloc(*buf, *len + 1);
(*buf)[*len] = '\0';
}
/* Transform a string so that it is safe to insert into the middle of a CPE URL. */
static char *transform_cpe(const char *s) {
char *result;
size_t n, len, repllen;
const char *p;
strbuf_init(&result, &n, &len);
for (p = s; *p != '\0'; p++) {
const char *repl;
char buf[32];
/* Section 5.4 of the CPE specification lists these characters to be
escaped. */
if (strchr(":/?#[]@!$&'()*+,;=%<>\"", *p) != NULL) {
Snprintf(buf, sizeof(buf), "%%%02X", *p);
repl = buf;
/* Replacing spaces with underscores is also a convention. */
} else if (isspace(*p)) {
repl = "_";
/* Otherwise just make lower-case. */
} else {
buf[0] = tolower(*p);
buf[1] = '\0';
repl = buf;
}
repllen = strlen(repl);
strbuf_append(&result, &n, &len, repl, repllen);
}
strbuf_finish(&result, &n, &len);
return result;
}
// This function does the substitution of a placeholder like $2 or $P(4). It
// returns a newly allocated string, or NULL if it fails. tmplvar is a template
// variable, such as "$P(2)". We set *tmplvarend to the character after the
// variable. subject, subjectlen, and match_data mean the same as in
// dotmplsubst().
static char *substvar(char *tmplvar, char **tmplvarend,
const u8 *subject, size_t subjectlen, pcre2_match_data *match_data
) {
char substcommand[16];
char *p = NULL;
char *p_end;
u8 subnum = 0;
PCRE2_SIZE offstart, offend;
int rc;
struct substargs command_args;
char *result;
size_t n, len;
// skip the '$'
if (*tmplvar != '$') return NULL;
tmplvar++;
if (!isdigit((int) (unsigned char) *tmplvar)) {
int commandlen;
/* This is a command like $P(1). */
p = strchr(tmplvar, '(');
if (!p) return NULL;
commandlen = p - tmplvar;
if (!commandlen || commandlen >= (int) sizeof(substcommand))
return NULL;
memcpy(substcommand, tmplvar, commandlen);
substcommand[commandlen] = '\0';
tmplvar = p+1;
// Now we grab the arguments.
rc = getsubstcommandargs(&command_args, tmplvar, &p_end);
if (rc <= 0) return NULL;
tmplvar = p_end;
} else {
/* This is a placeholder like $2. */
substcommand[0] = '\0';
subnum = *tmplvar - '0';
tmplvar++;
}
if (tmplvarend) *tmplvarend = tmplvar;
u32 nummatches = pcre2_get_ovector_count(match_data);
PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
strbuf_init(&result, &n, &len);
if (!*substcommand) {
/* Handler for a placeholder like $2. */
if (subnum > 9 || subnum <= 0) return NULL;
if (subnum >= nummatches) return NULL;
offstart = ovector[subnum * 2];
if (offstart == PCRE2_UNSET) return NULL;
offend = ovector[subnum * 2 + 1];
assert(offstart <= subjectlen);
assert(offend != PCRE2_UNSET && offend <= subjectlen);
// A plain-jane copy
strbuf_append(&result, &n, &len, (const char *) subject + offstart, offend - offstart);
} else if (strcmp(substcommand, "P") == 0) {
if (command_args.num_args != 1 ||
command_args.arg_types[0] != SUBSTARGS_ARGTYPE_INT) {
return NULL;
}
subnum = command_args.int_args[0];
if (subnum > 9 || subnum <= 0) return NULL;
if (subnum >= nummatches) return NULL;
offstart = ovector[subnum * 2];
if (offstart == PCRE2_UNSET) return NULL;
offend = ovector[subnum * 2 + 1];
assert(offstart <= subjectlen);
assert(offend != PCRE2_UNSET && offend <= subjectlen);
// This filter only includes printable characters. It is particularly
// useful for collapsing unicode text that looks like
// "W\0O\0R\0K\0G\0R\0O\0U\0P\0"
for(PCRE2_SIZE i=offstart; i < offend; i++) {
if (isprint((int) subject[i]))
strbuf_append(&result, &n, &len, (const char *) subject + i, 1);
}
} else if (strcmp(substcommand, "SUBST") == 0) {
char *findstr, *replstr;
int findstrlen, replstrlen;
if (command_args.num_args != 3 ||
command_args.arg_types[0] != SUBSTARGS_ARGTYPE_INT ||
command_args.arg_types[1] != SUBSTARGS_ARGTYPE_STRING ||
command_args.arg_types[2] != SUBSTARGS_ARGTYPE_STRING) {
return NULL;
}
subnum = command_args.int_args[0];
if (subnum > 9 || subnum <= 0) return NULL;
if (subnum >= nummatches) return NULL;
offstart = ovector[subnum * 2];
if (offstart == PCRE2_UNSET) return NULL;
offend = ovector[subnum * 2 + 1];
assert(offstart <= subjectlen);
assert(offend != PCRE2_UNSET && offend <= subjectlen);
findstr = command_args.str_args[1];
findstrlen = command_args.str_args_len[1];
replstr = command_args.str_args[2];
replstrlen = command_args.str_args_len[2];
for(PCRE2_SIZE i=offstart; i < offend; ) {
if (memcmp(subject + i, findstr, findstrlen) != 0) {
strbuf_append(&result, &n, &len, (const char *) subject + i, 1); // no match
i++;
} else {
// The find string was found, copy it to newstring
strbuf_append(&result, &n, &len, replstr, replstrlen);
i += findstrlen;
}
}
} else if (strcmp(substcommand, "I") == 0 ){
// Parse an unsigned int
long long unsigned val = 0;
bool bigendian = true;
char buf[24]; //0xffffffffffffffff = 18446744073709551615, 20 chars
int buflen;
if (command_args.num_args != 2 ||
command_args.arg_types[0] != SUBSTARGS_ARGTYPE_INT ||
command_args.arg_types[1] != SUBSTARGS_ARGTYPE_STRING ||
command_args.str_args_len[1] != 1) {
return NULL;
}
subnum = command_args.int_args[0];
if (subnum > 9 || subnum <= 0) return NULL;
if (subnum >= nummatches) return NULL;
offstart = ovector[subnum * 2];
if (offstart == PCRE2_UNSET) return NULL;
offend = ovector[subnum * 2 + 1];
assert(offend != PCRE2_UNSET && offstart <= subjectlen);
// overflow
if (offend - offstart > 8) {
return NULL;
}
switch (command_args.str_args[1][0]) {
case '>':
bigendian = true;
break;
case '<':
bigendian = false;
break;
default:
return NULL;
break;
}
if (bigendian) {
for(PCRE2_SIZE i=offstart; i < offend; i++) {
val = (val<<8) + subject[i];
}
} else {
for(PCRE2_SIZE i=offend - 1; i > offstart - 1; i--) {
val = (val<<8) + subject[i];
}
}
buflen = Snprintf(buf, sizeof(buf), "%llu", val);
if (buflen < 0 || buflen >= (int) sizeof(buf)) {
return NULL;
}
strbuf_append(&result, &n, &len, buf, buflen);
} else return NULL; // Unknown command
strbuf_finish(&result, &n, &len);
return result;
}
// This function takes a template string (tmpl) which can have
// placeholders in it such as $1 for substring matches in a regexp
// that was run against subject, and subjectlen, with the
// matches in match_data. The NUL-terminated newly composted string is
// placed into 'newstr', as long as it doesn't exceed 'newstrlen'
// bytes. Trailing whitespace and commas are removed. Returns zero for success
//
// The transform argument is a function pointer. If not NULL, the given
// function is applied to all substitutions before they are inserted
// into the result string.
static int dotmplsubst(const u8 *subject, size_t subjectlen,
pcre2_match_data *match_data, char *tmpl, char *newstr,
int newstrlen,
char *(*transform)(const char *) = NULL) {
int newlen;
char *srcstart=tmpl, *srcend;
char *dst = newstr;
char *newstrend = newstr + newstrlen; // Right after the final char
char *subst;
if (!newstr || !tmpl) return -1;
if (newstrlen < 3) return -1; // Have a nice day!
while(*srcstart) {
// First do any literal text before '$'
srcend = strchr(srcstart, '$');
if (!srcend) {
// Only literal text remain!
while(*srcstart) {
if (dst >= newstrend - 1)
return -1;
*dst++ = *srcstart++;
}
*dst = '\0';
while (--dst >= newstr) {
if (isspace((int) (unsigned char) *dst) || *dst == ',')
*dst = '\0';
else break;
}
return 0;
} else {
// Copy the literal text up to the '$', then do the substitution
newlen = srcend - srcstart;
if (newlen > 0) {
if (newstrend - dst <= newlen - 1)
return -1;
memcpy(dst, srcstart, newlen);
dst += newlen;
}
srcstart = srcend;
subst = substvar(srcstart, &srcend, subject, subjectlen, match_data);
if (subst == NULL)
return -1;
/* Apply transformation if requested. */
if (transform != NULL) {
char *tmp = subst;
subst = transform(subst);
free(tmp);
if (subst == NULL)
return -1;
}
newlen = strlen(subst);
if (dst + newlen >= newstrend - 1) {
free(subst);
return -1;
}
memcpy(dst, subst, newlen);
free(subst);
dst += newlen;
srcstart = srcend;
}
}
if (dst >= newstrend - 1)
return -1;
*dst = '\0';
while (--dst >= newstr) {
if (isspace((int) (unsigned char) *dst) || *dst == ',')
*dst = '\0';
else break;
}
return 0;
}
// Use the version templates and the match data included here
// to put the version info into the given strings, (as long as the sizes
// are sufficient). Returns zero for success. If no template is available
// for a string, that string will have zero length after the function
// call (assuming the corresponding length passed in is at least 1)
int ServiceProbeMatch::getVersionStr(const u8 *subject, size_t subjectlen,
char *product, size_t productlen,
char *version, size_t versionlen, char *info, size_t infolen,
char *hostname, size_t hostnamelen, char *ostype, size_t ostypelen,
char *devicetype, size_t devicetypelen,
char *cpe_a, size_t cpe_alen,
char *cpe_h, size_t cpe_hlen,
char *cpe_o, size_t cpe_olen) const {
int rc;
assert(productlen >= 0 && versionlen >= 0 && infolen >= 0 &&
hostnamelen >= 0 && ostypelen >= 0 && devicetypelen >= 0);
if (productlen > 0) *product = '\0';
if (versionlen > 0) *version = '\0';
if (infolen > 0) *info = '\0';
if (hostnamelen > 0) *hostname = '\0';
if (ostypelen > 0) *ostype = '\0';
if (devicetypelen > 0) *devicetype = '\0';
if (cpe_alen > 0) *cpe_a = '\0';
if (cpe_hlen > 0) *cpe_h = '\0';
if (cpe_olen > 0) *cpe_o = '\0';
int retval = 0;
// Now lets get this started! We begin with the product name
if (product_template) {
rc = dotmplsubst(subject, subjectlen, match_data, product_template, product, productlen);
if (rc != 0) {
error("Warning: Servicescan failed to fill product_template (subjectlen: %lu, productlen: %lu). Capture exceeds length? Match string was line %d: p/%s/%s/%s", subjectlen, productlen, deflineno,
(product_template)? product_template : "",
(version_template)? version_template : "",
(info_template)? info_template : "");
if (productlen > 0) *product = '\0';
retval = -1;
}
}
if (version_template) {
rc = dotmplsubst(subject, subjectlen, match_data, version_template, version, versionlen);
if (rc != 0) {