qvm-backup 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/python2
  2. # -*- encoding: utf8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (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 General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. from qubes.qubes import QubesVmCollection
  24. from qubes.qubes import QubesException
  25. from qubes.backup import backup_prepare, backup_do
  26. from qubes.qubesutils import size_to_human
  27. from optparse import OptionParser
  28. import qubes.backup
  29. import os
  30. import sys
  31. import getpass
  32. from locale import getpreferredencoding
  33. def print_progress(progress):
  34. print >> sys.stderr, "\r-> Backing up files: {0}%...".format (progress),
  35. def main():
  36. usage = "usage: %prog [options] <backup-dir-path> [vms-to-be-included ...]"
  37. parser = OptionParser (usage)
  38. parser.add_option ("-x", "--exclude", action="append",
  39. dest="exclude_list", default=[],
  40. help="Exclude the specified VM from backup (may be "
  41. "repeated)")
  42. parser.add_option ("--force-root", action="store_true", dest="force_root", default=False,
  43. help="Force to run, even with root privileges")
  44. parser.add_option ("-d", "--dest-vm", action="store", dest="appvm",
  45. help="The AppVM to send backups to (implies -e)")
  46. parser.add_option ("-e", "--encrypt", action="store_true", dest="encrypt", default=False,
  47. help="Encrypts the backup")
  48. parser.add_option ("--no-encrypt", action="store_true",
  49. dest="no_encrypt", default=False,
  50. help="Skip encryption even if sending the backup to VM")
  51. parser.add_option ("-p", "--passphrase-file", action="store",
  52. dest="pass_file", default=None,
  53. help="File containing the pass phrase to use, or '-' "
  54. "to read it from stdin")
  55. parser.add_option ("-E", "--enc-algo", action="store",
  56. dest="crypto_algorithm", default=None,
  57. help="Specify non-default encryption algorithm. For "
  58. "list of supported algos execute 'openssl "
  59. "list-cipher-algorithms' (implies -e)")
  60. parser.add_option ("-H", "--hmac-algo", action="store",
  61. dest="hmac_algorithm", default=None,
  62. help="Specify non-default hmac algorithm. For list of "
  63. "supported algos execute 'openssl "
  64. "list-message-digest-algorithms'")
  65. parser.add_option ("-z", "--compress", action="store_true", dest="compress", default=False,
  66. help="Compress the backup")
  67. parser.add_option ("-Z", "--compress-filter", action="store",
  68. dest="compress_filter", default=False,
  69. help="Compress the backup using specified filter "
  70. "program (default: gzip)")
  71. parser.add_option("--tmpdir", action="store", dest="tmpdir", default=None,
  72. help="Custom temporary directory (if you have at least "
  73. "1GB free RAM in dom0, use of /tmp is advised) ("
  74. "default: /var/tmp)")
  75. parser.add_option ("--debug", action="store_true", dest="debug",
  76. default=False, help="Enable (a lot of) debug output")
  77. (options, args) = parser.parse_args ()
  78. if (len (args) < 1):
  79. print >> sys.stderr, "You must specify the target backup directory (e.g. /mnt/backup)"
  80. print >> sys.stderr, "qvm-backup will create a subdirectory there for each individual backup."
  81. exit (0)
  82. base_backup_dir = args[0]
  83. if hasattr(os, "geteuid") and os.geteuid() == 0:
  84. if not options.force_root:
  85. print >> sys.stderr, "*** Running this tool as root is strongly discouraged, this will lead you in permissions problems."
  86. print >> sys.stderr, "Retry as unprivileged user."
  87. print >> sys.stderr, "... or use --force-root to continue anyway."
  88. exit(1)
  89. # Only for locking
  90. qvm_collection = QubesVmCollection()
  91. qvm_collection.lock_db_for_reading()
  92. qvm_collection.load()
  93. vms = None
  94. if (len (args) > 1):
  95. vms = [qvm_collection.get_vm_by_name(vmname) for vmname in args[1:]]
  96. if options.appvm:
  97. options.exclude_list.append(options.appvm)
  98. if options.appvm or options.crypto_algorithm:
  99. options.encrypt = True
  100. if options.no_encrypt:
  101. options.encrypt = False
  102. if options.debug:
  103. qubes.backup.BACKUP_DEBUG = True
  104. files_to_backup = None
  105. try:
  106. files_to_backup = backup_prepare(
  107. vms_list=vms,
  108. exclude_list=options.exclude_list,
  109. hide_vm_names=options.encrypt)
  110. except QubesException as e:
  111. print >>sys.stderr, "ERROR: %s" % str(e)
  112. exit(1)
  113. total_backup_sz = reduce(lambda size, file: size+file["size"],
  114. files_to_backup, 0)
  115. if not options.appvm:
  116. appvm = None
  117. if os.path.isdir(base_backup_dir):
  118. stat = os.statvfs(base_backup_dir)
  119. else:
  120. stat = os.statvfs(os.path.dirname(base_backup_dir))
  121. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  122. print
  123. if (total_backup_sz > backup_fs_free_sz):
  124. print >>sys.stderr, "ERROR: Not enough space available on the backup filesystem!"
  125. exit(1)
  126. print "-> Available space: {0}".format(size_to_human(backup_fs_free_sz))
  127. else:
  128. appvm = qvm_collection.get_vm_by_name(options.appvm)
  129. if appvm is None:
  130. print >>sys.stderr, "ERROR: VM {0} does not exist".format(options.appvm)
  131. exit(1)
  132. stat = os.statvfs('/var/tmp')
  133. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  134. print
  135. if (backup_fs_free_sz < 1000000000):
  136. print >>sys.stderr, "ERROR: Not enough space available " \
  137. "on the local filesystem (needs 1GB for temporary files)!"
  138. exit(1)
  139. if not appvm.is_running():
  140. appvm.start(verbose=True)
  141. if options.appvm:
  142. print >>sys.stderr, ("WARNING: VM {} excluded because it's used to "
  143. "store the backup.").format(options.appvm)
  144. options.exclude_list.append(options.appvm)
  145. if not options.encrypt:
  146. print >>sys.stderr, "WARNING: encryption will not be used"
  147. if options.pass_file is not None:
  148. f = open(options.pass_file) if options.pass_file != "-" else sys.stdin
  149. passphrase = f.readline().rstrip()
  150. if f is not sys.stdin:
  151. f.close()
  152. else:
  153. if raw_input("Do you want to proceed? [y/N] ").upper() != "Y":
  154. exit(0)
  155. s = ("Please enter the pass phrase that will be used to {}verify "
  156. "the backup: ").format('encrypt and ' if options.encrypt else '')
  157. passphrase = getpass.getpass(s)
  158. if getpass.getpass("Enter again for verification: ") != passphrase:
  159. print >>sys.stderr, "ERROR: Password mismatch"
  160. exit(1)
  161. encoding = sys.stdin.encoding or getpreferredencoding()
  162. passphrase = passphrase.decode(encoding)
  163. kwargs = {}
  164. if options.hmac_algorithm:
  165. kwargs['hmac_algorithm'] = options.hmac_algorithm
  166. if options.crypto_algorithm:
  167. kwargs['crypto_algorithm'] = options.crypto_algorithm
  168. if options.tmpdir:
  169. kwargs['tmpdir'] = options.tmpdir
  170. try:
  171. backup_do(base_backup_dir, files_to_backup, passphrase,
  172. progress_callback=print_progress,
  173. encrypted=options.encrypt,
  174. compressed=options.compress_filter or options.compress,
  175. appvm=appvm, **kwargs)
  176. except QubesException as e:
  177. print >>sys.stderr, "ERROR: %s" % str(e)
  178. exit(1)
  179. print
  180. print "-> Backup completed."
  181. qvm_collection.unlock_db()
  182. main()