OpenSecurity/bin/vmmanager/vmmanager.py
changeset 13 4457d7071a23
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/OpenSecurity/bin/vmmanager/vmmanager.py	Fri Dec 06 10:51:15 2013 +0100
     1.3 @@ -0,0 +1,342 @@
     1.4 +'''
     1.5 +Created on Nov 19, 2013
     1.6 +
     1.7 +@author: BarthaM
     1.8 +'''
     1.9 +import os
    1.10 +import os.path
    1.11 +from subprocess import Popen, PIPE, call
    1.12 +import subprocess
    1.13 +import sys
    1.14 +import re
    1.15 +from cygwin import Cygwin
    1.16 +import _winreg
    1.17 +
    1.18 +DEBUG = True
    1.19 +
    1.20 +class USBFilter:
    1.21 +    vendorid = ""
    1.22 +    productid = ""
    1.23 +    revision = ""
    1.24 +    
    1.25 +    def __init__(self, vendorid, productid, revision):
    1.26 +        self.vendorid = vendorid.lower()
    1.27 +        self.productid = productid.lower()
    1.28 +        self.revision = revision.lower()
    1.29 +        return
    1.30 +    
    1.31 +    def __eq__(self, other):
    1.32 +        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    1.33 +    
    1.34 +    def __hash__(self):
    1.35 +        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    1.36 +    
    1.37 +    def __repr__(self):
    1.38 +        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    1.39 +        
    1.40 +
    1.41 +class VMManager(object):
    1.42 +    """Manage Virtual Machines"""
    1.43 +
    1.44 +    vmRootName = "SecurityDVM"
    1.45 +    
    1.46 +    def __init__(self):
    1.47 +        self.vBoxPath = self.getVBoxManagePath()
    1.48 +        self.vBoxManage = os.path.join(self.vBoxPath, 'VBoxManage.exe')
    1.49 +        self.systemProperties = self.getSystemProperties()
    1.50 +        self.cygwin_path = Cygwin.root()
    1.51 +        return
    1.52 +         
    1.53 +    def execute(self, cmd):
    1.54 +        """execute a command"""
    1.55 +    
    1.56 +        # we can handle strings and lists as input
    1.57 +        c = cmd
    1.58 +        if type(cmd) == list:
    1.59 +            c = ' '.join(cmd)
    1.60 +    
    1.61 +        if DEBUG:
    1.62 +            sys.stderr.write('trying to launch: ' + c + '\n')
    1.63 +        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    1.64 +        if DEBUG:
    1.65 +            sys.stderr.write('launched: ' + c + '\n')
    1.66 +            
    1.67 +        result = process.wait()
    1.68 +        res_stdout = process.stdout.read();
    1.69 +        res_stderr = process.stderr.read();
    1.70 +        if DEBUG:
    1.71 +            if res_stdout != "":
    1.72 +                print res_stdout
    1.73 +            if res_stderr != "":
    1.74 +                print res_stderr
    1.75 +        return result, res_stdout, res_stderr
    1.76 +    
    1.77 +    
    1.78 +    def getVBoxManagePath(self):
    1.79 +        """get the path to the VirtualBox installation on this system"""
    1.80 +        p = None
    1.81 +        try:
    1.82 +            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    1.83 +            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    1.84 +            _winreg.CloseKey(k)
    1.85 +        except:
    1.86 +            pass
    1.87 +        return p
    1.88 +    
    1.89 +    # return host system properties
    1.90 +    def getSystemProperties(self):
    1.91 +        cmd = [self.vBoxManage, 'list', 'systemproperties']
    1.92 +        result = self.execute(cmd)
    1.93 +        if result[1]=='':
    1.94 +            return None
    1.95 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
    1.96 +        return props
    1.97 +    
    1.98 +    # return the folder containing the guest VMs     
    1.99 +    def getDefaultMachineFolder(self):
   1.100 +        return self.systemProperties["Default machine folder"]
   1.101 +    
   1.102 +    #list the hostonly IFs exposed by the VBox host
   1.103 +    def getHostOnlyIFs(self):
   1.104 +        cmd = [self.vBoxManage, 'list', 'hostonlyifs']
   1.105 +        result = self.execute(cmd)[1]
   1.106 +        if result=='':
   1.107 +            return None
   1.108 +        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
   1.109 +        return props
   1.110 +        
   1.111 +    def listRSDS(self):
   1.112 +        cmd = [self.vBoxManage, 'list', 'usbhost']
   1.113 +        results = self.execute(cmd)
   1.114 +        results = results.split('Host USB Devices:')[1].strip()
   1.115 +        
   1.116 +        items = list( "UUID:" + result for result in results.split('UUID:') if result != '')
   1.117 +        rsds = dict()   
   1.118 +        for item in items:
   1.119 +            props = dict()
   1.120 +            for line in item.splitlines():
   1.121 +                if line != "":         
   1.122 +                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   1.123 +                    props[k] = v;
   1.124 +            
   1.125 +            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   1.126 +                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   1.127 +                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   1.128 +                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   1.129 +                rsds[props['UUID']] = usb_filter;
   1.130 +                if DEBUG:
   1.131 +                    print filter
   1.132 +        return rsds
   1.133 +
   1.134 +    # list all existing VMs registered with VBox
   1.135 +    def listVM(self):
   1.136 +        cmd = [self.vBoxManage, 'list', 'vms']
   1.137 +        result = self.execute(cmd)[1]
   1.138 +        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   1.139 +        return vms
   1.140 +    
   1.141 +    # list existing SDVMs
   1.142 +    def listSDVM(self):
   1.143 +        vms = self.listVM()
   1.144 +        svdms = []
   1.145 +        for vm in vms:
   1.146 +            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   1.147 +                svdms.append(vm)
   1.148 +        return svdms
   1.149 +    
   1.150 +    # generate valid (not already existing SDVM name). necessary for creating a new VM
   1.151 +    def generateSDVMName(self):
   1.152 +        vms = self.listVM()
   1.153 +        for i in range(0,999):
   1.154 +            if(not self.vmRootName+str(i) in vms):
   1.155 +                return self.vmRootName+str(i)
   1.156 +        return ''
   1.157 +    
   1.158 +    # return the RSDs attached to all existing SDVMs
   1.159 +    def getAttachedRSDs(self):
   1.160 +        vms = self.listSDVM()
   1.161 +        attached_devices = dict()
   1.162 +        for vm in vms:
   1.163 +            rsd_filter = self.getUSBFilter(vm)
   1.164 +            if filter != None:
   1.165 +                attached_devices[vm] = rsd_filter
   1.166 +        return attached_devices
   1.167 +    
   1.168 +    # configures hostonly networking and DHCP server. requires admin rights
   1.169 +    def configureHostNetworking(self):
   1.170 +        #cmd = 'vboxmanage list hostonlyifs'
   1.171 +        #self.execute(cmd)
   1.172 +        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   1.173 +        #self.execute(cmd)
   1.174 +        #cmd = 'vboxmanage hostonlyif create'
   1.175 +        #self.execute(cmd)
   1.176 +        cmd = self.vBoxManage + ' hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   1.177 +        self.execute(cmd)
   1.178 +        #cmd = 'vboxmanage dhcpserver add'
   1.179 +        #self.execute(cmd)
   1.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'
   1.181 +        self.execute(cmd)
   1.182 +    
   1.183 +    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   1.184 +    def createVM(self, vm_name):
   1.185 +        hostonly_if = self.getHostOnlyIFs()
   1.186 +        machineFolder = self.getDefaultMachineFolder()
   1.187 +        cmd = self.vBoxManage + ' createvm --name ' + vm_name + ' --ostype Debian --register'
   1.188 +        self.execute(cmd)
   1.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' 
   1.190 +        self.execute(cmd)
   1.191 +        cmd = self.vBoxManage + ' storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   1.192 +        self.execute(cmd)
   1.193 +        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --mtype normal --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   1.194 +        self.execute(cmd)
   1.195 +        return
   1.196 +    
   1.197 +    #remove VM from the system. should be used on VMs returned by listSDVMs    
   1.198 +    def removeVM(self, vm_name):
   1.199 +        print('removing ' + vm_name)
   1.200 +        cmd = self.vBoxManage + ' unregistervm', vm_name, '--delete'
   1.201 +        print self.execute(cmd)
   1.202 +        machineFolder = self.getDefaultMachineFolder()
   1.203 +        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   1.204 +        print self.execute(cmd)
   1.205 +    
   1.206 +    # start VM
   1.207 +    def startVM(self, vm_name):
   1.208 +        print('starting ' +  vm_name)
   1.209 +        cmd = self.vBoxManage + ' startvm ' + vm_name + ' --type headless'
   1.210 +        print self.execute(cmd)
   1.211 +        
   1.212 +    # stop VM    
   1.213 +    def stopVM(self, vm_name):
   1.214 +        print('stopping ' + vm_name)
   1.215 +        cmd = self.vBoxManage + ' controlvm ' + vm_name + ' poweroff'
   1.216 +        print self.execute(cmd)
   1.217 +    
   1.218 +    # return the hostOnly IP for a running guest    
   1.219 +    def getHostOnlyIP(self, vm_name):
   1.220 +        print('gettting hostOnly IP address ' + vm_name)
   1.221 +        cmd = self.vBoxManage + ' guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   1.222 +        result = self.execute(cmd)
   1.223 +        if result=='':
   1.224 +            return None
   1.225 +        result = result[1]
   1.226 +        return result[result.index(':')+1:].strip()
   1.227 +    
   1.228 +    # attach removable storage device to VM by provision of filter
   1.229 +    def attachRSD(self, vm_name, rsd_filter):
   1.230 +        cmd = self.vBoxManage + ' usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   1.231 +        print self.execute(cmd)
   1.232 +        
   1.233 +    
   1.234 +    # return the description set for an existing VM
   1.235 +    def getVMInfo(self, vm_name):
   1.236 +        cmd = self.vBoxManage + ' showvminfo ' + vm_name + ' --machinereadable'
   1.237 +        r, o, e = self.execute(cmd)
   1.238 +        props = dict((k.strip(),v.strip().strip('"')) for k, v in (line.split('=', 1) for line in o.splitlines()))
   1.239 +        return props
   1.240 +    
   1.241 +    # return the configured USB filter for an existing VM 
   1.242 +    def getUSBFilter(self, vm_name):
   1.243 +        props = self.getVMInfo(vm_name)
   1.244 +        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   1.245 +        keyset = set(props.keys())
   1.246 +        usb_filter = None
   1.247 +        if keyset.issuperset(keys):
   1.248 +            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   1.249 +        return usb_filter
   1.250 +    
   1.251 +    #generates ISO containing authorized_keys for use with guest VM
   1.252 +    def genCertificateISO(self, vm_name):
   1.253 +        machineFolder = self.getDefaultMachineFolder()
   1.254 +        # create .ssh folder in vm_name
   1.255 +        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   1.256 +        result = self.execute(cmd)
   1.257 +        # generate dvm_key pair in vm_name / .ssh     
   1.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" |',
   1.259 +        result = self.execute(cmd)
   1.260 +        # set permissions for keys
   1.261 +        #TODO: test without chmod
   1.262 +        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   1.263 +        result = self.execute(cmd)
   1.264 +        # move out private key
   1.265 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   1.266 +        result = self.execute(cmd)
   1.267 +        # rename public key to authorized_keys
   1.268 +        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   1.269 +        result = self.execute(cmd)
   1.270 +        # generate iso image with .ssh/authorized keys
   1.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\\\"\"'
   1.272 +        result = self.execute(cmd)
   1.273 +    
   1.274 +    # attaches generated ssh public cert to guest vm
   1.275 +    def attachCertificateISO(self, vm_name):
   1.276 +        machineFolder = self.getDefaultMachineFolder()
   1.277 +        cmd = self.vBoxManage + ' storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   1.278 +        result = self.execute(cmd)
   1.279 +        return result
   1.280 +    
   1.281 +    # handles device change events
   1.282 +    def handleDeviceChange(self):
   1.283 +        attached_devices = self.getAttachedRSDs()
   1.284 +        connected_devices = self.listRSDS()
   1.285 +        for vm_name in attached_devices.keys():
   1.286 +            if attached_devices[vm_name] not in connected_devices.values():
   1.287 +                self.stopVM(vm_name)
   1.288 +                self.removeVM(vm_name)
   1.289 +        
   1.290 +        attached_devices = self.getAttachedRSDs()
   1.291 +        for connected_device in connected_devices.values():
   1.292 +            if connected_device not in attached_devices.values():
   1.293 +                new_sdvm = self.generateSDVMName()
   1.294 +                self.createVM(new_sdvm)
   1.295 +                self.genCertificateISO(new_sdvm)
   1.296 +                self.attachCertificateISO(new_sdvm)
   1.297 +                self.attachRSD(new_sdvm, connected_device)
   1.298 +                self.startVM(new_sdvm)
   1.299 +    
   1.300 +    # executes command over ssh on guest vm
   1.301 +    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   1.302 +        # get vm ip
   1.303 +        address = self.getHostOnlyIP(vm_name)
   1.304 +        machineFolder = self.getDefaultMachineFolder()
   1.305 +        # run command
   1.306 +        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   1.307 +        return self.execute(cmd)
   1.308 +    
   1.309 +    # executes command over ssh on guest vm with X forwarding
   1.310 +    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   1.311 +        #TODO: verify if X server is running on user account 
   1.312 +        #TODO: set DISPLAY accordingly
   1.313 +        address = self.getHostOnlyIP(vm_name)
   1.314 +        machineFolder = self.getDefaultMachineFolder()
   1.315 +        # run command
   1.316 +        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   1.317 +        return self.execute(cmd)    
   1.318 +        
   1.319 +    # executes NET USE and connects to samba share on guestos 
   1.320 +    def netUse(self, vm_name):
   1.321 +        ip = self.getHostOnlyIP(vm_name)
   1.322 +        cmd = 'net use H: \\' + ip + '\RSD_Device'
   1.323 +        return self.execute(cmd)
   1.324 +        
   1.325 +    
   1.326 +if __name__ == '__main__':
   1.327 +    man = VMManager()
   1.328 +    man.cygwin_path = 'c:\\cygwin64\\bin\\'
   1.329 +    #man.handleDeviceChange()
   1.330 +    #print man.listSDVM()
   1.331 +    #man.configureHostNetworking()
   1.332 +    new_vm = man.generateSDVMName()
   1.333 +    man.createVM(new_vm)
   1.334 +    man.genCertificateISO(new_vm)
   1.335 +    man.attachCertificateISO(new_vm)
   1.336 +    
   1.337 +    #man.attachCertificateISO(vm_name)
   1.338 +    #man.sshGuestExecute(vm_name, "ls")
   1.339 +    #man.sshGuestX11Execute(vm_name, "iceweasel")
   1.340 +    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   1.341 +    #man.execute(cmd)
   1.342 +    
   1.343 +    
   1.344 +
   1.345 +