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