restore.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. '''Backup restore module'''
  21. import errno
  22. import fcntl
  23. import functools
  24. import getpass
  25. import grp
  26. import logging
  27. import multiprocessing
  28. from multiprocessing import Queue, Process
  29. import os
  30. import pwd
  31. import re
  32. import shutil
  33. import subprocess
  34. import sys
  35. import tempfile
  36. import termios
  37. import time
  38. import qubesadmin
  39. import qubesadmin.vm
  40. from qubesadmin.backup import BackupVM
  41. from qubesadmin.backup.core2 import Core2Qubes
  42. from qubesadmin.backup.core3 import Core3Qubes
  43. from qubesadmin.devices import DeviceAssignment
  44. from qubesadmin.exc import QubesException
  45. from qubesadmin.utils import size_to_human
  46. # must be picklable
  47. QUEUE_FINISHED = "!!!FINISHED"
  48. QUEUE_ERROR = "!!!ERROR"
  49. HEADER_FILENAME = 'backup-header'
  50. DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
  51. # 'scrypt' is not exactly HMAC algorithm, but a tool we use to
  52. # integrity-protect the data
  53. DEFAULT_HMAC_ALGORITHM = 'scrypt'
  54. DEFAULT_COMPRESSION_FILTER = 'gzip'
  55. # Maximum size of error message get from process stderr (including VM process)
  56. MAX_STDERR_BYTES = 1024
  57. # header + qubes.xml max size
  58. HEADER_QUBES_XML_MAX_SIZE = 1024 * 1024
  59. # hmac file max size - regardless of backup format version!
  60. HMAC_MAX_SIZE = 4096
  61. BLKSIZE = 512
  62. _re_alphanum = re.compile(r'^[A-Za-z0-9-]*$')
  63. _tar_msg_re = re.compile(r".*#[0-9].*restore_pipe")
  64. _tar_file_size_re = re.compile(r"^[^ ]+ [^ ]+/[^ ]+ *([0-9]+) .*")
  65. class BackupCanceledError(QubesException):
  66. '''Exception raised when backup/restore was cancelled'''
  67. def __init__(self, msg, tmpdir=None):
  68. super(BackupCanceledError, self).__init__(msg)
  69. self.tmpdir = tmpdir
  70. class BackupHeader(object):
  71. '''Structure describing backup-header file included as the first file in
  72. backup archive
  73. '''
  74. header_keys = {
  75. 'version': 'version',
  76. 'encrypted': 'encrypted',
  77. 'compressed': 'compressed',
  78. 'compression-filter': 'compression_filter',
  79. 'crypto-algorithm': 'crypto_algorithm',
  80. 'hmac-algorithm': 'hmac_algorithm',
  81. 'backup-id': 'backup_id'
  82. }
  83. bool_options = ['encrypted', 'compressed']
  84. int_options = ['version']
  85. def __init__(self,
  86. header_data=None,
  87. version=None,
  88. encrypted=None,
  89. compressed=None,
  90. compression_filter=None,
  91. hmac_algorithm=None,
  92. crypto_algorithm=None,
  93. backup_id=None):
  94. # repeat the list to help code completion...
  95. self.version = version
  96. self.encrypted = encrypted
  97. self.compressed = compressed
  98. # Options introduced in backup format 3+, which always have a header,
  99. # so no need for fallback in function parameter
  100. self.compression_filter = compression_filter
  101. self.hmac_algorithm = hmac_algorithm
  102. self.crypto_algorithm = crypto_algorithm
  103. self.backup_id = backup_id
  104. if header_data is not None:
  105. self.load(header_data)
  106. def load(self, untrusted_header_text):
  107. """Parse backup header file.
  108. :param untrusted_header_text: header content
  109. :type untrusted_header_text: basestring
  110. .. warning::
  111. This function may be exposed to not yet verified header,
  112. so is security critical.
  113. """
  114. try:
  115. untrusted_header_text = untrusted_header_text.decode('ascii')
  116. except UnicodeDecodeError:
  117. raise QubesException(
  118. "Non-ASCII characters in backup header")
  119. for untrusted_line in untrusted_header_text.splitlines():
  120. if untrusted_line.count('=') != 1:
  121. raise QubesException("Invalid backup header")
  122. key, value = untrusted_line.strip().split('=', 1)
  123. if not _re_alphanum.match(key):
  124. raise QubesException("Invalid backup header ("
  125. "key)")
  126. if key not in self.header_keys.keys():
  127. # Ignoring unknown option
  128. continue
  129. if not _re_alphanum.match(value):
  130. raise QubesException("Invalid backup header ("
  131. "value)")
  132. if getattr(self, self.header_keys[key]) is not None:
  133. raise QubesException(
  134. "Duplicated header line: {}".format(key))
  135. if key in self.bool_options:
  136. value = value.lower() in ["1", "true", "yes"]
  137. elif key in self.int_options:
  138. value = int(value)
  139. setattr(self, self.header_keys[key], value)
  140. self.validate()
  141. def validate(self):
  142. '''Validate header data, according to header version'''
  143. if self.version == 1:
  144. # header not really present
  145. pass
  146. elif self.version in [2, 3, 4]:
  147. expected_attrs = ['version', 'encrypted', 'compressed',
  148. 'hmac_algorithm']
  149. if self.encrypted and self.version < 4:
  150. expected_attrs += ['crypto_algorithm']
  151. if self.version >= 3 and self.compressed:
  152. expected_attrs += ['compression_filter']
  153. if self.version >= 4:
  154. expected_attrs += ['backup_id']
  155. for key in expected_attrs:
  156. if getattr(self, key) is None:
  157. raise QubesException(
  158. "Backup header lack '{}' info".format(key))
  159. else:
  160. raise QubesException(
  161. "Unsupported backup version {}".format(self.version))
  162. def save(self, filename):
  163. '''Save backup header into a file'''
  164. with open(filename, "w") as f_header:
  165. # make sure 'version' is the first key
  166. f_header.write('version={}\n'.format(self.version))
  167. for key, attr in self.header_keys.items():
  168. if key == 'version':
  169. continue
  170. if getattr(self, attr) is None:
  171. continue
  172. f_header.write("{!s}={!s}\n".format(key, getattr(self, attr)))
  173. def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
  174. """Similar to pty.fork, but handle stdin/stdout according to parameters
  175. instead of connecting to the pty
  176. :return tuple (subprocess.Popen, pty_master)
  177. """
  178. def set_ctty(ctty_fd, master_fd):
  179. '''Set controlling terminal'''
  180. os.setsid()
  181. os.close(master_fd)
  182. fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
  183. if not echo:
  184. termios_p = termios.tcgetattr(ctty_fd)
  185. # termios_p.c_lflags
  186. termios_p[3] &= ~termios.ECHO
  187. termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
  188. (pty_master, pty_slave) = os.openpty()
  189. # pylint: disable=subprocess-popen-preexec-fn
  190. p = subprocess.Popen(args, stdin=stdin, stdout=stdout,
  191. stderr=stderr,
  192. preexec_fn=lambda: set_ctty(pty_slave, pty_master))
  193. os.close(pty_slave)
  194. return p, open(pty_master, 'wb+', buffering=0)
  195. def launch_scrypt(action, input_name, output_name, passphrase):
  196. '''
  197. Launch 'scrypt' process, pass passphrase to it and return
  198. subprocess.Popen object.
  199. :param action: 'enc' or 'dec'
  200. :param input_name: input path or '-' for stdin
  201. :param output_name: output path or '-' for stdout
  202. :param passphrase: passphrase
  203. :return: subprocess.Popen object
  204. '''
  205. command_line = ['scrypt', action, input_name, output_name]
  206. (p, pty) = launch_proc_with_pty(command_line,
  207. stdin=subprocess.PIPE if input_name == '-' else None,
  208. stdout=subprocess.PIPE if output_name == '-' else None,
  209. stderr=subprocess.PIPE,
  210. echo=False)
  211. if action == 'enc':
  212. prompts = (b'Please enter passphrase: ', b'Please confirm passphrase: ')
  213. else:
  214. prompts = (b'Please enter passphrase: ',)
  215. for prompt in prompts:
  216. actual_prompt = p.stderr.read(len(prompt))
  217. if actual_prompt != prompt:
  218. raise QubesException(
  219. 'Unexpected prompt from scrypt: {}'.format(actual_prompt))
  220. pty.write(passphrase.encode('utf-8') + b'\n')
  221. pty.flush()
  222. # save it here, so garbage collector would not close it (which would kill
  223. # the child)
  224. p.pty = pty
  225. return p
  226. class ExtractWorker3(Process):
  227. '''Process for handling inner tar layer of backup archive'''
  228. # pylint: disable=too-many-instance-attributes
  229. def __init__(self, queue, base_dir, passphrase, encrypted,
  230. progress_callback, vmproc=None,
  231. compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
  232. compression_filter=None, verify_only=False, handlers=None):
  233. '''Start inner tar extraction worker
  234. The purpose of this class is to process files extracted from outer
  235. archive layer and pass to appropriate handlers. Input files are given
  236. through a queue. Insert :py:obj:`QUEUE_FINISHED` or
  237. :py:obj:`QUEUE_ERROR` to end data processing (either cleanly,
  238. or forcefully).
  239. Handlers are given as a map filename -> (data_func, size_func),
  240. where data_func is called with file-like object to process,
  241. and size_func is called with file size as argument. Note that
  242. data_func and size_func may be called simultaneusly, in a different
  243. processes.
  244. :param multiprocessing.Queue queue: a queue with filenames to
  245. process; those files needs to be given as full path, inside *base_dir*
  246. :param str base_dir: directory where all files to process live
  247. :param str passphrase: passphrase to decrypt the data
  248. :param bool encrypted: is encryption applied?
  249. :param callable progress_callback: report extraction progress
  250. :param subprocess.Popen vmproc: process extracting outer layer,
  251. given here to monitor
  252. it for failures (when it exits with non-zero exit code, inner layer
  253. processing is stopped)
  254. :param bool compressed: is the data compressed?
  255. :param str crypto_algorithm: encryption algorithm, either `scrypt` or an
  256. algorithm supported by openssl
  257. :param str compression_filter: compression program, `gzip` by default
  258. :param bool verify_only: only verify data integrity, do not extract
  259. :param dict handlers: handlers for actual data
  260. '''
  261. super(ExtractWorker3, self).__init__()
  262. #: queue with files to extract
  263. self.queue = queue
  264. #: paths on the queue are relative to this dir
  265. self.base_dir = base_dir
  266. #: passphrase to decrypt/authenticate data
  267. self.passphrase = passphrase
  268. #: handlers for files; it should be dict filename -> (data_function,
  269. # size_function),
  270. # where data_function will get file-like object as the only argument and
  271. # might be called in a separate process (multiprocessing.Process),
  272. # and size_function will get file size (when known) in bytes
  273. self.handlers = handlers
  274. #: is the backup encrypted?
  275. self.encrypted = encrypted
  276. #: is the backup compressed?
  277. self.compressed = compressed
  278. #: what crypto algorithm is used for encryption?
  279. self.crypto_algorithm = crypto_algorithm
  280. #: only verify integrity, don't extract anything
  281. self.verify_only = verify_only
  282. #: progress
  283. self.blocks_backedup = 0
  284. #: inner tar layer extraction (subprocess.Popen instance)
  285. self.tar2_process = None
  286. #: current inner tar archive name
  287. self.tar2_current_file = None
  288. #: cat process feeding tar2_process
  289. self.tar2_feeder = None
  290. #: decompressor subprocess.Popen instance
  291. self.decompressor_process = None
  292. #: decryptor subprocess.Popen instance
  293. self.decryptor_process = None
  294. #: data import multiprocessing.Process instance
  295. self.import_process = None
  296. #: callback reporting progress to UI
  297. self.progress_callback = progress_callback
  298. #: process (subprocess.Popen instance) feeding the data into
  299. # extraction tool
  300. self.vmproc = vmproc
  301. self.log = logging.getLogger('qubesadmin.backup.extract')
  302. self.stderr_encoding = sys.stderr.encoding or 'utf-8'
  303. self.tar2_stderr = []
  304. self.compression_filter = compression_filter
  305. def collect_tar_output(self):
  306. '''Retrieve tar stderr and handle it appropriately
  307. Log errors, process file size if requested.
  308. This use :py:attr:`tar2_process`.
  309. '''
  310. if not self.tar2_process.stderr:
  311. return
  312. if self.tar2_process.poll() is None:
  313. try:
  314. new_lines = self.tar2_process.stderr \
  315. .read(MAX_STDERR_BYTES).splitlines()
  316. except IOError as e:
  317. if e.errno == errno.EAGAIN:
  318. return
  319. raise
  320. else:
  321. new_lines = self.tar2_process.stderr.readlines()
  322. new_lines = [x.decode(self.stderr_encoding) for x in new_lines]
  323. debug_msg = [msg for msg in new_lines if _tar_msg_re.match(msg)]
  324. self.log.debug('tar2_stderr: %s', '\n'.join(debug_msg))
  325. new_lines = [msg for msg in new_lines if not _tar_msg_re.match(msg)]
  326. self.tar2_stderr += new_lines
  327. def run(self):
  328. try:
  329. self.__run__()
  330. except Exception:
  331. # Cleanup children
  332. for process in [self.decompressor_process,
  333. self.decryptor_process,
  334. self.tar2_process]:
  335. if process:
  336. try:
  337. process.terminate()
  338. except OSError:
  339. pass
  340. process.wait()
  341. self.log.exception('ERROR')
  342. raise
  343. def handle_dir(self, dirname):
  344. ''' Relocate files in given director when it's already extracted
  345. :param dirname: directory path to handle (relative to backup root),
  346. without trailing slash
  347. '''
  348. for fname, (data_func, size_func) in self.handlers.items():
  349. if not fname.startswith(dirname + '/'):
  350. continue
  351. if not os.path.exists(fname):
  352. # for example firewall.xml
  353. continue
  354. if size_func is not None:
  355. size_func(os.path.getsize(fname))
  356. with open(fname, 'rb') as input_file:
  357. data_func(input_file)
  358. os.unlink(fname)
  359. shutil.rmtree(dirname)
  360. def cleanup_tar2(self, wait=True, terminate=False):
  361. '''Cleanup running :py:attr:`tar2_process`
  362. :param wait: wait for it termination, otherwise method exit early if
  363. process is still running
  364. :param terminate: terminate the process if still running
  365. '''
  366. if self.tar2_process is None:
  367. return
  368. if terminate:
  369. if self.import_process is not None:
  370. self.tar2_process.terminate()
  371. self.import_process.terminate()
  372. if wait:
  373. self.tar2_process.wait()
  374. if self.import_process is not None:
  375. self.import_process.join()
  376. elif self.tar2_process.poll() is None:
  377. return
  378. self.collect_tar_output()
  379. if self.tar2_process.stderr:
  380. self.tar2_process.stderr.close()
  381. if self.tar2_process.returncode != 0:
  382. self.log.error(
  383. "ERROR: unable to extract files for %s, tar "
  384. "output:\n %s",
  385. self.tar2_current_file,
  386. "\n ".join(self.tar2_stderr))
  387. else:
  388. # Finished extracting the tar file
  389. # if that was whole-directory archive, handle
  390. # relocated files now
  391. inner_name = self.tar2_current_file.rsplit('.', 1)[0] \
  392. .replace(self.base_dir + '/', '')
  393. if os.path.basename(inner_name) == '.':
  394. self.handle_dir(
  395. os.path.dirname(inner_name))
  396. self.tar2_current_file = None
  397. self.tar2_process = None
  398. def _data_import_wrapper(self, close_fds, data_func, size_func,
  399. tar2_process):
  400. '''Close not needed file descriptors, handle output size reported
  401. by tar (if needed) then call data_func(tar2_process.stdout).
  402. This is to prevent holding write end of a pipe in subprocess,
  403. preventing EOF transfer.
  404. '''
  405. for fd in close_fds:
  406. if fd in (tar2_process.stdout.fileno(),
  407. tar2_process.stderr.fileno()):
  408. continue
  409. try:
  410. os.close(fd)
  411. except OSError:
  412. pass
  413. # retrieve file size from tar's stderr; warning: we do
  414. # not read data from tar's stdout at this point, it will
  415. # hang if it tries to output file content before
  416. # reporting its size on stderr first
  417. if size_func:
  418. # process lines on stderr until we get file size
  419. # search for first file size reported by tar -
  420. # this is used only when extracting single-file archive, so don't
  421. # bother with checking file name
  422. # Also, this needs to be called before anything is retrieved
  423. # from tar stderr, otherwise the process may deadlock waiting for
  424. # size (at this point nothing is retrieving data from tar stdout
  425. # yet, so it will hang on write() when the output pipe fill up).
  426. while True:
  427. line = tar2_process.stderr.readline()
  428. if not line:
  429. self.log.warning('EOF from tar before got file size info')
  430. break
  431. line = line.decode()
  432. if _tar_msg_re.match(line):
  433. self.log.debug('tar2_stderr: %s', line)
  434. else:
  435. match = _tar_file_size_re.match(line)
  436. if match:
  437. file_size = int(match.groups()[0])
  438. size_func(file_size)
  439. break
  440. else:
  441. self.log.warning(
  442. 'unexpected tar output (no file size report): %s',
  443. line)
  444. return data_func(tar2_process.stdout)
  445. def feed_tar2(self, filename, input_pipe):
  446. '''Feed data from *filename* to *input_pipe*
  447. Start a cat process to do that (do not block this process). Cat
  448. subprocess instance will be in :py:attr:`tar2_feeder`
  449. '''
  450. assert self.tar2_feeder is None
  451. self.tar2_feeder = subprocess.Popen(['cat', filename],
  452. stdout=input_pipe)
  453. def check_processes(self, processes):
  454. '''Check if any process failed.
  455. And if so, wait for other relevant processes to cleanup.
  456. '''
  457. run_error = None
  458. for name, proc in processes.items():
  459. if proc is None:
  460. continue
  461. if isinstance(proc, Process):
  462. if not proc.is_alive() and proc.exitcode != 0:
  463. run_error = name
  464. break
  465. elif proc.poll():
  466. run_error = name
  467. break
  468. if run_error:
  469. if run_error == "target":
  470. self.collect_tar_output()
  471. details = "\n".join(self.tar2_stderr)
  472. else:
  473. details = "%s failed" % run_error
  474. if self.decryptor_process:
  475. self.decryptor_process.terminate()
  476. self.decryptor_process.wait()
  477. self.decryptor_process = None
  478. self.log.error('Error while processing \'%s\': %s',
  479. self.tar2_current_file, details)
  480. self.cleanup_tar2(wait=True, terminate=True)
  481. def __run__(self):
  482. self.log.debug("Started sending thread")
  483. self.log.debug("Moving to dir %s", self.base_dir)
  484. os.chdir(self.base_dir)
  485. filename = None
  486. input_pipe = None
  487. for filename in iter(self.queue.get, None):
  488. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  489. break
  490. assert isinstance(filename, str)
  491. self.log.debug("Extracting file %s", filename)
  492. if filename.endswith('.000'):
  493. # next file
  494. if self.tar2_process is not None:
  495. input_pipe.close()
  496. self.cleanup_tar2(wait=True, terminate=False)
  497. inner_name = filename[:-len('.000')].replace(
  498. self.base_dir + '/', '')
  499. redirect_stdout = None
  500. if os.path.basename(inner_name) == '.':
  501. if (inner_name in self.handlers or
  502. any(x.startswith(os.path.dirname(inner_name) + '/')
  503. for x in self.handlers)):
  504. tar2_cmdline = ['tar',
  505. '-%s' % ("t" if self.verify_only else "x"),
  506. inner_name]
  507. else:
  508. # ignore this directory
  509. tar2_cmdline = None
  510. elif os.path.dirname(inner_name) == "dom0-home":
  511. tar2_cmdline = ['cat']
  512. redirect_stdout = subprocess.PIPE
  513. elif inner_name in self.handlers:
  514. tar2_cmdline = ['tar',
  515. '-%svvO' % ("t" if self.verify_only else "x"),
  516. inner_name]
  517. redirect_stdout = subprocess.PIPE
  518. else:
  519. # no handlers for this file, ignore it
  520. tar2_cmdline = None
  521. if tar2_cmdline is None:
  522. # ignore the file
  523. os.remove(filename)
  524. continue
  525. tar_compress_cmd = None
  526. if self.compressed:
  527. if self.compression_filter:
  528. tar_compress_cmd = self.compression_filter
  529. else:
  530. tar_compress_cmd = DEFAULT_COMPRESSION_FILTER
  531. if os.path.dirname(inner_name) == "dom0-home":
  532. # Replaces 'cat' for compressed dom0-home!
  533. tar2_cmdline = [tar_compress_cmd, "-d"]
  534. else:
  535. tar2_cmdline.insert(-1, "--use-compress-program=%s " %
  536. tar_compress_cmd)
  537. self.log.debug("Running command %s", str(tar2_cmdline))
  538. if self.encrypted:
  539. # Start decrypt
  540. self.decryptor_process = subprocess.Popen(
  541. ["openssl", "enc",
  542. "-d",
  543. "-" + self.crypto_algorithm,
  544. "-pass",
  545. "pass:" + self.passphrase],
  546. stdin=subprocess.PIPE,
  547. stdout=subprocess.PIPE)
  548. self.tar2_process = subprocess.Popen(
  549. tar2_cmdline,
  550. stdin=self.decryptor_process.stdout,
  551. stdout=redirect_stdout,
  552. stderr=subprocess.PIPE)
  553. self.decryptor_process.stdout.close()
  554. input_pipe = self.decryptor_process.stdin
  555. else:
  556. self.tar2_process = subprocess.Popen(
  557. tar2_cmdline,
  558. stdin=subprocess.PIPE,
  559. stdout=redirect_stdout,
  560. stderr=subprocess.PIPE)
  561. input_pipe = self.tar2_process.stdin
  562. self.feed_tar2(filename, input_pipe)
  563. if inner_name in self.handlers:
  564. assert redirect_stdout is subprocess.PIPE
  565. data_func, size_func = self.handlers[inner_name]
  566. self.import_process = multiprocessing.Process(
  567. target=self._data_import_wrapper,
  568. args=([input_pipe.fileno()],
  569. data_func, size_func, self.tar2_process))
  570. self.import_process.start()
  571. self.tar2_process.stdout.close()
  572. self.tar2_stderr = []
  573. elif not self.tar2_process:
  574. # Extracting of the current archive failed, skip to the next
  575. # archive
  576. os.remove(filename)
  577. continue
  578. else:
  579. # os.path.splitext fails to handle 'something/..000'
  580. (basename, ext) = self.tar2_current_file.rsplit('.', 1)
  581. previous_chunk_number = int(ext)
  582. expected_filename = basename + '.%03d' % (
  583. previous_chunk_number+1)
  584. if expected_filename != filename:
  585. self.cleanup_tar2(wait=True, terminate=True)
  586. self.log.error(
  587. 'Unexpected file in archive: %s, expected %s',
  588. filename, expected_filename)
  589. os.remove(filename)
  590. continue
  591. self.log.debug("Releasing next chunk")
  592. self.feed_tar2(filename, input_pipe)
  593. self.tar2_current_file = filename
  594. self.tar2_feeder.wait()
  595. # check if any process failed
  596. processes = {
  597. 'target': self.tar2_feeder,
  598. 'vmproc': self.vmproc,
  599. 'addproc': self.tar2_process,
  600. 'data_import': self.import_process,
  601. 'decryptor': self.decryptor_process,
  602. }
  603. self.check_processes(processes)
  604. self.tar2_feeder = None
  605. if callable(self.progress_callback):
  606. self.progress_callback(os.path.getsize(filename))
  607. # Delete the file as we don't need it anymore
  608. self.log.debug('Removing file %s', filename)
  609. os.remove(filename)
  610. if self.tar2_process is not None:
  611. input_pipe.close()
  612. if filename == QUEUE_ERROR:
  613. if self.decryptor_process:
  614. self.decryptor_process.terminate()
  615. self.decryptor_process.wait()
  616. self.decryptor_process = None
  617. self.cleanup_tar2(terminate=(filename == QUEUE_ERROR))
  618. self.log.debug('Finished extracting thread')
  619. def get_supported_hmac_algo(hmac_algorithm=None):
  620. '''Generate a list of supported hmac algorithms
  621. :param hmac_algorithm: default algorithm, if given, it is placed as a
  622. first element
  623. '''
  624. # Start with provided default
  625. if hmac_algorithm:
  626. yield hmac_algorithm
  627. if hmac_algorithm != 'scrypt':
  628. yield 'scrypt'
  629. proc = subprocess.Popen(
  630. 'openssl list-message-digest-algorithms || '
  631. 'openssl list -digest-algorithms',
  632. shell=True,
  633. stdout=subprocess.PIPE,
  634. stderr=subprocess.DEVNULL)
  635. try:
  636. for algo in proc.stdout.readlines():
  637. algo = algo.decode('ascii')
  638. if '=>' in algo:
  639. continue
  640. yield algo.strip()
  641. finally:
  642. proc.terminate()
  643. proc.wait()
  644. proc.stdout.close()
  645. class BackupRestoreOptions(object):
  646. '''Options for restore operation'''
  647. # pylint: disable=too-few-public-methods
  648. def __init__(self):
  649. #: use default NetVM if the one referenced in backup do not exists on
  650. # the host
  651. self.use_default_netvm = True
  652. #: set NetVM to "none" if the one referenced in backup do not exists
  653. # on the host
  654. self.use_none_netvm = False
  655. #: set template to default if the one referenced in backup do not
  656. # exists on the host
  657. self.use_default_template = True
  658. #: use default kernel if the one referenced in backup do not exists
  659. # on the host
  660. self.use_default_kernel = True
  661. #: restore dom0 home
  662. self.dom0_home = True
  663. #: restore dom0 home even if username is different
  664. self.ignore_username_mismatch = False
  665. #: do not restore data, only verify backup integrity
  666. self.verify_only = False
  667. #: automatically rename VM during restore, when it would conflict
  668. # with existing one
  669. self.rename_conflicting = True
  670. #: list of VM names to exclude
  671. self.exclude = []
  672. #: restore VMs into selected storage pool
  673. self.override_pool = None
  674. #: ignore size limit calculated from backup metadata
  675. self.ignore_size_limit = False
  676. class BackupRestore(object):
  677. """Usage:
  678. >>> restore_op = BackupRestore(...)
  679. >>> # adjust restore_op.options here
  680. >>> restore_info = restore_op.get_restore_info()
  681. >>> # manipulate restore_info to select VMs to restore here
  682. >>> restore_op.restore_do(restore_info)
  683. """
  684. class VMToRestore(object):
  685. '''Information about a single VM to be restored'''
  686. # pylint: disable=too-few-public-methods
  687. #: VM excluded from restore by user
  688. EXCLUDED = object()
  689. #: VM with such name already exists on the host
  690. ALREADY_EXISTS = object()
  691. #: NetVM used by the VM does not exists on the host
  692. MISSING_NETVM = object()
  693. #: TemplateVM used by the VM does not exists on the host
  694. MISSING_TEMPLATE = object()
  695. #: Kernel used by the VM does not exists on the host
  696. MISSING_KERNEL = object()
  697. def __init__(self, vm):
  698. assert isinstance(vm, BackupVM)
  699. self.vm = vm
  700. self.name = vm.name
  701. self.subdir = vm.backup_path
  702. self.size = vm.size
  703. self.problems = set()
  704. self.template = vm.template
  705. if vm.properties.get('netvm', None):
  706. self.netvm = vm.properties['netvm']
  707. else:
  708. self.netvm = None
  709. self.orig_template = None
  710. self.restored_vm = None
  711. @property
  712. def good_to_go(self):
  713. '''Is the VM ready for restore?'''
  714. return len(self.problems) == 0
  715. class Dom0ToRestore(VMToRestore):
  716. '''Information about dom0 home to restore'''
  717. # pylint: disable=too-few-public-methods
  718. #: backup was performed on system with different dom0 username
  719. USERNAME_MISMATCH = object()
  720. def __init__(self, vm, subdir=None):
  721. super(BackupRestore.Dom0ToRestore, self).__init__(vm)
  722. if subdir:
  723. self.subdir = subdir
  724. self.username = os.path.basename(subdir)
  725. def __init__(self, app, backup_location, backup_vm, passphrase):
  726. super(BackupRestore, self).__init__()
  727. #: qubes.Qubes instance
  728. self.app = app
  729. #: options how the backup should be restored
  730. self.options = BackupRestoreOptions()
  731. #: VM from which backup should be retrieved
  732. self.backup_vm = backup_vm
  733. if backup_vm and backup_vm.qid == 0:
  734. self.backup_vm = None
  735. #: backup path, inside VM pointed by :py:attr:`backup_vm`
  736. self.backup_location = backup_location
  737. #: passphrase protecting backup integrity and optionally decryption
  738. self.passphrase = passphrase
  739. #: temporary directory used to extract the data before moving to the
  740. # final location
  741. self.tmpdir = tempfile.mkdtemp(prefix="restore", dir="/var/tmp")
  742. #: list of processes (Popen objects) to kill on cancel
  743. self.processes_to_kill_on_cancel = []
  744. #: is the backup operation canceled
  745. self.canceled = False
  746. #: report restore progress, called with one argument - percents of
  747. # data restored
  748. # FIXME: convert to float [0,1]
  749. self.progress_callback = None
  750. self.log = logging.getLogger('qubesadmin.backup')
  751. #: basic information about the backup
  752. self.header_data = self._retrieve_backup_header()
  753. #: VMs included in the backup
  754. self.backup_app = self._process_qubes_xml()
  755. def _start_retrieval_process(self, filelist, limit_count, limit_bytes):
  756. """Retrieve backup stream and extract it to :py:attr:`tmpdir`
  757. :param filelist: list of files to extract; listing directory name
  758. will extract the whole directory; use empty list to extract the whole
  759. archive
  760. :param limit_count: maximum number of files to extract
  761. :param limit_bytes: maximum size of extracted data
  762. :return: a touple of (Popen object of started process, file-like
  763. object for reading extracted files list, file-like object for reading
  764. errors)
  765. """
  766. vmproc = None
  767. if self.backup_vm is not None:
  768. # If APPVM, STDOUT is a PIPE
  769. vmproc = self.backup_vm.run_service('qubes.Restore')
  770. vmproc.stdin.write(
  771. (self.backup_location.replace("\r", "").replace("\n",
  772. "") + "\n").encode())
  773. vmproc.stdin.flush()
  774. # Send to tar2qfile the VMs that should be extracted
  775. vmproc.stdin.write((" ".join(filelist) + "\n").encode())
  776. vmproc.stdin.flush()
  777. self.processes_to_kill_on_cancel.append(vmproc)
  778. backup_stdin = vmproc.stdout
  779. # FIXME use /usr/lib/qubes/qfile-unpacker in non-dom0
  780. tar1_command = ['/usr/libexec/qubes/qfile-dom0-unpacker',
  781. str(os.getuid()), self.tmpdir, '-v']
  782. else:
  783. backup_stdin = open(self.backup_location, 'rb')
  784. tar1_command = ['tar',
  785. '-ixv',
  786. '--occurrence=1',
  787. '-C', self.tmpdir] + filelist
  788. tar1_env = os.environ.copy()
  789. tar1_env['UPDATES_MAX_BYTES'] = str(limit_bytes)
  790. tar1_env['UPDATES_MAX_FILES'] = str(limit_count)
  791. self.log.debug("Run command %s", str(tar1_command))
  792. command = subprocess.Popen(
  793. tar1_command,
  794. stdin=backup_stdin,
  795. stdout=vmproc.stdin if vmproc else subprocess.PIPE,
  796. stderr=subprocess.PIPE,
  797. env=tar1_env)
  798. backup_stdin.close()
  799. self.processes_to_kill_on_cancel.append(command)
  800. # qfile-dom0-unpacker output filelist on stderr
  801. # and have stdout connected to the VM), while tar output filelist
  802. # on stdout
  803. if self.backup_vm:
  804. filelist_pipe = command.stderr
  805. # let qfile-dom0-unpacker hold the only open FD to the write end of
  806. # pipe, otherwise qrexec-client will not receive EOF when
  807. # qfile-dom0-unpacker terminates
  808. vmproc.stdin.close()
  809. else:
  810. filelist_pipe = command.stdout
  811. if self.backup_vm:
  812. error_pipe = vmproc.stderr
  813. else:
  814. error_pipe = command.stderr
  815. return command, filelist_pipe, error_pipe
  816. def _verify_hmac(self, filename, hmacfile, algorithm=None):
  817. '''Verify hmac of a file using given algorithm.
  818. If algorithm is not specified, use the one from backup header (
  819. :py:attr:`header_data`).
  820. Raise :py:exc:`QubesException` on failure, return :py:obj:`True` on
  821. success.
  822. 'scrypt' algorithm is supported only for header file; hmac file is
  823. encrypted (and integrity protected) version of plain header.
  824. :param filename: path to file to be verified
  825. :param hmacfile: path to hmac file for *filename*
  826. :param algorithm: override algorithm
  827. '''
  828. def load_hmac(hmac_text):
  829. '''Parse hmac output by openssl.
  830. Return just hmac, without filename and other metadata.
  831. '''
  832. if any(ord(x) not in range(128) for x in hmac_text):
  833. raise QubesException(
  834. "Invalid content of {}".format(hmacfile))
  835. hmac_text = hmac_text.strip().split("=")
  836. if len(hmac_text) > 1:
  837. hmac_text = hmac_text[1].strip()
  838. else:
  839. raise QubesException(
  840. "ERROR: invalid hmac file content")
  841. return hmac_text
  842. if algorithm is None:
  843. algorithm = self.header_data.hmac_algorithm
  844. passphrase = self.passphrase.encode('utf-8')
  845. self.log.debug("Verifying file %s", filename)
  846. if os.stat(os.path.join(self.tmpdir, hmacfile)).st_size > \
  847. HMAC_MAX_SIZE:
  848. raise QubesException('HMAC file {} too large'.format(
  849. hmacfile))
  850. if hmacfile != filename + ".hmac":
  851. raise QubesException(
  852. "ERROR: expected hmac for {}, but got {}".
  853. format(filename, hmacfile))
  854. if algorithm == 'scrypt':
  855. # in case of 'scrypt' _verify_hmac is only used for backup header
  856. assert filename == HEADER_FILENAME
  857. self._verify_and_decrypt(hmacfile, HEADER_FILENAME + '.dec')
  858. f_name = os.path.join(self.tmpdir, filename)
  859. with open(f_name, 'rb') as f_one:
  860. with open(f_name + '.dec', 'rb') as f_two:
  861. if f_one.read() != f_two.read():
  862. raise QubesException(
  863. 'Invalid hmac on {}'.format(filename))
  864. else:
  865. return True
  866. with open(os.path.join(self.tmpdir, filename), 'rb') as f_input:
  867. hmac_proc = subprocess.Popen(
  868. ["openssl", "dgst", "-" + algorithm, "-hmac", passphrase],
  869. stdin=f_input,
  870. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  871. hmac_stdout, hmac_stderr = hmac_proc.communicate()
  872. if hmac_stderr:
  873. raise QubesException(
  874. "ERROR: verify file {0}: {1}".format(filename, hmac_stderr))
  875. else:
  876. self.log.debug("Loading hmac for file %s", filename)
  877. try:
  878. with open(os.path.join(self.tmpdir, hmacfile), 'r',
  879. encoding='ascii') as f_hmac:
  880. hmac = load_hmac(f_hmac.read())
  881. except UnicodeDecodeError as err:
  882. raise QubesException('Cannot load hmac file: ' + str(err))
  883. if hmac and load_hmac(hmac_stdout.decode('ascii')) == hmac:
  884. os.unlink(os.path.join(self.tmpdir, hmacfile))
  885. self.log.debug(
  886. "File verification OK -> Sending file %s", filename)
  887. return True
  888. raise QubesException(
  889. "ERROR: invalid hmac for file {0}: {1}. "
  890. "Is the passphrase correct?".
  891. format(filename, load_hmac(hmac_stdout.decode('ascii'))))
  892. def _verify_and_decrypt(self, filename, output=None):
  893. '''Handle scrypt-wrapped file
  894. Decrypt the file, and verify its integrity - both tasks handled by
  895. 'scrypt' tool. Filename (without extension) is also validated.
  896. :param filename: Input file name (relative to :py:attr:`tmpdir`),
  897. needs to have `.enc` or `.hmac` extension
  898. :param output: Output file name (relative to :py:attr:`tmpdir`),
  899. use :py:obj:`None` to use *filename* without extension
  900. :return: *filename* without extension
  901. '''
  902. assert filename.endswith('.enc') or filename.endswith('.hmac')
  903. fullname = os.path.join(self.tmpdir, filename)
  904. (origname, _) = os.path.splitext(filename)
  905. if output:
  906. fulloutput = os.path.join(self.tmpdir, output)
  907. else:
  908. fulloutput = os.path.join(self.tmpdir, origname)
  909. if origname == HEADER_FILENAME:
  910. passphrase = u'{filename}!{passphrase}'.format(
  911. filename=origname,
  912. passphrase=self.passphrase)
  913. else:
  914. passphrase = u'{backup_id}!{filename}!{passphrase}'.format(
  915. backup_id=self.header_data.backup_id,
  916. filename=origname,
  917. passphrase=self.passphrase)
  918. try:
  919. p = launch_scrypt('dec', fullname, fulloutput, passphrase)
  920. except OSError as err:
  921. raise QubesException('failed to decrypt {}: {!s}'.format(
  922. fullname, err))
  923. (_, stderr) = p.communicate()
  924. if hasattr(p, 'pty'):
  925. p.pty.close()
  926. if p.returncode != 0:
  927. os.unlink(fulloutput)
  928. raise QubesException('failed to decrypt {}: {}'.format(
  929. fullname, stderr))
  930. # encrypted file is no longer needed
  931. os.unlink(fullname)
  932. return origname
  933. def _retrieve_backup_header_files(self, files, allow_none=False):
  934. '''Retrieve backup header.
  935. Start retrieval process (possibly involving network access from
  936. another VM). Returns a collection of retrieved file paths.
  937. '''
  938. (retrieve_proc, filelist_pipe, error_pipe) = \
  939. self._start_retrieval_process(
  940. files, len(files), 1024 * 1024)
  941. filelist = filelist_pipe.read()
  942. filelist_pipe.close()
  943. retrieve_proc_returncode = retrieve_proc.wait()
  944. if retrieve_proc in self.processes_to_kill_on_cancel:
  945. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  946. extract_stderr = error_pipe.read(MAX_STDERR_BYTES)
  947. error_pipe.close()
  948. # wait for other processes (if any)
  949. for proc in self.processes_to_kill_on_cancel:
  950. if proc.wait() != 0:
  951. raise QubesException(
  952. "Backup header retrieval failed (exit code {})".format(
  953. proc.wait())
  954. )
  955. if retrieve_proc_returncode != 0:
  956. if not filelist and 'Not found in archive' in extract_stderr:
  957. if allow_none:
  958. return None
  959. raise QubesException(
  960. "unable to read the qubes backup file {0} ({1}): {2}".
  961. format(
  962. self.backup_location,
  963. retrieve_proc.wait(),
  964. extract_stderr
  965. ))
  966. actual_files = filelist.decode('ascii').splitlines()
  967. if sorted(actual_files) != sorted(files):
  968. raise QubesException(
  969. 'unexpected files in archive: got {!r}, expected {!r}'.format(
  970. actual_files, files
  971. ))
  972. for fname in files:
  973. if not os.path.exists(os.path.join(self.tmpdir, fname)):
  974. if allow_none:
  975. return None
  976. raise QubesException(
  977. 'Unable to retrieve file {} from backup {}: {}'.format(
  978. fname, self.backup_location, extract_stderr
  979. )
  980. )
  981. return files
  982. def _retrieve_backup_header(self):
  983. """Retrieve backup header and qubes.xml. Only backup header is
  984. analyzed, qubes.xml is left as-is
  985. (not even verified/decrypted/uncompressed)
  986. :return header_data
  987. :rtype :py:class:`BackupHeader`
  988. """
  989. if not self.backup_vm and os.path.exists(
  990. os.path.join(self.backup_location, 'qubes.xml')):
  991. # backup format version 1 doesn't have header
  992. header_data = BackupHeader()
  993. header_data.version = 1
  994. return header_data
  995. header_files = self._retrieve_backup_header_files(
  996. ['backup-header', 'backup-header.hmac'], allow_none=True)
  997. if not header_files:
  998. # R2-Beta3 didn't have backup header, so if none is found,
  999. # assume it's version=2 and use values present at that time
  1000. header_data = BackupHeader(
  1001. version=2,
  1002. # place explicitly this value, because it is what format_version
  1003. # 2 have
  1004. hmac_algorithm='SHA1',
  1005. crypto_algorithm='aes-256-cbc',
  1006. # TODO: set encrypted to something...
  1007. )
  1008. else:
  1009. filename = HEADER_FILENAME
  1010. hmacfile = HEADER_FILENAME + '.hmac'
  1011. self.log.debug("Got backup header and hmac: %s, %s",
  1012. filename, hmacfile)
  1013. file_ok = False
  1014. hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  1015. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  1016. try:
  1017. if self._verify_hmac(filename, hmacfile, hmac_algo):
  1018. file_ok = True
  1019. break
  1020. except QubesException as err:
  1021. self.log.debug(
  1022. 'Failed to verify %s using %s: %r',
  1023. hmacfile, hmac_algo, err)
  1024. # Ignore exception here, try the next algo
  1025. if not file_ok:
  1026. raise QubesException(
  1027. "Corrupted backup header (hmac verification "
  1028. "failed). Is the password correct?")
  1029. filename = os.path.join(self.tmpdir, filename)
  1030. with open(filename, 'rb') as f_header:
  1031. header_data = BackupHeader(f_header.read())
  1032. os.unlink(filename)
  1033. return header_data
  1034. def _start_inner_extraction_worker(self, queue, handlers):
  1035. """Start a worker process, extracting inner layer of bacup archive,
  1036. extract them to :py:attr:`tmpdir`.
  1037. End the data by pushing QUEUE_FINISHED or QUEUE_ERROR to the queue.
  1038. :param queue :py:class:`Queue` object to handle files from
  1039. """
  1040. # Setup worker to extract encrypted data chunks to the restore dirs
  1041. # Create the process here to pass it options extracted from
  1042. # backup header
  1043. extractor_params = {
  1044. 'queue': queue,
  1045. 'base_dir': self.tmpdir,
  1046. 'passphrase': self.passphrase,
  1047. 'encrypted': self.header_data.encrypted,
  1048. 'compressed': self.header_data.compressed,
  1049. 'crypto_algorithm': self.header_data.crypto_algorithm,
  1050. 'verify_only': self.options.verify_only,
  1051. 'progress_callback': self.progress_callback,
  1052. 'handlers': handlers,
  1053. }
  1054. self.log.debug(
  1055. 'Starting extraction worker in %s, file handlers map: %s',
  1056. self.tmpdir, repr(handlers))
  1057. format_version = self.header_data.version
  1058. if format_version in [3, 4]:
  1059. extractor_params['compression_filter'] = \
  1060. self.header_data.compression_filter
  1061. if format_version == 4:
  1062. # encryption already handled
  1063. extractor_params['encrypted'] = False
  1064. extract_proc = ExtractWorker3(**extractor_params)
  1065. else:
  1066. raise NotImplementedError(
  1067. "Backup format version %d not supported" % format_version)
  1068. extract_proc.start()
  1069. return extract_proc
  1070. @staticmethod
  1071. def _save_qubes_xml(path, stream):
  1072. '''Handler for qubes.xml.000 content - just save the data to a file'''
  1073. with open(path, 'wb') as f_qubesxml:
  1074. f_qubesxml.write(stream.read())
  1075. def _process_qubes_xml(self):
  1076. """Verify, unpack and load qubes.xml. Possibly convert its format if
  1077. necessary. It expect that :py:attr:`header_data` is already populated,
  1078. and :py:meth:`retrieve_backup_header` was called.
  1079. """
  1080. if self.header_data.version == 1:
  1081. raise NotImplementedError('Backup format version 1 not supported')
  1082. elif self.header_data.version in [2, 3]:
  1083. self._retrieve_backup_header_files(
  1084. ['qubes.xml.000', 'qubes.xml.000.hmac'])
  1085. self._verify_hmac("qubes.xml.000", "qubes.xml.000.hmac")
  1086. else:
  1087. self._retrieve_backup_header_files(['qubes.xml.000.enc'])
  1088. self._verify_and_decrypt('qubes.xml.000.enc')
  1089. queue = Queue()
  1090. queue.put("qubes.xml.000")
  1091. queue.put(QUEUE_FINISHED)
  1092. qubes_xml_path = os.path.join(self.tmpdir, 'qubes-restored.xml')
  1093. handlers = {
  1094. 'qubes.xml': (
  1095. functools.partial(self._save_qubes_xml, qubes_xml_path),
  1096. None)
  1097. }
  1098. extract_proc = self._start_inner_extraction_worker(queue, handlers)
  1099. extract_proc.join()
  1100. if extract_proc.exitcode != 0:
  1101. raise QubesException(
  1102. "unable to extract the qubes backup. "
  1103. "Check extracting process errors.")
  1104. if self.header_data.version in [2, 3]:
  1105. backup_app = Core2Qubes(qubes_xml_path)
  1106. elif self.header_data.version in [4]:
  1107. backup_app = Core3Qubes(qubes_xml_path)
  1108. else:
  1109. raise QubesException(
  1110. 'Unsupported qubes.xml format version: {}'.format(
  1111. self.header_data.version))
  1112. # Not needed anymore - all the data stored in backup_app
  1113. os.unlink(qubes_xml_path)
  1114. return backup_app
  1115. def _restore_vm_data(self, vms_dirs, vms_size, handlers):
  1116. '''Restore data of VMs
  1117. :param vms_dirs: list of directories to extract (skip others)
  1118. :param vms_size: expected size (abort if source stream exceed this
  1119. value)
  1120. :param handlers: handlers for restored files - see
  1121. :py:class:`ExtractWorker3` for details
  1122. '''
  1123. # Currently each VM consists of at most 7 archives (count
  1124. # file_to_backup calls in backup_prepare()), but add some safety
  1125. # margin for further extensions. Each archive is divided into 100MB
  1126. # chunks. Additionally each file have own hmac file. So assume upper
  1127. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  1128. limit_count = str(2 * (10 * len(vms_dirs) +
  1129. int(vms_size / (100 * 1024 * 1024))))
  1130. if self.options.ignore_size_limit:
  1131. limit_count = '0'
  1132. vms_size = 0
  1133. self.log.debug("Working in temporary dir: %s", self.tmpdir)
  1134. self.log.info("Extracting data: %s to restore", size_to_human(vms_size))
  1135. # retrieve backup from the backup stream (either VM, or dom0 file)
  1136. (retrieve_proc, filelist_pipe, error_pipe) = \
  1137. self._start_retrieval_process(
  1138. vms_dirs, limit_count, vms_size)
  1139. to_extract = Queue()
  1140. # extract data retrieved by retrieve_proc
  1141. extract_proc = self._start_inner_extraction_worker(
  1142. to_extract, handlers)
  1143. try:
  1144. filename = None
  1145. hmacfile = None
  1146. nextfile = None
  1147. while True:
  1148. if self.canceled:
  1149. break
  1150. if not extract_proc.is_alive():
  1151. retrieve_proc.terminate()
  1152. retrieve_proc.wait()
  1153. if retrieve_proc in self.processes_to_kill_on_cancel:
  1154. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1155. # wait for other processes (if any)
  1156. for proc in self.processes_to_kill_on_cancel:
  1157. proc.wait()
  1158. break
  1159. if nextfile is not None:
  1160. filename = nextfile
  1161. else:
  1162. filename = filelist_pipe.readline().decode('ascii').strip()
  1163. self.log.debug("Getting new file: %s", filename)
  1164. if not filename or filename == "EOF":
  1165. break
  1166. # if reading archive directly with tar, wait for next filename -
  1167. # tar prints filename before processing it, so wait for
  1168. # the next one to be sure that whole file was extracted
  1169. if not self.backup_vm:
  1170. nextfile = filelist_pipe.readline().decode('ascii').strip()
  1171. if self.header_data.version in [2, 3]:
  1172. if not self.backup_vm:
  1173. hmacfile = nextfile
  1174. nextfile = filelist_pipe.readline().\
  1175. decode('ascii').strip()
  1176. else:
  1177. hmacfile = filelist_pipe.readline().\
  1178. decode('ascii').strip()
  1179. if self.canceled:
  1180. break
  1181. self.log.debug("Getting hmac: %s", hmacfile)
  1182. if not hmacfile or hmacfile == "EOF":
  1183. # Premature end of archive, either of tar1_command or
  1184. # vmproc exited with error
  1185. break
  1186. else: # self.header_data.version == 4
  1187. if not filename.endswith('.enc'):
  1188. raise qubesadmin.exc.QubesException(
  1189. 'Invalid file extension found in archive: {}'.
  1190. format(filename))
  1191. if not any(filename.startswith(x) for x in vms_dirs):
  1192. self.log.debug("Ignoring VM not selected for restore")
  1193. os.unlink(os.path.join(self.tmpdir, filename))
  1194. if hmacfile:
  1195. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1196. continue
  1197. if self.header_data.version in [2, 3]:
  1198. self._verify_hmac(filename, hmacfile)
  1199. else:
  1200. # _verify_and_decrypt will write output to a file with
  1201. # '.enc' extension cut off. This is safe because:
  1202. # - `scrypt` tool will override output, so if the file was
  1203. # already there (received from the VM), it will be removed
  1204. # - incoming archive extraction will refuse to override
  1205. # existing file, so if `scrypt` already created one,
  1206. # it can not be manipulated by the VM
  1207. # - when the file is retrieved from the VM, it appears at
  1208. # the final form - if it's visible, VM have no longer
  1209. # influence over its content
  1210. #
  1211. # This all means that if the file was correctly verified
  1212. # + decrypted, we will surely access the right file
  1213. filename = self._verify_and_decrypt(filename)
  1214. if not self.options.verify_only:
  1215. to_extract.put(os.path.join(self.tmpdir, filename))
  1216. else:
  1217. os.unlink(os.path.join(self.tmpdir, filename))
  1218. if self.canceled:
  1219. raise BackupCanceledError("Restore canceled",
  1220. tmpdir=self.tmpdir)
  1221. if retrieve_proc.wait() != 0:
  1222. if retrieve_proc.returncode == errno.EDQUOT:
  1223. raise QubesException(
  1224. 'retrieved backup size exceed expected size, if you '
  1225. 'believe this is ok, use --ignore-size-limit option')
  1226. else:
  1227. raise QubesException(
  1228. "unable to read the qubes backup file {} ({}): {}"
  1229. .format(self.backup_location,
  1230. retrieve_proc.returncode, error_pipe.read(
  1231. MAX_STDERR_BYTES)))
  1232. # wait for other processes (if any)
  1233. for proc in self.processes_to_kill_on_cancel:
  1234. proc.wait()
  1235. if proc.returncode != 0:
  1236. raise QubesException(
  1237. "Backup completed, "
  1238. "but VM sending it reported an error (exit code {})".
  1239. format(proc.returncode))
  1240. if filename and filename != "EOF":
  1241. raise QubesException(
  1242. "Premature end of archive, the last file was %s" % filename)
  1243. except:
  1244. to_extract.put(QUEUE_ERROR)
  1245. extract_proc.join()
  1246. raise
  1247. else:
  1248. to_extract.put(QUEUE_FINISHED)
  1249. finally:
  1250. error_pipe.close()
  1251. filelist_pipe.close()
  1252. self.log.debug("Waiting for the extraction process to finish...")
  1253. extract_proc.join()
  1254. self.log.debug("Extraction process finished with code: %s",
  1255. extract_proc.exitcode)
  1256. if extract_proc.exitcode != 0:
  1257. raise QubesException(
  1258. "unable to extract the qubes backup. "
  1259. "Check extracting process errors.")
  1260. def new_name_for_conflicting_vm(self, orig_name, restore_info):
  1261. '''Generate new name for conflicting VM
  1262. Add a number suffix, until the name is unique. If no unique name can
  1263. be found using this strategy, return :py:obj:`None`
  1264. '''
  1265. number = 1
  1266. if len(orig_name) > 29:
  1267. orig_name = orig_name[0:29]
  1268. new_name = orig_name
  1269. while (new_name in restore_info.keys() or
  1270. new_name in [x.name for x in restore_info.values()] or
  1271. new_name in self.app.domains):
  1272. new_name = str('{}{}'.format(orig_name, number))
  1273. number += 1
  1274. if number == 100:
  1275. # give up
  1276. return None
  1277. return new_name
  1278. def restore_info_verify(self, restore_info):
  1279. '''Verify restore info - validate VM dependencies, name conflicts
  1280. etc.
  1281. '''
  1282. for vm in restore_info.keys():
  1283. if vm in ['dom0']:
  1284. continue
  1285. vm_info = restore_info[vm]
  1286. assert isinstance(vm_info, self.VMToRestore)
  1287. vm_info.problems.clear()
  1288. if vm in self.options.exclude:
  1289. vm_info.problems.add(self.VMToRestore.EXCLUDED)
  1290. if not self.options.verify_only and \
  1291. vm_info.name in self.app.domains:
  1292. if self.options.rename_conflicting:
  1293. new_name = self.new_name_for_conflicting_vm(
  1294. vm, restore_info
  1295. )
  1296. if new_name is not None:
  1297. vm_info.name = new_name
  1298. else:
  1299. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1300. else:
  1301. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1302. # check template
  1303. if vm_info.template:
  1304. present_on_host = False
  1305. if vm_info.template in self.app.domains:
  1306. host_tpl = self.app.domains[vm_info.template]
  1307. if vm_info.vm.klass == 'DispVM':
  1308. present_on_host = (
  1309. getattr(host_tpl, 'template_for_dispvms', False))
  1310. else:
  1311. present_on_host = host_tpl.klass == 'TemplateVM'
  1312. present_in_backup = False
  1313. if vm_info.template in restore_info:
  1314. bak_tpl = restore_info[vm_info.template]
  1315. if bak_tpl.good_to_go:
  1316. if vm_info.vm.klass == 'DispVM':
  1317. present_in_backup = (
  1318. bak_tpl.vm.properties.get(
  1319. 'template_for_dispvms', False))
  1320. else:
  1321. present_in_backup = (
  1322. bak_tpl.vm.klass == 'TemplateVM')
  1323. self.log.debug(
  1324. "vm=%s template=%s on_host=%s in_backup=%s",
  1325. vm_info.name, vm_info.template,
  1326. present_on_host, present_in_backup)
  1327. if not present_on_host and not present_in_backup:
  1328. if vm_info.vm.klass == 'DispVM':
  1329. default_template = self.app.default_dispvm
  1330. else:
  1331. default_template = self.app.default_template
  1332. if (self.options.use_default_template
  1333. and default_template is not None):
  1334. if vm_info.orig_template is None:
  1335. vm_info.orig_template = vm_info.template
  1336. vm_info.template = default_template.name
  1337. self.log.debug(
  1338. "vm=%s orig_template=%s -> default_template=%s",
  1339. vm_info.name, vm_info.orig_template,
  1340. default_template.name)
  1341. else:
  1342. vm_info.problems.add(self.VMToRestore.MISSING_TEMPLATE)
  1343. # check netvm
  1344. if vm_info.vm.properties.get('netvm', None) is not None:
  1345. netvm_name = vm_info.netvm
  1346. try:
  1347. netvm_on_host = self.app.domains[netvm_name]
  1348. except KeyError:
  1349. netvm_on_host = None
  1350. present_on_host = (netvm_on_host is not None
  1351. and netvm_on_host.provides_network)
  1352. present_in_backup = (netvm_name in restore_info.keys() and
  1353. restore_info[netvm_name].good_to_go and
  1354. restore_info[netvm_name].vm.properties.get(
  1355. 'provides_network', False))
  1356. if not present_on_host and not present_in_backup:
  1357. if self.options.use_default_netvm:
  1358. del vm_info.vm.properties['netvm']
  1359. elif self.options.use_none_netvm:
  1360. vm_info.netvm = None
  1361. else:
  1362. vm_info.problems.add(self.VMToRestore.MISSING_NETVM)
  1363. return restore_info
  1364. def get_restore_info(self):
  1365. '''Get restore info
  1366. Return information about what is included in the backup.
  1367. That dictionary can be adjusted to select what VM should be restore.
  1368. '''
  1369. # Format versions:
  1370. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1371. # 2 - Qubes R2 beta3+
  1372. # 3 - Qubes R2+
  1373. # 4 - Qubes R4+
  1374. vms_to_restore = {}
  1375. for vm in self.backup_app.domains.values():
  1376. if vm.klass == 'AdminVM':
  1377. # Handle dom0 as special case later
  1378. continue
  1379. if vm.included_in_backup:
  1380. self.log.debug("%s is included in backup", vm.name)
  1381. vms_to_restore[vm.name] = self.VMToRestore(vm)
  1382. if vm.template is not None:
  1383. templatevm_name = vm.template
  1384. vms_to_restore[vm.name].template = templatevm_name
  1385. vms_to_restore = self.restore_info_verify(vms_to_restore)
  1386. # ...and dom0 home
  1387. if self.options.dom0_home and \
  1388. self.backup_app.domains['dom0'].included_in_backup:
  1389. vm = self.backup_app.domains['dom0']
  1390. vms_to_restore['dom0'] = self.Dom0ToRestore(vm,
  1391. self.backup_app.domains['dom0'].backup_path)
  1392. try:
  1393. local_user = grp.getgrnam('qubes').gr_mem[0]
  1394. except KeyError:
  1395. # if no qubes group is present, assume username matches
  1396. local_user = vms_to_restore['dom0'].username
  1397. if vms_to_restore['dom0'].username != local_user:
  1398. if not self.options.ignore_username_mismatch:
  1399. vms_to_restore['dom0'].problems.add(
  1400. self.Dom0ToRestore.USERNAME_MISMATCH)
  1401. return vms_to_restore
  1402. @staticmethod
  1403. def get_restore_summary(restore_info):
  1404. '''Return a ASCII formatted table with restore info summary'''
  1405. fields = {
  1406. "name": {'func': lambda vm: vm.name},
  1407. "type": {'func': lambda vm: vm.klass},
  1408. "template": {'func': lambda vm:
  1409. 'n/a' if vm.template is None else vm.template},
  1410. "netvm": {'func': lambda vm:
  1411. '(default)' if 'netvm' not in vm.properties else
  1412. '-' if vm.properties['netvm'] is None else
  1413. vm.properties['netvm']},
  1414. "label": {'func': lambda vm: vm.label},
  1415. }
  1416. fields_to_display = ['name', 'type', 'template',
  1417. 'netvm', 'label']
  1418. # First calculate the maximum width of each field we want to display
  1419. total_width = 0
  1420. for field in fields_to_display:
  1421. fields[field]['max_width'] = len(field)
  1422. for vm_info in restore_info.values():
  1423. if vm_info.vm:
  1424. # noinspection PyUnusedLocal
  1425. field_len = len(str(fields[field]["func"](vm_info.vm)))
  1426. if field_len > fields[field]['max_width']:
  1427. fields[field]['max_width'] = field_len
  1428. total_width += fields[field]['max_width']
  1429. summary = ""
  1430. summary += "The following VMs are included in the backup:\n"
  1431. summary += "\n"
  1432. # Display the header
  1433. for field in fields_to_display:
  1434. # noinspection PyTypeChecker
  1435. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1436. summary += fmt.format('-')
  1437. summary += "\n"
  1438. for field in fields_to_display:
  1439. # noinspection PyTypeChecker
  1440. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1441. summary += fmt.format(field)
  1442. summary += "\n"
  1443. for field in fields_to_display:
  1444. # noinspection PyTypeChecker
  1445. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1446. summary += fmt.format('-')
  1447. summary += "\n"
  1448. for vm_info in restore_info.values():
  1449. assert isinstance(vm_info, BackupRestore.VMToRestore)
  1450. # Skip non-VM here
  1451. if not vm_info.vm:
  1452. continue
  1453. # noinspection PyUnusedLocal
  1454. summary_line = ""
  1455. for field in fields_to_display:
  1456. # noinspection PyTypeChecker
  1457. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1458. summary_line += fmt.format(fields[field]["func"](vm_info.vm))
  1459. if BackupRestore.VMToRestore.EXCLUDED in vm_info.problems:
  1460. summary_line += " <-- Excluded from restore"
  1461. elif BackupRestore.VMToRestore.ALREADY_EXISTS in vm_info.problems:
  1462. summary_line += \
  1463. " <-- A VM with the same name already exists on the host!"
  1464. elif BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  1465. vm_info.problems:
  1466. summary_line += " <-- No matching template on the host " \
  1467. "or in the backup found!"
  1468. elif BackupRestore.VMToRestore.MISSING_NETVM in \
  1469. vm_info.problems:
  1470. summary_line += " <-- No matching netvm on the host " \
  1471. "or in the backup found!"
  1472. elif vm_info.name == "dom0" and \
  1473. BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  1474. restore_info['dom0'].problems:
  1475. summary_line += " <-- username in backup and dom0 mismatch"
  1476. else:
  1477. if vm_info.template != vm_info.vm.template:
  1478. summary_line += " <-- Template change to '{}'".format(
  1479. vm_info.template)
  1480. if vm_info.name != vm_info.vm.name:
  1481. summary_line += " <-- Will be renamed to '{}'".format(
  1482. vm_info.name)
  1483. summary += summary_line + "\n"
  1484. return summary
  1485. @staticmethod
  1486. def _templates_first(vms):
  1487. '''Sort templates before other VM types'''
  1488. def key_function(instance):
  1489. '''Key function for :py:func:`sorted`'''
  1490. if isinstance(instance, BackupVM):
  1491. if instance.klass == 'TemplateVM':
  1492. return 0
  1493. if instance.properties.get('template_for_dispvms', False):
  1494. return 1
  1495. return 2
  1496. if hasattr(instance, 'vm'):
  1497. return key_function(instance.vm)
  1498. return 9
  1499. return sorted(vms, key=key_function)
  1500. def _handle_dom0(self, stream):
  1501. '''Extract dom0 home'''
  1502. try:
  1503. local_user = grp.getgrnam('qubes').gr_mem[0]
  1504. home_dir = pwd.getpwnam(local_user).pw_dir
  1505. except KeyError:
  1506. home_dir = os.path.expanduser('~')
  1507. local_user = getpass.getuser()
  1508. restore_home_backupdir = "home-restore-{0}".format(
  1509. time.strftime("%Y-%m-%d-%H%M%S"))
  1510. self.log.info("Restoring home of user '%s' to '%s' directory...",
  1511. local_user, restore_home_backupdir)
  1512. os.mkdir(os.path.join(home_dir, restore_home_backupdir))
  1513. tar3_cmdline = ['tar', '-C',
  1514. os.path.join(home_dir, restore_home_backupdir), '-x']
  1515. retcode = subprocess.call(tar3_cmdline, stdin=stream)
  1516. if retcode != 0:
  1517. raise QubesException("Inner tar error for dom0-home")
  1518. retcode = subprocess.call(['sudo', 'chown', '-R',
  1519. local_user, os.path.join(home_dir, restore_home_backupdir)])
  1520. if retcode != 0:
  1521. self.log.error("*** Error while setting restore directory owner")
  1522. def _handle_appmenus_list(self, vm, stream):
  1523. '''Handle whitelisted-appmenus.list file'''
  1524. try:
  1525. subprocess.check_call(
  1526. ['qvm-appmenus', '--set-whitelist=-', vm.name],
  1527. stdin=stream)
  1528. except (subprocess.CalledProcessError, FileNotFoundError):
  1529. self.log.error('Failed to set application list for %s', vm.name)
  1530. def _handle_volume_data(self, vm, volume, stream):
  1531. '''Wrap volume data import with logging'''
  1532. try:
  1533. volume.import_data(stream)
  1534. except Exception as err: # pylint: disable=broad-except
  1535. self.log.error('Failed to restore volume %s of VM %s: %s',
  1536. volume.name, vm.name, err)
  1537. def _handle_volume_size(self, vm, volume, size):
  1538. '''Wrap volume resize with logging'''
  1539. try:
  1540. if volume.size < size:
  1541. volume.resize(size)
  1542. except Exception as err: # pylint: disable=broad-except
  1543. self.log.error('Failed to resize volume %s of VM %s to %d: %s',
  1544. volume.name, vm.name, size, err)
  1545. def restore_do(self, restore_info):
  1546. '''
  1547. High level workflow:
  1548. 1. Create VMs object in host collection (qubes.xml)
  1549. 2. Create them on disk (vm.create_on_disk)
  1550. 3. Restore VM data, overriding/converting VM files
  1551. 4. Apply possible fixups and save qubes.xml
  1552. :param restore_info:
  1553. :return:
  1554. '''
  1555. if self.header_data.version == 1:
  1556. raise NotImplementedError('Backup format version 1 not supported')
  1557. restore_info = self.restore_info_verify(restore_info)
  1558. self._restore_vms_metadata(restore_info)
  1559. # Perform VM restoration in backup order
  1560. vms_dirs = []
  1561. handlers = {}
  1562. vms_size = 0
  1563. for vm_info in self._templates_first(restore_info.values()):
  1564. vm = vm_info.restored_vm
  1565. if vm and vm_info.subdir:
  1566. if isinstance(vm_info, self.Dom0ToRestore) and \
  1567. vm_info.good_to_go:
  1568. vms_dirs.append(os.path.dirname(vm_info.subdir))
  1569. vms_size += int(vm_info.size)
  1570. if self.options.verify_only:
  1571. continue
  1572. handlers[vm_info.subdir] = (self._handle_dom0, None)
  1573. else:
  1574. vms_size += int(vm_info.size)
  1575. vms_dirs.append(vm_info.subdir)
  1576. if self.options.verify_only:
  1577. continue
  1578. for name, volume in vm.volumes.items():
  1579. if not volume.save_on_stop:
  1580. continue
  1581. data_func = functools.partial(
  1582. self._handle_volume_data, vm, volume)
  1583. size_func = functools.partial(
  1584. self._handle_volume_size, vm, volume)
  1585. img_path = os.path.join(vm_info.subdir, name + '.img')
  1586. handlers[img_path] = (data_func, size_func)
  1587. handlers[os.path.join(vm_info.subdir, 'firewall.xml')] = (
  1588. functools.partial(vm_info.vm.handle_firewall_xml, vm),
  1589. None)
  1590. handlers[os.path.join(vm_info.subdir,
  1591. 'whitelisted-appmenus.list')] = (
  1592. functools.partial(self._handle_appmenus_list, vm), None)
  1593. try:
  1594. self._restore_vm_data(vms_dirs=vms_dirs, vms_size=vms_size,
  1595. handlers=handlers)
  1596. except QubesException as err:
  1597. if self.options.verify_only:
  1598. raise
  1599. else:
  1600. self.log.error('Error extracting data: %s', str(err))
  1601. finally:
  1602. if self.log.getEffectiveLevel() > logging.DEBUG:
  1603. shutil.rmtree(self.tmpdir)
  1604. if self.canceled:
  1605. raise BackupCanceledError("Restore canceled",
  1606. tmpdir=self.tmpdir)
  1607. self.log.info("-> Done.")
  1608. if not self.options.verify_only:
  1609. self.log.info("-> Please install updates for all the restored "
  1610. "templates.")
  1611. def _restore_property(self, vm, prop, value):
  1612. '''Restore a single VM property, logging exceptions'''
  1613. try:
  1614. setattr(vm, prop, value)
  1615. except Exception as err: # pylint: disable=broad-except
  1616. self.log.error('Error setting %s.%s to %s: %s',
  1617. vm.name, prop, value, err)
  1618. def _restore_vms_metadata(self, restore_info):
  1619. '''Restore VM metadata
  1620. Create VMs, set their properties etc.
  1621. '''
  1622. vms = {}
  1623. for vm_info in restore_info.values():
  1624. assert isinstance(vm_info, self.VMToRestore)
  1625. if not vm_info.vm:
  1626. continue
  1627. if not vm_info.good_to_go:
  1628. continue
  1629. vm = vm_info.vm
  1630. vms[vm.name] = vm
  1631. # First load templates, then other VMs
  1632. for vm in self._templates_first(vms.values()):
  1633. if self.canceled:
  1634. return
  1635. if self.options.verify_only:
  1636. self.log.info("-> Verifying %s...", vm.name)
  1637. else:
  1638. self.log.info("-> Restoring %s...", vm.name)
  1639. kwargs = {}
  1640. if vm.template:
  1641. template = restore_info[vm.name].template
  1642. # handle potentially renamed template
  1643. if template in restore_info \
  1644. and restore_info[template].good_to_go:
  1645. template = restore_info[template].name
  1646. kwargs['template'] = template
  1647. new_vm = None
  1648. vm_name = restore_info[vm.name].name
  1649. if self.options.verify_only or vm.name == 'dom0':
  1650. # can't create vm, but need backup info
  1651. new_vm = self.backup_app.domains[vm_name]
  1652. else:
  1653. try:
  1654. # first only create VMs, later setting may require other VMs
  1655. # be already created
  1656. new_vm = self.app.add_new_vm(
  1657. vm.klass,
  1658. name=vm_name,
  1659. label=vm.label,
  1660. pool=self.options.override_pool,
  1661. **kwargs)
  1662. except Exception as err: # pylint: disable=broad-except
  1663. self.log.error('Error restoring VM %s, skipping: %s',
  1664. vm.name, err)
  1665. if new_vm:
  1666. del self.app.domains[new_vm.name]
  1667. continue
  1668. # restore this property early to be ready for dependent DispVMs
  1669. prop = 'template_for_dispvms'
  1670. value = vm.properties.get(prop, None)
  1671. if value is not None:
  1672. self._restore_property(new_vm, prop, value)
  1673. restore_info[vm.name].restored_vm = new_vm
  1674. for vm in vms.values():
  1675. if self.canceled:
  1676. return
  1677. new_vm = restore_info[vm.name].restored_vm
  1678. if not new_vm:
  1679. # skipped/failed
  1680. continue
  1681. for prop, value in vm.properties.items():
  1682. # can't reset the first; already handled the second
  1683. if prop in ['dispid', 'template_for_dispvms']:
  1684. continue
  1685. # exclude VM references - handled manually according to
  1686. # restore options
  1687. if prop in ['template', 'netvm', 'default_dispvm']:
  1688. continue
  1689. self._restore_property(new_vm, prop, value)
  1690. for feature, value in vm.features.items():
  1691. try:
  1692. new_vm.features[feature] = value
  1693. except Exception as err: # pylint: disable=broad-except
  1694. self.log.error('Error setting %s.features[%s] to %s: %s',
  1695. vm.name, feature, value, err)
  1696. for tag in vm.tags:
  1697. try:
  1698. new_vm.tags.add(tag)
  1699. except Exception as err: # pylint: disable=broad-except
  1700. self.log.error('Error adding tag %s to %s: %s',
  1701. tag, vm.name, err)
  1702. for bus in vm.devices:
  1703. for backend_domain, ident in vm.devices[bus]:
  1704. options = vm.devices[bus][(backend_domain, ident)]
  1705. assignment = DeviceAssignment(
  1706. backend_domain=backend_domain,
  1707. ident=ident,
  1708. options=options,
  1709. persistent=True)
  1710. try:
  1711. new_vm.devices[bus].attach(assignment)
  1712. except Exception as err: # pylint: disable=broad-except
  1713. self.log.error('Error attaching device %s:%s to %s: %s',
  1714. bus, ident, vm.name, err)
  1715. # Set VM dependencies - only non-default setting
  1716. for vm in vms.values():
  1717. vm_info = restore_info[vm.name]
  1718. vm_name = vm_info.name
  1719. try:
  1720. host_vm = self.app.domains[vm_name]
  1721. except KeyError:
  1722. # Failed/skipped VM
  1723. continue
  1724. if 'netvm' in vm.properties:
  1725. if vm_info.netvm in restore_info:
  1726. value = restore_info[vm_info.netvm].name
  1727. else:
  1728. value = vm_info.netvm
  1729. try:
  1730. host_vm.netvm = value
  1731. except Exception as err: # pylint: disable=broad-except
  1732. self.log.error('Error setting %s.%s to %s: %s',
  1733. vm.name, 'netvm', value, err)
  1734. if 'default_dispvm' in vm.properties:
  1735. if vm.properties['default_dispvm'] in restore_info:
  1736. value = restore_info[vm.properties[
  1737. 'default_dispvm']].name
  1738. else:
  1739. value = vm.properties['default_dispvm']
  1740. try:
  1741. host_vm.default_dispvm = value
  1742. except Exception as err: # pylint: disable=broad-except
  1743. self.log.error('Error setting %s.%s to %s: %s',
  1744. vm.name, 'default_dispvm', value, err)