2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
13 from cygwin import Cygwin
24 def __init__(self, vendorid, productid, revision):
25 self.vendorid = vendorid.lower()
26 self.productid = productid.lower()
27 self.revision = revision.lower()
30 def __eq__(self, other):
31 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
34 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
37 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
40 class VMManager(object):
41 vmRootName = "SecurityDVM"
42 systemProperties = None
43 cygwin_path = 'c:\\cygwin64\\bin\\'
44 vboxManage = 'VBoxManage'
45 startNotifications = list()
48 #def __new__(cls, *args, **kwargs):
49 # if not cls._instance:
50 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
51 # return cls._instance
54 #def __new__(cls, *args, **kwargs):
55 # if not cls._instance:
56 # cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
57 # return cls._instance
60 self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
61 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
62 self.systemProperties = self.getSystemProperties()
67 if VMManager._instance == None:
68 VMManager._instance = VMManager()
69 return VMManager._instance
71 def putStartNotification(self, ip):
72 self.startNotifications.append(ip)
74 def isSDVMStarted(self, ip):
75 return self.startNotifications.contains(ip)
77 def execute(self, cmd):
79 print('trying to launch: ' + cmd)
80 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
82 print('launched: ' + cmd)
83 result = process.wait()
84 res_stdout = process.stdout.read();
85 res_stderr = process.stderr.read();
91 return result, res_stdout, res_stderr
93 def getVBoxManagePath(self):
94 """get the path to the VirtualBox installation on this system"""
97 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
98 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
104 # return hosty system properties
105 def getSystemProperties(self):
106 cmd = self.vboxManage + ' list systemproperties'
107 result = self.execute(cmd)
110 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
113 # return the folder containing the guest VMs
114 def getDefaultMachineFolder(self):
115 return self.systemProperties["Default machine folder"]
117 #list the hostonly IFs exposed by the VBox host
118 def getHostOnlyIFs(self):
119 cmd = 'VBoxManage list hostonlyifs'
120 result = self.execute(cmd)[1]
123 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
127 cmd = 'VBoxManage list usbhost'
128 results = self.execute(cmd)[1]
129 results = results.split('Host USB Devices:')[1].strip()
131 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
135 for line in item.splitlines():
137 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
140 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
141 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
142 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
143 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
144 rsds[props['UUID']] = usb_filter;
149 # list all existing VMs registered with VBox
151 cmd = 'VBoxManage list vms'
152 result = self.execute(cmd)[1]
153 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
156 # list existing SDVMs
161 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
165 # generate valid (not already existing SDVM name). necessary for creating a new VM
166 def generateSDVMName(self):
168 for i in range(0,999):
169 if(not self.vmRootName+str(i) in vms):
170 return self.vmRootName+str(i)
173 # return the RSDs attached to all existing SDVMs
174 def getAttachedRSDs(self):
175 vms = self.listSDVM()
176 attached_devices = dict()
178 rsd_filter = self.getUSBFilter(vm)
179 if rsd_filter != None:
180 attached_devices[vm] = rsd_filter
181 return attached_devices
183 # configures hostonly networking and DHCP server. requires admin rights
184 def configureHostNetworking(self):
185 #cmd = 'vboxmanage list hostonlyifs'
187 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
189 #cmd = 'vboxmanage hostonlyif create'
191 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
193 #cmd = 'vboxmanage dhcpserver add'
195 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'
198 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
199 def createVM(self, vm_name):
200 hostonly_if = self.getHostOnlyIFs()
201 machineFolder = self.getDefaultMachineFolder()
202 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
204 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
206 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
208 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
213 #remove VM from the system. should be used on VMs returned by listSDVMs
214 def removeVM(self, vm_name):
215 print('removing ' + vm_name)
216 cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
217 print self.execute(cmd)
218 machineFolder = self.getDefaultMachineFolder()
219 cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
220 print self.execute(cmd)
223 def startVM(self, vm_name):
224 print('starting ' + vm_name)
225 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
226 print self.execute(cmd)
229 def stopVM(self, vm_name):
230 print('stopping ' + vm_name)
231 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
232 print self.execute(cmd)
234 # return the hostOnly IP for a running guest
235 def getHostOnlyIP(self, vm_name):
236 print('gettting hostOnly IP address ' + vm_name)
237 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
238 result = self.execute(cmd)
242 return result[result.index(':')+1:].strip()
244 # attach removable storage device to VM by provision of filter
245 def attachRSD(self, vm_name, rsd_filter):
246 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
247 print self.execute(cmd)
250 # return the description set for an existing VM
251 def getVMInfo(self, vm_name):
252 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
253 results = self.execute(cmd)[1]
254 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
257 # return the configured USB filter for an existing VM
258 def getUSBFilter(self, vm_name):
259 props = self.getVMInfo(vm_name)
260 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
261 keyset = set(props.keys())
263 if keyset.issuperset(keys):
264 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
267 #generates ISO containing authorized_keys for use with guest VM
268 def genCertificateISO(self, vm_name):
269 machineFolder = self.getDefaultMachineFolder()
270 # create .ssh folder in vm_name
271 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
272 result = self.execute(cmd)
273 # generate dvm_key pair in vm_name / .ssh
274 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" |',
275 result = self.execute(cmd)
276 # set permissions for keys
277 #TODO: test without chmod
278 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
279 result = self.execute(cmd)
280 # move out private key
281 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
282 result = self.execute(cmd)
283 # rename public key to authorized_keys
284 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
285 result = self.execute(cmd)
286 # generate iso image with .ssh/authorized keys
287 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
288 result = self.execute(cmd)
290 # attaches generated ssh public cert to guest vm
291 def attachCertificateISO(self, vm_name):
292 machineFolder = self.getDefaultMachineFolder()
293 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
294 result = self.execute(cmd)
297 handleDeviceChangeLock = threading.Lock()
299 # handles device change events
300 def handleDeviceChange(self):
301 if VMManager.handleDeviceChangeLock.acquire(True):
303 attached_devices = self.getAttachedRSDs()
304 connected_devices = self.listRSDS()
305 for vm_name in attached_devices.keys():
306 if attached_devices[vm_name] not in connected_devices.values():
307 # self.netUnUse(vm_name)
309 self.removeVM(vm_name)
310 #create new vm for attached device if any
311 attached_devices = self.getAttachedRSDs()
312 for connected_device in connected_devices.values():
313 if (attached_devices and False) or (connected_device not in attached_devices.values()):
314 new_sdvm = self.generateSDVMName()
315 self.createVM(new_sdvm)
316 self.attachRSD(new_sdvm, connected_device)
317 self.startVM(new_sdvm)
319 #self.netUse(new_sdvm)
320 VMManager.handleDeviceChangeLock.release()
322 def handleBrowsingRequest(self):
323 new_sdvm = self.generateSDVMName()
324 self.createVM(new_sdvm)
325 self.genCertificateISO(new_sdvm)
326 self.attachCertificateISO(new_sdvm)
329 # executes command over ssh on guest vm
330 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
332 address = self.getHostOnlyIP(vm_name)
333 machineFolder = self.getDefaultMachineFolder()
335 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
336 return self.execute(cmd)
338 # executes command over ssh on guest vm with X forwarding
339 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
340 #TODO: verify if X server is running on user account
341 #TODO: set DISPLAY accordingly
342 address = self.getHostOnlyIP(vm_name)
343 machineFolder = self.getDefaultMachineFolder()
345 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
346 return self.execute(cmd)
348 # executes NET USE and connects to samba share on guestos
349 def netUse(self, vm_name):
350 ip = self.getHostOnlyIP(vm_name)
351 cmd = 'net use H: \\' + ip + '\USB'
352 return self.execute(cmd)
355 #if __name__ == '__main__':
357 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
358 #man.handleDeviceChange()
359 #print man.listSDVM()
360 #man.configureHostNetworking()
361 #new_vm = man.generateSDVMName()
362 #man.createVM(new_vm)
363 #man.genCertificateISO(new_vm)
364 #man.attachCertificateISO(new_vm)
366 #man.attachCertificateISO(vm_name)
367 #man.sshGuestExecute(vm_name, "ls")
368 #man.sshGuestX11Execute(vm_name, "iceweasel")
369 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""