005QubesNetVm.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2013 Marek Marczykowski <marmarek@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. import sys
  24. import os.path
  25. import xen.lowlevel.xs
  26. from qubes.qubes import QubesVm,register_qubes_vm_class,xs,dry_run
  27. from qubes.qubes import defaults,system_path,vm_files
  28. from qubes.qubes import QubesVmCollection,QubesException
  29. class QubesNetVm(QubesVm):
  30. """
  31. A class that represents a NetVM. A child of QubesCowVM.
  32. """
  33. # In which order load this VM type from qubes.xml
  34. load_order = 70
  35. def get_attrs_config(self):
  36. attrs_config = super(QubesNetVm, self).get_attrs_config()
  37. attrs_config['dir_path']['func'] = \
  38. lambda value: value if value is not None else \
  39. os.path.join(system_path["qubes_servicevms_dir"], self.name)
  40. attrs_config['label']['default'] = defaults["servicevm_label"]
  41. attrs_config['memory']['default'] = 200
  42. # New attributes
  43. attrs_config['netid'] = {
  44. 'save': lambda: str(self.netid),
  45. 'order': 30,
  46. 'func': lambda value: value if value is not None else
  47. self._collection.get_new_unused_netid() }
  48. attrs_config['netprefix'] = {
  49. 'func': lambda x: "10.137.{0}.".format(self.netid) }
  50. attrs_config['dispnetprefix'] = {
  51. 'func': lambda x: "10.138.{0}.".format(self.netid) }
  52. # Dont save netvm prop
  53. attrs_config['netvm'].pop('save')
  54. attrs_config['uses_default_netvm'].pop('save')
  55. return attrs_config
  56. def __init__(self, **kwargs):
  57. super(QubesNetVm, self).__init__(**kwargs)
  58. self.connected_vms = QubesVmCollection()
  59. self.__network = "10.137.{0}.0".format(self.netid)
  60. self.__netmask = defaults["vm_default_netmask"]
  61. self.__gateway = self.netprefix + "1"
  62. self.__secondary_dns = self.netprefix + "254"
  63. self.__external_ip_allowed_xids = set()
  64. @property
  65. def type(self):
  66. return "NetVM"
  67. def is_netvm(self):
  68. return True
  69. @property
  70. def gateway(self):
  71. return self.__gateway
  72. @property
  73. def secondary_dns(self):
  74. return self.__secondary_dns
  75. @property
  76. def netmask(self):
  77. return self.__netmask
  78. @property
  79. def network(self):
  80. return self.__network
  81. def get_ip_for_vm(self, qid):
  82. lo = qid % 253 + 2
  83. assert lo >= 2 and lo <= 254, "Wrong IP address for VM"
  84. return self.netprefix + "{0}".format(lo)
  85. def get_ip_for_dispvm(self, dispid):
  86. lo = dispid % 254 + 1
  87. assert lo >= 1 and lo <= 254, "Wrong IP address for VM"
  88. return self.dispnetprefix + "{0}".format(lo)
  89. def create_xenstore_entries(self, xid = None):
  90. if dry_run:
  91. return
  92. if xid is None:
  93. xid = self.xid
  94. super(QubesNetVm, self).create_xenstore_entries(xid)
  95. xs.write('', "/local/domain/{0}/qubes-netvm-external-ip".format(xid), '')
  96. self.update_external_ip_permissions(xid)
  97. def update_external_ip_permissions(self, xid = -1):
  98. if xid < 0:
  99. xid = self.get_xid()
  100. if xid < 0:
  101. return
  102. perms = [ { 'dom': xid } ]
  103. for xid in self.__external_ip_allowed_xids:
  104. perms.append({ 'dom': xid, 'read': True })
  105. try:
  106. xs.set_permissions('', '/local/domain/{0}/qubes-netvm-external-ip'.format(xid),
  107. perms)
  108. except xen.lowlevel.xs.Error as e:
  109. print >>sys.stderr, "WARNING: failed to update external IP " \
  110. "permissions: %s" % (str(e))
  111. def start(self, **kwargs):
  112. if dry_run:
  113. return
  114. xid=super(QubesNetVm, self).start(**kwargs)
  115. # Connect vif's of already running VMs
  116. for vm in self.connected_vms.values():
  117. if not vm.is_running():
  118. continue
  119. if 'verbose' in kwargs and kwargs['verbose']:
  120. print >> sys.stderr, "--> Attaching network to '{0}'...".format(vm.name)
  121. # Cleanup stale VIFs
  122. vm.cleanup_vifs()
  123. # force frontend to forget about this device
  124. # module actually will be loaded back by udev, as soon as network is attached
  125. vm.run("modprobe -r xen-netfront xennet", user="root")
  126. try:
  127. vm.attach_network(wait=False)
  128. except QubesException as ex:
  129. print >> sys.stderr, ("WARNING: Cannot attach to network to '{0}': {1}".format(vm.name, ex))
  130. return xid
  131. def shutdown(self, force=False):
  132. if dry_run:
  133. return
  134. connected_vms = [vm for vm in self.connected_vms.values() if vm.is_running()]
  135. if connected_vms and not force:
  136. raise QubesException("There are other VMs connected to this VM: " + str([vm.name for vm in connected_vms]))
  137. super(QubesNetVm, self).shutdown(force=force)
  138. def add_external_ip_permission(self, xid):
  139. if int(xid) < 0:
  140. return
  141. self.__external_ip_allowed_xids.add(int(xid))
  142. self.update_external_ip_permissions()
  143. def remove_external_ip_permission(self, xid):
  144. self.__external_ip_allowed_xids.discard(int(xid))
  145. self.update_external_ip_permissions()
  146. register_qubes_vm_class(QubesNetVm)