restore.py 79 KB

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