OpenSecurity/bin/vmmanager.py
author mb
Wed, 29 Jan 2014 14:25:20 +0100
changeset 55 42238cd74afe
parent 54 59f1d824a070
parent 53 01839f13cef3
child 56 9180aaaf2551
permissions -rw-r--r--
merge - verify unaccepted changes
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
dyle@53
    14
from environment import Environment
mb@36
    15
import threading
mb@40
    16
import time
mb@40
    17
import string
mb@7
    18
dyle@53
    19
import shutil
dyle@53
    20
import stat
dyle@53
    21
import tempfile
dyle@52
    22
om@19
    23
om@42
    24
DEBUG = True
mb@46
    25
class VMManagerException(Exception):
mb@46
    26
    def __init__(self, value):
mb@46
    27
        self.value = value
mb@46
    28
    def __str__(self):
mb@46
    29
        return repr(self.value)
mb@7
    30
mb@7
    31
class USBFilter:
mb@7
    32
    vendorid = ""
mb@7
    33
    productid = ""
mb@7
    34
    revision = ""
mb@7
    35
    
mb@7
    36
    def __init__(self, vendorid, productid, revision):
mb@7
    37
        self.vendorid = vendorid.lower()
mb@7
    38
        self.productid = productid.lower()
mb@7
    39
        self.revision = revision.lower()
mb@7
    40
        return
mb@7
    41
    
mb@7
    42
    def __eq__(self, other):
mb@7
    43
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@7
    44
    
mb@7
    45
    def __hash__(self):
mb@7
    46
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@7
    47
    
mb@7
    48
    def __repr__(self):
mb@7
    49
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@7
    50
        
mb@7
    51
mb@7
    52
class VMManager(object):
mb@7
    53
    vmRootName = "SecurityDVM"
mb@7
    54
    systemProperties = None
mb@7
    55
    cygwin_path = 'c:\\cygwin64\\bin\\'
om@19
    56
    vboxManage = 'VBoxManage'
mb@34
    57
    startNotifications = list()
mb@34
    58
    
mb@34
    59
    _instance = None
mb@34
    60
    #def __new__(cls, *args, **kwargs):
mb@34
    61
    #    if not cls._instance:
mb@34
    62
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@34
    63
    #    return cls._instance
mb@7
    64
    
mb@33
    65
    _instance = None
mb@33
    66
    #def __new__(cls, *args, **kwargs):
mb@33
    67
    #    if not cls._instance:
mb@33
    68
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@33
    69
    #    return cls._instance
mb@33
    70
    
mb@7
    71
    def __init__(self):
om@31
    72
        self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
om@22
    73
        self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
mb@7
    74
        self.systemProperties = self.getSystemProperties()
mb@7
    75
        return
mb@33
    76
    
mb@33
    77
    @staticmethod
mb@33
    78
    def getInstance():
mb@33
    79
        if VMManager._instance == None:
mb@33
    80
            VMManager._instance = VMManager()
mb@33
    81
        return VMManager._instance
mb@34
    82
    
mb@34
    83
    def putStartNotification(self, ip):
mb@34
    84
        self.startNotifications.append(ip)
mb@34
    85
    
mb@34
    86
    def isSDVMStarted(self, ip):
mb@34
    87
        return self.startNotifications.contains(ip)
mb@7
    88
    
om@19
    89
    def getVBoxManagePath(self):
om@19
    90
        """get the path to the VirtualBox installation on this system"""
om@19
    91
        p = None
om@19
    92
        try:
om@19
    93
            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
om@19
    94
            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
om@19
    95
            _winreg.CloseKey(k)
om@19
    96
        except:
om@19
    97
            pass
om@19
    98
        return p
om@19
    99
    
BarthaM@8
   100
    # return hosty system properties
mb@7
   101
    def getSystemProperties(self):
om@22
   102
        cmd = self.vboxManage + ' list systemproperties'
mb@54
   103
        result = self.hostExecute(cmd)
mb@7
   104
        if result[1]=='':
mb@7
   105
            return None
mb@7
   106
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@7
   107
        return props
BarthaM@8
   108
    
BarthaM@8
   109
    # return the folder containing the guest VMs     
mb@7
   110
    def getDefaultMachineFolder(self):
mb@54
   111
        machineFolder = self.systemProperties["Default machine folder"]
mb@54
   112
        return machineFolder
mb@7
   113
    
BarthaM@8
   114
    #list the hostonly IFs exposed by the VBox host
mb@7
   115
    def getHostOnlyIFs(self):
mb@11
   116
        cmd = 'VBoxManage list hostonlyifs'
mb@54
   117
        result = self.hostExecute(cmd)[1]
mb@7
   118
        if result=='':
mb@7
   119
            return None
mb@7
   120
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@7
   121
        return props
mb@7
   122
        
mb@7
   123
    def listRSDS(self):
mb@7
   124
        cmd = 'VBoxManage list usbhost'
mb@54
   125
        results = self.hostExecute(cmd)[1]
mb@7
   126
        results = results.split('Host USB Devices:')[1].strip()
mb@7
   127
        
mb@7
   128
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@7
   129
        rsds = dict()   
mb@7
   130
        for item in items:
mb@7
   131
            props = dict()
mb@7
   132
            for line in item.splitlines():
mb@7
   133
                if line != "":         
mb@7
   134
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@7
   135
                    props[k] = v;
mb@7
   136
            
mb@7
   137
            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@7
   138
                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@7
   139
                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@7
   140
                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@7
   141
                rsds[props['UUID']] = usb_filter;
mb@7
   142
                if DEBUG:
mb@33
   143
                    print usb_filter
mb@7
   144
        return rsds
mb@7
   145
BarthaM@8
   146
    # list all existing VMs registered with VBox
mb@7
   147
    def listVM(self):
mb@7
   148
        cmd = 'VBoxManage list vms'
mb@54
   149
        result = self.hostExecute(cmd)[1]
mb@54
   150
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@54
   151
        return vms
mb@54
   152
    
mb@54
   153
    # list running VMs
mb@54
   154
    def listRunningVMS(self):
mb@54
   155
        cmd = 'VBoxManage list runningvms'
mb@54
   156
        result = self.hostExecute(cmd)[1]
mb@7
   157
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@7
   158
        return vms
mb@7
   159
    
BarthaM@8
   160
    # list existing SDVMs
mb@7
   161
    def listSDVM(self):
mb@7
   162
        vms = self.listVM()
mb@7
   163
        svdms = []
mb@7
   164
        for vm in vms:
mb@7
   165
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@7
   166
                svdms.append(vm)
mb@7
   167
        return svdms
mb@7
   168
    
BarthaM@8
   169
    # generate valid (not already existing SDVM name). necessary for creating a new VM
mb@7
   170
    def generateSDVMName(self):
mb@7
   171
        vms = self.listVM()
mb@7
   172
        for i in range(0,999):
mb@7
   173
            if(not self.vmRootName+str(i) in vms):
mb@7
   174
                return self.vmRootName+str(i)
mb@7
   175
        return ''
mb@7
   176
    
BarthaM@8
   177
    # return the RSDs attached to all existing SDVMs
BarthaM@8
   178
    def getAttachedRSDs(self):
BarthaM@8
   179
        vms = self.listSDVM()
BarthaM@8
   180
        attached_devices = dict()
BarthaM@8
   181
        for vm in vms:
BarthaM@8
   182
            rsd_filter = self.getUSBFilter(vm)
mb@12
   183
            if rsd_filter != None:
BarthaM@8
   184
                attached_devices[vm] = rsd_filter
BarthaM@8
   185
        return attached_devices
BarthaM@8
   186
    
BarthaM@8
   187
    # configures hostonly networking and DHCP server. requires admin rights
BarthaM@8
   188
    def configureHostNetworking(self):
BarthaM@8
   189
        #cmd = 'vboxmanage list hostonlyifs'
mb@54
   190
        #self.hostExecute(cmd)
BarthaM@8
   191
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
mb@54
   192
        #self.hostExecute(cmd)
BarthaM@8
   193
        #cmd = 'vboxmanage hostonlyif create'
mb@54
   194
        #self.hostExecute(cmd)
mb@33
   195
        cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
mb@54
   196
        self.hostExecute(cmd)
BarthaM@8
   197
        #cmd = 'vboxmanage dhcpserver add'
mb@54
   198
        #self.hostExecute(cmd)
mb@33
   199
        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'
mb@54
   200
        self.hostExecute(cmd)
BarthaM@8
   201
    
mb@11
   202
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
BarthaM@8
   203
    def createVM(self, vm_name):
BarthaM@8
   204
        hostonly_if = self.getHostOnlyIFs()
mb@54
   205
        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
mb@54
   206
        self.hostExecute(cmd)
mb@54
   207
        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
mb@54
   208
        self.hostExecute(cmd)
mb@54
   209
        cmd = 'VBoxManage storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'
mb@54
   210
        self.hostExecute(cmd)
mb@54
   211
        return
mb@54
   212
    
mb@54
   213
    # attach storage image to controller
mb@54
   214
    def storageAttach(self, vm_name):
mb@54
   215
        if self.isStorageAttached(vm_name):
mb@54
   216
            self.storageDetach(vm_name)
BarthaM@8
   217
        machineFolder = self.getDefaultMachineFolder()
mb@54
   218
        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
mb@54
   219
        self.hostExecute(cmd)
BarthaM@8
   220
        return
BarthaM@8
   221
    
mb@54
   222
    # return true if storage is attached 
mb@54
   223
    def isStorageAttached(self, vm_name):
mb@54
   224
        info = self.getVMInfo(vm_name)
mb@54
   225
        return (info['SATA-0-0']!='none')
mb@54
   226
    
mb@54
   227
    # detach storage from controller
mb@54
   228
    def storageDetach(self, vm_name):
mb@54
   229
        if self.isStorageAttached(vm_name):
mb@54
   230
            cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'
mb@54
   231
            self.hostExecute(cmd)
mb@54
   232
        return
mb@54
   233
    
mb@54
   234
    def changeStorageType(self, filename, type):
mb@54
   235
        cmd = 'VBoxManage modifyhd \"' + filename + '\" --type ' + type
mb@54
   236
        self.hostExecute(cmd)
mb@54
   237
        return
mb@54
   238
    
mb@54
   239
    # list storage snaphots for VM
mb@54
   240
    def updateTemplate(self):
mb@54
   241
        self.poweroffVM('SecurityDVM')
mb@54
   242
        self.waitShutdown('SecurityDVM')
mb@54
   243
        
mb@54
   244
        # check for updates
mb@54
   245
        self.genCertificateISO('SecurityDVM')
mb@54
   246
        self.attachCertificateISO('SecurityDVM')
mb@54
   247
        
mb@54
   248
        self.storageDetach('SecurityDVM')
mb@54
   249
        cmd = 'VBoxManage list hdds'
mb@54
   250
        results = self.hostExecute(cmd)[1]
mb@54
   251
        results = results.replace('Parent UUID', 'Parent')
mb@54
   252
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@54
   253
        
mb@54
   254
        snaps = dict()   
mb@54
   255
        for item in items:
mb@54
   256
            #print item
mb@54
   257
            props = dict()
mb@54
   258
            for line in item.splitlines():
mb@54
   259
                if line != "":         
mb@54
   260
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@54
   261
                    props[k] = v;
mb@54
   262
            snaps[props['UUID']] = props
mb@54
   263
        
mb@54
   264
        machineFolder = self.getDefaultMachineFolder()
mb@54
   265
        template_storage = machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
mb@54
   266
        
mb@54
   267
        # find template uuid
mb@54
   268
        template_uuid = ''
mb@54
   269
        for hdd in snaps.values():
mb@54
   270
            if hdd['Location'] == template_storage:
mb@54
   271
                template_uuid = hdd['UUID']
mb@54
   272
        print 'found parent uuid ' + template_uuid
mb@54
   273
        
mb@54
   274
        # remove snapshots 
mb@54
   275
        for hdd in snaps.values():
mb@54
   276
            if hdd['Parent'] == template_uuid:
mb@54
   277
                #template_uuid = hdd['UUID']
mb@54
   278
                print 'removing snapshot ' + hdd['UUID']
mb@54
   279
                cmd = 'VBoxManage closemedium disk {' + hdd['UUID'] + '} --delete'
mb@54
   280
                results = self.hostExecute(cmd)[1]
mb@54
   281
                # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
mb@54
   282
        
mb@54
   283
        self.changeStorageType(template_storage,'normal')
mb@54
   284
        self.storageAttach('SecurityDVM')
mb@54
   285
        self.startVM('SecurityDVM')
mb@54
   286
        self.waitStartup('SecurityDVM')
mb@54
   287
        self.guestExecute('SecurityDVM', 'sudo apt-get -y update' )
mb@54
   288
        self.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
mb@54
   289
        self.stopVM('SecurityDVM')
mb@54
   290
        self.waitShutdown('SecurityDVM')
mb@54
   291
        self.storageDetach('SecurityDVM')
mb@54
   292
        self.changeStorageType(template_storage,'immutable')
mb@54
   293
        self.storageAttach('SecurityDVM')
mb@54
   294
        
mb@54
   295
    
BarthaM@8
   296
    #remove VM from the system. should be used on VMs returned by listSDVMs    
BarthaM@8
   297
    def removeVM(self, vm_name):
BarthaM@8
   298
        print('removing ' + vm_name)
mb@36
   299
        cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
mb@54
   300
        print self.hostExecute(cmd)
BarthaM@8
   301
        machineFolder = self.getDefaultMachineFolder()
mb@36
   302
        cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
mb@54
   303
        print self.hostExecute(cmd)
BarthaM@8
   304
    
BarthaM@8
   305
    # start VM
BarthaM@8
   306
    def startVM(self, vm_name):
BarthaM@8
   307
        print('starting ' +  vm_name)
mb@40
   308
        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' 
mb@54
   309
        result = self.hostExecute(cmd)
mb@46
   310
        while not string.find(str(result), 'successfully started',):
mb@46
   311
            print "Failed to start SDVM: ", vm_name, " retrying"
mb@46
   312
            time.sleep(1)
mb@54
   313
            result = self.hostExecute(cmd)
mb@46
   314
        return result[0]
mb@54
   315
    
mb@54
   316
    # return wether VM is running or not
mb@54
   317
    def isVMRunning(self, vm_name):
mb@54
   318
        return vm_name in self.listRunningVMS()    
mb@54
   319
    
mb@54
   320
    # stop VM
BarthaM@8
   321
    def stopVM(self, vm_name):
BarthaM@8
   322
        print('stopping ' + vm_name)
mb@54
   323
        cmd = 'sudo shutdown -h now'
mb@54
   324
        self.guestExecute('SecurityDVM', cmd)
mb@54
   325
            
mb@54
   326
    # poweroff VM
mb@54
   327
    def poweroffVM(self, vm_name):
mb@54
   328
        if not self.isVMRunning(vm_name):
mb@54
   329
            return
mb@54
   330
        print('powering off ' + vm_name)
BarthaM@8
   331
        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
mb@54
   332
        self.hostExecute(cmd)
BarthaM@8
   333
    
BarthaM@8
   334
    # return the hostOnly IP for a running guest    
BarthaM@8
   335
    def getHostOnlyIP(self, vm_name):
BarthaM@8
   336
        print('gettting hostOnly IP address ' + vm_name)
BarthaM@8
   337
        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
mb@54
   338
        result = self.hostExecute(cmd)
BarthaM@8
   339
        if result=='':
BarthaM@8
   340
            return None
BarthaM@8
   341
        result = result[1]
mb@40
   342
        if result.startswith('No value set!'):
mb@40
   343
            return None
BarthaM@8
   344
        return result[result.index(':')+1:].strip()
BarthaM@8
   345
    
BarthaM@8
   346
    # attach removable storage device to VM by provision of filter
BarthaM@8
   347
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@8
   348
        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
mb@54
   349
        print self.hostExecute(cmd)
BarthaM@8
   350
        
BarthaM@8
   351
    
BarthaM@8
   352
    # return the description set for an existing VM
mb@7
   353
    def getVMInfo(self, vm_name):
mb@7
   354
        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
mb@54
   355
        results = self.hostExecute(cmd)[1]
mb@54
   356
        props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@7
   357
        return props
mb@7
   358
    
BarthaM@8
   359
    # return the configured USB filter for an existing VM 
mb@7
   360
    def getUSBFilter(self, vm_name):
mb@7
   361
        props = self.getVMInfo(vm_name)
mb@7
   362
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@7
   363
        keyset = set(props.keys())
mb@7
   364
        usb_filter = None
mb@7
   365
        if keyset.issuperset(keys):
mb@7
   366
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@7
   367
        return usb_filter
mb@7
   368
    
mb@7
   369
    #generates ISO containing authorized_keys for use with guest VM
mb@7
   370
    def genCertificateISO(self, vm_name):
mb@7
   371
        machineFolder = self.getDefaultMachineFolder()
mb@54
   372
        machineFolder = self.cygwinPath(machineFolder)
mb@54
   373
        # remove .ssh folder if exists
mb@54
   374
        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
mb@54
   375
        self.hostExecute(cmd)
mb@54
   376
        # remove .ssh folder if exists
mb@54
   377
        cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'
mb@54
   378
        self.hostExecute(cmd)
mb@46
   379
        # create .ssh folder in vm_name
mb@54
   380
        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
mb@54
   381
        self.hostExecute(cmd)
mb@46
   382
        # generate dvm_key pair in vm_name / .ssh     
mb@54
   383
        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@54
   384
        self.hostExecute(cmd)
mb@46
   385
        # move out private key
mb@54
   386
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'
mb@54
   387
        self.hostExecute(cmd)
mb@54
   388
        # set permissions for private key
mb@54
   389
        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'
mb@54
   390
        self.hostExecute(cmd)
mb@46
   391
        # rename public key to authorized_keys
mb@54
   392
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'
mb@54
   393
        self.hostExecute(cmd)
mb@54
   394
        # set permissions for authorized_keys
mb@54
   395
        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"'
mb@54
   396
        self.hostExecute(cmd)
mb@46
   397
        # generate iso image with .ssh/authorized keys
mb@54
   398
        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@54
   399
        self.hostExecute(cmd)
mb@7
   400
    
mb@7
   401
    # attaches generated ssh public cert to guest vm
mb@7
   402
    def attachCertificateISO(self, vm_name):
mb@7
   403
        machineFolder = self.getDefaultMachineFolder()
mb@54
   404
        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
mb@54
   405
        result = self.hostExecute(cmd)
mb@7
   406
        return result
mb@7
   407
    
mb@36
   408
    handleDeviceChangeLock = threading.Lock()
mb@36
   409
    
mb@7
   410
    # handles device change events
mb@7
   411
    def handleDeviceChange(self):
mb@36
   412
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@36
   413
            #destroy unused vms
mb@40
   414
            new_ip = None
mb@36
   415
            attached_devices = self.getAttachedRSDs()
mb@36
   416
            connected_devices = self.listRSDS()
mb@36
   417
            for vm_name in attached_devices.keys():
mb@36
   418
                if attached_devices[vm_name] not in connected_devices.values():
mb@40
   419
                    self.unmapNetworkDrive('h:')
mb@36
   420
                    self.stopVM(vm_name)
mb@36
   421
                    self.removeVM(vm_name)
mb@36
   422
            #create new vm for attached device if any
mb@36
   423
            attached_devices = self.getAttachedRSDs()
mb@36
   424
            for connected_device in connected_devices.values():
mb@36
   425
                if (attached_devices and False) or (connected_device not in attached_devices.values()):
mb@36
   426
                    new_sdvm = self.generateSDVMName()
mb@36
   427
                    self.createVM(new_sdvm)
mb@36
   428
                    self.attachRSD(new_sdvm, connected_device)
mb@46
   429
mb@46
   430
mb@36
   431
                    self.startVM(new_sdvm)
mb@46
   432
                    # wait for machine to come up
mb@40
   433
                    while new_ip == None:
mb@40
   434
                        time.sleep(1)
mb@40
   435
                        new_ip = self.getHostOnlyIP(new_sdvm)
mb@40
   436
                    while new_ip not in self.startNotifications:
mb@40
   437
                        time.sleep(1)
mb@46
   438
                    if new_ip != None:
mb@46
   439
                        self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
mb@40
   440
                    #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@40
   441
                    self.startNotifications.remove(new_ip)
mb@36
   442
            VMManager.handleDeviceChangeLock.release()
mb@40
   443
            return new_ip
mb@12
   444
    
mb@54
   445
    # wait for machine to come up
mb@54
   446
    def waitStartup(self, vm_name): 
mb@54
   447
        new_ip = None
mb@54
   448
        while new_ip == None:
mb@54
   449
            time.sleep(1)
mb@54
   450
            new_ip = self.getHostOnlyIP(vm_name)
mb@54
   451
        while new_ip not in self.startNotifications:
mb@54
   452
            time.sleep(1)
mb@54
   453
        return
mb@54
   454
    
mb@54
   455
    # wait for machine to shutdown
mb@54
   456
    def waitShutdown(self, vm_name):
mb@54
   457
        while vm_name in self.listRunningVMS():
mb@54
   458
            time.sleep(1)
mb@54
   459
        return
mb@54
   460
        
mb@54
   461
    # handles browsing request    
mb@12
   462
    def handleBrowsingRequest(self):
mb@46
   463
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@46
   464
            new_ip = None
mb@46
   465
            new_sdvm = self.generateSDVMName()
mb@46
   466
            self.createVM(new_sdvm)
mb@46
   467
            self.genCertificateISO(new_sdvm)
mb@46
   468
            self.attachCertificateISO(new_sdvm)
mb@46
   469
            self.startVM(new_sdvm)
mb@54
   470
            self.waitStartup(new_sdvm)
mb@46
   471
            if new_ip != None:
mb@46
   472
                self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
mb@46
   473
            #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@46
   474
            self.startNotifications.remove(new_ip)
mb@46
   475
            VMManager.handleDeviceChangeLock.release()
om@31
   476
        return new_sdvm
mb@7
   477
    
mb@54
   478
    def cygwinPath(self, path):
mb@54
   479
        # TODO: test if env ist cygwin
mb@54
   480
        cmd = self.cygwin_path + 'bash.exe --login -c \"cygpath -u \\\"' + path + '\\\"\"' 
mb@54
   481
        return self.hostExecute(cmd)[1].rstrip('\n')
mb@54
   482
    
mb@54
   483
    #executes command on host system
mb@54
   484
    def hostExecute(self, cmd, wait_return=True ):
mb@54
   485
        if DEBUG:
mb@54
   486
            print('trying to launch: ' + cmd)
mb@54
   487
        process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
mb@54
   488
        if DEBUG:
mb@54
   489
            print('launched: ' + cmd)
mb@54
   490
        if not wait_return:
mb@54
   491
            return [0, 'working in background', '']
mb@54
   492
        result = process.wait()
mb@54
   493
        res_stdout = process.stdout.read();
mb@54
   494
        res_stderr = process.stderr.read();
mb@54
   495
        if DEBUG:
mb@54
   496
            if res_stdout != "":
mb@54
   497
                print res_stdout
mb@54
   498
            if res_stderr != "":
mb@54
   499
                print res_stderr
mb@54
   500
        if result !=0:
mb@54
   501
            raise VMManagerException(res_stderr)
mb@54
   502
        return result, res_stdout, res_stderr
mb@54
   503
    
mb@7
   504
    # executes command over ssh on guest vm
mb@54
   505
    def guestExecute(self, vm_name, prog, user_name='osecuser'):
mb@7
   506
        # get vm ip
mb@7
   507
        address = self.getHostOnlyIP(vm_name)
mb@7
   508
        machineFolder = self.getDefaultMachineFolder()
mb@54
   509
        machineFolder = self.cygwinPath(machineFolder)
mb@54
   510
        # run command //mintty.exe -e
mb@54
   511
        cmd = self.cygwin_path + 'bash.exe --login -c \"/usr/bin/ssh -v -i \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
mb@54
   512
        return self.hostExecute(cmd)
mb@7
   513
    
mb@7
   514
    # executes command over ssh on guest vm with X forwarding
mb@54
   515
    def guestExecuteX11(self, vm_name, prog, user_name='osecuser'):
mb@7
   516
        #TODO: verify if X server is running on user account 
mb@7
   517
        #TODO: set DISPLAY accordingly
mb@7
   518
        address = self.getHostOnlyIP(vm_name)
mb@7
   519
        machineFolder = self.getDefaultMachineFolder()
mb@7
   520
        # run command
mb@46
   521
        #--login
mb@46
   522
        #cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
dyle@53
   523
        cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -o StrictHostKeyChecking=no -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\"  '  + user_name + '@' + address + ' ' + prog + ''
mb@46
   524
        #cmd = self.cygwin_path+'mintty.exe -e /bin/bash --login -c \"DISPLAY=:0 /usr/bin/ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
mb@46
   525
        if DEBUG:
mb@46
   526
            print('trying to launch: ' + cmd)
mb@46
   527
        process = Popen(cmd)
mb@46
   528
        if DEBUG:
mb@46
   529
            print('launched: ' + cmd)
mb@46
   530
        return     
mb@7
   531
    
mb@40
   532
    #Small function to check the availability of network resource.
mb@40
   533
    def isAvailable(self, path):
mb@40
   534
        cmd = 'IF EXIST ' + path + ' echo YES'
mb@40
   535
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   536
        return string.find(str(result), 'YES',)
mb@40
   537
    
mb@40
   538
    #Small function to check if the mention location is a directory
mb@40
   539
    def isDirectory(self, path):
mb@40
   540
        cmd = 'dir ' + path + ' | FIND ".."'
mb@40
   541
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   542
        return string.find(str(result), 'DIR',)
mb@40
   543
mb@40
   544
    def mapNetworkDrive(self, drive, networkPath, user, password):
mb@40
   545
        self.unmapNetworkDrive('h:')
mb@40
   546
        #Check for drive availability
mb@40
   547
        if self.isAvailable(drive) > -1:
mb@40
   548
            print "Drive letter is already in use: ", drive
mb@40
   549
            return -1
mb@40
   550
        #Check for network resource availability
mb@40
   551
        while self.isAvailable(networkPath) == -1:
mb@40
   552
            time.sleep(1)
mb@40
   553
            print "Path not accessible: ", networkPath, " retrying"
mb@40
   554
            #return -1
mb@40
   555
    
mb@40
   556
        #Prepare 'NET USE' commands
mb@40
   557
        cmd = 'NET USE ' + drive + ' ' + networkPath
mb@40
   558
        if user != None:
mb@40
   559
            cmd = cmd + ' ' + password + ' /User' + user
mb@40
   560
    
mb@40
   561
        print "cmd = ", cmd
mb@40
   562
        #Execute 'NET USE' command with authentication
mb@40
   563
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   564
        print "Executed: ", cmd
mb@40
   565
        if string.find(str(result), 'successfully',) == -1:
mb@40
   566
            print cmd, " FAILED"
mb@40
   567
            return -1
mb@40
   568
        #Mapped with first try
mb@40
   569
        return 1
mb@40
   570
    
mb@40
   571
    def unmapNetworkDrive(self, drive):
mb@40
   572
        #Check if the drive is in use
mb@40
   573
        if self.isAvailable(drive) == -1:
mb@40
   574
            #Drive is not in use
mb@40
   575
            return -1
mb@40
   576
        #Prepare 'NET USE' command
mb@40
   577
        cmd = 'net use ' + drive + ' /DELETE'
mb@40
   578
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   579
        if string.find(str(result), 'successfully',) == -1:
mb@40
   580
            return -1
mb@40
   581
        return 1
mb@40
   582
mb@54
   583
mb@40
   584
if __name__ == '__main__':
mb@40
   585
    man = VMManager.getInstance()
mb@40
   586
    #man.removeVM('SecurityDVM0')
mb@40
   587
    #man.netUse('192.168.56.134', 'USB\\')
mb@46
   588
    #ip = '192.168.56.139'
mb@46
   589
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
mb@33
   590
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@7
   591
    #man.handleDeviceChange()
mb@7
   592
    #print man.listSDVM()
mb@11
   593
    #man.configureHostNetworking()
mb@33
   594
    #new_vm = man.generateSDVMName()
mb@33
   595
    #man.createVM(new_vm)
mb@33
   596
    #man.genCertificateISO(new_vm)
mb@33
   597
    #man.attachCertificateISO(new_vm)
mb@11
   598
    
mb@7
   599
    #man.attachCertificateISO(vm_name)
mb@54
   600
    #man.guestExecute(vm_name, "ls")
mb@54
   601
    #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@54
   602
    #time.sleep(60)
mb@54
   603
    #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
mb@54
   604
    #man.genCertificateISO('SecurityDVM')
mb@54
   605
    #man.attachCertificateISO('SecurityDVM')
mb@54
   606
    #man.isStorageAttached('SecurityDVM')
mb@54
   607
    man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
mb@54
   608
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
mb@54
   609
    
mb@54
   610
    #man.stopVM('SecurityDVM')
mb@54
   611
    #man.storageDetach('SecurityDVM')
mb@54
   612
    #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
mb@54
   613
    #man.storageAttach('SecurityDVM')
mb@54
   614
    
mb@54
   615
    
mb@7
   616
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@7
   617
    #man.execute(cmd)
dyle@52
   618