-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm_core.py
More file actions
1891 lines (1597 loc) · 73.7 KB
/
Copy pathvm_core.py
File metadata and controls
1891 lines (1597 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
vm_core.py v2.0 | Enhanced VM Detection Library
Core VM detection library (importable)
Targets Python 3.12+
__Author__ = therealOri
__Enhancements__ = CPUID access, cloud probing, container detection, parallel gathering, tiered scoring
"""
from __future__ import annotations
import os
import platform
import subprocess
import sys
import re
import socket
import time
import threading
import ctypes
from typing import Dict, List, Set, Optional, Any, Callable, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
try:
import psutil
except Exception:
psutil = None
# Cloud probe dependency (optional)
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# For Windows-only registry stuff
if platform.system() == "Windows":
try:
import winreg
except Exception:
winreg = None
# ============================================================
# Direct CPUID Module Setup
# ============================================================
# Comment out if you don't want to use the compiled libcpuid.so (Linux) or cpuid.dll (Windows) file. -> [compiled from cpuid.c]
try:
_CPUID_LIB_LOADED = False
if platform.system() == "Linux":
_CPUID_PATH = "libcpuid.so"
if os.path.exists(_CPUID_PATH):
_CPUID_LIB = ctypes.CDLL(os.path.abspath(_CPUID_PATH))
_CPUID_LIB.cpuid.argtypes = [ctypes.c_uint32, ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint32)]
_CPUID_LIB_loaded = True
elif platform.system() == "Windows":
_CPUID_PATH = "cpuid.dll"
if os.path.exists(_CPUID_PATH):
_CPUID_LIB = ctypes.CDLL(os.path.abspath(_CPUID_PATH))
_CPUID_LIB.cpuid.argtypes = [ctypes.c_uint32, ctypes.c_uint32,
ctypes.POINTER(ctypes.c_uint32)]
_CPUID_LIB_loaded = True
except NameError:
pass # ctypes not imported yet
except Exception:
_CPUID_LIB_loaded = False
def get_direct_cpuid(eax: int, ecx: int = 0) -> Tuple[int, int, int, int]:
"""
Direct CPUID instruction access via native library.
Falls back to sys/commands if unavailable.
Returns (eax, ebx, ecx, edx) values.
"""
global _CPUID_LIB_loaded
if globals().get('_CPUID_LIB_loaded', False):
out = (ctypes.c_uint32 * 4)()
try:
_CPUID_LIB.cpuid(eax, ecx, out)
return (out[0], out[1], out[2], out[3])
except Exception:
pass
# Fallback: parse from lscpu / wmic
if platform.system() == "Linux":
out = run(["lscpu"])
# Can't easily extract raw registers without parsing kernel messages
# Return placeholder indicating indirect mode
return (0, 0, 0, 0)
else:
return (0, 0, 0, 0)
# ============================================================
# Configuration & Signatures
# ============================================================
VM_PCI_VENDORS: Dict[str, List[str]] = {
"VirtualBox": ["0x80EE"],
"VMware": ["0x15AD"],
"Hyper-V": ["0x1414"],
"QEMU/KVM": ["0x1AF4", "0x1B36"],
"Parallels": ["0x1AB8"],
"Xen": ["0x5853"],
}
VM_PCI_DEVICES: Dict[str, List[str]] = {
"QEMU/KVM": ["0x29C0", "0x293E", "0x2918", "0x2922"],
"VMware": ["0x07B0", "0x07C0"],
"VirtualBox": ["0x0400"],
}
VM_PCI_SIGNATURES: Dict[str, Dict[str, Set[str]]] = {
"QEMU/KVM": {"vendors": {"1AF4", "1B36", "00DA", "1D0F"}, "devices": {"29C0", "293E", "2918", "2922", "2930"}},
"VMware": {"vendors": {"15AD"}, "devices": {"07B0", "07C0", "0790", "07A0", "0740"}},
"VirtualBox":{"vendors": {"80EE"}, "devices": {"0400", "CAFE", "BEEF"}},
"Hyper-V": {"vendors": {"1414"}, "devices": {"5353", "5801", "0700"}},
"Xen": {"vendors": {"5853"}, "devices": {"0001", "0002"}},
"Parallels": {"vendors": {"1AB8"}, "devices": {"4005", "0001"}},
}
MAC_PREFIXES: Dict[str, List[str]] = {
"VirtualBox": ["08:00:27"],
"VMware": ["00:05:69", "00:0C:29", "00:1C:14", "00:50:56"],
"Hyper-V": ["00:15:5D"],
"QEMU/KVM": ["52:54:00"],
"Parallels": ["00:1C:42"],
}
VM_CPUID_SIGS: Dict[str, str] = {
"VMware": "VMwareVMware",
"VirtualBox": "VBoxVBoxVBox",
"QEMU/KVM": "KVMKVMKVM",
"Microsoft Hv": "Microsoft Hv",
"TCGTCGTCGTCG": "TCGTCGTCGTCG", # QEMU TCG software emulation
}
VM_SOFT_KEYWORDS: Dict[str, Dict[str, List[str]]] = {
"VirtualBox": {"bios": ["virtualbox", "innotek", "oracle"], "process": ["vboxservice", "vboxtray"]},
"VMware": {"bios": ["vmware"], "process": ["vmtoolsd", "vmwaretray", "vmwareuser"]},
"Hyper-V": {"bios": ["microsoft corporation", "hyper-v"], "process": ["vmcompute", "vmguest.iso"]},
"QEMU/KVM": {"bios": ["qemu", "seabios"], "process": ["qemu-ga", "qemuguestagent"]},
"Parallels": {"bios": ["parallels"], "process": ["prltools", "prl_vm_app"]},
"Xen": {"bios": ["xen"], "process": ["xenstore", "xenconsoled"]},
}
VM_ACPI_PREFIXES = ("VBOX", "VMW", "QEMU", "XEN", "BOCHS", "VMBUS")
ACPI_SIGS: Dict[str, List[str]] = {
"VirtualBox": ["VBOX__"],
"VMware": ["VMWARE"],
"QEMU/KVM": ["QEMU"],
"Hyper-V": ["VMBUS"],
"Xen": ["XEN_"],
}
VM_DISK_VENDORS: Dict[str, List[str]] = {
"QEMU/KVM": ["QEMU", "KVM"],
"VirtualBox": ["VBOX", "VBOX_HARDDISK", "Oracle"],
"VMware": ["VMware", "VMWARE, Inc"],
"Parallels": ["Parallels"],
}
SANDBOX_PROCS = [
"sandbox", "cuckoo", "vmsrvc", "vboxservice", "vmtoolsd",
"ollydbg", "x64dbg", "x32dbg", "wireshark", "procexp", "procmon",
"remnux", "snort", "suricata", "volatility"
]
# Intel/AMD CPU specification database for thread validation
CPU_THREAD_DATABASE: Dict[str, Dict[str, Any]] = {
"Intel Core i9-13900K": {"cores": 8, "threads": 16, "ratio_max": 2.0},
"Intel Core i7-12700K": {"cores": 12, "threads": 20, "ratio_max": 1.67},
"AMD Ryzen 9 7950X": {"cores": 16, "threads": 32, "ratio_max": 2.0},
# Add more as needed, can auto-fetch online if desired
}
CLOUD_METADATA_ENDPOINTS = {
"AWS": {
"url": "http://169.254.169.254/latest/meta-data/",
"timeout_ms": 100,
"headers": {},
},
"Azure": {
"url": "http://169.254.169.254/metadata/instance?api-version=2021-02-01",
"timeout_ms": 100,
"headers": {"Metadata": "true"},
},
"GCP": {
"url": "http://metadata.google.internal/computeMetadata/v1/",
"timeout_ms": 100,
"headers": {"Metadata-Flavor": "Google"},
},
"Alibaba": {
"url": "http://100.100.100.200/latest/meta-data/",
"timeout_ms": 100,
"headers": {},
},
"DigitalOcean": {
"url": "http://169.254.169.254/metadata/v1.json",
"timeout_ms": 100,
"headers": {},
},
}
# ============================================================
# Utility Functions
# ============================================================
def run(cmd: List[str], *, text: bool = True, timeout: float = 5.0) -> str:
try:
return subprocess.check_output(cmd, stderr=subprocess.DEVNULL,
text=text, timeout=timeout) or ""
except Exception:
return ""
def _clean_hex(s: str) -> str:
if not s:
return s
s = str(s).strip()
if s.lower().startswith("0x"):
s = s[2:]
s = re.sub(r"[^0-9A-Fa-f]", "", s).upper()
if not s:
return ""
return "0x" + s.rjust(4, "0")
def _safe_read_text(path: str) -> Optional[str]:
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
except Exception:
return None
def shutil_which(cmd: str) -> bool:
try:
import shutil
return shutil.which(cmd) is not None
except Exception:
return False
# ============================================================
# Artifact Collection Class
# ============================================================
class ArtifactCollection:
def __init__(self) -> None:
self.cpu_vendor: Optional[str] = None
self.hypervisor_flag: bool = False
self.pci_vendors: List[str] = []
self.pci_devices: List[str] = []
self.acpi_tables: List[str] = []
self.acpi_signatures: List[str] = []
self.cpuid_signature: Optional[str] = None
self.cpuid_leaf_0: Optional[Tuple[int,int,int,int]] = None # Hypervisor ID
self.bios_vendor: Optional[str] = None
self.bios_brand: Optional[str] = None
self.system_product: Optional[str] = None
self.processes: List[str] = []
self.mac_prefixes: List[str] = []
self.disk_vendors: List[str] = []
self.notes: List[str] = []
# Behavioral data
self.interrupt_behavior: Dict[str, Any] = {}
self.entropy_behavior: Dict[str, Any] = {}
self.cpu_topology: Dict[str, Any] = {}
self.cache_behavior: Dict[str, Any] = {}
self.instruction_timing: Dict[str, Any] = {}
self.memory_patterns: Dict[str, Any] = {}
self.filesystem_artifacts: List[str] = []
self.hardware_quirks: List[str] = []
self.network_latency: Dict[str, Any] = {}
self.gpu_info: Dict[str, Any] = {}
self.uptime: Dict[str, Any] = {}
# NEW fields v2.0
self.container_runtime: Optional[str] = None
self.cloud_provider: Optional[str] = None
self.cloud_metadata_reachable: Dict[str, Any] = {}
self.nested_virtualization: Dict[str, Any] = {}
self.thread_validation: Dict[str, Any] = {}
self.direct_cpuid_available: bool = _CPUID_LIB_loaded if '_CPUID_LIB_loaded' in globals() else False
def to_dict(self) -> Dict[str, Any]:
return {
"cpu_vendor": self.cpu_vendor,
"hypervisor_flag": self.hypervisor_flag,
"pci_vendors": self.pci_vendors,
"pci_devices": self.pci_devices,
"acpi_tables": self.acpi_tables,
"acpi_signatures": self.acpi_signatures,
"cpuid_signature": self.cpuid_signature,
"direct_cpuid_available": self.direct_cpuid_available,
"bios_vendor": self.bios_vendor,
"bios_brand": self.bios_brand,
"system_product": self.system_product,
"processes": self.processes,
"mac_prefixes": self.mac_prefixes,
"disk_vendors": self.disk_vendors,
"container_runtime": self.container_runtime,
"cloud_provider": self.cloud_provider,
"nested_virtualization": self.nested_virtualization,
"thread_validation": self.thread_validation,
"notes": self.notes,
"interrupt_behavior": self.interrupt_behavior,
"entropy_behavior": self.entropy_behavior,
"cpu_topology": self.cpu_topology,
"cache_behavior": self.cache_behavior,
"instruction_timing": self.instruction_timing,
"memory_patterns": self.memory_patterns,
"filesystem_artifacts": self.filesystem_artifacts,
"hardware_quirks": self.hardware_quirks,
"network_latency": self.network_latency,
"gpu_info": self.gpu_info,
"uptime": self.uptime,
}
# ============================================================
# Gatherer Functions v2.0
# ============================================================
def gather_interrupt_behavior(art: ArtifactCollection) -> None:
"""Measure interrupt/jitter behavior - harder to spoof consistently."""
deltas = []
for _ in range(1000):
t0 = time.perf_counter()
time.sleep(0)
deltas.append(time.perf_counter() - t0)
jitter = max(deltas) - min(deltas)
avg_jitter = sum(deltas) / len(deltas) if deltas else 0
art.interrupt_behavior = {
"samples": len(deltas),
"jitter": jitter,
"avg_jitter_ns": avg_jitter * 1e9,
"low_jitter": jitter < 1e-6, # Tightened from 1e-5
"distribution_width": max(deltas[-100:]) - min(deltas[:100]) if len(deltas) > 200 else None,
}
def gather_entropy_behavior(art: ArtifactCollection) -> None:
"""Check entropy collection variance under hypervisors."""
timings = []
for _ in range(512):
t0 = time.perf_counter_ns()
os.urandom(64)
timings.append(time.perf_counter_ns() - t0)
variance = max(timings) - min(timings)
median_time = sorted(timings)[len(timings)//2]
art.entropy_behavior = {
"samples": len(timings),
"variance_ns": variance,
"median_ns": median_time,
"low_variance": variance < 1000000, # ← CHANGED: was 1e5
"high_outliers": sum(1 for t in timings if t > median_time * 3),
"variance_ratio": variance / median_time if median_time > 0 else 0,
}
def gather_cpu_topology(art: ArtifactCollection) -> None:
"""Detailed CPU topology including validation against specs."""
topo = {}
try:
if psutil:
topo["logical"] = psutil.cpu_count(logical=True)
topo["physical"] = psutil.cpu_count(logical=False)
else:
topo["logical"] = os.cpu_count()
topo["physical"] = None
if topo.get("physical") and topo.get("logical"):
ratio = topo["logical"] / topo["physical"]
# Changed: 6× instead of 4× threshold
topo["ratio"] = ratio
topo["suspicious_ratio"] = ratio > 6
# Check for odd core/thread counts
logical = topo.get("logical")
if logical and logical % 2 != 0:
topo["odd_thread_count"] = True
else:
topo["odd_thread_count"] = False
except Exception:
pass
art.cpu_topology = topo
def gather_cpu_vendor_with_cpuid(art: ArtifactCollection) -> None:
"""Attempt direct CPUID access for unforgeable hypervisor detection."""
art.direct_cpuid_available = _CPUID_LIB_loaded if '_CPUID_LIB_loaded' in globals() else False
# First try direct CPUID
if art.direct_cpuid_available:
# Leaf 0: Vendor string
leaf0 = get_direct_cpuid(0)
art.cpuid_leaf_0 = leaf0
# Leaf 0x1: Feature flags
leaf1 = get_direct_cpuid(1)
eax, ebx, ecx, edx = leaf1
# ECX bit 31 = Hypervisor present
art.hypervisor_flag = bool(ecx & (1 << 31))
# Leaf 0x40000000+: Hypervisor vendor strings
hyp_sig_raw = get_direct_cpuid(0x40000000)
if hyp_sig_raw[0] >= 0x40000100: # Extended leaves available
for leaf_num in range(0x40000000, min(hyp_sig_raw[0] + 1, 0x40000101)):
sig_data = get_direct_cpuid(leaf_num)
# Convert bytes to ASCII signature
sig_bytes = (sig_data[1]).to_bytes(4, 'little') + \
(sig_data[3]).to_bytes(4, 'little') + \
(sig_data[2]).to_bytes(4, 'little')
sig_str = sig_bytes.rstrip(b'\x00').decode('ascii', errors='ignore')
if sig_str and sig_str != '':
art.cpuid_signature = sig_str
break
# Fallback to existing methods
if platform.system() == "Linux":
txt = _safe_read_text("/proc/cpuinfo") or ""
m = re.search(r"vendor_id\s+:\s+(.+)", txt)
if m:
art.cpu_vendor = m.group(1).strip()
if "hypervisor" in txt.lower():
art.hypervisor_flag = True
out = run(["lscpu"])
m2 = re.search(r"Hypervisor vendor:\s*(.+)", out)
if m2 and not art.cpuid_signature:
art.cpuid_signature = m2.group(1).strip()
elif platform.system() == "Windows":
out = run(["wmic", "cpu", "get", "Manufacturer"])
lines = [l.strip() for l in out.splitlines() if l.strip()]
if len(lines) >= 2:
art.cpu_vendor = lines[1]
hv = run(["powershell", "-NoProfile", "-Command",
"(Get-CimInstance -ClassName Win32_ComputerSystem).HypervisorPresent"])
if hv and hv.strip().lower() in ("true", "1"):
art.hypervisor_flag = True
def gather_pci(art: ArtifactCollection) -> None:
"""Collect PCI vendor/device IDs across platforms."""
vendors: Set[str] = set()
devices: Set[str] = set()
system = platform.system()
if system == "Linux":
base = "/sys/bus/pci/devices/"
if os.path.isdir(base):
for dev in os.listdir(base)[:100]: # Limit scan scope
vfile = os.path.join(base, dev, "vendor")
dfile = os.path.join(base, dev, "device")
vtxt = _safe_read_text(vfile)
dtxt = _safe_read_text(dfile)
if vtxt:
v = vtxt.strip().replace("0x", "").upper()
if v:
vendors.add("0x" + v)
if dtxt:
d = dtxt.strip().replace("0x", "").upper()
if d:
devices.add("0x" + d)
if shutil_which("lspci"):
out = run(["lspci", "-nn"])
for line in out.splitlines():
m = re.search(r"\[([0-9A-Fa-f]{4}):([0-9A-Fa-f]{4})\]", line)
if m:
vendors.add("0x" + m.group(1).upper())
devices.add("0x" + m.group(2).upper())
elif system == "Windows" and winreg:
roots = [r"SYSTEM\CurrentControlSet\Enum\PCI", r"SYSTEM\ControlSet001\Enum\PCI"]
ven_re = re.compile(r"VEN_([0-9A-Fa-f]{4})", re.I)
dev_re = re.compile(r"DEV_([0-9A-Fa-f]{4})", re.I)
for root in roots:
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, root) as hroot:
count = winreg.QueryInfoKey(hroot)[0]
for i in range(min(count, 200)): # Limit iteration
try:
subname = winreg.EnumKey(hroot, i)
except OSError:
continue
mv = ven_re.search(subname)
md = dev_re.search(subname)
if mv:
vendors.add("0x" + mv.group(1).upper())
if md:
devices.add("0x" + md.group(1).upper())
except FileNotFoundError:
continue
except Exception:
continue
art.pci_vendors = sorted(vendors)
art.pci_devices = sorted(devices)
def gather_acpi_tables(art: ArtifactCollection) -> None:
"""Parse ACPI table signatures for VM fingerprints."""
if platform.system() == "Linux":
path = "/sys/firmware/acpi/tables/"
if os.path.isdir(path):
try:
tables = [f.strip() for f in os.listdir(path) if f][:50]
art.acpi_tables = sorted(tables)
sigs: Set[str] = set()
for t in tables:
for vm, patterns in ACPI_SIGS.items():
for p in patterns:
if t.upper().startswith(p.upper()):
sigs.add(f"{vm}:{t}")
art.acpi_signatures = sorted(sigs)
except Exception:
pass
def read_dmi_from_sysfs(art: ArtifactCollection) -> None:
"""Fallback reader for DMI data from /sys/class/dmi/id."""
base = "/sys/class/dmi/id/"
if not os.path.isdir(base):
return
# Read available files safely
sv = _safe_read_text(os.path.join(base, "sys_vendor")) or ""
pn = _safe_read_text(os.path.join(base, "product_name")) or ""
brn = _safe_read_text(os.path.join(base, "board_vendor")) or ""
# Update only if we actually got something new
if sv.strip():
art.bios_vendor = sv.strip()
if pn.strip():
art.system_product = pn.strip()
elif brn.strip():
# Product name sometimes absent, try board vendor instead
art.system_product = brn.strip()
def gather_bios_system(art: ArtifactCollection) -> None:
"""Collect BIOS/SMBIOS vendor/product information."""
is_root = os.geteuid() == 0
system = platform.system()
if system == "Linux":
# Step 1: Try privileged dmidecode
if shutil_which("dmidecode"):
cmd_prepend = ["sudo", "-n"] if not is_root else []
dmi_source_used = None
man = run(cmd_prepend + ["dmidecode", "-s", "system-manufacturer"])
prod = run(cmd_prepend + ["dmidecode", "-s", "system-product-name"])
found_via_sudo = False
if man.strip():
art.bios_vendor = man.strip()
found_via_sudo = True
dmi_source_used = "dmidecode" + ("-sudo" if not is_root else "-root")
if prod.strip():
art.system_product = prod.strip()
found_via_sudo = True
dmi_source_used = "dmidecode" + ("-sudo" if not is_root else "-root")
if not found_via_sudo:
read_dmi_from_sysfs(art)
dmi_source_used = "sysfs_fallback"
if not art.bios_vendor and not art.system_product:
art.notes.append("ℹ Running without root + sudo unavailable")
if dmi_source_used:
art.notes.append(f"[DMI_SOURCE] {dmi_source_used}")
else:
# Tool missing? Straight to sysfs
read_dmi_from_sysfs(art)
art.notes.append("[DMI_SOURCE] sysfs_no_dmidecode")
elif system == "Windows":
out = run(["wmic", "bios", "get", "Manufacturer", "/value"])
lines = [l.strip() for l in out.splitlines() if l.strip()]
if len(lines) >= 2:
art.bios_vendor = lines[1]
out2 = run(["wmic", "computersystem", "get", "Manufacturer,Model", "/value"]) or ""
lines2 = [l.strip() for l in out2.splitlines() if l.strip()]
if len(lines2) >= 2:
art.system_product = lines2[1]
# Normalize brand classification
art.bios_brand = None
if art.bios_vendor:
b = art.bios_vendor.lower()
if "virtualbox" in b or "oracle" in b or "innotek" in b:
art.bios_brand = "VirtualBox"
elif "vmware" in b:
art.bios_brand = "VMware"
elif "qemu" in b or "seabios" in b:
art.bios_brand = "QEMU/KVM"
elif "microsoft" in b or "hyper-v" in b:
art.bios_brand = "Hyper-V"
elif "parallels" in b:
art.bios_brand = "Parallels"
elif "xen" in b:
art.bios_brand = "Xen"
else:
art.bios_brand = "Legit/Not_VM_Brand"
def gather_processes(art: ArtifactCollection) -> None:
"""Enumerate running processes for sandbox tools."""
procs: Set[str] = set()
try:
if psutil:
for p in psutil.process_iter(attrs=("name",)):
name = (p.info.get("name") or "").strip()
if name:
procs.add(name)
else:
if platform.system() == "Windows":
out = run(["tasklist"])
for line in out.splitlines():
if ".exe" in line.lower():
parts = line.split()
if parts:
procs.add(parts[0])
else:
out = run(["ps", "axo", "comm"])
for line in out.splitlines()[1:]:
ln = line.strip()
if ln:
procs.add(ln)
except Exception:
pass
art.processes = sorted(procs)
def gather_mac_prefixes(art: ArtifactCollection) -> None:
"""Extract MAC address OUI prefixes from interfaces."""
prefixes: Set[str] = set()
try:
if psutil:
for nic, addrs in psutil.net_if_addrs().items():
for a in addrs:
addr = getattr(a, "address", None)
if not addr:
continue
addr = addr.strip()
if re.match(r"^[0-9A-Fa-f:.-]{11,}$", addr):
if ":" in addr:
pref = ":".join(addr.split(":")[:3]).upper()
elif "-" in addr:
pref = ":".join(addr.split("-")[:3]).upper()
else:
pref = addr[:8].upper()
prefixes.add(pref)
else:
if platform.system() == "Linux":
out = run(["ip", "link"]) or run(["ifconfig"]) or ""
for m in re.finditer(r"([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})", out, re.I):
prefixes.add(m.group(1).upper())
except Exception:
pass
art.mac_prefixes = sorted(prefixes)
def gather_disk_vendors(art: ArtifactCollection) -> None:
"""Identify disk drive vendors/models."""
vendors: Set[str] = set()
if platform.system() == "Linux":
base = "/sys/block/"
if os.path.isdir(base):
for b in os.listdir(base):
p = os.path.join(base, b, "device", "vendor")
vtxt = _safe_read_text(p)
if vtxt:
vendors.add(vtxt.strip())
byid = "/dev/disk/by-id/"
if os.path.isdir(byid):
for entry in os.listdir(byid):
if any(x in entry.lower() for x in ("qemu", "vbox", "vmware", "parallels")):
vendors.add(entry)
elif platform.system() == "Windows":
out = run(["wmic", "diskdrive", "get", "Model,Manufacturer"]) or ""
for line in out.splitlines():
line = line.strip()
if line:
vendors.add(line)
art.disk_vendors = sorted(vendors)
def gather_container_detection(art: ArtifactCollection) -> None:
"""STRONG EVIDENCE ONLY | Reduced false positives on bare metal."""
indicators = []
runtime = None
# Condition 1: /.dockerenv file exists (rare but very strong signal)
has_docker_env = os.path.exists("/.dockerenv")
# Condition 2: Look for actual container ID hashes (64 char hex) in cgroups
cgroup_txt = _safe_read_text("/proc/self/cgroup")
cgroup_matches = False
if cgroup_txt:
# Match Docker/containerd-style IDs (64+ hex chars before slash)
import re
container_id_pattern = re.compile(r'/([a-f0-9]{64}/|container=)')
if container_id_pattern.search(cgroup_txt):
cgroup_matches = True
# Also check for systemd slice patterns that contain scope/session
if re.search(r'/(systemd-)?scope\.service|session', cgroup_txt.lower()):
cgroup_matches = True
# Or explicit docker path patterns
if "/docker/" in cgroup_txt or "/containers/" in cgroup_txt:
cgroup_matches = True
# Condition 3: Docker socket actually exists
docker_socket_exists = any(os.path.exists(p) for p in ["/run/docker.sock", "/var/run/docker.sock"])
# STRONG EVIDENCE REQUIREMENT | Need multiple signals together
if has_docker_env and (cgroup_matches or docker_socket_exists):
indicators.append("strong_container_evidence")
runtime = "Docker"
elif docker_socket_exists and has_docker_env:
indicators.append("socket_and_marker_present")
runtime = "Docker"
else:
# Store weak signals but DON'T classify as container
art.container_has_marker_file = has_docker_env
art.container_cgroup_match = cgroup_matches
if docker_socket_exists:
art.docker_socket_found = True
art.notes.append("[DOCKER_SOCKET] No_Docker_ENV")
runtime = None
art.container_runtime = runtime
if indicators:
art.notes.extend(indicators)
def gather_cloud_probing(art: ArtifactCollection) -> None:
"""Probe cloud provider metadata endpoints (non-destructive)."""
results = {}
for provider, config in CLOUD_METADATA_ENDPOINTS.items():
url = config["url"]
timeout_ms = config["timeout_ms"]
headers = config.get("headers", {})
reachable = False
latency_ms = None
response_status = None
try:
if HAS_REQUESTS:
t0 = time.perf_counter()
resp = requests.head(url, headers=headers, timeout=timeout_ms / 1000)
latency_ms = (time.perf_counter() - t0) * 1000
reachable = resp.status_code == 200
response_status = resp.status_code
else:
# Socket-based probe fallback
parsed_url = url.replace("http://", "").split("/")
host = parsed_url[0]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout_ms / 1000)
t0 = time.perf_counter()
conn_result = s.connect_ex((host, 80))
latency_ms = (time.perf_counter() - t0) * 1000
if conn_result == 0:
reachable = True
response_status = 200
else:
response_status = conn_result
s.close()
except Exception as e:
response_status = str(e)
results[provider] = {
"reachable": reachable,
"latency_ms": latency_ms,
"response_status": response_status,
}
if reachable:
art.cloud_provider = provider
break
art.cloud_metadata_reachable = results
def gather_instruction_timing_advanced(art: ArtifactCollection) -> None:
"""Improved timing measurement focusing on privileged op overhead."""
samples_per_batch = 100
num_batches = 10
batch_times = []
for _batch_idx in range(num_batches):
batch_start = time.perf_counter_ns()
# Multiple iterations increase hypervisor overhead signal
for _i in range(samples_per_batch):
# Use a loop that triggers different behaviors
_ = sum(range(50))
batch_end = time.perf_counter_ns()
batch_times.append(batch_end - batch_start)
avg_time = sum(batch_times) / len(batch_times)
std_dev = (sum((t - avg_time)**2 for t in batch_times) / len(batch_times)) ** 0.5
# Real bare metal batches: ~200-500μs per batch
# Hypervisor batches: ~2-10ms per batch
med_time = sorted(batch_times)[len(batch_times)//2]
art.instruction_timing = {
"samples_total": samples_per_batch * num_batches,
"batch_avg_us": avg_time / 1000,
"batch_median_us": med_time / 1000,
"batch_std_dev_us": std_dev / 1000,
"suspicious_timing": med_time > 5000, # >1ms per batch suggests VM
"timing_variance_high": std_dev / avg_time > 0.5 if avg_time > 0 else False,
"baseline_comparison": f"{med_time / 1000:.2f} μs/batch" # Diagnostic
}
def gather_nested_virtualization(art: ArtifactCollection) -> None:
"""Detect signs of nested virtualization layers."""
signals = []
# Check if VT-x/AMD-V advertised inside guest (outer layer exists)
if platform.system() == "Linux":
cpu_flags = _safe_read_text("/proc/cpuinfo") or ""
if "vmx" in cpu_flags.lower() or "svm" in cpu_flags.lower():
# CPU has virtualization extensions exposed TO guest
signals.append("virtualization_extensions_visible_in_guest")
# High instruction timing variance suggests nesting overhead
if art.instruction_timing.get("timing_variance_high"):
signals.append("high_timing_variance_nested_signal")
# VirtIO devices indicate virtual infrastructure underneath
virtio_indicators = ["virtio", "1af4"]
for vendor in art.pci_vendors or []:
if any(v in vendor.lower() for v in virtio_indicators):
signals.append("virtio_device_detected")
break
art.nested_virtualization = {
"likely_nested": len(signals) >= 2,
"signal_count": len(signals),
"signals": signals,
}
def gather_hardware_quirks(art: ArtifactCollection) -> None:
"""Identify hardware characteristics typical of physical vs virtual systems."""
quirks = []
# Battery check
if platform.system() == "Windows":
out = run(["powershell", "-NoProfile", "-Command",
"(Get-WmiObject -Class Win32_Battery | Measure-Object).Count"])
if out.strip() == "0":
# Desktop PCs also lack batteries! Context matters.
battery_status = "desktop_or_vm"
elif platform.system() == "Linux":
if os.path.exists("/sys/class/power_supply/BAT0"):
battery_status = "present"
else:
battery_status = "absent_desktop_or_vm"
else:
battery_status = "unknown"
# SMBIOS serial validation
if platform.system() == "Linux" and shutil_which("dmidecode"):
serial = run(["dmidecode", "-s", "system-serial-number"]).strip()
dummy_serials = ["0", "None", "To Be Filled By O.E.M.", "Default string", "Unknown"]
if serial in dummy_serials:
quirks.append(f"dummy_serial:{serial}")
# RAM configuration analysis
if psutil:
mem = psutil.virtual_memory()
total_gb = mem.total / (1024**3)
# Round numbers suggest default VM allocations
rounded_sizes = [2, 4, 6, 8, 12, 16, 24, 32, 48, 64]
closest = min(rounded_sizes, key=lambda x: abs(total_gb - x))
if abs(total_gb - closest) < 0.3:
quirks.append(f"rounded_ram_size:{total_gb:.1f}GB")
# Boot loader identification
if platform.system() == "Linux":
grub_cfg = _safe_read_text("/boot/grub/grub.cfg") or ""
if "kvm" in grub_cfg.lower() or "qemu" in grub_cfg.lower():
quirks.append("grub_config_reference")
art.hardware_quirks = quirks
def gather_uptime_check(art: ArtifactCollection) -> None:
"""Calculate system uptime, low uptime may indicate sandbox/analysis env."""
try:
if psutil:
boot_time = psutil.boot_time()
uptime_seconds = time.time() - boot_time
uptime_hours = uptime_seconds / 3600
art.uptime = {
"hours": uptime_hours,
"seconds": uptime_seconds,
"reboot_timestamp": boot_time,
"suspiciously_recent": uptime_hours < 2, # Increased from 1hr
}
except Exception:
pass
def gather_gpu_detection(art: ArtifactCollection) -> None:
"""Detect GPU drivers and virtual graphics adapters."""
gpu_info = []
vm_gpu_detected = False
if platform.system() == "Windows":
out = run(["wmic", "path", "win32_VideoController", "get", "name"])
for line in out.splitlines()[1:]:
line = line.strip()
if line:
gpu_info.append(line)
vm_gpu_keywords = ["qxl", "vmsvga", "virtio", "vboxvideo", "cirrus"]
if any(kw in line.lower() for kw in vm_gpu_keywords):
vm_gpu_detected = True
elif platform.system() == "Linux":
if shutil_which("lspci"):
out = run(["lspci", "-v"])
for line in out.splitlines():
if "VGA" in line or "3D" in line:
gpu_info.append(line)
vm_gpu_keywords = ["qxl", "vmsvga", "virtio", "vboxvideo", "cirrus"]
if any(kw in line.lower() for kw in vm_gpu_keywords):
vm_gpu_detected = True
# Also detect NVIDIA/AMD passthrough scenarios
if "nvidia" in line.lower() or "amd" in line.lower():
gpu_info.append("GPU_passthrough_candidate:" + line[:50])
art.gpu_info = {
"adapters": gpu_info,
"vm_gpu": vm_gpu_detected,
"passthrough_candidates": any("passthrough_candidate" in g for g in gpu_info),
}
def gather_filesystem_artifacts_extended(art: ArtifactCollection) -> None:
"""Extended filesystem checks for VM artifacts."""
vm_paths = []
# Non exhaustive list, expandable
if platform.system() == "Windows":
check_paths = [
"C:\\Program Files\\VMware",
"C:\\Program Files\\Oracle\\VirtualBox Guest Additions",
"C:\\Program Files\\Tools\\Guest Tools",
"C:\\Windows\\System32\\drivers\\vmmouse.sys",
"C:\\Windows\\System32\\drivers\\vmhgfs.sys",
"C:\\Windows\\System32\\drivers\\VBoxGuest.sys",
"C:\\Windows\\System32\\Drivers\\VBoxSF.sys",
"C:\\windows\\潘顿\\vmusr.bin", # VMware shared folder cache
]
# Registry keys (check via wmic/powershell alternative)
else: # Linux
check_paths = [
"/dev/vda",
"/dev/vdb",
"/dev/vdc",
"/dev/xvda",
"/dev/xvdb",