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