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