# HG changeset patch # User om # Date 1386328518 -3600 # Node ID 2e4cb1ebcbedc1dbfe539f80cc2e0e839758c21a # Parent c187aaceca3230e334ac9f713243ea134d580044 moved server python stuff into bin folder diff -r c187aaceca32 -r 2e4cb1ebcbed OpenSecurity/bin/opensecurityd.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/OpenSecurity/bin/opensecurityd.py Fri Dec 06 12:15:18 2013 +0100 @@ -0,0 +1,192 @@ +#!/bin/env python +# -*- coding: utf-8 -*- + +# ------------------------------------------------------------ +# opensecurityd +# +# the opensecurityd as RESTful server +# +# Autor: Oliver Maurhart, +# +# Copyright (C) 2013 AIT Austrian Institute of Technology +# AIT Austrian Institute of Technology GmbH +# Donau-City-Strasse 1 | 1220 Vienna | Austria +# http://www.ait.ac.at +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation version 2. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301, USA. +# ------------------------------------------------------------ + + +# ------------------------------------------------------------ +# imports + +import os +import os.path +import subprocess +import sys +import web +from vmmanager.vmmanager import VMManager + +# local +from environment import Environment + + +# ------------------------------------------------------------ +# const + +__version__ = "0.1" + + +"""All the URLs we know mapping to class handler""" +opensecurity_urls = ( + '/device_change', 'os_device_change', + '/application', 'os_application', + '/device', 'os_device', + '/device/credentials', 'os_device_credentials', + '/device/password', 'os_device_password', + '/', 'os_root' +) + + +# ------------------------------------------------------------ +# code + +gvm_mgr = VMManager() + + +class os_application: + + """OpenSecurity '/application' handler. + + This is called on GET /application?vm=VM-ID&app=APP-ID + This tries to access the vm identified with the label VM-ID + and launched the application identified APP-ID + """ + + def GET(self): + + # pick the arguments + args = web.input() + + # we _need_ a vm + if not "vm" in args: + raise web.badrequest() + + # we _need_ a app + if not "app" in args: + raise web.badrequest() + + ## TODO: HARD CODED STUFF HERE! THIS SHOULD BE FLEXIBLE! + ssh_private_key = os.path.join(Environment("opensecurity").data_path, 'share', '192.168.56.15.ppk') + putty_session = '192.168.56.15' + process_command = ['plink.exe', '-i', ssh_private_key, putty_session, args.app] + si = subprocess.STARTUPINFO() + si.dwFlags = subprocess.STARTF_USESHOWWINDOW + si.wShowWindow = subprocess.SW_HIDE + print('tyring to launch: ' + ' '.join(process_command)) + process = subprocess.Popen(process_command, shell = True) + return 'launched: ' + ' '.join(process_command) + +class os_device: + + """OpenSecurity '/device' handler""" + + def GET(self): + return "os_device" + +class os_device_change: + + """OpenSecurity '/device_change' handler""" + + def GET(self): + print 'received device_change' + gvm_mgr.cygwin_path = 'c:\\cygwin64\\bin\\' + gvm_mgr.handleDeviceChange() + + #gvm_mgr.configureHostNetworking() + return "os_device_change" + + +class os_device_credentials: + + """OpenSecurity '/device/credentials' handler. + + This is called on GET /device/credentials?id=DEVICE-ID. + Ideally this should pop up a user dialog to insert his + credentials based the DEVICE-ID + """ + + def GET(self): + + # pick the arguments + args = web.input() + + # we _need_ a device id + if not "id" in args: + raise web.badrequest() + + # invoke the user dialog as a subprocess + dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py') + process_command = [sys.executable, dlg_credentials_image, 'credentials', 'Please provide credentials for accessing \ndevice: "{0}".'.format(args.id)] + process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE) + result = process.communicate()[0] + if process.returncode != 0: + return 'Credentials request has been aborted.' + + return result + + +class os_device_password: + + """OpenSecurity '/device/password' handler. + + This is called on GET /device/password?id=DEVICE-ID. + Ideally this should pop up a user dialog to insert his + password based the DEVICE-ID + """ + + def GET(self): + + # pick the arguments + args = web.input() + + # we _need_ a device id + if not "id" in args: + raise web.badrequest() + + # invoke the user dialog as a subprocess + dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py') + process_command = [sys.executable, dlg_credentials_image, 'password', 'Please provide a password for accessing \ndevice: "{0}".'.format(args.id)] + process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE) + result = process.communicate()[0] + if process.returncode != 0: + return 'Credentials request has been aborted.' + + return result + + +class os_root: + + """OpenSecurity '/' handler""" + + def GET(self): + return "OpenSecurity-Server { \"version\": \"%s\" }" % __version__ + + +# start +if __name__ == "__main__": + server = web.application(opensecurity_urls, globals()) + server.run() + diff -r c187aaceca32 -r 2e4cb1ebcbed OpenSecurity/bin/vmmanager.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/OpenSecurity/bin/vmmanager.py Fri Dec 06 12:15:18 2013 +0100 @@ -0,0 +1,325 @@ +''' +Created on Nov 19, 2013 + +@author: BarthaM +''' +import os +import os.path +from subprocess import Popen, PIPE, call +import subprocess +import sys +import re + +DEBUG = True + +class USBFilter: + vendorid = "" + productid = "" + revision = "" + + def __init__(self, vendorid, productid, revision): + self.vendorid = vendorid.lower() + self.productid = productid.lower() + self.revision = revision.lower() + return + + def __eq__(self, other): + return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision + + def __hash__(self): + return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision) + + def __repr__(self): + return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'" + + +class VMManager(object): + vmRootName = "SecurityDVM" + systemProperties = None + cygwin_path = 'c:\\cygwin64\\bin\\' + + def __init__(self): + self.systemProperties = self.getSystemProperties() + #TODO: get cygwin path externally + return + + def execute(self, cmd): + if DEBUG: + print('trying to launch: ' + cmd) + process = Popen(cmd, stdout=PIPE, stderr=PIPE) + if DEBUG: + print('launched: ' + cmd) + result = process.wait() + res_stdout = process.stdout.read(); + res_stderr = process.stderr.read(); + if DEBUG: + if res_stdout != "": + print res_stdout + if res_stderr != "": + print res_stderr + return result, res_stdout, res_stderr + + # return hosty system properties + def getSystemProperties(self): + cmd = 'VBoxManage list systemproperties' + result = self.execute(cmd) + if result[1]=='': + return None + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines())) + return props + + # return the folder containing the guest VMs + def getDefaultMachineFolder(self): + return self.systemProperties["Default machine folder"] + + #list the hostonly IFs exposed by the VBox host + def getHostOnlyIFs(self): + cmd = 'VBoxManage list hostonlyifs' + result = self.execute(cmd)[1] + if result=='': + return None + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines())) + return props + + def listRSDS(self): + cmd = 'VBoxManage list usbhost' + results = self.execute(cmd)[1] + results = results.split('Host USB Devices:')[1].strip() + + items = list( "UUID:"+result for result in results.split('UUID:') if result != '') + rsds = dict() + for item in items: + props = dict() + for line in item.splitlines(): + if line != "": + k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip() + props[k] = v; + + if 'Product' in props.keys() and props['Product'] == 'Mass Storage': + usb_filter = USBFilter( re.search(r"\((?P[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], + re.search(r"\((?P[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'], + re.search(r"\((?P[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] ) + rsds[props['UUID']] = usb_filter; + if DEBUG: + print filter + return rsds + + # list all existing VMs registered with VBox + def listVM(self): + cmd = 'VBoxManage list vms' + result = self.execute(cmd)[1] + vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines())) + return vms + + # list existing SDVMs + def listSDVM(self): + vms = self.listVM() + svdms = [] + for vm in vms: + if vm.startswith(self.vmRootName) and vm != self.vmRootName: + svdms.append(vm) + return svdms + + # generate valid (not already existing SDVM name). necessary for creating a new VM + def generateSDVMName(self): + vms = self.listVM() + for i in range(0,999): + if(not self.vmRootName+str(i) in vms): + return self.vmRootName+str(i) + return '' + + # return the RSDs attached to all existing SDVMs + def getAttachedRSDs(self): + vms = self.listSDVM() + attached_devices = dict() + for vm in vms: + rsd_filter = self.getUSBFilter(vm) + if rsd_filter != None: + attached_devices[vm] = rsd_filter + return attached_devices + + # configures hostonly networking and DHCP server. requires admin rights + def configureHostNetworking(self): + #cmd = 'vboxmanage list hostonlyifs' + #self.execute(cmd) + #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"' + #self.execute(cmd) + #cmd = 'vboxmanage hostonlyif create' + #self.execute(cmd) + cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0' + self.execute(cmd) + #cmd = 'vboxmanage dhcpserver add' + #self.execute(cmd) + 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' + self.execute(cmd) + + #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk) + def createVM(self, vm_name): + hostonly_if = self.getHostOnlyIFs() + machineFolder = self.getDefaultMachineFolder() + cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register' + self.execute(cmd) + cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' + self.execute(cmd) + cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2' + self.execute(cmd) + cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' + #--mtype immutable + self.execute(cmd) + return + + #remove VM from the system. should be used on VMs returned by listSDVMs + def removeVM(self, vm_name): + print('removing ' + vm_name) + cmd = 'VBoxManage unregistervm', vm_name, '--delete' + print self.execute(cmd) + machineFolder = self.getDefaultMachineFolder() + cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"' + print self.execute(cmd) + + # start VM + def startVM(self, vm_name): + print('starting ' + vm_name) + cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' + print self.execute(cmd) + + # stop VM + def stopVM(self, vm_name): + print('stopping ' + vm_name) + cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff' + print self.execute(cmd) + + # return the hostOnly IP for a running guest + def getHostOnlyIP(self, vm_name): + print('gettting hostOnly IP address ' + vm_name) + cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP' + result = self.execute(cmd) + if result=='': + return None + result = result[1] + return result[result.index(':')+1:].strip() + + # attach removable storage device to VM by provision of filter + def attachRSD(self, vm_name, rsd_filter): + cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision + print self.execute(cmd) + + + # return the description set for an existing VM + def getVMInfo(self, vm_name): + cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable' + results = self.execute(cmd)[1] + props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines())) + return props + + # return the configured USB filter for an existing VM + def getUSBFilter(self, vm_name): + props = self.getVMInfo(vm_name) + keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1']) + keyset = set(props.keys()) + usb_filter = None + if keyset.issuperset(keys): + usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1']) + return usb_filter + + #generates ISO containing authorized_keys for use with guest VM + def genCertificateISO(self, vm_name): + machineFolder = self.getDefaultMachineFolder() + # create .ssh folder in vm_name + cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"' + result = self.execute(cmd) + # generate dvm_key pair in vm_name / .ssh + 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" |', + result = self.execute(cmd) + # set permissions for keys + #TODO: test without chmod + cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"' + result = self.execute(cmd) + # move out private key + cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"' + result = self.execute(cmd) + # rename public key to authorized_keys + cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"' + result = self.execute(cmd) + # generate iso image with .ssh/authorized keys + cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"' + result = self.execute(cmd) + + # attaches generated ssh public cert to guest vm + def attachCertificateISO(self, vm_name): + machineFolder = self.getDefaultMachineFolder() + cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"' + result = self.execute(cmd) + return result + + # handles device change events + def handleDeviceChange(self): + attached_devices = self.getAttachedRSDs() + connected_devices = self.listRSDS() + for vm_name in attached_devices.keys(): + if connected_devices and attached_devices[vm_name] not in connected_devices.values(): + # self.netUse(vm_name) + self.stopVM(vm_name) + self.removeVM(vm_name) + + attached_devices = self.getAttachedRSDs() + for connected_device in connected_devices.values(): + if attached_devices or connected_device not in attached_devices.values(): + new_sdvm = self.generateSDVMName() + self.createVM(new_sdvm) + self.attachRSD(new_sdvm, connected_device) + self.startVM(new_sdvm) + self.netUse(new_sdvm) + + def handleBrowsingRequest(self): + new_sdvm = self.generateSDVMName() + self.createVM(new_sdvm) + self.genCertificateISO(new_sdvm) + self.attachCertificateISO(new_sdvm) + + # executes command over ssh on guest vm + def sshGuestExecute(self, vm_name, prog, user_name='opensec'): + # get vm ip + address = self.getHostOnlyIP(vm_name) + machineFolder = self.getDefaultMachineFolder() + # run command + cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"' + return self.execute(cmd) + + # executes command over ssh on guest vm with X forwarding + def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'): + #TODO: verify if X server is running on user account + #TODO: set DISPLAY accordingly + address = self.getHostOnlyIP(vm_name) + machineFolder = self.getDefaultMachineFolder() + # run command + cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"' + return self.execute(cmd) + + # executes NET USE and connects to samba share on guestos + def netUse(self, vm_name): + ip = self.getHostOnlyIP(vm_name) + cmd = 'net use H: \\' + ip + '\USB' + return self.execute(cmd) + + +if __name__ == '__main__': + man = VMManager() + man.cygwin_path = 'c:\\cygwin64\\bin\\' + #man.handleDeviceChange() + #print man.listSDVM() + #man.configureHostNetworking() + new_vm = man.generateSDVMName() + man.createVM(new_vm) + man.genCertificateISO(new_vm) + man.attachCertificateISO(new_vm) + + #man.attachCertificateISO(vm_name) + #man.sshGuestExecute(vm_name, "ls") + #man.sshGuestX11Execute(vm_name, "iceweasel") + #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\"" + #man.execute(cmd) + + + + diff -r c187aaceca32 -r 2e4cb1ebcbed server/opensecurityd.py --- a/server/opensecurityd.py Fri Dec 06 12:10:30 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,192 +0,0 @@ -#!/bin/env python -# -*- coding: utf-8 -*- - -# ------------------------------------------------------------ -# opensecurityd -# -# the opensecurityd as RESTful server -# -# Autor: Oliver Maurhart, -# -# Copyright (C) 2013 AIT Austrian Institute of Technology -# AIT Austrian Institute of Technology GmbH -# Donau-City-Strasse 1 | 1220 Vienna | Austria -# http://www.ait.ac.at -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation version 2. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, -# Boston, MA 02110-1301, USA. -# ------------------------------------------------------------ - - -# ------------------------------------------------------------ -# imports - -import os -import os.path -import subprocess -import sys -import web -from vmmanager.vmmanager import VMManager - -# local -from environment import Environment - - -# ------------------------------------------------------------ -# const - -__version__ = "0.1" - - -"""All the URLs we know mapping to class handler""" -opensecurity_urls = ( - '/device_change', 'os_device_change', - '/application', 'os_application', - '/device', 'os_device', - '/device/credentials', 'os_device_credentials', - '/device/password', 'os_device_password', - '/', 'os_root' -) - - -# ------------------------------------------------------------ -# code - -gvm_mgr = VMManager() - - -class os_application: - - """OpenSecurity '/application' handler. - - This is called on GET /application?vm=VM-ID&app=APP-ID - This tries to access the vm identified with the label VM-ID - and launched the application identified APP-ID - """ - - def GET(self): - - # pick the arguments - args = web.input() - - # we _need_ a vm - if not "vm" in args: - raise web.badrequest() - - # we _need_ a app - if not "app" in args: - raise web.badrequest() - - ## TODO: HARD CODED STUFF HERE! THIS SHOULD BE FLEXIBLE! - ssh_private_key = os.path.join(Environment("opensecurity").data_path, 'share', '192.168.56.15.ppk') - putty_session = '192.168.56.15' - process_command = ['plink.exe', '-i', ssh_private_key, putty_session, args.app] - si = subprocess.STARTUPINFO() - si.dwFlags = subprocess.STARTF_USESHOWWINDOW - si.wShowWindow = subprocess.SW_HIDE - print('tyring to launch: ' + ' '.join(process_command)) - process = subprocess.Popen(process_command, shell = True) - return 'launched: ' + ' '.join(process_command) - -class os_device: - - """OpenSecurity '/device' handler""" - - def GET(self): - return "os_device" - -class os_device_change: - - """OpenSecurity '/device_change' handler""" - - def GET(self): - print 'received device_change' - gvm_mgr.cygwin_path = 'c:\\cygwin64\\bin\\' - gvm_mgr.handleDeviceChange() - - #gvm_mgr.configureHostNetworking() - return "os_device_change" - - -class os_device_credentials: - - """OpenSecurity '/device/credentials' handler. - - This is called on GET /device/credentials?id=DEVICE-ID. - Ideally this should pop up a user dialog to insert his - credentials based the DEVICE-ID - """ - - def GET(self): - - # pick the arguments - args = web.input() - - # we _need_ a device id - if not "id" in args: - raise web.badrequest() - - # invoke the user dialog as a subprocess - dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py') - process_command = [sys.executable, dlg_credentials_image, 'credentials', 'Please provide credentials for accessing \ndevice: "{0}".'.format(args.id)] - process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE) - result = process.communicate()[0] - if process.returncode != 0: - return 'Credentials request has been aborted.' - - return result - - -class os_device_password: - - """OpenSecurity '/device/password' handler. - - This is called on GET /device/password?id=DEVICE-ID. - Ideally this should pop up a user dialog to insert his - password based the DEVICE-ID - """ - - def GET(self): - - # pick the arguments - args = web.input() - - # we _need_ a device id - if not "id" in args: - raise web.badrequest() - - # invoke the user dialog as a subprocess - dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py') - process_command = [sys.executable, dlg_credentials_image, 'password', 'Please provide a password for accessing \ndevice: "{0}".'.format(args.id)] - process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE) - result = process.communicate()[0] - if process.returncode != 0: - return 'Credentials request has been aborted.' - - return result - - -class os_root: - - """OpenSecurity '/' handler""" - - def GET(self): - return "OpenSecurity-Server { \"version\": \"%s\" }" % __version__ - - -# start -if __name__ == "__main__": - server = web.application(opensecurity_urls, globals()) - server.run() - diff -r c187aaceca32 -r 2e4cb1ebcbed server/vmmanager/vmmanager.py --- a/server/vmmanager/vmmanager.py Fri Dec 06 12:10:30 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,325 +0,0 @@ -''' -Created on Nov 19, 2013 - -@author: BarthaM -''' -import os -import os.path -from subprocess import Popen, PIPE, call -import subprocess -import sys -import re - -DEBUG = True - -class USBFilter: - vendorid = "" - productid = "" - revision = "" - - def __init__(self, vendorid, productid, revision): - self.vendorid = vendorid.lower() - self.productid = productid.lower() - self.revision = revision.lower() - return - - def __eq__(self, other): - return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision - - def __hash__(self): - return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision) - - def __repr__(self): - return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'" - - -class VMManager(object): - vmRootName = "SecurityDVM" - systemProperties = None - cygwin_path = 'c:\\cygwin64\\bin\\' - - def __init__(self): - self.systemProperties = self.getSystemProperties() - #TODO: get cygwin path externally - return - - def execute(self, cmd): - if DEBUG: - print('trying to launch: ' + cmd) - process = Popen(cmd, stdout=PIPE, stderr=PIPE) - if DEBUG: - print('launched: ' + cmd) - result = process.wait() - res_stdout = process.stdout.read(); - res_stderr = process.stderr.read(); - if DEBUG: - if res_stdout != "": - print res_stdout - if res_stderr != "": - print res_stderr - return result, res_stdout, res_stderr - - # return hosty system properties - def getSystemProperties(self): - cmd = 'VBoxManage list systemproperties' - result = self.execute(cmd) - if result[1]=='': - return None - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines())) - return props - - # return the folder containing the guest VMs - def getDefaultMachineFolder(self): - return self.systemProperties["Default machine folder"] - - #list the hostonly IFs exposed by the VBox host - def getHostOnlyIFs(self): - cmd = 'VBoxManage list hostonlyifs' - result = self.execute(cmd)[1] - if result=='': - return None - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines())) - return props - - def listRSDS(self): - cmd = 'VBoxManage list usbhost' - results = self.execute(cmd)[1] - results = results.split('Host USB Devices:')[1].strip() - - items = list( "UUID:"+result for result in results.split('UUID:') if result != '') - rsds = dict() - for item in items: - props = dict() - for line in item.splitlines(): - if line != "": - k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip() - props[k] = v; - - if 'Product' in props.keys() and props['Product'] == 'Mass Storage': - usb_filter = USBFilter( re.search(r"\((?P[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], - re.search(r"\((?P[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'], - re.search(r"\((?P[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] ) - rsds[props['UUID']] = usb_filter; - if DEBUG: - print filter - return rsds - - # list all existing VMs registered with VBox - def listVM(self): - cmd = 'VBoxManage list vms' - result = self.execute(cmd)[1] - vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines())) - return vms - - # list existing SDVMs - def listSDVM(self): - vms = self.listVM() - svdms = [] - for vm in vms: - if vm.startswith(self.vmRootName) and vm != self.vmRootName: - svdms.append(vm) - return svdms - - # generate valid (not already existing SDVM name). necessary for creating a new VM - def generateSDVMName(self): - vms = self.listVM() - for i in range(0,999): - if(not self.vmRootName+str(i) in vms): - return self.vmRootName+str(i) - return '' - - # return the RSDs attached to all existing SDVMs - def getAttachedRSDs(self): - vms = self.listSDVM() - attached_devices = dict() - for vm in vms: - rsd_filter = self.getUSBFilter(vm) - if rsd_filter != None: - attached_devices[vm] = rsd_filter - return attached_devices - - # configures hostonly networking and DHCP server. requires admin rights - def configureHostNetworking(self): - #cmd = 'vboxmanage list hostonlyifs' - #self.execute(cmd) - #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"' - #self.execute(cmd) - #cmd = 'vboxmanage hostonlyif create' - #self.execute(cmd) - cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0' - self.execute(cmd) - #cmd = 'vboxmanage dhcpserver add' - #self.execute(cmd) - 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' - self.execute(cmd) - - #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk) - def createVM(self, vm_name): - hostonly_if = self.getHostOnlyIFs() - machineFolder = self.getDefaultMachineFolder() - cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register' - self.execute(cmd) - cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' - self.execute(cmd) - cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2' - self.execute(cmd) - cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' - #--mtype immutable - self.execute(cmd) - return - - #remove VM from the system. should be used on VMs returned by listSDVMs - def removeVM(self, vm_name): - print('removing ' + vm_name) - cmd = 'VBoxManage unregistervm', vm_name, '--delete' - print self.execute(cmd) - machineFolder = self.getDefaultMachineFolder() - cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"' - print self.execute(cmd) - - # start VM - def startVM(self, vm_name): - print('starting ' + vm_name) - cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' - print self.execute(cmd) - - # stop VM - def stopVM(self, vm_name): - print('stopping ' + vm_name) - cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff' - print self.execute(cmd) - - # return the hostOnly IP for a running guest - def getHostOnlyIP(self, vm_name): - print('gettting hostOnly IP address ' + vm_name) - cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP' - result = self.execute(cmd) - if result=='': - return None - result = result[1] - return result[result.index(':')+1:].strip() - - # attach removable storage device to VM by provision of filter - def attachRSD(self, vm_name, rsd_filter): - cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision - print self.execute(cmd) - - - # return the description set for an existing VM - def getVMInfo(self, vm_name): - cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable' - results = self.execute(cmd)[1] - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines())) - return props - - # return the configured USB filter for an existing VM - def getUSBFilter(self, vm_name): - props = self.getVMInfo(vm_name) - keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1']) - keyset = set(props.keys()) - usb_filter = None - if keyset.issuperset(keys): - usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1']) - return usb_filter - - #generates ISO containing authorized_keys for use with guest VM - def genCertificateISO(self, vm_name): - machineFolder = self.getDefaultMachineFolder() - # create .ssh folder in vm_name - cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"' - result = self.execute(cmd) - # generate dvm_key pair in vm_name / .ssh - 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" |', - result = self.execute(cmd) - # set permissions for keys - #TODO: test without chmod - cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"' - result = self.execute(cmd) - # move out private key - cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"' - result = self.execute(cmd) - # rename public key to authorized_keys - cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"' - result = self.execute(cmd) - # generate iso image with .ssh/authorized keys - cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"' - result = self.execute(cmd) - - # attaches generated ssh public cert to guest vm - def attachCertificateISO(self, vm_name): - machineFolder = self.getDefaultMachineFolder() - cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"' - result = self.execute(cmd) - return result - - # handles device change events - def handleDeviceChange(self): - attached_devices = self.getAttachedRSDs() - connected_devices = self.listRSDS() - for vm_name in attached_devices.keys(): - if connected_devices and attached_devices[vm_name] not in connected_devices.values(): - # self.netUse(vm_name) - self.stopVM(vm_name) - self.removeVM(vm_name) - - attached_devices = self.getAttachedRSDs() - for connected_device in connected_devices.values(): - if attached_devices or connected_device not in attached_devices.values(): - new_sdvm = self.generateSDVMName() - self.createVM(new_sdvm) - self.attachRSD(new_sdvm, connected_device) - self.startVM(new_sdvm) - self.netUse(new_sdvm) - - def handleBrowsingRequest(self): - new_sdvm = self.generateSDVMName() - self.createVM(new_sdvm) - self.genCertificateISO(new_sdvm) - self.attachCertificateISO(new_sdvm) - - # executes command over ssh on guest vm - def sshGuestExecute(self, vm_name, prog, user_name='opensec'): - # get vm ip - address = self.getHostOnlyIP(vm_name) - machineFolder = self.getDefaultMachineFolder() - # run command - cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"' - return self.execute(cmd) - - # executes command over ssh on guest vm with X forwarding - def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'): - #TODO: verify if X server is running on user account - #TODO: set DISPLAY accordingly - address = self.getHostOnlyIP(vm_name) - machineFolder = self.getDefaultMachineFolder() - # run command - cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"' - return self.execute(cmd) - - # executes NET USE and connects to samba share on guestos - def netUse(self, vm_name): - ip = self.getHostOnlyIP(vm_name) - cmd = 'net use H: \\' + ip + '\USB' - return self.execute(cmd) - - -if __name__ == '__main__': - man = VMManager() - man.cygwin_path = 'c:\\cygwin64\\bin\\' - #man.handleDeviceChange() - #print man.listSDVM() - #man.configureHostNetworking() - new_vm = man.generateSDVMName() - man.createVM(new_vm) - man.genCertificateISO(new_vm) - man.attachCertificateISO(new_vm) - - #man.attachCertificateISO(vm_name) - #man.sshGuestExecute(vm_name, "ls") - #man.sshGuestX11Execute(vm_name, "iceweasel") - #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\"" - #man.execute(cmd) - - - -