-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathdnscat.c
1962 lines (1689 loc) · 61.2 KB
/
dnscat.c
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
/* dnscat.c
* By Ron Bowes
* Created January, 2010
*
* (See LICENSE.txt)
*
* For up to date documentation, please see the wiki:
* http://www.skullsecurity.org/wiki/index.php/Dnscat
*
*/
#define _POSIX_SOURCE /* For fileno(). */
#include <ctype.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef WIN32
#include <io.h>
#include <winsock2.h>
#else
#include <netdb.h>
#include <strings.h>
#include <unistd.h>
#endif
#include "buffer.h"
#include "dns.h"
#include "memory.h"
#include "my_getopt.h"
#include "select_group.h"
#include "session.h"
#include "types.h"
#include "udp.h"
/* Used for a state machine when processing packets. */
typedef enum
{
PROCESSING_STATE_SIG,
PROCESSING_STATE_FLAGS,
PROCESSING_STATE_IDENTIFIER,
PROCESSING_STATE_SESSION,
PROCESSING_STATE_SEQ,
PROCESSING_STATE_COUNT,
PROCESSING_STATE_DATA,
PROCESSING_STATE_ERROR_CODE,
PROCESSING_STATE_GARBAGE,
PROCESSING_STATE_DOMAIN
} processing_state_t;
/* Flags for the packets. */
typedef enum
{
FLAG_STREAM = 0x00000001,
/* FLAG_SYN = 0x00000002, Deprecated */
/* FLAG_ACK = 0x00000004, Deprecated */
FLAG_RST = 0x00000008,
FLAG_HEX = 0x00000010,
FLAG_SESSION = 0x00000020,
FLAG_IDENTIFIER = 0x00000040,
} flags_t;
/* Error code for remote connections. */
typedef enum
{
REMOTE_ERROR_SUCCESS = 0x00000000,
REMOTE_ERROR_BUSY = 0x00000001,
REMOTE_ERROR_INVALID_IN_STATE = 0x00000002,
REMOTE_ERROR_FIN = 0x00000003,
REMOTE_ERROR_4 = 0x00000004, /* Left to take up space. */
REMOTE_ERROR_BAD_SEQ = 0x00000005,
REMOTE_ERROR_NOT_IMPL = 0x00000006,
REMOTE_ERROR_TESTING = 0xFFFFFFFF
/* Don't forget to update REMOTE_ERROR_MAX. */
} remote_error_t;
/* Encoding types. */
typedef enum
{
ENCODING_NETBIOS,
ENCODING_HEX
} encoding_t;
/* An array for the errors (not currently being used). */
static char *remote_error[] = {"ERROR_SUCCESS", "ERROR_BUSY", "ERROR_INVALID_IN_STATE", "ERROR_FIN", "ERROR_4", "ERROR_BAD_SEQ", "ERROR_NOT_IMPL", "ERROR_TESTING"};
/* The maximum remote error, to prevent overflows. */
#define REMOTE_ERROR_MAX REMOTE_ERROR_NOT_IMPL
/* A macro to display remote protocol errors. */
#define REMOTE_ERROR(s) ((s < 0 || s > REMOTE_ERROR_MAX) ? "(unknown error)" : remote_error[s])
/* Local errors. */
typedef enum
{
LOCAL_ERROR_SUCCESS = 0x00000000, /* Everything's okay! */
LOCAL_ERROR_WRONG_DOMAIN = 0x00000001, /* Packet is sent to incorrect domain. */
LOCAL_ERROR_INVALID = 0x00000002, /* Packet couldn't be parsed (wrong number of fields, wrong type, etc.) */
LOCAL_ERROR_BAD_SIGNATURE = 0x00000003, /* Packet didn't start with the proper signature. */
/* Don't forget to update LOCAL_ERROR_MAX. */
} local_error_t;
static char *local_error[] = {"ERROR_SUCCESS", "ERROR_WRONG_DOMAIN", "ERROR_INVALID", "ERROR_BAD_SIGNATURE"};
/* The maximum local error, to prevent overflows. */
#define LOCAL_ERROR_MAX LOCAL_ERROR_BAD_SIGNATURE
/* A macro to display local protocol errors. */
#define LOCAL_ERROR(s) ((s < 0 || s > LOCAL_ERROR_MAX) ? "(unknown error)" : local_error[s])
/* The size of chunks to send when --stage is enabled. */
#define STAGE_CHUNK_SIZE 255
/* Some defaults. */
#define DEFAULT_CHUNK_SIZE 62
#define DEFAULT_SECTION_COUNT 3
#define DEFAULT_SIGNATURE "dnscat"
#define DEFAULT_REQUEST_TYPE DNS_TYPE_CNAME
#define DEFAULT_USE_STREAM TRUE
#define DEFAULT_USER "nobody"
#define DEFAULT_DOMAIN_NAME "*"
#define DEFAULT_FREQUENCY 1000
#define DEFAULT_TIMEOUT 5
#define DEFAULT_ENCODING ENCODING_NETBIOS
#define DEFAULT_PORT 53
#define DEFAULT_SOURCE_ADDR "0.0.0.0"
#define NAME "dnscat"
typedef struct
{
int socket; /* Store the socket. */
NBBOOL is_server; /* Set to TRUE if it's a listener, FALSE otherwise. */
NBBOOL built_in; /* Set to TRUE to use built-in functions (gethostbyname()) instead of our custom resolver. */
char *signature; /* The signature to prefix each request with (and to check each incoming request for). */
char *identifier; /* The identifier we're sending (client only). */
char *session; /* The session that we're a part of (client only). */
NBBOOL no_session; /* If set, sessionid won't be included in packets. */
char *domain; /* The domain to append to each request (and to check for, in server mode). */
char *source; /* The source address (Default: 0.0.0.0). */
uint16_t port; /* The source port in listener mode, the target port otherwise. */
NBBOOL waiting_for_ack; /* Waiting for the server to acknowledge our message. */
dns_types_t request_type; /* The request type (CNAME, MX, AAAA, etc). */
#ifndef WIN32
NBBOOL AAAA; /* Set to TRUE to display AAAA requests. They aren't displayed by default. */
#endif
sessions_t *sessions; /* Store the list of sessions running. */
NBBOOL use_stream; /* Set to TRUE to use stream mode (default); otherwise, uses datagram mode. */
int timeout; /* The amount of time before a connection resets. */
uint32_t chunk_size; /* The maximum encoded size of a DNS section. Protocol states that 64 is the max, including the one-byte prefix. */
uint32_t section_count; /* The number of DNS sections to send. Any more than 3 results in packets that are too long. */
int frequency; /* The frequency with which the client polls the server. */
char *user; /* The user to drop privileges to. */
NBBOOL keep_root; /* Set to TRUE to keep root privileges (no dropping). */
select_group_t *select_group; /* Used to keep track of the sockets. */
char *dns_user; /* The user-supplied DNS server. Takes precident over dns_system. */
char *dns_system; /* The system-wide DNS server. */
NBBOOL multi; /* If set, one server will talk to multiple clients. */
char *exec; /* The program to execute. */
NBBOOL exec_no_stderr; /* Ignore stderr. */
char *stage; /* Set to the 'stage' file. */
FILE *stage_file; /* The handle to the stage file. */
char *log_filename; /* The file to use for logging. */
encoding_t encoding; /* The type of payload encoding to use. */
#if TEST
/* Testing stuff. */
NBBOOL test_errors;
#endif
} settings_t;
/* The data stored in a single dnscat packet. This is encoded as a DNS name. */
typedef struct
{
char *signature;
uint32_t flags;
char *identifier;
char *session;
uint32_t seq;
uint8_t *data;
uint32_t data_length;
char *domain;
remote_error_t error_code;
} dnscat_packet_t;
/* We need this for catching signals and cleaning up properly. */
static settings_t *global_settings = NULL;
/* Client only. Get the DNS server that's being used to send requests. This is
* either the system DNS or the DNS given by the user. */
static char *get_dns(settings_t *settings)
{
if(settings->dns_user)
return settings->dns_user;
return settings->dns_system;
}
/* Take the given packet and convert it into a DNS name. The data section will
* be encoded in as many chunks as necessary. The packet->flags field is used
* to decide which fields to include. */
static char *packet_to_name(settings_t *settings, dnscat_packet_t *packet)
{
buffer_t *name = buffer_create(BO_NETWORK);
char number[9]; /* Used throughout as a buffer. */
uint8_t i;
/* Twiddle the flags if the use requested no session. */
if(settings->no_session)
packet->flags = packet->flags & (~FLAG_SESSION);
/* Add the signature. */
buffer_add_string(name, packet->signature);
buffer_add_int8(name, '.');
/* Add the flags. */
#ifdef WIN32
sprintf_s(number, 9, "%x", packet->flags);
#else
sprintf(number, "%x", packet->flags);
#endif
buffer_add_string(name, number);
buffer_add_int8(name, '.');
/* Add the identifier, if required. */
if(packet->flags & FLAG_IDENTIFIER)
{
buffer_add_string(name, packet->identifier);
buffer_add_int8(name, '.');
}
/* Add the session id, if required. */
if(packet->flags & FLAG_SESSION)
{
buffer_add_string(name, packet->session);
buffer_add_int8(name, '.');
}
/* Add the sequence number, if required. */
if(packet->flags & FLAG_STREAM)
{
#ifdef WIN32
sprintf_s(number, 9, "%x", packet->seq);
#else
sprintf(number, "%x", packet->seq);
#endif
buffer_add_string(name, number);
buffer_add_int8(name, '.');
}
/* Add the error, if required. */
if(packet->flags & FLAG_RST)
{
#ifdef WIN32
sprintf_s(number, 9, "%x", packet->error_code);
#else
sprintf(number, "%x", packet->error_code);
#endif
buffer_add_string(name, number);
buffer_add_int8(name, '.');
}
else
{
/* This is where it gets a little more complicated. We have to marshall up the
* data into chunks, encode it, then add the length to the beginning. */
buffer_t *data = buffer_create(BO_NETWORK);
uint32_t index = 0;
uint32_t length = 0;
uint32_t sections = 0;
/* Loop until we're out of data. */
while(index < packet->data_length)
{
while(length < settings->chunk_size && index < packet->data_length)
{
if(packet->flags & FLAG_HEX)
{
uint8_t bit;
bit = packet->data[index] >> 4;
buffer_add_int8(data, bit > 9 ? ('a' + bit - 10) : ('0' + bit));
length++;
bit = packet->data[index] & 0x0F;
buffer_add_int8(data, bit > 9 ? ('a' + bit - 10) : ('0' + bit));
length++;
}
else
{
buffer_add_int8(data, ((packet->data[index] >> 4) & 0x0F) + 'a');
length++;
buffer_add_int8(data, ((packet->data[index] >> 0) & 0x0F) + 'a');
length++;
}
/* Increment the index. */
index++;
}
buffer_add_int8(data, '.');
length = 0;
sections++;
}
/* Now that we've built up the name, add the appropriate count and data. */
#ifdef WIN32
sprintf_s(number, 9, "%x", sections);
#else
sprintf(number, "%x", sections);
#endif
buffer_add_string(name, number);
buffer_add_int8(name, '.');
buffer_add_buffer(name, data);
/* Clean up data. */
buffer_destroy(data);
}
/* Add some randomness to prevent caching. */
for(i = 0; i < 4; i++)
buffer_add_int8(name, 'a' + (rand() % 26));
buffer_add_int8(name, '.');
/* Add the domain. */
buffer_add_string(name, packet->domain);
/* Terminate with a NULL. */
buffer_add_int8(name, 0);
/* Convert the whole thing into a string. */
return (char*)buffer_create_string_and_destroy(name, NULL);
}
static char *get_next_request_server(settings_t *settings, dnscat_packet_t *incoming, remote_error_t error)
{
/* Generate the next name to send out. This is largely based on the incoming packet's values. */
dnscat_packet_t packet;
uint32_t flags = 0;
char *result;
if(error != REMOTE_ERROR_SUCCESS)
fprintf(stderr, "Sending error: %s (%d)\n", REMOTE_ERROR(error), error);
/* Initialize the packet to 0. */
memset(&packet, 0, sizeof(dnscat_packet_t));
packet.signature = incoming->signature;
packet.domain = incoming->domain;
if(incoming->flags & FLAG_IDENTIFIER)
{
packet.identifier = incoming->identifier;
flags = flags | FLAG_IDENTIFIER;
}
if(incoming->flags & FLAG_SESSION)
{
packet.session = incoming->session;
flags = flags | FLAG_SESSION;
}
if(incoming->flags & FLAG_STREAM)
{
packet.seq = incoming->seq;
flags = flags | FLAG_STREAM;
}
if(error != REMOTE_ERROR_SUCCESS)
{
packet.error_code = error;
flags = flags | FLAG_RST;
}
packet.flags = flags;
if(error == REMOTE_ERROR_SUCCESS)
{
/* Finally, grab just the right amount of data. */
packet.data_length = ((settings->chunk_size - 1) / 2) * settings->section_count; /* Maximum amount of data. */
/* If we're in 'multi' mode, read data from the given session.
* Otherwise, read it from the NULL session. */
packet.data = session_read(settings->sessions, incoming->session, &packet.data_length);
/* If session_read() failed for some reason, reply with an error and delete the session. */
if(packet.data == NULL)
{
fprintf(stderr, "An error occurred in session %s, closing\n", incoming->session);
packet.error_code = REMOTE_ERROR_FIN;
flags = flags | FLAG_RST;
session_delete(settings->sessions, incoming->session);
}
}
/* Convert the request into a dns name. */
result = packet_to_name(settings, &packet);
if(packet.data)
safe_free(packet.data);
return result;
}
static char *get_next_request_client(settings_t *settings, remote_error_t error)
{
/* Generate the next name to send out. This is largely based on the 'settings' values. */
dnscat_packet_t packet;
uint32_t flags = 0;
char *result;
if(error != REMOTE_ERROR_SUCCESS)
fprintf(stderr, "Sending error: %s (%d)\n", REMOTE_ERROR(error), error);
/* Initialize the packet to 0. */
memset(&packet, 0, sizeof(dnscat_packet_t));
/* Set up the easy stuff. */
packet.signature = settings->signature;
packet.domain = settings->domain;
if(settings->identifier)
{
packet.identifier = settings->identifier;
flags = flags | FLAG_IDENTIFIER;
}
if(settings->session)
{
packet.session = settings->session;
flags = flags | FLAG_SESSION;
}
if(settings->use_stream)
{
packet.seq = session_get_seq(settings->sessions, settings->session);
flags = flags | FLAG_STREAM;
}
if(settings->encoding == ENCODING_HEX)
flags = flags | FLAG_HEX;
if(error != REMOTE_ERROR_SUCCESS)
{
packet.error_code = error;
flags = flags | FLAG_RST;
}
packet.flags = flags;
if(error == REMOTE_ERROR_SUCCESS)
{
/* Finally, grab just the right amount of data. */
packet.data_length = ((settings->chunk_size - 1) / 2) * settings->section_count; /* Maximum amount of data. */
packet.data = session_read(settings->sessions, settings->session, &packet.data_length);
/* If session_read() failed for some reason, print an error and die. */
if(packet.data == NULL)
{
fprintf(stderr, "An error occurred in session %s, terminating\n", settings->session);
exit(1);
}
}
/* Convert the request into a dns name. */
result = packet_to_name(settings, &packet);
if(packet.data)
safe_free(packet.data);
return result;
}
/* Parse an incoming name into a dnscat_packet_t structure. Does its best to do
* nothing but parse the name, doesn't update state or sanity check or anything
* like that. The only sanity checks done are to make sure the packet structure
* is correct, and that the signature matches (packets without a matching
* signature are considered "wrong").
*
* Remember, the data coming into this function may be out of state or an
* arbitrary (or even potentially malicious) connection, so be careful what you
* update here.
*
* Note that the packet itself may be an "error" packet (an RST), but this
* function will still return successfully, with the result itself will being an
* error. */
static local_error_t parse_name(settings_t *settings, char *name_in, dnscat_packet_t **result)
{
char *name = safe_strdup(name_in); /* Copy the name to prevent strtok() from modifying the original. */
buffer_t *decoded_stream = buffer_create(BO_NETWORK); /* The data is built in here. */
processing_state_t state = PROCESSING_STATE_SIG; /* Keep track of the state. */
char *piece;
#ifdef WIN32
char *context;
#endif
uint32_t count;
size_t i;
local_error_t error = LOCAL_ERROR_SUCCESS;
buffer_t *domain = NULL;
/*printf("Parsing name: %s\n", name_in);*/
/* Create the result. */
*result = (dnscat_packet_t*) safe_malloc(sizeof(dnscat_packet_t));
/* Initialize the result to blank. */
memset(*result, 0, sizeof(dnscat_packet_t));
/* Loop through the name, breaking it up at the periods and updating the state as we go. */
#ifdef WIN32
for(piece = strtok_s(name, ".", &context); piece && error == LOCAL_ERROR_SUCCESS; piece = strtok_s(NULL, ".", &context))
#else
for(piece = strtok(name, "."); piece && error == LOCAL_ERROR_SUCCESS; piece = strtok(NULL, "."))
#endif
{
switch(state)
{
case PROCESSING_STATE_SIG:
(*result)->signature = safe_strdup(piece);
if(strcmp((*result)->signature, settings->signature))
error = LOCAL_ERROR_WRONG_DOMAIN;
state = PROCESSING_STATE_FLAGS;
break;
case PROCESSING_STATE_FLAGS:
(*result)->flags = strtol(piece, NULL, 16);
/* If we have an identifier, proceed to the identifier. */
if((*result)->flags & FLAG_IDENTIFIER)
state = PROCESSING_STATE_IDENTIFIER;
/* If we have a session, proceed to the session id. */
else if((*result)->flags & FLAG_SESSION)
state = PROCESSING_STATE_SESSION;
/* If we're in stream mode, go to the sequence number. */
else if((*result)->flags & FLAG_STREAM)
state = PROCESSING_STATE_SEQ;
/* If we have an error, go to the error code. */
else if((*result)->flags & FLAG_RST)
state = PROCESSING_STATE_ERROR_CODE;
/* If nothing else triggers, it's a normal datagram packet. Go to the field count. */
else
state = PROCESSING_STATE_COUNT;
break;
case PROCESSING_STATE_IDENTIFIER:
(*result)->identifier = safe_strdup(piece);
/* If we have a session, proceed to the session id. */
if((*result)->flags & FLAG_SESSION)
state = PROCESSING_STATE_SESSION;
/* If we're in stream mode, go to the sequence number. */
else if((*result)->flags & FLAG_STREAM)
state = PROCESSING_STATE_SEQ;
/* If we have an error, go to the error code. */
else if((*result)->flags & FLAG_RST)
state = PROCESSING_STATE_ERROR_CODE;
/* If nothing else happens, it's a normal datagram packet. Go to the field count. */
else
state = PROCESSING_STATE_COUNT;
break;
case PROCESSING_STATE_SESSION:
(*result)->session = safe_strdup(piece);
/* If we're in stream mode, go to the sequence number. */
if((*result)->flags & FLAG_STREAM)
state = PROCESSING_STATE_SEQ;
/* If we have an error, go to the error code. */
else if((*result)->flags & FLAG_RST)
state = PROCESSING_STATE_ERROR_CODE;
/* If nothing else happens, it's a normal datagram packet. Go to the field count. */
else
state = PROCESSING_STATE_COUNT;
break;
case PROCESSING_STATE_SEQ:
/* Simply process the sequence number then move onto the section count. */
(*result)->seq = strtol(piece, NULL, 16);
/* If it's an error, go to the error code.
* If it's a SYN or ACK, go to garbage.
* Otherwise, go to count. */
if((*result)->flags & FLAG_RST)
state = PROCESSING_STATE_ERROR_CODE;
else
state = PROCESSING_STATE_COUNT;
break;
case PROCESSING_STATE_COUNT:
/* Read the count, and check if it has a value; if it's non-zero, start reading the data. */
count = strtol(piece, NULL, 16);
if(count)
state = PROCESSING_STATE_DATA;
else
state = PROCESSING_STATE_GARBAGE;
break;
case PROCESSING_STATE_DATA:
if(strlen(piece) % 2)
{
fprintf(stderr, "Data wasn't a multiple of 2\n");
error = LOCAL_ERROR_INVALID;
}
else
{
/* Loop through this piece and decode. As the decode happens, add the new characters to a buffer. */
for(i = 0; i < strlen(piece) / 2 && error == LOCAL_ERROR_SUCCESS; i++)
{
uint8_t ch1, ch2;
uint8_t ch = 0;
/* Take the next two characters in a non-case-sensitive way. Note: the 'int' typecast is to fix a warning in cygwin. */
ch1 = tolower((int)piece[(i * 2)]);
ch2 = tolower((int)piece[(i * 2) + 1]);
if((*result)->flags & FLAG_HEX)
{
if(!isalnum(ch1) || !isalnum(ch2))
{
fprintf(stderr, "Invalid data in response (all characters need to be encoded as alphanumeric characters)\n");
error = LOCAL_ERROR_INVALID;
}
else
{
ch = ((ch1 >= 'a') ? (ch1 - 'a' + 10) : (ch1 - '0') << 4);
ch |= ((ch2 >= 'a') ? (ch2 - 'a' + 10) : (ch2 - '0') << 0);
buffer_add_int8(decoded_stream, ch);
}
}
else
{
if(!isalpha(ch1) || !isalpha(ch2))
{
fprintf(stderr, "Invalid data in response (all characters need to be encoded as alphabetic characters)\n");
error = LOCAL_ERROR_INVALID;
}
else
{
ch = (ch1 - 'a') << 4;
ch |= (ch2 - 'a');
buffer_add_int8(decoded_stream, ch);
}
}
}
}
/* Decrement the section count and move on if we're out of data sections. */
count--;
if(count == 0)
state = PROCESSING_STATE_GARBAGE;
break;
case PROCESSING_STATE_ERROR_CODE:
/* This field is only present in an RST packet. */
(*result)->error_code = strtol(piece, NULL, 16);
state = PROCESSING_STATE_GARBAGE;
break;
case PROCESSING_STATE_GARBAGE:
/* Don't care. */
state = PROCESSING_STATE_DOMAIN;
break;
case PROCESSING_STATE_DOMAIN:
if(domain == NULL)
domain = buffer_create(BO_NETWORK);
else
buffer_add_int8(domain, '.');
buffer_add_string(domain, piece);
/* No more state transitions - domain has to be at the end. */
break;
default:
fprintf(stderr, "Entered an unknown processing state: %d\n", state);
exit(1);
}
}
/* Free the name we copied. */
safe_free(name);
/* If there's an error, clean up and get out. */
if(error != LOCAL_ERROR_SUCCESS)
{
buffer_destroy(decoded_stream);
if(domain)
buffer_destroy(domain);
if((*result)->identifier)
safe_free((*result)->identifier);
if((*result)->session)
safe_free((*result)->session);
if((*result)->signature)
safe_free((*result)->signature);
safe_free(*result);
*result = NULL;
return error;
}
/* Save the domain name. */
buffer_add_int8(domain, 0);
(*result)->domain = (char*)buffer_create_string_and_destroy(domain, NULL);
/* Make sure we have a valid session id. */
if(!(*result)->session)
(*result)->session = safe_strdup("");
/* Make sure the domain is right. */
if(strcmp(settings->domain, "*") && strcasecmp((*result)->domain, settings->domain))
{
fprintf(stderr, "Incorrect domain name used; set the domain name with -d or --domain flag (currently: %s, received %s).\n", settings->domain, (*result)->domain);
safe_free((*result)->signature);
safe_free((*result)->domain);
if((*result)->identifier)
safe_free((*result)->identifier);
if((*result)->session)
safe_free((*result)->session);
safe_free(*result);
*result = NULL;
return LOCAL_ERROR_WRONG_DOMAIN;
}
/* If there's a remote error, also don't bother creating the string. */
if((*result)->flags & FLAG_RST)
{
buffer_destroy(decoded_stream);
return LOCAL_ERROR_SUCCESS;
}
/* If life's good, create the string. */
(*result)->data = buffer_create_string_and_destroy(decoded_stream, &(*result)->data_length);
return LOCAL_ERROR_SUCCESS;
}
static void dns_send(settings_t *settings, char *name)
{
#if 0
fprintf(stderr, "Sending request for %s...\n", name); /* TODO: Make this an option. */
#endif
if(settings->built_in)
{
gethostbyname(name);
}
else
{
uint8_t *packet;
uint32_t packet_length;
/* Create the DNS request. */
dns_t *dns = dns_create();
dns->trn_id = rand() % 0xFFFF; /* Randomize the transaction id. */
dns->flags = 0x0100;
dns_add_question(dns, name, settings->request_type, 0x0001);
packet = dns_to_packet(dns, &packet_length);
dns_destroy(dns);
udp_send(settings->socket, get_dns(settings), settings->port, packet, packet_length);
safe_free(packet);
}
}
/* Sends the next queued request, assuming:
* - We're a client (servers don't send requests, they respond)
* - We aren't waiting for acknowledgement of our last request (remember, datagrams never wait)
*
* This should be called on a regular basis. Even if no data is waiting to be sent, this will
* send blank requests to the server, allowing the server to send back data. It also ensures
* that the server doesn't time out our session. */
static void try_send_queued_data(settings_t *settings, remote_error_t outgoing_error)
{
char *name = NULL;
/* Check if we're in the right place. */
if(settings->is_server)
{
fprintf(stderr, "Server entered try_send_queued_data... something's broken!\n");
exit(1);
}
/* Check if our session has gone away, and exit if it has. */
if(!session_exists(settings->sessions, settings->session))
{
fprintf(stderr, "Session has went away, exiting.\n");
exit(0);
}
/* Check if our session has been closed, and exit if it is. */
if(session_is_closed(settings->sessions, settings->session))
{
fprintf(stderr, "Session is closed, exiting.\n");
exit(0);
}
if(outgoing_error != REMOTE_ERROR_SUCCESS)
{
name = get_next_request_client(settings, outgoing_error);
}
else
{
/* If we're in server mode, don't bother. */
if(!settings->is_server && (!settings->use_stream || !settings->waiting_for_ack))
{
/* Get the next domain name to use, if applicable. */
name = get_next_request_client(settings, REMOTE_ERROR_SUCCESS);
}
}
if(name)
{
dns_send(settings, name);
safe_free(name);
if(settings->use_stream)
settings->waiting_for_ack = TRUE;
}
/* Since this is a client, if an error was sent out then we're hooped. */
if(outgoing_error != REMOTE_ERROR_SUCCESS)
exit(0);
}
static dns_t *stage_get_response(settings_t *settings, dns_t *request)
{
int offset;
uint8_t data[STAGE_CHUNK_SIZE];
size_t size;
/* Make sure this looks like a valid stage request (the first part of the name is 2 bytes). Note: 'int' typecast is to fix a compiler warning on cygwin. */
if(!isdigit((int)request->questions[0].name[0]) || !isdigit((int)request->questions[0].name[1]) || request->questions[0].name[2] != '.')
{
fprintf(stderr, "Received invalid stage name: %s\n", request->questions[0].name);
return NULL;
}
/* Get the offset from the first two digits in the request name. */
offset = atoi(request->questions[0].name) * STAGE_CHUNK_SIZE;
fseek(settings->stage_file, offset, SEEK_SET);
fprintf(stderr, "Received request for bytes %d - %d\n", offset, offset + STAGE_CHUNK_SIZE);
/* Read the next chunk of the file. If the file ends, we set the appropriate flag and keep going. */
size = fread(data, 1, STAGE_CHUNK_SIZE, settings->stage_file);
if(size == 0)
{
/* Let the user know it's done. */
fprintf(stderr, "Stager complete! Returning NXDOMAIN.\n");
/* Return a DNS error to let the client know that we're done. */
return dns_create_error(request->trn_id, request->questions[0]);
}
else
{
/* Create our response. */
dns_t *response;
/* Check if any NULL bytes exist (which will break this). */
size_t i;
for(i = 0; i < size; i++)
{
if(data[i] == '\0')
{
fprintf(stderr, "WARNING: Stage contains at least one NULL byte, this likely won't work if the client is a Microsoft implementation\n");
break;
}
}
response = dns_create();
response->trn_id = request->trn_id;
response->flags = 0x8000;
/* Add the original question back to the response. */
dns_add_question(response, request->questions[0].name, request->questions[0].type, request->questions[0].class);
/* Add those bytes to the request as a TEXT response (note that at the end of the file, this will return some crap. It doesn't matter, though. */
dns_add_answer_TEXT(response, request->questions[0].name, request->questions[0].class, 0x00000001, data, STAGE_CHUNK_SIZE);
return response;
}
}
/* This function is used by servers to get the next outbound request. It gets the next name, re-creates the question,
* and adds an answer of the appropriate type. */
static dns_t *server_get_response(settings_t *settings, dns_t *request, char *response_name)
{
dns_t *response;
/* Start creating a DNS packet. */
response = dns_create();
response->trn_id = request->trn_id;
response->flags = 0x8000;
/* Add the original question back to the response. */
dns_add_question(response, request->questions[0].name, request->questions[0].type, request->questions[0].class);
/* Add an answer appropriate to the request type. */
if(request->questions[0].type == DNS_TYPE_A)
dns_add_answer_A(response, request->questions[0].name, request->questions[0].class, 0x00000001, "127.0.0.1");
else if(request->questions[0].type == DNS_TYPE_NS)
dns_add_answer_NS(response, request->questions[0].name, request->questions[0].class, 0x00000001, response_name);
else if(request->questions[0].type == DNS_TYPE_CNAME)
dns_add_answer_CNAME(response, request->questions[0].name, request->questions[0].class, 0x00000001, response_name);
else if(request->questions[0].type == DNS_TYPE_MX)
dns_add_answer_MX(response, request->questions[0].name, request->questions[0].class, 0x00000001, 0x1337, response_name);
else if(request->questions[0].type == DNS_TYPE_TEXT)
dns_add_answer_TEXT(response, request->questions[0].name, request->questions[0].class, 0x00000001, (uint8_t*)response_name, (uint8_t)strlen(response_name));
#ifndef WIN32
else if(request->questions[0].type == DNS_TYPE_AAAA)
dns_add_answer_AAAA(response, request->questions[0].name, request->questions[0].class, 0x00000001, "::1");
#endif
return response;
}
/* Retrieves the appropriate name from the DNS packet. If it is a dnscat server, the first
* 'question' field is used. If it is a dnscat client, the first answer field is used,
* unless it's an A or AAAA request; in that case, NULL is returned.
*
* The string returned is allocated and must be freed. */
static char *get_requested_name(settings_t *settings, dns_t *dns)
{
char *name;
if(settings->is_server)
{
#ifdef WIN32
/* On Windows, we don't support IPv6 (AAAA), so it's even easier. */
name = dns->questions[0].name;
#else
/* Server is easy -- just take the name, unless it's IPv6 (AAAA). */
if(dns->questions[0].type == DNS_TYPE_AAAA && !settings->AAAA)
name = NULL;
else
name = dns->questions[0].name;
#endif
}
else
{
/* Client is a bit more tricky.. we have to figure out which type of DNS it is. */
if(dns->answers[0].type == DNS_TYPE_A)
{
/* Do nothing. */
}
else if(dns->answers[0].type == DNS_TYPE_NS)
{
name = dns->answers[0].answer->NS.name;
}
else if(dns->answers[0].type == DNS_TYPE_CNAME)
{
name = dns->answers[0].answer->CNAME.name;
}
else if(dns->answers[0].type == DNS_TYPE_MX)
{
name = dns->answers[0].answer->MX.name;
}
else if(dns->answers[0].type == DNS_TYPE_TEXT)
{
name = (char*)dns->answers[0].answer->TEXT.text;
}
#ifndef WIN32
else if(dns->answers[0].type == DNS_TYPE_AAAA)
{
/* Do nothing. */
}
#endif
}