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