qvm_backup.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. '''qvm-backup tool'''
  21. import asyncio
  22. import functools
  23. import getpass
  24. import os
  25. import signal
  26. import sys
  27. import yaml
  28. try:
  29. import qubesadmin.events
  30. have_events = True
  31. except ImportError:
  32. have_events = False
  33. import qubesadmin.tools
  34. from qubesadmin.exc import QubesException
  35. backup_profile_dir = '/etc/qubes/backup'
  36. parser = qubesadmin.tools.QubesArgumentParser()
  37. parser.add_argument("--yes", "-y", action="store_true",
  38. dest="yes", default=False,
  39. help="Do not ask for confirmation")
  40. group = parser.add_mutually_exclusive_group()
  41. group.add_argument('--profile', action='store',
  42. help='Perform backup defined by a given profile')
  43. no_profile = group.add_argument_group('Profile setup',
  44. 'Manually specify profile options')
  45. no_profile.add_argument("--exclude", "-x", action="append",
  46. dest="exclude_list", default=[],
  47. help="Exclude the specified VM from the backup (may be "
  48. "repeated)")
  49. no_profile.add_argument("--dest-vm", "-d", action="store",
  50. dest="appvm", default=None,
  51. help="Specify the destination VM to which the backup "
  52. "will be sent (implies -e)")
  53. no_profile.add_argument("--encrypt", "-e", action="store_true",
  54. dest="encrypted", default=True,
  55. help="Ignored, backup is always encrypted")
  56. no_profile.add_argument("--passphrase-file", "-p", action="store",
  57. dest="passphrase_file", default=None,
  58. help="Read passphrase from a file, or use '-' to read "
  59. "from stdin")
  60. no_profile.add_argument("--compress", "-z", action="store_true",
  61. dest="compression", default=False,
  62. help="Compress the backup")
  63. no_profile.add_argument("--compress-filter", "-Z", action="store",
  64. dest="compression",
  65. help="Specify a non-default compression filter program "
  66. "(default: gzip)")
  67. no_profile.add_argument('--save-profile', action='store',
  68. help='Save profile under selected name for further use.'
  69. 'Available only in dom0.')
  70. no_profile.add_argument("backup_location", action="store", default=None,
  71. nargs='?',
  72. help="Backup location (directory path, or command to pipe backup to)")
  73. no_profile.add_argument("vms", nargs="*", action=qubesadmin.tools.VmNameAction,
  74. help="Backup only those VMs")
  75. def write_backup_profile(output_stream, args, passphrase=None):
  76. '''Format backup profile and print it to *output_stream* (a file or
  77. stdout)
  78. :param output_stream: file-like object ro print the profile to
  79. :param args: parsed arguments
  80. :param passphrase: passphrase to use
  81. '''
  82. profile_data = {}
  83. if args.vms:
  84. profile_data['include'] = args.vms
  85. else:
  86. profile_data['include'] = [
  87. '$type:AppVM', '$type:TemplateVM', '$type:StandaloneVM']
  88. if args.exclude_list:
  89. profile_data['exclude'] = args.exclude_list
  90. if passphrase:
  91. profile_data['passphrase_text'] = passphrase
  92. if args.compression:
  93. profile_data['compression'] = args.compression
  94. if args.appvm:
  95. profile_data['destination_vm'] = args.appvm
  96. else:
  97. profile_data['destination_vm'] = 'dom0'
  98. profile_data['destination_path'] = args.backup_location
  99. yaml.safe_dump(profile_data, output_stream)
  100. def print_progress(expected_profile, _subject, _event, backup_profile,
  101. progress):
  102. '''Event handler for reporting backup progress'''
  103. if backup_profile != expected_profile:
  104. return
  105. sys.stderr.write('\rMaking a backup... {:.02f}%'.format(float(progress)))
  106. def main(args=None, app=None):
  107. '''Main function of qvm-backup tool'''
  108. args = parser.parse_args(args, app=app)
  109. profile_path = None
  110. if args.profile is None:
  111. if args.backup_location is None:
  112. parser.error('either --profile or \'backup_location\' is required')
  113. if args.app.qubesd_connection_type == 'socket':
  114. # when running in dom0, we can create backup profile, including
  115. # passphrase
  116. if args.save_profile:
  117. profile_name = args.save_profile
  118. else:
  119. # don't care about collisions because only the user in dom0 can
  120. # trigger this, and qrexec policy should not allow random VM
  121. # to execute the same backup in the meantime
  122. profile_name = 'backup-run-{}'.format(os.getpid())
  123. # first write the backup profile without passphrase, to display
  124. # summary
  125. profile_path = os.path.join(
  126. backup_profile_dir, profile_name + '.conf')
  127. with open(profile_path, 'w') as f_profile:
  128. write_backup_profile(f_profile, args)
  129. else:
  130. if args.save_profile:
  131. parser.error(
  132. 'Cannot save backup profile when running not in dom0')
  133. # unreachable - parser.error terminate the process
  134. return 1
  135. print('To perform the backup according to selected options, '
  136. 'create backup profile ({}) in dom0 with following '
  137. 'content:'.format(
  138. os.path.join(backup_profile_dir, 'profile_name.conf')))
  139. write_backup_profile(sys.stdout, args)
  140. print('# specify backup passphrase below')
  141. print('passphrase_text: ...')
  142. return 1
  143. else:
  144. profile_name = args.profile
  145. backup_summary = args.app.qubesd_call(
  146. 'dom0', 'admin.backup.Info', profile_name)
  147. print(backup_summary.decode())
  148. if not args.yes:
  149. if input("Do you want to proceed? [y/N] ").upper() != "Y":
  150. if args.profile is None and not args.save_profile:
  151. os.unlink(profile_path)
  152. return 0
  153. if args.profile is None:
  154. if args.passphrase_file is not None:
  155. pass_f = open(args.passphrase_file) \
  156. if args.passphrase_file != "-" else sys.stdin
  157. passphrase = pass_f.readline().rstrip()
  158. if pass_f is not sys.stdin:
  159. pass_f.close()
  160. else:
  161. prompt = ("Please enter the passphrase that will be used to "
  162. "encrypt and verify the backup: ")
  163. passphrase = getpass.getpass(prompt)
  164. if getpass.getpass("Enter again for verification: ") != passphrase:
  165. parser.error_runtime("Passphrase mismatch!")
  166. with open(profile_path, 'w') as f_profile:
  167. write_backup_profile(f_profile, args, passphrase)
  168. loop = asyncio.get_event_loop()
  169. if have_events:
  170. # pylint: disable=no-member
  171. events_dispatcher = qubesadmin.events.EventsDispatcher(args.app)
  172. events_dispatcher.add_handler('backup-progress',
  173. functools.partial(print_progress, profile_name))
  174. events_task = asyncio.ensure_future(
  175. events_dispatcher.listen_for_events())
  176. loop.add_signal_handler(signal.SIGINT,
  177. args.app.qubesd_call, 'dom0', 'admin.backup.Cancel', profile_name)
  178. try:
  179. loop.run_until_complete(loop.run_in_executor(None,
  180. args.app.qubesd_call, 'dom0', 'admin.backup.Execute', profile_name))
  181. except QubesException as err:
  182. print('\nBackup error: {}'.format(err), file=sys.stderr)
  183. return 1
  184. finally:
  185. if have_events:
  186. events_task.cancel()
  187. try:
  188. loop.run_until_complete(events_task)
  189. except asyncio.CancelledError:
  190. pass
  191. loop.close()
  192. if args.profile is None and not args.save_profile:
  193. os.unlink(profile_path)
  194. print('\n')
  195. return 0
  196. if __name__ == '__main__':
  197. sys.exit(main())