OpenSecurity/bin/vmmanager.pyw
author BarthaM@N3SIM1218.D03.arc.local
Thu, 22 May 2014 16:01:28 +0100
changeset 170 81d5f845d966
parent 169 a133c8d03ef8
child 171 2701e921bf4c
permissions -rwxr-xr-x
corrected terminate / update template / etc.
mb@90
     1
'''
mb@90
     2
Created on Nov 19, 2013
mb@90
     3
mb@90
     4
@author: BarthaM
mb@90
     5
'''
mb@90
     6
import os
mb@90
     7
import os.path
mb@90
     8
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
mb@90
     9
import sys
mb@90
    10
import re
mb@90
    11
mb@90
    12
from cygwin import Cygwin
mb@90
    13
from environment import Environment
mb@90
    14
import threading
mb@90
    15
import time
mb@90
    16
import string
mb@90
    17
mb@90
    18
import shutil
mb@90
    19
import stat
mb@90
    20
import tempfile
mb@90
    21
from opensecurity_util import logger, setupLogger, OpenSecurityException
mb@90
    22
import ctypes
mb@90
    23
import itertools
BarthaM@143
    24
import win32api
BarthaM@143
    25
import win32con
BarthaM@143
    26
import win32security
BarthaM@151
    27
import urllib
BarthaM@151
    28
import urllib2
mb@90
    29
DEBUG = True
mb@90
    30
BarthaM@159
    31
BarthaM@159
    32
new_sdvm_lock = threading.Lock()
BarthaM@159
    33
mb@90
    34
class VMManagerException(Exception):
mb@90
    35
    def __init__(self, value):
mb@90
    36
        self.value = value
mb@90
    37
    def __str__(self):
mb@90
    38
        return repr(self.value)
mb@90
    39
mb@90
    40
class USBFilter:
mb@90
    41
    vendorid = ""
mb@90
    42
    productid = ""
mb@90
    43
    revision = ""
mb@90
    44
    
mb@90
    45
    def __init__(self, vendorid, productid, revision):
mb@90
    46
        self.vendorid = vendorid.lower()
mb@90
    47
        self.productid = productid.lower()
mb@90
    48
        self.revision = revision.lower()
mb@90
    49
        return
mb@90
    50
    
mb@90
    51
    def __eq__(self, other):
mb@90
    52
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@90
    53
    
mb@90
    54
    def __hash__(self):
mb@90
    55
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@90
    56
    
mb@90
    57
    def __repr__(self):
mb@90
    58
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@90
    59
    
mb@90
    60
    #def __getitem__(self, item):
mb@90
    61
    #    return self.coords[item]
mb@90
    62
 
mb@90
    63
class VMManager(object):
mb@90
    64
    vmRootName = "SecurityDVM"
mb@90
    65
    systemProperties = None
mb@90
    66
    _instance = None
mb@90
    67
    machineFolder = ''
mb@90
    68
    rsdHandler = None
BarthaM@141
    69
    browsingManager = None
oliver@131
    70
    status_message = 'Starting up...'
oliver@131
    71
oliver@131
    72
 
oliver@131
    73
    def __init__(self):
oliver@131
    74
oliver@131
    75
        self.systemProperties = self.getSystemProperties()
oliver@133
    76
        self.machineFolder = self.systemProperties["Default machine folder"]
oliver@131
    77
oliver@131
    78
        # only proceed if we have a working background environment
oliver@131
    79
        if self.backend_ok():
oliver@131
    80
            self.cleanup()
BarthaM@170
    81
            self.start()
oliver@131
    82
        else:
oliver@131
    83
            logger.critical(self.status_message)
mb@90
    84
    
oliver@131
    85
mb@90
    86
    @staticmethod
mb@90
    87
    def getInstance():
mb@90
    88
        if VMManager._instance == None:
mb@90
    89
            VMManager._instance = VMManager()
mb@90
    90
        return VMManager._instance
mb@90
    91
    
oliver@131
    92
oliver@131
    93
    def backend_ok(self):
oliver@131
    94
oliver@131
    95
        """check if the backend (VirtualBox) is sufficient for our task"""
oliver@131
    96
oliver@131
    97
        # ensure we have our system props
oliver@131
    98
        if self.systemProperties == None:
oliver@131
    99
            self.systemProperties = self.getSystemProperties()
oliver@131
   100
        if self.systemProperties == None:
oliver@131
   101
            self.status_message = 'Failed to get backend system properties. Is Backend (VirtualBox?) installed?'
oliver@131
   102
            return False
oliver@131
   103
oliver@131
   104
        # check for existing Extension pack
oliver@131
   105
        if not 'Remote desktop ExtPack' in self.systemProperties:
oliver@131
   106
            self.status_message = 'No remote desktop extension pack found. Please install the "Oracle VM VirtualBox Extension Pack" from https://www.virtualbox.org/wiki/Downloads.'
oliver@131
   107
            return False
oliver@131
   108
        if self.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ':
oliver@131
   109
            self.status_message = 'Unsure if suitable extension pack is installed. Please install the "Oracle VM VirtualBox Extension Pack" from https://www.virtualbox.org/wiki/Downloads.'
oliver@131
   110
            return False
oliver@131
   111
oliver@131
   112
        # check if we do have our root VMs installed
oliver@131
   113
        vms = self.listVM()
oliver@131
   114
        if not self.vmRootName in vms:
oliver@131
   115
            self.status_message = 'Unable to locate root SecurityDVM. Please download and setup the initial image.'
oliver@131
   116
            return False
oliver@131
   117
oliver@131
   118
        # basically all seems nice and ready to rumble
oliver@131
   119
        self.status_message = 'All is ok.'
oliver@131
   120
oliver@131
   121
        return True
BarthaM@170
   122
    
BarthaM@170
   123
    def stop(self):
mb@90
   124
        if self.rsdHandler != None:
mb@90
   125
            self.rsdHandler.stop()
mb@90
   126
            self.rsdHandler.join()
BarthaM@170
   127
            self.rsdHandler = None
BarthaM@170
   128
            
BarthaM@170
   129
        if self.browsingManager != None:
BarthaM@170
   130
            self.browsingManager.stop()
BarthaM@170
   131
            self.browsingManager.join()
BarthaM@170
   132
            self.browsingManager = None
BarthaM@170
   133
    
BarthaM@170
   134
    def start(self):
BarthaM@170
   135
        self.stop()
BarthaM@170
   136
        self.browsingManager = BrowsingManager(self)
BarthaM@170
   137
        self.browsingManager.start()
BarthaM@170
   138
        self.rsdHandler = DeviceHandler(self)
BarthaM@170
   139
        self.rsdHandler.start()
BarthaM@170
   140
        
BarthaM@170
   141
BarthaM@170
   142
    def cleanup(self):
BarthaM@170
   143
        self.stop()
mb@90
   144
        drives = self.getNetworkDrives()
mb@90
   145
        for drive in drives.keys():
BarthaM@166
   146
            try:
BarthaM@166
   147
                result = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+drive).readline()
BarthaM@166
   148
            except urllib2.URLError:
BarthaM@170
   149
                logger.info("Network drive disconnect skipped. OpenSecurity Tray client not started yet.")
BarthaM@151
   150
            
mb@90
   151
        for vm in self.listSDVM():
mb@90
   152
            self.poweroffVM(vm)
mb@90
   153
            self.removeVM(vm)
mb@90
   154
        
mb@90
   155
    # return hosty system properties
mb@90
   156
    def getSystemProperties(self):
BarthaM@151
   157
        result = Cygwin.checkResult(Cygwin.vboxExecute('list systemproperties'))
mb@90
   158
        if result[1]=='':
mb@90
   159
            return None
mb@90
   160
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@90
   161
        return props
mb@90
   162
    
mb@90
   163
    # return the folder containing the guest VMs     
mb@90
   164
    def getMachineFolder(self):
mb@90
   165
        return self.machineFolder
mb@90
   166
mb@90
   167
    # list all existing VMs registered with VBox
mb@90
   168
    def listVM(self):
BarthaM@151
   169
        result = Cygwin.checkResult(Cygwin.vboxExecute('list vms'))[1]
mb@90
   170
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   171
        return vms
mb@90
   172
    
mb@90
   173
    # list running VMs
mb@90
   174
    def listRunningVMS(self):
BarthaM@151
   175
        result = Cygwin.checkResult(Cygwin.vboxExecute('list runningvms'))[1]
mb@90
   176
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   177
        return vms
mb@90
   178
    
mb@90
   179
    # list existing SDVMs
mb@90
   180
    def listSDVM(self):
mb@90
   181
        vms = self.listVM()
mb@90
   182
        svdms = []
mb@90
   183
        for vm in vms:
mb@90
   184
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@90
   185
                svdms.append(vm)
mb@90
   186
        return svdms
mb@90
   187
    
mb@90
   188
    # generate valid (not already existing SDVM name). necessary for creating a new VM
BarthaM@159
   189
    def genSDVMName(self):
mb@90
   190
        vms = self.listVM()
mb@90
   191
        for i in range(0,999):
mb@90
   192
            if(not self.vmRootName+str(i) in vms):
mb@90
   193
                return self.vmRootName+str(i)
mb@90
   194
        return ''
mb@90
   195
    
mb@90
   196
    # check if the device is mass storage type
mb@90
   197
    @staticmethod
mb@90
   198
    def isMassStorageDevice(device):
oliver@167
   199
        #TODO: implement filtering for card readers (this is olivers) 
oliver@167
   200
        #      alternatively implement handling of multiple drives on same USB client
oliver@167
   201
        if device.vendorid == '058f' and  device.productid=='6362':
oliver@167
   202
            return False
mb@90
   203
        keyname = 'SYSTEM\CurrentControlSet\Enum\USB' + '\VID_' + device.vendorid+'&'+'PID_'+ device.productid
BarthaM@143
   204
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname)
mb@90
   205
        #subkeys = _winreg.QueryInfoKey(key)[0]
mb@90
   206
        #for i in range(0, subkeys):
mb@90
   207
        #    print _winreg.EnumKey(key, i)     
BarthaM@143
   208
        devinfokeyname = win32api.RegEnumKey(key, 0)
BarthaM@143
   209
        win32api.RegCloseKey(key)
mb@90
   210
BarthaM@143
   211
        devinfokey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname+'\\'+devinfokeyname)
BarthaM@143
   212
        value = win32api.RegQueryValueEx(devinfokey, 'SERVICE')[0]
BarthaM@143
   213
        win32api.RegCloseKey(devinfokey)
mb@90
   214
        
mb@90
   215
        return 'USBSTOR' in value
mb@90
   216
    
mb@90
   217
    # return the RSDs connected to the host
mb@90
   218
    @staticmethod
mb@90
   219
    def getConnectedRSDS():
BarthaM@151
   220
        results = Cygwin.checkResult(Cygwin.vboxExecute('list usbhost'))[1]
mb@90
   221
        results = results.split('Host USB Devices:')[1].strip()
mb@90
   222
        
mb@90
   223
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   224
        rsds = dict()   
mb@90
   225
        for item in items:
mb@90
   226
            props = dict()
mb@90
   227
            for line in item.splitlines():
mb@90
   228
                if line != "":         
mb@90
   229
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   230
                    props[k] = v
mb@90
   231
            
mb@90
   232
            #if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@90
   233
            
mb@90
   234
            usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@90
   235
                                    re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@90
   236
                                    re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@90
   237
            if VMManager.isMassStorageDevice(usb_filter):
mb@90
   238
                rsds[props['UUID']] = usb_filter;
mb@90
   239
                logger.debug(usb_filter)
mb@90
   240
        return rsds
mb@90
   241
    
mb@90
   242
    # return the RSDs attached to all existing SDVMs
mb@90
   243
    def getAttachedRSDs(self):
mb@90
   244
        vms = self.listSDVM()
mb@90
   245
        attached_devices = dict()
mb@90
   246
        for vm in vms:
mb@90
   247
            rsd_filter = self.getUSBFilter(vm)
mb@90
   248
            if rsd_filter != None:
mb@90
   249
                attached_devices[vm] = rsd_filter
mb@90
   250
        return attached_devices
mb@90
   251
    
mb@90
   252
    # configures hostonly networking and DHCP server. requires admin rights
mb@90
   253
    def configureHostNetworking(self):
mb@90
   254
        #cmd = 'vboxmanage list hostonlyifs'
mb@90
   255
        #Cygwin.vboxExecute(cmd)
mb@90
   256
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
mb@90
   257
        #Cygwin.vboxExecute(cmd)
mb@90
   258
        #cmd = 'vboxmanage hostonlyif create'
mb@90
   259
        #Cygwin.vboxExecute(cmd)
BarthaM@151
   260
        Cygwin.checkResult(Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'))
mb@90
   261
        #cmd = 'vboxmanage dhcpserver add'
mb@90
   262
        #Cygwin.vboxExecute(cmd)
BarthaM@151
   263
        Cygwin.checkResult(Cygwin.vboxExecute('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@90
   264
    
BarthaM@125
   265
    def isSDVMExisting(self, vm_name):
BarthaM@125
   266
        sdvms = self.listSDVM()
BarthaM@125
   267
        return vm_name in sdvms
BarthaM@125
   268
        
mb@90
   269
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
mb@90
   270
    def createVM(self, vm_name):
BarthaM@125
   271
        if self.isSDVMExisting(vm_name):
BarthaM@125
   272
            return
BarthaM@125
   273
        #remove eventually existing SDVM folder
BarthaM@125
   274
        machineFolder = Cygwin.cygPath(self.machineFolder)
BarthaM@151
   275
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   276
        hostonly_if = self.getHostOnlyIFs()
BarthaM@151
   277
        Cygwin.checkResult(Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register'))
BarthaM@151
   278
        Cygwin.checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'))
BarthaM@151
   279
        Cygwin.checkResult(Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'))
BarthaM@159
   280
BarthaM@159
   281
    #create new SecurityDVM with automatically generated name from template (thread safe)        
BarthaM@159
   282
    def newSDVM(self):
BarthaM@159
   283
        with new_sdvm_lock:
BarthaM@159
   284
            vm_name = self.genSDVMName()
BarthaM@159
   285
            self.createVM(vm_name)
BarthaM@159
   286
        return vm_name
mb@90
   287
    
mb@90
   288
    # attach storage image to controller
mb@90
   289
    def storageAttach(self, vm_name):
mb@90
   290
        if self.isStorageAttached(vm_name):
mb@90
   291
            self.storageDetach(vm_name)
BarthaM@151
   292
        Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'))
mb@90
   293
    
mb@90
   294
    # return true if storage is attached 
mb@90
   295
    def isStorageAttached(self, vm_name):
mb@90
   296
        info = self.getVMInfo(vm_name)
mb@90
   297
        return (info['SATA-0-0']!='none')
mb@90
   298
    
mb@90
   299
    # detach storage from controller
mb@90
   300
    def storageDetach(self, vm_name):
mb@90
   301
        if self.isStorageAttached(vm_name):
BarthaM@151
   302
            Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'))
mb@90
   303
    
mb@90
   304
    def changeStorageType(self, filename, storage_type):
BarthaM@151
   305
        Cygwin.checkResult(Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type))
mb@90
   306
    
BarthaM@170
   307
    def removeSnapshots(self, vm_name):
BarthaM@151
   308
        results = Cygwin.checkResult(Cygwin.vboxExecute('list hdds'))[1]
mb@90
   309
        results = results.replace('Parent UUID', 'Parent')
mb@90
   310
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   311
        
mb@90
   312
        snaps = dict()   
mb@90
   313
        for item in items:
mb@90
   314
            props = dict()
mb@90
   315
            for line in item.splitlines():
mb@90
   316
                if line != "":         
mb@90
   317
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   318
                    props[k] = v;
mb@90
   319
            snaps[props['UUID']] = props
mb@90
   320
        
BarthaM@170
   321
        template_storage = self.machineFolder + '\\' + vm_name + '\\' + vm_name + '.vmdk'
mb@90
   322
        
mb@90
   323
        # find template uuid
mb@90
   324
        template_uuid = ''
mb@90
   325
        for hdd in snaps.values():
mb@90
   326
            if hdd['Location'] == template_storage:
mb@90
   327
                template_uuid = hdd['UUID']
mb@90
   328
        logger.debug('found parent uuid ' + template_uuid)
mb@90
   329
        
mb@90
   330
        # remove snapshots 
mb@90
   331
        for hdd in snaps.values():
mb@90
   332
            if hdd['Parent'] == template_uuid:
mb@90
   333
                #template_uuid = hdd['UUID']
mb@90
   334
                logger.debug('removing snapshot ' + hdd['UUID'])
BarthaM@151
   335
                Cygwin.checkResult(Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete'))#[1]
mb@90
   336
                # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
BarthaM@170
   337
                
BarthaM@170
   338
    # list storage snaphots for VM
BarthaM@170
   339
    def updateTemplate(self):
BarthaM@170
   340
        self.stop()
BarthaM@170
   341
        self.cleanup()
BarthaM@170
   342
        self.poweroffVM('SecurityDVM')
BarthaM@170
   343
        self.waitShutdown('SecurityDVM')
mb@90
   344
        
BarthaM@170
   345
        # check for updates
BarthaM@170
   346
        self.genCertificateISO('SecurityDVM')
BarthaM@170
   347
        self.attachCertificateISO('SecurityDVM')
BarthaM@170
   348
        
BarthaM@170
   349
        self.storageDetach('SecurityDVM')
BarthaM@170
   350
        self.removeSnapshots('SecurityDVM')
BarthaM@170
   351
        
BarthaM@170
   352
        template_storage = self.machineFolder + '\\' + 'SecurityDVM' + '\\' + 'SecurityDVM' + '.vmdk'
BarthaM@170
   353
        #TODO:// modify to take vm name as argument
mb@90
   354
        self.changeStorageType(template_storage,'normal')
mb@90
   355
        self.storageAttach('SecurityDVM')
mb@90
   356
        self.startVM('SecurityDVM')
mb@90
   357
        self.waitStartup('SecurityDVM')
BarthaM@151
   358
        Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
BarthaM@151
   359
        Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
mb@90
   360
        #self.stopVM('SecurityDVM')
mb@90
   361
        self.hibernateVM('SecurityDVM')
mb@90
   362
        self.waitShutdown('SecurityDVM')
mb@90
   363
        self.storageDetach('SecurityDVM')
mb@90
   364
        self.changeStorageType(template_storage,'immutable')
mb@90
   365
        self.storageAttach('SecurityDVM')
BarthaM@170
   366
        
BarthaM@170
   367
        self.start()
mb@90
   368
    
mb@90
   369
    #remove VM from the system. should be used on VMs returned by listSDVMs    
mb@90
   370
    def removeVM(self, vm_name):
mb@90
   371
        logger.info('Removing ' + vm_name)
BarthaM@151
   372
        Cygwin.checkResult(Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete'))
BarthaM@170
   373
        #TODO:// try to close medium if still existing
BarthaM@170
   374
        #Cygwin.checkResult(Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete'))#[1]
BarthaM@170
   375
        self.removeVMFolder(vm_name)
BarthaM@170
   376
    
BarthaM@170
   377
    def removeVMFolder(self, vm_name):
mb@90
   378
        machineFolder = Cygwin.cygPath(self.machineFolder)
BarthaM@151
   379
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   380
    
mb@90
   381
    # start VM
mb@90
   382
    def startVM(self, vm_name):
mb@90
   383
        logger.info('Starting ' +  vm_name)
BarthaM@151
   384
        result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' ))
mb@90
   385
        while 'successfully started' not in result[1]:
mb@90
   386
            logger.error("Failed to start SDVM: " + vm_name + " retrying")
oliver@129
   387
            logger.error("Command returned:\n" + result[2])
mb@90
   388
            time.sleep(1)
BarthaM@151
   389
            result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless'))
mb@90
   390
        return result[0]
mb@90
   391
    
mb@90
   392
    # return wether VM is running or not
mb@90
   393
    def isVMRunning(self, vm_name):
mb@90
   394
        return vm_name in self.listRunningVMS()    
mb@90
   395
    
mb@90
   396
    # stop VM
mb@90
   397
    def stopVM(self, vm_name):
mb@90
   398
        logger.info('Sending shutdown signal to ' + vm_name)
BarthaM@151
   399
        Cygwin.checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' ))
mb@90
   400
    
mb@90
   401
    # stop VM
mb@90
   402
    def hibernateVM(self, vm_name):
mb@95
   403
        logger.info('Sending hibernate-disk signal to ' + vm_name)
oliver@167
   404
        Cygwin.checkResult(Cygwin.sshBackgroundExecute( '"sudo hibernate-disk"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False))
mb@90
   405
            
mb@90
   406
    # poweroff VM
mb@90
   407
    def poweroffVM(self, vm_name):
mb@90
   408
        if not self.isVMRunning(vm_name):
mb@90
   409
            return
mb@90
   410
        logger.info('Powering off ' + vm_name)
BarthaM@151
   411
        return Cygwin.checkResult(Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff'))
mb@90
   412
    
mb@90
   413
    #list the hostonly IFs exposed by the VBox host
mb@90
   414
    @staticmethod    
mb@90
   415
    def getHostOnlyIFs():
mb@90
   416
        result = Cygwin.vboxExecute('list hostonlyifs')[1]
mb@90
   417
        if result=='':
mb@90
   418
            return None
mb@90
   419
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@90
   420
        return props
mb@90
   421
    
mb@90
   422
    # return the hostOnly IP for a running guest or the host
mb@90
   423
    @staticmethod    
mb@90
   424
    def getHostOnlyIP(vm_name):
mb@90
   425
        if vm_name == None:
oliver@129
   426
            logger.info('Getting hostOnly IP address for Host')
mb@90
   427
            return VMManager.getHostOnlyIFs()['IPAddress']
mb@90
   428
        else:
oliver@129
   429
            logger.info('Getting hostOnly IP address ' + vm_name)
BarthaM@151
   430
            result = Cygwin.checkResult(Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'))
mb@90
   431
            if result=='':
mb@90
   432
                return None
mb@90
   433
            result = result[1]
mb@90
   434
            if result.startswith('No value set!'):
mb@90
   435
                return None
mb@90
   436
            return result[result.index(':')+1:].strip()
mb@90
   437
            
mb@90
   438
    # attach removable storage device to VM by provision of filter
mb@90
   439
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@151
   440
        return Cygwin.checkResult(Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision))
mb@90
   441
    
mb@90
   442
    # detach removable storage from VM by 
mb@90
   443
    def detachRSD(self, vm_name):
BarthaM@151
   444
        return Cygwin.checkResult(Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name))
mb@90
   445
        
mb@90
   446
    # return the description set for an existing VM
mb@90
   447
    def getVMInfo(self, vm_name):
BarthaM@151
   448
        results = Cygwin.checkResult(Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable'))[1]
mb@90
   449
        props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@90
   450
        return props
mb@90
   451
    
mb@90
   452
    # return the configured USB filter for an existing VM 
mb@90
   453
    def getUSBFilter(self, vm_name):
mb@90
   454
        props = self.getVMInfo(vm_name)
mb@90
   455
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@90
   456
        keyset = set(props.keys())
mb@90
   457
        usb_filter = None
mb@90
   458
        if keyset.issuperset(keys):
mb@90
   459
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@90
   460
        return usb_filter
mb@90
   461
    
mb@90
   462
    #generates ISO containing authorized_keys for use with guest VM
mb@90
   463
    def genCertificateISO(self, vm_name):
mb@90
   464
        machineFolder = Cygwin.cygPath(self.machineFolder)
mb@90
   465
        # remove .ssh folder if exists
BarthaM@151
   466
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   467
        # remove .ssh folder if exists
BarthaM@151
   468
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
mb@90
   469
        # create .ssh folder in vm_name
BarthaM@151
   470
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   471
        # generate dvm_key pair in vm_name / .ssh     
BarthaM@151
   472
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/ssh-keygen -q -t rsa -N \\\"\\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"'))
mb@90
   473
        # move out private key
BarthaM@151
   474
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   475
        # set permissions for private key
BarthaM@151
   476
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
mb@90
   477
        # rename public key to authorized_keys
BarthaM@151
   478
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
mb@90
   479
        # set permissions for authorized_keys
BarthaM@151
   480
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
mb@90
   481
        # generate iso image with .ssh/authorized keys
BarthaM@151
   482
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   483
    
mb@90
   484
    # attaches generated ssh public cert to guest vm
mb@90
   485
    def attachCertificateISO(self, vm_name):
BarthaM@151
   486
        result = Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'))
mb@90
   487
        return result
mb@90
   488
    
mb@90
   489
    # wait for machine to come up
mb@90
   490
    def waitStartup(self, vm_name, timeout_ms = 30000):
BarthaM@151
   491
        Cygwin.checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout'))
mb@90
   492
        return VMManager.getHostOnlyIP(vm_name)
mb@90
   493
    
mb@90
   494
    # wait for machine to shutdown
mb@90
   495
    def waitShutdown(self, vm_name):
mb@90
   496
        while vm_name in self.listRunningVMS():
mb@90
   497
            time.sleep(1)
mb@90
   498
        return
mb@90
   499
    
BarthaM@135
   500
    #Small function to check if the mentioned location is a directory
mb@90
   501
    def isDirectory(self, path):
BarthaM@151
   502
        result = Cygwin.checkResult(Cygwin.cmdExecute('dir ' + path + ' | FIND ".."'))
mb@90
   503
        return string.find(result[1], 'DIR',)
mb@90
   504
    
mb@90
   505
    def getNetworkDrives(self):
mb@90
   506
        ip = VMManager.getHostOnlyIP(None)
mb@90
   507
        ip = ip[:ip.rindex('.')]
mb@90
   508
        drives = dict()    
BarthaM@151
   509
        result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
oliver@167
   510
oliver@167
   511
        #logger.info( result[1] )
mb@90
   512
        for line in result[1].splitlines():
mb@90
   513
            if ip in line:
mb@90
   514
                parts = line.split()
mb@90
   515
                drives[parts[1]] = parts[2]
oliver@167
   516
mb@90
   517
        return drives
mb@90
   518
mb@90
   519
    def getNetworkDrive(self, vm_name):
mb@90
   520
        ip = self.getHostOnlyIP(vm_name)
BarthaM@151
   521
        result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
mb@90
   522
        for line in result[1].splitlines():
mb@90
   523
            if line != None and ip in line:
mb@90
   524
                parts = line.split()
BarthaM@135
   525
                return parts[1]
oliver@167
   526
    
oliver@167
   527
    def genNetworkDrive(self):
oliver@167
   528
        network_drives = self.getNetworkDrives()
oliver@167
   529
        logger.info("Used network drive letters: "+ str(network_drives.keys()).strip('[]') ) 
oliver@167
   530
        logical_drives = VMManager.getLogicalDrives()
oliver@167
   531
        logger.info("Used logical drive letters: "+ str(logical_drives).strip('[]') )
oliver@167
   532
        drives = list(map(chr, range(68, 91)))  
oliver@167
   533
        for drive in drives:
oliver@167
   534
            if drive+':' not in network_drives and drive not in logical_drives:
oliver@167
   535
                return drive+':'
BarthaM@151
   536
            
mb@90
   537
    @staticmethod
mb@90
   538
    def getLogicalDrives():
mb@90
   539
        drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@90
   540
        return list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@90
   541
    
mb@90
   542
    @staticmethod
mb@90
   543
    def getDriveType(drive):
mb@90
   544
        return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
mb@90
   545
    
mb@90
   546
    @staticmethod
mb@90
   547
    def getVolumeInfo(drive):
mb@90
   548
        volumeNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   549
        fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   550
        serial_number = None
mb@90
   551
        max_component_length = None
mb@90
   552
        file_system_flags = None
mb@90
   553
        
mb@90
   554
        rc = ctypes.cdll.kernel32.GetVolumeInformationW(
mb@90
   555
            #ctypes.c_wchar_p("F:\\"),
mb@90
   556
            u"%s:\\"%drive,
mb@90
   557
            volumeNameBuffer,
mb@90
   558
            ctypes.sizeof(volumeNameBuffer),
mb@90
   559
            serial_number,
mb@90
   560
            max_component_length,
mb@90
   561
            file_system_flags,
mb@90
   562
            fileSystemNameBuffer,
mb@90
   563
            ctypes.sizeof(fileSystemNameBuffer)
mb@90
   564
        )
mb@90
   565
        
mb@90
   566
        return volumeNameBuffer.value, fileSystemNameBuffer.value
BarthaM@141
   567
    
BarthaM@141
   568
    # handles browsing request    
BarthaM@141
   569
    def handleBrowsingRequest(self):
BarthaM@141
   570
        handler = BrowsingHandler(self)
BarthaM@141
   571
        handler.start()
BarthaM@141
   572
        return 'ok'
BarthaM@143
   573
    
BarthaM@143
   574
    def getActiveUserName(self):
BarthaM@143
   575
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI')
BarthaM@143
   576
        v = str(win32api.RegQueryValueEx(key, 'LastLoggedOnUser')[0])
BarthaM@143
   577
        win32api.RegCloseKey(key)
BarthaM@143
   578
        user_name = win32api.ExpandEnvironmentStrings(v)
BarthaM@143
   579
        return user_name
BarthaM@143
   580
        
BarthaM@143
   581
    def getUserSID(self, user_name):
oliver@167
   582
        domain, user = user_name.split("\\")
oliver@167
   583
        account_name = win32security.LookupAccountName(domain, user)
oliver@167
   584
        if account_name == None:
oliver@167
   585
            logger.error("Failed lookup account name for user " + user_name)
oliver@167
   586
            return None
BarthaM@143
   587
        sid = win32security.ConvertSidToStringSid(account_name[0])
oliver@167
   588
        if sid == None:
oliver@167
   589
            logger.error("Failed converting SID for account " + account_name[0])
oliver@167
   590
            return None
BarthaM@143
   591
        return sid
BarthaM@143
   592
        
BarthaM@143
   593
    def getAppDataDir(self, sid):    
BarthaM@143
   594
        key = win32api.RegOpenKey(win32con.HKEY_USERS, sid + '\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
BarthaM@143
   595
        value, type = win32api.RegQueryValueEx(key, "AppData")
BarthaM@143
   596
        win32api.RegCloseKey(key)
BarthaM@143
   597
        return value
BarthaM@143
   598
        
BarthaM@143
   599
        #key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' + '\\' + sid)
BarthaM@143
   600
        #value, type = win32api.RegQueryValueEx(key, "ProfileImagePath")
BarthaM@143
   601
        #print value
BarthaM@143
   602
    
BarthaM@143
   603
    def backupFile(self, src, dest):
BarthaM@143
   604
        certificate = Cygwin.cygPath(self.getMachineFolder()) + '/' + self.browsingManager.vm_name + '/dvm_key'
BarthaM@143
   605
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "osecuser@' + self.browsingManager.ip_addr + ':' + src + '" "' + dest + '"'
BarthaM@143
   606
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)
BarthaM@143
   607
    
BarthaM@143
   608
    def restoreFile(self, src, dest):
BarthaM@143
   609
        certificate = Cygwin.cygPath(self.getMachineFolder()) + '/' + self.browsingManager.vm_name + '/dvm_key'
BarthaM@143
   610
        #command = '-r -v -o StrictHostKeyChecking=no -i \"' + certificate + '\" \"' + src + '\" \"osecuser@' + self.browsingManager.ip_addr + ':' + dest + '\"'
BarthaM@143
   611
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "' + src + '" "osecuser@' + self.browsingManager.ip_addr + ':' + dest + '"'
BarthaM@143
   612
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)    
mb@90
   613
BarthaM@141
   614
BarthaM@141
   615
#handles browsing session creation 
BarthaM@141
   616
class BrowsingHandler(threading.Thread):
mb@90
   617
    vmm = None
BarthaM@141
   618
    def __init__(self, vmmanager):
BarthaM@141
   619
         threading.Thread.__init__(self)
BarthaM@141
   620
         self.vmm = vmmanager
BarthaM@141
   621
        
BarthaM@141
   622
    def run(self):
oliver@169
   623
        #browser = '\\\"/usr/bin/chromium; pidof dbus-launch | xargs kill\\\"'
oliver@169
   624
        browser = '\\\"/usr/bin/chromium\\\"'
oliver@169
   625
        #if not Cygwin.is_X11_running():
oliver@169
   626
        #    self.vmm.browsingManager.restart.set()
oliver@169
   627
        #    return
BarthaM@162
   628
        
BarthaM@141
   629
        try:
BarthaM@143
   630
            self.vmm.browsingManager.started.wait() 
BarthaM@151
   631
            result = Cygwin.checkResult(Cygwin.sshExecuteX11(browser, self.vmm.browsingManager.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vmm.browsingManager.vm_name + '/dvm_key'))
oliver@169
   632
            self.vmm.backupFile('/home/osecuser/.config/chromium', self.vmm.browsingManager.appDataDir + '/OpenSecurity/')
BarthaM@141
   633
        except:
oliver@169
   634
            logger.info("BrowsingHandler closing. Restarting browsing SDVM.")
oliver@169
   635
BarthaM@141
   636
        self.vmm.browsingManager.restart.set()
BarthaM@141
   637
        
BarthaM@141
   638
            
BarthaM@141
   639
# handles browsing Vm creation and destruction                    
BarthaM@141
   640
class BrowsingManager(threading.Thread):   
BarthaM@141
   641
    vmm = None
BarthaM@141
   642
    running = True
BarthaM@141
   643
    restart = None
BarthaM@141
   644
    ip_addr = None
BarthaM@141
   645
    vm_name = None
BarthaM@141
   646
    drive = None
BarthaM@143
   647
    appDataDir = None
BarthaM@141
   648
    
mb@90
   649
    def __init__(self, vmmanager):
mb@90
   650
        threading.Thread.__init__(self)
mb@90
   651
        self.vmm = vmmanager
BarthaM@141
   652
        self.restart = threading.Event()
BarthaM@141
   653
        self.started = threading.Event()
BarthaM@170
   654
    
BarthaM@170
   655
    def stop(self):
BarthaM@170
   656
        self.running = False
BarthaM@170
   657
        self.restart.set()   
mb@90
   658
     
mb@90
   659
    def run(self):
BarthaM@141
   660
        while self.running:
BarthaM@141
   661
            self.restart.clear()
BarthaM@141
   662
            self.started.clear()
BarthaM@166
   663
            
BarthaM@166
   664
            if self.drive == None:
BarthaM@166
   665
                logger.info("Missing browsing SDVM's network drive letter. Skipping disconnect")
BarthaM@166
   666
            else:
BarthaM@166
   667
                try:
BarthaM@166
   668
                    browsing_vm = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+self.drive).readline()
BarthaM@166
   669
                    self.drive = None
BarthaM@166
   670
                except urllib2.URLError:
BarthaM@166
   671
                    logger.error("Network drive disconnect failed. OpenSecurity Tray client not running.")
BarthaM@166
   672
                    continue
BarthaM@135
   673
            
BarthaM@141
   674
            self.ip_addr = None
BarthaM@166
   675
BarthaM@141
   676
            if self.vm_name != None:
BarthaM@141
   677
                self.vmm.poweroffVM(self.vm_name)
BarthaM@141
   678
                self.vmm.removeVM(self.vm_name)
BarthaM@141
   679
            
BarthaM@141
   680
            try:
BarthaM@159
   681
                self.vm_name = self.vmm.newSDVM()
BarthaM@141
   682
                self.vmm.storageAttach(self.vm_name)
BarthaM@141
   683
                self.vmm.genCertificateISO(self.vm_name)
BarthaM@141
   684
                self.vmm.attachCertificateISO(self.vm_name)
BarthaM@141
   685
                self.vmm.startVM(self.vm_name)
BarthaM@141
   686
                self.ip_addr = self.vmm.waitStartup(self.vm_name)
BarthaM@141
   687
                if self.ip_addr == None:
oliver@167
   688
                    logger.error("Failed to get ip address")
BarthaM@141
   689
                    continue
oliver@167
   690
                else:
oliver@167
   691
                    logger.info("Got IP address for " + self.vm_name + ' ' + self.ip_addr)
oliver@167
   692
                
BarthaM@141
   693
                self.drive = self.vmm.genNetworkDrive()
BarthaM@141
   694
                if self.drive == None:
oliver@167
   695
                    logger.error("Failed to assign Network drive letter")
BarthaM@141
   696
                    continue
oliver@167
   697
                else:
oliver@167
   698
                    logger.info("Assigned drive " + self.drive + " to " + self.vm_name)
BarthaM@151
   699
                
BarthaM@166
   700
                try:
BarthaM@166
   701
                    net_resource = '\\\\' + self.ip_addr + '\\Download'
BarthaM@166
   702
                    result = urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'drive_letter='+self.drive+'&net_resource='+net_resource).readline()
BarthaM@166
   703
                except urllib2.URLError:
BarthaM@166
   704
                    logger.error("Network drive connect failed. OpenSecurity Tray client not running.")
BarthaM@166
   705
                    self.drive = None
BarthaM@166
   706
                    continue
BarthaM@143
   707
                
BarthaM@143
   708
                user = self.vmm.getActiveUserName()
oliver@167
   709
                if user == None:
oliver@167
   710
                    logger.error("Cannot get active user name")
oliver@167
   711
                    continue
oliver@167
   712
                else:
oliver@167
   713
                    logger.info('Got active user name ' + user)
BarthaM@143
   714
                sid = self.vmm.getUserSID(user)
oliver@167
   715
                if sid == None:
oliver@167
   716
                    logger.error("Cannot get SID for active user")
oliver@167
   717
                    continue
oliver@167
   718
                else:
oliver@167
   719
                    logger.info("Got active user SID " + sid + " for user " + user)
oliver@167
   720
                    
BarthaM@143
   721
                path = self.vmm.getAppDataDir(sid)
oliver@167
   722
                if path == None:
oliver@167
   723
                    logger.error("Cannot get AppDataDir for active user")
oliver@167
   724
                    continue
oliver@167
   725
                else:
oliver@167
   726
                    logger.info("Got AppData dir for user " + user + ': ' + path)
oliver@167
   727
                
BarthaM@143
   728
                self.appDataDir = Cygwin.cygPath(path)
oliver@167
   729
                logger.info("Restoring browser settings in AppData dir " + self.appDataDir)
BarthaM@149
   730
                # create OpenSecurity settings dir on local machine user home /AppData/Roaming 
BarthaM@151
   731
                Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + self.appDataDir + '/OpenSecurity\\\"'))
BarthaM@143
   732
                # create chromium settings dir on local machine if not existing
BarthaM@151
   733
                Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + self.appDataDir + '/OpenSecurity/chromium\\\"'))
BarthaM@143
   734
                # create chromium settings dir on remote machine if not existing
BarthaM@151
   735
                Cygwin.checkResult(Cygwin.sshExecute('"mkdir -p \\\"/home/osecuser/.config\\\""', self.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key'))
BarthaM@143
   736
                #restore settings on vm
BarthaM@143
   737
                self.vmm.restoreFile(self.appDataDir + '/OpenSecurity/chromium', '/home/osecuser/.config/')
oliver@167
   738
                self.started.set()
oliver@167
   739
                logger.error("Browsing SDVM running.")
BarthaM@141
   740
                self.restart.wait()
BarthaM@141
   741
            except:
BarthaM@141
   742
                logger.error("BrowsingHandler failed. Cleaning up")
mb@90
   743
                
mb@90
   744
class DeviceHandler(threading.Thread): 
mb@90
   745
    vmm = None
mb@90
   746
    attachedRSDs = None  
mb@90
   747
    connectedRSDs = None
mb@90
   748
    running = True
mb@90
   749
    def __init__(self, vmmanger): 
mb@90
   750
        threading.Thread.__init__(self)
mb@90
   751
        self.vmm = vmmanger
mb@90
   752
 
mb@90
   753
    def stop(self):
mb@90
   754
        self.running = False
mb@90
   755
        
mb@90
   756
    def run(self):
mb@90
   757
        self.connectedRSDs = dict()
BarthaM@135
   758
        
mb@90
   759
        while self.running:
mb@90
   760
            tmp_rsds = self.vmm.getConnectedRSDS()
mb@95
   761
            
mb@95
   762
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@95
   763
            for vm_name in self.attachedRSDs.keys():
mb@95
   764
                if self.attachedRSDs[vm_name] not in tmp_rsds.values():
mb@95
   765
                    drive = self.vmm.getNetworkDrive(vm_name)
BarthaM@166
   766
                    if drive == None:
BarthaM@166
   767
                        logger.error("Error getting SDVM's network drive letter.")
BarthaM@166
   768
                        continue
BarthaM@166
   769
                    try:
BarthaM@166
   770
                        result = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+drive).readline()
BarthaM@166
   771
                    except urllib2.URLError:
BarthaM@166
   772
                        logger.error("Network drive disconnect failed. OpenSecurity Tray client not running.")
BarthaM@166
   773
                        continue
mb@95
   774
                    self.vmm.detachRSD(vm_name)
mb@95
   775
                    self.vmm.poweroffVM(vm_name)
mb@95
   776
                    self.vmm.removeVM(vm_name)
mb@95
   777
                    break
mb@95
   778
                    
mb@95
   779
                    
mb@90
   780
            if tmp_rsds.keys() == self.connectedRSDs.keys():
mb@90
   781
                logger.debug("Nothing's changed. sleep(3)")
mb@90
   782
                time.sleep(3)
mb@90
   783
                continue
mb@90
   784
            
mb@90
   785
            logger.info("Something's changed")          
mb@90
   786
            self.connectedRSDs = tmp_rsds
BarthaM@135
   787
           
mb@90
   788
            #create new vm for attached device if any
mb@90
   789
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@90
   790
            self.connectedRSDs = self.vmm.getConnectedRSDS()
mb@90
   791
            
mb@90
   792
            new_ip = None
mb@90
   793
            for connected_device in self.connectedRSDs.values():
mb@90
   794
                if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
BarthaM@159
   795
                    new_sdvm = self.vmm.newSDVM()
mb@90
   796
                    self.vmm.storageAttach(new_sdvm)
mb@90
   797
                    self.vmm.attachRSD(new_sdvm, connected_device)
mb@90
   798
                    self.vmm.startVM(new_sdvm)
mb@90
   799
                    new_ip = self.vmm.waitStartup(new_sdvm)
BarthaM@166
   800
                    if new_ip == None:
BarthaM@166
   801
                        logger.error("Error getting IP address of SDVM.")
BarthaM@166
   802
                        continue
mb@90
   803
                    drive = self.vmm.genNetworkDrive()
BarthaM@166
   804
                    if drive == None:
BarthaM@166
   805
                        logger.error("Error getting drive letter for network drive.")
BarthaM@166
   806
                        continue
BarthaM@166
   807
                    try:
BarthaM@151
   808
                        net_resource = '\\\\' + new_ip + '\\USB'
BarthaM@151
   809
                        result = urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'drive_letter='+drive+'&net_resource='+net_resource).readline()
BarthaM@166
   810
                    except urllib2.URLError:
BarthaM@166
   811
                        logger.error("Network drive connect failed. OpenSecurity Tray client not running.")
BarthaM@166
   812
                        continue
BarthaM@151
   813
                        
mb@90
   814
mb@90
   815
if __name__ == '__main__':
mb@90
   816
    #man = VMManager.getInstance()
mb@90
   817
    #man.listVM()
mb@90
   818
    #print man.getConnectedRSDs()
mb@90
   819
    #print man.getNetworkDrives()
mb@90
   820
    #man.genNetworkDrive()
mb@90
   821
    #drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@90
   822
    #print list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@90
   823
    #print list(map(chr, range(68, 91))) 
mb@90
   824
    #print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0]
mb@90
   825
    #devices = VMManager.getConnectedRSDS()
mb@90
   826
    #print devices
mb@90
   827
    
mb@90
   828
    drives = VMManager.getLogicalDrives()
mb@90
   829
    print drives
mb@90
   830
    print VMManager.getDriveType("E")
mb@90
   831
    print VMManager.getVolumeInfo("E")
BarthaM@143
   832
    
BarthaM@143
   833
    #vmm.backupFile()
mb@90
   834
    #for device in devices.values():
mb@90
   835
    #    #print device
mb@90
   836
    #    if VMManager.isMassStorageDevice(device):
mb@90
   837
    #        print device
mb@90
   838
        
mb@90
   839
    
mb@90
   840
    
mb@90
   841
    #time.sleep(-1)
mb@90
   842
    #man.listVM()
mb@90
   843
    #man.listVM()
mb@90
   844
    #man.listVM()
mb@90
   845
    #man.listVM()
mb@90
   846
    #man.genCertificateISO('SecurityDVM0')
mb@90
   847
    #man.guestExecute('SecurityDVM0', '/bin/ls -la')
mb@90
   848
    #logger = setupLogger('VMManager')
mb@90
   849
    #c = Cygwin()
mb@90
   850
    
mb@90
   851
    #man.sshExecute('/bin/ls -la', 'SecurityDVM0')
mb@90
   852
    #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
mb@90
   853
    #man.removeVM('SecurityDVM0')
mb@90
   854
    #man.netUse('192.168.56.134', 'USB\\')
mb@90
   855
    #ip = '192.168.56.139'
mb@90
   856
    
mb@90
   857
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@90
   858
    #man.handleDeviceChange()
mb@90
   859
    #print man.listSDVM()
mb@90
   860
    #man.configureHostNetworking()
mb@90
   861
    #new_vm = man.generateSDVMName()
mb@90
   862
    #man.createVM(new_vm)
mb@90
   863
    
mb@90
   864
    #print Cygwin.cmd()
mb@90
   865
    #man.isAvailable('c:')
mb@90
   866
    #ip = man.getHostOnlyIP('SecurityDVM0')
mb@90
   867
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
mb@90
   868
    
mb@90
   869
    #man.genCertificateISO(new_vm)
mb@90
   870
    #man.attachCertificateISO(new_vm)
mb@90
   871
    
mb@90
   872
    #man.attachCertificateISO(vm_name)
mb@90
   873
    #man.guestExecute(vm_name, "ls")
mb@90
   874
    #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@90
   875
    #time.sleep(60)
mb@90
   876
    #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
mb@90
   877
    #man.genCertificateISO('SecurityDVM')
mb@90
   878
    #man.attachCertificateISO('SecurityDVM')
mb@90
   879
    #man.isStorageAttached('SecurityDVM')
mb@90
   880
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
mb@90
   881
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
mb@90
   882
    
mb@90
   883
    #man.stopVM('SecurityDVM')
mb@90
   884
    #man.storageDetach('SecurityDVM')
mb@90
   885
    #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
mb@90
   886
    #man.storageAttach('SecurityDVM')
mb@90
   887
    
mb@90
   888
    
mb@90
   889
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@90
   890
    #man.execute(cmd)