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