1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/server/vmmanager/vmmanager.py Tue Dec 03 18:04:46 2013 +0100
1.3 @@ -0,0 +1,299 @@
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 + def getSystemProperties(self):
1.66 + cmd = 'VBoxManage list systemproperties'
1.67 + result = self.execute(cmd)
1.68 + if result[1]=='':
1.69 + return None
1.70 + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
1.71 + return props
1.72 +
1.73 + def getDefaultMachineFolder(self):
1.74 + return self.systemProperties["Default machine folder"]
1.75 +
1.76 + def createVM(self, vm_name):
1.77 + hostonly_if = self.getHostOnlyIFs()
1.78 + cmd = 'VBoxManage createvm --name ' + vm_name, ' --ostype Debian --register'
1.79 + self.execute(cmd)
1.80 + cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 ' + hostonly_if['Name'] + ' --nic2 nat'
1.81 + self.execute(cmd)
1.82 + cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --sataportcount 2'
1.83 + self.execute(cmd)
1.84 + cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --mtype normal --medium C:\Users\BarthaM\VirtualBox VMs\SecurityVM\SecurityVM.vdi'
1.85 + self.execute(cmd)
1.86 + return
1.87 +
1.88 + def attachRSD(self, vm_name, filter):
1.89 + cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + filter.vendorid + ' --productid ' + filter.productid + ' --revision ' + filter.revision
1.90 + print self.execute(cmd)
1.91 +
1.92 + def removeVM(self, vm_name):
1.93 + print('removing ' + vm_name)
1.94 + cmd = 'VBoxManage unregistervm', vm_name, '--delete'
1.95 + print self.execute(cmd)
1.96 + machineFolder = self.getDefaultMachineFolder()
1.97 + cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
1.98 + print self.execute(cmd)
1.99 +
1.100 + def startVM(self, vm_name):
1.101 + print('starting ' + vm_name)
1.102 + cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
1.103 + print self.execute(cmd)
1.104 +
1.105 + def stopVM(self, vm_name):
1.106 + print('stopping ' + vm_name)
1.107 + cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
1.108 + print self.execute(cmd)
1.109 +
1.110 + def getHostOnlyIFs(self):
1.111 + cmd = ['VBoxManage list hostonlyifs']
1.112 + result = self.execute(cmd)
1.113 + if result=='':
1.114 + return None
1.115 + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
1.116 + return props
1.117 +
1.118 + def getHostOnlyIP(self, vm_name):
1.119 + print('gettting hostOnly IP address ' + vm_name)
1.120 + cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
1.121 + result = self.execute(cmd)
1.122 + if result=='':
1.123 + return None
1.124 + result = result[1]
1.125 + return result[result.index(':')+1:].strip()
1.126 +
1.127 + def listRSDS(self):
1.128 + cmd = 'VBoxManage list usbhost'
1.129 + results = self.execute(cmd)
1.130 + results = results.split('Host USB Devices:')[1].strip()
1.131 +
1.132 + items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
1.133 + rsds = dict()
1.134 + for item in items:
1.135 + props = dict()
1.136 + for line in item.splitlines():
1.137 + if line != "":
1.138 + k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
1.139 + props[k] = v;
1.140 +
1.141 + if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
1.142 + usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
1.143 + re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
1.144 + re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
1.145 + rsds[props['UUID']] = usb_filter;
1.146 + if DEBUG:
1.147 + print filter
1.148 + return rsds
1.149 +
1.150 + def listVM(self):
1.151 + cmd = 'VBoxManage list vms'
1.152 + result = self.execute(cmd)
1.153 + vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
1.154 + return vms
1.155 +
1.156 + def listSDVM(self):
1.157 + vms = self.listVM()
1.158 + svdms = []
1.159 + for vm in vms:
1.160 + if vm.startswith(self.vmRootName) and vm != self.vmRootName:
1.161 + svdms.append(vm)
1.162 + return svdms
1.163 +
1.164 + def generateSDVMName(self):
1.165 + vms = self.listVM()
1.166 + for i in range(0,999):
1.167 + if(not self.vmRootName+str(i) in vms):
1.168 + return self.vmRootName+str(i)
1.169 + return ''
1.170 +
1.171 + def getVMInfo(self, vm_name):
1.172 + cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
1.173 + results = self.execute(cmd)
1.174 + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
1.175 + return props
1.176 +
1.177 + def getUSBFilter(self, vm_name):
1.178 + props = self.getVMInfo(vm_name)
1.179 + keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
1.180 + keyset = set(props.keys())
1.181 + usb_filter = None
1.182 + if keyset.issuperset(keys):
1.183 + usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
1.184 + return usb_filter
1.185 +
1.186 + def getAttachedRSDs(self):
1.187 + vms = self.listSDVM()
1.188 + attached_devices = dict()
1.189 + for vm in vms:
1.190 + filter = self.getUSBFilter(vm)
1.191 + if filter != None:
1.192 + attached_devices[vm] = filter
1.193 + return attached_devices
1.194 +
1.195 + #generates ISO containing authorized_keys for use with guest VM
1.196 + def genCertificateISO(self, vm_name):
1.197 + machineFolder = self.getDefaultMachineFolder()
1.198 + # create .ssh folder in vm_name
1.199 + cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
1.200 + result = self.execute(cmd)
1.201 + # generate dvm_key pair in vm_name / .ssh
1.202 + 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.203 + result = self.execute(cmd)
1.204 + # set permissions for keys
1.205 + #TODO: test without chmod
1.206 + cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
1.207 + result = self.execute(cmd)
1.208 + # move out private key
1.209 + cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
1.210 + result = self.execute(cmd)
1.211 + # rename public key to authorized_keys
1.212 + cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
1.213 + result = self.execute(cmd)
1.214 + # generate iso image with .ssh/authorized keys
1.215 + 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.216 + result = self.execute(cmd)
1.217 +
1.218 + # attaches generated ssh public cert to guest vm
1.219 + def attachCertificateISO(self, vm_name):
1.220 + machineFolder = self.getDefaultMachineFolder()
1.221 + cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
1.222 + result = self.execute(cmd)
1.223 + return result
1.224 +
1.225 + # handles device change events
1.226 + def handleDeviceChange(self):
1.227 + attached_devices = self.getAttachedRSDs()
1.228 + connected_devices = self.listRSDS()
1.229 + for vm_name in attached_devices.keys():
1.230 + if attached_devices[vm_name] not in connected_devices.values():
1.231 + self.stopVM(vm_name)
1.232 + self.removeVM(vm_name)
1.233 +
1.234 + attached_devices = self.getAttachedRSDs()
1.235 + for connected_device in connected_devices.values():
1.236 + if connected_device not in attached_devices.values():
1.237 + new_sdvm = self.generateSDVMName()
1.238 + self.createVM(new_sdvm)
1.239 + self.genCertificateISO(new_sdvm)
1.240 + self.attachCertificateISO(new_sdvm)
1.241 + self.attachRSD(new_sdvm, connected_device)
1.242 + self.startVM(new_sdvm)
1.243 +
1.244 + # executes command over ssh on guest vm
1.245 + def sshGuestExecute(self, vm_name, prog):
1.246 + # get vm ip
1.247 + address = self.getHostOnlyIP(vm_name)
1.248 + machineFolder = self.getDefaultMachineFolder()
1.249 + # run command
1.250 + cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" bartham@' + address + ' ' + prog + '\"'
1.251 + return self.execute(cmd)
1.252 +
1.253 + # executes command over ssh on guest vm with X forwarding
1.254 + def sshGuestX11Execute(self, vm_name, prog):
1.255 + #TODO: verify if X server is running on user account
1.256 + #TODO: set DISPLAY accordingly
1.257 + address = self.getHostOnlyIP(vm_name)
1.258 + machineFolder = self.getDefaultMachineFolder()
1.259 + # run command
1.260 + cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" bartham@' + address + ' ' + prog + '\"'
1.261 + return self.execute(cmd)
1.262 +
1.263 + # configures hostonly networking and DHCP server
1.264 + # requires admin rights
1.265 + def configureHostNetworking(self):
1.266 + #cmd = 'vboxmanage list hostonlyifs'
1.267 + #self.execute(cmd)
1.268 + #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
1.269 + #self.execute(cmd)
1.270 + #cmd = 'vboxmanage hostonlyif create'
1.271 + #self.execute(cmd)
1.272 + cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
1.273 + self.execute(cmd)
1.274 + #cmd = 'vboxmanage dhcpserver add'
1.275 + #self.execute(cmd)
1.276 + 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.277 + self.execute(cmd)
1.278 +
1.279 + # executes NET USE and connects to samba share on guestos
1.280 + def netUse(self, vm_name):
1.281 + ip = self.getHostOnlyIP(vm_name)
1.282 + cmd = 'net use H: \\' + ip + '\RSD_Device'
1.283 + return self.execute(cmd)
1.284 +
1.285 +
1.286 +if __name__ == '__main__':
1.287 + man = VMManager()
1.288 + man.cygwin_path = 'c:\\cygwin64\\bin\\'
1.289 + #man.handleDeviceChange()
1.290 + #print man.listSDVM()
1.291 + man.configureHostNetworking()
1.292 + vm_name = "SecurityDVM0"
1.293 + man.genCertificateISO(vm_name)
1.294 + #man.attachCertificateISO(vm_name)
1.295 + #man.sshGuestExecute(vm_name, "ls")
1.296 + #man.sshGuestX11Execute(vm_name, "iceweasel")
1.297 + #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
1.298 + #man.execute(cmd)
1.299 +
1.300 +
1.301 +
1.302 +