2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
13 from cygwin import Cygwin
20 class VMManagerException(Exception):
21 def __init__(self, value):
24 return repr(self.value)
31 def __init__(self, vendorid, productid, revision):
32 self.vendorid = vendorid.lower()
33 self.productid = productid.lower()
34 self.revision = revision.lower()
37 def __eq__(self, other):
38 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
41 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
44 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
47 class VMManager(object):
48 vmRootName = "SecurityDVM"
49 systemProperties = None
50 cygwin_path = 'c:\\cygwin64\\bin\\'
51 vboxManage = 'VBoxManage'
52 startNotifications = list()
55 #def __new__(cls, *args, **kwargs):
56 # if not cls._instance:
57 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
58 # return cls._instance
61 #def __new__(cls, *args, **kwargs):
62 # if not cls._instance:
63 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
64 # return cls._instance
67 self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
68 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
69 self.systemProperties = self.getSystemProperties()
74 if VMManager._instance == None:
75 VMManager._instance = VMManager()
76 return VMManager._instance
78 def putStartNotification(self, ip):
79 self.startNotifications.append(ip)
81 def isSDVMStarted(self, ip):
82 return self.startNotifications.contains(ip)
84 def execute(self, cmd, wait_return=True ):
86 print('trying to launch: ' + cmd)
87 process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
89 print('launched: ' + cmd)
91 return [0, 'working in background', '']
92 result = process.wait()
93 res_stdout = process.stdout.read();
94 res_stderr = process.stderr.read();
101 raise VMManagerException(res_stderr)
102 return result, res_stdout, res_stderr
104 def getVBoxManagePath(self):
105 """get the path to the VirtualBox installation on this system"""
108 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
109 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
115 # return hosty system properties
116 def getSystemProperties(self):
117 cmd = self.vboxManage + ' list systemproperties'
118 result = self.execute(cmd)
121 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
124 # return the folder containing the guest VMs
125 def getDefaultMachineFolder(self):
126 return self.systemProperties["Default machine folder"]
128 #list the hostonly IFs exposed by the VBox host
129 def getHostOnlyIFs(self):
130 cmd = 'VBoxManage list hostonlyifs'
131 result = self.execute(cmd)[1]
134 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
138 cmd = 'VBoxManage list usbhost'
139 results = self.execute(cmd)[1]
140 results = results.split('Host USB Devices:')[1].strip()
142 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
146 for line in item.splitlines():
148 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
151 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
152 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
153 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
154 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
155 rsds[props['UUID']] = usb_filter;
160 # list all existing VMs registered with VBox
162 cmd = 'VBoxManage list vms'
163 result = self.execute(cmd)[1]
164 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
167 # list existing SDVMs
172 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
176 # generate valid (not already existing SDVM name). necessary for creating a new VM
177 def generateSDVMName(self):
179 for i in range(0,999):
180 if(not self.vmRootName+str(i) in vms):
181 return self.vmRootName+str(i)
184 # return the RSDs attached to all existing SDVMs
185 def getAttachedRSDs(self):
186 vms = self.listSDVM()
187 attached_devices = dict()
189 rsd_filter = self.getUSBFilter(vm)
190 if rsd_filter != None:
191 attached_devices[vm] = rsd_filter
192 return attached_devices
194 # configures hostonly networking and DHCP server. requires admin rights
195 def configureHostNetworking(self):
196 #cmd = 'vboxmanage list hostonlyifs'
198 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
200 #cmd = 'vboxmanage hostonlyif create'
202 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
204 #cmd = 'vboxmanage dhcpserver add'
206 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'
209 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
210 def createVM(self, vm_name):
211 hostonly_if = self.getHostOnlyIFs()
212 machineFolder = self.getDefaultMachineFolder()
213 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
215 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
217 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
219 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' #--mtype immutable
223 #remove VM from the system. should be used on VMs returned by listSDVMs
224 def removeVM(self, vm_name):
225 print('removing ' + vm_name)
226 cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
227 print self.execute(cmd)
228 machineFolder = self.getDefaultMachineFolder()
229 cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
230 print self.execute(cmd)
233 def startVM(self, vm_name):
234 print('starting ' + vm_name)
235 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
236 result = self.execute(cmd)
237 while not string.find(str(result), 'successfully started',):
238 print "Failed to start SDVM: ", vm_name, " retrying"
240 result = self.execute(cmd)
244 def stopVM(self, vm_name):
245 print('stopping ' + vm_name)
246 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
249 # return the hostOnly IP for a running guest
250 def getHostOnlyIP(self, vm_name):
251 print('gettting hostOnly IP address ' + vm_name)
252 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
253 result = self.execute(cmd)
257 if result.startswith('No value set!'):
259 return result[result.index(':')+1:].strip()
261 # attach removable storage device to VM by provision of filter
262 def attachRSD(self, vm_name, rsd_filter):
263 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
264 print self.execute(cmd)
267 # return the description set for an existing VM
268 def getVMInfo(self, vm_name):
269 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
270 results = self.execute(cmd)[1]
271 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
274 # return the configured USB filter for an existing VM
275 def getUSBFilter(self, vm_name):
276 props = self.getVMInfo(vm_name)
277 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
278 keyset = set(props.keys())
280 if keyset.issuperset(keys):
281 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
284 #generates ISO containing authorized_keys for use with guest VM
285 def genCertificateISO(self, vm_name):
286 machineFolder = self.getDefaultMachineFolder()
287 # create .ssh folder in vm_name
288 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
290 # generate dvm_key pair in vm_name / .ssh
291 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" |',
293 # set permissions for keys
294 #TODO: test without chmod
295 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
297 # move out private key
298 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
300 # rename public key to authorized_keys
301 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
303 # generate iso image with .ssh/authorized keys
304 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
307 # attaches generated ssh public cert to guest vm
308 def attachCertificateISO(self, vm_name):
309 machineFolder = self.getDefaultMachineFolder()
310 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
311 result = self.execute(cmd)
314 handleDeviceChangeLock = threading.Lock()
316 # handles device change events
317 def handleDeviceChange(self):
318 if VMManager.handleDeviceChangeLock.acquire(True):
321 attached_devices = self.getAttachedRSDs()
322 connected_devices = self.listRSDS()
323 for vm_name in attached_devices.keys():
324 if attached_devices[vm_name] not in connected_devices.values():
325 self.unmapNetworkDrive('h:')
327 self.removeVM(vm_name)
328 #create new vm for attached device if any
329 attached_devices = self.getAttachedRSDs()
330 for connected_device in connected_devices.values():
331 if (attached_devices and False) or (connected_device not in attached_devices.values()):
332 new_sdvm = self.generateSDVMName()
333 self.createVM(new_sdvm)
334 self.attachRSD(new_sdvm, connected_device)
337 self.startVM(new_sdvm)
338 # wait for machine to come up
339 while new_ip == None:
341 new_ip = self.getHostOnlyIP(new_sdvm)
342 while new_ip not in self.startNotifications:
345 self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
346 #TODO: cleanup notifications somwhere else (eg. machine shutdown)
347 self.startNotifications.remove(new_ip)
348 VMManager.handleDeviceChangeLock.release()
351 def handleBrowsingRequest(self):
352 if VMManager.handleDeviceChangeLock.acquire(True):
354 new_sdvm = self.generateSDVMName()
355 self.createVM(new_sdvm)
356 self.genCertificateISO(new_sdvm)
357 self.attachCertificateISO(new_sdvm)
358 self.startVM(new_sdvm)
359 # wait for machine to come up
360 while new_ip == None:
362 new_ip = self.getHostOnlyIP(new_sdvm)
363 while new_ip not in self.startNotifications:
366 self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
367 #TODO: cleanup notifications somwhere else (eg. machine shutdown)
368 self.startNotifications.remove(new_ip)
369 VMManager.handleDeviceChangeLock.release()
372 # executes command over ssh on guest vm
373 def sshGuestExecute(self, vm_name, prog, user_name='osecuser'):
375 address = self.getHostOnlyIP(vm_name)
376 machineFolder = self.getDefaultMachineFolder()
378 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
379 return self.execute(cmd)
381 # executes command over ssh on guest vm with X forwarding
382 def sshGuestX11Execute(self, vm_name, prog, user_name='osecuser'):
383 #TODO: verify if X server is running on user account
384 #TODO: set DISPLAY accordingly
385 address = self.getHostOnlyIP(vm_name)
386 machineFolder = self.getDefaultMachineFolder()
389 #cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
390 cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\" ' + user_name + '@' + address + ' ' + prog + ''
391 #cmd = self.cygwin_path+'mintty.exe -e /bin/bash --login -c \"DISPLAY=:0 /usr/bin/ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
393 print('trying to launch: ' + cmd)
396 print('launched: ' + cmd)
399 #Small function to check the availability of network resource.
400 def isAvailable(self, path):
401 cmd = 'IF EXIST ' + path + ' echo YES'
402 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
403 return string.find(str(result), 'YES',)
405 #Small function to check if the mention location is a directory
406 def isDirectory(self, path):
407 cmd = 'dir ' + path + ' | FIND ".."'
408 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
409 return string.find(str(result), 'DIR',)
411 def mapNetworkDrive(self, drive, networkPath, user, password):
412 self.unmapNetworkDrive('h:')
413 #Check for drive availability
414 if self.isAvailable(drive) > -1:
415 print "Drive letter is already in use: ", drive
417 #Check for network resource availability
418 while self.isAvailable(networkPath) == -1:
420 print "Path not accessible: ", networkPath, " retrying"
423 #Prepare 'NET USE' commands
424 cmd = 'NET USE ' + drive + ' ' + networkPath
426 cmd = cmd + ' ' + password + ' /User' + user
429 #Execute 'NET USE' command with authentication
430 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
431 print "Executed: ", cmd
432 if string.find(str(result), 'successfully',) == -1:
435 #Mapped with first try
438 def unmapNetworkDrive(self, drive):
439 #Check if the drive is in use
440 if self.isAvailable(drive) == -1:
443 #Prepare 'NET USE' command
444 cmd = 'net use ' + drive + ' /DELETE'
445 result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
446 if string.find(str(result), 'successfully',) == -1:
450 if __name__ == '__main__':
451 man = VMManager.getInstance()
452 #man.removeVM('SecurityDVM0')
453 #man.netUse('192.168.56.134', 'USB\\')
454 #ip = '192.168.56.139'
455 #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
456 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
457 #man.handleDeviceChange()
458 #print man.listSDVM()
459 #man.configureHostNetworking()
460 #new_vm = man.generateSDVMName()
461 #man.createVM(new_vm)
462 #man.genCertificateISO(new_vm)
463 #man.attachCertificateISO(new_vm)
465 #man.attachCertificateISO(vm_name)
466 #man.sshGuestExecute(vm_name, "ls")
467 man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
469 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""