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