-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
restore.py
2144 lines (1883 loc) · 84.8 KB
/
restore.py
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
# -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
'''Backup restore module'''
import contextlib
import errno
import fcntl
import functools
import getpass
import grp
import inspect
import logging
import multiprocessing
from multiprocessing import Queue, Process
import os
import pwd
import re
import shutil
import subprocess
import sys
import tempfile
import termios
import time
import threading
# only for a python bug workaround
import concurrent.futures.thread
import collections
import qubesadmin
import qubesadmin.vm
from qubesadmin.backup import BackupVM
from qubesadmin.backup.core2 import Core2Qubes
from qubesadmin.backup.core3 import Core3Qubes
from qubesadmin.device_protocol import DeviceAssignment
from qubesadmin.exc import QubesException
from qubesadmin.utils import size_to_human
# must be picklable
QUEUE_FINISHED = "!!!FINISHED"
QUEUE_ERROR = "!!!ERROR"
HEADER_FILENAME = 'backup-header'
DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
# 'scrypt' is not exactly HMAC algorithm, but a tool we use to
# integrity-protect the data
DEFAULT_HMAC_ALGORITHM = 'scrypt'
DEFAULT_COMPRESSION_FILTER = 'gzip'
KNOWN_COMPRESSION_FILTERS = ('gzip', 'bzip2', 'xz')
# lazy loaded
KNOWN_CRYPTO_ALGORITHMS = []
# lazy loaded
KNOWN_HMAC_ALGORITHMS = []
# Maximum size of error message get from process stderr (including VM process)
MAX_STDERR_BYTES = 1024
# header + qubes.xml max size
HEADER_QUBES_XML_MAX_SIZE = 1024 * 1024
# hmac file max size - regardless of backup format version!
HMAC_MAX_SIZE = 4096
BLKSIZE = 512
_re_alphanum = re.compile(r'^[A-Za-z0-9-]*$')
_tar_msg_re = re.compile(r".*#[0-9].*restore_pipe")
_tar_file_size_re = re.compile(r"^[^ ]+ [^ ]+/[^ ]+ *([0-9]+) .*")
class BackupCanceledError(QubesException):
'''Exception raised when backup/restore was cancelled'''
def __init__(self, msg, tmpdir=None):
super().__init__(msg)
self.tmpdir = tmpdir
def init_supported_hmac_and_crypto():
"""Collect supported hmac and crypto algorithms.
This calls openssl to list actual supported algos.
"""
if not KNOWN_HMAC_ALGORITHMS:
KNOWN_HMAC_ALGORITHMS.extend(get_supported_hmac_algo())
if not KNOWN_CRYPTO_ALGORITHMS:
KNOWN_CRYPTO_ALGORITHMS.extend(get_supported_crypto_algo())
class BackupHeader(object):
'''Structure describing backup-header file included as the first file in
backup archive
'''
Header = collections.namedtuple('Header', ['field', 't', 'validator'])
known_headers = {
'version': Header(field='version', t=int,
validator=lambda x: 1 <= x <= 4),
'encrypted': Header(field='encrypted', t=bool,
validator=lambda x: True),
'compressed': Header(field='compressed', t=bool,
validator=lambda x: True),
'compression-filter': Header(
field='compression_filter',
t=str,
validator=lambda x: x in KNOWN_COMPRESSION_FILTERS),
'crypto-algorithm': Header(
field='crypto_algorithm',
t=str,
validator=lambda x: x.lower() in KNOWN_CRYPTO_ALGORITHMS),
'hmac-algorithm': Header(
field='hmac_algorithm',
t=str,
validator=lambda x: x.lower() in KNOWN_HMAC_ALGORITHMS),
'backup-id': Header(
field='backup_id',
t=str,
validator=lambda x: not x.startswith('-') and x != ''),
}
def __init__(self,
header_data=None,
*,
version=None,
encrypted=None,
compressed=None,
compression_filter=None,
hmac_algorithm=None,
crypto_algorithm=None,
backup_id=None):
# repeat the list to help code completion...
self.version = version
self.encrypted = encrypted
self.compressed = compressed
# Options introduced in backup format 3+, which always have a header,
# so no need for fallback in function parameter
self.compression_filter = compression_filter
self.hmac_algorithm = hmac_algorithm
self.crypto_algorithm = crypto_algorithm
self.backup_id = backup_id
init_supported_hmac_and_crypto()
if header_data is not None:
self.load(header_data)
def load(self, untrusted_header_text):
"""Parse backup header file.
:param untrusted_header_text: header content
:type untrusted_header_text: basestring
.. warning::
This function may be exposed to not yet verified header,
so is security critical.
"""
try:
untrusted_header_text = untrusted_header_text.decode('ascii')
except UnicodeDecodeError:
raise QubesException(
"Non-ASCII characters in backup header")
seen = set()
for untrusted_line in untrusted_header_text.splitlines():
if untrusted_line.count('=') != 1:
raise QubesException("Invalid backup header")
key, value = untrusted_line.strip().split('=', 1)
if not _re_alphanum.match(key):
raise QubesException("Invalid backup header (key)")
if key not in self.known_headers:
# Ignoring unknown option
continue
header = self.known_headers[key]
if key in seen:
raise QubesException("Duplicated header line: {}".format(key))
seen.add(key)
if getattr(self, header.field, None) is not None:
# ignore options already set (potentially forced values)
continue
if not _re_alphanum.match(value):
raise QubesException("Invalid backup header (value)")
if header.t is bool:
value = value.lower() in ["1", "true", "yes"]
elif header.t is int:
value = int(value)
elif header.t is str:
pass
else:
raise QubesException("Unrecognized header type")
if not header.validator(value):
if key == 'compression-filter':
raise QubesException(
"Unusual compression filter '{f}' found. Use "
"--compression-filter={f} to use it anyway.".format(
f=value))
raise QubesException("Invalid value for header: {}".format(key))
setattr(self, header.field, value)
self.validate()
def validate(self):
'''Validate header data, according to header version'''
if self.version == 1:
# header not really present
pass
elif self.version in [2, 3, 4]:
expected_attrs = ['version', 'encrypted', 'compressed',
'hmac_algorithm']
if self.encrypted and self.version < 4:
expected_attrs += ['crypto_algorithm']
if self.version >= 3 and self.compressed:
expected_attrs += ['compression_filter']
if self.version >= 4:
expected_attrs += ['backup_id']
for key in expected_attrs:
if getattr(self, key) is None:
raise QubesException(
"Backup header lack '{}' info".format(key))
else:
raise QubesException(
"Unsupported backup version {}".format(self.version))
def save(self, filename):
'''Save backup header into a file'''
with open(filename, "w", encoding='utf-8') as f_header:
# make sure 'version' is the first key
f_header.write('version={}\n'.format(self.version))
for key, header in self.known_headers.items():
if key == 'version':
continue
attr = header.field
if getattr(self, attr) is None:
continue
f_header.write("{!s}={!s}\n".format(key, getattr(self, attr)))
def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
"""Similar to pty.fork, but handle stdin/stdout according to parameters
instead of connecting to the pty
:return tuple (subprocess.Popen, pty_master)
"""
def set_ctty(ctty_fd, master_fd):
'''Set controlling terminal'''
os.setsid()
os.close(master_fd)
fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
if not echo:
termios_p = termios.tcgetattr(ctty_fd)
# termios_p.c_lflags
termios_p[3] &= ~termios.ECHO
termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
(pty_master, pty_slave) = os.openpty()
# pylint: disable=subprocess-popen-preexec-fn,consider-using-with
p = subprocess.Popen(args, stdin=stdin, stdout=stdout,
stderr=stderr,
preexec_fn=lambda: set_ctty(pty_slave, pty_master))
os.close(pty_slave)
return p, open(pty_master, 'wb+', buffering=0)
def launch_scrypt(action, input_name, output_name, passphrase):
'''
Launch 'scrypt' process, pass passphrase to it and return
subprocess.Popen object.
:param action: 'enc' or 'dec'
:param input_name: input path or '-' for stdin
:param output_name: output path or '-' for stdout
:param passphrase: passphrase
:return: subprocess.Popen object
'''
command_line = ['scrypt', action, '-f', input_name, output_name]
(p, pty) = launch_proc_with_pty(command_line,
stdin=subprocess.PIPE if input_name == '-' else None,
stdout=subprocess.PIPE if output_name == '-' else None,
stderr=subprocess.PIPE,
echo=False)
if action == 'enc':
prompts = (b'Please enter passphrase: ', b'Please confirm passphrase: ')
else:
prompts = (b'Please enter passphrase: ',)
for prompt in prompts:
actual_prompt = p.stderr.read(len(prompt))
if actual_prompt != prompt:
raise QubesException(
'Unexpected prompt from scrypt: {}'.format(actual_prompt))
pty.write(passphrase.encode('utf-8') + b'\n')
pty.flush()
# save it here, so garbage collector would not close it (which would kill
# the child)
p.pty = pty
return p
def _fix_threading_after_fork():
"""
HACK
Clear thread queues after fork (threads are gone at this point),
otherwise atexit callback will crash.
https://github.com/python/cpython/issues/88110
And initialize DummyThread locks:
https://github.com/python/cpython/issues/102512
"""
# pylint: disable=protected-access
concurrent.futures.thread._threads_queues.clear()
thread = threading.current_thread()
if isinstance(thread, threading._DummyThread) and \
getattr(thread, '_tstate_lock', "missing") is None:
# mimic threading._after_fork()
thread._set_tstate_lock()
class ExtractWorker3(Process):
'''Process for handling inner tar layer of backup archive'''
# pylint: disable=too-many-instance-attributes
def __init__(self, queue, base_dir, passphrase, encrypted, *,
progress_callback, vmproc=None,
compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
compression_filter=None, verify_only=False, handlers=None):
'''Start inner tar extraction worker
The purpose of this class is to process files extracted from outer
archive layer and pass to appropriate handlers. Input files are given
through a queue. Insert :py:obj:`QUEUE_FINISHED` or
:py:obj:`QUEUE_ERROR` to end data processing (either cleanly,
or forcefully).
:param multiprocessing.Queue queue: a queue with filenames to
process; those files needs to be given as full path, inside *base_dir*
:param str base_dir: directory where all files to process live
:param str passphrase: passphrase to decrypt the data
:param bool encrypted: is encryption applied?
:param callable progress_callback: report extraction progress
:param subprocess.Popen vmproc: process extracting outer layer,
given here to monitor
it for failures (when it exits with non-zero exit code, inner layer
processing is stopped)
:param bool compressed: is the data compressed?
:param str crypto_algorithm: encryption algorithm, either `scrypt` or an
algorithm supported by openssl
:param str compression_filter: compression program, `gzip` by default
:param bool verify_only: only verify data integrity, do not extract
:param dict handlers: handlers for actual data
'''
super().__init__()
#: queue with files to extract
self.queue = queue
#: paths on the queue are relative to this dir
self.base_dir = base_dir
#: passphrase to decrypt/authenticate data
self.passphrase = passphrase
#: handlers for files; it should be dict filename -> data_function
# where data_function (which might be called in a separate
# multiprocessing.Process) will get a file-like object as the first
# argument. If the data_function signature accepts a keyword-only
# argument named file_size, it will also get the size in bytes when
# known.
self.handlers = handlers
#: is the backup encrypted?
self.encrypted = encrypted
#: is the backup compressed?
self.compressed = compressed
#: what crypto algorithm is used for encryption?
self.crypto_algorithm = crypto_algorithm
#: only verify integrity, don't extract anything
self.verify_only = verify_only
#: progress
self.blocks_backedup = 0
#: inner tar layer extraction (subprocess.Popen instance)
self.tar2_process = None
#: current inner tar archive name
self.tar2_current_file = None
#: cat process feeding tar2_process
self.tar2_feeder = None
#: decompressor subprocess.Popen instance
self.decompressor_process = None
#: decryptor subprocess.Popen instance
self.decryptor_process = None
#: data import multiprocessing.Process instance
self.import_process = None
#: callback reporting progress to UI
self.progress_callback = progress_callback
#: process (subprocess.Popen instance) feeding the data into
# extraction tool
self.vmproc = vmproc
self.log = logging.getLogger('qubesadmin.backup.extract')
self.stderr_encoding = sys.stderr.encoding or 'utf-8'
self.tar2_stderr = []
self.compression_filter = compression_filter
def collect_tar_output(self):
'''Retrieve tar stderr and handle it appropriately
Log errors, process file size if requested.
This use :py:attr:`tar2_process`.
'''
if not self.tar2_process.stderr:
return
if self.tar2_process.poll() is None:
try:
new_lines = self.tar2_process.stderr \
.read(MAX_STDERR_BYTES).splitlines()
except IOError as e:
if e.errno == errno.EAGAIN:
return
raise
else:
new_lines = self.tar2_process.stderr.readlines()
new_lines = [x.decode(self.stderr_encoding) for x in new_lines]
debug_msg = [msg for msg in new_lines if _tar_msg_re.match(msg)]
self.log.debug('tar2_stderr: %s', '\n'.join(debug_msg))
new_lines = [msg for msg in new_lines if not _tar_msg_re.match(msg)]
self.tar2_stderr += new_lines
def run(self):
try:
_fix_threading_after_fork()
self.__run__()
except Exception:
# Cleanup children
for process in [self.decompressor_process,
self.decryptor_process,
self.tar2_process]:
if process:
try:
process.terminate()
except OSError:
pass
process.wait()
self.log.exception('ERROR')
raise
def handle_dir(self, dirname):
''' Relocate files in given director when it's already extracted
:param dirname: directory path to handle (relative to backup root),
without trailing slash
'''
for fname, data_func in self.handlers.items():
if not fname.startswith(dirname + '/'):
continue
if not os.path.exists(fname):
# for example firewall.xml
continue
with open(fname, 'rb') as input_file:
data_func_kwargs = {}
if 'file_size' in inspect.getfullargspec(data_func).kwonlyargs:
data_func_kwargs['file_size'] = \
os.stat(input_file.fileno()).st_size
data_func(input_file, **data_func_kwargs)
os.unlink(fname)
shutil.rmtree(dirname)
def cleanup_tar2(self, wait=True, terminate=False):
'''Cleanup running :py:attr:`tar2_process`
:param wait: wait for it termination, otherwise method exit early if
process is still running
:param terminate: terminate the process if still running
'''
if self.tar2_process is None:
return
if terminate:
if self.import_process is not None:
self.tar2_process.terminate()
self.import_process.terminate()
if wait:
self.tar2_process.wait()
if self.import_process is not None:
self.import_process.join()
elif self.tar2_process.poll() is None:
return
self.collect_tar_output()
if self.tar2_process.stderr:
self.tar2_process.stderr.close()
if self.tar2_process.returncode != 0:
self.log.error(
"ERROR: unable to extract files for %s, tar "
"output:\n %s",
self.tar2_current_file,
"\n ".join(self.tar2_stderr))
else:
# Finished extracting the tar file
# if that was whole-directory archive, handle
# relocated files now
inner_name = self.tar2_current_file.rsplit('.', 1)[0] \
.replace(self.base_dir + '/', '')
if os.path.basename(inner_name) == '.':
self.handle_dir(
os.path.dirname(inner_name))
self.tar2_current_file = None
self.tar2_process = None
def _data_import_wrapper(self, close_fds, data_func, tar2_process):
'''Close not needed file descriptors, handle output size reported
by tar (if needed) then call data_func(tar2_process.stdout).
This is to prevent holding write end of a pipe in subprocess,
preventing EOF transfer.
'''
for fd in close_fds:
if fd in (tar2_process.stdout.fileno(),
tar2_process.stderr.fileno()):
continue
try:
os.close(fd)
except OSError:
pass
# retrieve file size from tar's stderr; warning: we do
# not read data from tar's stdout at this point, it will
# hang if it tries to output file content before
# reporting its size on stderr first
data_func_kwargs = {}
if 'file_size' in inspect.getfullargspec(data_func).kwonlyargs:
# process lines on stderr until we get file size
# search for first file size reported by tar -
# this is used only when extracting single-file archive, so don't
# bother with checking file name
# Also, this needs to be called before anything is retrieved
# from tar stderr, otherwise the process may deadlock waiting for
# size (at this point nothing is retrieving data from tar stdout
# yet, so it will hang on write() when the output pipe fill up).
while True:
line = tar2_process.stderr.readline()
if not line:
self.log.warning('EOF from tar before got file size info')
break
line = line.decode()
if _tar_msg_re.match(line):
self.log.debug('tar2_stderr: %s', line)
else:
match = _tar_file_size_re.match(line)
if match:
data_func_kwargs['file_size'] = int(match.groups()[0])
break
self.log.warning(
'unexpected tar output (no file size report): %s', line)
return data_func(tar2_process.stdout, **data_func_kwargs)
def feed_tar2(self, filename, input_pipe):
'''Feed data from *filename* to *input_pipe*
Start a cat process to do that (do not block this process). Cat
subprocess instance will be in :py:attr:`tar2_feeder`
'''
assert self.tar2_feeder is None
# pylint: disable=consider-using-with
self.tar2_feeder = subprocess.Popen(['cat', filename],
stdout=input_pipe)
def check_processes(self, processes):
'''Check if any process failed.
And if so, wait for other relevant processes to cleanup.
'''
run_error = None
for name, proc in processes.items():
if proc is None:
continue
if isinstance(proc, Process):
if not proc.is_alive() and proc.exitcode != 0:
run_error = name
break
elif proc.poll():
run_error = name
break
if run_error:
if run_error == "target":
self.collect_tar_output()
details = "\n".join(self.tar2_stderr)
else:
details = "%s failed" % run_error
if self.decryptor_process:
self.decryptor_process.terminate()
self.decryptor_process.wait()
self.decryptor_process = None
self.log.error('Error while processing \'%s\': %s',
self.tar2_current_file, details)
self.cleanup_tar2(wait=True, terminate=True)
def __run__(self):
self.log.debug("Started sending thread")
self.log.debug("Moving to dir %s", self.base_dir)
os.chdir(self.base_dir)
filename = None
input_pipe = None
for filename in iter(self.queue.get, None):
if filename in (QUEUE_FINISHED, QUEUE_ERROR):
break
assert isinstance(filename, str)
self.log.debug("Extracting file %s", filename)
if filename.endswith('.000'):
# next file
if self.tar2_process is not None:
input_pipe.close()
self.cleanup_tar2(wait=True, terminate=False)
inner_name = filename[:-len('.000')].replace(
self.base_dir + '/', '')
redirect_stdout = None
if os.path.basename(inner_name) == '.':
if (inner_name in self.handlers or
any(x.startswith(os.path.dirname(inner_name) + '/')
for x in self.handlers)):
tar2_cmdline = ['tar',
'-%s' % ("t" if self.verify_only else "x"),
inner_name]
else:
# ignore this directory
tar2_cmdline = None
elif os.path.dirname(inner_name) == "dom0-home":
tar2_cmdline = ['cat']
redirect_stdout = subprocess.PIPE
elif inner_name in self.handlers:
tar2_cmdline = ['tar',
'-%svvO' % ("t" if self.verify_only else "x"),
inner_name]
redirect_stdout = subprocess.PIPE
else:
# no handlers for this file, ignore it
tar2_cmdline = None
if tar2_cmdline is None:
# ignore the file
os.remove(filename)
continue
tar_compress_cmd = None
if self.compressed:
if self.compression_filter:
tar_compress_cmd = self.compression_filter
else:
tar_compress_cmd = DEFAULT_COMPRESSION_FILTER
if os.path.dirname(inner_name) == "dom0-home":
# Replaces 'cat' for compressed dom0-home!
tar2_cmdline = [tar_compress_cmd, "-d"]
else:
tar2_cmdline.insert(-1, "--use-compress-program=%s " %
tar_compress_cmd)
self.log.debug("Running command %s", str(tar2_cmdline))
# pylint: disable=consider-using-with
if self.encrypted:
# Start decrypt
self.decryptor_process = subprocess.Popen(
["openssl", "enc",
"-d",
"-" + self.crypto_algorithm,
"-md",
"MD5",
"-pass",
"pass:" + self.passphrase],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
self.tar2_process = subprocess.Popen(
tar2_cmdline,
stdin=self.decryptor_process.stdout,
stdout=redirect_stdout,
stderr=subprocess.PIPE)
self.decryptor_process.stdout.close()
input_pipe = self.decryptor_process.stdin
else:
self.tar2_process = subprocess.Popen(
tar2_cmdline,
stdin=subprocess.PIPE,
stdout=redirect_stdout,
stderr=subprocess.PIPE)
input_pipe = self.tar2_process.stdin
self.feed_tar2(filename, input_pipe)
if inner_name in self.handlers:
assert redirect_stdout is subprocess.PIPE
data_func = self.handlers[inner_name]
self.import_process = multiprocessing.Process(
target=self._data_import_wrapper,
args=([input_pipe.fileno()],
data_func, self.tar2_process))
self.import_process.start()
self.tar2_process.stdout.close()
self.tar2_stderr = []
elif not self.tar2_process:
# Extracting of the current archive failed, skip to the next
# archive
os.remove(filename)
continue
else:
# os.path.splitext fails to handle 'something/..000'
(basename, ext) = self.tar2_current_file.rsplit('.', 1)
previous_chunk_number = int(ext)
expected_filename = basename + '.%03d' % (
previous_chunk_number+1)
if expected_filename != filename:
self.cleanup_tar2(wait=True, terminate=True)
self.log.error(
'Unexpected file in archive: %s, expected %s',
filename, expected_filename)
os.remove(filename)
continue
self.log.debug("Releasing next chunk")
self.feed_tar2(filename, input_pipe)
self.tar2_current_file = filename
self.tar2_feeder.wait()
# check if any process failed
processes = {
'target': self.tar2_feeder,
'vmproc': self.vmproc,
'addproc': self.tar2_process,
'data_import': self.import_process,
'decryptor': self.decryptor_process,
}
self.check_processes(processes)
self.tar2_feeder = None
if callable(self.progress_callback):
self.progress_callback(os.path.getsize(filename))
# Delete the file as we don't need it anymore
self.log.debug('Removing file %s', filename)
os.remove(filename)
if self.tar2_process is not None:
input_pipe.close()
if filename == QUEUE_ERROR:
if self.decryptor_process:
self.decryptor_process.terminate()
self.decryptor_process.wait()
self.decryptor_process = None
self.cleanup_tar2(terminate=(filename == QUEUE_ERROR))
self.log.debug('Finished extracting thread')
def get_supported_hmac_algo(hmac_algorithm=None):
'''Generate a list of supported hmac algorithms
:param hmac_algorithm: default algorithm, if given, it is placed as a
first element
'''
# Start with provided default
if hmac_algorithm:
yield hmac_algorithm
if hmac_algorithm != 'scrypt':
yield 'scrypt'
with subprocess.Popen(
'openssl list-message-digest-algorithms || '
'openssl list -digest-algorithms',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL) as proc:
for algo in proc.stdout.readlines():
algo = algo.decode('ascii')
if '=>' in algo:
continue
yield algo.strip().lower()
def get_supported_crypto_algo(crypto_algorithm=None):
'''Generate a list of supported hmac algorithms
:param crypto_algorithm: default algorithm, if given, it is placed as a
first element
'''
# Start with provided default
if crypto_algorithm:
yield crypto_algorithm
if crypto_algorithm != 'scrypt':
yield 'scrypt'
with subprocess.Popen(
'openssl list-cipher-algorithms || '
'openssl list -cipher-algorithms',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL) as proc:
for algo in proc.stdout.readlines():
algo = algo.decode('ascii')
if '=>' in algo:
continue
yield algo.strip().lower()
class BackupRestoreOptions(object):
'''Options for restore operation'''
# pylint: disable=too-few-public-methods
def __init__(self):
#: use default NetVM if the one referenced in backup do not exists on
# the host
self.use_default_netvm = True
#: set NetVM to "none" if the one referenced in backup do not exists
# on the host
self.use_none_netvm = False
#: set template to default if the one referenced in backup do not
# exists on the host
self.use_default_template = True
#: use default kernel if the one referenced in backup do not exists
# on the host
self.use_default_kernel = True
#: restore dom0 home
self.dom0_home = True
#: restore dom0 home even if username is different
self.ignore_username_mismatch = False
#: do not restore data, only verify backup integrity
self.verify_only = False
#: automatically rename VM during restore, when it would conflict
# with existing one
self.rename_conflicting = True
#: list of VM names to exclude
self.exclude = []
#: restore VMs into selected storage pool
self.override_pool = None
#: ignore size limit calculated from backup metadata
self.ignore_size_limit = False
class BackupRestore(object):
"""Usage:
>>> restore_op = BackupRestore(...)
>>> # adjust restore_op.options here
>>> restore_info = restore_op.get_restore_info()
>>> # manipulate restore_info to select VMs to restore here
>>> restore_op.restore_do(restore_info)
"""
class VMToRestore(object):
'''Information about a single VM to be restored'''
# pylint: disable=too-few-public-methods
#: VM excluded from restore by user
EXCLUDED = object()
#: VM with such name already exists on the host
ALREADY_EXISTS = object()
#: NetVM used by the VM does not exists on the host
MISSING_NETVM = object()
#: TemplateVM used by the VM does not exists on the host
MISSING_TEMPLATE = object()
#: Kernel used by the VM does not exists on the host
MISSING_KERNEL = object()
def __init__(self, vm):
assert isinstance(vm, BackupVM)
self.vm = vm
self.name = vm.name
self.subdir = vm.backup_path
self.size = vm.size
self.problems = set()
self.template = vm.template
if vm.properties.get('netvm', None):
self.netvm = vm.properties['netvm']
else:
self.netvm = None
self.orig_template = None
self.restored_vm = None
@property
def good_to_go(self):
'''Is the VM ready for restore?'''
return len(self.problems) == 0
class Dom0ToRestore(VMToRestore):
'''Information about dom0 home to restore'''
# pylint: disable=too-few-public-methods
#: backup was performed on system with different dom0 username
USERNAME_MISMATCH = object()
def __init__(self, vm, subdir=None):
super().__init__(vm)
if subdir:
self.subdir = subdir
self.username = os.path.basename(subdir)
def __init__(self, app, backup_location, backup_vm, passphrase, *,
location_is_service=False, force_compression_filter=None,
tmpdir=None):
super().__init__()
#: qubes.Qubes instance
self.app = app
#: options how the backup should be restored
self.options = BackupRestoreOptions()
#: VM from which backup should be retrieved
self.backup_vm = backup_vm
if backup_vm and backup_vm.name == 'dom0':
self.backup_vm = None
#: backup path, inside VM pointed by :py:attr:`backup_vm`
self.backup_location = backup_location
#: use alternative qrexec service to retrieve backup data, instead of
#: ``qubes.Restore`` with *backup_location* given on stdin
self.location_is_service = location_is_service
#: force using specific application for (de)compression, instead of
#: the one named in the backup header
self.force_compression_filter = force_compression_filter
#: passphrase protecting backup integrity and optionally decryption
self.passphrase = passphrase
if tmpdir is None:
# put it here, to enable qfile-unpacker even on SELinux-enabled
# system
tmpdir = os.path.expanduser("~/QubesIncoming")
#: temporary directory used to extract the data before moving to the
# final location
# due to possible location in ~/QubesIncoming, the prefix should not be
# a valid VM name
os.makedirs(tmpdir, exist_ok=True)
self.tmpdir = tempfile.mkdtemp(prefix="backup#restore-", dir=tmpdir)
#: list of processes (Popen objects) to kill on cancel
self.processes_to_kill_on_cancel = []
#: is the backup operation canceled
self.canceled = False
#: report restore progress, called with one argument - percents of
# data restored
# FIXME: convert to float [0,1]
self.progress_callback = None
self.log = logging.getLogger('qubesadmin.backup')
#: basic information about the backup
self.header_data = self._retrieve_backup_header()
#: VMs included in the backup
self.backup_app = self._process_qubes_xml()
def _start_retrieval_process(self, filelist, limit_count, limit_bytes):
"""Retrieve backup stream and extract it to :py:attr:`tmpdir`
:param filelist: list of files to extract; listing directory name
will extract the whole directory; use empty list to extract the whole
archive
:param limit_count: maximum number of files to extract
:param limit_bytes: maximum size of extracted data
:return: a touple of (Popen object of started process, file-like
object for reading extracted files list, file-like object for reading
errors)
"""
# pylint: disable=consider-using-with
vmproc = None
if self.backup_vm is not None:
# If APPVM, STDOUT is a PIPE
if self.location_is_service:
vmproc = self.backup_vm.run_service(self.backup_location)
else:
vmproc = self.backup_vm.run_service('qubes.Restore')
vmproc.stdin.write(
(self.backup_location.replace("\r", "").replace("\n",
"") + "\n").encode())
vmproc.stdin.flush()
# Send to tar2qfile the VMs that should be extracted
vmproc.stdin.write((" ".join(filelist) + "\n").encode())
vmproc.stdin.flush()
self.processes_to_kill_on_cancel.append(vmproc)
backup_stdin = vmproc.stdout
if isinstance(self.app, qubesadmin.app.QubesRemote):
qfile_unpacker_path = '/usr/lib/qubes/qfile-unpacker'