singleton in VMManager. get using VMManager.getInstance()
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'
46 #def __new__(cls, *args, **kwargs):
47 # if not cls._instance:
48 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
49 # return cls._instance
52 self.cygwin_path = os.path.join(Cygwin.root(), 'bin')
53 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
54 self.systemProperties = self.getSystemProperties()
60 if VMManager._instance == None:
61 VMManager._instance = VMManager()
62 return VMManager._instance
64 def execute(self, cmd):
66 print('trying to launch: ' + cmd)
67 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
69 print('launched: ' + cmd)
70 result = process.wait()
71 res_stdout = process.stdout.read();
72 res_stderr = process.stderr.read();
78 return result, res_stdout, res_stderr
80 def getVBoxManagePath(self):
81 """get the path to the VirtualBox installation on this system"""
84 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
85 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
91 # return hosty system properties
92 def getSystemProperties(self):
93 cmd = self.vboxManage + ' list systemproperties'
94 result = self.execute(cmd)
97 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
100 # return the folder containing the guest VMs
101 def getDefaultMachineFolder(self):
102 return self.systemProperties["Default machine folder"]
104 #list the hostonly IFs exposed by the VBox host
105 def getHostOnlyIFs(self):
106 cmd = 'VBoxManage list hostonlyifs'
107 result = self.execute(cmd)[1]
110 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
114 cmd = 'VBoxManage list usbhost'
115 results = self.execute(cmd)[1]
116 results = results.split('Host USB Devices:')[1].strip()
118 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
122 for line in item.splitlines():
124 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
127 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
128 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
129 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
130 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
131 rsds[props['UUID']] = usb_filter;
136 # list all existing VMs registered with VBox
138 cmd = 'VBoxManage list vms'
139 result = self.execute(cmd)[1]
140 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
143 # list existing SDVMs
148 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
152 # generate valid (not already existing SDVM name). necessary for creating a new VM
153 def generateSDVMName(self):
155 for i in range(0,999):
156 if(not self.vmRootName+str(i) in vms):
157 return self.vmRootName+str(i)
160 # return the RSDs attached to all existing SDVMs
161 def getAttachedRSDs(self):
162 vms = self.listSDVM()
163 attached_devices = dict()
165 rsd_filter = self.getUSBFilter(vm)
166 if rsd_filter != None:
167 attached_devices[vm] = rsd_filter
168 return attached_devices
170 # configures hostonly networking and DHCP server. requires admin rights
171 def configureHostNetworking(self):
172 #cmd = 'vboxmanage list hostonlyifs'
174 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
176 #cmd = 'vboxmanage hostonlyif create'
178 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
180 #cmd = 'vboxmanage dhcpserver add'
182 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'
185 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
186 def createVM(self, vm_name):
187 hostonly_if = self.getHostOnlyIFs()
188 machineFolder = self.getDefaultMachineFolder()
189 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
191 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
193 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
195 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
200 #remove VM from the system. should be used on VMs returned by listSDVMs
201 def removeVM(self, vm_name):
202 print('removing ' + vm_name)
203 cmd = 'VBoxManage unregistervm', vm_name, '--delete'
204 print self.execute(cmd)
205 machineFolder = self.getDefaultMachineFolder()
206 cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
207 print self.execute(cmd)
210 def startVM(self, vm_name):
211 print('starting ' + vm_name)
212 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
213 print self.execute(cmd)
216 def stopVM(self, vm_name):
217 print('stopping ' + vm_name)
218 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
219 print self.execute(cmd)
221 # return the hostOnly IP for a running guest
222 def getHostOnlyIP(self, vm_name):
223 print('gettting hostOnly IP address ' + vm_name)
224 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
225 result = self.execute(cmd)
229 return result[result.index(':')+1:].strip()
231 # attach removable storage device to VM by provision of filter
232 def attachRSD(self, vm_name, rsd_filter):
233 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
234 print self.execute(cmd)
237 # return the description set for an existing VM
238 def getVMInfo(self, vm_name):
239 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
240 results = self.execute(cmd)[1]
241 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
244 # return the configured USB filter for an existing VM
245 def getUSBFilter(self, vm_name):
246 props = self.getVMInfo(vm_name)
247 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
248 keyset = set(props.keys())
250 if keyset.issuperset(keys):
251 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
254 #generates ISO containing authorized_keys for use with guest VM
255 def genCertificateISO(self, vm_name):
256 machineFolder = self.getDefaultMachineFolder()
257 # create .ssh folder in vm_name
258 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
259 result = self.execute(cmd)
260 # generate dvm_key pair in vm_name / .ssh
261 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" |',
262 result = self.execute(cmd)
263 # set permissions for keys
264 #TODO: test without chmod
265 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
266 result = self.execute(cmd)
267 # move out private key
268 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
269 result = self.execute(cmd)
270 # rename public key to authorized_keys
271 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
272 result = self.execute(cmd)
273 # generate iso image with .ssh/authorized keys
274 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
275 result = self.execute(cmd)
277 # attaches generated ssh public cert to guest vm
278 def attachCertificateISO(self, vm_name):
279 machineFolder = self.getDefaultMachineFolder()
280 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
281 result = self.execute(cmd)
284 # handles device change events
285 def handleDeviceChange(self):
286 attached_devices = self.getAttachedRSDs()
287 connected_devices = self.listRSDS()
288 for vm_name in attached_devices.keys():
289 if connected_devices and attached_devices[vm_name] not in connected_devices.values():
290 # self.netUse(vm_name)
292 self.removeVM(vm_name)
294 attached_devices = self.getAttachedRSDs()
295 for connected_device in connected_devices.values():
296 if attached_devices or connected_device not in attached_devices.values():
297 new_sdvm = self.generateSDVMName()
298 self.createVM(new_sdvm)
299 self.attachRSD(new_sdvm, connected_device)
300 self.startVM(new_sdvm)
301 self.netUse(new_sdvm)
303 def handleBrowsingRequest(self):
304 new_sdvm = self.generateSDVMName()
305 self.createVM(new_sdvm)
306 self.genCertificateISO(new_sdvm)
307 self.attachCertificateISO(new_sdvm)
309 # executes command over ssh on guest vm
310 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
312 address = self.getHostOnlyIP(vm_name)
313 machineFolder = self.getDefaultMachineFolder()
315 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
316 return self.execute(cmd)
318 # executes command over ssh on guest vm with X forwarding
319 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
320 #TODO: verify if X server is running on user account
321 #TODO: set DISPLAY accordingly
322 address = self.getHostOnlyIP(vm_name)
323 machineFolder = self.getDefaultMachineFolder()
325 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
326 return self.execute(cmd)
328 # executes NET USE and connects to samba share on guestos
329 def netUse(self, vm_name):
330 ip = self.getHostOnlyIP(vm_name)
331 cmd = 'net use H: \\' + ip + '\USB'
332 return self.execute(cmd)
335 #if __name__ == '__main__':
337 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
338 #man.handleDeviceChange()
339 #print man.listSDVM()
340 #man.configureHostNetworking()
341 #new_vm = man.generateSDVMName()
342 #man.createVM(new_vm)
343 #man.genCertificateISO(new_vm)
344 #man.attachCertificateISO(new_vm)
346 #man.attachCertificateISO(vm_name)
347 #man.sshGuestExecute(vm_name, "ls")
348 #man.sshGuestX11Execute(vm_name, "iceweasel")
349 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""