OpenSecurity/bin/vmmanager.pyw
author BarthaM@N3SIM1218.D03.arc.local
Thu, 02 Oct 2014 13:08:09 +0100
changeset 234 216da9017f8f
parent 223 a4fb6694e6fe
child 235 8fd7b197735c
permissions -rwxr-xr-x
- changed opensecurity to always hold at least 2 SDVM sessions to be ready when needed
- added automatic wpad proxy detection
BarthaM@212
     1
#!/bin/env python
BarthaM@212
     2
# -*- coding: utf-8 -*-
mb@90
     3
BarthaM@212
     4
# ------------------------------------------------------------
BarthaM@212
     5
# opensecurityd
BarthaM@212
     6
#   
BarthaM@212
     7
# the opensecurityd as RESTful server
BarthaM@212
     8
#
BarthaM@212
     9
# Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
BarthaM@212
    10
#
BarthaM@212
    11
# Copyright (C) 2013 AIT Austrian Institute of Technology
BarthaM@212
    12
# AIT Austrian Institute of Technology GmbH
BarthaM@212
    13
# Donau-City-Strasse 1 | 1220 Vienna | Austria
BarthaM@212
    14
# http://www.ait.ac.at
BarthaM@212
    15
#
BarthaM@212
    16
# This program is free software; you can redistribute it and/or
BarthaM@212
    17
# modify it under the terms of the GNU General Public License
BarthaM@212
    18
# as published by the Free Software Foundation version 2.
BarthaM@212
    19
# 
BarthaM@212
    20
# This program is distributed in the hope that it will be useful,
BarthaM@212
    21
# but WITHOUT ANY WARRANTY; without even the implied warranty of
BarthaM@212
    22
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
BarthaM@212
    23
# GNU General Public License for more details.
BarthaM@212
    24
# 
BarthaM@212
    25
# You should have received a copy of the GNU General Public License
BarthaM@212
    26
# along with this program; if not, write to the Free Software
BarthaM@212
    27
# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
BarthaM@212
    28
# Boston, MA  02110-1301, USA.
BarthaM@212
    29
# ------------------------------------------------------------
BarthaM@212
    30
BarthaM@212
    31
BarthaM@212
    32
# ------------------------------------------------------------
BarthaM@212
    33
# imports
BarthaM@212
    34
mb@90
    35
import os
mb@90
    36
import os.path
mb@90
    37
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
mb@90
    38
import sys
mb@90
    39
import re
mb@90
    40
mb@90
    41
from cygwin import Cygwin
mb@90
    42
from environment import Environment
mb@90
    43
import threading
mb@90
    44
import time
mb@90
    45
import string
mb@90
    46
mb@90
    47
import shutil
mb@90
    48
import stat
mb@90
    49
import tempfile
BarthaM@221
    50
from opensecurity_util import logger, import_logger, setupLogger, OpenSecurityException, showTrayMessage
mb@90
    51
import ctypes
mb@90
    52
import itertools
BarthaM@143
    53
import win32api
BarthaM@143
    54
import win32con
BarthaM@143
    55
import win32security
BarthaM@176
    56
import win32wnet
BarthaM@151
    57
import urllib
BarthaM@151
    58
import urllib2
BarthaM@212
    59
import unittest
mb@90
    60
DEBUG = True
mb@90
    61
BarthaM@159
    62
BarthaM@159
    63
new_sdvm_lock = threading.Lock()
BarthaM@159
    64
mb@90
    65
class VMManagerException(Exception):
mb@90
    66
    def __init__(self, value):
mb@90
    67
        self.value = value
mb@90
    68
    def __str__(self):
mb@90
    69
        return repr(self.value)
mb@90
    70
mb@90
    71
class USBFilter:
BarthaM@172
    72
    uuid = ""
mb@90
    73
    vendorid = ""
mb@90
    74
    productid = ""
mb@90
    75
    revision = ""
BarthaM@172
    76
    serial = ""
mb@90
    77
    
BarthaM@172
    78
    def __init__(self, uuid, vendorid, productid, revision, serial):
BarthaM@172
    79
        self.uuid = uuid
mb@90
    80
        self.vendorid = vendorid.lower()
mb@90
    81
        self.productid = productid.lower()
mb@90
    82
        self.revision = revision.lower()
BarthaM@172
    83
        self.serial = serial
mb@90
    84
        return
mb@90
    85
    
mb@90
    86
    def __eq__(self, other):
BarthaM@172
    87
        return self.uuid == other.uuid #self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@90
    88
    
mb@90
    89
    def __hash__(self):
BarthaM@172
    90
        return hash(self.uuid) ^ hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision) ^ hash(self.serial)
mb@90
    91
    
mb@90
    92
    def __repr__(self):
BarthaM@172
    93
        return "UUID:" + str(self.uuid) + " VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\'" + "\' Revision = \'" + str(self.revision) + "\' SerialNumber = \'" + str(self.serial)
mb@90
    94
    
mb@90
    95
    #def __getitem__(self, item):
mb@90
    96
    #    return self.coords[item]
BarthaM@212
    97
def once(theClass):
BarthaM@212
    98
    theClass.systemProperties = theClass.getSystemProperties()
BarthaM@212
    99
    theClass.machineFolder =    theClass.systemProperties["Default machine folder"]
BarthaM@217
   100
    #theClass.hostonlyIF =       theClass.getHostOnlyIFs()["VirtualBox Host-Only Ethernet Adapter"]
BarthaM@212
   101
    theClass.blacklistedRSD =   theClass.loadRSDBlacklist()
BarthaM@221
   102
    theClass.templateImage =    theClass.machineFolder + '\\' + theClass.vmRootName + '\\' + theClass.vmRootName + '.vmdk'
BarthaM@212
   103
    return theClass
BarthaM@212
   104
    
BarthaM@212
   105
@once
mb@90
   106
class VMManager(object):
mb@90
   107
    vmRootName = "SecurityDVM"
mb@90
   108
    systemProperties = None
mb@90
   109
    _instance = None
mb@90
   110
    machineFolder = ''
BarthaM@217
   111
    hostonlyIF = None
BarthaM@234
   112
    
BarthaM@183
   113
    blacklistedRSD = None
oliver@131
   114
    status_message = 'Starting up...'
BarthaM@221
   115
    templateImage = None
BarthaM@221
   116
    importHandler = None
BarthaM@221
   117
    updateHandler = None
BarthaM@234
   118
    deviceHandler = None
BarthaM@234
   119
    sdvmFactory = None
BarthaM@234
   120
    vms = dict()
BarthaM@234
   121
    
oliver@131
   122
 
oliver@131
   123
    def __init__(self):
oliver@131
   124
        # only proceed if we have a working background environment
oliver@131
   125
        if self.backend_ok():
BarthaM@217
   126
            VMManager.hostonlyIF = self.getHostOnlyIFs()["VirtualBox Host-Only Ethernet Adapter"]
oliver@131
   127
            self.cleanup()
oliver@131
   128
        else:
oliver@131
   129
            logger.critical(self.status_message)
mb@90
   130
    
oliver@131
   131
mb@90
   132
    @staticmethod
mb@90
   133
    def getInstance():
mb@90
   134
        if VMManager._instance == None:
mb@90
   135
            VMManager._instance = VMManager()
mb@90
   136
        return VMManager._instance
mb@90
   137
    
BarthaM@176
   138
    #list the hostonly IFs exposed by the VBox host
BarthaM@176
   139
    @staticmethod    
BarthaM@176
   140
    def getHostOnlyIFs():
BarthaM@217
   141
        results = Cygwin.vboxExecute('list hostonlyifs')[1]
BarthaM@217
   142
        ifs = dict()
BarthaM@217
   143
        if results=='':
BarthaM@217
   144
            return ifs
BarthaM@217
   145
        items = list( "Name:    " + result for result in results.split('Name:    ') if result != '')
BarthaM@217
   146
        for item in items:
BarthaM@217
   147
            if item != "":
BarthaM@217
   148
                props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in item.strip().splitlines()))
BarthaM@217
   149
                ifs[props["Name"]] = props
BarthaM@217
   150
        return ifs
BarthaM@217
   151
    
BarthaM@217
   152
    #list the hostonly IFs exposed by the VBox host
BarthaM@217
   153
    @staticmethod    
BarthaM@217
   154
    def getDHCPServers():
BarthaM@217
   155
        results = Cygwin.vboxExecute('list dhcpservers')[1]
BarthaM@217
   156
        if results=='':
BarthaM@217
   157
            return dict()
BarthaM@217
   158
        items = list( "NetworkName:    " + result for result in results.split('NetworkName:    ') if result != '')
BarthaM@217
   159
        dhcps = dict()   
BarthaM@217
   160
        for item in items:
BarthaM@217
   161
            if item != "":
BarthaM@217
   162
                props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in item.strip().splitlines()))
BarthaM@217
   163
                dhcps[props["NetworkName"]] = props
BarthaM@217
   164
        return dhcps 
BarthaM@176
   165
        
BarthaM@176
   166
    # return hosty system properties
BarthaM@176
   167
    @staticmethod
BarthaM@176
   168
    def getSystemProperties():
BarthaM@218
   169
        result = Cygwin.vboxExecute('list systemproperties')
BarthaM@176
   170
        if result[1]=='':
BarthaM@176
   171
            return None
BarthaM@176
   172
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
BarthaM@176
   173
        return props
BarthaM@176
   174
    
BarthaM@176
   175
    # return the folder containing the guest VMs     
BarthaM@176
   176
    def getMachineFolder(self):
BarthaM@212
   177
        return VMManager.machineFolder
BarthaM@217
   178
    
BarthaM@217
   179
    # verifies the hostonly interface and DHCP server settings
BarthaM@217
   180
    def verifyHostOnlySettings(self):
BarthaM@217
   181
        interfaceName = "VirtualBox Host-Only Ethernet Adapter"
BarthaM@217
   182
        networkName = "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter"
BarthaM@217
   183
        
BarthaM@217
   184
        hostonlyifs = self.getHostOnlyIFs()
BarthaM@217
   185
        if not interfaceName in hostonlyifs.keys():
BarthaM@217
   186
            Cygwin.vboxExecute('hostonlyif create')
BarthaM@217
   187
            hostonlyifs = self.getHostOnlyIFs()
BarthaM@217
   188
            if not interfaceName in hostonlyifs.keys():
BarthaM@217
   189
                return False
BarthaM@217
   190
        
BarthaM@217
   191
        interface = hostonlyifs[interfaceName]
BarthaM@217
   192
        if interface['VBoxNetworkName'] != networkName or interface['DHCP'] != 'Disabled' or interface['IPAddress'] != '192.168.56.1':
BarthaM@217
   193
            Cygwin.vboxExecute('hostonlyif ipconfig "' + interfaceName + '" --ip 192.168.56.1 --netmask 255.255.255.0')
BarthaM@217
   194
            
BarthaM@217
   195
        dhcpservers = self.getDHCPServers()
BarthaM@217
   196
        if not networkName in dhcpservers.keys():
BarthaM@217
   197
            Cygwin.vboxExecute('dhcpserver add --ifname "' + interfaceName + '" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.254 --enable')
BarthaM@217
   198
            dhcpservers = self.getDHCPServers()
BarthaM@217
   199
            if not networkName in dhcpservers.keys():
BarthaM@217
   200
                return False
BarthaM@217
   201
            
BarthaM@217
   202
        server = dhcpservers[networkName]
BarthaM@217
   203
        if server['IP'] != '192.168.56.100' or server['NetworkMask'] != '255.255.255.0' or server['lowerIPAddress'] != '192.168.56.101' or server['upperIPAddress'] != '192.168.56.254' or server['Enabled'] != 'Yes':
BarthaM@217
   204
            Cygwin.vboxExecute('VBoxManage dhcpserver modify --netname "' + networkName + '" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.254 --enable')
BarthaM@217
   205
        
BarthaM@217
   206
        return True
oliver@131
   207
BarthaM@219
   208
    def template_installed(self):
BarthaM@219
   209
        """ check if we do have our root VMs installed """
BarthaM@221
   210
        vms = self.listVMS()
BarthaM@219
   211
        if not self.vmRootName in vms:
BarthaM@219
   212
            self.status_message = 'Unable to locate root SecurityDVM. Please download and setup the initial image.'
BarthaM@219
   213
            return False
BarthaM@219
   214
        return True
BarthaM@219
   215
        
oliver@131
   216
    def backend_ok(self):
oliver@131
   217
        """check if the backend (VirtualBox) is sufficient for our task"""
oliver@131
   218
oliver@131
   219
        # ensure we have our system props
BarthaM@212
   220
        if VMManager.systemProperties == None:
BarthaM@212
   221
            VMManager.systemProperties = self.getSystemProperties()
BarthaM@212
   222
        if VMManager.systemProperties == None:
oliver@131
   223
            self.status_message = 'Failed to get backend system properties. Is Backend (VirtualBox?) installed?'
oliver@131
   224
            return False
oliver@131
   225
oliver@131
   226
        # check for existing Extension pack
BarthaM@212
   227
        if not 'Remote desktop ExtPack' in VMManager.systemProperties:
oliver@131
   228
            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
   229
            return False
BarthaM@212
   230
        if VMManager.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ':
oliver@131
   231
            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
   232
            return False
oliver@131
   233
BarthaM@219
   234
        # check the existing hostOnly network settings and try to reconfigure if faulty
BarthaM@219
   235
        if not self.verifyHostOnlySettings():
oliver@131
   236
            return False
BarthaM@219
   237
        
oliver@131
   238
        # basically all seems nice and ready to rumble
oliver@131
   239
        self.status_message = 'All is ok.'
oliver@131
   240
        return True
BarthaM@170
   241
    
BarthaM@221
   242
    def start(self, force = False):
BarthaM@221
   243
        if not force:
BarthaM@221
   244
            if self.importHandler and self.importHandler.isAlive():
BarthaM@221
   245
                logger.info("Initial update running canceling start.")
BarthaM@221
   246
                return
BarthaM@221
   247
        
BarthaM@221
   248
            if self.updateHandler and self.updateHandler.isAlive():
BarthaM@221
   249
                logger.info("Update running canceling start.")
BarthaM@221
   250
                return
BarthaM@221
   251
        
BarthaM@170
   252
        self.stop()
BarthaM@219
   253
        Cygwin.allowExec()
BarthaM@219
   254
        if self.backend_ok() and self.template_installed():
BarthaM@234
   255
            self.sdvmFactory = SDVMFactory(self)
BarthaM@234
   256
            self.sdvmFactory.start()
BarthaM@234
   257
            self.deviceHandler = DeviceHandler(self)
BarthaM@234
   258
            self.deviceHandler.start()
BarthaM@234
   259
    
BarthaM@234
   260
    def stop(self):
BarthaM@234
   261
        Cygwin.denyExec()
BarthaM@234
   262
        if self.sdvmFactory != None:
BarthaM@234
   263
            self.sdvmFactory.stop()
BarthaM@234
   264
            self.sdvmFactory.join()
BarthaM@234
   265
            self.sdvmFactory = None
BarthaM@234
   266
        if self.deviceHandler != None:
BarthaM@234
   267
            self.deviceHandler.stop()
BarthaM@234
   268
            self.deviceHandler.join()
BarthaM@234
   269
            self.deviceHandler = None
BarthaM@170
   270
        
BarthaM@234
   271
        Cygwin.allowExec()
BarthaM@170
   272
BarthaM@170
   273
    def cleanup(self):
BarthaM@170
   274
        self.stop()
BarthaM@219
   275
        Cygwin.allowExec()
BarthaM@176
   276
        ip = self.getHostOnlyIP(None)
BarthaM@176
   277
        try:
BarthaM@176
   278
            result = urllib2.urlopen('http://127.0.0.1:8090/netcleanup?'+'hostonly_ip='+ip).readline()
BarthaM@176
   279
        except urllib2.URLError:
BarthaM@176
   280
            logger.info("Network drive cleanup all skipped. OpenSecurity Tray client not started yet.")
BarthaM@151
   281
            
mb@90
   282
        for vm in self.listSDVM():
mb@90
   283
            self.poweroffVM(vm)
mb@90
   284
            self.removeVM(vm)
mb@90
   285
mb@90
   286
    # list all existing VMs registered with VBox
BarthaM@221
   287
    def listVMS(self):
BarthaM@218
   288
        result = Cygwin.vboxExecute('list vms')[1]
mb@90
   289
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   290
        return vms
mb@90
   291
    
mb@90
   292
    # list running VMs
mb@90
   293
    def listRunningVMS(self):
BarthaM@218
   294
        result = Cygwin.vboxExecute('list runningvms')[1]
mb@90
   295
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   296
        return vms
mb@90
   297
    
mb@90
   298
    # list existing SDVMs
mb@90
   299
    def listSDVM(self):
BarthaM@221
   300
        vms = self.listVMS()
mb@90
   301
        svdms = []
mb@90
   302
        for vm in vms:
mb@90
   303
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@90
   304
                svdms.append(vm)
mb@90
   305
        return svdms
mb@90
   306
    
mb@90
   307
    # generate valid (not already existing SDVM name). necessary for creating a new VM
BarthaM@159
   308
    def genSDVMName(self):
BarthaM@221
   309
        vms = self.listVMS()
mb@90
   310
        for i in range(0,999):
mb@90
   311
            if(not self.vmRootName+str(i) in vms):
mb@90
   312
                return self.vmRootName+str(i)
mb@90
   313
        return ''
mb@90
   314
    
BarthaM@183
   315
    @staticmethod
BarthaM@183
   316
    def loadRSDBlacklist():
BarthaM@183
   317
        blacklist = dict()
BarthaM@183
   318
        try:
BarthaM@183
   319
            fo = open(Environment('OpenSecurity').prefix_path +"\\bin\\blacklist.usb", "r")
BarthaM@183
   320
        except IOError:
BarthaM@183
   321
            logger.error("Could not open RSD blacklist file.")
BarthaM@183
   322
            return blacklist
BarthaM@183
   323
        
BarthaM@183
   324
        lines = fo.readlines()
BarthaM@183
   325
        for line in lines:
BarthaM@183
   326
            if line != "":  
BarthaM@183
   327
                parts = line.strip().split(' ')
BarthaM@183
   328
                blacklist[parts[0].lower()] = parts[1].lower()
BarthaM@183
   329
        return blacklist
BarthaM@183
   330
         
BarthaM@183
   331
    @staticmethod
BarthaM@183
   332
    def isBlacklisted(device):
BarthaM@183
   333
        if VMManager.blacklistedRSD:
BarthaM@183
   334
            blacklisted = device.vendorid.lower() in VMManager.blacklistedRSD.keys() and device.productid.lower() == VMManager.blacklistedRSD[device.vendorid]
BarthaM@183
   335
            return blacklisted
BarthaM@183
   336
        return False 
BarthaM@183
   337
    
mb@90
   338
    # check if the device is mass storage type
mb@90
   339
    @staticmethod
mb@90
   340
    def isMassStorageDevice(device):
BarthaM@219
   341
        vidkey = None
BarthaM@219
   342
        devinfokey = None
BarthaM@219
   343
        value = ""
BarthaM@219
   344
        try:
BarthaM@219
   345
            keyname = 'SYSTEM\CurrentControlSet\Enum\USB' + '\VID_' + device.vendorid+'&'+'PID_'+ device.productid
BarthaM@219
   346
            vidkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname)
BarthaM@219
   347
            devinfokeyname = win32api.RegEnumKey(vidkey, 0)
BarthaM@219
   348
            win32api.RegCloseKey(vidkey)
BarthaM@219
   349
    
BarthaM@219
   350
            devinfokey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname+'\\'+devinfokeyname)
BarthaM@219
   351
            value = win32api.RegQueryValueEx(devinfokey, 'SERVICE')[0]
BarthaM@219
   352
            win32api.RegCloseKey(devinfokey)
BarthaM@219
   353
        except Exception as ex:
BarthaM@219
   354
            logger.error('Error reading registry.Exception details: %s' %ex)
BarthaM@219
   355
        finally:
BarthaM@219
   356
            if vidkey is not None:
BarthaM@219
   357
                win32api.RegCloseKey(vidkey)
BarthaM@219
   358
            if devinfokey is not None:
BarthaM@219
   359
                win32api.RegCloseKey(devinfokey)
mb@90
   360
        
mb@90
   361
        return 'USBSTOR' in value
mb@90
   362
    
mb@90
   363
    # return the RSDs connected to the host
mb@90
   364
    @staticmethod
BarthaM@172
   365
    def getExistingRSDs():
BarthaM@218
   366
        results = Cygwin.vboxExecute('list usbhost')[1]
mb@90
   367
        results = results.split('Host USB Devices:')[1].strip()
mb@90
   368
        
mb@90
   369
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   370
        rsds = dict()   
mb@90
   371
        for item in items:
mb@90
   372
            props = dict()
BarthaM@172
   373
            for line in item.splitlines():     
mb@90
   374
                if line != "":         
mb@90
   375
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   376
                    props[k] = v
mb@90
   377
            
BarthaM@172
   378
            uuid = re.search(r"(?P<uuid>[0-9A-Fa-f\-]+)", props['UUID']).groupdict()['uuid']
BarthaM@172
   379
            vid = re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid']
BarthaM@172
   380
            pid = re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid']
BarthaM@172
   381
            rev = re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev']
BarthaM@172
   382
            serial = None
BarthaM@172
   383
            if 'SerialNumber' in props.keys():
BarthaM@172
   384
                serial = re.search(r"(?P<ser>[0-9A-Fa-f]+)", props['SerialNumber']).groupdict()['ser']
BarthaM@183
   385
            usb_filter = USBFilter( uuid, vid, pid, rev, serial)
BarthaM@183
   386
             
BarthaM@183
   387
            if VMManager.isMassStorageDevice(usb_filter) and not VMManager.isBlacklisted(usb_filter):
BarthaM@172
   388
                rsds[uuid] = usb_filter
mb@90
   389
                logger.debug(usb_filter)
mb@90
   390
        return rsds
mb@90
   391
    
BarthaM@172
   392
   
BarthaM@172
   393
    # return the attached USB device as usb descriptor for an existing VM 
BarthaM@172
   394
    def getAttachedRSD(self, vm_name):
BarthaM@172
   395
        props = self.getVMInfo(vm_name)
BarthaM@172
   396
        keys = set(['USBAttachedUUID1', 'USBAttachedVendorId1', 'USBAttachedProductId1', 'USBAttachedRevision1', 'USBAttachedSerialNumber1'])
BarthaM@172
   397
        keyset = set(props.keys())
BarthaM@172
   398
        usb_filter = None
BarthaM@172
   399
        if keyset.issuperset(keys):
BarthaM@172
   400
            usb_filter = USBFilter(props['USBAttachedUUID1'], props['USBAttachedVendorId1'], props['USBAttachedProductId1'], props['USBAttachedRevision1'], props['USBAttachedSerialNumber1'])
BarthaM@172
   401
        return usb_filter
BarthaM@172
   402
        
mb@90
   403
    # return the RSDs attached to all existing SDVMs
mb@90
   404
    def getAttachedRSDs(self):
mb@90
   405
        vms = self.listSDVM()
mb@90
   406
        attached_devices = dict()
mb@90
   407
        for vm in vms:
BarthaM@172
   408
            rsd_filter = self.getAttachedRSD(vm)
mb@90
   409
            if rsd_filter != None:
mb@90
   410
                attached_devices[vm] = rsd_filter
mb@90
   411
        return attached_devices
mb@90
   412
    
BarthaM@172
   413
    # attach removable storage device to VM by provision of filter
BarthaM@172
   414
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@218
   415
        #return 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@218
   416
        return Cygwin.vboxExecute('controlvm ' + vm_name + ' usbattach ' + rsd_filter.uuid )
BarthaM@172
   417
    
BarthaM@172
   418
    # detach removable storage from VM by 
BarthaM@172
   419
    def detachRSD(self, vm_name, rsd_filter):
BarthaM@218
   420
        #return Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name)
BarthaM@218
   421
        return Cygwin.vboxExecute('controlvm ' + vm_name + ' usbdetach ' + rsd_filter.uuid )
BarthaM@172
   422
        
mb@90
   423
    # configures hostonly networking and DHCP server. requires admin rights
mb@90
   424
    def configureHostNetworking(self):
mb@90
   425
        #cmd = 'vboxmanage list hostonlyifs'
mb@90
   426
        #Cygwin.vboxExecute(cmd)
mb@90
   427
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
mb@90
   428
        #Cygwin.vboxExecute(cmd)
mb@90
   429
        #cmd = 'vboxmanage hostonlyif create'
mb@90
   430
        #Cygwin.vboxExecute(cmd)
BarthaM@218
   431
        Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0')
mb@90
   432
        #cmd = 'vboxmanage dhcpserver add'
mb@90
   433
        #Cygwin.vboxExecute(cmd)
BarthaM@218
   434
        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
   435
    
BarthaM@125
   436
    def isSDVMExisting(self, vm_name):
BarthaM@125
   437
        sdvms = self.listSDVM()
BarthaM@125
   438
        return vm_name in sdvms
BarthaM@125
   439
        
mb@90
   440
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
mb@90
   441
    def createVM(self, vm_name):
BarthaM@125
   442
        if self.isSDVMExisting(vm_name):
BarthaM@125
   443
            return
BarthaM@125
   444
        #remove eventually existing SDVM folder
BarthaM@212
   445
        machineFolder = Cygwin.cygPath(VMManager.machineFolder)
BarthaM@218
   446
        Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"')
BarthaM@218
   447
        Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register')
BarthaM@218
   448
        Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 768 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + self.hostonlyIF['Name'] + '\" --nic2 nat')
BarthaM@218
   449
        Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2')
BarthaM@159
   450
BarthaM@159
   451
    #create new SecurityDVM with automatically generated name from template (thread safe)        
BarthaM@159
   452
    def newSDVM(self):
BarthaM@159
   453
        with new_sdvm_lock:
BarthaM@159
   454
            vm_name = self.genSDVMName()
BarthaM@159
   455
            self.createVM(vm_name)
BarthaM@159
   456
        return vm_name
mb@90
   457
    
BarthaM@221
   458
    #VMManager.machineFolder + '\SecurityDVM\SecurityDVM.vmdk
mb@90
   459
    # attach storage image to controller
BarthaM@221
   460
    def attachVDisk(self, vm_name, vdisk_controller, vdisk_port, vdisk_device, vdisk_image):
BarthaM@221
   461
        if self.isVDiskAttached(vm_name, vdisk_controller, vdisk_port, vdisk_device):
BarthaM@221
   462
            self.detachVDisk(vm_name, vdisk_controller, vdisk_port, vdisk_device)
BarthaM@221
   463
        Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl '+ vdisk_controller + ' --port ' + vdisk_port + ' --device ' + vdisk_device + ' --type hdd --medium "'+ vdisk_image + '"')
mb@90
   464
    
mb@90
   465
    # return true if storage is attached 
BarthaM@221
   466
    def isVDiskAttached(self, vm_name, vdisk_controller, vdisk_port, vdisk_device):
mb@90
   467
        info = self.getVMInfo(vm_name)
BarthaM@221
   468
        return (info[vdisk_controller+'-'+vdisk_port+'-'+vdisk_device] != 'none')
mb@90
   469
    
mb@90
   470
    # detach storage from controller
BarthaM@221
   471
    def detachVDisk(self, vm_name, vdisk_controller, vdisk_port, vdisk_device):
BarthaM@221
   472
        if self.isVDiskAttached(vm_name, vdisk_controller, vdisk_port, vdisk_device):
BarthaM@221
   473
            Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl ' + vdisk_controller + ' --port ' + vdisk_port + ' --device ' + vdisk_device + ' --medium none')
mb@90
   474
    
BarthaM@221
   475
    # modify type of the vdisk_image
BarthaM@221
   476
    def changeVDiskType(self, vdisk_image, storage_type):
BarthaM@221
   477
        Cygwin.vboxExecute('modifyhd "' + vdisk_image + '" --type ' + storage_type)
BarthaM@171
   478
        
BarthaM@221
   479
    # grab VM storage controller, port and device for vdisk image name
BarthaM@221
   480
    def getVDiskController(self, vm_name, image_name = '.vmdk'):
BarthaM@221
   481
        vm_description = self.getVMInfo(vm_name)
BarthaM@221
   482
        vdisk_controller = None
BarthaM@221
   483
        for key, value in vm_description.iteritems():
BarthaM@221
   484
            if image_name in value:
BarthaM@221
   485
                vdisk_controller = key
BarthaM@221
   486
                break
BarthaM@221
   487
        return vdisk_controller
BarthaM@221
   488
    
BarthaM@221
   489
    # return attached vmdk image name containing image_name 
BarthaM@221
   490
    def getVDiskImage(self, vm_name, image_name = '.vmdk'):
BarthaM@221
   491
        vmInfo = self.getVMInfo(vm_name)
BarthaM@221
   492
        vdisk_image = None
BarthaM@221
   493
        for value in vmInfo.values():
BarthaM@221
   494
            if image_name in value:
BarthaM@221
   495
                break
BarthaM@221
   496
        return vdisk_image 
BarthaM@212
   497
        
BarthaM@212
   498
    @staticmethod    
BarthaM@221
   499
    def getVDiskImages():
BarthaM@218
   500
        results = Cygwin.vboxExecute('list hdds')[1]
mb@90
   501
        results = results.replace('Parent UUID', 'Parent')
mb@90
   502
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   503
        
mb@90
   504
        snaps = dict()   
mb@90
   505
        for item in items:
mb@90
   506
            props = dict()
mb@90
   507
            for line in item.splitlines():
mb@90
   508
                if line != "":         
mb@90
   509
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   510
                    props[k] = v;
mb@90
   511
            snaps[props['UUID']] = props
BarthaM@171
   512
        return snaps
BarthaM@171
   513
    
BarthaM@212
   514
    @staticmethod 
BarthaM@221
   515
    def getVDiskUUID(vdisk_image):
BarthaM@221
   516
        images = VMManager.getVDiskImages()
mb@90
   517
        # find template uuid
BarthaM@171
   518
        template_uuid = None
BarthaM@171
   519
        for hdd in images.values():
BarthaM@221
   520
            if hdd['Location'] == vdisk_image:
mb@90
   521
                template_uuid = hdd['UUID']
BarthaM@171
   522
                break
BarthaM@171
   523
        return template_uuid
BarthaM@221
   524
    
BarthaM@171
   525
    def removeSnapshots(self, imageUUID):
BarthaM@221
   526
        snaps = self.getVDiskImages()
mb@90
   527
        # remove snapshots 
mb@90
   528
        for hdd in snaps.values():
BarthaM@171
   529
            if hdd['Parent'] == imageUUID:
BarthaM@171
   530
                snapshotUUID = hdd['UUID']
BarthaM@171
   531
                self.removeImage(snapshotUUID)
BarthaM@170
   532
                
BarthaM@171
   533
    def removeImage(self, imageUUID):
BarthaM@171
   534
        logger.debug('removing snapshot ' + imageUUID)
BarthaM@218
   535
        Cygwin.vboxExecute('closemedium disk {' + imageUUID + '} --delete')
BarthaM@171
   536
        # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
mb@90
   537
    
mb@90
   538
    #remove VM from the system. should be used on VMs returned by listSDVMs    
mb@90
   539
    def removeVM(self, vm_name):
mb@90
   540
        logger.info('Removing ' + vm_name)
BarthaM@218
   541
        Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete')
BarthaM@221
   542
        #try to close medium if still existing
BarthaM@218
   543
        #Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete')
BarthaM@170
   544
        self.removeVMFolder(vm_name)
BarthaM@170
   545
    
BarthaM@170
   546
    def removeVMFolder(self, vm_name):
BarthaM@212
   547
        machineFolder = Cygwin.cygPath(VMManager.machineFolder)
BarthaM@221
   548
        Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '\\' + vm_name + '\\\"')
mb@90
   549
    
mb@90
   550
    # start VM
mb@90
   551
    def startVM(self, vm_name):
mb@90
   552
        logger.info('Starting ' +  vm_name)
BarthaM@218
   553
        Cygwin.vboxExecute('guestproperty set ' + vm_name + ' SDVMStarted False')
BarthaM@212
   554
        result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' )
mb@90
   555
        while 'successfully started' not in result[1]:
mb@90
   556
            logger.error("Failed to start SDVM: " + vm_name + " retrying")
oliver@129
   557
            logger.error("Command returned:\n" + result[2])
mb@90
   558
            time.sleep(1)
BarthaM@212
   559
            result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless')
mb@90
   560
        return result[0]
mb@90
   561
    
mb@90
   562
    # return wether VM is running or not
mb@90
   563
    def isVMRunning(self, vm_name):
mb@90
   564
        return vm_name in self.listRunningVMS()    
mb@90
   565
    
mb@90
   566
    # stop VM
mb@90
   567
    def stopVM(self, vm_name):
mb@90
   568
        logger.info('Sending shutdown signal to ' + vm_name)
BarthaM@218
   569
        Cygwin.sshExecute( '"sudo shutdown -h now"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(VMManager.machineFolder) + '/' + vm_name + '/dvm_key' )
BarthaM@218
   570
        Cygwin.vboxExecute('guestproperty set ' + vm_name + ' SDVMStarted False')
mb@90
   571
    
mb@90
   572
    # stop VM
mb@90
   573
    def hibernateVM(self, vm_name):
mb@95
   574
        logger.info('Sending hibernate-disk signal to ' + vm_name)
BarthaM@218
   575
        Cygwin.sshBackgroundExecute( '"sudo hibernate-disk"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(VMManager.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False)
BarthaM@218
   576
        Cygwin.vboxExecute('guestproperty set ' + vm_name + ' SDVMStarted False')
mb@90
   577
            
mb@90
   578
    # poweroff VM
mb@90
   579
    def poweroffVM(self, vm_name):
mb@90
   580
        if not self.isVMRunning(vm_name):
mb@90
   581
            return
mb@90
   582
        logger.info('Powering off ' + vm_name)
BarthaM@218
   583
        Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff')
BarthaM@218
   584
        Cygwin.vboxExecute('guestproperty set ' + vm_name + ' SDVMStarted False')
BarthaM@218
   585
    
mb@90
   586
    
BarthaM@176
   587
    # return the hostOnly IP for a running guest or the host    
BarthaM@176
   588
    def getHostOnlyIP(self, vm_name):
mb@90
   589
        if vm_name == None:
oliver@129
   590
            logger.info('Getting hostOnly IP address for Host')
BarthaM@217
   591
            return VMManager.hostonlyIF['IPAddress']
mb@90
   592
        else:
oliver@129
   593
            logger.info('Getting hostOnly IP address ' + vm_name)
BarthaM@218
   594
            result = Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP')
mb@90
   595
            if result=='':
mb@90
   596
                return None
mb@90
   597
            result = result[1]
mb@90
   598
            if result.startswith('No value set!'):
mb@90
   599
                return None
mb@90
   600
            return result[result.index(':')+1:].strip()
mb@90
   601
        
mb@90
   602
    # return the description set for an existing VM
mb@90
   603
    def getVMInfo(self, vm_name):
BarthaM@218
   604
        results = Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable')[1]
mb@90
   605
        props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@90
   606
        return props
mb@90
   607
    
mb@90
   608
    #generates ISO containing authorized_keys for use with guest VM
BarthaM@218
   609
    def genCertificate(self, vm_name):
BarthaM@212
   610
        machineFolder = Cygwin.cygPath(VMManager.machineFolder)
mb@90
   611
        # remove .ssh folder if exists
BarthaM@218
   612
        Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"')
mb@90
   613
        # remove .ssh folder if exists
BarthaM@218
   614
        Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"')
mb@90
   615
        # create .ssh folder in vm_name
BarthaM@218
   616
        Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"')
mb@90
   617
        # generate dvm_key pair in vm_name / .ssh     
BarthaM@218
   618
        Cygwin.bashExecute('/usr/bin/ssh-keygen -q -t rsa -N \\\"\\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"')
mb@90
   619
        # move out private key
BarthaM@218
   620
        Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"')
mb@90
   621
        # set permissions for private key
BarthaM@218
   622
        Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"')
mb@90
   623
        # rename public key to authorized_keys
BarthaM@218
   624
        Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"')
mb@90
   625
        # set permissions for authorized_keys
BarthaM@218
   626
        Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"')
mb@90
   627
        # generate iso image with .ssh/authorized keys
BarthaM@218
   628
        Cygwin.bashExecute('/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"')
mb@90
   629
    
mb@90
   630
    # attaches generated ssh public cert to guest vm
BarthaM@218
   631
    def attachCertificate(self, vm_name):
BarthaM@218
   632
        if self.isCertificateAttached(vm_name):
BarthaM@218
   633
            self.detachCertificate(vm_name)
BarthaM@218
   634
        Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + VMManager.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"')
mb@90
   635
    
BarthaM@218
   636
    # return true if storage is attached 
BarthaM@218
   637
    def isCertificateAttached(self, vm_name):
BarthaM@218
   638
        info = self.getVMInfo(vm_name)
BarthaM@218
   639
        return (info['SATA-1-0']!='none')
BarthaM@218
   640
    
BarthaM@218
   641
    # detach storage from controller
BarthaM@218
   642
    def detachCertificate(self, vm_name):
BarthaM@218
   643
        if self.isCertificateAttached(vm_name):
BarthaM@218
   644
            Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type hdd --medium none')
BarthaM@218
   645
            
mb@90
   646
    # wait for machine to come up
BarthaM@218
   647
    def waitStartup(self, vm_name):
BarthaM@218
   648
        #Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout', try_count = 60)
BarthaM@217
   649
        started = False
BarthaM@217
   650
        while not started:
BarthaM@218
   651
            result = Cygwin.vboxExecute('guestproperty get ' + vm_name + ' SDVMStarted')[1]
BarthaM@217
   652
            if "Value: True" in result:
BarthaM@217
   653
                started = True
BarthaM@217
   654
            else:
BarthaM@217
   655
                time.sleep(3) 
BarthaM@176
   656
        return self.getHostOnlyIP(vm_name)
mb@90
   657
    
mb@90
   658
    # wait for machine to shutdown
mb@90
   659
    def waitShutdown(self, vm_name):
mb@90
   660
        while vm_name in self.listRunningVMS():
mb@90
   661
            time.sleep(1)
mb@90
   662
        return
mb@90
   663
    
BarthaM@135
   664
    #Small function to check if the mentioned location is a directory
mb@90
   665
    def isDirectory(self, path):
BarthaM@218
   666
        result = Cygwin.cmdExecute('dir ' + path + ' | FIND ".."')
mb@90
   667
        return string.find(result[1], 'DIR',)
mb@90
   668
    
oliver@167
   669
    def genNetworkDrive(self):
oliver@167
   670
        logical_drives = VMManager.getLogicalDrives()
oliver@167
   671
        logger.info("Used logical drive letters: "+ str(logical_drives).strip('[]') )
oliver@167
   672
        drives = list(map(chr, range(68, 91)))  
oliver@167
   673
        for drive in drives:
BarthaM@176
   674
            if drive not in logical_drives:
BarthaM@176
   675
                return drive
BarthaM@151
   676
            
mb@90
   677
    @staticmethod
mb@90
   678
    def getLogicalDrives():
mb@90
   679
        drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
BarthaM@176
   680
        drives = list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
BarthaM@176
   681
        return drives
mb@90
   682
    
mb@90
   683
    @staticmethod
mb@90
   684
    def getDriveType(drive):
mb@90
   685
        return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
mb@90
   686
    
mb@90
   687
    @staticmethod
BarthaM@176
   688
    def getNetworkPath(drive):
BarthaM@176
   689
        return win32wnet.WNetGetConnection(drive+':')
BarthaM@176
   690
    
BarthaM@176
   691
    @staticmethod
mb@90
   692
    def getVolumeInfo(drive):
mb@90
   693
        volumeNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   694
        fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   695
        serial_number = None
mb@90
   696
        max_component_length = None
mb@90
   697
        file_system_flags = None
mb@90
   698
        
mb@90
   699
        rc = ctypes.cdll.kernel32.GetVolumeInformationW(
mb@90
   700
            u"%s:\\"%drive,
mb@90
   701
            volumeNameBuffer,
mb@90
   702
            ctypes.sizeof(volumeNameBuffer),
mb@90
   703
            serial_number,
mb@90
   704
            max_component_length,
mb@90
   705
            file_system_flags,
mb@90
   706
            fileSystemNameBuffer,
mb@90
   707
            ctypes.sizeof(fileSystemNameBuffer)
mb@90
   708
        )
mb@90
   709
        return volumeNameBuffer.value, fileSystemNameBuffer.value
BarthaM@141
   710
    
BarthaM@176
   711
    def getNetworkDrive(self, vm_name):
BarthaM@176
   712
        ip = self.getHostOnlyIP(vm_name)
BarthaM@176
   713
        if ip == None:
BarthaM@176
   714
            logger.error("Failed getting hostonly IP for " + vm_name)
BarthaM@176
   715
            return None
BarthaM@176
   716
        logger.info("Got IP address for " + vm_name + ': ' + ip)
BarthaM@176
   717
        for drive in VMManager.getLogicalDrives():
BarthaM@176
   718
            #if is a network drive
BarthaM@176
   719
            if VMManager.getDriveType(drive) == 4:
BarthaM@176
   720
                network_path = VMManager.getNetworkPath(drive)
BarthaM@176
   721
                if ip in network_path:
BarthaM@176
   722
                    return drive
BarthaM@176
   723
        return None
BarthaM@176
   724
    
BarthaM@176
   725
    def getNetworkDrives(self):
BarthaM@176
   726
        ip = self.getHostOnlyIP(None)
BarthaM@176
   727
        if ip == None:
BarthaM@176
   728
            logger.error("Failed getting hostonly IP for system")
BarthaM@176
   729
            return None
BarthaM@176
   730
        logger.info("Got IP address for system: " + ip)
BarthaM@176
   731
        ip = ip[:ip.rindex('.')]
BarthaM@176
   732
        network_drives = dict()
BarthaM@176
   733
        for drive in VMManager.getLogicalDrives():
BarthaM@176
   734
            #if is a network drive
BarthaM@176
   735
            if VMManager.getDriveType(drive) == 4:
BarthaM@176
   736
                network_path = VMManager.getNetworkPath(drive)
BarthaM@176
   737
                if ip in network_path:
BarthaM@176
   738
                    network_drives[drive] = network_path  
BarthaM@176
   739
        return network_drives
BarthaM@176
   740
    
BarthaM@141
   741
    # handles browsing request    
BarthaM@234
   742
    def handleBrowsingRequest(self, proxy = None, wpad = None):
oliver@193
   743
        showTrayMessage('Starting Secure Browsing...', 7000)
BarthaM@223
   744
        handler = BrowsingHandler(self, proxy, wpad)
BarthaM@141
   745
        handler.start()
BarthaM@141
   746
        return 'ok'
BarthaM@143
   747
    
BarthaM@143
   748
    def getActiveUserName(self):
BarthaM@143
   749
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI')
BarthaM@143
   750
        v = str(win32api.RegQueryValueEx(key, 'LastLoggedOnUser')[0])
BarthaM@143
   751
        win32api.RegCloseKey(key)
BarthaM@143
   752
        user_name = win32api.ExpandEnvironmentStrings(v)
BarthaM@143
   753
        return user_name
BarthaM@143
   754
        
BarthaM@143
   755
    def getUserSID(self, user_name):
oliver@167
   756
        domain, user = user_name.split("\\")
oliver@167
   757
        account_name = win32security.LookupAccountName(domain, user)
oliver@167
   758
        if account_name == None:
oliver@167
   759
            logger.error("Failed lookup account name for user " + user_name)
oliver@167
   760
            return None
BarthaM@143
   761
        sid = win32security.ConvertSidToStringSid(account_name[0])
oliver@167
   762
        if sid == None:
oliver@167
   763
            logger.error("Failed converting SID for account " + account_name[0])
oliver@167
   764
            return None
BarthaM@143
   765
        return sid
BarthaM@143
   766
        
BarthaM@143
   767
    def getAppDataDir(self, sid):    
BarthaM@143
   768
        key = win32api.RegOpenKey(win32con.HKEY_USERS, sid + '\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
BarthaM@221
   769
        value, _ = win32api.RegQueryValueEx(key, "AppData")
BarthaM@143
   770
        win32api.RegCloseKey(key)
BarthaM@143
   771
        return value
BarthaM@143
   772
        #key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' + '\\' + sid)
BarthaM@143
   773
        #value, type = win32api.RegQueryValueEx(key, "ProfileImagePath")
BarthaM@143
   774
        #print value
BarthaM@143
   775
    
BarthaM@221
   776
    #import initial template
BarthaM@221
   777
    def importTemplate(self, image_path):
BarthaM@221
   778
        import_logger.info('Stopping Opensecurity...')
BarthaM@221
   779
        self.stop()
BarthaM@221
   780
        
BarthaM@221
   781
        import_logger.info('Cleaning up system in preparation for import...')
BarthaM@221
   782
        self.cleanup()
BarthaM@221
   783
        
BarthaM@221
   784
        import_logger.info('Removing template SDVM...')
BarthaM@221
   785
        # if template exists
BarthaM@221
   786
        if self.vmRootName in self.listVMS():
BarthaM@221
   787
            # shutdown template if running
BarthaM@221
   788
            self.poweroffVM(self.vmRootName)
BarthaM@221
   789
            # detach and remove VDisk
BarthaM@221
   790
            tmplateUUID = self.getVDiskUUID(self.templateImage)
BarthaM@221
   791
            if tmplateUUID != None:
BarthaM@221
   792
                logger.debug('Found template VDisk uuid ' + tmplateUUID)
BarthaM@221
   793
                controller = self.getVDiskController(self.vmRootName)
BarthaM@221
   794
                if controller:
BarthaM@221
   795
                    controller = controller.split('-')
BarthaM@221
   796
                    self.detachVDisk(self.vmRootName, controller[0], controller[1], controller[2])
BarthaM@221
   797
                self.removeSnapshots(tmplateUUID)
BarthaM@221
   798
                self.removeImage(tmplateUUID)
BarthaM@221
   799
            else:
BarthaM@221
   800
                logger.info('Template uuid not found')
BarthaM@221
   801
            # remove VM    
BarthaM@221
   802
            self.removeVM(self.vmRootName)
BarthaM@221
   803
        # remove template VM folder 
BarthaM@221
   804
        self.removeVMFolder(self.vmRootName)
BarthaM@221
   805
        import_logger.info('Cleanup finished...')
BarthaM@221
   806
        
BarthaM@221
   807
        import_logger.info('Checking privileges...')
BarthaM@221
   808
        result = Cygwin.bashExecute('id -G')
BarthaM@221
   809
        if '544' not in result[1]:
BarthaM@221
   810
            import_logger.debug('Insufficient privileges.')
BarthaM@221
   811
            import_logger.debug("Trying to continue...")
BarthaM@221
   812
        
BarthaM@221
   813
        # check OpenSecurity Initial VM Image
BarthaM@221
   814
        import_logger.debug('Looking for VM image: ' + image_path)
BarthaM@221
   815
        result = os.path.isfile(image_path)
BarthaM@221
   816
      
BarthaM@221
   817
        if not result:
BarthaM@221
   818
            import_logger.debug('Warning: no OpenSecurity Initial Image found.')
BarthaM@221
   819
            import_logger.debug('Please download using the OpenSecurity download tool.')
BarthaM@221
   820
            raise OpenSecurityException('OpenSecurity Initial Image not found.')
BarthaM@221
   821
        logger.debug('Initial VM image: ' + image_path + ' found')
BarthaM@221
   822
        
BarthaM@221
   823
        if not self.template_installed():
BarthaM@221
   824
            import_logger.info('Importing SDVm template: ' + image_path)
BarthaM@221
   825
            Cygwin.vboxExecute('import "' + image_path + '" --vsys 0 --vmname ' + VMManager.vmRootName + ' --unit 12 --disk "' + self.templateImage + '"')
BarthaM@221
   826
        else:
BarthaM@221
   827
            import_logger.info('Found ' + VMManager.vmRootName + ' already present in VBox reusing it.')
BarthaM@221
   828
            import_logger.info('if you want a complete new import please remove the VM first.')
BarthaM@221
   829
            import_logger.info('starting OpenSecurity service...')
BarthaM@221
   830
            return
mb@90
   831
BarthaM@221
   832
        # remove unnecessary IDE controller
BarthaM@221
   833
        Cygwin.vboxExecute('storagectl ' + VMManager.vmRootName + ' --name IDE --remove')
BarthaM@221
   834
BarthaM@221
   835
        info = self.getVDiskController(VMManager.vmRootName, self.templateImage)
BarthaM@221
   836
        if info:
BarthaM@221
   837
            info = info.split('-')
BarthaM@221
   838
            self.detachVDisk(VMManager.vmRootName, info[0], info[1], info[2])
BarthaM@221
   839
        
BarthaM@221
   840
        self.changeVDiskType(self.templateImage, 'immutable')
BarthaM@221
   841
        self.attachVDisk(VMManager.vmRootName, info[0], info[1], info[2], self.templateImage)
BarthaM@221
   842
        import_logger.info('Initial import finished.')    
BarthaM@221
   843
        
BarthaM@221
   844
    # update template 
BarthaM@221
   845
    def updateTemplate(self):
BarthaM@221
   846
        import_logger.debug('Stopping Opensecurity...')
BarthaM@221
   847
        self.stop()
BarthaM@221
   848
        
BarthaM@221
   849
        import_logger.debug('Cleaning up system in preparation for update...')
BarthaM@221
   850
        self.cleanup()
BarthaM@221
   851
        
BarthaM@221
   852
        import_logger.info('Cleanup finished...')
BarthaM@221
   853
        
BarthaM@221
   854
        # shutdown template if running
BarthaM@221
   855
        self.poweroffVM(self.vmRootName)
BarthaM@221
   856
        
BarthaM@221
   857
        import_logger.info('Starting template VM...')
BarthaM@221
   858
        # check for updates
BarthaM@221
   859
        self.genCertificate(self.vmRootName)
BarthaM@221
   860
        self.attachCertificate(self.vmRootName)
BarthaM@221
   861
BarthaM@221
   862
        import_logger.info('Removing snapshots...')        
BarthaM@221
   863
        
BarthaM@221
   864
        self.detachVDisk(self.vmRootName, 'SATA', '0', '0')
BarthaM@221
   865
        templateUUID = self.getVDiskUUID(self.templateImage)
BarthaM@221
   866
        self.removeSnapshots(templateUUID)
BarthaM@221
   867
        
BarthaM@221
   868
        import_logger.info('Setting VDisk image to normal...')
BarthaM@221
   869
        self.changeVDiskType(self.templateImage, 'normal')
BarthaM@221
   870
        self.attachVDisk(self.vmRootName, 'SATA', '0', '0', self.templateImage)
BarthaM@221
   871
        
BarthaM@221
   872
        import_logger.info('Starting VM...')
BarthaM@221
   873
        self.startVM(self.vmRootName)
BarthaM@221
   874
        self.waitStartup(self.vmRootName)
BarthaM@221
   875
        
BarthaM@221
   876
        import_logger.info('Updating components...')
BarthaM@221
   877
        tmp_ip = self.getHostOnlyIP(self.vmRootName)
BarthaM@221
   878
        tmp_machine_folder = Cygwin.cygPath(VMManager.machineFolder)
BarthaM@221
   879
        Cygwin.sshExecute('"sudo apt-get -y update"', tmp_ip, 'osecuser', tmp_machine_folder + '/' + self.vmRootName + '/dvm_key')
BarthaM@221
   880
        Cygwin.sshExecute('"sudo apt-get -y upgrade"', tmp_ip, 'osecuser', tmp_machine_folder + '/' + self.vmRootName + '/dvm_key')
BarthaM@221
   881
        
BarthaM@221
   882
        import_logger.info('Restarting template VM...')
BarthaM@221
   883
        #check if reboot is required
BarthaM@221
   884
        result = Cygwin.sshExecute('"if [ -f /var/run/reboot-required ]; then echo \\\"Yes\\\"; fi"', tmp_ip, 'osecuser', tmp_machine_folder + '/' + self.vmRootName + '/dvm_key')
BarthaM@221
   885
        if "Yes" in result[1]:
BarthaM@221
   886
            self.stopVM(self.vmRootName)
BarthaM@221
   887
            self.waitShutdown(self.vmRootName)
BarthaM@221
   888
            self.startVM(self.vmRootName)
BarthaM@221
   889
            self.waitStartup(self.vmRootName)
BarthaM@221
   890
        
BarthaM@221
   891
        import_logger.info('Stopping template VM...')
BarthaM@221
   892
        self.stopVM(self.vmRootName)
BarthaM@221
   893
        self.waitShutdown(self.vmRootName)
BarthaM@221
   894
        
BarthaM@221
   895
        import_logger.info('Setting VDisk image to immutable...')
BarthaM@221
   896
        self.detachVDisk(self.vmRootName, 'SATA', '0', '0') 
BarthaM@221
   897
        self.changeVDiskType(self.templateImage, 'immutable')
BarthaM@221
   898
        self.attachVDisk(self.vmRootName,  'SATA', '0', '0', self.templateImage)
BarthaM@221
   899
        
BarthaM@221
   900
        import_logger.info('Update template finished...')
BarthaM@221
   901
    
BarthaM@221
   902
    def startInitialImport(self):
BarthaM@221
   903
        if self.importHandler and self.importHandler.isAlive():
BarthaM@221
   904
            import_logger.info("Initial import already running.")
BarthaM@221
   905
            return
BarthaM@221
   906
        self.importHandler = InitialImportHandler(self)
BarthaM@221
   907
        self.importHandler.start()
BarthaM@221
   908
        import_logger.info("Initial import started.")
BarthaM@221
   909
        
BarthaM@221
   910
    def startUpdateTemplate(self):
BarthaM@221
   911
        if self.updateHandler and self.updateHandler.isAlive():
BarthaM@221
   912
            import_logger.info("Initial import already running.")
BarthaM@221
   913
            return
BarthaM@221
   914
        self.updateHandler = UpdateHandler(self)
BarthaM@221
   915
        self.updateHandler.start()
BarthaM@221
   916
        import_logger.info("Initial import started.")
BarthaM@234
   917
        
BarthaM@234
   918
    def createSession(self):
BarthaM@234
   919
        new_sdvm = self.newSDVM()
BarthaM@234
   920
        self.attachVDisk(new_sdvm, 'SATA', '0', '0', self.templateImage)
BarthaM@234
   921
        self.genCertificate(new_sdvm)
BarthaM@234
   922
        self.attachCertificate(new_sdvm)
BarthaM@234
   923
        self.startVM(new_sdvm)
BarthaM@234
   924
        new_ip = self.waitStartup(new_sdvm)
BarthaM@234
   925
        if new_ip == None:
BarthaM@234
   926
            logger.error("Error getting IP address of SDVM. Cleaning up.")
BarthaM@234
   927
            self.poweroffVM(new_sdvm)
BarthaM@234
   928
            self.removeVM(new_sdvm)
BarthaM@234
   929
            return None
BarthaM@234
   930
        else:
BarthaM@234
   931
            logger.info("Got IP address for " + new_sdvm + ' ' + new_ip)
BarthaM@234
   932
            self.vms[new_sdvm] = {'vm_name' : new_sdvm, 'ip_addr' : new_ip, 'used' : False, 'running' : True}
BarthaM@234
   933
            return self.vms[new_sdvm]
BarthaM@234
   934
            
BarthaM@234
   935
    def releaseSession(self, vm_name):
BarthaM@234
   936
        del self.vms[vm_name]
BarthaM@234
   937
        self.poweroffVM(vm_name)
BarthaM@234
   938
        self.removeVM(vm_name)
BarthaM@234
   939
        self.sdvmFactory.trigger()
BarthaM@234
   940
        
BarthaM@234
   941
    def getSession(self):
BarthaM@234
   942
        # return first found unused SDVM
BarthaM@234
   943
        for vm in self.vms.values():
BarthaM@234
   944
            if vm['used'] == False:
BarthaM@234
   945
                vm['used'] = True
BarthaM@234
   946
                self.sdvmFactory.trigger()
BarthaM@234
   947
                return vm
BarthaM@234
   948
        return self.createSession()
BarthaM@234
   949
        
BarthaM@234
   950
class SDVMFactory(threading.Thread):
BarthaM@234
   951
    vmm = None
BarthaM@234
   952
    running = True
BarthaM@234
   953
    triggerEv = None
BarthaM@234
   954
    
BarthaM@234
   955
    def __init__(self, vmmanager):
BarthaM@234
   956
        threading.Thread.__init__(self)
BarthaM@234
   957
        self.vmm = vmmanager
BarthaM@234
   958
        self.triggerEv = threading.Event()
BarthaM@234
   959
        
BarthaM@234
   960
    def run(self):
BarthaM@234
   961
        while self.running:
BarthaM@234
   962
            self.triggerEv.clear()            
BarthaM@234
   963
BarthaM@234
   964
            if len(self.vmm.vms) < 2:
BarthaM@234
   965
                self.vmm.createSession()
BarthaM@234
   966
                continue
BarthaM@234
   967
            unused = 0
BarthaM@234
   968
            for vm in self.vmm.vms.values():
BarthaM@234
   969
                if vm['used'] == False:
BarthaM@234
   970
                    unused+=1
BarthaM@234
   971
            if unused == 0:
BarthaM@234
   972
                self.vmm.createSession()
BarthaM@234
   973
            self.triggerEv.wait()
BarthaM@234
   974
    
BarthaM@234
   975
    def trigger(self):
BarthaM@234
   976
        self.triggerEv.set()
BarthaM@234
   977
        
BarthaM@234
   978
    def stop(self):
BarthaM@234
   979
        self.running = False
BarthaM@234
   980
        self.triggerEv.set()
BarthaM@234
   981
        
BarthaM@234
   982
#handles browsing session creation 
BarthaM@234
   983
class BrowsingHandler(threading.Thread):
BarthaM@234
   984
    vmm = None
BarthaM@234
   985
    proxy = None
BarthaM@234
   986
    wpad = None
BarthaM@234
   987
    net_resource = None
BarthaM@234
   988
    ip_addr = None
BarthaM@234
   989
    vm_name = None
BarthaM@234
   990
    
BarthaM@234
   991
    def __init__(self, vmmanager, proxy, wpad):
BarthaM@234
   992
        threading.Thread.__init__(self)
BarthaM@234
   993
        self.vmm = vmmanager
BarthaM@234
   994
        self.proxy = proxy
BarthaM@234
   995
        self.wpad = wpad
BarthaM@234
   996
        
BarthaM@234
   997
    def run(self):
BarthaM@234
   998
        session = None
BarthaM@234
   999
        try:
BarthaM@234
  1000
            appDataDir = self.getAppDataDir()
BarthaM@234
  1001
BarthaM@234
  1002
            session = self.vmm.getSession()
BarthaM@234
  1003
            if not session:
BarthaM@234
  1004
                raise OpenSecurityException("Could not get new SDVM session.")
BarthaM@234
  1005
            
BarthaM@234
  1006
            self.ip_addr = session['ip_addr']
BarthaM@234
  1007
            self.vm_name = session['vm_name']
BarthaM@234
  1008
            
BarthaM@234
  1009
            self.net_resource = '\\\\' + self.ip_addr + '\\Download'
BarthaM@234
  1010
            urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'net_resource='+self.net_resource).readline()
BarthaM@234
  1011
            
BarthaM@234
  1012
            logger.info("Restoring browser settings in AppData dir " + appDataDir)
BarthaM@234
  1013
            # create OpenSecurity settings dir on local machine user home /AppData/Roaming 
BarthaM@234
  1014
            Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + appDataDir + '/OpenSecurity\\\"')
BarthaM@234
  1015
            # create chromium settings dir on local machine if not existing
BarthaM@234
  1016
            Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + appDataDir + '/OpenSecurity/chromium\\\"')
BarthaM@234
  1017
            # create chromium settings dir on remote machine if not existing
BarthaM@234
  1018
            Cygwin.sshExecute('"mkdir -p \\\"/home/osecuser/.config\\\""', self.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key')
BarthaM@234
  1019
            #restore settings on vm
BarthaM@234
  1020
            self.restoreFile(appDataDir + '/OpenSecurity/chromium', '/home/osecuser/.config/')
BarthaM@234
  1021
                    
BarthaM@234
  1022
            if self.wpad:
BarthaM@234
  1023
                browser = '\\\"/usr/bin/chromium --proxy-pac-url=\\\"'+self.wpad+'\\\"\\\"'
BarthaM@234
  1024
            elif self.proxy:
BarthaM@234
  1025
                browser = '\\\"export http_proxy='+self.proxy+'; /usr/bin/chromium\\\"'
BarthaM@234
  1026
            else:
BarthaM@234
  1027
                browser = '\\\"/usr/bin/chromium\\\"'
BarthaM@234
  1028
                
BarthaM@234
  1029
            Cygwin.sshExecuteX11(browser, self.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key')
BarthaM@234
  1030
            self.backupFile('/home/osecuser/.config/chromium', appDataDir + '/OpenSecurity/')
BarthaM@234
  1031
        
BarthaM@234
  1032
        except urllib2.URLError:
BarthaM@234
  1033
            logger.error("Network drive connect failed. OpenSecurity Tray client not running.")
BarthaM@234
  1034
            self.net_resource = None
BarthaM@234
  1035
BarthaM@234
  1036
        except:
BarthaM@234
  1037
            logger.info("BrowsingHandler failed. See log for details")
BarthaM@234
  1038
        
BarthaM@234
  1039
        if session:
BarthaM@234
  1040
            if self.net_resource == None:
BarthaM@234
  1041
                logger.info("Missing browsing SDVM's network share. Skipping disconnect")
BarthaM@234
  1042
            else:
BarthaM@234
  1043
                try:
BarthaM@234
  1044
                    urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'net_resource='+self.net_resource).readline()
BarthaM@234
  1045
                    self.net_resource = None
BarthaM@234
  1046
                except urllib2.URLError:
BarthaM@234
  1047
                    logger.error("Network share disconnect failed. OpenSecurity Tray client not running.")
BarthaM@234
  1048
        if self.vm_name:
BarthaM@234
  1049
            self.vmm.releaseSession(self.vm_name)
BarthaM@234
  1050
        
BarthaM@234
  1051
        self.vmm.sdvmFactory.trigger()
BarthaM@234
  1052
BarthaM@234
  1053
    def backupFile(self, src, dest):
BarthaM@234
  1054
        certificate = Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key'
BarthaM@234
  1055
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "osecuser@' + self.ip_addr + ':' + src + '" "' + dest + '"'
BarthaM@234
  1056
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)
BarthaM@234
  1057
    
BarthaM@234
  1058
    def restoreFile(self, src, dest):
BarthaM@234
  1059
        certificate = Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key'
BarthaM@234
  1060
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "' + src + '" "osecuser@' + self.ip_addr + ':' + dest + '"'
BarthaM@234
  1061
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)
BarthaM@234
  1062
                
BarthaM@234
  1063
    def getAppDataDir(self):
BarthaM@234
  1064
        user = self.vmm.getActiveUserName()
BarthaM@234
  1065
        if user == None:
BarthaM@234
  1066
            logger.error("Cannot get active user name")
BarthaM@234
  1067
            raise OpenSecurityException("Cannot get active user name")
BarthaM@234
  1068
        else:
BarthaM@234
  1069
            logger.info('Got active user name ' + user)
BarthaM@234
  1070
        sid = self.vmm.getUserSID(user)
BarthaM@234
  1071
        if sid == None:
BarthaM@234
  1072
            logger.error("Cannot get SID for active user")
BarthaM@234
  1073
            raise OpenSecurityException("Cannot get SID for active user")
BarthaM@234
  1074
        else:
BarthaM@234
  1075
            logger.info("Got active user SID " + sid + " for user " + user)
BarthaM@234
  1076
            
BarthaM@234
  1077
        path = self.vmm.getAppDataDir(sid)
BarthaM@234
  1078
        if path == None:
BarthaM@234
  1079
            logger.error("Cannot get AppDataDir for active user")
BarthaM@234
  1080
            raise OpenSecurityException("Cannot get AppDataDir for active user")
BarthaM@234
  1081
        else:
BarthaM@234
  1082
            logger.info("Got AppData dir for user " + user + ': ' + path)
BarthaM@234
  1083
        
BarthaM@234
  1084
        return Cygwin.cygPath(path)
BarthaM@234
  1085
            
BarthaM@234
  1086
                
BarthaM@234
  1087
class DeviceHandler(threading.Thread): 
BarthaM@234
  1088
    vmm = None
BarthaM@234
  1089
    existingRSDs = None
BarthaM@234
  1090
    attachedRSDs = None  
BarthaM@234
  1091
    running = True
BarthaM@234
  1092
    def __init__(self, vmmanger): 
BarthaM@234
  1093
        threading.Thread.__init__(self)
BarthaM@234
  1094
        self.vmm = vmmanger
BarthaM@234
  1095
 
BarthaM@234
  1096
    def stop(self):
BarthaM@234
  1097
        self.running = False
BarthaM@234
  1098
        
BarthaM@234
  1099
    def run(self):
BarthaM@234
  1100
        self.existingRSDs = dict()
BarthaM@234
  1101
        self.attachedRSDs = self.vmm.getAttachedRSDs()
BarthaM@234
  1102
        
BarthaM@234
  1103
        while self.running:
BarthaM@234
  1104
            tmp_rsds = self.vmm.getExistingRSDs()
BarthaM@234
  1105
            if tmp_rsds.keys() == self.existingRSDs.keys():
BarthaM@234
  1106
                logger.debug("Nothing's changed. sleep(3)")
BarthaM@234
  1107
                time.sleep(3)
BarthaM@234
  1108
                continue
BarthaM@234
  1109
            
BarthaM@234
  1110
            showTrayMessage('System changed.\nEvaluating...', 7000)
BarthaM@234
  1111
            logger.info("Something's changed")
BarthaM@234
  1112
            
BarthaM@234
  1113
            tmp_attached = self.attachedRSDs     
BarthaM@234
  1114
            for vm_name in tmp_attached.keys():
BarthaM@234
  1115
                if tmp_attached[vm_name] not in tmp_rsds.values():
BarthaM@234
  1116
                    ip = self.vmm.getHostOnlyIP(vm_name)
BarthaM@234
  1117
                    if ip == None:
BarthaM@234
  1118
                        logger.error("Failed getting hostonly IP for " + vm_name)
BarthaM@234
  1119
                        continue
BarthaM@234
  1120
                    
BarthaM@234
  1121
                    try:
BarthaM@234
  1122
                        net_resource = '\\\\' + ip + '\\USB'
BarthaM@234
  1123
                        result = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'net_resource='+net_resource).readline()
BarthaM@234
  1124
                    except urllib2.URLError:
BarthaM@234
  1125
                        logger.error("Network drive disconnect failed. OpenSecurity Tray client not running.")
BarthaM@234
  1126
                        continue
BarthaM@234
  1127
                    
BarthaM@234
  1128
                    # detach not necessary as already removed from vm description upon disconnect
BarthaM@234
  1129
                    del self.attachedRSDs[vm_name]
BarthaM@234
  1130
                    self.vmm.releaseSession(vm_name)
BarthaM@234
  1131
                    
BarthaM@234
  1132
            #create new vms for new devices if any
BarthaM@234
  1133
            new_ip = None
BarthaM@234
  1134
            for new_device in tmp_rsds.values():
BarthaM@234
  1135
                showTrayMessage('Mounting device...', 7000)
BarthaM@234
  1136
                if (self.attachedRSDs and False) or (new_device not in self.attachedRSDs.values()):
BarthaM@234
  1137
                   
BarthaM@234
  1138
                    session = self.vmm.getSession()
BarthaM@234
  1139
                    if not session:
BarthaM@234
  1140
                        logger.info("Could not get new SDVM session.")
BarthaM@234
  1141
                        continue
BarthaM@234
  1142
                        #raise OpenSecurityException("Could not get new SDVM session.")
BarthaM@234
  1143
                    new_sdvm = session['vm_name']
BarthaM@234
  1144
                    new_ip = session['ip_addr']
BarthaM@234
  1145
                    try:
BarthaM@234
  1146
                        self.vmm.attachRSD(new_sdvm, new_device)
BarthaM@234
  1147
                        self.attachedRSDs[new_sdvm] = new_device
BarthaM@234
  1148
                    except:
BarthaM@234
  1149
                        logger.info("RSD prematurely removed. Cleaning up.")
BarthaM@234
  1150
                        self.vmm.releaseSession(new_sdvm)
BarthaM@234
  1151
                        continue
BarthaM@234
  1152
                    
BarthaM@234
  1153
                    try:
BarthaM@234
  1154
                        net_resource = '\\\\' + new_ip + '\\USB'
BarthaM@234
  1155
                        result = urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'net_resource='+net_resource).readline()
BarthaM@234
  1156
                    except urllib2.URLError:
BarthaM@234
  1157
                        logger.error("Network drive connect failed (tray client not accessible). Cleaning up.")
BarthaM@234
  1158
                        self.vmm.releaseSession(new_sdvm)
BarthaM@234
  1159
                        continue
BarthaM@234
  1160
                    
BarthaM@234
  1161
            self.existingRSDs = tmp_rsds
BarthaM@221
  1162
BarthaM@221
  1163
class UpdateHandler(threading.Thread):
BarthaM@221
  1164
    vmm = None    
BarthaM@221
  1165
    def __init__(self, vmmanager):
BarthaM@221
  1166
        threading.Thread.__init__(self)
BarthaM@221
  1167
        self.vmm = vmmanager
BarthaM@221
  1168
    
BarthaM@221
  1169
    def run(self):
BarthaM@221
  1170
        try:
BarthaM@221
  1171
            self.vmm.updateTemplate()
BarthaM@221
  1172
        except:
BarthaM@221
  1173
            import_logger.info("Update template failed. Refer to service log for details.")
BarthaM@221
  1174
        self.vmm.start(force=True)
BarthaM@221
  1175
    
BarthaM@221
  1176
class InitialImportHandler(threading.Thread):
BarthaM@221
  1177
    vmm = None    
BarthaM@221
  1178
    def __init__(self, vmmanager):
BarthaM@221
  1179
        threading.Thread.__init__(self)
BarthaM@221
  1180
        self.vmm = vmmanager
BarthaM@221
  1181
    
BarthaM@221
  1182
    def run(self):
BarthaM@221
  1183
        try:
BarthaM@221
  1184
            self.vmm.importTemplate(self.vmm.getMachineFolder() + '\\OsecVM.ova')
BarthaM@221
  1185
            self.vmm.updateTemplate()
BarthaM@221
  1186
        except:
BarthaM@221
  1187
            import_logger.info("Initial import failed. Refer to service log for details.")
BarthaM@234
  1188
        self.vmm.start(force=True)