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