added registry VirtualBox path reading
authorom
Fri, 06 Dec 2013 12:52:34 +0100
changeset 193111f077646d
parent 18 d7d7b8dee78e
child 20 85571680438a
added registry VirtualBox path reading
OpenSecurity/bin/vmmanager.py
OpenSecurity/bin/vmmanager/PKG-INFO
OpenSecurity/bin/vmmanager/__init__.py
OpenSecurity/bin/vmmanager/vmmanager.py
     1.1 --- a/OpenSecurity/bin/vmmanager.py	Fri Dec 06 12:47:53 2013 +0100
     1.2 +++ b/OpenSecurity/bin/vmmanager.py	Fri Dec 06 12:52:34 2013 +0100
     1.3 @@ -9,8 +9,10 @@
     1.4  import subprocess
     1.5  import sys
     1.6  import re
     1.7 +import _winreg
     1.8  from cygwin import Cygwin
     1.9  
    1.10 +
    1.11  DEBUG = True
    1.12  
    1.13  class USBFilter:
    1.14 @@ -38,10 +40,12 @@
    1.15      vmRootName = "SecurityDVM"
    1.16      systemProperties = None
    1.17      cygwin_path = 'c:\\cygwin64\\bin\\'
    1.18 +    vboxManage = 'VBoxManage'
    1.19      
    1.20      def __init__(self):
    1.21          self.systemProperties = self.getSystemProperties()
    1.22          self.cygwin_path = Cygwin.root()
    1.23 +        self.vboxManage = os.path.join(getVBoxManagePath, 'VBoxManage')
    1.24          return
    1.25           
    1.26      def execute(self, cmd):
    1.27 @@ -60,6 +64,17 @@
    1.28                  print res_stderr
    1.29          return result, res_stdout, res_stderr
    1.30      
    1.31 +    def getVBoxManagePath(self):
    1.32 +        """get the path to the VirtualBox installation on this system"""
    1.33 +        p = None
    1.34 +        try:
    1.35 +            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    1.36 +            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    1.37 +            _winreg.CloseKey(k)
    1.38 +        except:
    1.39 +            pass
    1.40 +        return p
    1.41 +    
    1.42      # return hosty system properties
    1.43      def getSystemProperties(self):
    1.44          cmd = 'VBoxManage list systemproperties'
     2.1 --- a/OpenSecurity/bin/vmmanager/PKG-INFO	Fri Dec 06 12:47:53 2013 +0100
     2.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.3 @@ -1,10 +0,0 @@
     2.4 -Metadata-Version: 1.0
     2.5 -Name: vmmanager.py
     2.6 -Version: 0.1
     2.7 -Summary: vmmanager.py: manages GustVM's
     2.8 -Home-page:  http://webpy.org/
     2.9 -Author: Mihai Bartha
    2.10 -Author-email: mihai.bartha@ait.ac.at
    2.11 -License: Public domain
    2.12 -Description: Module to manage virtualbox guests and host
    2.13 -Platform: any
     3.1 --- a/OpenSecurity/bin/vmmanager/__init__.py	Fri Dec 06 12:47:53 2013 +0100
     3.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.3 @@ -1,6 +0,0 @@
     3.4 -__version__ = "0.1"
     3.5 -__author__ = [
     3.6 -    "Mihai Bartha <mihai.bartha@ait.ac.at>"
     3.7 -]
     3.8 -__license__ = "public domain"
     3.9 -__contributors__ = "OpenSecurity Consortium"
    3.10 \ No newline at end of file
     4.1 --- a/OpenSecurity/bin/vmmanager/vmmanager.py	Fri Dec 06 12:47:53 2013 +0100
     4.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.3 @@ -1,342 +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 -from cygwin import Cygwin
    4.16 -import _winreg
    4.17 -
    4.18 -DEBUG = True
    4.19 -
    4.20 -class USBFilter:
    4.21 -    vendorid = ""
    4.22 -    productid = ""
    4.23 -    revision = ""
    4.24 -    
    4.25 -    def __init__(self, vendorid, productid, revision):
    4.26 -        self.vendorid = vendorid.lower()
    4.27 -        self.productid = productid.lower()
    4.28 -        self.revision = revision.lower()
    4.29 -        return
    4.30 -    
    4.31 -    def __eq__(self, other):
    4.32 -        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    4.33 -    
    4.34 -    def __hash__(self):
    4.35 -        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    4.36 -    
    4.37 -    def __repr__(self):
    4.38 -        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    4.39 -        
    4.40 -
    4.41 -class VMManager(object):
    4.42 -    """Manage Virtual Machines"""
    4.43 -
    4.44 -    vmRootName = "SecurityDVM"
    4.45 -    
    4.46 -    def __init__(self):
    4.47 -        self.vBoxPath = self.getVBoxManagePath()
    4.48 -        self.vBoxManage = os.path.join(self.vBoxPath, 'VBoxManage.exe')
    4.49 -        self.systemProperties = self.getSystemProperties()
    4.50 -        self.cygwin_path = Cygwin.root()
    4.51 -        return
    4.52 -         
    4.53 -    def execute(self, cmd):
    4.54 -        """execute a command"""
    4.55 -    
    4.56 -        # we can handle strings and lists as input
    4.57 -        c = cmd
    4.58 -        if type(cmd) == list:
    4.59 -            c = ' '.join(cmd)
    4.60 -    
    4.61 -        if DEBUG:
    4.62 -            sys.stderr.write('trying to launch: ' + c + '\n')
    4.63 -        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    4.64 -        if DEBUG:
    4.65 -            sys.stderr.write('launched: ' + c + '\n')
    4.66 -            
    4.67 -        result = process.wait()
    4.68 -        res_stdout = process.stdout.read();
    4.69 -        res_stderr = process.stderr.read();
    4.70 -        if DEBUG:
    4.71 -            if res_stdout != "":
    4.72 -                print res_stdout
    4.73 -            if res_stderr != "":
    4.74 -                print res_stderr
    4.75 -        return result, res_stdout, res_stderr
    4.76 -    
    4.77 -    
    4.78 -    def getVBoxManagePath(self):
    4.79 -        """get the path to the VirtualBox installation on this system"""
    4.80 -        p = None
    4.81 -        try:
    4.82 -            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    4.83 -            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    4.84 -            _winreg.CloseKey(k)
    4.85 -        except:
    4.86 -            pass
    4.87 -        return p
    4.88 -    
    4.89 -    # return host system properties
    4.90 -    def getSystemProperties(self):
    4.91 -        cmd = [self.vBoxManage, 'list', 'systemproperties']
    4.92 -        result = self.execute(cmd)
    4.93 -        if result[1]=='':
    4.94 -            return None
    4.95 -        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
    4.96 -        return props
    4.97 -    
    4.98 -    # return the folder containing the guest VMs     
    4.99 -    def getDefaultMachineFolder(self):
   4.100 -        return self.systemProperties["Default machine folder"]
   4.101 -    
   4.102 -    #list the hostonly IFs exposed by the VBox host
   4.103 -    def getHostOnlyIFs(self):
   4.104 -        cmd = [self.vBoxManage, 'list', 'hostonlyifs']
   4.105 -        result = self.execute(cmd)[1]
   4.106 -        if result=='':
   4.107 -            return None
   4.108 -        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
   4.109 -        return props
   4.110 -        
   4.111 -    def listRSDS(self):
   4.112 -        cmd = [self.vBoxManage, 'list', 'usbhost']
   4.113 -        results = self.execute(cmd)
   4.114 -        results = results.split('Host USB Devices:')[1].strip()
   4.115 -        
   4.116 -        items = list( "UUID:" + result for result in results.split('UUID:') if result != '')
   4.117 -        rsds = dict()   
   4.118 -        for item in items:
   4.119 -            props = dict()
   4.120 -            for line in item.splitlines():
   4.121 -                if line != "":         
   4.122 -                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   4.123 -                    props[k] = v;
   4.124 -            
   4.125 -            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   4.126 -                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   4.127 -                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   4.128 -                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   4.129 -                rsds[props['UUID']] = usb_filter;
   4.130 -                if DEBUG:
   4.131 -                    print filter
   4.132 -        return rsds
   4.133 -
   4.134 -    # list all existing VMs registered with VBox
   4.135 -    def listVM(self):
   4.136 -        cmd = [self.vBoxManage, 'list', 'vms']
   4.137 -        result = self.execute(cmd)[1]
   4.138 -        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   4.139 -        return vms
   4.140 -    
   4.141 -    # list existing SDVMs
   4.142 -    def listSDVM(self):
   4.143 -        vms = self.listVM()
   4.144 -        svdms = []
   4.145 -        for vm in vms:
   4.146 -            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   4.147 -                svdms.append(vm)
   4.148 -        return svdms
   4.149 -    
   4.150 -    # generate valid (not already existing SDVM name). necessary for creating a new VM
   4.151 -    def generateSDVMName(self):
   4.152 -        vms = self.listVM()
   4.153 -        for i in range(0,999):
   4.154 -            if(not self.vmRootName+str(i) in vms):
   4.155 -                return self.vmRootName+str(i)
   4.156 -        return ''
   4.157 -    
   4.158 -    # return the RSDs attached to all existing SDVMs
   4.159 -    def getAttachedRSDs(self):
   4.160 -        vms = self.listSDVM()
   4.161 -        attached_devices = dict()
   4.162 -        for vm in vms:
   4.163 -            rsd_filter = self.getUSBFilter(vm)
   4.164 -            if filter != None:
   4.165 -                attached_devices[vm] = rsd_filter
   4.166 -        return attached_devices
   4.167 -    
   4.168 -    # configures hostonly networking and DHCP server. requires admin rights
   4.169 -    def configureHostNetworking(self):
   4.170 -        #cmd = 'vboxmanage list hostonlyifs'
   4.171 -        #self.execute(cmd)
   4.172 -        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   4.173 -        #self.execute(cmd)
   4.174 -        #cmd = 'vboxmanage hostonlyif create'
   4.175 -        #self.execute(cmd)
   4.176 -        cmd = self.vBoxManage + ' hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   4.177 -        self.execute(cmd)
   4.178 -        #cmd = 'vboxmanage dhcpserver add'
   4.179 -        #self.execute(cmd)
   4.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'
   4.181 -        self.execute(cmd)
   4.182 -    
   4.183 -    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   4.184 -    def createVM(self, vm_name):
   4.185 -        hostonly_if = self.getHostOnlyIFs()
   4.186 -        machineFolder = self.getDefaultMachineFolder()
   4.187 -        cmd = self.vBoxManage + ' createvm --name ' + vm_name + ' --ostype Debian --register'
   4.188 -        self.execute(cmd)
   4.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' 
   4.190 -        self.execute(cmd)
   4.191 -        cmd = self.vBoxManage + ' storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   4.192 -        self.execute(cmd)
   4.193 -        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --mtype normal --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   4.194 -        self.execute(cmd)
   4.195 -        return
   4.196 -    
   4.197 -    #remove VM from the system. should be used on VMs returned by listSDVMs    
   4.198 -    def removeVM(self, vm_name):
   4.199 -        print('removing ' + vm_name)
   4.200 -        cmd = self.vBoxManage + ' unregistervm', vm_name, '--delete'
   4.201 -        print self.execute(cmd)
   4.202 -        machineFolder = self.getDefaultMachineFolder()
   4.203 -        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   4.204 -        print self.execute(cmd)
   4.205 -    
   4.206 -    # start VM
   4.207 -    def startVM(self, vm_name):
   4.208 -        print('starting ' +  vm_name)
   4.209 -        cmd = self.vBoxManage + ' startvm ' + vm_name + ' --type headless'
   4.210 -        print self.execute(cmd)
   4.211 -        
   4.212 -    # stop VM    
   4.213 -    def stopVM(self, vm_name):
   4.214 -        print('stopping ' + vm_name)
   4.215 -        cmd = self.vBoxManage + ' controlvm ' + vm_name + ' poweroff'
   4.216 -        print self.execute(cmd)
   4.217 -    
   4.218 -    # return the hostOnly IP for a running guest    
   4.219 -    def getHostOnlyIP(self, vm_name):
   4.220 -        print('gettting hostOnly IP address ' + vm_name)
   4.221 -        cmd = self.vBoxManage + ' guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   4.222 -        result = self.execute(cmd)
   4.223 -        if result=='':
   4.224 -            return None
   4.225 -        result = result[1]
   4.226 -        return result[result.index(':')+1:].strip()
   4.227 -    
   4.228 -    # attach removable storage device to VM by provision of filter
   4.229 -    def attachRSD(self, vm_name, rsd_filter):
   4.230 -        cmd = self.vBoxManage + ' usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   4.231 -        print self.execute(cmd)
   4.232 -        
   4.233 -    
   4.234 -    # return the description set for an existing VM
   4.235 -    def getVMInfo(self, vm_name):
   4.236 -        cmd = self.vBoxManage + ' showvminfo ' + vm_name + ' --machinereadable'
   4.237 -        r, o, e = self.execute(cmd)
   4.238 -        props = dict((k.strip(),v.strip().strip('"')) for k, v in (line.split('=', 1) for line in o.splitlines()))
   4.239 -        return props
   4.240 -    
   4.241 -    # return the configured USB filter for an existing VM 
   4.242 -    def getUSBFilter(self, vm_name):
   4.243 -        props = self.getVMInfo(vm_name)
   4.244 -        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   4.245 -        keyset = set(props.keys())
   4.246 -        usb_filter = None
   4.247 -        if keyset.issuperset(keys):
   4.248 -            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   4.249 -        return usb_filter
   4.250 -    
   4.251 -    #generates ISO containing authorized_keys for use with guest VM
   4.252 -    def genCertificateISO(self, vm_name):
   4.253 -        machineFolder = self.getDefaultMachineFolder()
   4.254 -        # create .ssh folder in vm_name
   4.255 -        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   4.256 -        result = self.execute(cmd)
   4.257 -        # generate dvm_key pair in vm_name / .ssh     
   4.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" |',
   4.259 -        result = self.execute(cmd)
   4.260 -        # set permissions for keys
   4.261 -        #TODO: test without chmod
   4.262 -        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   4.263 -        result = self.execute(cmd)
   4.264 -        # move out private key
   4.265 -        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   4.266 -        result = self.execute(cmd)
   4.267 -        # rename public key to authorized_keys
   4.268 -        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   4.269 -        result = self.execute(cmd)
   4.270 -        # generate iso image with .ssh/authorized keys
   4.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\\\"\"'
   4.272 -        result = self.execute(cmd)
   4.273 -    
   4.274 -    # attaches generated ssh public cert to guest vm
   4.275 -    def attachCertificateISO(self, vm_name):
   4.276 -        machineFolder = self.getDefaultMachineFolder()
   4.277 -        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   4.278 -        result = self.execute(cmd)
   4.279 -        return result
   4.280 -    
   4.281 -    # handles device change events
   4.282 -    def handleDeviceChange(self):
   4.283 -        attached_devices = self.getAttachedRSDs()
   4.284 -        connected_devices = self.listRSDS()
   4.285 -        for vm_name in attached_devices.keys():
   4.286 -            if attached_devices[vm_name] not in connected_devices.values():
   4.287 -                self.stopVM(vm_name)
   4.288 -                self.removeVM(vm_name)
   4.289 -        
   4.290 -        attached_devices = self.getAttachedRSDs()
   4.291 -        for connected_device in connected_devices.values():
   4.292 -            if connected_device not in attached_devices.values():
   4.293 -                new_sdvm = self.generateSDVMName()
   4.294 -                self.createVM(new_sdvm)
   4.295 -                self.genCertificateISO(new_sdvm)
   4.296 -                self.attachCertificateISO(new_sdvm)
   4.297 -                self.attachRSD(new_sdvm, connected_device)
   4.298 -                self.startVM(new_sdvm)
   4.299 -    
   4.300 -    # executes command over ssh on guest vm
   4.301 -    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   4.302 -        # get vm ip
   4.303 -        address = self.getHostOnlyIP(vm_name)
   4.304 -        machineFolder = self.getDefaultMachineFolder()
   4.305 -        # run command
   4.306 -        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   4.307 -        return self.execute(cmd)
   4.308 -    
   4.309 -    # executes command over ssh on guest vm with X forwarding
   4.310 -    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   4.311 -        #TODO: verify if X server is running on user account 
   4.312 -        #TODO: set DISPLAY accordingly
   4.313 -        address = self.getHostOnlyIP(vm_name)
   4.314 -        machineFolder = self.getDefaultMachineFolder()
   4.315 -        # run command
   4.316 -        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   4.317 -        return self.execute(cmd)    
   4.318 -        
   4.319 -    # executes NET USE and connects to samba share on guestos 
   4.320 -    def netUse(self, vm_name):
   4.321 -        ip = self.getHostOnlyIP(vm_name)
   4.322 -        cmd = 'net use H: \\' + ip + '\RSD_Device'
   4.323 -        return self.execute(cmd)
   4.324 -        
   4.325 -    
   4.326 -if __name__ == '__main__':
   4.327 -    man = VMManager()
   4.328 -    man.cygwin_path = 'c:\\cygwin64\\bin\\'
   4.329 -    #man.handleDeviceChange()
   4.330 -    #print man.listSDVM()
   4.331 -    #man.configureHostNetworking()
   4.332 -    new_vm = man.generateSDVMName()
   4.333 -    man.createVM(new_vm)
   4.334 -    man.genCertificateISO(new_vm)
   4.335 -    man.attachCertificateISO(new_vm)
   4.336 -    
   4.337 -    #man.attachCertificateISO(vm_name)
   4.338 -    #man.sshGuestExecute(vm_name, "ls")
   4.339 -    #man.sshGuestX11Execute(vm_name, "iceweasel")
   4.340 -    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   4.341 -    #man.execute(cmd)
   4.342 -    
   4.343 -    
   4.344 -
   4.345 -