added /sdvm_started notification edpoint and isSDVMStarted vmmanager method.
changed VMManager to sinleton. retrieve with 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'
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 self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
54 self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
55 self.systemProperties = self.getSystemProperties()
60 if VMManager._instance == None:
61 VMManager._instance = VMManager()
62 return VMManager._instance
64 def putStartNotification(self, ip):
65 self.startNotifications.append(ip)
67 def isSDVMStarted(self, ip):
68 return self.startNotifications.contains(ip)
70 def execute(self, cmd):
72 print('trying to launch: ' + cmd)
73 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
75 print('launched: ' + cmd)
76 result = process.wait()
77 res_stdout = process.stdout.read();
78 res_stderr = process.stderr.read();
84 return result, res_stdout, res_stderr
86 def getVBoxManagePath(self):
87 """get the path to the VirtualBox installation on this system"""
90 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
91 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
97 # return hosty system properties
98 def getSystemProperties(self):
99 cmd = self.vboxManage + ' list systemproperties'
100 result = self.execute(cmd)
103 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
106 # return the folder containing the guest VMs
107 def getDefaultMachineFolder(self):
108 return self.systemProperties["Default machine folder"]
110 #list the hostonly IFs exposed by the VBox host
111 def getHostOnlyIFs(self):
112 cmd = 'VBoxManage list hostonlyifs'
113 result = self.execute(cmd)[1]
116 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
120 cmd = 'VBoxManage list usbhost'
121 results = self.execute(cmd)[1]
122 results = results.split('Host USB Devices:')[1].strip()
124 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
128 for line in item.splitlines():
130 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
133 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
134 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
135 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
136 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
137 rsds[props['UUID']] = usb_filter;
142 # list all existing VMs registered with VBox
144 cmd = 'VBoxManage list vms'
145 result = self.execute(cmd)[1]
146 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
149 # list existing SDVMs
154 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
158 # generate valid (not already existing SDVM name). necessary for creating a new VM
159 def generateSDVMName(self):
161 for i in range(0,999):
162 if(not self.vmRootName+str(i) in vms):
163 return self.vmRootName+str(i)
166 # return the RSDs attached to all existing SDVMs
167 def getAttachedRSDs(self):
168 vms = self.listSDVM()
169 attached_devices = dict()
171 rsd_filter = self.getUSBFilter(vm)
172 if rsd_filter != None:
173 attached_devices[vm] = rsd_filter
174 return attached_devices
176 # configures hostonly networking and DHCP server. requires admin rights
177 def configureHostNetworking(self):
178 #cmd = 'vboxmanage list hostonlyifs'
180 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
182 #cmd = 'vboxmanage hostonlyif create'
184 cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
186 #cmd = 'vboxmanage dhcpserver add'
188 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'
191 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
192 def createVM(self, vm_name):
193 hostonly_if = self.getHostOnlyIFs()
194 machineFolder = self.getDefaultMachineFolder()
195 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
197 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
199 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
201 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
206 #remove VM from the system. should be used on VMs returned by listSDVMs
207 def removeVM(self, vm_name):
208 print('removing ' + vm_name)
209 cmd = 'VBoxManage unregistervm', vm_name, '--delete'
210 print self.execute(cmd)
211 machineFolder = self.getDefaultMachineFolder()
212 cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
213 print self.execute(cmd)
216 def startVM(self, vm_name):
217 print('starting ' + vm_name)
218 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
219 print self.execute(cmd)
222 def stopVM(self, vm_name):
223 print('stopping ' + vm_name)
224 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
225 print self.execute(cmd)
227 # return the hostOnly IP for a running guest
228 def getHostOnlyIP(self, vm_name):
229 print('gettting hostOnly IP address ' + vm_name)
230 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
231 result = self.execute(cmd)
235 return result[result.index(':')+1:].strip()
237 # attach removable storage device to VM by provision of filter
238 def attachRSD(self, vm_name, rsd_filter):
239 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
240 print self.execute(cmd)
243 # return the description set for an existing VM
244 def getVMInfo(self, vm_name):
245 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
246 results = self.execute(cmd)[1]
247 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
250 # return the configured USB filter for an existing VM
251 def getUSBFilter(self, vm_name):
252 props = self.getVMInfo(vm_name)
253 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
254 keyset = set(props.keys())
256 if keyset.issuperset(keys):
257 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
260 #generates ISO containing authorized_keys for use with guest VM
261 def genCertificateISO(self, vm_name):
262 machineFolder = self.getDefaultMachineFolder()
263 # create .ssh folder in vm_name
264 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
265 result = self.execute(cmd)
266 # generate dvm_key pair in vm_name / .ssh
267 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" |',
268 result = self.execute(cmd)
269 # set permissions for keys
270 #TODO: test without chmod
271 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
272 result = self.execute(cmd)
273 # move out private key
274 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
275 result = self.execute(cmd)
276 # rename public key to authorized_keys
277 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
278 result = self.execute(cmd)
279 # generate iso image with .ssh/authorized keys
280 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
281 result = self.execute(cmd)
283 # attaches generated ssh public cert to guest vm
284 def attachCertificateISO(self, vm_name):
285 machineFolder = self.getDefaultMachineFolder()
286 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
287 result = self.execute(cmd)
290 # handles device change events
291 def handleDeviceChange(self):
292 attached_devices = self.getAttachedRSDs()
293 connected_devices = self.listRSDS()
294 for vm_name in attached_devices.keys():
295 if connected_devices and attached_devices[vm_name] not in connected_devices.values():
296 # self.netUse(vm_name)
298 self.removeVM(vm_name)
300 attached_devices = self.getAttachedRSDs()
301 for connected_device in connected_devices.values():
302 if attached_devices or connected_device not in attached_devices.values():
303 new_sdvm = self.generateSDVMName()
304 self.createVM(new_sdvm)
305 self.attachRSD(new_sdvm, connected_device)
306 self.startVM(new_sdvm)
307 self.netUse(new_sdvm)
309 def handleBrowsingRequest(self):
310 new_sdvm = self.generateSDVMName()
311 self.createVM(new_sdvm)
312 self.genCertificateISO(new_sdvm)
313 self.attachCertificateISO(new_sdvm)
316 # executes command over ssh on guest vm
317 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
319 address = self.getHostOnlyIP(vm_name)
320 machineFolder = self.getDefaultMachineFolder()
322 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
323 return self.execute(cmd)
325 # executes command over ssh on guest vm with X forwarding
326 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
327 #TODO: verify if X server is running on user account
328 #TODO: set DISPLAY accordingly
329 address = self.getHostOnlyIP(vm_name)
330 machineFolder = self.getDefaultMachineFolder()
332 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
333 return self.execute(cmd)
335 # executes NET USE and connects to samba share on guestos
336 def netUse(self, vm_name):
337 ip = self.getHostOnlyIP(vm_name)
338 cmd = 'net use H: \\' + ip + '\USB'
339 return self.execute(cmd)
342 #if __name__ == '__main__':
344 #man.cygwin_path = 'c:\\cygwin64\\bin\\'
345 #man.handleDeviceChange()
346 #print man.listSDVM()
347 #man.configureHostNetworking()
348 #new_vm = man.generateSDVMName()
349 #man.createVM(new_vm)
350 #man.genCertificateISO(new_vm)
351 #man.attachCertificateISO(new_vm)
353 #man.attachCertificateISO(vm_name)
354 #man.sshGuestExecute(vm_name, "ls")
355 #man.sshGuestX11Execute(vm_name, "iceweasel")
356 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""