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