qvm-backup 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 ("--debug", action="store_true", dest="debug",
  72. default=False, help="Enable (a lot of) debug output")
  73. (options, args) = parser.parse_args ()
  74. if (len (args) < 1):
  75. print >> sys.stderr, "You must specify the target backup directory (e.g. /mnt/backup)"
  76. print >> sys.stderr, "qvm-backup will create a subdirectory there for each individual backup."
  77. exit (0)
  78. base_backup_dir = args[0]
  79. if hasattr(os, "geteuid") and os.geteuid() == 0:
  80. if not options.force_root:
  81. print >> sys.stderr, "*** Running this tool as root is strongly discouraged, this will lead you in permissions problems."
  82. print >> sys.stderr, "Retry as unprivileged user."
  83. print >> sys.stderr, "... or use --force-root to continue anyway."
  84. exit(1)
  85. # Only for locking
  86. qvm_collection = QubesVmCollection()
  87. qvm_collection.lock_db_for_reading()
  88. qvm_collection.load()
  89. vms = None
  90. if (len (args) > 1):
  91. vms = [qvm_collection.get_vm_by_name(vmname) for vmname in args[1:]]
  92. if options.appvm:
  93. options.exclude_list.append(options.appvm)
  94. if options.appvm or options.crypto_algorithm:
  95. options.encrypt = True
  96. if options.no_encrypt:
  97. options.encrypt = False
  98. if options.debug:
  99. qubes.backup.BACKUP_DEBUG = True
  100. files_to_backup = None
  101. try:
  102. files_to_backup = backup_prepare(
  103. vms_list=vms,
  104. exclude_list=options.exclude_list,
  105. hide_vm_names=options.encrypt)
  106. except QubesException as e:
  107. print >>sys.stderr, "ERROR: %s" % str(e)
  108. exit(1)
  109. total_backup_sz = reduce(lambda size, file: size+file["size"],
  110. files_to_backup, 0)
  111. if not options.appvm:
  112. appvm = None
  113. if os.path.isdir(base_backup_dir):
  114. stat = os.statvfs(base_backup_dir)
  115. else:
  116. stat = os.statvfs(os.path.dirname(base_backup_dir))
  117. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  118. print
  119. if (total_backup_sz > backup_fs_free_sz):
  120. print >>sys.stderr, "ERROR: Not enough space available on the backup filesystem!"
  121. exit(1)
  122. print "-> Available space: {0}".format(size_to_human(backup_fs_free_sz))
  123. else:
  124. appvm = qvm_collection.get_vm_by_name(options.appvm)
  125. if appvm is None:
  126. print >>sys.stderr, "ERROR: VM {0} does not exist".format(options.appvm)
  127. exit(1)
  128. stat = os.statvfs('/var/tmp')
  129. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  130. print
  131. if (backup_fs_free_sz < 1000000000):
  132. print >>sys.stderr, "ERROR: Not enough space available " \
  133. "on the local filesystem (needs 1GB for temporary files)!"
  134. exit(1)
  135. if not appvm.is_running():
  136. appvm.start(verbose=True)
  137. if options.appvm:
  138. print >>sys.stderr, ("WARNING: VM {} excluded because it's used to "
  139. "store the backup.").format(options.appvm)
  140. options.exclude_list.append(options.appvm)
  141. if not options.encrypt:
  142. print >>sys.stderr, "WARNING: encryption will not be used"
  143. if options.pass_file is not None:
  144. f = open(options.pass_file) if options.pass_file != "-" else sys.stdin
  145. passphrase = f.readline().rstrip()
  146. if f is not sys.stdin:
  147. f.close()
  148. else:
  149. if raw_input("Do you want to proceed? [y/N] ").upper() != "Y":
  150. exit(0)
  151. s = ("Please enter the pass phrase that will be used to {}verify "
  152. "the backup: ").format('encrypt and ' if options.encrypt else '')
  153. passphrase = getpass.getpass(s)
  154. if getpass.getpass("Enter again for verification: ") != passphrase:
  155. print >>sys.stderr, "ERROR: Password mismatch"
  156. exit(1)
  157. encoding = sys.stdin.encoding or getpreferredencoding()
  158. passphrase = passphrase.decode(encoding)
  159. kwargs = {}
  160. if options.hmac_algorithm:
  161. kwargs['hmac_algorithm'] = options.hmac_algorithm
  162. if options.crypto_algorithm:
  163. kwargs['crypto_algorithm'] = options.crypto_algorithm
  164. try:
  165. backup_do(base_backup_dir, files_to_backup, passphrase,
  166. progress_callback=print_progress,
  167. encrypted=options.encrypt,
  168. compressed=options.compress_filter or options.compress,
  169. appvm=appvm, **kwargs)
  170. except QubesException as e:
  171. print >>sys.stderr, "ERROR: %s" % str(e)
  172. exit(1)
  173. print
  174. print "-> Backup completed."
  175. qvm_collection.unlock_db()
  176. main()