2 Created on Nov 19, 2013
8 from subprocess import Popen, PIPE, call
12 from cygwin import Cygwin
21 def __init__(self, vendorid, productid, revision):
22 self.vendorid = vendorid.lower()
23 self.productid = productid.lower()
24 self.revision = revision.lower()
27 def __eq__(self, other):
28 return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
31 return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
34 return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
37 class VMManager(object):
38 vmRootName = "SecurityDVM"
39 systemProperties = None
40 cygwin_path = 'c:\\cygwin64\\bin\\'
43 self.systemProperties = self.getSystemProperties()
44 self.cygwin_path = Cygwin.root()
47 def execute(self, cmd):
49 print('trying to launch: ' + cmd)
50 process = Popen(cmd, stdout=PIPE, stderr=PIPE)
52 print('launched: ' + cmd)
53 result = process.wait()
54 res_stdout = process.stdout.read();
55 res_stderr = process.stderr.read();
61 return result, res_stdout, res_stderr
63 # return hosty system properties
64 def getSystemProperties(self):
65 cmd = 'VBoxManage list systemproperties'
66 result = self.execute(cmd)
69 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
72 # return the folder containing the guest VMs
73 def getDefaultMachineFolder(self):
74 return self.systemProperties["Default machine folder"]
76 #list the hostonly IFs exposed by the VBox host
77 def getHostOnlyIFs(self):
78 cmd = 'VBoxManage list hostonlyifs'
79 result = self.execute(cmd)[1]
82 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
86 cmd = 'VBoxManage list usbhost'
87 results = self.execute(cmd)[1]
88 results = results.split('Host USB Devices:')[1].strip()
90 items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
94 for line in item.splitlines():
96 k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
99 if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
100 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
101 re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
102 re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
103 rsds[props['UUID']] = usb_filter;
108 # list all existing VMs registered with VBox
110 cmd = 'VBoxManage list vms'
111 result = self.execute(cmd)[1]
112 vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
115 # list existing SDVMs
120 if vm.startswith(self.vmRootName) and vm != self.vmRootName:
124 # generate valid (not already existing SDVM name). necessary for creating a new VM
125 def generateSDVMName(self):
127 for i in range(0,999):
128 if(not self.vmRootName+str(i) in vms):
129 return self.vmRootName+str(i)
132 # return the RSDs attached to all existing SDVMs
133 def getAttachedRSDs(self):
134 vms = self.listSDVM()
135 attached_devices = dict()
137 rsd_filter = self.getUSBFilter(vm)
138 if rsd_filter != None:
139 attached_devices[vm] = rsd_filter
140 return attached_devices
142 # configures hostonly networking and DHCP server. requires admin rights
143 def configureHostNetworking(self):
144 #cmd = 'vboxmanage list hostonlyifs'
146 #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
148 #cmd = 'vboxmanage hostonlyif create'
150 cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
152 #cmd = 'vboxmanage dhcpserver add'
154 cmd = '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'
157 #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
158 def createVM(self, vm_name):
159 hostonly_if = self.getHostOnlyIFs()
160 machineFolder = self.getDefaultMachineFolder()
161 cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
163 cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
165 cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
167 cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
172 #remove VM from the system. should be used on VMs returned by listSDVMs
173 def removeVM(self, vm_name):
174 print('removing ' + vm_name)
175 cmd = 'VBoxManage unregistervm', vm_name, '--delete'
176 print self.execute(cmd)
177 machineFolder = self.getDefaultMachineFolder()
178 cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
179 print self.execute(cmd)
182 def startVM(self, vm_name):
183 print('starting ' + vm_name)
184 cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
185 print self.execute(cmd)
188 def stopVM(self, vm_name):
189 print('stopping ' + vm_name)
190 cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
191 print self.execute(cmd)
193 # return the hostOnly IP for a running guest
194 def getHostOnlyIP(self, vm_name):
195 print('gettting hostOnly IP address ' + vm_name)
196 cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
197 result = self.execute(cmd)
201 return result[result.index(':')+1:].strip()
203 # attach removable storage device to VM by provision of filter
204 def attachRSD(self, vm_name, rsd_filter):
205 cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
206 print self.execute(cmd)
209 # return the description set for an existing VM
210 def getVMInfo(self, vm_name):
211 cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
212 results = self.execute(cmd)[1]
213 props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
216 # return the configured USB filter for an existing VM
217 def getUSBFilter(self, vm_name):
218 props = self.getVMInfo(vm_name)
219 keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
220 keyset = set(props.keys())
222 if keyset.issuperset(keys):
223 usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
226 #generates ISO containing authorized_keys for use with guest VM
227 def genCertificateISO(self, vm_name):
228 machineFolder = self.getDefaultMachineFolder()
229 # create .ssh folder in vm_name
230 cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
231 result = self.execute(cmd)
232 # generate dvm_key pair in vm_name / .ssh
233 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" |',
234 result = self.execute(cmd)
235 # set permissions for keys
236 #TODO: test without chmod
237 cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
238 result = self.execute(cmd)
239 # move out private key
240 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
241 result = self.execute(cmd)
242 # rename public key to authorized_keys
243 cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
244 result = self.execute(cmd)
245 # generate iso image with .ssh/authorized keys
246 cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
247 result = self.execute(cmd)
249 # attaches generated ssh public cert to guest vm
250 def attachCertificateISO(self, vm_name):
251 machineFolder = self.getDefaultMachineFolder()
252 cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
253 result = self.execute(cmd)
256 # handles device change events
257 def handleDeviceChange(self):
258 attached_devices = self.getAttachedRSDs()
259 connected_devices = self.listRSDS()
260 for vm_name in attached_devices.keys():
261 if connected_devices and attached_devices[vm_name] not in connected_devices.values():
262 # self.netUse(vm_name)
264 self.removeVM(vm_name)
266 attached_devices = self.getAttachedRSDs()
267 for connected_device in connected_devices.values():
268 if attached_devices or connected_device not in attached_devices.values():
269 new_sdvm = self.generateSDVMName()
270 self.createVM(new_sdvm)
271 self.attachRSD(new_sdvm, connected_device)
272 self.startVM(new_sdvm)
273 self.netUse(new_sdvm)
275 def handleBrowsingRequest(self):
276 new_sdvm = self.generateSDVMName()
277 self.createVM(new_sdvm)
278 self.genCertificateISO(new_sdvm)
279 self.attachCertificateISO(new_sdvm)
281 # executes command over ssh on guest vm
282 def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
284 address = self.getHostOnlyIP(vm_name)
285 machineFolder = self.getDefaultMachineFolder()
287 cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
288 return self.execute(cmd)
290 # executes command over ssh on guest vm with X forwarding
291 def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
292 #TODO: verify if X server is running on user account
293 #TODO: set DISPLAY accordingly
294 address = self.getHostOnlyIP(vm_name)
295 machineFolder = self.getDefaultMachineFolder()
297 cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
298 return self.execute(cmd)
300 # executes NET USE and connects to samba share on guestos
301 def netUse(self, vm_name):
302 ip = self.getHostOnlyIP(vm_name)
303 cmd = 'net use H: \\' + ip + '\USB'
304 return self.execute(cmd)
307 if __name__ == '__main__':
309 man.cygwin_path = 'c:\\cygwin64\\bin\\'
310 #man.handleDeviceChange()
311 #print man.listSDVM()
312 #man.configureHostNetworking()
313 new_vm = man.generateSDVMName()
315 man.genCertificateISO(new_vm)
316 man.attachCertificateISO(new_vm)
318 #man.attachCertificateISO(vm_name)
319 #man.sshGuestExecute(vm_name, "ls")
320 #man.sshGuestX11Execute(vm_name, "iceweasel")
321 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""