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