-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmain.go
More file actions
689 lines (588 loc) · 18.3 KB
/
main.go
File metadata and controls
689 lines (588 loc) · 18.3 KB
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
package main
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"math/big"
"net"
"net/http"
"net/netip"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/flynn/noise"
"golang.org/x/crypto/blake2s"
"golang.org/x/crypto/curve25519"
)
var (
asnsToFilter = []int{
13335,
209242,
14789,
202623,
203898,
394536,
395747,
139242,
132892,
}
url = "https://bgp.tools/table.jsonl" // URL for the JSONL table dump
userAgent = "compassvpn-cf-tools bgp.tools" // Custom User-Agent header
)
const (
ConcurrentPrefixes = 55 // Number of Concurrencies
RetryCount = 4 // Number of retries if one checker fails
RetryDelay = 1 * time.Second // Delay between each retry
RequestTimeout = 4 * time.Second // Timeout delay
TestIPIncrement1 = 8 // First IP to check in a /24 prefix (Changed from 13 to 8)
TestIPIncrement2 = 13 // Second IP to check in a /24 prefix
TestIPIncrement3 = 69 // Third IP to check in a /24 prefix
TestIPIncrement4 = 144 // Fourth IP to check in a /24 prefix
TestIPIncrement5 = 234 // Fifth IP to check in a /24 prefix
defaultInputFile = "all_cf_v4.txt" // Default output file name: All CloudFlare IPv4 ranges converted to /24 prefixes
defaultCDNOutputFile = "all_cdn_v4.txt" // Default output file name: All CloudFlare CDN IPv4 with /24 prefixes
defaultWARPOutputFile = "all_warp_v4.txt" // Default output file name: All CloudFlare WARP IPv4 with /24 prefixes
// WARP Wireguard configurations
privateKeyB64 = "0ALZyBx68KO4by/oQR+3kmPpYbrOuq605aBYv5GKU0Y="
publicKeyB64 = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
presharedKeyB64 = ""
)
var (
httpClient = &http.Client{Timeout: RequestTimeout}
scanPorts = []int{2408} // List of ports to scan WARP. Example: {2408, 7559, 2371, 894, ...}
)
// Prefix structure for JSON parsing
type Prefix struct {
CIDR netip.Prefix `json:"CIDR"`
ASN int `json:"ASN"`
}
// Holds the result of prefix processing
type PrefixResult struct {
Prefix netip.Prefix
IsValid bool
}
// Helper function to show usage
func showHelp() {
fmt.Println("Usage:")
fmt.Println(" -h, --help Show help")
fmt.Println(" -f, --fetch Fetch and convert to /24 only")
fmt.Println(" -c, --cdn Run the CDN checker")
fmt.Println(" -w, --warp Run the WARP checker")
fmt.Println(" -o, --output Specify the output file name")
}
// Fetches the prefixes from the URL and filters them by the given ASNs
func fetchAndFilterPrefixes(url string, asns []int) ([]netip.Prefix, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
// Set the custom User-Agent header
req.Header.Set("User-Agent", userAgent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close()
// Check for non-200 status codes
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-200 status code %d", resp.StatusCode)
}
var v4Prefixes []netip.Prefix
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
var prefix Prefix
line := scanner.Text()
// Decode each JSON object
if err := json.Unmarshal([]byte(line), &prefix); err != nil {
fmt.Printf("Error decoding JSON line: %v\n", err)
continue
}
// Filter for the specified ASNs and store IPv4 prefixes
isTargetASN := false
for _, asn := range asns {
if prefix.ASN == asn {
isTargetASN = true
break
}
}
if isTargetASN && !prefix.CIDR.Addr().Is6() {
v4Prefixes = append(v4Prefixes, prefix.CIDR)
}
}
// Check for errors during scanning
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scanning response: %w", err)
}
return v4Prefixes, nil
}
// Converts the prefixes to /24 blocks and writes them to the output file
func convertTo24AndWrite(prefixes []netip.Prefix, outputFile string) error {
outFile, err := os.Create(outputFile)
if err != nil {
return fmt.Errorf("creating output file: %w", err)
}
defer outFile.Close()
writer := bufio.NewWriter(outFile)
defer writer.Flush()
unique24s := make(map[string]struct{})
var wg sync.WaitGroup
prefixChan := make(chan string, len(prefixes))
// Process each prefix in a separate goroutine
for _, prefix := range prefixes {
wg.Add(1)
go func(p netip.Prefix) {
defer wg.Done()
processPrefix(p, prefixChan)
}(prefix)
}
// Close the channel once all processing is done
go func() {
wg.Wait()
close(prefixChan)
}()
// Collect processed prefixes
var sortedPrefixes []string
for line := range prefixChan {
if _, exists := unique24s[line]; !exists {
unique24s[line] = struct{}{}
sortedPrefixes = append(sortedPrefixes, line)
}
}
// Sort prefixes
sort.Slice(sortedPrefixes, func(i, j int) bool {
return compareIPs(sortedPrefixes[i], sortedPrefixes[j])
})
for _, prefix := range sortedPrefixes {
if _, err := writer.WriteString(prefix + "\n"); err != nil {
return fmt.Errorf("writing to output file: %w", err)
}
}
return nil
}
// Compares two IP addresses based on the first three octets
func compareIPs(ip1, ip2 string) bool {
parts1 := strings.Split(ip1, ".")
parts2 := strings.Split(ip2, ".")
for i := 0; i < 3; i++ {
num1, _ := strconv.Atoi(parts1[i])
num2, _ := strconv.Atoi(parts2[i])
if num1 != num2 {
return num1 < num2
}
}
return false
}
// Processes a single prefix and sends /24 blocks to the channel
func processPrefix(prefix netip.Prefix, prefixChan chan<- string) {
ip := prefix.Addr()
prefixLen := prefix.Bits()
// Directly send /24 prefixes
if prefixLen == 24 {
prefixChan <- prefix.String()
return
}
ipInt := ipToInt(ip)
numBlocks := 1 << (24 - prefixLen)
for i := 0; i < numBlocks; i++ {
ip := intToIP(ipInt)
net24 := netip.PrefixFrom(ip, 24).String()
prefixChan <- net24
incrementIPBy24(ipInt)
}
}
// Converts an IP address to a big integer
func ipToInt(ip netip.Addr) *big.Int {
ipInt := big.NewInt(0)
ipInt.SetBytes(ip.AsSlice())
return ipInt
}
// Increments an IP address by one /24 block using bit shift operations
func incrementIPBy24(ipInt *big.Int) {
increment := big.NewInt(1 << 8) // 256 for /24
ipInt.Add(ipInt, increment)
}
// Converts a big integer back to an IP address
func intToIP(ipInt *big.Int) netip.Addr {
ipBytes := make([]byte, 4)
ipInt.FillBytes(ipBytes)
ip, _ := netip.AddrFromSlice(ipBytes)
return ip
}
// Checks if an IP address responds with StatusOK for the CDN trace URL.
func isValidCDNIP(ip netip.Addr) bool {
url := fmt.Sprintf("http://%s/cdn-cgi/trace", ip)
for i := 0; i < RetryCount; i++ {
resp, err := httpClient.Head(url)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return true
}
}
time.Sleep(RetryDelay)
}
return false
}
// Increments the given IP address by a specified value.
func incrementIP(ip netip.Addr, increment int) netip.Addr {
ipBytes := ip.As4()
ipUint := uint32(ipBytes[0])<<24 | uint32(ipBytes[1])<<16 | uint32(ipBytes[2])<<8 | uint32(ipBytes[3])
ipUint += uint32(increment)
newIP := netip.AddrFrom4([4]byte{byte(ipUint >> 24), byte(ipUint >> 16), byte(ipUint >> 8), byte(ipUint)})
return newIP
}
// Checks if any IP within the prefix is a CDN IP.
func processPrefixCDN(prefix netip.Prefix) bool {
baseIP := prefix.Addr()
testIP1 := incrementIP(baseIP, TestIPIncrement1)
testIP2 := incrementIP(baseIP, TestIPIncrement2)
testIP3 := incrementIP(baseIP, TestIPIncrement3)
testIP4 := incrementIP(baseIP, TestIPIncrement4)
testIP5 := incrementIP(baseIP, TestIPIncrement5)
return isValidCDNIP(testIP1) || isValidCDNIP(testIP2) || isValidCDNIP(testIP3) || isValidCDNIP(testIP4) || isValidCDNIP(testIP5)
}
// Processes each prefix and sends the result to the channel.
func parallelFunctionCDN(ipChannel chan PrefixResult, prefix netip.Prefix) {
isValid := processPrefixCDN(prefix)
ipChannel <- PrefixResult{
Prefix: prefix,
IsValid: isValid,
}
}
// Generates a static keypair from a base64-encoded private key
func staticKeypair(privateKeyBase64 string) (noise.DHKey, error) {
privateKey, err := base64.StdEncoding.DecodeString(privateKeyBase64)
if err != nil {
return noise.DHKey{}, err
}
var pubkey, privkey [32]byte
copy(privkey[:], privateKey)
curve25519.ScalarBaseMult(&pubkey, &privkey)
return noise.DHKey{
Private: privateKey,
Public: pubkey[:],
}, nil
}
// Generates an ephemeral keypair
func ephemeralKeypair() (noise.DHKey, error) {
ephemeralPrivateKey := make([]byte, 32)
if _, err := rand.Read(ephemeralPrivateKey); err != nil {
return noise.DHKey{}, err
}
ephemeralPublicKey, err := curve25519.X25519(ephemeralPrivateKey, curve25519.Basepoint)
if err != nil {
return noise.DHKey{}, err
}
return noise.DHKey{
Private: ephemeralPrivateKey,
Public: ephemeralPublicKey,
}, nil
}
// Converts a uint32 to a byte slice
func uint32ToBytes(n uint32) []byte {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, n)
return b
}
// Initiates a handshake with the server and returns the round-trip time (RTT)
func initiateHandshake(serverAddr netip.AddrPort, privateKeyBase64, peerPublicKeyBase64, presharedKeyBase64 string) (time.Duration, error) {
staticKeyPair, err := staticKeypair(privateKeyBase64)
if err != nil {
return 0, err
}
peerPublicKey, err := base64.StdEncoding.DecodeString(peerPublicKeyBase64)
if err != nil {
return 0, err
}
presharedKey, err := base64.StdEncoding.DecodeString(presharedKeyBase64)
if err != nil {
return 0, err
}
if presharedKeyBase64 == "" {
presharedKey = make([]byte, 32)
}
ephemeral, err := ephemeralKeypair()
if err != nil {
return 0, err
}
cs := noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashBLAKE2s)
hs, err := noise.NewHandshakeState(noise.Config{
CipherSuite: cs,
Pattern: noise.HandshakeIK,
Initiator: true,
StaticKeypair: staticKeyPair,
PeerStatic: peerPublicKey,
Prologue: []byte("WireGuard v1 zx2c4 Jason@zx2c4.com"),
PresharedKey: presharedKey,
PresharedKeyPlacement: 2,
EphemeralKeypair: ephemeral,
Random: rand.Reader,
})
if err != nil {
return 0, err
}
now := time.Now().UTC()
epochOffset := int64(4611686018427387914) // TAI offset from Unix epoch
tai64nTimestampBuf := make([]byte, 0, 16)
tai64nTimestampBuf = binary.BigEndian.AppendUint64(tai64nTimestampBuf, uint64(epochOffset+now.Unix()))
tai64nTimestampBuf = binary.BigEndian.AppendUint32(tai64nTimestampBuf, uint32(now.Nanosecond()))
msg, _, _, err := hs.WriteMessage(nil, tai64nTimestampBuf)
if err != nil {
return 0, err
}
initiationPacket := new(bytes.Buffer)
binary.Write(initiationPacket, binary.BigEndian, []byte{0x01, 0x00, 0x00, 0x00})
binary.Write(initiationPacket, binary.BigEndian, uint32ToBytes(28))
binary.Write(initiationPacket, binary.BigEndian, msg)
macKey := blake2s.Sum256(append([]byte("mac1----"), peerPublicKey...))
hasher, err := blake2s.New128(macKey[:])
if err != nil {
return 0, err
}
_, err = hasher.Write(initiationPacket.Bytes())
if err != nil {
return 0, err
}
initiationPacketMAC := hasher.Sum(nil)
binary.Write(initiationPacket, binary.BigEndian, initiationPacketMAC[:16])
binary.Write(initiationPacket, binary.BigEndian, [16]byte{})
conn, err := net.Dial("udp", serverAddr.String())
if err != nil {
return 0, err
}
defer conn.Close()
_, err = initiationPacket.WriteTo(conn)
if err != nil {
return 0, err
}
t0 := time.Now()
response := make([]byte, 92)
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
i, err := conn.Read(response)
if err != nil {
return 0, err
}
rtt := time.Since(t0)
if i < 60 {
return 0, fmt.Errorf("invalid handshake response length %d bytes", i)
}
if response[0] != 2 {
return 0, errors.New("invalid response type")
}
ourIndex := binary.LittleEndian.Uint32(response[8:12])
if ourIndex != 28 {
return 0, errors.New("invalid sender index in response")
}
payload, _, _, err := hs.ReadMessage(nil, response[12:60])
if err != nil {
return 0, err
}
if len(payload) != 0 {
return 0, errors.New("unexpected payload in response")
}
return rtt, nil
}
// Checks if an IP address responds with StatusOK for the WARP trace URL on any of the given ports
func isValidWarpIP(ip netip.Addr) bool {
for _, port := range scanPorts {
ip2 := netip.AddrPortFrom(ip, uint16(port))
for i := 0; i < RetryCount; i++ {
_, err := initiateHandshake(ip2, privateKeyB64, publicKeyB64, presharedKeyB64)
if err == nil {
return true
}
time.Sleep(RetryDelay)
}
}
return false
}
// Checks if any IP within the prefix is a WARP IP
func processPrefixWARP(prefix netip.Prefix) bool {
baseIP := prefix.Addr()
testIP1 := incrementIP(baseIP, TestIPIncrement1)
testIP2 := incrementIP(baseIP, TestIPIncrement2)
testIP3 := incrementIP(baseIP, TestIPIncrement3)
testIP4 := incrementIP(baseIP, TestIPIncrement4)
testIP5 := incrementIP(baseIP, TestIPIncrement5)
return isValidWarpIP(testIP1) || isValidWarpIP(testIP2) || isValidWarpIP(testIP3) || isValidWarpIP(testIP4) || isValidWarpIP(testIP5)
}
// Processes each prefix and sends the result to the channel
func parallelFunctionWARP(ipChannel chan PrefixResult, prefix netip.Prefix) {
isValid := processPrefixWARP(prefix)
ipChannel <- PrefixResult{
Prefix: prefix,
IsValid: isValid,
}
}
func main() {
// Define flags
helpFlag := flag.Bool("h", false, "Show help")
helpFlagLong := flag.Bool("help", false, "Show help")
cdnFlag := flag.Bool("c", false, "Run the CDN checker")
cdnFlagLong := flag.Bool("cdn", false, "Run the CDN checker")
warpFlag := flag.Bool("w", false, "Run the WARP checker")
warpFlagLong := flag.Bool("warp", false, "Run the WARP checker")
fetchFlag := flag.Bool("f", false, "Fetch and convert to /24 only")
fetchFlagLong := flag.Bool("fetch", false, "Fetch and convert to /24 only")
outputFile := flag.String("o", "", "Specify the output file name")
outputFileLong := flag.String("output", "", "Specify the output file name")
flag.Parse()
// If no flag is provided, show help
if !*helpFlag && !*helpFlagLong && !*cdnFlag && !*cdnFlagLong && !*warpFlag && !*warpFlagLong && !*fetchFlag && !*fetchFlagLong {
showHelp()
return
}
if *helpFlag || *helpFlagLong {
showHelp()
return
}
// Fetch and filter the prefixes
v4Prefixes, err := fetchAndFilterPrefixes(url, asnsToFilter)
if err != nil {
fmt.Printf("Error fetching and filtering prefixes: %v\n", err)
return
}
// Determine the output file
output := defaultInputFile
if *outputFile != "" {
output = *outputFile
}
if *outputFileLong != "" {
output = *outputFileLong
}
// Convert the prefixes to /24 and write to the intermediate file
err = convertTo24AndWrite(v4Prefixes, output)
if err != nil {
fmt.Printf("Error converting to /24 and writing to file: %v\n", err)
return
}
// If fetch-only flag is set, exit after converting and writing the prefixes
if *fetchFlag || *fetchFlagLong {
fmt.Println("Prefixes fetched and converted to /24. Output written to", output)
return
}
// Open intermediate file containing IP prefixes
file, err := os.Open(output)
if err != nil {
fmt.Printf("Error opening file: %v\n", err)
return
}
defer file.Close()
// Read all prefixes and store them in a map to avoid duplicates
prefixSet := make(map[string]struct{})
scanner := bufio.NewScanner(file)
for scanner.Scan() {
prefixString := scanner.Text()
prefixSet[prefixString] = struct{}{}
}
// Convert the map keys back to a slice
var prefixes []netip.Prefix
for prefixString := range prefixSet {
prefix, err := netip.ParsePrefix(prefixString)
if err == nil {
prefixes = append(prefixes, prefix)
}
}
if *cdnFlag || *cdnFlagLong {
output := defaultCDNOutputFile
if *outputFile != "" {
output = *outputFile
}
if *outputFileLong != "" {
output = *outputFileLong
}
// Create output file for valid CDN IP prefixes
outputFile, err := os.Create(output)
if err != nil {
fmt.Printf("Error creating output file: %v\n", err)
return
}
defer outputFile.Close()
ipChannel := make(chan PrefixResult)
sem := make(chan struct{}, ConcurrentPrefixes)
// Process prefixes concurrently with limited concurrency
go func() {
for _, prefix := range prefixes {
sem <- struct{}{}
go func(prefix netip.Prefix) {
defer func() { <-sem }()
parallelFunctionCDN(ipChannel, prefix)
}(prefix)
}
}()
var validPrefixes []string
// Collect results and store valid prefixes
for i := 0; i < len(prefixes); i++ {
result := <-ipChannel
if result.IsValid {
fmt.Printf("Valid CDN Prefix: %v\n", result.Prefix)
validPrefixes = append(validPrefixes, result.Prefix.String())
}
}
close(ipChannel)
// Sort and write valid prefixes to the output file
sort.Slice(validPrefixes, func(i, j int) bool {
return compareIPs(validPrefixes[i], validPrefixes[j])
})
for _, prefix := range validPrefixes {
outputFile.WriteString(prefix + "\n")
}
fmt.Println("Processing complete. Valid /24 prefixes have been written to", output)
}
if *warpFlag || *warpFlagLong {
output := defaultWARPOutputFile
if *outputFile != "" {
output = *outputFile
}
if *outputFileLong != "" {
output = *outputFileLong
}
// Create output file for valid WARP IP prefixes
outputFile, err := os.Create(output)
if err != nil {
fmt.Printf("Error creating output file: %v\n", err)
return
}
defer outputFile.Close()
ipChannel := make(chan PrefixResult)
sem := make(chan struct{}, ConcurrentPrefixes)
// Process prefixes concurrently with limited concurrency
go func() {
for _, prefix := range prefixes {
sem <- struct{}{}
go func(prefix netip.Prefix) {
defer func() { <-sem }()
parallelFunctionWARP(ipChannel, prefix)
}(prefix)
}
}()
var validPrefixes []string
// Collect results and store valid prefixes
for i := 0; i < len(prefixes); i++ {
result := <-ipChannel
if result.IsValid {
fmt.Printf("Valid WARP Prefix: %v\n", result.Prefix)
validPrefixes = append(validPrefixes, result.Prefix.String())
}
}
close(ipChannel)
// Sort and write valid prefixes to the output file
sort.Slice(validPrefixes, func(i, j int) bool {
return compareIPs(validPrefixes[i], validPrefixes[j])
})
for _, prefix := range validPrefixes {
outputFile.WriteString(prefix + "\n")
}
fmt.Println("Processing complete. Valid /24 prefixes have been written to", output)
}
}