-
Notifications
You must be signed in to change notification settings - Fork 237
/
ncrack.cc
2686 lines (2311 loc) · 90.8 KB
/
ncrack.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
/***************************************************************************
* ncrack.cc -- ncrack's core engine along with all nsock callback *
* handlers reside in here. Simple options' (not host or service-options *
* specification handling) parsing also happens in main() here. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2019 Insecure.Com LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* This program is free software; you may redistribute and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE *
* CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your *
* right to use, modify, and redistribute this software under certain *
* conditions. If you wish to embed Nmap technology into proprietary *
* software, we sell alternative licenses (contact [email protected]). *
* Dozens of software vendors already license Nmap technology such as *
* host discovery, port scanning, OS detection, version detection, and *
* the Nmap Scripting Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, the Nmap Project grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* The Nmap Project has permission to redistribute Npcap, a packet *
* capturing driver and library for the Microsoft Windows platform. *
* Npcap is a separate work with it's own license rather than this Nmap *
* license. Since the Npcap license does not permit redistribution *
* without special permission, our Nmap Windows binary packages which *
* contain Npcap may not be redistributed without special permission. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact [email protected] with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, we are happy to help. As mentioned above, we also *
* offer an alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing support and updates. They also fund the continued *
* development of Nmap. Please email [email protected] for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* 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 send your changes *
* to the [email protected] mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify *
* otherwise) that you are offering the Nmap Project the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because *
* the inability to relicense code has caused devastating problems for *
* other Free Software projects (such as KDE and NASM). We also *
* occasionally relicense the code to third parties as discussed above. *
* If you wish to specify special license conditions of your *
* contributions, just say so when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
#include "ncrack.h"
#include "NcrackOps.h"
#include "utils.h"
#include "services.h"
#include "targets.h"
#include "TargetGroup.h"
#include "ServiceGroup.h"
#include "nsock.h"
#include "global_structures.h"
#include "NcrackOutputTable.h"
#include "modules.h"
#include "ncrack_error.h"
#include "output.h"
#include "ncrack_tty.h"
#include "ncrack_input.h"
#include "ncrack_resume.h"
#include "xml.h"
#include <time.h>
#include <vector>
#if HAVE_SIGNAL
#include <signal.h>
#endif
#if HAVE_OPENSSL
#include <openssl/ssl.h>
#endif
#ifdef WIN32
#include "winfix.h"
#endif
#define DEFAULT_CONNECT_TIMEOUT 5000
/* includes connect() + ssl negotiation */
#define DEFAULT_CONNECT_SSL_TIMEOUT 8000
#define DEFAULT_USERNAME_FILE "default.usr"
#define DEFAULT_PASSWORD_FILE "default.pwd"
/* (in milliseconds) every such interval we poll for interactive user input */
#define KEYPRESSED_INTERVAL 500
/* (in milliseconds) every such interval check for pending signals */
#define SIGNAL_CHECK_INTERVAL 1000
#define SERVICE_TIMEDOUT "Service timed-out as specified by user option."
extern NcrackOps o;
using namespace std;
/* global lookup table for available services */
vector <global_service> ServicesTable;
/* global login and pass array */
vector <char *> UserArray;
vector <char *> PassArray;
struct tm local_time;
/* schedule additional connections */
static void ncrack_probes(nsock_pool nsp, ServiceGroup *SG);
/* ncrack initialization */
static int ncrack(ServiceGroup *SG);
/* Poll for interactive user input every time this timer is called. */
static void status_timer_handler(nsock_pool nsp, nsock_event nse,
void *mydata);
static void signal_timer_handler(nsock_pool nsp, nsock_event nse,
void *mydata);
/* module name demultiplexor */
static void call_module(nsock_pool nsp, Connection* con);
static void parse_login_list(char *const arg, int mode);
static void load_login_file(const char *filename, int mode);
enum mode { USER, PASS };
static void print_usage(void);
static void lookup_init(const char *const filename);
static int file_readable(const char *pathname);
static int ncrack_fetchfile(char *filename_returned, int bufferlen,
const char *file, int useroption = 0);
static char *grab_next_host_spec(FILE *inputfd, int argc, char **argv);
static void startTimeOutClocks(ServiceGroup *SG);
static void sigcatch(int signo);
static void sigcheck(ServiceGroup *SG);
static int ncrack_main(int argc, char **argv);
static void
print_usage(void)
{
log_write(LOG_STDOUT, "%s %s ( %s )\n"
"Usage: ncrack [Options] {target and service specification}\n"
"TARGET SPECIFICATION:\n"
" Can pass hostnames, IP addresses, networks, etc.\n"
" Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; "
"10.0.0-255.1-254\n"
" -iX <inputfilename>: Input from Nmap's -oX XML output format\n"
" -iN <inputfilename>: Input from Nmap's -oN Normal output format\n"
" -iL <inputfilename>: Input from list of hosts/networks\n"
" --exclude <host1[,host2][,host3],...>: Exclude hosts/networks\n"
" --excludefile <exclude_file>: Exclude list from file\n"
"SERVICE SPECIFICATION:\n"
" Can pass target specific services in <service>://target (standard) "
"notation or\n"
" using -p which will be applied to all hosts in non-standard "
"notation.\n"
" Service arguments can be specified to be host-specific, type of "
"service-specific\n"
" (-m) or global (-g). Ex: ssh://10.0.0.10,at=10,cl=30 -m ssh:at=50 "
"-g cd=3000\n"
" Ex2: ncrack -p ssh,ftp:3500,25 10.0.0.10 scanme.nmap.org "
"google.com:80,ssl\n"
" -p <service-list>: services will be applied to all non-standard "
"notation hosts\n"
" -m <service>:<options>: options will be applied to all services "
"of this type\n"
" -g <options>: options will be applied to every service globally\n"
" Misc options:\n"
" ssl: enable SSL over this service\n"
" path <name>: used in modules like HTTP ('=' needs escaping if "
"used)\n"
" db <name>: used in modules like MongoDB to specify the database\n"
" domain <name>: used in modules like WinRM to specify the domain\n"
"TIMING AND PERFORMANCE:\n"
" Options which take <time> are in seconds, unless you append 'ms'\n"
" (miliseconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m)."
"\n"
" Service-specific options:\n"
" cl (min connection limit): minimum number of concurrent parallel "
"connections\n"
" CL (max connection limit): maximum number of concurrent parallel "
"connections\n"
" at (authentication tries): authentication attempts per connection\n"
" cd (connection delay): delay <time> between each connection "
"initiation\n"
" cr (connection retries): caps number of service connection "
"attempts\n"
" to (time-out): maximum cracking <time> for service, regardless "
"of success so far\n"
" -T<0-5>: Set timing template (higher is faster)\n"
" --connection-limit <number>: threshold for total concurrent "
"connections\n"
" --stealthy-linear: try credentials using only one connection against "
"each specified host \n until you hit the same host again. "
"Overrides all other timing options.\n"
"AUTHENTICATION:\n"
" -U <filename>: username file\n"
" -P <filename>: password file\n"
" --user <username_list>: comma-separated username list\n"
" --pass <password_list>: comma-separated password list\n"
" --passwords-first: Iterate password list for each username. "
"Default is opposite.\n"
" --pairwise: Choose usernames and passwords in pairs.\n"
"OUTPUT:\n"
" -oN/-oX <file>: Output scan in normal and XML format, respectively, "
"to the given filename.\n"
" -oA <basename>: Output in the two major formats at once\n"
" -v: Increase verbosity level (use twice or more for greater effect)\n"
" -d[level]: Set or increase debugging level (Up to 10 is meaningful)\n"
" --nsock-trace <level>: Set nsock trace level (Valid range: 0 - 10)\n"
" --log-errors: Log errors/warnings to the normal-format output file\n"
" --append-output: Append to rather than clobber specified output "
"files\n"
"MISC:\n"
" --resume <file>: Continue previously saved session\n"
" --save <file>: Save restoration file with specific filename\n"
" -f: quit cracking service after one found credential\n"
" -6: Enable IPv6 cracking\n"
" -sL or --list: only list hosts and services\n"
" --datadir <dirname>: Specify custom Ncrack data file location\n"
" --proxy <type://proxy:port>: Make connections via socks4, 4a, http.\n"
" -V: Print version number\n"
" -h: Print this help summary page.\n"
"MODULES:\n"
" SSH, RDP, FTP, Telnet, HTTP(S), Wordpress, POP3(S), IMAP, CVS, SMB, VNC, SIP, Redis, "
"PostgreSQL, MQTT, MySQL, MSSQL, MongoDB, Cassandra, WinRM, OWA, DICOM\n"
"EXAMPLES:\n"
" ncrack -v --user root localhost:22\n"
" ncrack -v -T5 https://192.168.0.1\n"
" ncrack -v -iX ~/nmap.xml -g CL=5,to=1h\n"
"SEE THE MAN PAGE (http://nmap.org/ncrack/man.html) FOR MORE OPTIONS "
"AND EXAMPLES\n",
NCRACK_NAME, NCRACK_VERSION, NCRACK_URL);
exit(EXIT_FAILURE);
}
static void
lookup_init(const char *const filename)
{
char line[1024];
char servicename[128], proto[16];
u16 portno;
FILE *fp;
vector <global_service>::iterator vi;
global_service temp;
memset(&temp, 0, sizeof(temp));
temp.timing.min_connection_limit = -1;
temp.timing.max_connection_limit = -1;
temp.timing.auth_tries = -1;
temp.timing.connection_delay = -1;
temp.timing.connection_retries = -1;
temp.timing.timeout = -1;
fp = fopen(filename, "r");
if (!fp)
fatal("%s: failed to open file %s for reading!", __func__, filename);
while (fgets(line, sizeof(line), fp)) {
if (*line == '\n' || *line == '#')
continue;
temp.misc.ssl = false;
temp.misc.db = NULL;
temp.misc.domain = NULL;
if (sscanf(line, "%127s %hu/%15s", servicename, &portno, proto) != 3)
fatal("invalid ncrack-services file: %s", filename);
temp.lookup.portno = portno;
temp.lookup.proto = str2proto(proto);
temp.lookup.name = strdup(servicename);
/*
* When more ssl-services are going to be added, this will probably
* need a more generic scheme
*/
if (!strncmp(servicename, "https", sizeof("https"))
|| !strncmp(servicename, "pop3s", sizeof("pop3s"))
|| !strncmp(servicename, "owa", sizeof("owa"))
|| !strncmp(servicename, "wordpress-tls", sizeof("wordpress-tls"))
|| !strncmp(servicename, "wp-tls", sizeof("wp-tls"))
|| !strncmp(servicename, "webform-tls", sizeof("webform-tls"))
|| !strncmp(servicename, "web-tls", sizeof("web-tls")))
temp.misc.ssl = true;
if (!strncmp(servicename, "mongodb", sizeof("mongodb")))
temp.misc.db = Strndup("admin", sizeof("admin"));
if (!strncmp(servicename, "winrm", sizeof("winrm")))
temp.misc.domain = Strndup("Workstation", sizeof("Workstation"));
for (vi = ServicesTable.begin(); vi != ServicesTable.end(); vi++) {
if ((vi->lookup.portno == temp.lookup.portno)
&& (vi->lookup.proto == temp.lookup.proto)
&& !(strcmp(vi->lookup.name, temp.lookup.name))) {
if (o.debugging)
error("Port %d proto %s is duplicated in services file %s",
portno, proto, filename);
continue;
}
}
ServicesTable.push_back(temp);
}
fclose(fp);
}
/* Returns one if the file pathname given exists, is not a directory and
* is readable by the executing process. Returns two if it is readable
* and is a directory. Otherwise returns 0.
*/
static int
file_readable(const char *pathname) {
char *pathname_buf = strdup(pathname);
int status = 0;
#ifdef WIN32
/* stat on windows only works for "dir_name" not for "dir_name/"
* or "dir_name\\"
*/
int pathname_len = strlen(pathname_buf);
char last_char = pathname_buf[pathname_len - 1];
if( last_char == '/'
|| last_char == '\\')
pathname_buf[pathname_len - 1] = '\0';
#endif
struct stat st;
if (stat(pathname_buf, &st) == -1)
status = 0;
else if (access(pathname_buf, R_OK) != -1)
status = S_ISDIR(st.st_mode) ? 2 : 1;
free(pathname_buf);
return status;
}
/*
* useroption should be 1 if either -U or -P has been specified.
* by default it is 0
*/
int
ncrack_fetchfile(char *filename_returned, int bufferlen, const char *file,
int useroption) {
char *dirptr;
int res;
int foundsomething = 0;
struct passwd *pw;
static int warningcount = 0;
char dot_buffer[512];
/* -U or -P has been specified */
if (useroption) {
res = Snprintf(filename_returned, bufferlen, "%s", file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
/* First, check the map of requested data file names. If there's an entry for
file, use it and return.
Otherwise, we try [--datadir]/file, then $NCRACKDIR/file
next we try ~user/.ncrack/file
then we try NCRACKDATADIR/file <--NCRACKDATADIR
finally we try ./file
-- or on Windows --
--datadir -> $NCRACKDIR -> ncrack.exe directory -> NCRACKDATADIR -> .
*/
if (o.datadir && !foundsomething) {
res = Snprintf(filename_returned, bufferlen, "%s/%s", o.datadir, file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
if (!foundsomething && (dirptr = getenv("NCRACKDIR"))) {
res = Snprintf(filename_returned, bufferlen, "%s/%s", dirptr, file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
#ifndef WIN32
if (!foundsomething) {
pw = getpwuid(getuid());
if (pw) {
res = Snprintf(filename_returned, bufferlen, "%s/.ncrack/%s",
pw->pw_dir, file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
if (!foundsomething && getuid() != geteuid()) {
pw = getpwuid(geteuid());
if (pw) {
res = Snprintf(filename_returned, bufferlen, "%s/.ncrack/%s",
pw->pw_dir, file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
}
}
#else
if (!foundsomething) { /* Try the Ncrack directory */
char fnbuf[MAX_PATH];
int i;
res = GetModuleFileName(GetModuleHandle(0), fnbuf, 1024);
if(!res) fatal("GetModuleFileName failed (!)\n");
/* Strip it */
for(i = res - 1; i >= 0 && fnbuf[i] != '/' && fnbuf[i] != '\\'; i--);
if(i >= 0) /* we found it */
fnbuf[i] = 0;
res = Snprintf(filename_returned, bufferlen, "%s\\%s", fnbuf, file);
if(res > 0 && res < bufferlen)
foundsomething = file_readable(filename_returned);
/* Now try under 'lists' for the installed directory */
if (!foundsomething) {
res = Snprintf(filename_returned, bufferlen, "%s\\lists\\%s", fnbuf, file);
if(res > 0 && res < bufferlen)
foundsomething = file_readable(filename_returned);
}
}
#endif
if (!foundsomething) {
res = Snprintf(filename_returned, bufferlen, "%s/%s", NCRACKDATADIR, file);
if (res > 0 && res < bufferlen) {
foundsomething = file_readable(filename_returned);
}
}
if (foundsomething && (*filename_returned != '.') && !useroption) {
res = Snprintf(dot_buffer, sizeof(dot_buffer), "./%s", file);
if (res > 0 && res < bufferlen) {
if (file_readable(dot_buffer)) {
#ifdef WIN32
if (warningcount++ < 1 && o.debugging)
#else
if(warningcount++ < 1)
#endif
error("Warning: File %s exists, but Ncrack is using %s for "
"security and consistency reasons. Set NCRACKDIR=. to give "
"priority to files in your local directory (may affect the "
"other data files too).", dot_buffer, filename_returned);
}
}
}
if (!foundsomething) {
res = Snprintf(filename_returned, bufferlen, "./%s", file);
if (res > 0 && res < bufferlen)
foundsomething = file_readable(filename_returned);
}
/* For username/password lists also search ./lists */
if (!foundsomething) {
res = Snprintf(filename_returned, bufferlen, "./lists/%s", file);
if (res > 0 && res < bufferlen)
foundsomething = file_readable(filename_returned);
}
if (!foundsomething) {
Snprintf(filename_returned, bufferlen, "%s", file);
}
if (foundsomething && o.debugging > 1)
log_write(LOG_PLAIN, "Fetchfile found %s\n", filename_returned);
return foundsomething;
}
/*
* The only thing that a safe and generic signal handler should do, is to set a
* flag that will be later checked by the main program. Ncrack will
* periodically check this variable, and take appropriate action to exit
* cleanly and also possibly save the current state into a file that can be
* used later with --resume.
*/
static void
sigcatch(int signo)
{
o.saved_signal = signo;
return;
}
static void
sigcheck(ServiceGroup *SG)
{
if (o.saved_signal == -1)
return;
fflush(stdout);
switch (o.saved_signal) {
case SIGINT:
error("caught SIGINT signal, cleaning up");
break;
#ifdef SIGTERM
case SIGTERM:
error("caught SIGTERM signal, cleaning up");
break;
#endif
#ifdef SIGHUP
case SIGHUP:
error("caught SIGHUP signal, cleaning up");
break;
#endif
#ifdef SIGBUS
case SIGBUS:
error("caught SIGBUS signal, cleaning up");
break;
#endif
default:
error("caught signal %d, cleaning up", o.saved_signal);
break;
}
log_close(LOG_NORMAL);
/* Now try and save available information into a file that might be later
* recalled with --resume.
*/
ncrack_save(SG);
exit(1);
}
static char *
grab_next_host_spec(FILE *inputfd, int argc, char **argv)
{
static char host_spec[1024];
unsigned int host_spec_index;
int ch;
if (!inputfd) {
return ((optind < argc) ? argv[optind++] : NULL);
} else {
if (o.nmap_input_xml) {
if (xml_input(inputfd, host_spec) < 0)
return NULL;
} else if (o.nmap_input_normal) {
if (normal_input(inputfd, host_spec) < 0)
return NULL;
} else {
host_spec_index = 0;
while((ch = getc(inputfd)) != EOF) {
if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\0') {
if (host_spec_index == 0)
continue;
host_spec[host_spec_index] = '\0';
return host_spec;
} else if (host_spec_index < sizeof(host_spec) / sizeof(char) -1) {
host_spec[host_spec_index++] = (char) ch;
} else fatal("One of the host_specifications from your input file "
"is too long (> %d chars)", (int) sizeof(host_spec));
}
host_spec[host_spec_index] = '\0';
}
}
if (!*host_spec)
return NULL;
return host_spec;
}
/*
* Parses the username and password list that has been specified from the
* command line through the --user and --pass options. The argument must be a
* comma separated list of words for each case.
*/
static void
parse_login_list(char *const arg, int mode)
{
vector <char *> *p = NULL;
size_t i, j, arg_len;
char *word;
if (mode == USER)
p = &UserArray;
else if (mode == PASS)
p = &PassArray;
else
fatal("%s invalid mode specified!", __func__);
arg_len = strlen(arg);
j = i = 0;
while (i < arg_len) {
if (arg[i] == ',') {
word = Strndup(&arg[j], i - j);
p->push_back(word);
j = i + 1;
}
i++;
}
/* In case, user just typed --user "," or --pass "," don't add two blank
* passwords as there is no point in that.
*/
if (arg[0] == ',' && arg_len == 1)
return;
word = Strndup(&arg[j], i - j);
p->push_back(word);
}
static void
load_login_file(const char *filename, int mode)
{
char line[1024];
char *tmp;
FILE *fd;
vector <char *> *p = NULL;
if (!strcmp(filename, "-"))
fd = stdin;
else {
fd = fopen(filename, "r");
if (!fd)
fatal("Failed to open input file %s for reading!", filename);
}
if (mode == USER)
p = &UserArray;
else if (mode == PASS)
p = &PassArray;
else
fatal("%s invalid mode specified!", __func__);
while (fgets(line, sizeof(line), fd)) {
/* Note that supporting comment lines starting with '#' automatically
* entails not being able to get passwords that start with '#'.
*/
if (*line == '#')
continue;
/* A blank line (just the '\n' char) in a wordlist file means that a
* blank entry will be tested. Strndup allocates an entry that is at least
* of 1 size ('\0'), so supplying it with the length of each line minus the
* '\n' character of the line will universally work in all cases.
* However, we need to take into account the possibility that the user
* supplies Windows-derived wordlists which use CRLF termination.
* In that case, just drop the 1 extra character.
*/
if (strlen(line) == 2 && !strncmp(line, "\r\n", 2))
line[1] = '\0';
tmp = Strndup(line, strlen(line) - 1);
p->push_back(tmp);
}
}
static void
call_module(nsock_pool nsp, Connection *con)
{
char *name = con->service->name;
/* initialize connection state variables */
con->auth_success = false;
con->check_closed = false;
con->auth_complete = false;
con->peer_alive = false;
con->finished_normally = false;
con->close_reason = -1;
con->force_close = false;
if (!strcmp(name, "ftp"))
ncrack_ftp(nsp, con);
else if (!strcmp(name, "telnet"))
ncrack_telnet(nsp, con);
else if (!strcmp(name, "http"))
ncrack_http(nsp, con);
else if (!strcmp(name, "pop3"))
ncrack_pop3(nsp, con);
else if (!strcmp(name, "vnc"))
ncrack_vnc(nsp, con);
else if (!strcmp(name, "redis"))
ncrack_redis(nsp, con);
else if (!strcmp(name, "mqtt"))
ncrack_mqtt(nsp, con);
else if (!strcmp(name, "imap"))
ncrack_imap(nsp, con);
else if (!strcmp(name, "cassandra"))
ncrack_cassandra(nsp, con);
else if (!strcmp(name,"cvs"))
ncrack_cvs(nsp,con);
else if (!strcmp(name, "joomla"))
ncrack_joomla(nsp, con);
else if (!strcmp(name, "dicom"))
ncrack_dicom(nsp, con);
else if (!strcmp(name, "couchbase"))
ncrack_couchbase(nsp, con);
else if (!strcmp(name, "wordpress") || !strcmp(name, "wp"))
ncrack_wordpress(nsp, con);
else if (!strcmp(name, "webform") || !strcmp(name, "web"))
ncrack_webform(nsp, con);
#if HAVE_OPENSSL
else if (!strcmp(name, "wordpress-tls") || !strcmp(name, "wp-tls"))
ncrack_wordpress(nsp, con);
else if (!strcmp(name, "webform-tls") || !strcmp(name, "web-tls"))
ncrack_webform(nsp, con);
else if (!strcmp(name, "winrm"))
ncrack_winrm(nsp, con);
else if (!strcmp(name, "mongodb"))
ncrack_mongodb(nsp, con);
else if (!strcmp(name, "pop3s"))
ncrack_pop3(nsp, con);
else if (!strcmp(name, "mysql"))
ncrack_mysql(nsp, con);
else if (!strcmp(name, "psql"))
ncrack_psql(nsp, con);
else if (!strcmp(name, "mssql"))
ncrack_mssql(nsp, con);
else if (!strcmp(name, "ssh"))
ncrack_ssh(nsp, con);
else if (!strcmp(name, "owa"))
ncrack_owa(nsp, con);
else if (!strcmp(name, "https"))
ncrack_http(nsp, con);
else if (!strcmp(name, "sip"))
ncrack_sip(nsp, con);
else if (!strcmp(name, "rdp") || !strcmp(name, "ms-wbt-server"))
ncrack_rdp(nsp, con);
else if (!strcmp(name, "smb") || !strcmp(name, "netbios-ssn") || !strcmp(name, "microsoft-ds"))
ncrack_smb(nsp, con);
else if (!strcmp(name, "smb2"))
ncrack_smb2(nsp, con);
#endif
else
fatal("Invalid service module: %s", name);
}
int
main(int argc, char **argv)
{
char **myargv = NULL;
int myargc = 0;
if (argc == 3 && strcmp("--resume", argv[1]) == 0) {
if (ncrack_resume(argv[2], &myargc, &myargv) == -1) {
fatal("Cannot resume from (supposed) log file %s", argv[2]);
}
o.resume = true;
return ncrack_main(myargc, myargv);
}
return ncrack_main(argc, argv);
}
static int
ncrack_main(int argc, char **argv)
{
ts_spec spec;
FILE *inputfd = NULL;
char *normalfilename = NULL;
char *xmlfilename = NULL;
time_t timep;
unsigned int i; /* iteration var */
char services_file[256]; /* path name for "ncrack-services" file */
char username_file[256];
char password_file[256];
/* strtok changes the first argument and we don't want to mess with
* the argv stuff, as they hold important info for later. For this reason,
* we copy optarg to tmp each time a function that calls strtok is going to
* be invoked.
*/
char *tmp = NULL;
int err;
char *host_spec = NULL;
Target *currenths = NULL;
vector <Target *> Targets; /* targets to be ncracked */
vector <Target *>::iterator Tvi;
ServiceGroup *SG; /* all services to be ncracked */
list <Service *>::iterator li;
vector <Service *>Services; /* temporary services vector */
vector <Service *>::iterator Svi; /* iterator for services vector */
Service *service;
vector <service_lookup *> services_cmd;
vector <service_lookup *>::iterator SCvi;
char *glob_options = NULL; /* for -g option */
timing_options timing; /* for -T option */
/* time variables */
time_t now;
char tbuf[128];
char mytime[128];
/* exclude-specific variables */
FILE *excludefd = NULL;
char *exclude_spec = NULL;
TargetGroup *exclude_group = NULL;
/* getopt-specific */
int arg;
int option_index;
extern char *optarg;
extern int optind;
struct option long_options[] =
{
{"resume", required_argument, 0, 0},
{"save", required_argument, 0, 0},
{"list", no_argument, 0, 0},
{"services", required_argument, 0, 'p'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"datadir", required_argument, 0, 0},
{"debug", optional_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"timing", required_argument, 0, 'T'},
{"excludefile", required_argument, 0, 0},
{"exclude", required_argument, 0, 0},
{"iL", required_argument, 0, 0},
{"iX", required_argument, 0, 0},
{"iN", required_argument, 0, 0},
{"oA", required_argument, 0, 0},
{"oN", required_argument, 0, 0},
{"oX", required_argument, 0, 0},
{"append_output", no_argument, 0, 0},
{"append-output", no_argument, 0, 0},
{"log_errors", no_argument, 0, 0},
{"log-errors", no_argument, 0, 0},
{"stealthy_linear", no_argument, 0, 0},
{"stealthy-linear", no_argument, 0, 0},
{"connection_limit", required_argument, 0, 0},
{"connection-limit", required_argument, 0, 0},
{"passwords_first", no_argument, 0, 0},
{"passwords-first", no_argument, 0, 0},
{"pairwise", no_argument, 0, 0},
{"user", required_argument, 0, 0},
{"pass", required_argument, 0, 0},
{"nsock-trace", required_argument, 0, 0},
{"nsock_trace", required_argument, 0, 0},
{"proxy", required_argument, 0, 0},
{"proxies", required_argument, 0, 0},
{0, 0, 0, 0}
};
if (argc < 2)
print_usage();
ncrack_fetchfile(services_file, sizeof(services_file), "ncrack-services");
/* Initialize available services' lookup table */
lookup_init(services_file);
#if WIN32
win_init();
#endif
now = time(NULL);
err = n_localtime(&now, &local_time);
if (err) {
fatal("n_localtime failed: %s", strerror(err));
}
/* Argument parsing */
optind = 1;
while((arg = getopt_long_only(argc, argv, "6d::f::g:hU:P:m:o:p:s:T:v::V",
long_options, &option_index)) != EOF) {
switch(arg) {
case 0:
if (!strcmp(long_options[option_index].name, "excludefile")) {
if (exclude_spec)
fatal("--excludefile and --exclude options are mutually "
"exclusive.");
excludefd = fopen(optarg, "r");
if (!excludefd)
fatal("Failed to open exclude file %s for reading", optarg);
} else if (!strcmp(long_options[option_index].name, "exclude")) {
if (excludefd)
fatal("--excludefile and --exclude options are mutually "
"exclusive.");
exclude_spec = strdup(optarg);
} else if (!strcmp(long_options[option_index].name, "services")) {
parse_services(optarg, services_cmd);
} else if (!strcmp(long_options[option_index].name, "list")) {
o.list_only = true;
} else if (!strcmp(long_options[option_index].name,
"connection-limit")) {
o.connection_limit = atoi(optarg);
} else if (!strcmp(long_options[option_index].name,
"passwords-first")) {
o.passwords_first = true;
} else if (!strcmp(long_options[option_index].name,