-
Notifications
You must be signed in to change notification settings - Fork 15
/
padcheck.go
557 lines (489 loc) · 18.3 KB
/
padcheck.go
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
// The original idea for this padding check tool was a very simple tool for checking for POODLE issues in TLS servers.
// See https://www.imperialviolet.org/2014/12/08/poodleagain.html
package main
import (
"bufio"
"crypto/sha1"
"crypto/tls"
"errors"
"flag"
"fmt"
"net"
"os"
"regexp"
"strings"
"sync"
"time"
)
var (
hostsFile *string = flag.String("hosts", "", "Filename containing hosts to query")
workerCount *int = flag.Int("workerCount", 32, "Desired number of workers for testing lists")
keyLogFile *string = flag.String("keylog", "/dev/null", "Path to a file NSS key log export (needed to decrypt pcap files)")
verboseLevel *int = flag.Int("v", 1, "Specify verboseness level (default: 1, max: 5)")
iterationCount *int = flag.Int("iterations", 3, "Number of iterations required to confirm oracle")
showHelp *bool = flag.Bool("h", false, "Show help")
)
const testCount = 5
type cbcSuite struct {
id uint16
macLen int
blockLen int
}
var cbcSuites = []*cbcSuite{
{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, 20, 8},
{tls.TLS_RSA_WITH_AES_128_CBC_SHA, 20, 16},
{tls.TLS_RSA_WITH_AES_256_CBC_SHA, 20, 16},
{tls.TLS_RSA_WITH_AES_128_CBC_SHA256, 32, 16},
{tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 20, 16},
{tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 20, 16},
{tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 20, 8},
{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 20, 16},
{tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 20, 16},
{tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 32, 16},
{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 32, 16},
}
func cbcSuiteByID(id uint16) *cbcSuite {
for _, cipherSuite := range cbcSuites {
if cipherSuite.id == id {
return cipherSuite
}
}
return nil
}
func SupportedCipherTest(hostname, serverName string, supportedCiphers []uint16, maxVersion uint16) (availableCipher *cbcSuite, protocolVersion uint16, err error) {
dialer := net.Dialer{
Timeout: 5 * time.Second,
}
keyLogWriter, err := os.OpenFile(*keyLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return
}
conn, err := tls.DialWithDialer(&dialer, "tcp", hostname, &tls.Config{
InsecureSkipVerify: true,
CipherSuites: supportedCiphers,
ServerName: serverName,
KeyLogWriter: keyLogWriter,
MaxVersion: maxVersion,
})
if err != nil {
if *verboseLevel > 2 {
fmt.Printf("Error connecting to %s: %v\n", serverName, err)
}
return
}
conn.Close()
availableCipher = cbcSuiteByID(conn.ConnectionState().CipherSuite)
protocolVersion = conn.ConnectionState().Version
return
}
func testCipher(hostname, serverName string, cipherId, protocolVersion uint16) (responseLengths [testCount]int, responseSizeProfile, errorStrings [testCount]string, err error) {
var (
selectedCipher = cbcSuiteByID(cipherId)
macLen = selectedCipher.macLen
blockLen = selectedCipher.blockLen
errorList, secondErrorList [testCount]error
secondResponseLengths [testCount]int
secondResponseSizeProfile [testCount]string
uniqueLengthCount int = 0
uniqueSecondLengthCount int = 0
responseBuffers, secondResponseBuffers [testCount][16384]byte
)
testNames := [testCount]string{"Invalid MAC/Valid Pad", "Missing MAC/Incomplete Pad", "Valid MAC/Invalid Pad", "Missing MAC/Valid Pad", "Invalid Mac/Valid Pad (0-length record)"}
keyLogWriter, err := os.OpenFile(*keyLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return
}
dialer := net.Dialer{
Timeout: 5 * time.Second,
}
// An HTTP request is prepared to have a full block of padding required
requestData := fmt.Sprintf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", serverName)
overrun := (len(requestData) + macLen) % blockLen
if overrun > 0 {
requestData = fmt.Sprintf("GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", strings.Repeat("a", blockLen-overrun), serverName)
}
if *verboseLevel >= 1 {
fmt.Printf("%s (%s) is being tested for oracles with cipher 0x%04x using TLS 0x%04x\n", serverName, hostname, cipherId, protocolVersion)
}
for i := 0; i < testCount; i++ {
// Establish connection with padding mode option
conn, connErr := tls.DialWithDialer(&dialer, "tcp", hostname, &tls.Config{
InsecureSkipVerify: true,
PaddingMode: i + 1,
KeyLogWriter: keyLogWriter,
ServerName: serverName,
CipherSuites: []uint16{cipherId},
MinVersion: protocolVersion,
MaxVersion: protocolVersion,
})
if connErr != nil {
err = connErr
return
}
// Send the request and set a timeout for reading the response
conn.Write([]byte(requestData))
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
// Read from the socket
responseLengths[i], errorList[i] = conn.Read(responseBuffers[i][:])
secondResponseLengths[i], secondErrorList[i] = conn.Read(secondResponseBuffers[i][:])
errClose := conn.Close()
// Response lengths must be normalized into letters for comparison
// 1) Initialize value with empty string
// 2) Iterate over responseLengths for matching length
// 3) Use ID from matching responseSizeProfile if lengths match
// 4) If responseSizeProfile is not set, assign next letter for length
responseSizeProfile[i] = ""
for w := 0; w < i; w++ {
if responseLengths[i] == responseLengths[w] {
responseSizeProfile[i] = responseSizeProfile[w]
break
}
}
if responseSizeProfile[i] == "" {
responseSizeProfile[i] = string(65 + uniqueLengthCount)
uniqueLengthCount++
}
// Deal with secondResponseProfile
secondResponseSizeProfile[i] = ""
for w := 0; w < i; w++ {
if secondResponseLengths[i] == secondResponseLengths[w] {
secondResponseSizeProfile[i] = secondResponseSizeProfile[w]
break
}
}
if secondResponseSizeProfile[i] == "" {
secondResponseSizeProfile[i] = string(65 + uniqueLengthCount)
uniqueSecondLengthCount++
}
//responseSizeProfile[i] += secondResponseSizeProfile[i]
secondErrString := ""
// Error message is converted to a string
if secondErrorList[i] != nil {
if secondErrorList[i] != errorList[i] {
r, _ := regexp.Compile(".*read: ")
errString := string(r.ReplaceAll([]byte(fmt.Sprintf("%v", secondErrorList[i])), []byte("")))
secondErrString = fmt.Sprintf("+%v", errString)
} else {
secondErrString = "+"
}
}
if errClose == nil {
errorStrings[i] = fmt.Sprintf("%v%s", errorList[i], secondErrString)
} else {
r, _ := regexp.Compile(".*write: ")
errString := string(r.ReplaceAll([]byte(fmt.Sprintf("%v", errClose)), []byte("")))
if strings.HasPrefix(errorStrings[i], errString) {
errorStrings[i] = fmt.Sprintf("%v%s+", errorList[i], secondErrString)
} else {
errorStrings[i] = fmt.Sprintf("%v%s+%v", errorList[i], secondErrString, errString)
}
if *verboseLevel > 2 {
fmt.Printf("%s (%s) error on close: %s\n", serverName, hostname, errString)
}
}
// Error messages must be normalized for comparison
// IP address / port number info must be stripped
if strings.HasPrefix(errorStrings[i], "read tcp") {
if strings.Contains(errorStrings[i], "timeout") {
errorStrings[i] = "Timeout"
} else if strings.Contains(errorStrings[i], "reset") {
errorStrings[i] = "Reset"
} else {
if *verboseLevel >= 5 {
fmt.Printf("WARN: %s|%s - Received unexpected error '%v' on padding mode %d\n", hostname, serverName, i+1)
}
errorStrings[i] = "Unknown TCP Error"
}
}
// Print test status if using high verbosity
if *verboseLevel >= 5 {
fmt.Printf("\t%s Test\n\t\tResponse Length: %v(%s)\n\t\tError: %v\n\t\tSecond Error: %v\n\t\tClose Error:%v\n", testNames[i], responseLengths[i], responseSizeProfile[i], errorList[i], secondErrorList[i], errClose)
if responseLengths[i] > 0 {
fmt.Printf("\tDecrypted Data (up to 256 bytes):\n%s\n", responseBuffers[i][0:256])
}
fmt.Println()
}
conn.Close()
}
return
}
func analyzeResponseProfile(hostname, serverName string, responseLengths [testCount]int, responseSizeProfile, errorStrings [testCount]string) (isVulnerable, isPoodle, isGoldenDoodle, isZombiePoodle, isZeroLength, isObservable bool, errorPrint, lengthPrint string, err error) {
// Decrypted response length should be zero for all tests
for i := 0; i < testCount; i++ {
if responseLengths[i] > 0 {
isVulnerable = true
isObservable = true
if i == 0 {
// Non-zero response length for valid padding with invalid MAC: GOLDENDOODLE
isGoldenDoodle = true
}
if i == 2 {
// Non-zero response length for invalid padding with valid MAC: POODLE
isPoodle = true
}
}
}
var uniqueErrorCount int
var messageHeader string
if *verboseLevel > 1 {
messageHeader = "\t"
} else {
messageHeader = fmt.Sprintf("%s (%s)\t\t", serverName, hostname)
}
for i := 1; i < testCount; i++ {
if errorStrings[i] != errorStrings[0] {
uniqueErrorCount++
isFirstRemote := strings.HasPrefix(errorStrings[0], "remote error: tls:")
isCurrentRemote := strings.HasPrefix(errorStrings[i], "remote error: tls:")
if *verboseLevel > 1 {
fmt.Printf("%sDistinct error observed. Error[0]==%v, Error[%d]==%v\n", messageHeader, errorStrings[0], i, errorStrings[i])
if isCurrentRemote && isFirstRemote {
fmt.Printf("%sThis may oracle may not be observable to the attacker.\n", messageHeader)
}
}
isVulnerable = true
if !(isCurrentRemote && isFirstRemote) {
isObservable = true
}
if i == 2 {
// Unique error on invalid padding with valid MAC: likely Zombie POODLE
isZombiePoodle = true
}
if i == 3 {
isZeroLength = true
}
}
}
if isVulnerable && *verboseLevel > 0 {
fmt.Println()
}
if uniqueErrorCount == testCount-1 {
// Distinct error for valid padding with invalid MAC: GOLDENDOODLE
isGoldenDoodle = true
}
// Generating a checksum makes for easier comparison across iterations
errorMap := []byte(fmt.Sprintf("%v/%v/%v/%v/%v", errorStrings[0], errorStrings[1], errorStrings[2], errorStrings[3], errorStrings[4]))
shasum := sha1.New()
shasum.Write(errorMap)
errorPrint = fmt.Sprintf("%x", shasum.Sum(nil))
lengthMap := []byte(fmt.Sprintf("%v/%v/%v/%v/%v", responseSizeProfile[0], responseSizeProfile[1], responseSizeProfile[2], responseSizeProfile[3], responseSizeProfile[4]))
shasum = sha1.New()
shasum.Write(lengthMap)
lengthPrint = fmt.Sprintf("%x", shasum.Sum(nil))
return
}
func scanHost(hostname, serverName string, cipherIndex int) error {
allCiphers := []uint16{
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
}
cipherList := []uint16{allCiphers[cipherIndex]}
availableCipher, availableProtocol, err := SupportedCipherTest(hostname, serverName, cipherList, 0x0303)
if err != nil {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) had an unexpected connection failure: %v (cipher 0x%04x)\n", serverName, hostname, err, cipherList[0])
}
return err
}
if *verboseLevel > 1 {
fmt.Printf("%s (%s) using TLS 0x%04x supports cipher 0x%04x which uses CBC.\n", serverName, hostname, availableProtocol, availableCipher.id)
}
var (
lastErrorPrint, lastLengthPrint string
isVulnerable, isPoodle, isGoldenDoodle, isZombiePoodle, isObservable, isZeroLength bool
errorPrint, lengthPrint string
responseLengths [testCount]int
responseSizeProfile, errorStrings [testCount]string
)
for iteration := 0; iteration < *iterationCount; iteration++ {
// Connect to target with identified cipher and test each malformed record case
responseLengths, responseSizeProfile, errorStrings, err = testCipher(hostname, serverName, availableCipher.id, availableProtocol)
if err != nil {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) encountered the following error while testing cipher 0x%04x: %v\n", serverName, hostname, availableCipher.id, err)
}
return err
}
// Analyze the response profile for oracles
isVulnerable, isPoodle, isGoldenDoodle, isZombiePoodle, isZeroLength, isObservable, errorPrint, lengthPrint, err = analyzeResponseProfile(hostname, serverName, responseLengths, responseSizeProfile, errorStrings)
if isVulnerable != true {
if iteration > 0 {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) exhibited an oracle which did not appear on iteration %d. (Not exploitable)\n", serverName, hostname, iteration)
}
return errors.New("Oracle disappeared")
}
return nil
}
if lastErrorPrint != "" {
if lastErrorPrint != errorPrint {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) has an inconsistent error oracle response. (Maybe exploitable)\n", serverName, hostname)
}
return errors.New("Inconsistent error responses")
}
} else {
lastErrorPrint = errorPrint
}
if lastLengthPrint != "" {
if lastLengthPrint != lengthPrint {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) has an inconsistent response length profile\n (Maybe exploitable)", serverName, hostname)
}
return errors.New("Inconsistent length responses")
}
} else {
lastLengthPrint = lengthPrint
}
}
if isVulnerable {
var vulnTag string
if isObservable {
vulnTag = "Observable "
}
if isGoldenDoodle {
vulnTag += "Padding Validity (GOLDENDOODLE)"
} else if isZombiePoodle {
vulnTag += "MAC Validity (Zombie POODLE)"
} else if isPoodle {
vulnTag += "MAC validity (POODLE or 'sleeping' POODLE)"
} else if isZeroLength {
vulnTag += "Incomplete or Missing MAC"
} else {
vulnTag += "unkown"
}
respLenTag := strings.Join(responseSizeProfile[:], "/")
respLenRaw := fmt.Sprintf("%v/%v/%v/%v", responseLengths[0], responseLengths[1], responseLengths[2], responseLengths[3])
errMsgTag := strings.Join(errorStrings[:], "/")
shortPrint := errorPrint[0:3] + lengthPrint[0:3]
fmt.Printf("%s (%s) is VULNERABLE with a %s oracle when using cipher 0x%04x with TLS 0x%04x. The fingerprint is %s\n", serverName, hostname, vulnTag, availableCipher.id, availableProtocol, shortPrint)
if *verboseLevel <= 1 {
fmt.Printf("%s (%s) error profile: ^%v^ and response size profile ^%v^\n", serverName, hostname, errMsgTag, respLenTag)
} else {
fmt.Printf("The following responses were observed:\n")
fmt.Printf("\tLengths:%s(%s)\n\tErrors:%s\n", respLenRaw, respLenTag, errMsgTag)
fmt.Printf("\tLength Hash:%v\n\tError Hash:%v\n", lengthPrint, errorPrint)
}
} else {
if *verboseLevel > 0 {
fmt.Printf("%s (%s) behaves securely\n", serverName, hostname)
}
}
return nil
}
func worker(hosts <-chan string, done *sync.WaitGroup) {
defer done.Done()
for hostname := range hosts {
var targetHost string
var hostnameParts []string
// Attempt to find hostname and port from argument
host, port, err := net.SplitHostPort(hostname)
if err == nil {
hostnameParts = []string{host, port}
} else {
// If bare hostname is IPv6, remove any supplied brackets
hostname = strings.Replace(hostname, "[", "", -1)
hostname = strings.Replace(hostname, "]", "", -1)
// Default to HTTPS
hostnameParts = []string{hostname, "443"}
}
address := ""
// Determine if the host is not an IPv4 or IPv6 address
if net.ParseIP(hostnameParts[0]) == nil {
// Host appears to be an FQDN
addressList, err := net.LookupIP(hostnameParts[0])
if err != nil {
if *verboseLevel > 2 {
fmt.Printf("Error resolving %s [error: %s]\n", hostname, err)
continue
}
}
if len(addressList) == 0 {
if *verboseLevel > 0 {
fmt.Printf("ERROR: No address associated with %s\n", hostnameParts[0])
}
continue
}
for i := 0; i < len(addressList); i++ {
if addressList[i].To4() != nil || addressList[i].To16() != nil {
address = addressList[i].String()
// If the hostname resolves to an IPv6 address make sure it is properly formatted
if addressList[i].To16() != nil {
address = "[" + address + "]"
}
break
}
}
if address == "" {
continue
}
} else {
// Host appars to be an IP address
if net.ParseIP(hostnameParts[0]) != nil && strings.Contains(hostnameParts[0], ":") {
// If the hostname is an IPv6 address make sure it is properly formatted
hostnameParts[0] = "[" + hostnameParts[0] + "]"
}
address = hostnameParts[0]
}
targetHost = fmt.Sprintf("%s:%s", address, hostnameParts[1])
for cipherIndex := 0; cipherIndex < len(cbcSuites); cipherIndex++ {
err := scanHost(targetHost, hostnameParts[0], cipherIndex)
if err != nil {
if *verboseLevel >= 5 {
fmt.Fprintf(os.Stderr, "%s: %s\n", hostname, err)
}
}
}
continue
}
}
func main() {
flag.Parse()
var wg sync.WaitGroup
var numWorkers = *workerCount
hostnames := make(chan string, numWorkers)
if *verboseLevel == 0 {
fmt.Fprintf(os.Stderr, "Quiet Mode Enabled: Only vulnerable hosts will be reported.\n")
}
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go worker(hostnames, &wg)
}
if len(*hostsFile) == 0 {
for _, hostname := range os.Args[len(os.Args)-1:] {
hostnames <- hostname
}
}
if *showHelp {
fmt.Fprintf(os.Stderr, "This tool tests how a server responds to various CBC padding errors.\n\nFive HTTPS GET requests will be made to the target with different padding modes.\nFirst a good padding and then the errors:\n\t1 - Invalid MAC with Valid Padding (0-length pad)\n\t2 - Missing MAC with Incomplete/Invalid Padding (255-length pad)\n\t3 - Typical POODLE condition (incorrect bytes followed by correct length)\n\t4 - All padding bytes set to 0x80 (integer overflow attempt)\n\nA file containing a list of hosts to scanned with worker threads can be specified via -hosts\n")
os.Exit(0)
}
if len(*hostsFile) > 0 {
hosts, err := os.Open(*hostsFile)
if *verboseLevel == 1 {
*verboseLevel = 0
}
if err != nil {
panic(err)
}
defer hosts.Close()
inHosts := bufio.NewScanner(hosts)
for inHosts.Scan() {
hostnames <- inHosts.Text()
}
if err := inHosts.Err(); err != nil {
panic(err)
}
}
close(hostnames)
wg.Wait()
}