OpenSecurity/bin/vmmanager.py
author mb
Tue, 10 Dec 2013 13:50:13 +0100
changeset 33 79ed9495fa88
parent 26 0b784719a211
child 35 ba1ca3e5870b
permissions -rw-r--r--
singleton in VMManager. get using VMManager.getInstance()
mb@7
     1
'''
mb@7
     2
Created on Nov 19, 2013
mb@7
     3
mb@7
     4
@author: BarthaM
mb@7
     5
'''
mb@7
     6
import os
mb@7
     7
import os.path
mb@7
     8
from subprocess import Popen, PIPE, call
mb@7
     9
import subprocess
mb@7
    10
import sys
mb@7
    11
import re
om@19
    12
import _winreg
om@18
    13
from cygwin import Cygwin
mb@7
    14
om@19
    15
mb@7
    16
DEBUG = True
mb@7
    17
mb@7
    18
class USBFilter:
mb@7
    19
    vendorid = ""
mb@7
    20
    productid = ""
mb@7
    21
    revision = ""
mb@7
    22
    
mb@7
    23
    def __init__(self, vendorid, productid, revision):
mb@7
    24
        self.vendorid = vendorid.lower()
mb@7
    25
        self.productid = productid.lower()
mb@7
    26
        self.revision = revision.lower()
mb@7
    27
        return
mb@7
    28
    
mb@7
    29
    def __eq__(self, other):
mb@7
    30
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@7
    31
    
mb@7
    32
    def __hash__(self):
mb@7
    33
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@7
    34
    
mb@7
    35
    def __repr__(self):
mb@7
    36
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@7
    37
        
mb@7
    38
mb@7
    39
class VMManager(object):
mb@7
    40
    vmRootName = "SecurityDVM"
mb@7
    41
    systemProperties = None
mb@7
    42
    cygwin_path = 'c:\\cygwin64\\bin\\'
om@19
    43
    vboxManage = 'VBoxManage'
mb@7
    44
    
mb@33
    45
    _instance = None
mb@33
    46
    #def __new__(cls, *args, **kwargs):
mb@33
    47
    #    if not cls._instance:
mb@33
    48
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@33
    49
    #    return cls._instance
mb@33
    50
    
mb@7
    51
    def __init__(self):
om@21
    52
        self.cygwin_path = os.path.join(Cygwin.root(), 'bin')
om@22
    53
        self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
mb@7
    54
        self.systemProperties = self.getSystemProperties()
mb@7
    55
        return
mb@33
    56
    
mb@33
    57
    #@classmethod
mb@33
    58
    @staticmethod
mb@33
    59
    def getInstance():
mb@33
    60
        if VMManager._instance == None:
mb@33
    61
            VMManager._instance = VMManager()
mb@33
    62
        return VMManager._instance
mb@33
    63
             
mb@7
    64
    def execute(self, cmd):
mb@7
    65
        if DEBUG:
mb@7
    66
            print('trying to launch: ' + cmd)
mb@7
    67
        process = Popen(cmd, stdout=PIPE, stderr=PIPE)
mb@7
    68
        if DEBUG:
mb@7
    69
            print('launched: ' + cmd)
mb@7
    70
        result = process.wait()
mb@7
    71
        res_stdout = process.stdout.read();
mb@7
    72
        res_stderr = process.stderr.read();
mb@7
    73
        if DEBUG:
mb@7
    74
            if res_stdout != "":
mb@7
    75
                print res_stdout
mb@7
    76
            if res_stderr != "":
mb@7
    77
                print res_stderr
mb@7
    78
        return result, res_stdout, res_stderr
mb@7
    79
    
om@19
    80
    def getVBoxManagePath(self):
om@19
    81
        """get the path to the VirtualBox installation on this system"""
om@19
    82
        p = None
om@19
    83
        try:
om@19
    84
            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
om@19
    85
            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
om@19
    86
            _winreg.CloseKey(k)
om@19
    87
        except:
om@19
    88
            pass
om@19
    89
        return p
om@19
    90
    
BarthaM@8
    91
    # return hosty system properties
mb@7
    92
    def getSystemProperties(self):
om@22
    93
        cmd = self.vboxManage + ' list systemproperties'
mb@7
    94
        result = self.execute(cmd)
mb@7
    95
        if result[1]=='':
mb@7
    96
            return None
mb@7
    97
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@7
    98
        return props
BarthaM@8
    99
    
BarthaM@8
   100
    # return the folder containing the guest VMs     
mb@7
   101
    def getDefaultMachineFolder(self):
mb@7
   102
        return self.systemProperties["Default machine folder"]
mb@7
   103
    
BarthaM@8
   104
    #list the hostonly IFs exposed by the VBox host
mb@7
   105
    def getHostOnlyIFs(self):
mb@11
   106
        cmd = 'VBoxManage list hostonlyifs'
mb@11
   107
        result = self.execute(cmd)[1]
mb@7
   108
        if result=='':
mb@7
   109
            return None
mb@7
   110
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@7
   111
        return props
mb@7
   112
        
mb@7
   113
    def listRSDS(self):
mb@7
   114
        cmd = 'VBoxManage list usbhost'
mb@12
   115
        results = self.execute(cmd)[1]
mb@7
   116
        results = results.split('Host USB Devices:')[1].strip()
mb@7
   117
        
mb@7
   118
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@7
   119
        rsds = dict()   
mb@7
   120
        for item in items:
mb@7
   121
            props = dict()
mb@7
   122
            for line in item.splitlines():
mb@7
   123
                if line != "":         
mb@7
   124
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@7
   125
                    props[k] = v;
mb@7
   126
            
mb@7
   127
            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@7
   128
                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@7
   129
                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@7
   130
                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@7
   131
                rsds[props['UUID']] = usb_filter;
mb@7
   132
                if DEBUG:
mb@33
   133
                    print usb_filter
mb@7
   134
        return rsds
mb@7
   135
BarthaM@8
   136
    # list all existing VMs registered with VBox
mb@7
   137
    def listVM(self):
mb@7
   138
        cmd = 'VBoxManage list vms'
mb@11
   139
        result = self.execute(cmd)[1]
mb@7
   140
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@7
   141
        return vms
mb@7
   142
    
BarthaM@8
   143
    # list existing SDVMs
mb@7
   144
    def listSDVM(self):
mb@7
   145
        vms = self.listVM()
mb@7
   146
        svdms = []
mb@7
   147
        for vm in vms:
mb@7
   148
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@7
   149
                svdms.append(vm)
mb@7
   150
        return svdms
mb@7
   151
    
BarthaM@8
   152
    # generate valid (not already existing SDVM name). necessary for creating a new VM
mb@7
   153
    def generateSDVMName(self):
mb@7
   154
        vms = self.listVM()
mb@7
   155
        for i in range(0,999):
mb@7
   156
            if(not self.vmRootName+str(i) in vms):
mb@7
   157
                return self.vmRootName+str(i)
mb@7
   158
        return ''
mb@7
   159
    
BarthaM@8
   160
    # return the RSDs attached to all existing SDVMs
BarthaM@8
   161
    def getAttachedRSDs(self):
BarthaM@8
   162
        vms = self.listSDVM()
BarthaM@8
   163
        attached_devices = dict()
BarthaM@8
   164
        for vm in vms:
BarthaM@8
   165
            rsd_filter = self.getUSBFilter(vm)
mb@12
   166
            if rsd_filter != None:
BarthaM@8
   167
                attached_devices[vm] = rsd_filter
BarthaM@8
   168
        return attached_devices
BarthaM@8
   169
    
BarthaM@8
   170
    # configures hostonly networking and DHCP server. requires admin rights
BarthaM@8
   171
    def configureHostNetworking(self):
BarthaM@8
   172
        #cmd = 'vboxmanage list hostonlyifs'
BarthaM@8
   173
        #self.execute(cmd)
BarthaM@8
   174
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
BarthaM@8
   175
        #self.execute(cmd)
BarthaM@8
   176
        #cmd = 'vboxmanage hostonlyif create'
BarthaM@8
   177
        #self.execute(cmd)
mb@33
   178
        cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
BarthaM@8
   179
        self.execute(cmd)
BarthaM@8
   180
        #cmd = 'vboxmanage dhcpserver add'
BarthaM@8
   181
        #self.execute(cmd)
mb@33
   182
        cmd = 'VBoxManage dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.200'
BarthaM@8
   183
        self.execute(cmd)
BarthaM@8
   184
    
mb@11
   185
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
BarthaM@8
   186
    def createVM(self, vm_name):
BarthaM@8
   187
        hostonly_if = self.getHostOnlyIFs()
BarthaM@8
   188
        machineFolder = self.getDefaultMachineFolder()
mb@11
   189
        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
BarthaM@8
   190
        self.execute(cmd)
mb@11
   191
        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
BarthaM@8
   192
        self.execute(cmd)
mb@11
   193
        cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
BarthaM@8
   194
        self.execute(cmd)
mb@12
   195
        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
mb@12
   196
        #--mtype immutable
BarthaM@8
   197
        self.execute(cmd)
BarthaM@8
   198
        return
BarthaM@8
   199
    
BarthaM@8
   200
    #remove VM from the system. should be used on VMs returned by listSDVMs    
BarthaM@8
   201
    def removeVM(self, vm_name):
BarthaM@8
   202
        print('removing ' + vm_name)
BarthaM@8
   203
        cmd = 'VBoxManage unregistervm', vm_name, '--delete'
BarthaM@8
   204
        print self.execute(cmd)
BarthaM@8
   205
        machineFolder = self.getDefaultMachineFolder()
BarthaM@8
   206
        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
BarthaM@8
   207
        print self.execute(cmd)
BarthaM@8
   208
    
BarthaM@8
   209
    # start VM
BarthaM@8
   210
    def startVM(self, vm_name):
BarthaM@8
   211
        print('starting ' +  vm_name)
BarthaM@8
   212
        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
BarthaM@8
   213
        print self.execute(cmd)
BarthaM@8
   214
        
BarthaM@8
   215
    # stop VM    
BarthaM@8
   216
    def stopVM(self, vm_name):
BarthaM@8
   217
        print('stopping ' + vm_name)
BarthaM@8
   218
        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
BarthaM@8
   219
        print self.execute(cmd)
BarthaM@8
   220
    
BarthaM@8
   221
    # return the hostOnly IP for a running guest    
BarthaM@8
   222
    def getHostOnlyIP(self, vm_name):
BarthaM@8
   223
        print('gettting hostOnly IP address ' + vm_name)
BarthaM@8
   224
        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
BarthaM@8
   225
        result = self.execute(cmd)
BarthaM@8
   226
        if result=='':
BarthaM@8
   227
            return None
BarthaM@8
   228
        result = result[1]
BarthaM@8
   229
        return result[result.index(':')+1:].strip()
BarthaM@8
   230
    
BarthaM@8
   231
    # attach removable storage device to VM by provision of filter
BarthaM@8
   232
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@8
   233
        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
BarthaM@8
   234
        print self.execute(cmd)
BarthaM@8
   235
        
BarthaM@8
   236
    
BarthaM@8
   237
    # return the description set for an existing VM
mb@7
   238
    def getVMInfo(self, vm_name):
mb@7
   239
        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
mb@12
   240
        results = self.execute(cmd)[1]
mb@7
   241
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@7
   242
        return props
mb@7
   243
    
BarthaM@8
   244
    # return the configured USB filter for an existing VM 
mb@7
   245
    def getUSBFilter(self, vm_name):
mb@7
   246
        props = self.getVMInfo(vm_name)
mb@7
   247
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@7
   248
        keyset = set(props.keys())
mb@7
   249
        usb_filter = None
mb@7
   250
        if keyset.issuperset(keys):
mb@7
   251
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@7
   252
        return usb_filter
mb@7
   253
    
mb@7
   254
    #generates ISO containing authorized_keys for use with guest VM
mb@7
   255
    def genCertificateISO(self, vm_name):
mb@7
   256
        machineFolder = self.getDefaultMachineFolder()
mb@7
   257
        # create .ssh folder in vm_name
mb@7
   258
        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
mb@7
   259
        result = self.execute(cmd)
mb@7
   260
        # generate dvm_key pair in vm_name / .ssh     
mb@7
   261
        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" |',
mb@7
   262
        result = self.execute(cmd)
mb@7
   263
        # set permissions for keys
mb@7
   264
        #TODO: test without chmod
mb@7
   265
        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
mb@7
   266
        result = self.execute(cmd)
mb@7
   267
        # move out private key
mb@7
   268
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
mb@7
   269
        result = self.execute(cmd)
mb@7
   270
        # rename public key to authorized_keys
mb@7
   271
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
mb@7
   272
        result = self.execute(cmd)
mb@7
   273
        # generate iso image with .ssh/authorized keys
mb@7
   274
        cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
mb@7
   275
        result = self.execute(cmd)
mb@7
   276
    
mb@7
   277
    # attaches generated ssh public cert to guest vm
mb@7
   278
    def attachCertificateISO(self, vm_name):
mb@7
   279
        machineFolder = self.getDefaultMachineFolder()
mb@7
   280
        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
mb@7
   281
        result = self.execute(cmd)
mb@7
   282
        return result
mb@7
   283
    
mb@7
   284
    # handles device change events
mb@7
   285
    def handleDeviceChange(self):
mb@7
   286
        attached_devices = self.getAttachedRSDs()
mb@7
   287
        connected_devices = self.listRSDS()
mb@7
   288
        for vm_name in attached_devices.keys():
mb@12
   289
            if connected_devices and attached_devices[vm_name] not in connected_devices.values():
mb@12
   290
                # self.netUse(vm_name)
mb@7
   291
                self.stopVM(vm_name)
mb@7
   292
                self.removeVM(vm_name)
mb@7
   293
        
mb@7
   294
        attached_devices = self.getAttachedRSDs()
mb@7
   295
        for connected_device in connected_devices.values():
mb@12
   296
            if attached_devices or connected_device not in attached_devices.values():
mb@7
   297
                new_sdvm = self.generateSDVMName()
mb@7
   298
                self.createVM(new_sdvm)
mb@7
   299
                self.attachRSD(new_sdvm, connected_device)
mb@7
   300
                self.startVM(new_sdvm)
mb@12
   301
                self.netUse(new_sdvm)
mb@12
   302
    
mb@12
   303
    def handleBrowsingRequest(self):
mb@12
   304
        new_sdvm = self.generateSDVMName()
mb@12
   305
        self.createVM(new_sdvm)
mb@12
   306
        self.genCertificateISO(new_sdvm)
mb@12
   307
        self.attachCertificateISO(new_sdvm)
mb@7
   308
    
mb@7
   309
    # executes command over ssh on guest vm
BarthaM@8
   310
    def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
mb@7
   311
        # get vm ip
mb@7
   312
        address = self.getHostOnlyIP(vm_name)
mb@7
   313
        machineFolder = self.getDefaultMachineFolder()
mb@7
   314
        # run command
BarthaM@8
   315
        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
mb@7
   316
        return self.execute(cmd)
mb@7
   317
    
mb@7
   318
    # executes command over ssh on guest vm with X forwarding
BarthaM@8
   319
    def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
mb@7
   320
        #TODO: verify if X server is running on user account 
mb@7
   321
        #TODO: set DISPLAY accordingly
mb@7
   322
        address = self.getHostOnlyIP(vm_name)
mb@7
   323
        machineFolder = self.getDefaultMachineFolder()
mb@7
   324
        # run command
BarthaM@8
   325
        cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
mb@7
   326
        return self.execute(cmd)    
mb@7
   327
        
mb@7
   328
    # executes NET USE and connects to samba share on guestos 
mb@7
   329
    def netUse(self, vm_name):
mb@7
   330
        ip = self.getHostOnlyIP(vm_name)
mb@12
   331
        cmd = 'net use H: \\' + ip + '\USB'
mb@7
   332
        return self.execute(cmd)
mb@7
   333
        
mb@7
   334
    
mb@33
   335
#if __name__ == '__main__':
mb@33
   336
    #man = VMManager()
mb@33
   337
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@7
   338
    #man.handleDeviceChange()
mb@7
   339
    #print man.listSDVM()
mb@11
   340
    #man.configureHostNetworking()
mb@33
   341
    #new_vm = man.generateSDVMName()
mb@33
   342
    #man.createVM(new_vm)
mb@33
   343
    #man.genCertificateISO(new_vm)
mb@33
   344
    #man.attachCertificateISO(new_vm)
mb@11
   345
    
mb@7
   346
    #man.attachCertificateISO(vm_name)
mb@7
   347
    #man.sshGuestExecute(vm_name, "ls")
mb@7
   348
    #man.sshGuestX11Execute(vm_name, "iceweasel")
mb@7
   349
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@7
   350
    #man.execute(cmd)
mb@33
   351