moved server python stuff into bin folder
authorom
Fri, 06 Dec 2013 12:15:18 +0100
changeset 152e4cb1ebcbed
parent 14 c187aaceca32
child 16 e16d64b5e008
moved server python stuff into bin folder
OpenSecurity/bin/opensecurityd.py
OpenSecurity/bin/vmmanager.py
server/opensecurityd.py
server/vmmanager/vmmanager.py
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/OpenSecurity/bin/opensecurityd.py	Fri Dec 06 12:15:18 2013 +0100
     1.3 @@ -0,0 +1,192 @@
     1.4 +#!/bin/env python
     1.5 +# -*- coding: utf-8 -*-
     1.6 +
     1.7 +# ------------------------------------------------------------
     1.8 +# opensecurityd
     1.9 +# 
    1.10 +# the opensecurityd as RESTful server
    1.11 +#
    1.12 +# Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    1.13 +#
    1.14 +# Copyright (C) 2013 AIT Austrian Institute of Technology
    1.15 +# AIT Austrian Institute of Technology GmbH
    1.16 +# Donau-City-Strasse 1 | 1220 Vienna | Austria
    1.17 +# http://www.ait.ac.at
    1.18 +#
    1.19 +# This program is free software; you can redistribute it and/or
    1.20 +# modify it under the terms of the GNU General Public License
    1.21 +# as published by the Free Software Foundation version 2.
    1.22 +# 
    1.23 +# This program is distributed in the hope that it will be useful,
    1.24 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.25 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.26 +# GNU General Public License for more details.
    1.27 +# 
    1.28 +# You should have received a copy of the GNU General Public License
    1.29 +# along with this program; if not, write to the Free Software
    1.30 +# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    1.31 +# Boston, MA  02110-1301, USA.
    1.32 +# ------------------------------------------------------------
    1.33 +
    1.34 +
    1.35 +# ------------------------------------------------------------
    1.36 +# imports
    1.37 +
    1.38 +import os
    1.39 +import os.path
    1.40 +import subprocess
    1.41 +import sys
    1.42 +import web
    1.43 +from vmmanager.vmmanager import VMManager
    1.44 +
    1.45 +# local
    1.46 +from environment import Environment
    1.47 +
    1.48 +
    1.49 +# ------------------------------------------------------------
    1.50 +# const
    1.51 +
    1.52 +__version__ = "0.1"
    1.53 +
    1.54 +
    1.55 +"""All the URLs we know mapping to class handler"""
    1.56 +opensecurity_urls = (
    1.57 +    '/device_change',           'os_device_change',
    1.58 +    '/application',             'os_application',
    1.59 +    '/device',                  'os_device',
    1.60 +    '/device/credentials',      'os_device_credentials',
    1.61 +    '/device/password',         'os_device_password',
    1.62 +    '/',                        'os_root'
    1.63 +)
    1.64 +
    1.65 +
    1.66 +# ------------------------------------------------------------
    1.67 +# code
    1.68 +
    1.69 +gvm_mgr = VMManager()
    1.70 +
    1.71 +
    1.72 +class os_application:
    1.73 +    
    1.74 +    """OpenSecurity '/application' handler.
    1.75 +    
    1.76 +    This is called on GET /application?vm=VM-ID&app=APP-ID
    1.77 +    This tries to access the vm identified with the label VM-ID
    1.78 +    and launched the application identified APP-ID
    1.79 +    """
    1.80 +    
    1.81 +    def GET(self):
    1.82 +        
    1.83 +        # pick the arguments
    1.84 +        args = web.input()
    1.85 +        
    1.86 +        # we _need_ a vm
    1.87 +        if not "vm" in args:
    1.88 +            raise web.badrequest()
    1.89 +        
    1.90 +        # we _need_ a app
    1.91 +        if not "app" in args:
    1.92 +            raise web.badrequest()
    1.93 +        
    1.94 +        ## TODO: HARD CODED STUFF HERE! THIS SHOULD BE FLEXIBLE!
    1.95 +        ssh_private_key = os.path.join(Environment("opensecurity").data_path, 'share', '192.168.56.15.ppk')
    1.96 +        putty_session = '192.168.56.15'
    1.97 +        process_command = ['plink.exe', '-i', ssh_private_key, putty_session, args.app]
    1.98 +        si = subprocess.STARTUPINFO()
    1.99 +        si.dwFlags = subprocess.STARTF_USESHOWWINDOW
   1.100 +        si.wShowWindow = subprocess.SW_HIDE
   1.101 +        print('tyring to launch: ' + ' '.join(process_command))
   1.102 +        process = subprocess.Popen(process_command, shell = True)
   1.103 +        return 'launched: ' + ' '.join(process_command)
   1.104 +
   1.105 +class os_device:
   1.106 +    
   1.107 +    """OpenSecurity '/device' handler"""
   1.108 +    
   1.109 +    def GET(self):
   1.110 +        return "os_device"
   1.111 +
   1.112 +class os_device_change:
   1.113 +    
   1.114 +    """OpenSecurity '/device_change' handler"""
   1.115 +    
   1.116 +    def GET(self):
   1.117 +        print 'received device_change'
   1.118 +        gvm_mgr.cygwin_path = 'c:\\cygwin64\\bin\\'
   1.119 +        gvm_mgr.handleDeviceChange()
   1.120 +        
   1.121 +        #gvm_mgr.configureHostNetworking()
   1.122 +        return "os_device_change"
   1.123 +
   1.124 +
   1.125 +class os_device_credentials:
   1.126 +    
   1.127 +    """OpenSecurity '/device/credentials' handler.
   1.128 +    
   1.129 +    This is called on GET /device/credentials?id=DEVICE-ID.
   1.130 +    Ideally this should pop up a user dialog to insert his
   1.131 +    credentials based the DEVICE-ID
   1.132 +    """
   1.133 +    
   1.134 +    def GET(self):
   1.135 +        
   1.136 +        # pick the arguments
   1.137 +        args = web.input()
   1.138 +        
   1.139 +        # we _need_ a device id
   1.140 +        if not "id" in args:
   1.141 +            raise web.badrequest()
   1.142 +        
   1.143 +        # invoke the user dialog as a subprocess
   1.144 +        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   1.145 +        process_command = [sys.executable, dlg_credentials_image, 'credentials', 'Please provide credentials for accessing \ndevice: "{0}".'.format(args.id)]
   1.146 +        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   1.147 +        result = process.communicate()[0]
   1.148 +        if process.returncode != 0:
   1.149 +            return 'Credentials request has been aborted.'
   1.150 +        
   1.151 +        return result
   1.152 +
   1.153 +
   1.154 +class os_device_password:
   1.155 +    
   1.156 +    """OpenSecurity '/device/password' handler.
   1.157 +    
   1.158 +    This is called on GET /device/password?id=DEVICE-ID.
   1.159 +    Ideally this should pop up a user dialog to insert his
   1.160 +    password based the DEVICE-ID
   1.161 +    """
   1.162 +    
   1.163 +    def GET(self):
   1.164 +        
   1.165 +        # pick the arguments
   1.166 +        args = web.input()
   1.167 +        
   1.168 +        # we _need_ a device id
   1.169 +        if not "id" in args:
   1.170 +            raise web.badrequest()
   1.171 +            
   1.172 +        # invoke the user dialog as a subprocess
   1.173 +        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   1.174 +        process_command = [sys.executable, dlg_credentials_image, 'password', 'Please provide a password for accessing \ndevice: "{0}".'.format(args.id)]
   1.175 +        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   1.176 +        result = process.communicate()[0]
   1.177 +        if process.returncode != 0:
   1.178 +            return 'Credentials request has been aborted.'
   1.179 +        
   1.180 +        return result
   1.181 +
   1.182 +
   1.183 +class os_root:
   1.184 +    
   1.185 +    """OpenSecurity '/' handler"""
   1.186 +    
   1.187 +    def GET(self):
   1.188 +        return "OpenSecurity-Server { \"version\": \"%s\" }" % __version__
   1.189 +
   1.190 +
   1.191 +# start
   1.192 +if __name__ == "__main__":
   1.193 +    server = web.application(opensecurity_urls, globals())
   1.194 +    server.run()
   1.195 +
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/OpenSecurity/bin/vmmanager.py	Fri Dec 06 12:15:18 2013 +0100
     2.3 @@ -0,0 +1,325 @@
     2.4 +'''
     2.5 +Created on Nov 19, 2013
     2.6 +
     2.7 +@author: BarthaM
     2.8 +'''
     2.9 +import os
    2.10 +import os.path
    2.11 +from subprocess import Popen, PIPE, call
    2.12 +import subprocess
    2.13 +import sys
    2.14 +import re
    2.15 +
    2.16 +DEBUG = True
    2.17 +
    2.18 +class USBFilter:
    2.19 +    vendorid = ""
    2.20 +    productid = ""
    2.21 +    revision = ""
    2.22 +    
    2.23 +    def __init__(self, vendorid, productid, revision):
    2.24 +        self.vendorid = vendorid.lower()
    2.25 +        self.productid = productid.lower()
    2.26 +        self.revision = revision.lower()
    2.27 +        return
    2.28 +    
    2.29 +    def __eq__(self, other):
    2.30 +        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    2.31 +    
    2.32 +    def __hash__(self):
    2.33 +        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    2.34 +    
    2.35 +    def __repr__(self):
    2.36 +        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    2.37 +        
    2.38 +
    2.39 +class VMManager(object):
    2.40 +    vmRootName = "SecurityDVM"
    2.41 +    systemProperties = None
    2.42 +    cygwin_path = 'c:\\cygwin64\\bin\\'
    2.43 +    
    2.44 +    def __init__(self):
    2.45 +        self.systemProperties = self.getSystemProperties()
    2.46 +        #TODO: get cygwin path externally
    2.47 +        return
    2.48 +         
    2.49 +    def execute(self, cmd):
    2.50 +        if DEBUG:
    2.51 +            print('trying to launch: ' + cmd)
    2.52 +        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    2.53 +        if DEBUG:
    2.54 +            print('launched: ' + cmd)
    2.55 +        result = process.wait()
    2.56 +        res_stdout = process.stdout.read();
    2.57 +        res_stderr = process.stderr.read();
    2.58 +        if DEBUG:
    2.59 +            if res_stdout != "":
    2.60 +                print res_stdout
    2.61 +            if res_stderr != "":
    2.62 +                print res_stderr
    2.63 +        return result, res_stdout, res_stderr
    2.64 +    
    2.65 +    # return hosty system properties
    2.66 +    def getSystemProperties(self):
    2.67 +        cmd = 'VBoxManage list systemproperties'
    2.68 +        result = self.execute(cmd)
    2.69 +        if result[1]=='':
    2.70 +            return None
    2.71 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
    2.72 +        return props
    2.73 +    
    2.74 +    # return the folder containing the guest VMs     
    2.75 +    def getDefaultMachineFolder(self):
    2.76 +        return self.systemProperties["Default machine folder"]
    2.77 +    
    2.78 +    #list the hostonly IFs exposed by the VBox host
    2.79 +    def getHostOnlyIFs(self):
    2.80 +        cmd = 'VBoxManage list hostonlyifs'
    2.81 +        result = self.execute(cmd)[1]
    2.82 +        if result=='':
    2.83 +            return None
    2.84 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
    2.85 +        return props
    2.86 +        
    2.87 +    def listRSDS(self):
    2.88 +        cmd = 'VBoxManage list usbhost'
    2.89 +        results = self.execute(cmd)[1]
    2.90 +        results = results.split('Host USB Devices:')[1].strip()
    2.91 +        
    2.92 +        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
    2.93 +        rsds = dict()   
    2.94 +        for item in items:
    2.95 +            props = dict()
    2.96 +            for line in item.splitlines():
    2.97 +                if line != "":         
    2.98 +                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
    2.99 +                    props[k] = v;
   2.100 +            
   2.101 +            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   2.102 +                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   2.103 +                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   2.104 +                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   2.105 +                rsds[props['UUID']] = usb_filter;
   2.106 +                if DEBUG:
   2.107 +                    print filter
   2.108 +        return rsds
   2.109 +
   2.110 +    # list all existing VMs registered with VBox
   2.111 +    def listVM(self):
   2.112 +        cmd = 'VBoxManage list vms'
   2.113 +        result = self.execute(cmd)[1]
   2.114 +        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   2.115 +        return vms
   2.116 +    
   2.117 +    # list existing SDVMs
   2.118 +    def listSDVM(self):
   2.119 +        vms = self.listVM()
   2.120 +        svdms = []
   2.121 +        for vm in vms:
   2.122 +            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   2.123 +                svdms.append(vm)
   2.124 +        return svdms
   2.125 +    
   2.126 +    # generate valid (not already existing SDVM name). necessary for creating a new VM
   2.127 +    def generateSDVMName(self):
   2.128 +        vms = self.listVM()
   2.129 +        for i in range(0,999):
   2.130 +            if(not self.vmRootName+str(i) in vms):
   2.131 +                return self.vmRootName+str(i)
   2.132 +        return ''
   2.133 +    
   2.134 +    # return the RSDs attached to all existing SDVMs
   2.135 +    def getAttachedRSDs(self):
   2.136 +        vms = self.listSDVM()
   2.137 +        attached_devices = dict()
   2.138 +        for vm in vms:
   2.139 +            rsd_filter = self.getUSBFilter(vm)
   2.140 +            if rsd_filter != None:
   2.141 +                attached_devices[vm] = rsd_filter
   2.142 +        return attached_devices
   2.143 +    
   2.144 +    # configures hostonly networking and DHCP server. requires admin rights
   2.145 +    def configureHostNetworking(self):
   2.146 +        #cmd = 'vboxmanage list hostonlyifs'
   2.147 +        #self.execute(cmd)
   2.148 +        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   2.149 +        #self.execute(cmd)
   2.150 +        #cmd = 'vboxmanage hostonlyif create'
   2.151 +        #self.execute(cmd)
   2.152 +        cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   2.153 +        self.execute(cmd)
   2.154 +        #cmd = 'vboxmanage dhcpserver add'
   2.155 +        #self.execute(cmd)
   2.156 +        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'
   2.157 +        self.execute(cmd)
   2.158 +    
   2.159 +    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   2.160 +    def createVM(self, vm_name):
   2.161 +        hostonly_if = self.getHostOnlyIFs()
   2.162 +        machineFolder = self.getDefaultMachineFolder()
   2.163 +        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
   2.164 +        self.execute(cmd)
   2.165 +        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
   2.166 +        self.execute(cmd)
   2.167 +        cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   2.168 +        self.execute(cmd)
   2.169 +        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   2.170 +        #--mtype immutable
   2.171 +        self.execute(cmd)
   2.172 +        return
   2.173 +    
   2.174 +    #remove VM from the system. should be used on VMs returned by listSDVMs    
   2.175 +    def removeVM(self, vm_name):
   2.176 +        print('removing ' + vm_name)
   2.177 +        cmd = 'VBoxManage unregistervm', vm_name, '--delete'
   2.178 +        print self.execute(cmd)
   2.179 +        machineFolder = self.getDefaultMachineFolder()
   2.180 +        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   2.181 +        print self.execute(cmd)
   2.182 +    
   2.183 +    # start VM
   2.184 +    def startVM(self, vm_name):
   2.185 +        print('starting ' +  vm_name)
   2.186 +        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
   2.187 +        print self.execute(cmd)
   2.188 +        
   2.189 +    # stop VM    
   2.190 +    def stopVM(self, vm_name):
   2.191 +        print('stopping ' + vm_name)
   2.192 +        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
   2.193 +        print self.execute(cmd)
   2.194 +    
   2.195 +    # return the hostOnly IP for a running guest    
   2.196 +    def getHostOnlyIP(self, vm_name):
   2.197 +        print('gettting hostOnly IP address ' + vm_name)
   2.198 +        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   2.199 +        result = self.execute(cmd)
   2.200 +        if result=='':
   2.201 +            return None
   2.202 +        result = result[1]
   2.203 +        return result[result.index(':')+1:].strip()
   2.204 +    
   2.205 +    # attach removable storage device to VM by provision of filter
   2.206 +    def attachRSD(self, vm_name, rsd_filter):
   2.207 +        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   2.208 +        print self.execute(cmd)
   2.209 +        
   2.210 +    
   2.211 +    # return the description set for an existing VM
   2.212 +    def getVMInfo(self, vm_name):
   2.213 +        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
   2.214 +        results = self.execute(cmd)[1]
   2.215 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
   2.216 +        return props
   2.217 +    
   2.218 +    # return the configured USB filter for an existing VM 
   2.219 +    def getUSBFilter(self, vm_name):
   2.220 +        props = self.getVMInfo(vm_name)
   2.221 +        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   2.222 +        keyset = set(props.keys())
   2.223 +        usb_filter = None
   2.224 +        if keyset.issuperset(keys):
   2.225 +            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   2.226 +        return usb_filter
   2.227 +    
   2.228 +    #generates ISO containing authorized_keys for use with guest VM
   2.229 +    def genCertificateISO(self, vm_name):
   2.230 +        machineFolder = self.getDefaultMachineFolder()
   2.231 +        # create .ssh folder in vm_name
   2.232 +        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   2.233 +        result = self.execute(cmd)
   2.234 +        # generate dvm_key pair in vm_name / .ssh     
   2.235 +        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" |',
   2.236 +        result = self.execute(cmd)
   2.237 +        # set permissions for keys
   2.238 +        #TODO: test without chmod
   2.239 +        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   2.240 +        result = self.execute(cmd)
   2.241 +        # move out private key
   2.242 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   2.243 +        result = self.execute(cmd)
   2.244 +        # rename public key to authorized_keys
   2.245 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   2.246 +        result = self.execute(cmd)
   2.247 +        # generate iso image with .ssh/authorized keys
   2.248 +        cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   2.249 +        result = self.execute(cmd)
   2.250 +    
   2.251 +    # attaches generated ssh public cert to guest vm
   2.252 +    def attachCertificateISO(self, vm_name):
   2.253 +        machineFolder = self.getDefaultMachineFolder()
   2.254 +        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   2.255 +        result = self.execute(cmd)
   2.256 +        return result
   2.257 +    
   2.258 +    # handles device change events
   2.259 +    def handleDeviceChange(self):
   2.260 +        attached_devices = self.getAttachedRSDs()
   2.261 +        connected_devices = self.listRSDS()
   2.262 +        for vm_name in attached_devices.keys():
   2.263 +            if connected_devices and attached_devices[vm_name] not in connected_devices.values():
   2.264 +                # self.netUse(vm_name)
   2.265 +                self.stopVM(vm_name)
   2.266 +                self.removeVM(vm_name)
   2.267 +        
   2.268 +        attached_devices = self.getAttachedRSDs()
   2.269 +        for connected_device in connected_devices.values():
   2.270 +            if attached_devices or connected_device not in attached_devices.values():
   2.271 +                new_sdvm = self.generateSDVMName()
   2.272 +                self.createVM(new_sdvm)
   2.273 +                self.attachRSD(new_sdvm, connected_device)
   2.274 +                self.startVM(new_sdvm)
   2.275 +                self.netUse(new_sdvm)
   2.276 +    
   2.277 +    def handleBrowsingRequest(self):
   2.278 +        new_sdvm = self.generateSDVMName()
   2.279 +        self.createVM(new_sdvm)
   2.280 +        self.genCertificateISO(new_sdvm)
   2.281 +        self.attachCertificateISO(new_sdvm)
   2.282 +    
   2.283 +    # executes command over ssh on guest vm
   2.284 +    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   2.285 +        # get vm ip
   2.286 +        address = self.getHostOnlyIP(vm_name)
   2.287 +        machineFolder = self.getDefaultMachineFolder()
   2.288 +        # run command
   2.289 +        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   2.290 +        return self.execute(cmd)
   2.291 +    
   2.292 +    # executes command over ssh on guest vm with X forwarding
   2.293 +    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   2.294 +        #TODO: verify if X server is running on user account 
   2.295 +        #TODO: set DISPLAY accordingly
   2.296 +        address = self.getHostOnlyIP(vm_name)
   2.297 +        machineFolder = self.getDefaultMachineFolder()
   2.298 +        # run command
   2.299 +        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   2.300 +        return self.execute(cmd)    
   2.301 +        
   2.302 +    # executes NET USE and connects to samba share on guestos 
   2.303 +    def netUse(self, vm_name):
   2.304 +        ip = self.getHostOnlyIP(vm_name)
   2.305 +        cmd = 'net use H: \\' + ip + '\USB'
   2.306 +        return self.execute(cmd)
   2.307 +        
   2.308 +    
   2.309 +if __name__ == '__main__':
   2.310 +    man = VMManager()
   2.311 +    man.cygwin_path = 'c:\\cygwin64\\bin\\'
   2.312 +    #man.handleDeviceChange()
   2.313 +    #print man.listSDVM()
   2.314 +    #man.configureHostNetworking()
   2.315 +    new_vm = man.generateSDVMName()
   2.316 +    man.createVM(new_vm)
   2.317 +    man.genCertificateISO(new_vm)
   2.318 +    man.attachCertificateISO(new_vm)
   2.319 +    
   2.320 +    #man.attachCertificateISO(vm_name)
   2.321 +    #man.sshGuestExecute(vm_name, "ls")
   2.322 +    #man.sshGuestX11Execute(vm_name, "iceweasel")
   2.323 +    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   2.324 +    #man.execute(cmd)
   2.325 +    
   2.326 +    
   2.327 +
   2.328 +    
     3.1 --- a/server/opensecurityd.py	Fri Dec 06 12:10:30 2013 +0100
     3.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.3 @@ -1,192 +0,0 @@
     3.4 -#!/bin/env python
     3.5 -# -*- coding: utf-8 -*-
     3.6 -
     3.7 -# ------------------------------------------------------------
     3.8 -# opensecurityd
     3.9 -# 
    3.10 -# the opensecurityd as RESTful server
    3.11 -#
    3.12 -# Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    3.13 -#
    3.14 -# Copyright (C) 2013 AIT Austrian Institute of Technology
    3.15 -# AIT Austrian Institute of Technology GmbH
    3.16 -# Donau-City-Strasse 1 | 1220 Vienna | Austria
    3.17 -# http://www.ait.ac.at
    3.18 -#
    3.19 -# This program is free software; you can redistribute it and/or
    3.20 -# modify it under the terms of the GNU General Public License
    3.21 -# as published by the Free Software Foundation version 2.
    3.22 -# 
    3.23 -# This program is distributed in the hope that it will be useful,
    3.24 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
    3.25 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    3.26 -# GNU General Public License for more details.
    3.27 -# 
    3.28 -# You should have received a copy of the GNU General Public License
    3.29 -# along with this program; if not, write to the Free Software
    3.30 -# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    3.31 -# Boston, MA  02110-1301, USA.
    3.32 -# ------------------------------------------------------------
    3.33 -
    3.34 -
    3.35 -# ------------------------------------------------------------
    3.36 -# imports
    3.37 -
    3.38 -import os
    3.39 -import os.path
    3.40 -import subprocess
    3.41 -import sys
    3.42 -import web
    3.43 -from vmmanager.vmmanager import VMManager
    3.44 -
    3.45 -# local
    3.46 -from environment import Environment
    3.47 -
    3.48 -
    3.49 -# ------------------------------------------------------------
    3.50 -# const
    3.51 -
    3.52 -__version__ = "0.1"
    3.53 -
    3.54 -
    3.55 -"""All the URLs we know mapping to class handler"""
    3.56 -opensecurity_urls = (
    3.57 -    '/device_change',           'os_device_change',
    3.58 -    '/application',             'os_application',
    3.59 -    '/device',                  'os_device',
    3.60 -    '/device/credentials',      'os_device_credentials',
    3.61 -    '/device/password',         'os_device_password',
    3.62 -    '/',                        'os_root'
    3.63 -)
    3.64 -
    3.65 -
    3.66 -# ------------------------------------------------------------
    3.67 -# code
    3.68 -
    3.69 -gvm_mgr = VMManager()
    3.70 -
    3.71 -
    3.72 -class os_application:
    3.73 -    
    3.74 -    """OpenSecurity '/application' handler.
    3.75 -    
    3.76 -    This is called on GET /application?vm=VM-ID&app=APP-ID
    3.77 -    This tries to access the vm identified with the label VM-ID
    3.78 -    and launched the application identified APP-ID
    3.79 -    """
    3.80 -    
    3.81 -    def GET(self):
    3.82 -        
    3.83 -        # pick the arguments
    3.84 -        args = web.input()
    3.85 -        
    3.86 -        # we _need_ a vm
    3.87 -        if not "vm" in args:
    3.88 -            raise web.badrequest()
    3.89 -        
    3.90 -        # we _need_ a app
    3.91 -        if not "app" in args:
    3.92 -            raise web.badrequest()
    3.93 -        
    3.94 -        ## TODO: HARD CODED STUFF HERE! THIS SHOULD BE FLEXIBLE!
    3.95 -        ssh_private_key = os.path.join(Environment("opensecurity").data_path, 'share', '192.168.56.15.ppk')
    3.96 -        putty_session = '192.168.56.15'
    3.97 -        process_command = ['plink.exe', '-i', ssh_private_key, putty_session, args.app]
    3.98 -        si = subprocess.STARTUPINFO()
    3.99 -        si.dwFlags = subprocess.STARTF_USESHOWWINDOW
   3.100 -        si.wShowWindow = subprocess.SW_HIDE
   3.101 -        print('tyring to launch: ' + ' '.join(process_command))
   3.102 -        process = subprocess.Popen(process_command, shell = True)
   3.103 -        return 'launched: ' + ' '.join(process_command)
   3.104 -
   3.105 -class os_device:
   3.106 -    
   3.107 -    """OpenSecurity '/device' handler"""
   3.108 -    
   3.109 -    def GET(self):
   3.110 -        return "os_device"
   3.111 -
   3.112 -class os_device_change:
   3.113 -    
   3.114 -    """OpenSecurity '/device_change' handler"""
   3.115 -    
   3.116 -    def GET(self):
   3.117 -        print 'received device_change'
   3.118 -        gvm_mgr.cygwin_path = 'c:\\cygwin64\\bin\\'
   3.119 -        gvm_mgr.handleDeviceChange()
   3.120 -        
   3.121 -        #gvm_mgr.configureHostNetworking()
   3.122 -        return "os_device_change"
   3.123 -
   3.124 -
   3.125 -class os_device_credentials:
   3.126 -    
   3.127 -    """OpenSecurity '/device/credentials' handler.
   3.128 -    
   3.129 -    This is called on GET /device/credentials?id=DEVICE-ID.
   3.130 -    Ideally this should pop up a user dialog to insert his
   3.131 -    credentials based the DEVICE-ID
   3.132 -    """
   3.133 -    
   3.134 -    def GET(self):
   3.135 -        
   3.136 -        # pick the arguments
   3.137 -        args = web.input()
   3.138 -        
   3.139 -        # we _need_ a device id
   3.140 -        if not "id" in args:
   3.141 -            raise web.badrequest()
   3.142 -        
   3.143 -        # invoke the user dialog as a subprocess
   3.144 -        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   3.145 -        process_command = [sys.executable, dlg_credentials_image, 'credentials', 'Please provide credentials for accessing \ndevice: "{0}".'.format(args.id)]
   3.146 -        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   3.147 -        result = process.communicate()[0]
   3.148 -        if process.returncode != 0:
   3.149 -            return 'Credentials request has been aborted.'
   3.150 -        
   3.151 -        return result
   3.152 -
   3.153 -
   3.154 -class os_device_password:
   3.155 -    
   3.156 -    """OpenSecurity '/device/password' handler.
   3.157 -    
   3.158 -    This is called on GET /device/password?id=DEVICE-ID.
   3.159 -    Ideally this should pop up a user dialog to insert his
   3.160 -    password based the DEVICE-ID
   3.161 -    """
   3.162 -    
   3.163 -    def GET(self):
   3.164 -        
   3.165 -        # pick the arguments
   3.166 -        args = web.input()
   3.167 -        
   3.168 -        # we _need_ a device id
   3.169 -        if not "id" in args:
   3.170 -            raise web.badrequest()
   3.171 -            
   3.172 -        # invoke the user dialog as a subprocess
   3.173 -        dlg_credentials_image = os.path.join(sys.path[0], 'opensecurity-dialog.py')
   3.174 -        process_command = [sys.executable, dlg_credentials_image, 'password', 'Please provide a password for accessing \ndevice: "{0}".'.format(args.id)]
   3.175 -        process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
   3.176 -        result = process.communicate()[0]
   3.177 -        if process.returncode != 0:
   3.178 -            return 'Credentials request has been aborted.'
   3.179 -        
   3.180 -        return result
   3.181 -
   3.182 -
   3.183 -class os_root:
   3.184 -    
   3.185 -    """OpenSecurity '/' handler"""
   3.186 -    
   3.187 -    def GET(self):
   3.188 -        return "OpenSecurity-Server { \"version\": \"%s\" }" % __version__
   3.189 -
   3.190 -
   3.191 -# start
   3.192 -if __name__ == "__main__":
   3.193 -    server = web.application(opensecurity_urls, globals())
   3.194 -    server.run()
   3.195 -
     4.1 --- a/server/vmmanager/vmmanager.py	Fri Dec 06 12:10:30 2013 +0100
     4.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.3 @@ -1,325 +0,0 @@
     4.4 -'''
     4.5 -Created on Nov 19, 2013
     4.6 -
     4.7 -@author: BarthaM
     4.8 -'''
     4.9 -import os
    4.10 -import os.path
    4.11 -from subprocess import Popen, PIPE, call
    4.12 -import subprocess
    4.13 -import sys
    4.14 -import re
    4.15 -
    4.16 -DEBUG = True
    4.17 -
    4.18 -class USBFilter:
    4.19 -    vendorid = ""
    4.20 -    productid = ""
    4.21 -    revision = ""
    4.22 -    
    4.23 -    def __init__(self, vendorid, productid, revision):
    4.24 -        self.vendorid = vendorid.lower()
    4.25 -        self.productid = productid.lower()
    4.26 -        self.revision = revision.lower()
    4.27 -        return
    4.28 -    
    4.29 -    def __eq__(self, other):
    4.30 -        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    4.31 -    
    4.32 -    def __hash__(self):
    4.33 -        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    4.34 -    
    4.35 -    def __repr__(self):
    4.36 -        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    4.37 -        
    4.38 -
    4.39 -class VMManager(object):
    4.40 -    vmRootName = "SecurityDVM"
    4.41 -    systemProperties = None
    4.42 -    cygwin_path = 'c:\\cygwin64\\bin\\'
    4.43 -    
    4.44 -    def __init__(self):
    4.45 -        self.systemProperties = self.getSystemProperties()
    4.46 -        #TODO: get cygwin path externally
    4.47 -        return
    4.48 -         
    4.49 -    def execute(self, cmd):
    4.50 -        if DEBUG:
    4.51 -            print('trying to launch: ' + cmd)
    4.52 -        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    4.53 -        if DEBUG:
    4.54 -            print('launched: ' + cmd)
    4.55 -        result = process.wait()
    4.56 -        res_stdout = process.stdout.read();
    4.57 -        res_stderr = process.stderr.read();
    4.58 -        if DEBUG:
    4.59 -            if res_stdout != "":
    4.60 -                print res_stdout
    4.61 -            if res_stderr != "":
    4.62 -                print res_stderr
    4.63 -        return result, res_stdout, res_stderr
    4.64 -    
    4.65 -    # return hosty system properties
    4.66 -    def getSystemProperties(self):
    4.67 -        cmd = 'VBoxManage list systemproperties'
    4.68 -        result = self.execute(cmd)
    4.69 -        if result[1]=='':
    4.70 -            return None
    4.71 -        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
    4.72 -        return props
    4.73 -    
    4.74 -    # return the folder containing the guest VMs     
    4.75 -    def getDefaultMachineFolder(self):
    4.76 -        return self.systemProperties["Default machine folder"]
    4.77 -    
    4.78 -    #list the hostonly IFs exposed by the VBox host
    4.79 -    def getHostOnlyIFs(self):
    4.80 -        cmd = 'VBoxManage list hostonlyifs'
    4.81 -        result = self.execute(cmd)[1]
    4.82 -        if result=='':
    4.83 -            return None
    4.84 -        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
    4.85 -        return props
    4.86 -        
    4.87 -    def listRSDS(self):
    4.88 -        cmd = 'VBoxManage list usbhost'
    4.89 -        results = self.execute(cmd)[1]
    4.90 -        results = results.split('Host USB Devices:')[1].strip()
    4.91 -        
    4.92 -        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
    4.93 -        rsds = dict()   
    4.94 -        for item in items:
    4.95 -            props = dict()
    4.96 -            for line in item.splitlines():
    4.97 -                if line != "":         
    4.98 -                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
    4.99 -                    props[k] = v;
   4.100 -            
   4.101 -            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   4.102 -                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   4.103 -                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   4.104 -                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   4.105 -                rsds[props['UUID']] = usb_filter;
   4.106 -                if DEBUG:
   4.107 -                    print filter
   4.108 -        return rsds
   4.109 -
   4.110 -    # list all existing VMs registered with VBox
   4.111 -    def listVM(self):
   4.112 -        cmd = 'VBoxManage list vms'
   4.113 -        result = self.execute(cmd)[1]
   4.114 -        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   4.115 -        return vms
   4.116 -    
   4.117 -    # list existing SDVMs
   4.118 -    def listSDVM(self):
   4.119 -        vms = self.listVM()
   4.120 -        svdms = []
   4.121 -        for vm in vms:
   4.122 -            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   4.123 -                svdms.append(vm)
   4.124 -        return svdms
   4.125 -    
   4.126 -    # generate valid (not already existing SDVM name). necessary for creating a new VM
   4.127 -    def generateSDVMName(self):
   4.128 -        vms = self.listVM()
   4.129 -        for i in range(0,999):
   4.130 -            if(not self.vmRootName+str(i) in vms):
   4.131 -                return self.vmRootName+str(i)
   4.132 -        return ''
   4.133 -    
   4.134 -    # return the RSDs attached to all existing SDVMs
   4.135 -    def getAttachedRSDs(self):
   4.136 -        vms = self.listSDVM()
   4.137 -        attached_devices = dict()
   4.138 -        for vm in vms:
   4.139 -            rsd_filter = self.getUSBFilter(vm)
   4.140 -            if rsd_filter != None:
   4.141 -                attached_devices[vm] = rsd_filter
   4.142 -        return attached_devices
   4.143 -    
   4.144 -    # configures hostonly networking and DHCP server. requires admin rights
   4.145 -    def configureHostNetworking(self):
   4.146 -        #cmd = 'vboxmanage list hostonlyifs'
   4.147 -        #self.execute(cmd)
   4.148 -        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   4.149 -        #self.execute(cmd)
   4.150 -        #cmd = 'vboxmanage hostonlyif create'
   4.151 -        #self.execute(cmd)
   4.152 -        cmd = 'vboxmanage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   4.153 -        self.execute(cmd)
   4.154 -        #cmd = 'vboxmanage dhcpserver add'
   4.155 -        #self.execute(cmd)
   4.156 -        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'
   4.157 -        self.execute(cmd)
   4.158 -    
   4.159 -    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   4.160 -    def createVM(self, vm_name):
   4.161 -        hostonly_if = self.getHostOnlyIFs()
   4.162 -        machineFolder = self.getDefaultMachineFolder()
   4.163 -        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
   4.164 -        self.execute(cmd)
   4.165 -        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
   4.166 -        self.execute(cmd)
   4.167 -        cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   4.168 -        self.execute(cmd)
   4.169 -        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   4.170 -        #--mtype immutable
   4.171 -        self.execute(cmd)
   4.172 -        return
   4.173 -    
   4.174 -    #remove VM from the system. should be used on VMs returned by listSDVMs    
   4.175 -    def removeVM(self, vm_name):
   4.176 -        print('removing ' + vm_name)
   4.177 -        cmd = 'VBoxManage unregistervm', vm_name, '--delete'
   4.178 -        print self.execute(cmd)
   4.179 -        machineFolder = self.getDefaultMachineFolder()
   4.180 -        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   4.181 -        print self.execute(cmd)
   4.182 -    
   4.183 -    # start VM
   4.184 -    def startVM(self, vm_name):
   4.185 -        print('starting ' +  vm_name)
   4.186 -        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
   4.187 -        print self.execute(cmd)
   4.188 -        
   4.189 -    # stop VM    
   4.190 -    def stopVM(self, vm_name):
   4.191 -        print('stopping ' + vm_name)
   4.192 -        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
   4.193 -        print self.execute(cmd)
   4.194 -    
   4.195 -    # return the hostOnly IP for a running guest    
   4.196 -    def getHostOnlyIP(self, vm_name):
   4.197 -        print('gettting hostOnly IP address ' + vm_name)
   4.198 -        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   4.199 -        result = self.execute(cmd)
   4.200 -        if result=='':
   4.201 -            return None
   4.202 -        result = result[1]
   4.203 -        return result[result.index(':')+1:].strip()
   4.204 -    
   4.205 -    # attach removable storage device to VM by provision of filter
   4.206 -    def attachRSD(self, vm_name, rsd_filter):
   4.207 -        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   4.208 -        print self.execute(cmd)
   4.209 -        
   4.210 -    
   4.211 -    # return the description set for an existing VM
   4.212 -    def getVMInfo(self, vm_name):
   4.213 -        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
   4.214 -        results = self.execute(cmd)[1]
   4.215 -        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
   4.216 -        return props
   4.217 -    
   4.218 -    # return the configured USB filter for an existing VM 
   4.219 -    def getUSBFilter(self, vm_name):
   4.220 -        props = self.getVMInfo(vm_name)
   4.221 -        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   4.222 -        keyset = set(props.keys())
   4.223 -        usb_filter = None
   4.224 -        if keyset.issuperset(keys):
   4.225 -            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   4.226 -        return usb_filter
   4.227 -    
   4.228 -    #generates ISO containing authorized_keys for use with guest VM
   4.229 -    def genCertificateISO(self, vm_name):
   4.230 -        machineFolder = self.getDefaultMachineFolder()
   4.231 -        # create .ssh folder in vm_name
   4.232 -        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   4.233 -        result = self.execute(cmd)
   4.234 -        # generate dvm_key pair in vm_name / .ssh     
   4.235 -        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" |',
   4.236 -        result = self.execute(cmd)
   4.237 -        # set permissions for keys
   4.238 -        #TODO: test without chmod
   4.239 -        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   4.240 -        result = self.execute(cmd)
   4.241 -        # move out private key
   4.242 -        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   4.243 -        result = self.execute(cmd)
   4.244 -        # rename public key to authorized_keys
   4.245 -        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   4.246 -        result = self.execute(cmd)
   4.247 -        # generate iso image with .ssh/authorized keys
   4.248 -        cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   4.249 -        result = self.execute(cmd)
   4.250 -    
   4.251 -    # attaches generated ssh public cert to guest vm
   4.252 -    def attachCertificateISO(self, vm_name):
   4.253 -        machineFolder = self.getDefaultMachineFolder()
   4.254 -        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   4.255 -        result = self.execute(cmd)
   4.256 -        return result
   4.257 -    
   4.258 -    # handles device change events
   4.259 -    def handleDeviceChange(self):
   4.260 -        attached_devices = self.getAttachedRSDs()
   4.261 -        connected_devices = self.listRSDS()
   4.262 -        for vm_name in attached_devices.keys():
   4.263 -            if connected_devices and attached_devices[vm_name] not in connected_devices.values():
   4.264 -                # self.netUse(vm_name)
   4.265 -                self.stopVM(vm_name)
   4.266 -                self.removeVM(vm_name)
   4.267 -        
   4.268 -        attached_devices = self.getAttachedRSDs()
   4.269 -        for connected_device in connected_devices.values():
   4.270 -            if attached_devices or connected_device not in attached_devices.values():
   4.271 -                new_sdvm = self.generateSDVMName()
   4.272 -                self.createVM(new_sdvm)
   4.273 -                self.attachRSD(new_sdvm, connected_device)
   4.274 -                self.startVM(new_sdvm)
   4.275 -                self.netUse(new_sdvm)
   4.276 -    
   4.277 -    def handleBrowsingRequest(self):
   4.278 -        new_sdvm = self.generateSDVMName()
   4.279 -        self.createVM(new_sdvm)
   4.280 -        self.genCertificateISO(new_sdvm)
   4.281 -        self.attachCertificateISO(new_sdvm)
   4.282 -    
   4.283 -    # executes command over ssh on guest vm
   4.284 -    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   4.285 -        # get vm ip
   4.286 -        address = self.getHostOnlyIP(vm_name)
   4.287 -        machineFolder = self.getDefaultMachineFolder()
   4.288 -        # run command
   4.289 -        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   4.290 -        return self.execute(cmd)
   4.291 -    
   4.292 -    # executes command over ssh on guest vm with X forwarding
   4.293 -    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   4.294 -        #TODO: verify if X server is running on user account 
   4.295 -        #TODO: set DISPLAY accordingly
   4.296 -        address = self.getHostOnlyIP(vm_name)
   4.297 -        machineFolder = self.getDefaultMachineFolder()
   4.298 -        # run command
   4.299 -        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   4.300 -        return self.execute(cmd)    
   4.301 -        
   4.302 -    # executes NET USE and connects to samba share on guestos 
   4.303 -    def netUse(self, vm_name):
   4.304 -        ip = self.getHostOnlyIP(vm_name)
   4.305 -        cmd = 'net use H: \\' + ip + '\USB'
   4.306 -        return self.execute(cmd)
   4.307 -        
   4.308 -    
   4.309 -if __name__ == '__main__':
   4.310 -    man = VMManager()
   4.311 -    man.cygwin_path = 'c:\\cygwin64\\bin\\'
   4.312 -    #man.handleDeviceChange()
   4.313 -    #print man.listSDVM()
   4.314 -    #man.configureHostNetworking()
   4.315 -    new_vm = man.generateSDVMName()
   4.316 -    man.createVM(new_vm)
   4.317 -    man.genCertificateISO(new_vm)
   4.318 -    man.attachCertificateISO(new_vm)
   4.319 -    
   4.320 -    #man.attachCertificateISO(vm_name)
   4.321 -    #man.sshGuestExecute(vm_name, "ls")
   4.322 -    #man.sshGuestX11Execute(vm_name, "iceweasel")
   4.323 -    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   4.324 -    #man.execute(cmd)
   4.325 -    
   4.326 -    
   4.327 -
   4.328 -