1.1 --- a/server/vmmanager/vmmanager.py Fri Dec 06 12:10:30 2013 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,325 +0,0 @@
1.4 -'''
1.5 -Created on Nov 19, 2013
1.6 -
1.7 -@author: BarthaM
1.8 -'''
1.9 -import os
1.10 -import os.path
1.11 -from subprocess import Popen, PIPE, call
1.12 -import subprocess
1.13 -import sys
1.14 -import re
1.15 -
1.16 -DEBUG = True
1.17 -
1.18 -class USBFilter:
1.19 - vendorid = ""
1.20 - productid = ""
1.21 - revision = ""
1.22 -
1.23 - def __init__(self, vendorid, productid, revision):
1.24 - self.vendorid = vendorid.lower()
1.25 - self.productid = productid.lower()
1.26 - self.revision = revision.lower()
1.27 - return
1.28 -
1.29 - def __eq__(self, other):
1.30 - return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
1.31 -
1.32 - def __hash__(self):
1.33 - return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
1.34 -
1.35 - def __repr__(self):
1.36 - return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
1.37 -
1.38 -
1.39 -class VMManager(object):
1.40 - vmRootName = "SecurityDVM"
1.41 - systemProperties = None
1.42 - cygwin_path = 'c:\\cygwin64\\bin\\'
1.43 -
1.44 - def __init__(self):
1.45 - self.systemProperties = self.getSystemProperties()
1.46 - #TODO: get cygwin path externally
1.47 - return
1.48 -
1.49 - def execute(self, cmd):
1.50 - if DEBUG:
1.51 - print('trying to launch: ' + cmd)
1.52 - process = Popen(cmd, stdout=PIPE, stderr=PIPE)
1.53 - if DEBUG:
1.54 - print('launched: ' + cmd)
1.55 - result = process.wait()
1.56 - res_stdout = process.stdout.read();
1.57 - res_stderr = process.stderr.read();
1.58 - if DEBUG:
1.59 - if res_stdout != "":
1.60 - print res_stdout
1.61 - if res_stderr != "":
1.62 - print res_stderr
1.63 - return result, res_stdout, res_stderr
1.64 -
1.65 - # return hosty system properties
1.66 - def getSystemProperties(self):
1.67 - cmd = 'VBoxManage list systemproperties'
1.68 - result = self.execute(cmd)
1.69 - if result[1]=='':
1.70 - return None
1.71 - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
1.72 - return props
1.73 -
1.74 - # return the folder containing the guest VMs
1.75 - def getDefaultMachineFolder(self):
1.76 - return self.systemProperties["Default machine folder"]
1.77 -
1.78 - #list the hostonly IFs exposed by the VBox host
1.79 - def getHostOnlyIFs(self):
1.80 - cmd = 'VBoxManage list hostonlyifs'
1.81 - result = self.execute(cmd)[1]
1.82 - if result=='':
1.83 - return None
1.84 - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
1.85 - return props
1.86 -
1.87 - def listRSDS(self):
1.88 - cmd = 'VBoxManage list usbhost'
1.89 - results = self.execute(cmd)[1]
1.90 - results = results.split('Host USB Devices:')[1].strip()
1.91 -
1.92 - items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
1.93 - rsds = dict()
1.94 - for item in items:
1.95 - props = dict()
1.96 - for line in item.splitlines():
1.97 - if line != "":
1.98 - k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
1.99 - props[k] = v;
1.100 -
1.101 - if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
1.102 - usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
1.103 - re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
1.104 - re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
1.105 - rsds[props['UUID']] = usb_filter;
1.106 - if DEBUG:
1.107 - print filter
1.108 - return rsds
1.109 -
1.110 - # list all existing VMs registered with VBox
1.111 - def listVM(self):
1.112 - cmd = 'VBoxManage list vms'
1.113 - result = self.execute(cmd)[1]
1.114 - vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
1.115 - return vms
1.116 -
1.117 - # list existing SDVMs
1.118 - def listSDVM(self):
1.119 - vms = self.listVM()
1.120 - svdms = []
1.121 - for vm in vms:
1.122 - if vm.startswith(self.vmRootName) and vm != self.vmRootName:
1.123 - svdms.append(vm)
1.124 - return svdms
1.125 -
1.126 - # generate valid (not already existing SDVM name). necessary for creating a new VM
1.127 - def generateSDVMName(self):
1.128 - vms = self.listVM()
1.129 - for i in range(0,999):
1.130 - if(not self.vmRootName+str(i) in vms):
1.131 - return self.vmRootName+str(i)
1.132 - return ''
1.133 -
1.134 - # return the RSDs attached to all existing SDVMs
1.135 - def getAttachedRSDs(self):
1.136 - vms = self.listSDVM()
1.137 - attached_devices = dict()
1.138 - for vm in vms:
1.139 - rsd_filter = self.getUSBFilter(vm)
1.140 - if rsd_filter != None:
1.141 - attached_devices[vm] = rsd_filter
1.142 - return attached_devices
1.143 -
1.144 - # configures hostonly networking and DHCP server. requires admin rights
1.145 - def configureHostNetworking(self):
1.146 - #cmd = 'vboxmanage list hostonlyifs'
1.147 - #self.execute(cmd)
1.148 - #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
1.149 - #self.execute(cmd)
1.150 - #cmd = 'vboxmanage hostonlyif create'
1.151 - #self.execute(cmd)
1.152 - cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
1.153 - self.execute(cmd)
1.154 - #cmd = 'vboxmanage dhcpserver add'
1.155 - #self.execute(cmd)
1.156 - cmd = 'vboxmanage dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0 --lowerip 192.168.56.100 --upperip 192.168.56.255'
1.157 - self.execute(cmd)
1.158 -
1.159 - #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
1.160 - def createVM(self, vm_name):
1.161 - hostonly_if = self.getHostOnlyIFs()
1.162 - machineFolder = self.getDefaultMachineFolder()
1.163 - cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
1.164 - self.execute(cmd)
1.165 - cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
1.166 - self.execute(cmd)
1.167 - cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
1.168 - self.execute(cmd)
1.169 - cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
1.170 - #--mtype immutable
1.171 - self.execute(cmd)
1.172 - return
1.173 -
1.174 - #remove VM from the system. should be used on VMs returned by listSDVMs
1.175 - def removeVM(self, vm_name):
1.176 - print('removing ' + vm_name)
1.177 - cmd = 'VBoxManage unregistervm', vm_name, '--delete'
1.178 - print self.execute(cmd)
1.179 - machineFolder = self.getDefaultMachineFolder()
1.180 - cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
1.181 - print self.execute(cmd)
1.182 -
1.183 - # start VM
1.184 - def startVM(self, vm_name):
1.185 - print('starting ' + vm_name)
1.186 - cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
1.187 - print self.execute(cmd)
1.188 -
1.189 - # stop VM
1.190 - def stopVM(self, vm_name):
1.191 - print('stopping ' + vm_name)
1.192 - cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
1.193 - print self.execute(cmd)
1.194 -
1.195 - # return the hostOnly IP for a running guest
1.196 - def getHostOnlyIP(self, vm_name):
1.197 - print('gettting hostOnly IP address ' + vm_name)
1.198 - cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
1.199 - result = self.execute(cmd)
1.200 - if result=='':
1.201 - return None
1.202 - result = result[1]
1.203 - return result[result.index(':')+1:].strip()
1.204 -
1.205 - # attach removable storage device to VM by provision of filter
1.206 - def attachRSD(self, vm_name, rsd_filter):
1.207 - cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
1.208 - print self.execute(cmd)
1.209 -
1.210 -
1.211 - # return the description set for an existing VM
1.212 - def getVMInfo(self, vm_name):
1.213 - cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
1.214 - results = self.execute(cmd)[1]
1.215 - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
1.216 - return props
1.217 -
1.218 - # return the configured USB filter for an existing VM
1.219 - def getUSBFilter(self, vm_name):
1.220 - props = self.getVMInfo(vm_name)
1.221 - keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
1.222 - keyset = set(props.keys())
1.223 - usb_filter = None
1.224 - if keyset.issuperset(keys):
1.225 - usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
1.226 - return usb_filter
1.227 -
1.228 - #generates ISO containing authorized_keys for use with guest VM
1.229 - def genCertificateISO(self, vm_name):
1.230 - machineFolder = self.getDefaultMachineFolder()
1.231 - # create .ssh folder in vm_name
1.232 - cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
1.233 - result = self.execute(cmd)
1.234 - # generate dvm_key pair in vm_name / .ssh
1.235 - cmd = self.cygwin_path+'bash.exe --login -c \"ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\"\"' #'echo -e "y\\n" |',
1.236 - result = self.execute(cmd)
1.237 - # set permissions for keys
1.238 - #TODO: test without chmod
1.239 - cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
1.240 - result = self.execute(cmd)
1.241 - # move out private key
1.242 - cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
1.243 - result = self.execute(cmd)
1.244 - # rename public key to authorized_keys
1.245 - cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
1.246 - result = self.execute(cmd)
1.247 - # generate iso image with .ssh/authorized keys
1.248 - cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
1.249 - result = self.execute(cmd)
1.250 -
1.251 - # attaches generated ssh public cert to guest vm
1.252 - def attachCertificateISO(self, vm_name):
1.253 - machineFolder = self.getDefaultMachineFolder()
1.254 - cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
1.255 - result = self.execute(cmd)
1.256 - return result
1.257 -
1.258 - # handles device change events
1.259 - def handleDeviceChange(self):
1.260 - attached_devices = self.getAttachedRSDs()
1.261 - connected_devices = self.listRSDS()
1.262 - for vm_name in attached_devices.keys():
1.263 - if connected_devices and attached_devices[vm_name] not in connected_devices.values():
1.264 - # self.netUse(vm_name)
1.265 - self.stopVM(vm_name)
1.266 - self.removeVM(vm_name)
1.267 -
1.268 - attached_devices = self.getAttachedRSDs()
1.269 - for connected_device in connected_devices.values():
1.270 - if attached_devices or connected_device not in attached_devices.values():
1.271 - new_sdvm = self.generateSDVMName()
1.272 - self.createVM(new_sdvm)
1.273 - self.attachRSD(new_sdvm, connected_device)
1.274 - self.startVM(new_sdvm)
1.275 - self.netUse(new_sdvm)
1.276 -
1.277 - def handleBrowsingRequest(self):
1.278 - new_sdvm = self.generateSDVMName()
1.279 - self.createVM(new_sdvm)
1.280 - self.genCertificateISO(new_sdvm)
1.281 - self.attachCertificateISO(new_sdvm)
1.282 -
1.283 - # executes command over ssh on guest vm
1.284 - def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
1.285 - # get vm ip
1.286 - address = self.getHostOnlyIP(vm_name)
1.287 - machineFolder = self.getDefaultMachineFolder()
1.288 - # run command
1.289 - cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
1.290 - return self.execute(cmd)
1.291 -
1.292 - # executes command over ssh on guest vm with X forwarding
1.293 - def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
1.294 - #TODO: verify if X server is running on user account
1.295 - #TODO: set DISPLAY accordingly
1.296 - address = self.getHostOnlyIP(vm_name)
1.297 - machineFolder = self.getDefaultMachineFolder()
1.298 - # run command
1.299 - cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
1.300 - return self.execute(cmd)
1.301 -
1.302 - # executes NET USE and connects to samba share on guestos
1.303 - def netUse(self, vm_name):
1.304 - ip = self.getHostOnlyIP(vm_name)
1.305 - cmd = 'net use H: \\' + ip + '\USB'
1.306 - return self.execute(cmd)
1.307 -
1.308 -
1.309 -if __name__ == '__main__':
1.310 - man = VMManager()
1.311 - man.cygwin_path = 'c:\\cygwin64\\bin\\'
1.312 - #man.handleDeviceChange()
1.313 - #print man.listSDVM()
1.314 - #man.configureHostNetworking()
1.315 - new_vm = man.generateSDVMName()
1.316 - man.createVM(new_vm)
1.317 - man.genCertificateISO(new_vm)
1.318 - man.attachCertificateISO(new_vm)
1.319 -
1.320 - #man.attachCertificateISO(vm_name)
1.321 - #man.sshGuestExecute(vm_name, "ls")
1.322 - #man.sshGuestX11Execute(vm_name, "iceweasel")
1.323 - #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
1.324 - #man.execute(cmd)
1.325 -
1.326 -
1.327 -
1.328 -