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