-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbeef.py
More file actions
executable file
·1367 lines (1140 loc) · 40.4 KB
/
beef.py
File metadata and controls
executable file
·1367 lines (1140 loc) · 40.4 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
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
#
# MIT License
#
# Copyright (c) Matt Martz <matt@sivel.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import abc
import argparse
import collections.abc as c
import contextlib
import ctypes
import fcntl
import functools
import json
import os
import pathlib
import platform
import random
import re
import shutil
import socket
import struct
import subprocess
import sys
import termios
import textwrap
import time
import types
import typing as t
from dataclasses import asdict, dataclass, field, fields
try:
import argcomplete
HAS_ARGCOMPLETE = True
except ModuleNotFoundError:
HAS_ARGCOMPLETE = False
__version__ = '0.0.1'
_MBR_BOOTABLE_FLAG = 0x80
clonefile: t.Callable[[bytes, bytes, int], int]
if sys.platform == 'darwin':
_LIBC = ctypes.CDLL(None)
clonefile = _LIBC.clonefile
clonefile.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int)
class _JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, pathlib.Path):
return str(o)
if isinstance(o, Resolution):
return str(o)
return super().default(o)
def storage_completer(
prefix: str,
parsed_args: argparse.Namespace,
**kwargs
) -> c.Iterator:
storage = pathlib.Path(parsed_args.storage)
return (p.name for p in storage.glob(f'{prefix}*') if p.is_dir())
def generate_laa_mac() -> str:
first_byte = random.randint(0x00, 0xFF) & 0b11111100 | 0b00000010
mac = [first_byte] + [random.randint(0x00, 0xFF) for _ in range(5)]
return ':'.join(f'{b:02x}' for b in mac)
class Resize(str):
def __new__(cls, value):
if int(value) < 0:
raise ValueError('negative values not supported')
return str(value)
@dataclass(frozen=True, slots=True)
class Resolution:
width: int
height: int
def __init__(self, value: str | t.Self | None = None):
match value:
case None:
width, height = 1024, 800
case Resolution():
width, height = value.width, value.height
case str():
w, h = value.split('x')
width, height = int(w), int(h)
case _:
raise TypeError(
f'Invalid resolution type: {value.__class__.__name__}'
)
object.__setattr__(self, 'width', width)
object.__setattr__(self, 'height', height)
def __str__(self) -> str:
return f'{self.width}x{self.height}'
@dataclass(kw_only=True, slots=False)
class RunConfig:
vm: str
src_image: pathlib.Path | None = None
storage: pathlib.Path
resize: Resize | None = None
cpus: int | None = None
memory: int | None = None
user_data: pathlib.Path | None = None
volumes: list[tuple[pathlib.Path, str]] = field(
default_factory=list,
)
mac: str | None = None
gui: Resolution | None = None
attach: bool = False
force: bool = False
def __post_init__(self) -> None:
for f in fields(self):
value = getattr(self, f.name, None)
if isinstance(f.type, types.UnionType):
f_type = f.type.__args__[0]
else:
f_type = f.type
if value is not None and f_type is pathlib.Path:
if not isinstance(value, pathlib.Path):
value = pathlib.Path(value)
setattr(
self,
f.name,
value.resolve()
)
elif value and f.name == 'volumes':
setattr(
self,
f.name,
self._parse_volumes(value),
)
@t.overload
def _parse_volumes(
self,
value: list[str]
) -> list[tuple[pathlib.Path, str]]: ...
@t.overload
def _parse_volumes(
self,
value: list[tuple[pathlib.Path, str]]
) -> list[tuple[pathlib.Path, str]]: ...
def _parse_volumes(self, value):
volumes = []
if value == [None]:
return volumes
for v in value:
if isinstance(v, (list, tuple)):
if isinstance(v[0], pathlib.Path):
volumes.append(tuple(v))
else:
volumes.append((
pathlib.Path(v[0]).resolve(),
v[1]
))
continue
src, dst = v.split(':', 1)
volumes.append((
pathlib.Path(src).resolve(),
dst
))
return volumes
@classmethod
def from_argparse(cls, args: argparse.Namespace) -> t.Self:
valid = set(f.name for f in fields(cls))
return cls(
**{k: v for k, v in vars(args).items() if k in valid}
)
@functools.cached_property
def vm_storage(self) -> pathlib.Path:
return pathlib.Path(self.storage).joinpath(self.vm)
@functools.cached_property
def vm_disk(self) -> pathlib.Path:
return pathlib.Path(
self.storage
).joinpath(
self.vm, self.vm
).with_suffix('.raw').resolve()
@functools.cached_property
def control_sock(self) -> pathlib.Path:
return self.vm_storage / 'control.sock'
@functools.cached_property
def pid(self) -> pathlib.Path:
return self.vm_disk.with_suffix('.pid')
@functools.cached_property
def state_file(self) -> pathlib.Path:
return self.storage / self.vm / 'config.json'
def asdict(self) -> dict[str, object]:
run_config = asdict(self)
run_config.pop('force')
run_config.pop('attach')
return run_config
def write(self) -> None:
run_config = self.asdict()
state_file = self.state_file
state_file.parent.mkdir(exist_ok=True)
with (state_file).open('w') as f:
json.dump(run_config, f, indent=4, cls=_JSONEncoder)
@classmethod
def read(cls, state_file: pathlib.Path) -> t.Self:
if not state_file.is_file():
raise ValueError(f'No such VM: {state_file.parent.name}')
with state_file.open('rb') as f:
return cls(**json.load(f))
@contextlib.contextmanager
def _make_control_sock(run_config: RunConfig):
"""Create a Unix socket connection to the VM's control socket"""
pid = run_config.pid
if not pid.parent.is_dir():
raise ValueError(f'No such VM: {run_config.vm}')
if not pid.is_file():
raise RuntimeError(f'{run_config.vm} is not running')
control_sock = run_config.control_sock
if not control_sock.is_socket():
raise RuntimeError('control sock is missing')
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(str(control_sock))
yield sock
class HypervisorBackend(abc.ABC):
_bridge_interface: str
@abc.abstractmethod
def verify(self) -> None:
"""Verify hypervisor is available"""
def get_vm_ip(self, mac: str) -> str | None:
"""Get VM IP address from MAC address"""
arp_re = re.compile(rf'^\S+ \(([^)]+)\) at {mac}', flags=re.M)
cmd = ['arp', '-an']
if bridge_interface := getattr(self, '_bridge_interface', None):
cmd.extend(['-i', bridge_interface])
ip_match = None
for _ in range(30):
try:
p = subprocess.run(
cmd,
check=True,
capture_output=True,
text=True,
)
if ip_match := arp_re.search(p.stdout):
break
time.sleep(1)
continue
except subprocess.SubprocessError:
time.sleep(1)
continue
if ip_match:
return ip_match.group(1)
return None
@abc.abstractmethod
def get_status(self, run_config: RunConfig) -> dict[str, object]:
"""Get VM status"""
@abc.abstractmethod
def stop_vm(self, run_config: RunConfig) -> None:
"""Stop a running VM"""
@abc.abstractmethod
def start_vm(self, run_config: RunConfig) -> subprocess.Popen:
"""Start a VM and return Popen object"""
if not run_config.vm_disk.is_file():
raise ValueError(
f'Could not locate disk image for {run_config.vm}'
)
@abc.abstractmethod
def _get_mount_entry(self, tag: str, dst: str) -> list[str]:
"""Get mount entry format for this hypervisor"""
def prepare_vm_storage(self, run_config: RunConfig) -> None:
"""Prepare VM storage (cloud-init, etc.)"""
mounts = []
for src, dst in run_config.volumes:
tag = dst.replace(os.sep, '-')
mounts.append(self._get_mount_entry(tag, dst))
user_data = run_config.user_data
user_data_file = run_config.vm_storage / 'user-data'
if mounts or (user_data and user_data.is_file()):
with user_data_file.open('w') as f:
if user_data and user_data.is_file():
f.write(user_data.read_text())
else:
f.write('#cloud-config\n')
if mounts:
f.write(f'\nmounts: {json.dumps(mounts)}\n')
f.flush()
@abc.abstractmethod
def prepare_vm_metadata(self, run_config: RunConfig) -> pathlib.Path:
"""Prepare VM metadata (bundles, boot artifacts, etc.) and return
actual disk path to clone
"""
src_image = run_config.src_image
if not src_image:
raise ValueError('src_image is required')
return src_image
@abc.abstractmethod
def clone_disk(
self,
src: pathlib.Path,
dst: pathlib.Path
) -> None:
"""Clone disk image from src to dst"""
class VfkitBackend(HypervisorBackend):
_bridge_interface = 'bridge100'
def verify(self) -> None:
if not shutil.which('vfkit'):
raise RuntimeError(
'vfkit not found, please install vfkit '
'(https://github.com/crc-org/vfkit)'
)
def get_vm_ip(self, mac: str) -> str | None:
mac = re.sub(r'(^|:)0', r'\1', mac)
return super().get_vm_ip(mac)
def get_status(self, run_config: RunConfig) -> dict[str, object]:
data: dict[str, object]
try:
with _make_control_sock(run_config) as sock:
sock.sendall(textwrap.dedent('''
GET /vm/state HTTP/1.1
Host: localhost
''').lstrip().encode('iso8859-1'))
resp = sock.recv(1024).decode()
except (RuntimeError, socket.error):
data = {"state": "Stopped"}
if run_config.pid.is_file():
run_config.pid.unlink(missing_ok=True)
run_config.control_sock.unlink(missing_ok=True)
else:
raw_data = json.loads(resp.partition('\r\n\r\n')[2])
state = raw_data.get('state') or 'Unknown'
if state.startswith('VirtualMachineState'):
state = state.replace('VirtualMachineState', '')
data = {
'state': state,
'pid': int(run_config.pid.read_text()),
}
return data
def stop_vm(self, run_config: RunConfig) -> None:
with _make_control_sock(run_config) as sock:
sock.sendall(textwrap.dedent('''
POST /vm/state HTTP/1.1
Host: localhost
Content-Type: application/json
Content-Length: 17
{"state": "Stop"}
''').lstrip().encode('iso8859-1'))
if sock.recv(21) != b'HTTP/1.1 202 Accepted':
raise RuntimeError(
f'Could not issue stop to {run_config.vm}'
)
run_config.pid.unlink()
run_config.control_sock.unlink()
def _get_mount_entry(self, tag: str, dst: str) -> list[str]:
return [tag, dst, 'virtiofs']
def prepare_vm_metadata(self, run_config: RunConfig) -> pathlib.Path:
src_image = super().prepare_vm_metadata(run_config)
if run_config.force:
efi = run_config.vm_disk.with_suffix('.efi')
efi.unlink(missing_ok=True)
is_bundle = (
src_image.is_dir() and src_image.suffix == '.bundle'
)
if not is_bundle:
return src_image
for file in ('AuxiliaryStorage', 'HardwareModel',
'MachineIdentifier'):
shutil.copy2(
src_image / file,
run_config.vm_storage
)
return src_image / 'Disk.img'
def clone_disk(
self,
src: pathlib.Path,
dst: pathlib.Path
) -> None:
rc = clonefile(bytes(src), bytes(dst), 0)
if rc == -1:
dst.unlink(missing_ok=True)
raise OSError(f'Could not clone {src} to {dst}')
def start_vm(self, run_config: RunConfig) -> subprocess.Popen:
super().start_vm(run_config)
is_mac = run_config.vm_storage.joinpath('AuxiliaryStorage').exists()
efi = run_config.vm_disk.with_suffix('.efi')
control_sock = run_config.control_sock
if control_sock.is_file():
control_sock.unlink()
cmd = [
'vfkit',
'--cpus', f'{run_config.cpus}',
'--memory', f'{run_config.memory}',
'--device', f'virtio-blk,path={run_config.vm_disk}',
'--device', f'virtio-net,nat,mac={run_config.mac}',
'--device', 'virtio-rng',
'--restful-uri', f'unix:{control_sock}',
]
if is_mac:
vm_storage = run_config.vm_storage
machine_identifier_path = vm_storage / 'MachineIdentifier'
cmd.extend([
'--bootloader',
(
'macos,'
f'machineIdentifierPath={machine_identifier_path},'
f'hardwareModelPath={vm_storage / "HardwareModel"},'
f'auxImagePath={vm_storage / "AuxiliaryStorage"}'
)
])
else:
cmd.extend([
'--bootloader', f'efi,variable-store={efi},create',
])
for src, dst in run_config.volumes:
if not src.exists():
src.mkdir(parents=True, exist_ok=True)
tag = dst.replace(os.sep, '-')
cmd.extend([
'--device',
f'virtio-fs,sharedDir={src},mountTag={tag}',
])
user_data = run_config.vm_storage / 'user-data'
if user_data.is_file():
cmd.extend(['--cloud-init', f'{user_data}'])
if is_mac or run_config.gui:
resolution = run_config.gui or Resolution()
cmd.extend([
'--device', 'virtio-input,keyboard',
'--device', 'virtio-input,pointing',
'--device', (
f'virtio-gpu,width={resolution.width},'
f'height={resolution.height}'
),
'--gui',
])
if run_config.attach:
cmd.extend(['--device', 'virtio-serial,stdio'])
popen_kwargs: dict[str, t.Any] = {
'text': True,
'env': os.environ | {'TMPDIR': str(run_config.vm_storage)},
}
if not run_config.attach:
popen_kwargs.update({
'start_new_session': True,
'stdin': subprocess.PIPE,
'stdout': subprocess.PIPE,
'stderr': subprocess.STDOUT,
})
p = subprocess.Popen(cmd, **popen_kwargs)
p.poll()
return p
class QemuBackend(HypervisorBackend):
_bridge_interface = 'virbr0'
def __init__(self):
self._machine_type = 'q35'
self._qemu_binary = 'qemu'
self._bridge_helper = 'qemu-bridge-helper'
self._ovmf_code = pathlib.Path('OVMF_CODE.fd')
self._ovmf_vars_template = pathlib.Path('OVMF_VARS.fd')
def _detect_qemu_binary(self) -> str:
"""Detect appropriate QEMU binary for the system architecture"""
arch = platform.machine().lower()
if arch in {'x86_64', 'amd64'}:
binary = 'qemu-system-x86_64'
self._machine_type = 'q35'
elif arch in {'aarch64', 'arm64'}:
binary = 'qemu-system-aarch64'
self._machine_type = 'virt'
else:
raise RuntimeError(f'Unsupported architecture: {arch}')
if not shutil.which(binary):
raise RuntimeError(f'{binary} not found')
return binary
def _detect_bridge_helper(self) -> str:
"""Detect qemu-bridge-helper location"""
common_paths = (
'/usr/lib/qemu/qemu-bridge-helper',
'/usr/libexec/qemu-bridge-helper',
)
for path in common_paths:
if pathlib.Path(path).exists():
return path
helper = shutil.which('qemu-bridge-helper')
if helper:
return helper
raise RuntimeError(
'qemu-bridge-helper not found. Please install qemu-bridge-helper '
'and ensure /etc/qemu/bridge.conf contains "allow virbr0"'
)
def _detect_ovmf(self) -> None:
"""Detect OVMF firmware files"""
ovmf_variants = (
('OVMF_CODE_4M.fd', 'OVMF_VARS_4M.fd'),
('OVMF_CODE.fd', 'OVMF_VARS.fd'),
)
for code_file, vars_file in ovmf_variants:
code_path = pathlib.Path('/usr/share/OVMF') / code_file
vars_path = pathlib.Path('/usr/share/OVMF') / vars_file
if code_path.exists() and vars_path.exists():
self._ovmf_code = code_path
self._ovmf_vars_template = vars_path
return
raise RuntimeError('OVMF not found, please install ovmf')
def verify(self) -> None:
self._qemu_binary = self._detect_qemu_binary()
self._bridge_helper = self._detect_bridge_helper()
self._detect_ovmf()
if not shutil.which('genisoimage'):
raise RuntimeError(
'genisoimage not found, please install genisoimage'
)
helper_path = pathlib.Path(self._bridge_helper)
if not (helper_path.stat().st_mode & 0o4000):
raise RuntimeError(
f'qemu-bridge-helper at {self._bridge_helper} does not have '
f'setuid bit set. Run: sudo chmod u+s {self._bridge_helper}'
)
bridge_conf = pathlib.Path('/etc/qemu/bridge.conf')
if not bridge_conf.exists():
raise RuntimeError(
'/etc/qemu/bridge.conf not found. '
'Run: echo "allow virbr0" | sudo tee /etc/qemu/bridge.conf'
)
if 'allow virbr0' not in bridge_conf.read_text():
raise RuntimeError(
'/etc/qemu/bridge.conf does not contain "allow virbr0". '
'Run: echo "allow virbr0" | sudo tee -a /etc/qemu/bridge.conf'
)
def _qmp_command(
self,
sock: socket.socket,
command: str,
arguments: dict[str, object] | None = None
) -> dict[str, object]:
"""Send QMP command and return response"""
cmd: dict[str, object] = {'execute': command}
if arguments:
cmd['arguments'] = arguments
sock.sendall((json.dumps(cmd) + '\n').encode())
response = b''
for chunk in iter(functools.partial(sock.recv, 4096), b''):
response += chunk
if b'\n' in chunk:
break
lines = response.decode().strip().split('\n')
for line in lines:
if stripped_line := line.strip():
data = json.loads(stripped_line)
if 'return' in data or 'error' in data:
return data
return {}
def get_status(self, run_config: RunConfig) -> dict[str, object]:
data: dict[str, object]
try:
with _make_control_sock(run_config) as sock:
sock.recv(4096)
self._qmp_command(sock, 'qmp_capabilities')
result = self._qmp_command(sock, 'query-status')
if 'return' in result:
return_data = t.cast(dict[str, str], result['return'])
qemu_status: str = return_data.get('status') or 'Unknown'
state_map = {
'running': 'Running',
'paused': 'Paused',
'shutdown': 'Stopped',
'inmigrate': 'Running',
}
data = {
'state': state_map.get(
qemu_status,
qemu_status.title()
)
}
else:
data = {'state': 'Unknown'}
except (RuntimeError, socket.error, json.JSONDecodeError):
data = {"state": "Stopped"}
if run_config.pid.is_file():
run_config.pid.unlink(missing_ok=True)
run_config.control_sock.unlink(missing_ok=True)
else:
data['pid'] = int(run_config.pid.read_text())
return data
def stop_vm(self, run_config: RunConfig) -> None:
with _make_control_sock(run_config) as sock:
sock.recv(4096)
self._qmp_command(sock, 'qmp_capabilities')
result = self._qmp_command(sock, 'system_powerdown')
if 'error' in result:
raise RuntimeError(
f'Could not issue stop to {run_config.vm}: '
f'{result["error"]}'
)
run_config.pid.unlink()
run_config.control_sock.unlink()
def _get_mount_entry(self, tag: str, dst: str) -> list[str]:
return [tag, dst, '9p', 'trans=virtio', '0', '0']
def _generate_cloud_init_iso(self, run_config: RunConfig) -> None:
"""Generate cloud-init ISO from user-data file"""
user_data_file = run_config.vm_storage / 'user-data'
if not user_data_file.is_file():
return
seed_iso = run_config.vm_storage / 'cloud-init.iso'
meta_data = run_config.vm_storage / 'meta-data'
meta_data.write_text('instance-id: iid-local01\n')
subprocess.run(
[
'genisoimage',
'-output', str(seed_iso),
'-volid', 'cidata',
'-joliet', '-rock',
str(user_data_file),
str(meta_data),
],
check=True,
capture_output=True,
)
def prepare_vm_metadata(self, run_config: RunConfig) -> pathlib.Path:
src_image = super().prepare_vm_metadata(run_config)
if run_config.force:
ovmf_vars = run_config.vm_storage / self._ovmf_vars_template.name
ovmf_vars.unlink(missing_ok=True)
return src_image
def clone_disk(
self,
src: pathlib.Path,
dst: pathlib.Path
) -> None:
with src.open('rb') as src_fd:
with dst.open('wb') as dst_fd:
try:
FICLONE = fcntl.FICLONE # type: ignore[missing-attribute]
fcntl.ioctl(dst_fd.fileno(), FICLONE, src_fd.fileno())
except OSError as e:
dst.unlink(missing_ok=True)
raise OSError(
f'Could not clone {src} to {dst}: {e}. '
'Reflink cloning is required. Ensure your filesystem '
'supports reflinks (btrfs, xfs with reflink enabled)'
)
def start_vm(self, run_config: RunConfig) -> subprocess.Popen:
super().start_vm(run_config)
self._generate_cloud_init_iso(run_config)
control_sock = run_config.control_sock
if control_sock.is_file():
control_sock.unlink()
ovmf_code = self._ovmf_code
ovmf_vars = run_config.vm_storage / self._ovmf_vars_template.name
if not ovmf_vars.exists():
shutil.copy2(self._ovmf_vars_template, ovmf_vars)
bridge_helper = self._bridge_helper
cmd = [
self._qemu_binary,
'-name', run_config.vm,
'-machine', f'{self._machine_type},accel=kvm',
'-cpu', 'host',
'-smp', str(run_config.cpus),
'-m', str(run_config.memory),
'-drive', f'file={run_config.vm_disk},format=raw,if=virtio',
'-netdev', f'bridge,id=net0,br=virbr0,helper={bridge_helper}',
'-device', f'virtio-net-pci,netdev=net0,mac={run_config.mac}',
'-device', 'virtio-rng-pci',
'-qmp', f'unix:{control_sock},server,nowait',
]
if ovmf_code.exists():
cmd.extend([
'-drive', f'if=pflash,format=raw,readonly=on,file={ovmf_code}',
'-drive', f'if=pflash,format=raw,file={ovmf_vars}',
])
seed_iso = run_config.vm_storage / 'cloud-init.iso'
if seed_iso.is_file():
cmd.extend([
'-drive', f'file={seed_iso},format=raw,if=virtio,readonly=on',
])
for src, dst in run_config.volumes:
if not src.exists():
src.mkdir(parents=True, exist_ok=True)
tag = dst.replace(os.sep, '-')
cmd.extend([
'-fsdev',
f'local,id=fsdev{tag},path={src},security_model=passthrough',
'-device',
f'virtio-9p-pci,fsdev=fsdev{tag},mount_tag={tag}',
])
if run_config.gui:
resolution = run_config.gui or Resolution()
cmd.extend([
'-device', (
f'virtio-vga,xres={resolution.width},'
f'yres={resolution.height}'
),
'-display', 'sdl',
])
else:
cmd.extend(['-display', 'none'])
if run_config.attach:
cmd.extend(['-serial', 'stdio'])
popen_kwargs: dict[str, t.Any] = {
'text': True,
}
if not run_config.attach:
popen_kwargs.update({
'start_new_session': True,
'stdin': subprocess.PIPE,
'stdout': subprocess.PIPE,
'stderr': subprocess.STDOUT,
})
p = subprocess.Popen(cmd, **popen_kwargs)
p.poll()
return p
@functools.cache
def _get_backend() -> HypervisorBackend:
"""Get the appropriate hypervisor backend for the current platform"""
if sys.platform == 'darwin':
return VfkitBackend()
elif sys.platform == 'linux':
return QemuBackend()
else:
raise RuntimeError(f'Unsupported platform: {sys.platform}')
def _settable_parser(defaults: bool = True) -> argparse.ArgumentParser:
arguments: list[tuple[tuple[str, ...], dict[str, t.Any]]] = [
(
('--resize',),
{
'default': Resize('+10'),
'help': (
'Resize the disk in GB. Can be exact, or start with + '
'to indicate a relative size change'
),
'type': Resize,
},
),
(
('--cpus',),
{
'default': 2,
'help': 'Number of CPUs',
'type': int,
},
),
(
('--memory',),
{
'default': 2048,
'help': 'Amount of memory in MB',
'type': int,
},
),
(
('--user-data',),
{
'default': os.getenv(
'BEEF_USER_DATA',
pathlib.Path.home() / 'vms' / 'user-data',
),
'help': 'Path to cloud-init user_data file',
'type': pathlib.Path,
},
),
(
('--volume', '-v'),
{
'dest': 'volumes',
'action': 'append',
'default': [],
'help': (
'Volumes to mount into the VM. May be specified multiple '
'times'
),
'metavar': 'src:dst',
},
),
(
('--mac',),
{
'default': generate_laa_mac(),
'help': 'MAC address',
},
),
]
parser = argparse.ArgumentParser(add_help=False)
for args, kwargs in arguments:
if not defaults:
if isinstance(kwargs['default'], list):
kwargs['nargs'] = '?'
kwargs['const'] = None
kwargs['default'] = None
elif kwargs.get('default'):
kwargs['help'] += '. Default: %(default)s'
parser.add_argument(*args, **kwargs)
return parser
def parse_args(
argv: list[str] | None = None
) -> tuple[t.Callable[[RunConfig], None], RunConfig]:
vm_parser = argparse.ArgumentParser(add_help=False)
vm_parser.add_argument( # type: ignore[attr-defined]
'vm',
help='Name of VM',
).completer = storage_completer
storage_parser = argparse.ArgumentParser(add_help=False)
storage_parser.add_argument(
'--storage',
default=os.getenv(
'BEEF_STORAGE',
pathlib.Path.home() / 'vms' / 'storage',
),
type=pathlib.Path,
help='Path to vmstorage dir. Default: %(default)s',
)
run_common_parser = argparse.ArgumentParser(add_help=False)
run_common_parser.add_argument(
'--attach', '-a',
action='store_true',
default=False,
help='Attach and to VM consolel and run in foreground',
)
run_common_parser.add_argument(
'--gui',
nargs='?',
type=Resolution,
const=Resolution(),
help=(
'Enable GUI. Automatically enabled if VM is macOS. '
'Defaults: %(const)s'
),
metavar='WxH',
)
parents = [vm_parser, storage_parser]
parser = argparse.ArgumentParser()
parser.add_argument(
'--version', '-V',
action='version',
version=f'%(prog)s {__version__}',
)
subparsers = parser.add_subparsers(dest='action', required=True)
run_parser = subparsers.add_parser(
'run',
help=run.__doc__,
parents=parents + [_settable_parser(), run_common_parser],
)
run_parser.set_defaults(
action=run,
)
run_parser.add_argument(
'src_image',
nargs='?',