005QubesNetVm.py 5.7 KB

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