mb@63
|
1 |
'''
|
mb@63
|
2 |
Created on Nov 19, 2013
|
mb@63
|
3 |
|
mb@63
|
4 |
@author: BarthaM
|
mb@63
|
5 |
'''
|
mb@63
|
6 |
import os
|
mb@63
|
7 |
import os.path
|
mb@63
|
8 |
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
|
mb@63
|
9 |
import subprocess
|
mb@63
|
10 |
import sys
|
mb@63
|
11 |
import re
|
mb@63
|
12 |
|
mb@63
|
13 |
from cygwin import Cygwin
|
mb@63
|
14 |
from environment import Environment
|
mb@63
|
15 |
import threading
|
mb@63
|
16 |
import time
|
mb@63
|
17 |
import string
|
mb@63
|
18 |
|
mb@63
|
19 |
import shutil
|
mb@63
|
20 |
import stat
|
mb@63
|
21 |
import tempfile
|
mb@63
|
22 |
from opensecurity_util import logger, setupLogger, OpenSecurityException
|
mb@63
|
23 |
|
mb@63
|
24 |
DEBUG = True
|
mb@63
|
25 |
|
mb@63
|
26 |
class VMManagerException(Exception):
|
mb@63
|
27 |
def __init__(self, value):
|
mb@63
|
28 |
self.value = value
|
mb@63
|
29 |
def __str__(self):
|
mb@63
|
30 |
return repr(self.value)
|
mb@63
|
31 |
|
mb@63
|
32 |
class USBFilter:
|
mb@63
|
33 |
vendorid = ""
|
mb@63
|
34 |
productid = ""
|
mb@63
|
35 |
revision = ""
|
mb@63
|
36 |
|
mb@63
|
37 |
def __init__(self, vendorid, productid, revision):
|
mb@63
|
38 |
self.vendorid = vendorid.lower()
|
mb@63
|
39 |
self.productid = productid.lower()
|
mb@63
|
40 |
self.revision = revision.lower()
|
mb@63
|
41 |
return
|
mb@63
|
42 |
|
mb@63
|
43 |
def __eq__(self, other):
|
mb@63
|
44 |
return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
|
mb@63
|
45 |
|
mb@63
|
46 |
def __hash__(self):
|
mb@63
|
47 |
return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
|
mb@63
|
48 |
|
mb@63
|
49 |
def __repr__(self):
|
mb@63
|
50 |
return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
|
mb@63
|
51 |
|
mb@63
|
52 |
class VMManager(object):
|
mb@63
|
53 |
vmRootName = "SecurityDVM"
|
mb@63
|
54 |
systemProperties = None
|
mb@63
|
55 |
startNotifications = list()
|
mb@63
|
56 |
_instance = None
|
mb@63
|
57 |
machineFolder = ''
|
mb@78
|
58 |
attachedRSDs = None
|
mb@78
|
59 |
connectedRSDs = None
|
mb@63
|
60 |
|
mb@63
|
61 |
def __init__(self):
|
mb@63
|
62 |
self.systemProperties = self.getSystemProperties()
|
mb@63
|
63 |
self.machineFolder = self.systemProperties["Default machine folder"]
|
mb@63
|
64 |
self.cleanup()
|
mb@78
|
65 |
self.attachedRSDs = self.getAttachedRSDs()
|
mb@78
|
66 |
self.connectedRSDs = self.getConnectedRSDS()
|
mb@63
|
67 |
return
|
mb@63
|
68 |
|
mb@63
|
69 |
@staticmethod
|
mb@63
|
70 |
def getInstance():
|
mb@63
|
71 |
if VMManager._instance == None:
|
mb@63
|
72 |
VMManager._instance = VMManager()
|
mb@63
|
73 |
return VMManager._instance
|
mb@63
|
74 |
|
mb@63
|
75 |
def cleanup(self):
|
mb@63
|
76 |
self.unmapNetworkDrive('G:')
|
mb@63
|
77 |
self.unmapNetworkDrive('H:')
|
mb@63
|
78 |
for vm in self.listSDVM():
|
mb@63
|
79 |
self.poweroffVM(vm)
|
mb@63
|
80 |
self.removeVM(vm)
|
mb@63
|
81 |
|
mb@63
|
82 |
def putStartNotification(self, ip):
|
mb@63
|
83 |
self.startNotifications.append(ip)
|
mb@63
|
84 |
|
mb@63
|
85 |
def isSDVMStarted(self, ip):
|
mb@63
|
86 |
return self.startNotifications.contains(ip)
|
mb@63
|
87 |
|
mb@63
|
88 |
# return hosty system properties
|
mb@63
|
89 |
def getSystemProperties(self):
|
mb@63
|
90 |
result = Cygwin.vboxExecute('list systemproperties')
|
mb@63
|
91 |
if result[1]=='':
|
mb@63
|
92 |
return None
|
mb@63
|
93 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
|
mb@78
|
94 |
#logger.debug(props)
|
mb@63
|
95 |
return props
|
mb@63
|
96 |
|
mb@63
|
97 |
# return the folder containing the guest VMs
|
mb@63
|
98 |
def getMachineFolder(self):
|
mb@63
|
99 |
return self.machineFolder
|
mb@63
|
100 |
|
mb@63
|
101 |
#list the hostonly IFs exposed by the VBox host
|
mb@63
|
102 |
def getHostOnlyIFs(self):
|
mb@63
|
103 |
result = Cygwin.vboxExecute('list hostonlyifs')[1]
|
mb@63
|
104 |
if result=='':
|
mb@63
|
105 |
return None
|
mb@63
|
106 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
|
mb@63
|
107 |
return props
|
mb@63
|
108 |
|
mb@63
|
109 |
# list all existing VMs registered with VBox
|
mb@63
|
110 |
def listVM(self):
|
mb@63
|
111 |
result = Cygwin.vboxExecute('list vms')[1]
|
mb@63
|
112 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@63
|
113 |
return vms
|
mb@63
|
114 |
|
mb@63
|
115 |
# list running VMs
|
mb@63
|
116 |
def listRunningVMS(self):
|
mb@63
|
117 |
result = Cygwin.vboxExecute('list runningvms')[1]
|
mb@63
|
118 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@63
|
119 |
return vms
|
mb@63
|
120 |
|
mb@63
|
121 |
# list existing SDVMs
|
mb@63
|
122 |
def listSDVM(self):
|
mb@63
|
123 |
vms = self.listVM()
|
mb@63
|
124 |
svdms = []
|
mb@63
|
125 |
for vm in vms:
|
mb@63
|
126 |
if vm.startswith(self.vmRootName) and vm != self.vmRootName:
|
mb@63
|
127 |
svdms.append(vm)
|
mb@63
|
128 |
return svdms
|
mb@63
|
129 |
|
mb@63
|
130 |
# generate valid (not already existing SDVM name). necessary for creating a new VM
|
mb@63
|
131 |
def generateSDVMName(self):
|
mb@63
|
132 |
vms = self.listVM()
|
mb@63
|
133 |
for i in range(0,999):
|
mb@63
|
134 |
if(not self.vmRootName+str(i) in vms):
|
mb@63
|
135 |
return self.vmRootName+str(i)
|
mb@63
|
136 |
return ''
|
mb@63
|
137 |
|
mb@78
|
138 |
# return the RSDs connected to the host
|
mb@78
|
139 |
def getConnectedRSDS(self):
|
mb@78
|
140 |
results = Cygwin.vboxExecute('list usbhost')[1]
|
mb@78
|
141 |
results = results.split('Host USB Devices:')[1].strip()
|
mb@78
|
142 |
|
mb@78
|
143 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@78
|
144 |
rsds = dict()
|
mb@78
|
145 |
for item in items:
|
mb@78
|
146 |
props = dict()
|
mb@78
|
147 |
for line in item.splitlines():
|
mb@78
|
148 |
if line != "":
|
mb@78
|
149 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@78
|
150 |
props[k] = v
|
mb@78
|
151 |
|
mb@78
|
152 |
if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
|
mb@78
|
153 |
usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
|
mb@78
|
154 |
re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
|
mb@78
|
155 |
re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
|
mb@78
|
156 |
rsds[props['UUID']] = usb_filter;
|
mb@78
|
157 |
logger.debug(usb_filter)
|
mb@78
|
158 |
return rsds
|
mb@78
|
159 |
|
mb@63
|
160 |
# return the RSDs attached to all existing SDVMs
|
mb@63
|
161 |
def getAttachedRSDs(self):
|
mb@63
|
162 |
vms = self.listSDVM()
|
mb@63
|
163 |
attached_devices = dict()
|
mb@63
|
164 |
for vm in vms:
|
mb@63
|
165 |
rsd_filter = self.getUSBFilter(vm)
|
mb@63
|
166 |
if rsd_filter != None:
|
mb@63
|
167 |
attached_devices[vm] = rsd_filter
|
mb@63
|
168 |
return attached_devices
|
mb@63
|
169 |
|
mb@63
|
170 |
# configures hostonly networking and DHCP server. requires admin rights
|
mb@63
|
171 |
def configureHostNetworking(self):
|
mb@63
|
172 |
#cmd = 'vboxmanage list hostonlyifs'
|
mb@63
|
173 |
#Cygwin.vboxExecute(cmd)
|
mb@63
|
174 |
#cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
|
mb@63
|
175 |
#Cygwin.vboxExecute(cmd)
|
mb@63
|
176 |
#cmd = 'vboxmanage hostonlyif create'
|
mb@63
|
177 |
#Cygwin.vboxExecute(cmd)
|
mb@63
|
178 |
Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0')
|
mb@63
|
179 |
#cmd = 'vboxmanage dhcpserver add'
|
mb@63
|
180 |
#Cygwin.vboxExecute(cmd)
|
mb@63
|
181 |
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@63
|
182 |
|
mb@63
|
183 |
#create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
|
mb@63
|
184 |
def createVM(self, vm_name):
|
mb@63
|
185 |
hostonly_if = self.getHostOnlyIFs()
|
mb@63
|
186 |
Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register')
|
mb@63
|
187 |
Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat')
|
mb@63
|
188 |
Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2')
|
mb@63
|
189 |
return
|
mb@63
|
190 |
|
mb@63
|
191 |
# attach storage image to controller
|
mb@63
|
192 |
def storageAttach(self, vm_name):
|
mb@63
|
193 |
if self.isStorageAttached(vm_name):
|
mb@63
|
194 |
self.storageDetach(vm_name)
|
mb@63
|
195 |
Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"')
|
mb@63
|
196 |
return
|
mb@63
|
197 |
|
mb@63
|
198 |
# return true if storage is attached
|
mb@63
|
199 |
def isStorageAttached(self, vm_name):
|
mb@63
|
200 |
info = self.getVMInfo(vm_name)
|
mb@63
|
201 |
return (info['SATA-0-0']!='none')
|
mb@63
|
202 |
|
mb@63
|
203 |
# detach storage from controller
|
mb@63
|
204 |
def storageDetach(self, vm_name):
|
mb@63
|
205 |
if self.isStorageAttached(vm_name):
|
mb@63
|
206 |
Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none')
|
mb@63
|
207 |
return
|
mb@63
|
208 |
|
mb@63
|
209 |
def changeStorageType(self, filename, storage_type):
|
mb@63
|
210 |
Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type)
|
mb@63
|
211 |
return
|
mb@63
|
212 |
|
mb@63
|
213 |
# list storage snaphots for VM
|
mb@63
|
214 |
def updateTemplate(self):
|
mb@78
|
215 |
self.cleanup()
|
mb@63
|
216 |
self.poweroffVM('SecurityDVM')
|
mb@63
|
217 |
self.waitShutdown('SecurityDVM')
|
mb@63
|
218 |
|
mb@63
|
219 |
# check for updates
|
mb@63
|
220 |
self.genCertificateISO('SecurityDVM')
|
mb@63
|
221 |
self.attachCertificateISO('SecurityDVM')
|
mb@63
|
222 |
|
mb@63
|
223 |
self.storageDetach('SecurityDVM')
|
mb@63
|
224 |
results = Cygwin.vboxExecute('list hdds')[1]
|
mb@63
|
225 |
results = results.replace('Parent UUID', 'Parent')
|
mb@63
|
226 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@63
|
227 |
|
mb@63
|
228 |
snaps = dict()
|
mb@63
|
229 |
for item in items:
|
mb@63
|
230 |
props = dict()
|
mb@63
|
231 |
for line in item.splitlines():
|
mb@63
|
232 |
if line != "":
|
mb@63
|
233 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@63
|
234 |
props[k] = v;
|
mb@63
|
235 |
snaps[props['UUID']] = props
|
mb@63
|
236 |
|
mb@63
|
237 |
|
mb@63
|
238 |
template_storage = self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
|
mb@63
|
239 |
|
mb@63
|
240 |
# find template uuid
|
mb@63
|
241 |
template_uuid = ''
|
mb@63
|
242 |
for hdd in snaps.values():
|
mb@63
|
243 |
if hdd['Location'] == template_storage:
|
mb@63
|
244 |
template_uuid = hdd['UUID']
|
mb@63
|
245 |
logger.debug('found parent uuid ' + template_uuid)
|
mb@63
|
246 |
|
mb@63
|
247 |
# remove snapshots
|
mb@63
|
248 |
for hdd in snaps.values():
|
mb@63
|
249 |
if hdd['Parent'] == template_uuid:
|
mb@63
|
250 |
#template_uuid = hdd['UUID']
|
mb@63
|
251 |
logger.debug('removing snapshot ' + hdd['UUID'])
|
mb@63
|
252 |
results = Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete')[1]
|
mb@63
|
253 |
# parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
|
mb@63
|
254 |
|
mb@63
|
255 |
self.changeStorageType(template_storage,'normal')
|
mb@63
|
256 |
self.storageAttach('SecurityDVM')
|
mb@63
|
257 |
self.startVM('SecurityDVM')
|
mb@63
|
258 |
self.waitStartup('SecurityDVM')
|
mb@78
|
259 |
Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key' )
|
mb@78
|
260 |
Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key' )
|
mb@63
|
261 |
self.stopVM('SecurityDVM')
|
mb@78
|
262 |
#self.hibernateVM('SecurityDVM')
|
mb@63
|
263 |
self.waitShutdown('SecurityDVM')
|
mb@63
|
264 |
self.storageDetach('SecurityDVM')
|
mb@63
|
265 |
self.changeStorageType(template_storage,'immutable')
|
mb@63
|
266 |
self.storageAttach('SecurityDVM')
|
mb@78
|
267 |
self.handleDeviceChange()
|
mb@63
|
268 |
|
mb@63
|
269 |
#remove VM from the system. should be used on VMs returned by listSDVMs
|
mb@63
|
270 |
def removeVM(self, vm_name):
|
mb@63
|
271 |
logger.info('Removing ' + vm_name)
|
mb@63
|
272 |
Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete')
|
mb@63
|
273 |
machineFolder = Cygwin.cygPath(self.machineFolder)
|
mb@63
|
274 |
Cygwin.bashExecute('"/usr/bin/rm -rf ' + machineFolder + '/' + vm_name + '"')
|
mb@63
|
275 |
|
mb@63
|
276 |
# start VM
|
mb@63
|
277 |
def startVM(self, vm_name):
|
mb@63
|
278 |
logger.info('Starting ' + vm_name)
|
mb@66
|
279 |
result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' )
|
mb@63
|
280 |
while not string.find(str(result), 'successfully started',):
|
mb@63
|
281 |
logger.error("Failed to start SDVM: " + vm_name + " retrying")
|
mb@63
|
282 |
time.sleep(1)
|
mb@63
|
283 |
result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless')
|
mb@63
|
284 |
return result[0]
|
mb@63
|
285 |
|
mb@63
|
286 |
# return wether VM is running or not
|
mb@63
|
287 |
def isVMRunning(self, vm_name):
|
mb@63
|
288 |
return vm_name in self.listRunningVMS()
|
mb@63
|
289 |
|
mb@63
|
290 |
# stop VM
|
mb@63
|
291 |
def stopVM(self, vm_name):
|
mb@63
|
292 |
logger.info('Sending shutdown signal to ' + vm_name)
|
mb@78
|
293 |
Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' )
|
mb@78
|
294 |
|
mb@78
|
295 |
# stop VM
|
mb@78
|
296 |
def hibernateVM(self, vm_name):
|
mb@78
|
297 |
logger.info('Sending shutdown signal to ' + vm_name)
|
mb@78
|
298 |
Cygwin.sshExecute( '"sudo hibernate-disk"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' )
|
mb@63
|
299 |
|
mb@63
|
300 |
# poweroff VM
|
mb@63
|
301 |
def poweroffVM(self, vm_name):
|
mb@63
|
302 |
if not self.isVMRunning(vm_name):
|
mb@63
|
303 |
return
|
mb@63
|
304 |
logger.info('Powering off ' + vm_name)
|
mb@63
|
305 |
return Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff')
|
mb@63
|
306 |
|
mb@63
|
307 |
# return the hostOnly IP for a running guest
|
mb@63
|
308 |
@staticmethod
|
mb@63
|
309 |
def getHostOnlyIP(vm_name):
|
mb@63
|
310 |
logger.info('Gettting hostOnly IP address ' + vm_name)
|
mb@63
|
311 |
result = Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP')
|
mb@63
|
312 |
if result=='':
|
mb@63
|
313 |
return None
|
mb@63
|
314 |
result = result[1]
|
mb@63
|
315 |
if result.startswith('No value set!'):
|
mb@63
|
316 |
return None
|
mb@63
|
317 |
return result[result.index(':')+1:].strip()
|
mb@63
|
318 |
|
mb@63
|
319 |
# attach removable storage device to VM by provision of filter
|
mb@63
|
320 |
def attachRSD(self, vm_name, rsd_filter):
|
mb@63
|
321 |
return Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision)
|
mb@63
|
322 |
|
mb@63
|
323 |
# detach removable storage from VM by
|
mb@63
|
324 |
def detachRSD(self, vm_name):
|
mb@63
|
325 |
return Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name )
|
mb@63
|
326 |
|
mb@63
|
327 |
|
mb@63
|
328 |
# return the description set for an existing VM
|
mb@63
|
329 |
def getVMInfo(self, vm_name):
|
mb@63
|
330 |
results = Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable')[1]
|
mb@63
|
331 |
props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
|
mb@78
|
332 |
#logger.debug(props)
|
mb@63
|
333 |
return props
|
mb@63
|
334 |
|
mb@63
|
335 |
# return the configured USB filter for an existing VM
|
mb@63
|
336 |
def getUSBFilter(self, vm_name):
|
mb@63
|
337 |
props = self.getVMInfo(vm_name)
|
mb@63
|
338 |
keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
|
mb@63
|
339 |
keyset = set(props.keys())
|
mb@63
|
340 |
usb_filter = None
|
mb@63
|
341 |
if keyset.issuperset(keys):
|
mb@63
|
342 |
usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
|
mb@63
|
343 |
return usb_filter
|
mb@63
|
344 |
|
mb@63
|
345 |
#generates ISO containing authorized_keys for use with guest VM
|
mb@63
|
346 |
def genCertificateISO(self, vm_name):
|
mb@63
|
347 |
machineFolder = Cygwin.cygPath(self.machineFolder)
|
mb@63
|
348 |
# remove .ssh folder if exists
|
mb@63
|
349 |
cmd = '\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
|
mb@63
|
350 |
Cygwin.bashExecute(cmd)
|
mb@63
|
351 |
# remove .ssh folder if exists
|
mb@63
|
352 |
Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"')
|
mb@63
|
353 |
# create .ssh folder in vm_name
|
mb@63
|
354 |
Cygwin.bashExecute('\"/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"')
|
mb@63
|
355 |
# generate dvm_key pair in vm_name / .ssh
|
mb@63
|
356 |
Cygwin.bashExecute('\"/usr/bin/ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"\"')
|
mb@63
|
357 |
# move out private key
|
mb@63
|
358 |
Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"')
|
mb@63
|
359 |
# set permissions for private key
|
mb@63
|
360 |
Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"')
|
mb@63
|
361 |
# rename public key to authorized_keys
|
mb@63
|
362 |
Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"')
|
mb@63
|
363 |
# set permissions for authorized_keys
|
mb@63
|
364 |
Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"')
|
mb@63
|
365 |
# generate iso image with .ssh/authorized keys
|
mb@63
|
366 |
Cygwin.bashExecute('\"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"')
|
mb@63
|
367 |
|
mb@63
|
368 |
# attaches generated ssh public cert to guest vm
|
mb@63
|
369 |
def attachCertificateISO(self, vm_name):
|
mb@63
|
370 |
result = Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"')
|
mb@63
|
371 |
return result
|
mb@63
|
372 |
|
mb@78
|
373 |
|
mb@63
|
374 |
handleDeviceChangeLock = threading.Lock()
|
mb@78
|
375 |
trigger = False
|
mb@63
|
376 |
# handles device change events
|
mb@63
|
377 |
def handleDeviceChange(self):
|
mb@63
|
378 |
if VMManager.handleDeviceChangeLock.acquire(True):
|
mb@78
|
379 |
#logger.debug("triggered")
|
mb@78
|
380 |
#VMManager.handleDeviceChangeLock.release()
|
mb@78
|
381 |
#return
|
mb@63
|
382 |
#destroy unused vms
|
mb@78
|
383 |
#diff = DictDiffer(self.connectedRSDs, tmp_conn)
|
mb@78
|
384 |
retry = 0
|
mb@78
|
385 |
while retry < 30:
|
mb@78
|
386 |
if self.getConnectedRSDS().keys() == self.connectedRSDs.keys():
|
mb@78
|
387 |
logger.info("Nothing's changed. Waiting for VBox USB sub-system to update...")
|
mb@78
|
388 |
else:
|
mb@78
|
389 |
self.connectedRSDs = self.getConnectedRSDS()
|
mb@78
|
390 |
break
|
mb@78
|
391 |
time.sleep(1)
|
mb@78
|
392 |
retry+=1
|
mb@78
|
393 |
|
mb@78
|
394 |
if retry == 30:
|
mb@78
|
395 |
VMManager.handleDeviceChangeLock.release()
|
mb@78
|
396 |
return None
|
mb@78
|
397 |
|
mb@78
|
398 |
logger.info("Something's changed")
|
mb@78
|
399 |
|
mb@78
|
400 |
self.attachedRSDs = self.getAttachedRSDs()
|
mb@78
|
401 |
|
mb@78
|
402 |
for vm_name in self.attachedRSDs.keys():
|
mb@78
|
403 |
if self.attachedRSDs[vm_name] not in self.connectedRSDs.values():
|
mb@63
|
404 |
self.unmapNetworkDrive('h:')
|
mb@63
|
405 |
#self.stopVM(vm_name)
|
mb@63
|
406 |
self.detachRSD(vm_name)
|
mb@63
|
407 |
self.poweroffVM(vm_name)
|
mb@63
|
408 |
self.removeVM(vm_name)
|
mb@63
|
409 |
#create new vm for attached device if any
|
mb@78
|
410 |
self.attachedRSDs = self.getAttachedRSDs()
|
mb@78
|
411 |
self.connectedRSDs = self.getConnectedRSDS()
|
mb@78
|
412 |
|
mb@78
|
413 |
new_ip = None
|
mb@78
|
414 |
for connected_device in self.connectedRSDs.values():
|
mb@78
|
415 |
if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
|
mb@63
|
416 |
new_sdvm = self.generateSDVMName()
|
mb@63
|
417 |
self.createVM(new_sdvm)
|
mb@63
|
418 |
self.storageAttach(new_sdvm)
|
mb@63
|
419 |
self.attachRSD(new_sdvm, connected_device)
|
mb@63
|
420 |
self.startVM(new_sdvm)
|
mb@63
|
421 |
new_ip = self.waitStartup(new_sdvm)
|
mb@78
|
422 |
|
mb@63
|
423 |
if new_ip != None:
|
mb@63
|
424 |
self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
|
mb@63
|
425 |
#TODO: cleanup notifications somwhere else (eg. machine shutdown)
|
mb@63
|
426 |
self.startNotifications.remove(new_ip)
|
mb@63
|
427 |
VMManager.handleDeviceChangeLock.release()
|
mb@63
|
428 |
return new_ip
|
mb@63
|
429 |
|
mb@63
|
430 |
# wait for machine to come up
|
mb@63
|
431 |
def waitStartup(self, vm_name):
|
mb@63
|
432 |
new_ip = None
|
mb@63
|
433 |
while new_ip == None:
|
mb@63
|
434 |
time.sleep(1)
|
mb@63
|
435 |
new_ip = VMManager.getHostOnlyIP(vm_name)
|
mb@63
|
436 |
while new_ip not in self.startNotifications:
|
mb@63
|
437 |
time.sleep(1)
|
mb@63
|
438 |
return new_ip
|
mb@63
|
439 |
|
mb@63
|
440 |
# wait for machine to shutdown
|
mb@63
|
441 |
def waitShutdown(self, vm_name):
|
mb@63
|
442 |
while vm_name in self.listRunningVMS():
|
mb@63
|
443 |
time.sleep(1)
|
mb@63
|
444 |
return
|
mb@63
|
445 |
|
mb@63
|
446 |
# handles browsing request
|
mb@63
|
447 |
def handleBrowsingRequest(self):
|
mb@63
|
448 |
if VMManager.handleDeviceChangeLock.acquire(True):
|
mb@63
|
449 |
new_sdvm = self.generateSDVMName()
|
mb@63
|
450 |
self.createVM(new_sdvm)
|
mb@63
|
451 |
self.storageAttach(new_sdvm)
|
mb@63
|
452 |
self.genCertificateISO(new_sdvm)
|
mb@63
|
453 |
self.attachCertificateISO(new_sdvm)
|
mb@63
|
454 |
self.startVM(new_sdvm)
|
mb@63
|
455 |
new_ip = self.waitStartup(new_sdvm)
|
mb@63
|
456 |
if new_ip != None:
|
mb@63
|
457 |
self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
|
mb@63
|
458 |
#TODO: cleanup notifications somwhere else (eg. machine shutdown)
|
mb@63
|
459 |
self.startNotifications.remove(new_ip)
|
mb@63
|
460 |
VMManager.handleDeviceChangeLock.release()
|
mb@63
|
461 |
return new_sdvm
|
mb@63
|
462 |
|
mb@63
|
463 |
#Small function to check the availability of network resource.
|
mb@78
|
464 |
#def isAvailable(self, path):
|
mb@78
|
465 |
#return os.path.exists(path)
|
mb@78
|
466 |
#result = Cygwin.cmdExecute('IF EXIST "' + path + '" echo YES')
|
mb@78
|
467 |
#return string.find(result[1], 'YES',)
|
mb@63
|
468 |
|
mb@63
|
469 |
#Small function to check if the mention location is a directory
|
mb@63
|
470 |
def isDirectory(self, path):
|
mb@63
|
471 |
result = Cygwin.cmdExecute('dir ' + path + ' | FIND ".."')
|
mb@63
|
472 |
return string.find(result[1], 'DIR',)
|
mb@63
|
473 |
|
mb@63
|
474 |
def mapNetworkDrive(self, drive, networkPath, user, password):
|
mb@63
|
475 |
self.unmapNetworkDrive(drive)
|
mb@63
|
476 |
#Check for drive availability
|
mb@78
|
477 |
if os.path.exists(drive):
|
mb@63
|
478 |
logger.error("Drive letter is already in use: " + drive)
|
mb@63
|
479 |
return -1
|
mb@63
|
480 |
#Check for network resource availability
|
mb@78
|
481 |
while not os.path.exists(networkPath):
|
mb@63
|
482 |
time.sleep(1)
|
mb@63
|
483 |
logger.info("Path not accessible: " + networkPath + " retrying")
|
mb@63
|
484 |
#return -1
|
mb@63
|
485 |
|
mb@63
|
486 |
command = 'USE ' + drive + ' ' + networkPath
|
mb@63
|
487 |
if user != None:
|
mb@63
|
488 |
command += ' ' + password + ' /User' + user
|
mb@63
|
489 |
|
mb@63
|
490 |
#TODO: Execute 'NET USE' command with authentication
|
mb@63
|
491 |
result = Cygwin.execute('C:\\Windows\\system32\\net.exe', command)
|
mb@63
|
492 |
if string.find(result[1], 'successfully',) == -1:
|
mb@63
|
493 |
logger.error("Failed: NET " + command)
|
mb@63
|
494 |
return -1
|
mb@63
|
495 |
return 1
|
mb@63
|
496 |
|
mb@63
|
497 |
def unmapNetworkDrive(self, drive):
|
mb@78
|
498 |
if not os.path.exists(drive):
|
mb@63
|
499 |
return -1
|
mb@63
|
500 |
result = Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE ' + drive + ' /DELETE /YES')
|
mb@63
|
501 |
if string.find(str(result), 'successfully',) == -1:
|
mb@78
|
502 |
logger.error(result[2])
|
mb@63
|
503 |
return -1
|
mb@63
|
504 |
return 1
|
mb@63
|
505 |
|
mb@78
|
506 |
class DeviceHandler(threading.Thread):
|
mb@78
|
507 |
vmm = None
|
mb@78
|
508 |
triggered = False
|
mb@78
|
509 |
def __init__(self, zahl):
|
mb@78
|
510 |
threading.Thread.__init__(self)
|
mb@78
|
511 |
self.vmm = None
|
mb@78
|
512 |
|
mb@78
|
513 |
def run(self):
|
mb@78
|
514 |
while True:
|
mb@78
|
515 |
if self.triggered:
|
mb@78
|
516 |
logger.debug("triggered")
|
mb@78
|
517 |
triggered = False
|
mb@78
|
518 |
else:
|
mb@78
|
519 |
time.sleep(1)
|
mb@78
|
520 |
|
mb@63
|
521 |
|
mb@63
|
522 |
if __name__ == '__main__':
|
mb@63
|
523 |
man = VMManager.getInstance()
|
mb@63
|
524 |
#man.listVM()
|
mb@78
|
525 |
print man.getConnectedRSDs()
|
mb@63
|
526 |
|
mb@63
|
527 |
#man.listVM()
|
mb@63
|
528 |
#man.listVM()
|
mb@63
|
529 |
#man.listVM()
|
mb@63
|
530 |
#man.listVM()
|
mb@63
|
531 |
#man.genCertificateISO('SecurityDVM0')
|
mb@63
|
532 |
#man.guestExecute('SecurityDVM0', '/bin/ls -la')
|
mb@63
|
533 |
#logger = setupLogger('VMManager')
|
mb@63
|
534 |
c = Cygwin()
|
mb@63
|
535 |
|
mb@63
|
536 |
#man.sshExecute('/bin/ls -la', 'SecurityDVM0')
|
mb@63
|
537 |
#man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
|
mb@63
|
538 |
#man.removeVM('SecurityDVM0')
|
mb@63
|
539 |
#man.netUse('192.168.56.134', 'USB\\')
|
mb@63
|
540 |
#ip = '192.168.56.139'
|
mb@63
|
541 |
|
mb@63
|
542 |
#man.cygwin_path = 'c:\\cygwin64\\bin\\'
|
mb@63
|
543 |
#man.handleDeviceChange()
|
mb@63
|
544 |
#print man.listSDVM()
|
mb@63
|
545 |
#man.configureHostNetworking()
|
mb@63
|
546 |
#new_vm = man.generateSDVMName()
|
mb@63
|
547 |
#man.createVM(new_vm)
|
mb@63
|
548 |
|
mb@63
|
549 |
#print Cygwin.cmd()
|
mb@63
|
550 |
#man.isAvailable('c:')
|
mb@63
|
551 |
#ip = man.getHostOnlyIP('SecurityDVM0')
|
mb@63
|
552 |
#man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
|
mb@63
|
553 |
|
mb@63
|
554 |
#man.genCertificateISO(new_vm)
|
mb@63
|
555 |
#man.attachCertificateISO(new_vm)
|
mb@63
|
556 |
|
mb@63
|
557 |
#man.attachCertificateISO(vm_name)
|
mb@63
|
558 |
#man.guestExecute(vm_name, "ls")
|
mb@63
|
559 |
#man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
|
mb@63
|
560 |
#time.sleep(60)
|
mb@63
|
561 |
#print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
|
mb@63
|
562 |
#man.genCertificateISO('SecurityDVM')
|
mb@63
|
563 |
#man.attachCertificateISO('SecurityDVM')
|
mb@63
|
564 |
#man.isStorageAttached('SecurityDVM')
|
mb@63
|
565 |
#man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
|
mb@63
|
566 |
#man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
|
mb@63
|
567 |
|
mb@63
|
568 |
#man.stopVM('SecurityDVM')
|
mb@63
|
569 |
#man.storageDetach('SecurityDVM')
|
mb@63
|
570 |
#man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
|
mb@63
|
571 |
#man.storageAttach('SecurityDVM')
|
mb@63
|
572 |
|
mb@63
|
573 |
|
mb@63
|
574 |
#cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
|
mb@63
|
575 |
#man.execute(cmd)
|
mb@63
|
576 |
|