qvm_backup.py 8.4 KB

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