restore.py 79 KB

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