working on client/server code merge
authorom
Fri, 06 Dec 2013 12:24:24 +0100
changeset 16e16d64b5e008
parent 15 2e4cb1ebcbed
parent 13 4457d7071a23
child 17 0b4efa323de3
working on client/server code merge
OpenSecurity/bin/about.py
OpenSecurity/bin/credentials.py
OpenSecurity/bin/cygwin.py
OpenSecurity/bin/environment.py
OpenSecurity/bin/launch.py
OpenSecurity/bin/opensecurity_client_restful_server.py
OpenSecurity/bin/opensecurity_dialog.py
OpenSecurity/bin/opensecurity_server.py
OpenSecurity/bin/opensecurity_tray.py
OpenSecurity/bin/opensecurityd.py
OpenSecurity/bin/password.py
     1.1 --- a/OpenSecurity/bin/opensecurity_server.py	Fri Dec 06 12:15:18 2013 +0100
     1.2 +++ b/OpenSecurity/bin/opensecurity_server.py	Fri Dec 06 12:24:24 2013 +0100
     1.3 @@ -42,8 +42,7 @@
     1.4      
     1.5      # TODO: REPLACE THIS HARDCODED STUFF WITH REAL CODE TO THE OS SERVER
     1.6      apps = [ 
     1.7 -        { 'vm': 'Debian 7', 'name': 'Browser', 'command': '/usr/bin/iceweasel'}, 
     1.8 -        { 'vm': 'Debian 7', 'name': 'VLC', 'command': '/usr/bin/vlc'}
     1.9 +        { 'vm': '', 'name': 'Browser', 'command': '/usr/bin/iceweasel'}, 
    1.10      ]
    1.11      
    1.12      return apps
    1.13 @@ -54,8 +53,8 @@
    1.14      
    1.15      # TODO: REPLACE THIS HARDCODED STUFF WITH REAL CODE TO THE OS SERVER
    1.16      vms = [ 
    1.17 -        { 'user': 'user', 'name': 'Debian 7', 'ip': '192.168.56.101'}, 
    1.18 -        { 'user': 'user', 'name': 'Anit-Virus VM', 'ip': '192.168.56.101'}
    1.19 +        { 'user': 'opensec', 'name': 'Debian 7', 'ip': '192.168.56.101'}, 
    1.20 +        { 'user': 'opensec', 'name': 'Anit-Virus VM', 'ip': '192.168.56.101'}
    1.21      ]
    1.22      
    1.23      return vms
     2.1 --- a/OpenSecurity/bin/opensecurityd.py	Fri Dec 06 12:15:18 2013 +0100
     2.2 +++ b/OpenSecurity/bin/opensecurityd.py	Fri Dec 06 12:24:24 2013 +0100
     2.3 @@ -52,137 +52,64 @@
     2.4  """All the URLs we know mapping to class handler"""
     2.5  opensecurity_urls = (
     2.6      '/device_change',           'os_device_change',
     2.7 -    '/application',             'os_application',
     2.8 -    '/device',                  'os_device',
     2.9 -    '/device/credentials',      'os_device_credentials',
    2.10 -    '/device/password',         'os_device_password',
    2.11 +    '/sdvms',                   'os_sdvms',
    2.12 +    '/vms',                     'os_vms',
    2.13 +    '/vms/(.*)',                'os_vm',
    2.14      '/',                        'os_root'
    2.15  )
    2.16  
    2.17  
    2.18  # ------------------------------------------------------------
    2.19 +# vars
    2.20 +
    2.21 +# Global VMManager instance
    2.22 +gvm_mgr = VMManager()
    2.23 +
    2.24 +
    2.25 +# ------------------------------------------------------------
    2.26  # code
    2.27  
    2.28 -gvm_mgr = VMManager()
    2.29 -
    2.30 -
    2.31 -class os_application:
    2.32 -    
    2.33 -    """OpenSecurity '/application' handler.
    2.34 -    
    2.35 -    This is called on GET /application?vm=VM-ID&app=APP-ID
    2.36 -    This tries to access the vm identified with the label VM-ID
    2.37 -    and launched the application identified APP-ID
    2.38 -    """
    2.39 -    
    2.40 -    def GET(self):
    2.41 -        
    2.42 -        # pick the arguments
    2.43 -        args = web.input()
    2.44 -        
    2.45 -        # we _need_ a vm
    2.46 -        if not "vm" in args:
    2.47 -            raise web.badrequest()
    2.48 -        
    2.49 -        # we _need_ a app
    2.50 -        if not "app" in args:
    2.51 -            raise web.badrequest()
    2.52 -        
    2.53 -        ## TODO: HARD CODED STUFF HERE! THIS SHOULD BE FLEXIBLE!
    2.54 -        ssh_private_key = os.path.join(Environment("opensecurity").data_path, 'share', '192.168.56.15.ppk')
    2.55 -        putty_session = '192.168.56.15'
    2.56 -        process_command = ['plink.exe', '-i', ssh_private_key, putty_session, args.app]
    2.57 -        si = subprocess.STARTUPINFO()
    2.58 -        si.dwFlags = subprocess.STARTF_USESHOWWINDOW
    2.59 -        si.wShowWindow = subprocess.SW_HIDE
    2.60 -        print('tyring to launch: ' + ' '.join(process_command))
    2.61 -        process = subprocess.Popen(process_command, shell = True)
    2.62 -        return 'launched: ' + ' '.join(process_command)
    2.63 -
    2.64 -class os_device:
    2.65 -    
    2.66 -    """OpenSecurity '/device' handler"""
    2.67 -    
    2.68 -    def GET(self):
    2.69 -        return "os_device"
    2.70  
    2.71  class os_device_change:
    2.72 -    
    2.73      """OpenSecurity '/device_change' handler"""
    2.74      
    2.75      def GET(self):
    2.76 +        #gvm_mgr.configureHostNetworking()
    2.77          print 'received device_change'
    2.78 -        gvm_mgr.cygwin_path = 'c:\\cygwin64\\bin\\'
    2.79 -        gvm_mgr.handleDeviceChange()
    2.80 -        
    2.81 -        #gvm_mgr.configureHostNetworking()
    2.82          return "os_device_change"
    2.83  
    2.84  
    2.85 -class os_device_credentials:
    2.86 -    
    2.87 -    """OpenSecurity '/device/credentials' handler.
    2.88 -    
    2.89 -    This is called on GET /device/credentials?id=DEVICE-ID.
    2.90 -    Ideally this should pop up a user dialog to insert his
    2.91 -    credentials based the DEVICE-ID
    2.92 -    """
    2.93 +class os_sdvms:
    2.94 +    """OpenSecurity '/sdvms' handler"""
    2.95      
    2.96      def GET(self):
    2.97 -        
    2.98 -        # pick the arguments
    2.99 -        args = web.input()
   2.100 -        
   2.101 -        # we _need_ a device id
   2.102 -        if not "id" in args:
   2.103 -            raise web.badrequest()
   2.104 -        
   2.105 -        # invoke the user dialog as a subprocess
   2.106 -        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   2.107 -        process_command = [sys.executable, dlg_credentials_image, 'credentials', 'Please provide credentials for accessing \ndevice: "{0}".'.format(args.id)]
   2.108 -        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   2.109 -        result = process.communicate()[0]
   2.110 -        if process.returncode != 0:
   2.111 -            return 'Credentials request has been aborted.'
   2.112 -        
   2.113 -        return result
   2.114 +        return gvm_mgr.listSDVM() 
   2.115 +            
   2.116  
   2.117 +class os_vm:
   2.118 +    """OpenSecurity '/vms/VM' handler"""
   2.119 +    
   2.120 +    def GET(self, name):
   2.121 +        return gvm_mgr.getVMInfo(name)
   2.122 +            
   2.123  
   2.124 -class os_device_password:
   2.125 -    
   2.126 -    """OpenSecurity '/device/password' handler.
   2.127 -    
   2.128 -    This is called on GET /device/password?id=DEVICE-ID.
   2.129 -    Ideally this should pop up a user dialog to insert his
   2.130 -    password based the DEVICE-ID
   2.131 -    """
   2.132 +class os_vms:
   2.133 +    """OpenSecurity '/vms' handler"""
   2.134      
   2.135      def GET(self):
   2.136 -        
   2.137 -        # pick the arguments
   2.138 -        args = web.input()
   2.139 -        
   2.140 -        # we _need_ a device id
   2.141 -        if not "id" in args:
   2.142 -            raise web.badrequest()
   2.143 +        return gvm_mgr.listVM() 
   2.144              
   2.145 -        # invoke the user dialog as a subprocess
   2.146 -        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   2.147 -        process_command = [sys.executable, dlg_credentials_image, 'password', 'Please provide a password for accessing \ndevice: "{0}".'.format(args.id)]
   2.148 -        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   2.149 -        result = process.communicate()[0]
   2.150 -        if process.returncode != 0:
   2.151 -            return 'Credentials request has been aborted.'
   2.152 -        
   2.153 -        return result
   2.154 -
   2.155  
   2.156  class os_root:
   2.157 -    
   2.158      """OpenSecurity '/' handler"""
   2.159      
   2.160      def GET(self):
   2.161 -        return "OpenSecurity-Server { \"version\": \"%s\" }" % __version__
   2.162 +        res = "'os_server': { "
   2.163 +        res += "'version': '" + __version__ + "', "
   2.164 +        res += "'virtualbox_path': '" + gvm_mgr.vBoxPath + "', "
   2.165 +        res += "'machine_folder': '" + gvm_mgr.getDefaultMachineFolder() + "' "
   2.166 +        res += "}"
   2.167 +        return res
   2.168  
   2.169  
   2.170  # start
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/OpenSecurity/bin/vmmanager/PKG-INFO	Fri Dec 06 12:24:24 2013 +0100
     3.3 @@ -0,0 +1,10 @@
     3.4 +Metadata-Version: 1.0
     3.5 +Name: vmmanager.py
     3.6 +Version: 0.1
     3.7 +Summary: vmmanager.py: manages GustVM's
     3.8 +Home-page:  http://webpy.org/
     3.9 +Author: Mihai Bartha
    3.10 +Author-email: mihai.bartha@ait.ac.at
    3.11 +License: Public domain
    3.12 +Description: Module to manage virtualbox guests and host
    3.13 +Platform: any
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/OpenSecurity/bin/vmmanager/__init__.py	Fri Dec 06 12:24:24 2013 +0100
     4.3 @@ -0,0 +1,6 @@
     4.4 +__version__ = "0.1"
     4.5 +__author__ = [
     4.6 +    "Mihai Bartha <mihai.bartha@ait.ac.at>"
     4.7 +]
     4.8 +__license__ = "public domain"
     4.9 +__contributors__ = "OpenSecurity Consortium"
    4.10 \ No newline at end of file
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/OpenSecurity/bin/vmmanager/vmmanager.py	Fri Dec 06 12:24:24 2013 +0100
     5.3 @@ -0,0 +1,342 @@
     5.4 +'''
     5.5 +Created on Nov 19, 2013
     5.6 +
     5.7 +@author: BarthaM
     5.8 +'''
     5.9 +import os
    5.10 +import os.path
    5.11 +from subprocess import Popen, PIPE, call
    5.12 +import subprocess
    5.13 +import sys
    5.14 +import re
    5.15 +from cygwin import Cygwin
    5.16 +import _winreg
    5.17 +
    5.18 +DEBUG = True
    5.19 +
    5.20 +class USBFilter:
    5.21 +    vendorid = ""
    5.22 +    productid = ""
    5.23 +    revision = ""
    5.24 +    
    5.25 +    def __init__(self, vendorid, productid, revision):
    5.26 +        self.vendorid = vendorid.lower()
    5.27 +        self.productid = productid.lower()
    5.28 +        self.revision = revision.lower()
    5.29 +        return
    5.30 +    
    5.31 +    def __eq__(self, other):
    5.32 +        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    5.33 +    
    5.34 +    def __hash__(self):
    5.35 +        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    5.36 +    
    5.37 +    def __repr__(self):
    5.38 +        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    5.39 +        
    5.40 +
    5.41 +class VMManager(object):
    5.42 +    """Manage Virtual Machines"""
    5.43 +
    5.44 +    vmRootName = "SecurityDVM"
    5.45 +    
    5.46 +    def __init__(self):
    5.47 +        self.vBoxPath = self.getVBoxManagePath()
    5.48 +        self.vBoxManage = os.path.join(self.vBoxPath, 'VBoxManage.exe')
    5.49 +        self.systemProperties = self.getSystemProperties()
    5.50 +        self.cygwin_path = Cygwin.root()
    5.51 +        return
    5.52 +         
    5.53 +    def execute(self, cmd):
    5.54 +        """execute a command"""
    5.55 +    
    5.56 +        # we can handle strings and lists as input
    5.57 +        c = cmd
    5.58 +        if type(cmd) == list:
    5.59 +            c = ' '.join(cmd)
    5.60 +    
    5.61 +        if DEBUG:
    5.62 +            sys.stderr.write('trying to launch: ' + c + '\n')
    5.63 +        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    5.64 +        if DEBUG:
    5.65 +            sys.stderr.write('launched: ' + c + '\n')
    5.66 +            
    5.67 +        result = process.wait()
    5.68 +        res_stdout = process.stdout.read();
    5.69 +        res_stderr = process.stderr.read();
    5.70 +        if DEBUG:
    5.71 +            if res_stdout != "":
    5.72 +                print res_stdout
    5.73 +            if res_stderr != "":
    5.74 +                print res_stderr
    5.75 +        return result, res_stdout, res_stderr
    5.76 +    
    5.77 +    
    5.78 +    def getVBoxManagePath(self):
    5.79 +        """get the path to the VirtualBox installation on this system"""
    5.80 +        p = None
    5.81 +        try:
    5.82 +            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    5.83 +            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    5.84 +            _winreg.CloseKey(k)
    5.85 +        except:
    5.86 +            pass
    5.87 +        return p
    5.88 +    
    5.89 +    # return host system properties
    5.90 +    def getSystemProperties(self):
    5.91 +        cmd = [self.vBoxManage, 'list', 'systemproperties']
    5.92 +        result = self.execute(cmd)
    5.93 +        if result[1]=='':
    5.94 +            return None
    5.95 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
    5.96 +        return props
    5.97 +    
    5.98 +    # return the folder containing the guest VMs     
    5.99 +    def getDefaultMachineFolder(self):
   5.100 +        return self.systemProperties["Default machine folder"]
   5.101 +    
   5.102 +    #list the hostonly IFs exposed by the VBox host
   5.103 +    def getHostOnlyIFs(self):
   5.104 +        cmd = [self.vBoxManage, 'list', 'hostonlyifs']
   5.105 +        result = self.execute(cmd)[1]
   5.106 +        if result=='':
   5.107 +            return None
   5.108 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
   5.109 +        return props
   5.110 +        
   5.111 +    def listRSDS(self):
   5.112 +        cmd = [self.vBoxManage, 'list', 'usbhost']
   5.113 +        results = self.execute(cmd)
   5.114 +        results = results.split('Host USB Devices:')[1].strip()
   5.115 +        
   5.116 +        items = list( "UUID:" + result for result in results.split('UUID:') if result != '')
   5.117 +        rsds = dict()   
   5.118 +        for item in items:
   5.119 +            props = dict()
   5.120 +            for line in item.splitlines():
   5.121 +                if line != "":         
   5.122 +                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   5.123 +                    props[k] = v;
   5.124 +            
   5.125 +            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   5.126 +                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   5.127 +                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   5.128 +                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   5.129 +                rsds[props['UUID']] = usb_filter;
   5.130 +                if DEBUG:
   5.131 +                    print filter
   5.132 +        return rsds
   5.133 +
   5.134 +    # list all existing VMs registered with VBox
   5.135 +    def listVM(self):
   5.136 +        cmd = [self.vBoxManage, 'list', 'vms']
   5.137 +        result = self.execute(cmd)[1]
   5.138 +        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   5.139 +        return vms
   5.140 +    
   5.141 +    # list existing SDVMs
   5.142 +    def listSDVM(self):
   5.143 +        vms = self.listVM()
   5.144 +        svdms = []
   5.145 +        for vm in vms:
   5.146 +            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   5.147 +                svdms.append(vm)
   5.148 +        return svdms
   5.149 +    
   5.150 +    # generate valid (not already existing SDVM name). necessary for creating a new VM
   5.151 +    def generateSDVMName(self):
   5.152 +        vms = self.listVM()
   5.153 +        for i in range(0,999):
   5.154 +            if(not self.vmRootName+str(i) in vms):
   5.155 +                return self.vmRootName+str(i)
   5.156 +        return ''
   5.157 +    
   5.158 +    # return the RSDs attached to all existing SDVMs
   5.159 +    def getAttachedRSDs(self):
   5.160 +        vms = self.listSDVM()
   5.161 +        attached_devices = dict()
   5.162 +        for vm in vms:
   5.163 +            rsd_filter = self.getUSBFilter(vm)
   5.164 +            if filter != None:
   5.165 +                attached_devices[vm] = rsd_filter
   5.166 +        return attached_devices
   5.167 +    
   5.168 +    # configures hostonly networking and DHCP server. requires admin rights
   5.169 +    def configureHostNetworking(self):
   5.170 +        #cmd = 'vboxmanage list hostonlyifs'
   5.171 +        #self.execute(cmd)
   5.172 +        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   5.173 +        #self.execute(cmd)
   5.174 +        #cmd = 'vboxmanage hostonlyif create'
   5.175 +        #self.execute(cmd)
   5.176 +        cmd = self.vBoxManage + ' hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   5.177 +        self.execute(cmd)
   5.178 +        #cmd = 'vboxmanage dhcpserver add'
   5.179 +        #self.execute(cmd)
   5.180 +        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'
   5.181 +        self.execute(cmd)
   5.182 +    
   5.183 +    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   5.184 +    def createVM(self, vm_name):
   5.185 +        hostonly_if = self.getHostOnlyIFs()
   5.186 +        machineFolder = self.getDefaultMachineFolder()
   5.187 +        cmd = self.vBoxManage + ' createvm --name ' + vm_name + ' --ostype Debian --register'
   5.188 +        self.execute(cmd)
   5.189 +        cmd = self.vBoxManage + ' modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
   5.190 +        self.execute(cmd)
   5.191 +        cmd = self.vBoxManage + ' storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   5.192 +        self.execute(cmd)
   5.193 +        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --mtype normal --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   5.194 +        self.execute(cmd)
   5.195 +        return
   5.196 +    
   5.197 +    #remove VM from the system. should be used on VMs returned by listSDVMs    
   5.198 +    def removeVM(self, vm_name):
   5.199 +        print('removing ' + vm_name)
   5.200 +        cmd = self.vBoxManage + ' unregistervm', vm_name, '--delete'
   5.201 +        print self.execute(cmd)
   5.202 +        machineFolder = self.getDefaultMachineFolder()
   5.203 +        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   5.204 +        print self.execute(cmd)
   5.205 +    
   5.206 +    # start VM
   5.207 +    def startVM(self, vm_name):
   5.208 +        print('starting ' +  vm_name)
   5.209 +        cmd = self.vBoxManage + ' startvm ' + vm_name + ' --type headless'
   5.210 +        print self.execute(cmd)
   5.211 +        
   5.212 +    # stop VM    
   5.213 +    def stopVM(self, vm_name):
   5.214 +        print('stopping ' + vm_name)
   5.215 +        cmd = self.vBoxManage + ' controlvm ' + vm_name + ' poweroff'
   5.216 +        print self.execute(cmd)
   5.217 +    
   5.218 +    # return the hostOnly IP for a running guest    
   5.219 +    def getHostOnlyIP(self, vm_name):
   5.220 +        print('gettting hostOnly IP address ' + vm_name)
   5.221 +        cmd = self.vBoxManage + ' guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   5.222 +        result = self.execute(cmd)
   5.223 +        if result=='':
   5.224 +            return None
   5.225 +        result = result[1]
   5.226 +        return result[result.index(':')+1:].strip()
   5.227 +    
   5.228 +    # attach removable storage device to VM by provision of filter
   5.229 +    def attachRSD(self, vm_name, rsd_filter):
   5.230 +        cmd = self.vBoxManage + ' usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   5.231 +        print self.execute(cmd)
   5.232 +        
   5.233 +    
   5.234 +    # return the description set for an existing VM
   5.235 +    def getVMInfo(self, vm_name):
   5.236 +        cmd = self.vBoxManage + ' showvminfo ' + vm_name + ' --machinereadable'
   5.237 +        r, o, e = self.execute(cmd)
   5.238 +        props = dict((k.strip(),v.strip().strip('"')) for k, v in (line.split('=', 1) for line in o.splitlines()))
   5.239 +        return props
   5.240 +    
   5.241 +    # return the configured USB filter for an existing VM 
   5.242 +    def getUSBFilter(self, vm_name):
   5.243 +        props = self.getVMInfo(vm_name)
   5.244 +        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   5.245 +        keyset = set(props.keys())
   5.246 +        usb_filter = None
   5.247 +        if keyset.issuperset(keys):
   5.248 +            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   5.249 +        return usb_filter
   5.250 +    
   5.251 +    #generates ISO containing authorized_keys for use with guest VM
   5.252 +    def genCertificateISO(self, vm_name):
   5.253 +        machineFolder = self.getDefaultMachineFolder()
   5.254 +        # create .ssh folder in vm_name
   5.255 +        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   5.256 +        result = self.execute(cmd)
   5.257 +        # generate dvm_key pair in vm_name / .ssh     
   5.258 +        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" |',
   5.259 +        result = self.execute(cmd)
   5.260 +        # set permissions for keys
   5.261 +        #TODO: test without chmod
   5.262 +        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   5.263 +        result = self.execute(cmd)
   5.264 +        # move out private key
   5.265 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   5.266 +        result = self.execute(cmd)
   5.267 +        # rename public key to authorized_keys
   5.268 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   5.269 +        result = self.execute(cmd)
   5.270 +        # generate iso image with .ssh/authorized keys
   5.271 +        cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   5.272 +        result = self.execute(cmd)
   5.273 +    
   5.274 +    # attaches generated ssh public cert to guest vm
   5.275 +    def attachCertificateISO(self, vm_name):
   5.276 +        machineFolder = self.getDefaultMachineFolder()
   5.277 +        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   5.278 +        result = self.execute(cmd)
   5.279 +        return result
   5.280 +    
   5.281 +    # handles device change events
   5.282 +    def handleDeviceChange(self):
   5.283 +        attached_devices = self.getAttachedRSDs()
   5.284 +        connected_devices = self.listRSDS()
   5.285 +        for vm_name in attached_devices.keys():
   5.286 +            if attached_devices[vm_name] not in connected_devices.values():
   5.287 +                self.stopVM(vm_name)
   5.288 +                self.removeVM(vm_name)
   5.289 +        
   5.290 +        attached_devices = self.getAttachedRSDs()
   5.291 +        for connected_device in connected_devices.values():
   5.292 +            if connected_device not in attached_devices.values():
   5.293 +                new_sdvm = self.generateSDVMName()
   5.294 +                self.createVM(new_sdvm)
   5.295 +                self.genCertificateISO(new_sdvm)
   5.296 +                self.attachCertificateISO(new_sdvm)
   5.297 +                self.attachRSD(new_sdvm, connected_device)
   5.298 +                self.startVM(new_sdvm)
   5.299 +    
   5.300 +    # executes command over ssh on guest vm
   5.301 +    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   5.302 +        # get vm ip
   5.303 +        address = self.getHostOnlyIP(vm_name)
   5.304 +        machineFolder = self.getDefaultMachineFolder()
   5.305 +        # run command
   5.306 +        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   5.307 +        return self.execute(cmd)
   5.308 +    
   5.309 +    # executes command over ssh on guest vm with X forwarding
   5.310 +    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   5.311 +        #TODO: verify if X server is running on user account 
   5.312 +        #TODO: set DISPLAY accordingly
   5.313 +        address = self.getHostOnlyIP(vm_name)
   5.314 +        machineFolder = self.getDefaultMachineFolder()
   5.315 +        # run command
   5.316 +        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   5.317 +        return self.execute(cmd)    
   5.318 +        
   5.319 +    # executes NET USE and connects to samba share on guestos 
   5.320 +    def netUse(self, vm_name):
   5.321 +        ip = self.getHostOnlyIP(vm_name)
   5.322 +        cmd = 'net use H: \\' + ip + '\RSD_Device'
   5.323 +        return self.execute(cmd)
   5.324 +        
   5.325 +    
   5.326 +if __name__ == '__main__':
   5.327 +    man = VMManager()
   5.328 +    man.cygwin_path = 'c:\\cygwin64\\bin\\'
   5.329 +    #man.handleDeviceChange()
   5.330 +    #print man.listSDVM()
   5.331 +    #man.configureHostNetworking()
   5.332 +    new_vm = man.generateSDVMName()
   5.333 +    man.createVM(new_vm)
   5.334 +    man.genCertificateISO(new_vm)
   5.335 +    man.attachCertificateISO(new_vm)
   5.336 +    
   5.337 +    #man.attachCertificateISO(vm_name)
   5.338 +    #man.sshGuestExecute(vm_name, "ls")
   5.339 +    #man.sshGuestX11Execute(vm_name, "iceweasel")
   5.340 +    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   5.341 +    #man.execute(cmd)
   5.342 +    
   5.343 +    
   5.344 +
   5.345 +