2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
12 from cygwin import Cygwin
22 def __init__(self, vendorid, productid, revision):
23 self.vendorid = vendorid.lower()
24 self.productid = productid.lower()
25 self.revision = revision.lower()
28 def __eq__(self, other):
29 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
32 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
35 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
38 class VMManager(object):
39 """Manage Virtual Machines"""
41 vmRootName = "SecurityDVM"
44 self.vBoxPath = self.getVBoxManagePath()
45 self.vBoxManage = os.path.join(self.vBoxPath, 'VBoxManage.exe')
46 self.systemProperties = self.getSystemProperties()
47 self.cygwin_path = Cygwin.root()
50 def execute(self, cmd):
51 """execute a command"""
53 # we can handle strings and lists as input
59 sys.stderr.write('trying to launch: ' + c + '\n')
60 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
62 sys.stderr.write('launched: ' + c + '\n')
64 result = process.wait()
65 res_stdout = process.stdout.read();
66 res_stderr = process.stderr.read();
72 return result, res_stdout, res_stderr
75 def getVBoxManagePath(self):
76 """get the path to the VirtualBox installation on this system"""
79 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
80 p = _winreg.QueryValueEx(k, 'InstallDir')[0]
86 # return host system properties
87 def getSystemProperties(self):
88 cmd = [self.vBoxManage, 'list', 'systemproperties']
89 result = self.execute(cmd)
92 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
95 # return the folder containing the guest VMs
96 def getDefaultMachineFolder(self):
97 return self.systemProperties["Default machine folder"]
99 #list the hostonly IFs exposed by the VBox host
100 def getHostOnlyIFs(self):
101 cmd = [self.vBoxManage, 'list', 'hostonlyifs']
102 result = self.execute(cmd)[1]
105 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
109 cmd = [self.vBoxManage, 'list', 'usbhost']
110 results = self.execute(cmd)
111 results = results.split('Host USB Devices:')[1].strip()
113 items = list( "UUID:" + result for result in results.split('UUID:') if result != '')
117 for line in item.splitlines():
119 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
122 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
123 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
124 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
125 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
126 rsds[props['UUID']] = usb_filter;
131 # list all existing VMs registered with VBox
133 cmd = [self.vBoxManage, 'list', 'vms']
134 result = self.execute(cmd)[1]
135 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
138 # list existing SDVMs
143 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
147 # generate valid (not already existing SDVM name). necessary for creating a new VM
148 def generateSDVMName(self):
150 for i in range(0,999):
151 if(not self.vmRootName+str(i) in vms):
152 return self.vmRootName+str(i)
155 # return the RSDs attached to all existing SDVMs
156 def getAttachedRSDs(self):
157 vms = self.listSDVM()
158 attached_devices = dict()
160 rsd_filter = self.getUSBFilter(vm)
162 attached_devices[vm] = rsd_filter
163 return attached_devices
165 # configures hostonly networking and DHCP server. requires admin rights
166 def configureHostNetworking(self):
167 #cmd = 'vboxmanage list hostonlyifs'
169 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
171 #cmd = 'vboxmanage hostonlyif create'
173 cmd = self.vBoxManage + ' hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
175 #cmd = 'vboxmanage dhcpserver add'
177 cmd = self.vBoxManage + ' dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0 --lowerip 192.168.56.100 --upperip 192.168.56.255'
180 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
181 def createVM(self, vm_name):
182 hostonly_if = self.getHostOnlyIFs()
183 machineFolder = self.getDefaultMachineFolder()
184 cmd = self.vBoxManage + ' createvm --name ' + vm_name + ' --ostype Debian --register'
186 cmd = self.vBoxManage + ' modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
188 cmd = self.vBoxManage + ' storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
190 cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --mtype normal --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
194 #remove VM from the system. should be used on VMs returned by listSDVMs
195 def removeVM(self, vm_name):
196 print('removing ' + vm_name)
197 cmd = self.vBoxManage + ' unregistervm', vm_name, '--delete'
198 print self.execute(cmd)
199 machineFolder = self.getDefaultMachineFolder()
200 cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
201 print self.execute(cmd)
204 def startVM(self, vm_name):
205 print('starting ' + vm_name)
206 cmd = self.vBoxManage + ' startvm ' + vm_name + ' --type headless'
207 print self.execute(cmd)
210 def stopVM(self, vm_name):
211 print('stopping ' + vm_name)
212 cmd = self.vBoxManage + ' controlvm ' + vm_name + ' poweroff'
213 print self.execute(cmd)
215 # return the hostOnly IP for a running guest
216 def getHostOnlyIP(self, vm_name):
217 print('gettting hostOnly IP address ' + vm_name)
218 cmd = self.vBoxManage + ' guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
219 result = self.execute(cmd)
223 return result[result.index(':')+1:].strip()
225 # attach removable storage device to VM by provision of filter
226 def attachRSD(self, vm_name, rsd_filter):
227 cmd = self.vBoxManage + ' usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
228 print self.execute(cmd)
231 # return the description set for an existing VM
232 def getVMInfo(self, vm_name):
233 cmd = self.vBoxManage + ' showvminfo ' + vm_name + ' --machinereadable'
234 r, o, e = self.execute(cmd)
235 props = dict((k.strip(),v.strip().strip('"')) for k, v in (line.split('=', 1) for line in o.splitlines()))
238 # return the configured USB filter for an existing VM
239 def getUSBFilter(self, vm_name):
240 props = self.getVMInfo(vm_name)
241 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
242 keyset = set(props.keys())
244 if keyset.issuperset(keys):
245 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
248 #generates ISO containing authorized_keys for use with guest VM
249 def genCertificateISO(self, vm_name):
250 machineFolder = self.getDefaultMachineFolder()
251 # create .ssh folder in vm_name
252 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
253 result = self.execute(cmd)
254 # generate dvm_key pair in vm_name / .ssh
255 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" |',
256 result = self.execute(cmd)
257 # set permissions for keys
258 #TODO: test without chmod
259 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
260 result = self.execute(cmd)
261 # move out private key
262 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
263 result = self.execute(cmd)
264 # rename public key to authorized_keys
265 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
266 result = self.execute(cmd)
267 # generate iso image with .ssh/authorized keys
268 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
269 result = self.execute(cmd)
271 # attaches generated ssh public cert to guest vm
272 def attachCertificateISO(self, vm_name):
273 machineFolder = self.getDefaultMachineFolder()
274 cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
275 result = self.execute(cmd)
278 # handles device change events
279 def handleDeviceChange(self):
280 attached_devices = self.getAttachedRSDs()
281 connected_devices = self.listRSDS()
282 for vm_name in attached_devices.keys():
283 if attached_devices[vm_name] not in connected_devices.values():
285 self.removeVM(vm_name)
287 attached_devices = self.getAttachedRSDs()
288 for connected_device in connected_devices.values():
289 if connected_device not in attached_devices.values():
290 new_sdvm = self.generateSDVMName()
291 self.createVM(new_sdvm)
292 self.genCertificateISO(new_sdvm)
293 self.attachCertificateISO(new_sdvm)
294 self.attachRSD(new_sdvm, connected_device)
295 self.startVM(new_sdvm)
297 # executes command over ssh on guest vm
298 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
300 address = self.getHostOnlyIP(vm_name)
301 machineFolder = self.getDefaultMachineFolder()
303 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
304 return self.execute(cmd)
306 # executes command over ssh on guest vm with X forwarding
307 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
308 #TODO: verify if X server is running on user account
309 #TODO: set DISPLAY accordingly
310 address = self.getHostOnlyIP(vm_name)
311 machineFolder = self.getDefaultMachineFolder()
313 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
314 return self.execute(cmd)
316 # executes NET USE and connects to samba share on guestos
317 def netUse(self, vm_name):
318 ip = self.getHostOnlyIP(vm_name)
319 cmd = 'net use H: \\' + ip + '\RSD_Device'
320 return self.execute(cmd)
323 if __name__ == '__main__':
325 man.cygwin_path = 'c:\\cygwin64\\bin\\'
326 #man.handleDeviceChange()
327 #print man.listSDVM()
328 #man.configureHostNetworking()
329 new_vm = man.generateSDVMName()
331 man.genCertificateISO(new_vm)
332 man.attachCertificateISO(new_vm)
334 #man.attachCertificateISO(vm_name)
335 #man.sshGuestExecute(vm_name, "ls")
336 #man.sshGuestX11Execute(vm_name, "iceweasel")
337 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""