2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
13 from cygwin import Cygwin
26 def __init__(self, vendorid, productid, revision):
27 self.vendorid = vendorid.lower()
28 self.productid = productid.lower()
29 self.revision = revision.lower()
32 def __eq__(self, other):
33 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
36 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
39 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
42 class VMManager(object):
43 vmRootName = "SecurityDVM"
44 systemProperties = None
45 cygwin_path = 'c:\\cygwin64\\bin\\'
46 vboxManage = 'VBoxManage'
47 startNotifications = list()
50 #def __new__(cls, *args, **kwargs):
51 # if not cls._instance:
52 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
53 # return cls._instance
56 #def __new__(cls, *args, **kwargs):
57 # if not cls._instance:
58 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
59 # return cls._instance
62 self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
63 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
64 self.systemProperties = self.getSystemProperties()
69 if VMManager._instance == None:
70 VMManager._instance = VMManager()
71 return VMManager._instance
73 def putStartNotification(self, ip):
74 self.startNotifications.append(ip)
76 def isSDVMStarted(self, ip):
77 return self.startNotifications.contains(ip)
79 def execute(self, cmd):
81 print('trying to launch: ' + cmd)
82 process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
84 print('launched: ' + cmd)
85 result = process.wait()
86 res_stdout = process.stdout.read();
87 res_stderr = process.stderr.read();
93 return result, res_stdout, res_stderr
95 def getVBoxManagePath(self):
96 """get the path to the VirtualBox installation on this system"""
99 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
100 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
106 # return hosty system properties
107 def getSystemProperties(self):
108 cmd = self.vboxManage + ' list systemproperties'
109 result = self.execute(cmd)
112 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
115 # return the folder containing the guest VMs
116 def getDefaultMachineFolder(self):
117 return self.systemProperties["Default machine folder"]
119 #list the hostonly IFs exposed by the VBox host
120 def getHostOnlyIFs(self):
121 cmd = 'VBoxManage list hostonlyifs'
122 result = self.execute(cmd)[1]
125 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
129 cmd = 'VBoxManage list usbhost'
130 results = self.execute(cmd)[1]
131 results = results.split('Host USB Devices:')[1].strip()
133 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
137 for line in item.splitlines():
139 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
142 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
143 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
144 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
145 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
146 rsds[props['UUID']] = usb_filter;
151 # list all existing VMs registered with VBox
153 cmd = 'VBoxManage list vms'
154 result = self.execute(cmd)[1]
155 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
158 # list existing SDVMs
163 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
167 # generate valid (not already existing SDVM name). necessary for creating a new VM
168 def generateSDVMName(self):
170 for i in range(0,999):
171 if(not self.vmRootName+str(i) in vms):
172 return self.vmRootName+str(i)
175 # return the RSDs attached to all existing SDVMs
176 def getAttachedRSDs(self):
177 vms = self.listSDVM()
178 attached_devices = dict()
180 rsd_filter = self.getUSBFilter(vm)
181 if rsd_filter != None:
182 attached_devices[vm] = rsd_filter
183 return attached_devices
185 # configures hostonly networking and DHCP server. requires admin rights
186 def configureHostNetworking(self):
187 #cmd = 'vboxmanage list hostonlyifs'
189 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
191 #cmd = 'vboxmanage hostonlyif create'
193 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
195 #cmd = 'vboxmanage dhcpserver add'
197 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'
200 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
201 def createVM(self, vm_name):
202 hostonly_if = self.getHostOnlyIFs()
203 machineFolder = self.getDefaultMachineFolder()
204 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
206 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
208 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
210 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
215 #remove VM from the system. should be used on VMs returned by listSDVMs
216 def removeVM(self, vm_name):
217 print('removing ' + vm_name)
218 cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
219 print self.execute(cmd)
220 machineFolder = self.getDefaultMachineFolder()
221 cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
222 print self.execute(cmd)
225 def startVM(self, vm_name):
226 print('starting ' + vm_name)
227 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
228 result = self.execute(cmd)
229 while result[0] != 0:
230 print "Failed to start SDVM: ", vm_name, " retrying"
232 result = self.execute(cmd)
233 #verify against (0, 'Waiting for VM "SecurityDVM0" to power on...\r\nVM "SecurityDVM0" has been successfully started.\r\n', '')
238 def stopVM(self, vm_name):
239 print('stopping ' + vm_name)
240 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
241 print self.execute(cmd)
243 # return the hostOnly IP for a running guest
244 def getHostOnlyIP(self, vm_name):
245 print('gettting hostOnly IP address ' + vm_name)
246 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
247 result = self.execute(cmd)
251 if result.startswith('No value set!'):
253 return result[result.index(':')+1:].strip()
255 # attach removable storage device to VM by provision of filter
256 def attachRSD(self, vm_name, rsd_filter):
257 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
258 print self.execute(cmd)
261 # return the description set for an existing VM
262 def getVMInfo(self, vm_name):
263 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
264 results = self.execute(cmd)[1]
265 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
268 # return the configured USB filter for an existing VM
269 def getUSBFilter(self, vm_name):
270 props = self.getVMInfo(vm_name)
271 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
272 keyset = set(props.keys())
274 if keyset.issuperset(keys):
275 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
278 #generates ISO containing authorized_keys for use with guest VM
279 def genCertificateISO(self, vm_name):
280 machineFolder = self.getDefaultMachineFolder()
281 # create .ssh folder in vm_name
282 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
283 result = self.execute(cmd)
284 # generate dvm_key pair in vm_name / .ssh
285 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" |',
286 result = self.execute(cmd)
287 # set permissions for keys
288 #TODO: test without chmod
289 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
290 result = self.execute(cmd)
291 # move out private key
292 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
293 result = self.execute(cmd)
294 # rename public key to authorized_keys
295 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
296 result = self.execute(cmd)
297 # generate iso image with .ssh/authorized keys
298 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
299 result = self.execute(cmd)
301 # attaches generated ssh public cert to guest vm
302 def attachCertificateISO(self, vm_name):
303 machineFolder = self.getDefaultMachineFolder()
304 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
305 result = self.execute(cmd)
308 handleDeviceChangeLock = threading.Lock()
310 # handles device change events
311 def handleDeviceChange(self):
312 if VMManager.handleDeviceChangeLock.acquire(True):
315 attached_devices = self.getAttachedRSDs()
316 connected_devices = self.listRSDS()
317 for vm_name in attached_devices.keys():
318 if attached_devices[vm_name] not in connected_devices.values():
319 self.unmapNetworkDrive('h:')
321 self.removeVM(vm_name)
322 #create new vm for attached device if any
323 attached_devices = self.getAttachedRSDs()
324 for connected_device in connected_devices.values():
325 if (attached_devices and False) or (connected_device not in attached_devices.values()):
326 new_sdvm = self.generateSDVMName()
327 self.createVM(new_sdvm)
328 self.attachRSD(new_sdvm, connected_device)
331 self.startVM(new_sdvm)
332 # wait for machine to come up
333 while new_ip == None:
335 new_ip = self.getHostOnlyIP(new_sdvm)
336 while new_ip not in self.startNotifications:
339 self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
340 #TODO: cleanup notifications somwhere else (eg. machine shutdown)
341 self.startNotifications.remove(new_ip)
342 VMManager.handleDeviceChangeLock.release()
345 def handleBrowsingRequest(self):
346 if VMManager.handleDeviceChangeLock.acquire(True):
348 new_sdvm = self.generateSDVMName()
349 self.createVM(new_sdvm)
350 self.genCertificateISO(new_sdvm)
351 self.attachCertificateISO(new_sdvm)
352 self.startVM(new_sdvm)
353 # wait for machine to come up
354 while new_ip == None:
356 new_ip = self.getHostOnlyIP(new_sdvm)
357 while new_ip not in self.startNotifications:
359 VMManager.handleDeviceChangeLock.release()
362 # executes command over ssh on guest vm
363 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
365 address = self.getHostOnlyIP(vm_name)
366 machineFolder = self.getDefaultMachineFolder()
368 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
369 return self.execute(cmd)
371 # executes command over ssh on guest vm with X forwarding
372 def sshGuestX11Execute(self, vm_name, prog, user_name='osecuser'):
373 #TODO: verify if X server is running on user account
374 #TODO: set DISPLAY accordingly
375 address = self.getHostOnlyIP(vm_name)
376 machineFolder = self.getDefaultMachineFolder()
378 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
379 return self.execute(cmd)
381 #Small function to check the availability of network resource.
382 def isAvailable(self, path):
383 cmd = 'IF EXIST ' + path + ' echo YES'
384 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
385 return string.find(str(result), 'YES',)
387 #Small function to check if the mention location is a directory
388 def isDirectory(self, path):
389 cmd = 'dir ' + path + ' | FIND ".."'
390 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
391 return string.find(str(result), 'DIR',)
393 def mapNetworkDrive(self, drive, networkPath, user, password):
394 self.unmapNetworkDrive('h:')
395 #Check for drive availability
396 if self.isAvailable(drive) > -1:
397 print "Drive letter is already in use: ", drive
399 #Check for network resource availability
400 while self.isAvailable(networkPath) == -1:
402 print "Path not accessible: ", networkPath, " retrying"
405 #Prepare 'NET USE' commands
406 cmd = 'NET USE ' + drive + ' ' + networkPath
408 cmd = cmd + ' ' + password + ' /User' + user
411 #Execute 'NET USE' command with authentication
412 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
413 print "Executed: ", cmd
414 if string.find(str(result), 'successfully',) == -1:
417 #Mapped with first try
420 def unmapNetworkDrive(self, drive):
421 #Check if the drive is in use
422 if self.isAvailable(drive) == -1:
425 #Prepare 'NET USE' command
426 cmd = 'net use ' + drive + ' /DELETE'
427 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
428 if string.find(str(result), 'successfully',) == -1:
432 #if __name__ == '__main__':
434 #man = VMManager.getInstance()
435 #man.removeVM('SecurityDVM0')
436 #man.netUse('192.168.56.134', 'USB\\')
437 #ip = '192.168.56.139'
438 #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
440 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
441 #man.handleDeviceChange()
442 #print man.listSDVM()
443 #man.configureHostNetworking()
444 #new_vm = man.generateSDVMName()
445 #man.createVM(new_vm)
446 #man.genCertificateISO(new_vm)
447 #man.attachCertificateISO(new_vm)
449 #man.attachCertificateISO(vm_name)
450 #man.sshGuestExecute(vm_name, "ls")
451 #man.sshGuestX11Execute(vm_name, "iceweasel")
452 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""