restore.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984
  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. p = subprocess.Popen(args, stdin=stdin, stdout=stdout,
  190. stderr=stderr,
  191. preexec_fn=lambda: set_ctty(pty_slave, pty_master))
  192. os.close(pty_slave)
  193. return p, open(pty_master, 'wb+', buffering=0)
  194. def launch_scrypt(action, input_name, output_name, passphrase):
  195. '''
  196. Launch 'scrypt' process, pass passphrase to it and return
  197. subprocess.Popen object.
  198. :param action: 'enc' or 'dec'
  199. :param input_name: input path or '-' for stdin
  200. :param output_name: output path or '-' for stdout
  201. :param passphrase: passphrase
  202. :return: subprocess.Popen object
  203. '''
  204. command_line = ['scrypt', action, input_name, output_name]
  205. (p, pty) = launch_proc_with_pty(command_line,
  206. stdin=subprocess.PIPE if input_name == '-' else None,
  207. stdout=subprocess.PIPE if output_name == '-' else None,
  208. stderr=subprocess.PIPE,
  209. echo=False)
  210. if action == 'enc':
  211. prompts = (b'Please enter passphrase: ', b'Please confirm passphrase: ')
  212. else:
  213. prompts = (b'Please enter passphrase: ',)
  214. for prompt in prompts:
  215. actual_prompt = p.stderr.read(len(prompt))
  216. if actual_prompt != prompt:
  217. raise QubesException(
  218. 'Unexpected prompt from scrypt: {}'.format(actual_prompt))
  219. pty.write(passphrase.encode('utf-8') + b'\n')
  220. pty.flush()
  221. # save it here, so garbage collector would not close it (which would kill
  222. # the child)
  223. p.pty = pty
  224. return p
  225. class ExtractWorker3(Process):
  226. '''Process for handling inner tar layer of backup archive'''
  227. # pylint: disable=too-many-instance-attributes
  228. def __init__(self, queue, base_dir, passphrase, encrypted,
  229. progress_callback, vmproc=None,
  230. compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
  231. compression_filter=None, verify_only=False, handlers=None):
  232. '''Start inner tar extraction worker
  233. The purpose of this class is to process files extracted from outer
  234. archive layer and pass to appropriate handlers. Input files are given
  235. through a queue. Insert :py:obj:`QUEUE_FINISHED` or
  236. :py:obj:`QUEUE_ERROR` to end data processing (either cleanly,
  237. or forcefully).
  238. Handlers are given as a map filename -> (data_func, size_func),
  239. where data_func is called with file-like object to process,
  240. and size_func is called with file size as argument. Note that
  241. data_func and size_func may be called simultaneusly, in a different
  242. processes.
  243. :param multiprocessing.Queue queue: a queue with filenames to
  244. process; those files needs to be given as full path, inside *base_dir*
  245. :param str base_dir: directory where all files to process live
  246. :param str passphrase: passphrase to decrypt the data
  247. :param bool encrypted: is encryption applied?
  248. :param callable progress_callback: report extraction progress
  249. :param subprocess.Popen vmproc: process extracting outer layer,
  250. given here to monitor
  251. it for failures (when it exits with non-zero exit code, inner layer
  252. processing is stopped)
  253. :param bool compressed: is the data compressed?
  254. :param str crypto_algorithm: encryption algorithm, either `scrypt` or an
  255. algorithm supported by openssl
  256. :param str compression_filter: compression program, `gzip` by default
  257. :param bool verify_only: only verify data integrity, do not extract
  258. :param dict handlers: handlers for actual data
  259. '''
  260. super(ExtractWorker3, self).__init__()
  261. #: queue with files to extract
  262. self.queue = queue
  263. #: paths on the queue are relative to this dir
  264. self.base_dir = base_dir
  265. #: passphrase to decrypt/authenticate data
  266. self.passphrase = passphrase
  267. #: handlers for files; it should be dict filename -> (data_function,
  268. # size_function),
  269. # where data_function will get file-like object as the only argument and
  270. # might be called in a separate process (multiprocessing.Process),
  271. # and size_function will get file size (when known) in bytes
  272. self.handlers = handlers
  273. #: is the backup encrypted?
  274. self.encrypted = encrypted
  275. #: is the backup compressed?
  276. self.compressed = compressed
  277. #: what crypto algorithm is used for encryption?
  278. self.crypto_algorithm = crypto_algorithm
  279. #: only verify integrity, don't extract anything
  280. self.verify_only = verify_only
  281. #: progress
  282. self.blocks_backedup = 0
  283. #: inner tar layer extraction (subprocess.Popen instance)
  284. self.tar2_process = None
  285. #: current inner tar archive name
  286. self.tar2_current_file = None
  287. #: cat process feeding tar2_process
  288. self.tar2_feeder = None
  289. #: decompressor subprocess.Popen instance
  290. self.decompressor_process = None
  291. #: decryptor subprocess.Popen instance
  292. self.decryptor_process = None
  293. #: data import multiprocessing.Process instance
  294. self.import_process = None
  295. #: callback reporting progress to UI
  296. self.progress_callback = progress_callback
  297. #: process (subprocess.Popen instance) feeding the data into
  298. # extraction tool
  299. self.vmproc = vmproc
  300. self.log = logging.getLogger('qubesadmin.backup.extract')
  301. self.stderr_encoding = sys.stderr.encoding or 'utf-8'
  302. self.tar2_stderr = []
  303. self.compression_filter = compression_filter
  304. def collect_tar_output(self):
  305. '''Retrieve tar stderr and handle it appropriately
  306. Log errors, process file size if requested.
  307. This use :py:attr:`tar2_process`.
  308. '''
  309. if not self.tar2_process.stderr:
  310. return
  311. if self.tar2_process.poll() is None:
  312. try:
  313. new_lines = self.tar2_process.stderr \
  314. .read(MAX_STDERR_BYTES).splitlines()
  315. except IOError as e:
  316. if e.errno == errno.EAGAIN:
  317. return
  318. else:
  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. else:
  889. raise QubesException(
  890. "ERROR: invalid hmac for file {0}: {1}. "
  891. "Is the passphrase correct?".
  892. format(filename, load_hmac(hmac_stdout.decode('ascii'))))
  893. def _verify_and_decrypt(self, filename, output=None):
  894. '''Handle scrypt-wrapped file
  895. Decrypt the file, and verify its integrity - both tasks handled by
  896. 'scrypt' tool. Filename (without extension) is also validated.
  897. :param filename: Input file name (relative to :py:attr:`tmpdir`),
  898. needs to have `.enc` or `.hmac` extension
  899. :param output: Output file name (relative to :py:attr:`tmpdir`),
  900. use :py:obj:`None` to use *filename* without extension
  901. :return: *filename* without extension
  902. '''
  903. assert filename.endswith('.enc') or filename.endswith('.hmac')
  904. fullname = os.path.join(self.tmpdir, filename)
  905. (origname, _) = os.path.splitext(filename)
  906. if output:
  907. fulloutput = os.path.join(self.tmpdir, output)
  908. else:
  909. fulloutput = os.path.join(self.tmpdir, origname)
  910. if origname == HEADER_FILENAME:
  911. passphrase = u'{filename}!{passphrase}'.format(
  912. filename=origname,
  913. passphrase=self.passphrase)
  914. else:
  915. passphrase = u'{backup_id}!{filename}!{passphrase}'.format(
  916. backup_id=self.header_data.backup_id,
  917. filename=origname,
  918. passphrase=self.passphrase)
  919. try:
  920. p = launch_scrypt('dec', fullname, fulloutput, passphrase)
  921. except OSError as err:
  922. raise QubesException('failed to decrypt {}: {!s}'.format(
  923. fullname, err))
  924. (_, stderr) = p.communicate()
  925. if hasattr(p, 'pty'):
  926. p.pty.close()
  927. if p.returncode != 0:
  928. os.unlink(fulloutput)
  929. raise QubesException('failed to decrypt {}: {}'.format(
  930. fullname, stderr))
  931. # encrypted file is no longer needed
  932. os.unlink(fullname)
  933. return origname
  934. def _retrieve_backup_header_files(self, files, allow_none=False):
  935. '''Retrieve backup header.
  936. Start retrieval process (possibly involving network access from
  937. another VM). Returns a collection of retrieved file paths.
  938. '''
  939. (retrieve_proc, filelist_pipe, error_pipe) = \
  940. self._start_retrieval_process(
  941. files, len(files), 1024 * 1024)
  942. filelist = filelist_pipe.read()
  943. filelist_pipe.close()
  944. retrieve_proc_returncode = retrieve_proc.wait()
  945. if retrieve_proc in self.processes_to_kill_on_cancel:
  946. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  947. extract_stderr = error_pipe.read(MAX_STDERR_BYTES)
  948. error_pipe.close()
  949. # wait for other processes (if any)
  950. for proc in self.processes_to_kill_on_cancel:
  951. if proc.wait() != 0:
  952. raise QubesException(
  953. "Backup header retrieval failed (exit code {})".format(
  954. proc.wait())
  955. )
  956. if retrieve_proc_returncode != 0:
  957. if not filelist and 'Not found in archive' in extract_stderr:
  958. if allow_none:
  959. return None
  960. else:
  961. raise QubesException(
  962. "unable to read the qubes backup file {0} ({1}): {2}".
  963. format(
  964. self.backup_location,
  965. retrieve_proc.wait(),
  966. extract_stderr
  967. ))
  968. actual_files = filelist.decode('ascii').splitlines()
  969. if sorted(actual_files) != sorted(files):
  970. raise QubesException(
  971. 'unexpected files in archive: got {!r}, expected {!r}'.format(
  972. actual_files, files
  973. ))
  974. for fname in files:
  975. if not os.path.exists(os.path.join(self.tmpdir, fname)):
  976. if allow_none:
  977. return None
  978. else:
  979. raise QubesException(
  980. 'Unable to retrieve file {} from backup {}: {}'.format(
  981. fname, self.backup_location, extract_stderr
  982. )
  983. )
  984. return files
  985. def _retrieve_backup_header(self):
  986. """Retrieve backup header and qubes.xml. Only backup header is
  987. analyzed, qubes.xml is left as-is
  988. (not even verified/decrypted/uncompressed)
  989. :return header_data
  990. :rtype :py:class:`BackupHeader`
  991. """
  992. if not self.backup_vm and os.path.exists(
  993. os.path.join(self.backup_location, 'qubes.xml')):
  994. # backup format version 1 doesn't have header
  995. header_data = BackupHeader()
  996. header_data.version = 1
  997. return header_data
  998. header_files = self._retrieve_backup_header_files(
  999. ['backup-header', 'backup-header.hmac'], allow_none=True)
  1000. if not header_files:
  1001. # R2-Beta3 didn't have backup header, so if none is found,
  1002. # assume it's version=2 and use values present at that time
  1003. header_data = BackupHeader(
  1004. version=2,
  1005. # place explicitly this value, because it is what format_version
  1006. # 2 have
  1007. hmac_algorithm='SHA1',
  1008. crypto_algorithm='aes-256-cbc',
  1009. # TODO: set encrypted to something...
  1010. )
  1011. else:
  1012. filename = HEADER_FILENAME
  1013. hmacfile = HEADER_FILENAME + '.hmac'
  1014. self.log.debug("Got backup header and hmac: %s, %s",
  1015. filename, hmacfile)
  1016. file_ok = False
  1017. hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  1018. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  1019. try:
  1020. if self._verify_hmac(filename, hmacfile, hmac_algo):
  1021. file_ok = True
  1022. break
  1023. except QubesException as err:
  1024. self.log.debug(
  1025. 'Failed to verify %s using %s: %r',
  1026. hmacfile, hmac_algo, err)
  1027. # Ignore exception here, try the next algo
  1028. if not file_ok:
  1029. raise QubesException(
  1030. "Corrupted backup header (hmac verification "
  1031. "failed). Is the password correct?")
  1032. filename = os.path.join(self.tmpdir, filename)
  1033. with open(filename, 'rb') as f_header:
  1034. header_data = BackupHeader(f_header.read())
  1035. os.unlink(filename)
  1036. return header_data
  1037. def _start_inner_extraction_worker(self, queue, handlers):
  1038. """Start a worker process, extracting inner layer of bacup archive,
  1039. extract them to :py:attr:`tmpdir`.
  1040. End the data by pushing QUEUE_FINISHED or QUEUE_ERROR to the queue.
  1041. :param queue :py:class:`Queue` object to handle files from
  1042. """
  1043. # Setup worker to extract encrypted data chunks to the restore dirs
  1044. # Create the process here to pass it options extracted from
  1045. # backup header
  1046. extractor_params = {
  1047. 'queue': queue,
  1048. 'base_dir': self.tmpdir,
  1049. 'passphrase': self.passphrase,
  1050. 'encrypted': self.header_data.encrypted,
  1051. 'compressed': self.header_data.compressed,
  1052. 'crypto_algorithm': self.header_data.crypto_algorithm,
  1053. 'verify_only': self.options.verify_only,
  1054. 'progress_callback': self.progress_callback,
  1055. 'handlers': handlers,
  1056. }
  1057. self.log.debug(
  1058. 'Starting extraction worker in %s, file handlers map: %s',
  1059. self.tmpdir, repr(handlers))
  1060. format_version = self.header_data.version
  1061. if format_version in [3, 4]:
  1062. extractor_params['compression_filter'] = \
  1063. self.header_data.compression_filter
  1064. if format_version == 4:
  1065. # encryption already handled
  1066. extractor_params['encrypted'] = False
  1067. extract_proc = ExtractWorker3(**extractor_params)
  1068. else:
  1069. raise NotImplementedError(
  1070. "Backup format version %d not supported" % format_version)
  1071. extract_proc.start()
  1072. return extract_proc
  1073. @staticmethod
  1074. def _save_qubes_xml(path, stream):
  1075. '''Handler for qubes.xml.000 content - just save the data to a file'''
  1076. with open(path, 'wb') as f_qubesxml:
  1077. f_qubesxml.write(stream.read())
  1078. def _process_qubes_xml(self):
  1079. """Verify, unpack and load qubes.xml. Possibly convert its format if
  1080. necessary. It expect that :py:attr:`header_data` is already populated,
  1081. and :py:meth:`retrieve_backup_header` was called.
  1082. """
  1083. if self.header_data.version == 1:
  1084. raise NotImplementedError('Backup format version 1 not supported')
  1085. elif self.header_data.version in [2, 3]:
  1086. self._retrieve_backup_header_files(
  1087. ['qubes.xml.000', 'qubes.xml.000.hmac'])
  1088. self._verify_hmac("qubes.xml.000", "qubes.xml.000.hmac")
  1089. else:
  1090. self._retrieve_backup_header_files(['qubes.xml.000.enc'])
  1091. self._verify_and_decrypt('qubes.xml.000.enc')
  1092. queue = Queue()
  1093. queue.put("qubes.xml.000")
  1094. queue.put(QUEUE_FINISHED)
  1095. qubes_xml_path = os.path.join(self.tmpdir, 'qubes-restored.xml')
  1096. handlers = {
  1097. 'qubes.xml': (
  1098. functools.partial(self._save_qubes_xml, qubes_xml_path),
  1099. None)
  1100. }
  1101. extract_proc = self._start_inner_extraction_worker(queue, handlers)
  1102. extract_proc.join()
  1103. if extract_proc.exitcode != 0:
  1104. raise QubesException(
  1105. "unable to extract the qubes backup. "
  1106. "Check extracting process errors.")
  1107. if self.header_data.version in [2, 3]:
  1108. backup_app = Core2Qubes(qubes_xml_path)
  1109. elif self.header_data.version in [4]:
  1110. backup_app = Core3Qubes(qubes_xml_path)
  1111. else:
  1112. raise QubesException(
  1113. 'Unsupported qubes.xml format version: {}'.format(
  1114. self.header_data.version))
  1115. # Not needed anymore - all the data stored in backup_app
  1116. os.unlink(qubes_xml_path)
  1117. return backup_app
  1118. def _restore_vm_data(self, vms_dirs, vms_size, handlers):
  1119. '''Restore data of VMs
  1120. :param vms_dirs: list of directories to extract (skip others)
  1121. :param vms_size: expected size (abort if source stream exceed this
  1122. value)
  1123. :param handlers: handlers for restored files - see
  1124. :py:class:`ExtractWorker3` for details
  1125. '''
  1126. # Currently each VM consists of at most 7 archives (count
  1127. # file_to_backup calls in backup_prepare()), but add some safety
  1128. # margin for further extensions. Each archive is divided into 100MB
  1129. # chunks. Additionally each file have own hmac file. So assume upper
  1130. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  1131. limit_count = str(2 * (10 * len(vms_dirs) +
  1132. int(vms_size / (100 * 1024 * 1024))))
  1133. if self.options.ignore_size_limit:
  1134. limit_count = '0'
  1135. vms_size = 0
  1136. self.log.debug("Working in temporary dir: %s", self.tmpdir)
  1137. self.log.info("Extracting data: %s to restore", size_to_human(vms_size))
  1138. # retrieve backup from the backup stream (either VM, or dom0 file)
  1139. (retrieve_proc, filelist_pipe, error_pipe) = \
  1140. self._start_retrieval_process(
  1141. vms_dirs, limit_count, vms_size)
  1142. to_extract = Queue()
  1143. # extract data retrieved by retrieve_proc
  1144. extract_proc = self._start_inner_extraction_worker(
  1145. to_extract, handlers)
  1146. try:
  1147. filename = None
  1148. hmacfile = None
  1149. nextfile = None
  1150. while True:
  1151. if self.canceled:
  1152. break
  1153. if not extract_proc.is_alive():
  1154. retrieve_proc.terminate()
  1155. retrieve_proc.wait()
  1156. if retrieve_proc in self.processes_to_kill_on_cancel:
  1157. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1158. # wait for other processes (if any)
  1159. for proc in self.processes_to_kill_on_cancel:
  1160. proc.wait()
  1161. break
  1162. if nextfile is not None:
  1163. filename = nextfile
  1164. else:
  1165. filename = filelist_pipe.readline().decode('ascii').strip()
  1166. self.log.debug("Getting new file: %s", filename)
  1167. if not filename or filename == "EOF":
  1168. break
  1169. # if reading archive directly with tar, wait for next filename -
  1170. # tar prints filename before processing it, so wait for
  1171. # the next one to be sure that whole file was extracted
  1172. if not self.backup_vm:
  1173. nextfile = filelist_pipe.readline().decode('ascii').strip()
  1174. if self.header_data.version in [2, 3]:
  1175. if not self.backup_vm:
  1176. hmacfile = nextfile
  1177. nextfile = filelist_pipe.readline().\
  1178. decode('ascii').strip()
  1179. else:
  1180. hmacfile = filelist_pipe.readline().\
  1181. decode('ascii').strip()
  1182. if self.canceled:
  1183. break
  1184. self.log.debug("Getting hmac: %s", hmacfile)
  1185. if not hmacfile or hmacfile == "EOF":
  1186. # Premature end of archive, either of tar1_command or
  1187. # vmproc exited with error
  1188. break
  1189. else: # self.header_data.version == 4
  1190. if not filename.endswith('.enc'):
  1191. raise qubesadmin.exc.QubesException(
  1192. 'Invalid file extension found in archive: {}'.
  1193. format(filename))
  1194. if not any(filename.startswith(x) for x in vms_dirs):
  1195. self.log.debug("Ignoring VM not selected for restore")
  1196. os.unlink(os.path.join(self.tmpdir, filename))
  1197. if hmacfile:
  1198. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1199. continue
  1200. if self.header_data.version in [2, 3]:
  1201. self._verify_hmac(filename, hmacfile)
  1202. else:
  1203. # _verify_and_decrypt will write output to a file with
  1204. # '.enc' extension cut off. This is safe because:
  1205. # - `scrypt` tool will override output, so if the file was
  1206. # already there (received from the VM), it will be removed
  1207. # - incoming archive extraction will refuse to override
  1208. # existing file, so if `scrypt` already created one,
  1209. # it can not be manipulated by the VM
  1210. # - when the file is retrieved from the VM, it appears at
  1211. # the final form - if it's visible, VM have no longer
  1212. # influence over its content
  1213. #
  1214. # This all means that if the file was correctly verified
  1215. # + decrypted, we will surely access the right file
  1216. filename = self._verify_and_decrypt(filename)
  1217. if not self.options.verify_only:
  1218. to_extract.put(os.path.join(self.tmpdir, filename))
  1219. else:
  1220. os.unlink(os.path.join(self.tmpdir, filename))
  1221. if self.canceled:
  1222. raise BackupCanceledError("Restore canceled",
  1223. tmpdir=self.tmpdir)
  1224. if retrieve_proc.wait() != 0:
  1225. if retrieve_proc.returncode == errno.EDQUOT:
  1226. raise QubesException(
  1227. 'retrieved backup size exceed expected size, if you '
  1228. 'believe this is ok, use --ignore-size-limit option')
  1229. else:
  1230. raise QubesException(
  1231. "unable to read the qubes backup file {} ({}): {}"
  1232. .format(self.backup_location,
  1233. retrieve_proc.returncode, error_pipe.read(
  1234. MAX_STDERR_BYTES)))
  1235. # wait for other processes (if any)
  1236. for proc in self.processes_to_kill_on_cancel:
  1237. proc.wait()
  1238. if proc.returncode != 0:
  1239. raise QubesException(
  1240. "Backup completed, "
  1241. "but VM sending it reported an error (exit code {})".
  1242. format(proc.returncode))
  1243. if filename and filename != "EOF":
  1244. raise QubesException(
  1245. "Premature end of archive, the last file was %s" % filename)
  1246. except:
  1247. to_extract.put(QUEUE_ERROR)
  1248. extract_proc.join()
  1249. raise
  1250. else:
  1251. to_extract.put(QUEUE_FINISHED)
  1252. finally:
  1253. error_pipe.close()
  1254. filelist_pipe.close()
  1255. self.log.debug("Waiting for the extraction process to finish...")
  1256. extract_proc.join()
  1257. self.log.debug("Extraction process finished with code: %s",
  1258. extract_proc.exitcode)
  1259. if extract_proc.exitcode != 0:
  1260. raise QubesException(
  1261. "unable to extract the qubes backup. "
  1262. "Check extracting process errors.")
  1263. def new_name_for_conflicting_vm(self, orig_name, restore_info):
  1264. '''Generate new name for conflicting VM
  1265. Add a number suffix, until the name is unique. If no unique name can
  1266. be found using this strategy, return :py:obj:`None`
  1267. '''
  1268. number = 1
  1269. if len(orig_name) > 29:
  1270. orig_name = orig_name[0:29]
  1271. new_name = orig_name
  1272. while (new_name in restore_info.keys() or
  1273. new_name in [x.name for x in restore_info.values()] or
  1274. new_name in self.app.domains):
  1275. new_name = str('{}{}'.format(orig_name, number))
  1276. number += 1
  1277. if number == 100:
  1278. # give up
  1279. return None
  1280. return new_name
  1281. def restore_info_verify(self, restore_info):
  1282. '''Verify restore info - validate VM dependencies, name conflicts
  1283. etc.
  1284. '''
  1285. for vm in restore_info.keys():
  1286. if vm in ['dom0']:
  1287. continue
  1288. vm_info = restore_info[vm]
  1289. assert isinstance(vm_info, self.VMToRestore)
  1290. vm_info.problems.clear()
  1291. if vm in self.options.exclude:
  1292. vm_info.problems.add(self.VMToRestore.EXCLUDED)
  1293. if not self.options.verify_only and \
  1294. vm_info.name in self.app.domains:
  1295. if self.options.rename_conflicting:
  1296. new_name = self.new_name_for_conflicting_vm(
  1297. vm, restore_info
  1298. )
  1299. if new_name is not None:
  1300. vm_info.name = new_name
  1301. else:
  1302. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1303. else:
  1304. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1305. # check template
  1306. if vm_info.template:
  1307. present_on_host = False
  1308. if vm_info.template in self.app.domains:
  1309. host_tpl = self.app.domains[vm_info.template]
  1310. if vm_info.vm.klass == 'DispVM':
  1311. present_on_host = (
  1312. getattr(host_tpl, 'template_for_dispvms', False))
  1313. else:
  1314. present_on_host = host_tpl.klass == 'TemplateVM'
  1315. present_in_backup = False
  1316. if vm_info.template in restore_info:
  1317. bak_tpl = restore_info[vm_info.template]
  1318. if bak_tpl.good_to_go:
  1319. if vm_info.vm.klass == 'DispVM':
  1320. present_in_backup = (
  1321. bak_tpl.vm.properties.get(
  1322. 'template_for_dispvms', False))
  1323. else:
  1324. present_in_backup = (
  1325. bak_tpl.vm.klass == 'TemplateVM')
  1326. self.log.debug(
  1327. "vm=%s template=%s on_host=%s in_backup=%s",
  1328. vm_info.name, vm_info.template,
  1329. present_on_host, present_in_backup)
  1330. if not present_on_host and not present_in_backup:
  1331. if vm_info.vm.klass == 'DispVM':
  1332. default_template = self.app.default_dispvm
  1333. else:
  1334. default_template = self.app.default_template
  1335. if (self.options.use_default_template
  1336. and default_template is not None):
  1337. if vm_info.orig_template is None:
  1338. vm_info.orig_template = vm_info.template
  1339. vm_info.template = default_template.name
  1340. self.log.debug(
  1341. "vm=%s orig_template=%s -> default_template=%s",
  1342. vm_info.name, vm_info.orig_template,
  1343. default_template.name)
  1344. else:
  1345. vm_info.problems.add(self.VMToRestore.MISSING_TEMPLATE)
  1346. # check netvm
  1347. if vm_info.vm.properties.get('netvm', None) is not None:
  1348. netvm_name = vm_info.netvm
  1349. try:
  1350. netvm_on_host = self.app.domains[netvm_name]
  1351. except KeyError:
  1352. netvm_on_host = None
  1353. present_on_host = (netvm_on_host is not None
  1354. and netvm_on_host.provides_network)
  1355. present_in_backup = (netvm_name in restore_info.keys() and
  1356. restore_info[netvm_name].good_to_go and
  1357. restore_info[netvm_name].vm.properties.get(
  1358. 'provides_network', False))
  1359. if not present_on_host and not present_in_backup:
  1360. if self.options.use_default_netvm:
  1361. del vm_info.vm.properties['netvm']
  1362. elif self.options.use_none_netvm:
  1363. vm_info.netvm = None
  1364. else:
  1365. vm_info.problems.add(self.VMToRestore.MISSING_NETVM)
  1366. return restore_info
  1367. def get_restore_info(self):
  1368. '''Get restore info
  1369. Return information about what is included in the backup.
  1370. That dictionary can be adjusted to select what VM should be restore.
  1371. '''
  1372. # Format versions:
  1373. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1374. # 2 - Qubes R2 beta3+
  1375. # 3 - Qubes R2+
  1376. # 4 - Qubes R4+
  1377. vms_to_restore = {}
  1378. for vm in self.backup_app.domains.values():
  1379. if vm.klass == 'AdminVM':
  1380. # Handle dom0 as special case later
  1381. continue
  1382. if vm.included_in_backup:
  1383. self.log.debug("%s is included in backup", vm.name)
  1384. vms_to_restore[vm.name] = self.VMToRestore(vm)
  1385. if vm.template is not None:
  1386. templatevm_name = vm.template
  1387. vms_to_restore[vm.name].template = templatevm_name
  1388. vms_to_restore = self.restore_info_verify(vms_to_restore)
  1389. # ...and dom0 home
  1390. if self.options.dom0_home and \
  1391. self.backup_app.domains['dom0'].included_in_backup:
  1392. vm = self.backup_app.domains['dom0']
  1393. vms_to_restore['dom0'] = self.Dom0ToRestore(vm,
  1394. self.backup_app.domains['dom0'].backup_path)
  1395. try:
  1396. local_user = grp.getgrnam('qubes').gr_mem[0]
  1397. except KeyError:
  1398. # if no qubes group is present, assume username matches
  1399. local_user = vms_to_restore['dom0'].username
  1400. if vms_to_restore['dom0'].username != local_user:
  1401. if not self.options.ignore_username_mismatch:
  1402. vms_to_restore['dom0'].problems.add(
  1403. self.Dom0ToRestore.USERNAME_MISMATCH)
  1404. return vms_to_restore
  1405. @staticmethod
  1406. def get_restore_summary(restore_info):
  1407. '''Return a ASCII formatted table with restore info summary'''
  1408. fields = {
  1409. "name": {'func': lambda vm: vm.name},
  1410. "type": {'func': lambda vm: vm.klass},
  1411. "template": {'func': lambda vm:
  1412. 'n/a' if vm.template is None else vm.template},
  1413. "netvm": {'func': lambda vm:
  1414. '(default)' if 'netvm' not in vm.properties else
  1415. '-' if vm.properties['netvm'] is None else
  1416. vm.properties['netvm']},
  1417. "label": {'func': lambda vm: vm.label},
  1418. }
  1419. fields_to_display = ['name', 'type', 'template',
  1420. 'netvm', 'label']
  1421. # First calculate the maximum width of each field we want to display
  1422. total_width = 0
  1423. for field in fields_to_display:
  1424. fields[field]['max_width'] = len(field)
  1425. for vm_info in restore_info.values():
  1426. if vm_info.vm:
  1427. # noinspection PyUnusedLocal
  1428. field_len = len(str(fields[field]["func"](vm_info.vm)))
  1429. if field_len > fields[field]['max_width']:
  1430. fields[field]['max_width'] = field_len
  1431. total_width += fields[field]['max_width']
  1432. summary = ""
  1433. summary += "The following VMs are included in the backup:\n"
  1434. summary += "\n"
  1435. # Display the header
  1436. for field in fields_to_display:
  1437. # noinspection PyTypeChecker
  1438. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1439. summary += fmt.format('-')
  1440. summary += "\n"
  1441. for field in fields_to_display:
  1442. # noinspection PyTypeChecker
  1443. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1444. summary += fmt.format(field)
  1445. summary += "\n"
  1446. for field in fields_to_display:
  1447. # noinspection PyTypeChecker
  1448. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1449. summary += fmt.format('-')
  1450. summary += "\n"
  1451. for vm_info in restore_info.values():
  1452. assert isinstance(vm_info, BackupRestore.VMToRestore)
  1453. # Skip non-VM here
  1454. if not vm_info.vm:
  1455. continue
  1456. # noinspection PyUnusedLocal
  1457. summary_line = ""
  1458. for field in fields_to_display:
  1459. # noinspection PyTypeChecker
  1460. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1461. summary_line += fmt.format(fields[field]["func"](vm_info.vm))
  1462. if BackupRestore.VMToRestore.EXCLUDED in vm_info.problems:
  1463. summary_line += " <-- Excluded from restore"
  1464. elif BackupRestore.VMToRestore.ALREADY_EXISTS in vm_info.problems:
  1465. summary_line += \
  1466. " <-- A VM with the same name already exists on the host!"
  1467. elif BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  1468. vm_info.problems:
  1469. summary_line += " <-- No matching template on the host " \
  1470. "or in the backup found!"
  1471. elif BackupRestore.VMToRestore.MISSING_NETVM in \
  1472. vm_info.problems:
  1473. summary_line += " <-- No matching netvm on the host " \
  1474. "or in the backup found!"
  1475. elif vm_info.name == "dom0" and \
  1476. BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  1477. restore_info['dom0'].problems:
  1478. summary_line += " <-- username in backup and dom0 mismatch"
  1479. else:
  1480. if vm_info.template != vm_info.vm.template:
  1481. summary_line += " <-- Template change to '{}'".format(
  1482. vm_info.template)
  1483. if vm_info.name != vm_info.vm.name:
  1484. summary_line += " <-- Will be renamed to '{}'".format(
  1485. vm_info.name)
  1486. summary += summary_line + "\n"
  1487. return summary
  1488. @staticmethod
  1489. def _templates_first(vms):
  1490. '''Sort templates before other VM types'''
  1491. def key_function(instance):
  1492. '''Key function for :py:func:`sorted`'''
  1493. if isinstance(instance, BackupVM):
  1494. if instance.klass == 'TemplateVM':
  1495. return 0
  1496. elif instance.properties.get('template_for_dispvms', False):
  1497. return 1
  1498. return 2
  1499. elif hasattr(instance, 'vm'):
  1500. return key_function(instance.vm)
  1501. return 9
  1502. return sorted(vms, key=key_function)
  1503. def _handle_dom0(self, stream):
  1504. '''Extract dom0 home'''
  1505. try:
  1506. local_user = grp.getgrnam('qubes').gr_mem[0]
  1507. home_dir = pwd.getpwnam(local_user).pw_dir
  1508. except KeyError:
  1509. home_dir = os.path.expanduser('~')
  1510. local_user = getpass.getuser()
  1511. restore_home_backupdir = "home-restore-{0}".format(
  1512. time.strftime("%Y-%m-%d-%H%M%S"))
  1513. self.log.info("Restoring home of user '%s' to '%s' directory...",
  1514. local_user, restore_home_backupdir)
  1515. os.mkdir(os.path.join(home_dir, restore_home_backupdir))
  1516. tar3_cmdline = ['tar', '-C',
  1517. os.path.join(home_dir, restore_home_backupdir), '-x']
  1518. retcode = subprocess.call(tar3_cmdline, stdin=stream)
  1519. if retcode != 0:
  1520. raise QubesException("Inner tar error for dom0-home")
  1521. retcode = subprocess.call(['sudo', 'chown', '-R',
  1522. local_user, os.path.join(home_dir, restore_home_backupdir)])
  1523. if retcode != 0:
  1524. self.log.error("*** Error while setting restore directory owner")
  1525. def _handle_appmenus_list(self, vm, stream):
  1526. '''Handle whitelisted-appmenus.list file'''
  1527. try:
  1528. subprocess.check_call(
  1529. ['qvm-appmenus', '--set-whitelist=-', vm.name],
  1530. stdin=stream)
  1531. except (subprocess.CalledProcessError, FileNotFoundError):
  1532. self.log.error('Failed to set application list for %s', vm.name)
  1533. def _handle_volume_data(self, vm, volume, stream):
  1534. '''Wrap volume data import with logging'''
  1535. try:
  1536. volume.import_data(stream)
  1537. except Exception as err: # pylint: disable=broad-except
  1538. self.log.error('Failed to restore volume %s of VM %s: %s',
  1539. volume.name, vm.name, err)
  1540. def _handle_volume_size(self, vm, volume, size):
  1541. '''Wrap volume resize with logging'''
  1542. try:
  1543. if volume.size < size:
  1544. volume.resize(size)
  1545. except Exception as err: # pylint: disable=broad-except
  1546. self.log.error('Failed to resize volume %s of VM %s to %d: %s',
  1547. volume.name, vm.name, size, err)
  1548. def restore_do(self, restore_info):
  1549. '''
  1550. High level workflow:
  1551. 1. Create VMs object in host collection (qubes.xml)
  1552. 2. Create them on disk (vm.create_on_disk)
  1553. 3. Restore VM data, overriding/converting VM files
  1554. 4. Apply possible fixups and save qubes.xml
  1555. :param restore_info:
  1556. :return:
  1557. '''
  1558. if self.header_data.version == 1:
  1559. raise NotImplementedError('Backup format version 1 not supported')
  1560. restore_info = self.restore_info_verify(restore_info)
  1561. self._restore_vms_metadata(restore_info)
  1562. # Perform VM restoration in backup order
  1563. vms_dirs = []
  1564. handlers = {}
  1565. vms_size = 0
  1566. for vm_info in self._templates_first(restore_info.values()):
  1567. vm = vm_info.restored_vm
  1568. if vm and vm_info.subdir:
  1569. if isinstance(vm_info, self.Dom0ToRestore) and \
  1570. vm_info.good_to_go:
  1571. vms_dirs.append(os.path.dirname(vm_info.subdir))
  1572. vms_size += int(vm_info.size)
  1573. if self.options.verify_only:
  1574. continue
  1575. handlers[vm_info.subdir] = (self._handle_dom0, None)
  1576. else:
  1577. vms_size += int(vm_info.size)
  1578. vms_dirs.append(vm_info.subdir)
  1579. if self.options.verify_only:
  1580. continue
  1581. for name, volume in vm.volumes.items():
  1582. if not volume.save_on_stop:
  1583. continue
  1584. data_func = functools.partial(
  1585. self._handle_volume_data, vm, volume)
  1586. size_func = functools.partial(
  1587. self._handle_volume_size, vm, volume)
  1588. img_path = os.path.join(vm_info.subdir, name + '.img')
  1589. handlers[img_path] = (data_func, size_func)
  1590. handlers[os.path.join(vm_info.subdir, 'firewall.xml')] = (
  1591. functools.partial(vm_info.vm.handle_firewall_xml, vm),
  1592. None)
  1593. handlers[os.path.join(vm_info.subdir,
  1594. 'whitelisted-appmenus.list')] = (
  1595. functools.partial(self._handle_appmenus_list, vm), None)
  1596. try:
  1597. self._restore_vm_data(vms_dirs=vms_dirs, vms_size=vms_size,
  1598. handlers=handlers)
  1599. except QubesException as err:
  1600. if self.options.verify_only:
  1601. raise
  1602. else:
  1603. self.log.error('Error extracting data: %s', str(err))
  1604. finally:
  1605. if self.log.getEffectiveLevel() > logging.DEBUG:
  1606. shutil.rmtree(self.tmpdir)
  1607. if self.canceled:
  1608. raise BackupCanceledError("Restore canceled",
  1609. tmpdir=self.tmpdir)
  1610. self.log.info("-> Done.")
  1611. if not self.options.verify_only:
  1612. self.log.info("-> Please install updates for all the restored "
  1613. "templates.")
  1614. def _restore_property(self, vm, prop, value):
  1615. '''Restore a single VM property, logging exceptions'''
  1616. try:
  1617. setattr(vm, prop, value)
  1618. except Exception as err: # pylint: disable=broad-except
  1619. self.log.error('Error setting %s.%s to %s: %s',
  1620. vm.name, prop, value, err)
  1621. def _restore_vms_metadata(self, restore_info):
  1622. '''Restore VM metadata
  1623. Create VMs, set their properties etc.
  1624. '''
  1625. vms = {}
  1626. for vm_info in restore_info.values():
  1627. assert isinstance(vm_info, self.VMToRestore)
  1628. if not vm_info.vm:
  1629. continue
  1630. if not vm_info.good_to_go:
  1631. continue
  1632. vm = vm_info.vm
  1633. vms[vm.name] = vm
  1634. # First load templates, then other VMs
  1635. for vm in self._templates_first(vms.values()):
  1636. if self.canceled:
  1637. return
  1638. if self.options.verify_only:
  1639. self.log.info("-> Verifying %s...", vm.name)
  1640. else:
  1641. self.log.info("-> Restoring %s...", vm.name)
  1642. kwargs = {}
  1643. if vm.template:
  1644. template = restore_info[vm.name].template
  1645. # handle potentially renamed template
  1646. if template in restore_info \
  1647. and restore_info[template].good_to_go:
  1648. template = restore_info[template].name
  1649. kwargs['template'] = template
  1650. new_vm = None
  1651. vm_name = restore_info[vm.name].name
  1652. if self.options.verify_only or vm.name == 'dom0':
  1653. # can't create vm, but need backup info
  1654. new_vm = self.backup_app.domains[vm_name]
  1655. else:
  1656. try:
  1657. # first only create VMs, later setting may require other VMs
  1658. # be already created
  1659. new_vm = self.app.add_new_vm(
  1660. vm.klass,
  1661. name=vm_name,
  1662. label=vm.label,
  1663. pool=self.options.override_pool,
  1664. **kwargs)
  1665. except Exception as err: # pylint: disable=broad-except
  1666. self.log.error('Error restoring VM %s, skipping: %s',
  1667. vm.name, err)
  1668. if new_vm:
  1669. del self.app.domains[new_vm.name]
  1670. continue
  1671. # restore this property early to be ready for dependent DispVMs
  1672. prop = 'template_for_dispvms'
  1673. value = vm.properties.get(prop, None)
  1674. if value is not None:
  1675. self._restore_property(new_vm, prop, value)
  1676. restore_info[vm.name].restored_vm = new_vm
  1677. for vm in vms.values():
  1678. if self.canceled:
  1679. return
  1680. new_vm = restore_info[vm.name].restored_vm
  1681. if not new_vm:
  1682. # skipped/failed
  1683. continue
  1684. for prop, value in vm.properties.items():
  1685. # can't reset the first; already handled the second
  1686. if prop in ['dispid', 'template_for_dispvms']:
  1687. continue
  1688. # exclude VM references - handled manually according to
  1689. # restore options
  1690. if prop in ['template', 'netvm', 'default_dispvm']:
  1691. continue
  1692. self._restore_property(new_vm, prop, value)
  1693. for feature, value in vm.features.items():
  1694. try:
  1695. new_vm.features[feature] = value
  1696. except Exception as err: # pylint: disable=broad-except
  1697. self.log.error('Error setting %s.features[%s] to %s: %s',
  1698. vm.name, feature, value, err)
  1699. for tag in vm.tags:
  1700. try:
  1701. new_vm.tags.add(tag)
  1702. except Exception as err: # pylint: disable=broad-except
  1703. self.log.error('Error adding tag %s to %s: %s',
  1704. tag, vm.name, err)
  1705. for bus in vm.devices:
  1706. for backend_domain, ident in vm.devices[bus]:
  1707. options = vm.devices[bus][(backend_domain, ident)]
  1708. assignment = DeviceAssignment(
  1709. backend_domain=backend_domain,
  1710. ident=ident,
  1711. options=options,
  1712. persistent=True)
  1713. try:
  1714. new_vm.devices[bus].attach(assignment)
  1715. except Exception as err: # pylint: disable=broad-except
  1716. self.log.error('Error attaching device %s:%s to %s: %s',
  1717. bus, ident, vm.name, err)
  1718. # Set VM dependencies - only non-default setting
  1719. for vm in vms.values():
  1720. vm_info = restore_info[vm.name]
  1721. vm_name = vm_info.name
  1722. try:
  1723. host_vm = self.app.domains[vm_name]
  1724. except KeyError:
  1725. # Failed/skipped VM
  1726. continue
  1727. if 'netvm' in vm.properties:
  1728. if vm_info.netvm in restore_info:
  1729. value = restore_info[vm_info.netvm].name
  1730. else:
  1731. value = vm_info.netvm
  1732. try:
  1733. host_vm.netvm = value
  1734. except Exception as err: # pylint: disable=broad-except
  1735. self.log.error('Error setting %s.%s to %s: %s',
  1736. vm.name, 'netvm', value, err)
  1737. if 'default_dispvm' in vm.properties:
  1738. if vm.properties['default_dispvm'] in restore_info:
  1739. value = restore_info[vm.properties[
  1740. 'default_dispvm']].name
  1741. else:
  1742. value = vm.properties['default_dispvm']
  1743. try:
  1744. host_vm.default_dispvm = value
  1745. except Exception as err: # pylint: disable=broad-except
  1746. self.log.error('Error setting %s.%s to %s: %s',
  1747. vm.name, 'default_dispvm', value, err)