isingleton vmmaneger. get with VMManager.getInstance()
/sdvm_started endpoint isSDVMStarted() methon in VMManager
2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
13 from cygwin import Cygwin
23 def __init__(self, vendorid, productid, revision):
24 self.vendorid = vendorid.lower()
25 self.productid = productid.lower()
26 self.revision = revision.lower()
29 def __eq__(self, other):
30 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
33 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
36 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
39 class VMManager(object):
40 vmRootName = "SecurityDVM"
41 systemProperties = None
42 cygwin_path = 'c:\\cygwin64\\bin\\'
43 vboxManage = 'VBoxManage'
44 startNotifications = list()
47 #def __new__(cls, *args, **kwargs):
48 # if not cls._instance:
49 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
50 # return cls._instance
53 #def __new__(cls, *args, **kwargs):
54 # if not cls._instance:
55 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
56 # return cls._instance
59 self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
60 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
61 self.systemProperties = self.getSystemProperties()
66 if VMManager._instance == None:
67 VMManager._instance = VMManager()
68 return VMManager._instance
70 def putStartNotification(self, ip):
71 self.startNotifications.append(ip)
73 def isSDVMStarted(self, ip):
74 return self.startNotifications.contains(ip)
76 def execute(self, cmd):
78 print('trying to launch: ' + cmd)
79 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
81 print('launched: ' + cmd)
82 result = process.wait()
83 res_stdout = process.stdout.read();
84 res_stderr = process.stderr.read();
90 return result, res_stdout, res_stderr
92 def getVBoxManagePath(self):
93 """get the path to the VirtualBox installation on this system"""
96 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
97 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
103 # return hosty system properties
104 def getSystemProperties(self):
105 cmd = self.vboxManage + ' list systemproperties'
106 result = self.execute(cmd)
109 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
112 # return the folder containing the guest VMs
113 def getDefaultMachineFolder(self):
114 return self.systemProperties["Default machine folder"]
116 #list the hostonly IFs exposed by the VBox host
117 def getHostOnlyIFs(self):
118 cmd = 'VBoxManage list hostonlyifs'
119 result = self.execute(cmd)[1]
122 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
126 cmd = 'VBoxManage list usbhost'
127 results = self.execute(cmd)[1]
128 results = results.split('Host USB Devices:')[1].strip()
130 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
134 for line in item.splitlines():
136 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
139 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
140 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
141 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
142 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
143 rsds[props['UUID']] = usb_filter;
148 # list all existing VMs registered with VBox
150 cmd = 'VBoxManage list vms'
151 result = self.execute(cmd)[1]
152 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
155 # list existing SDVMs
160 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
164 # generate valid (not already existing SDVM name). necessary for creating a new VM
165 def generateSDVMName(self):
167 for i in range(0,999):
168 if(not self.vmRootName+str(i) in vms):
169 return self.vmRootName+str(i)
172 # return the RSDs attached to all existing SDVMs
173 def getAttachedRSDs(self):
174 vms = self.listSDVM()
175 attached_devices = dict()
177 rsd_filter = self.getUSBFilter(vm)
178 if rsd_filter != None:
179 attached_devices[vm] = rsd_filter
180 return attached_devices
182 # configures hostonly networking and DHCP server. requires admin rights
183 def configureHostNetworking(self):
184 #cmd = 'vboxmanage list hostonlyifs'
186 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
188 #cmd = 'vboxmanage hostonlyif create'
190 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
192 #cmd = 'vboxmanage dhcpserver add'
194 cmd = 'VBoxManage dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.200'
197 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
198 def createVM(self, vm_name):
199 hostonly_if = self.getHostOnlyIFs()
200 machineFolder = self.getDefaultMachineFolder()
201 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
203 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
205 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
207 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
212 #remove VM from the system. should be used on VMs returned by listSDVMs
213 def removeVM(self, vm_name):
214 print('removing ' + vm_name)
215 cmd = 'VBoxManage unregistervm', vm_name, '--delete'
216 print self.execute(cmd)
217 machineFolder = self.getDefaultMachineFolder()
218 cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
219 print self.execute(cmd)
222 def startVM(self, vm_name):
223 print('starting ' + vm_name)
224 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
225 print self.execute(cmd)
228 def stopVM(self, vm_name):
229 print('stopping ' + vm_name)
230 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
231 print self.execute(cmd)
233 # return the hostOnly IP for a running guest
234 def getHostOnlyIP(self, vm_name):
235 print('gettting hostOnly IP address ' + vm_name)
236 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
237 result = self.execute(cmd)
241 return result[result.index(':')+1:].strip()
243 # attach removable storage device to VM by provision of filter
244 def attachRSD(self, vm_name, rsd_filter):
245 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
246 print self.execute(cmd)
249 # return the description set for an existing VM
250 def getVMInfo(self, vm_name):
251 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
252 results = self.execute(cmd)[1]
253 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
256 # return the configured USB filter for an existing VM
257 def getUSBFilter(self, vm_name):
258 props = self.getVMInfo(vm_name)
259 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
260 keyset = set(props.keys())
262 if keyset.issuperset(keys):
263 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
266 #generates ISO containing authorized_keys for use with guest VM
267 def genCertificateISO(self, vm_name):
268 machineFolder = self.getDefaultMachineFolder()
269 # create .ssh folder in vm_name
270 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
271 result = self.execute(cmd)
272 # generate dvm_key pair in vm_name / .ssh
273 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" |',
274 result = self.execute(cmd)
275 # set permissions for keys
276 #TODO: test without chmod
277 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
278 result = self.execute(cmd)
279 # move out private key
280 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
281 result = self.execute(cmd)
282 # rename public key to authorized_keys
283 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
284 result = self.execute(cmd)
285 # generate iso image with .ssh/authorized keys
286 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
287 result = self.execute(cmd)
289 # attaches generated ssh public cert to guest vm
290 def attachCertificateISO(self, vm_name):
291 machineFolder = self.getDefaultMachineFolder()
292 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
293 result = self.execute(cmd)
296 # handles device change events
297 def handleDeviceChange(self):
298 attached_devices = self.getAttachedRSDs()
299 connected_devices = self.listRSDS()
300 for vm_name in attached_devices.keys():
301 if connected_devices and attached_devices[vm_name] not in connected_devices.values():
302 # self.netUse(vm_name)
304 self.removeVM(vm_name)
306 attached_devices = self.getAttachedRSDs()
307 for connected_device in connected_devices.values():
308 if attached_devices or connected_device not in attached_devices.values():
309 new_sdvm = self.generateSDVMName()
310 self.createVM(new_sdvm)
311 self.attachRSD(new_sdvm, connected_device)
312 self.startVM(new_sdvm)
313 self.netUse(new_sdvm)
315 def handleBrowsingRequest(self):
316 new_sdvm = self.generateSDVMName()
317 self.createVM(new_sdvm)
318 self.genCertificateISO(new_sdvm)
319 self.attachCertificateISO(new_sdvm)
322 # executes command over ssh on guest vm
323 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
325 address = self.getHostOnlyIP(vm_name)
326 machineFolder = self.getDefaultMachineFolder()
328 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
329 return self.execute(cmd)
331 # executes command over ssh on guest vm with X forwarding
332 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
333 #TODO: verify if X server is running on user account
334 #TODO: set DISPLAY accordingly
335 address = self.getHostOnlyIP(vm_name)
336 machineFolder = self.getDefaultMachineFolder()
338 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
339 return self.execute(cmd)
341 # executes NET USE and connects to samba share on guestos
342 def netUse(self, vm_name):
343 ip = self.getHostOnlyIP(vm_name)
344 cmd = 'net use H: \\' + ip + '\USB'
345 return self.execute(cmd)
348 #if __name__ == '__main__':
350 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
351 #man.handleDeviceChange()
352 #print man.listSDVM()
353 #man.configureHostNetworking()
354 #new_vm = man.generateSDVMName()
355 #man.createVM(new_vm)
356 #man.genCertificateISO(new_vm)
357 #man.attachCertificateISO(new_vm)
359 #man.attachCertificateISO(vm_name)
360 #man.sshGuestExecute(vm_name, "ls")
361 #man.sshGuestX11Execute(vm_name, "iceweasel")
362 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""