mb@7
|
1 |
'''
|
mb@7
|
2 |
Created on Nov 19, 2013
|
mb@7
|
3 |
|
mb@7
|
4 |
@author: BarthaM
|
mb@7
|
5 |
'''
|
mb@7
|
6 |
import os
|
mb@7
|
7 |
import os.path
|
mb@7
|
8 |
from subprocess import Popen, PIPE, call
|
mb@7
|
9 |
import subprocess
|
mb@7
|
10 |
import sys
|
mb@7
|
11 |
import re
|
om@19
|
12 |
import _winreg
|
om@18
|
13 |
from cygwin import Cygwin
|
mb@36
|
14 |
import threading
|
mb@40
|
15 |
import time
|
mb@40
|
16 |
import string
|
mb@7
|
17 |
|
om@19
|
18 |
|
om@42
|
19 |
DEBUG = True
|
mb@7
|
20 |
|
mb@7
|
21 |
class USBFilter:
|
mb@7
|
22 |
vendorid = ""
|
mb@7
|
23 |
productid = ""
|
mb@7
|
24 |
revision = ""
|
mb@7
|
25 |
|
mb@7
|
26 |
def __init__(self, vendorid, productid, revision):
|
mb@7
|
27 |
self.vendorid = vendorid.lower()
|
mb@7
|
28 |
self.productid = productid.lower()
|
mb@7
|
29 |
self.revision = revision.lower()
|
mb@7
|
30 |
return
|
mb@7
|
31 |
|
mb@7
|
32 |
def __eq__(self, other):
|
mb@7
|
33 |
return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
|
mb@7
|
34 |
|
mb@7
|
35 |
def __hash__(self):
|
mb@7
|
36 |
return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
|
mb@7
|
37 |
|
mb@7
|
38 |
def __repr__(self):
|
mb@7
|
39 |
return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
|
mb@7
|
40 |
|
mb@7
|
41 |
|
mb@7
|
42 |
class VMManager(object):
|
mb@7
|
43 |
vmRootName = "SecurityDVM"
|
mb@7
|
44 |
systemProperties = None
|
mb@7
|
45 |
cygwin_path = 'c:\\cygwin64\\bin\\'
|
om@19
|
46 |
vboxManage = 'VBoxManage'
|
mb@34
|
47 |
startNotifications = list()
|
mb@34
|
48 |
|
mb@34
|
49 |
_instance = None
|
mb@34
|
50 |
#def __new__(cls, *args, **kwargs):
|
mb@34
|
51 |
# if not cls._instance:
|
mb@34
|
52 |
# cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
|
mb@34
|
53 |
# return cls._instance
|
mb@7
|
54 |
|
mb@33
|
55 |
_instance = None
|
mb@33
|
56 |
#def __new__(cls, *args, **kwargs):
|
mb@33
|
57 |
# if not cls._instance:
|
mb@33
|
58 |
# cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
|
mb@33
|
59 |
# return cls._instance
|
mb@33
|
60 |
|
mb@7
|
61 |
def __init__(self):
|
om@31
|
62 |
self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
|
om@22
|
63 |
self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
|
mb@7
|
64 |
self.systemProperties = self.getSystemProperties()
|
mb@7
|
65 |
return
|
mb@33
|
66 |
|
mb@33
|
67 |
@staticmethod
|
mb@33
|
68 |
def getInstance():
|
mb@33
|
69 |
if VMManager._instance == None:
|
mb@33
|
70 |
VMManager._instance = VMManager()
|
mb@33
|
71 |
return VMManager._instance
|
mb@34
|
72 |
|
mb@34
|
73 |
def putStartNotification(self, ip):
|
mb@34
|
74 |
self.startNotifications.append(ip)
|
mb@34
|
75 |
|
mb@34
|
76 |
def isSDVMStarted(self, ip):
|
mb@34
|
77 |
return self.startNotifications.contains(ip)
|
mb@33
|
78 |
|
mb@7
|
79 |
def execute(self, cmd):
|
mb@7
|
80 |
if DEBUG:
|
mb@7
|
81 |
print('trying to launch: ' + cmd)
|
mb@40
|
82 |
process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
|
mb@7
|
83 |
if DEBUG:
|
mb@7
|
84 |
print('launched: ' + cmd)
|
mb@7
|
85 |
result = process.wait()
|
mb@7
|
86 |
res_stdout = process.stdout.read();
|
mb@7
|
87 |
res_stderr = process.stderr.read();
|
mb@7
|
88 |
if DEBUG:
|
mb@7
|
89 |
if res_stdout != "":
|
mb@7
|
90 |
print res_stdout
|
mb@7
|
91 |
if res_stderr != "":
|
mb@7
|
92 |
print res_stderr
|
mb@7
|
93 |
return result, res_stdout, res_stderr
|
mb@7
|
94 |
|
om@19
|
95 |
def getVBoxManagePath(self):
|
om@19
|
96 |
"""get the path to the VirtualBox installation on this system"""
|
om@19
|
97 |
p = None
|
om@19
|
98 |
try:
|
om@19
|
99 |
k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
|
om@19
|
100 |
p = _winreg.QueryValueEx(k, 'InstallDir')[0]
|
om@19
|
101 |
_winreg.CloseKey(k)
|
om@19
|
102 |
except:
|
om@19
|
103 |
pass
|
om@19
|
104 |
return p
|
om@19
|
105 |
|
BarthaM@8
|
106 |
# return hosty system properties
|
mb@7
|
107 |
def getSystemProperties(self):
|
om@22
|
108 |
cmd = self.vboxManage + ' list systemproperties'
|
mb@7
|
109 |
result = self.execute(cmd)
|
mb@7
|
110 |
if result[1]=='':
|
mb@7
|
111 |
return None
|
mb@7
|
112 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
|
mb@7
|
113 |
return props
|
BarthaM@8
|
114 |
|
BarthaM@8
|
115 |
# return the folder containing the guest VMs
|
mb@7
|
116 |
def getDefaultMachineFolder(self):
|
mb@7
|
117 |
return self.systemProperties["Default machine folder"]
|
mb@7
|
118 |
|
BarthaM@8
|
119 |
#list the hostonly IFs exposed by the VBox host
|
mb@7
|
120 |
def getHostOnlyIFs(self):
|
mb@11
|
121 |
cmd = 'VBoxManage list hostonlyifs'
|
mb@11
|
122 |
result = self.execute(cmd)[1]
|
mb@7
|
123 |
if result=='':
|
mb@7
|
124 |
return None
|
mb@7
|
125 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
|
mb@7
|
126 |
return props
|
mb@7
|
127 |
|
mb@7
|
128 |
def listRSDS(self):
|
mb@7
|
129 |
cmd = 'VBoxManage list usbhost'
|
mb@12
|
130 |
results = self.execute(cmd)[1]
|
mb@7
|
131 |
results = results.split('Host USB Devices:')[1].strip()
|
mb@7
|
132 |
|
mb@7
|
133 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@7
|
134 |
rsds = dict()
|
mb@7
|
135 |
for item in items:
|
mb@7
|
136 |
props = dict()
|
mb@7
|
137 |
for line in item.splitlines():
|
mb@7
|
138 |
if line != "":
|
mb@7
|
139 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@7
|
140 |
props[k] = v;
|
mb@7
|
141 |
|
mb@7
|
142 |
if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
|
mb@7
|
143 |
usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
|
mb@7
|
144 |
re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
|
mb@7
|
145 |
re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
|
mb@7
|
146 |
rsds[props['UUID']] = usb_filter;
|
mb@7
|
147 |
if DEBUG:
|
mb@33
|
148 |
print usb_filter
|
mb@7
|
149 |
return rsds
|
mb@7
|
150 |
|
BarthaM@8
|
151 |
# list all existing VMs registered with VBox
|
mb@7
|
152 |
def listVM(self):
|
mb@7
|
153 |
cmd = 'VBoxManage list vms'
|
mb@11
|
154 |
result = self.execute(cmd)[1]
|
mb@7
|
155 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@7
|
156 |
return vms
|
mb@7
|
157 |
|
BarthaM@8
|
158 |
# list existing SDVMs
|
mb@7
|
159 |
def listSDVM(self):
|
mb@7
|
160 |
vms = self.listVM()
|
mb@7
|
161 |
svdms = []
|
mb@7
|
162 |
for vm in vms:
|
mb@7
|
163 |
if vm.startswith(self.vmRootName) and vm != self.vmRootName:
|
mb@7
|
164 |
svdms.append(vm)
|
mb@7
|
165 |
return svdms
|
mb@7
|
166 |
|
BarthaM@8
|
167 |
# generate valid (not already existing SDVM name). necessary for creating a new VM
|
mb@7
|
168 |
def generateSDVMName(self):
|
mb@7
|
169 |
vms = self.listVM()
|
mb@7
|
170 |
for i in range(0,999):
|
mb@7
|
171 |
if(not self.vmRootName+str(i) in vms):
|
mb@7
|
172 |
return self.vmRootName+str(i)
|
mb@7
|
173 |
return ''
|
mb@7
|
174 |
|
BarthaM@8
|
175 |
# return the RSDs attached to all existing SDVMs
|
BarthaM@8
|
176 |
def getAttachedRSDs(self):
|
BarthaM@8
|
177 |
vms = self.listSDVM()
|
BarthaM@8
|
178 |
attached_devices = dict()
|
BarthaM@8
|
179 |
for vm in vms:
|
BarthaM@8
|
180 |
rsd_filter = self.getUSBFilter(vm)
|
mb@12
|
181 |
if rsd_filter != None:
|
BarthaM@8
|
182 |
attached_devices[vm] = rsd_filter
|
BarthaM@8
|
183 |
return attached_devices
|
BarthaM@8
|
184 |
|
BarthaM@8
|
185 |
# configures hostonly networking and DHCP server. requires admin rights
|
BarthaM@8
|
186 |
def configureHostNetworking(self):
|
BarthaM@8
|
187 |
#cmd = 'vboxmanage list hostonlyifs'
|
BarthaM@8
|
188 |
#self.execute(cmd)
|
BarthaM@8
|
189 |
#cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
|
BarthaM@8
|
190 |
#self.execute(cmd)
|
BarthaM@8
|
191 |
#cmd = 'vboxmanage hostonlyif create'
|
BarthaM@8
|
192 |
#self.execute(cmd)
|
mb@33
|
193 |
cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
|
BarthaM@8
|
194 |
self.execute(cmd)
|
BarthaM@8
|
195 |
#cmd = 'vboxmanage dhcpserver add'
|
BarthaM@8
|
196 |
#self.execute(cmd)
|
mb@33
|
197 |
cmd = 'VBoxManage 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'
|
BarthaM@8
|
198 |
self.execute(cmd)
|
BarthaM@8
|
199 |
|
mb@11
|
200 |
#create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
|
BarthaM@8
|
201 |
def createVM(self, vm_name):
|
BarthaM@8
|
202 |
hostonly_if = self.getHostOnlyIFs()
|
BarthaM@8
|
203 |
machineFolder = self.getDefaultMachineFolder()
|
mb@11
|
204 |
cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
|
BarthaM@8
|
205 |
self.execute(cmd)
|
mb@11
|
206 |
cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
|
BarthaM@8
|
207 |
self.execute(cmd)
|
mb@11
|
208 |
cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
|
BarthaM@8
|
209 |
self.execute(cmd)
|
mb@12
|
210 |
cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
|
mb@12
|
211 |
#--mtype immutable
|
BarthaM@8
|
212 |
self.execute(cmd)
|
BarthaM@8
|
213 |
return
|
BarthaM@8
|
214 |
|
BarthaM@8
|
215 |
#remove VM from the system. should be used on VMs returned by listSDVMs
|
BarthaM@8
|
216 |
def removeVM(self, vm_name):
|
BarthaM@8
|
217 |
print('removing ' + vm_name)
|
mb@36
|
218 |
cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
|
BarthaM@8
|
219 |
print self.execute(cmd)
|
BarthaM@8
|
220 |
machineFolder = self.getDefaultMachineFolder()
|
mb@36
|
221 |
cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
|
BarthaM@8
|
222 |
print self.execute(cmd)
|
BarthaM@8
|
223 |
|
BarthaM@8
|
224 |
# start VM
|
BarthaM@8
|
225 |
def startVM(self, vm_name):
|
BarthaM@8
|
226 |
print('starting ' + vm_name)
|
mb@40
|
227 |
cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
|
mb@40
|
228 |
print self.execute(cmd) #verify against (0, 'Waiting for VM "SecurityDVM0" to power on...\r\nVM "SecurityDVM0" has been successfully started.\r\n', '')
|
BarthaM@8
|
229 |
|
BarthaM@8
|
230 |
# stop VM
|
BarthaM@8
|
231 |
def stopVM(self, vm_name):
|
BarthaM@8
|
232 |
print('stopping ' + vm_name)
|
BarthaM@8
|
233 |
cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
|
BarthaM@8
|
234 |
print self.execute(cmd)
|
BarthaM@8
|
235 |
|
BarthaM@8
|
236 |
# return the hostOnly IP for a running guest
|
BarthaM@8
|
237 |
def getHostOnlyIP(self, vm_name):
|
BarthaM@8
|
238 |
print('gettting hostOnly IP address ' + vm_name)
|
BarthaM@8
|
239 |
cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
|
BarthaM@8
|
240 |
result = self.execute(cmd)
|
BarthaM@8
|
241 |
if result=='':
|
BarthaM@8
|
242 |
return None
|
BarthaM@8
|
243 |
result = result[1]
|
mb@40
|
244 |
if result.startswith('No value set!'):
|
mb@40
|
245 |
return None
|
BarthaM@8
|
246 |
return result[result.index(':')+1:].strip()
|
BarthaM@8
|
247 |
|
BarthaM@8
|
248 |
# attach removable storage device to VM by provision of filter
|
BarthaM@8
|
249 |
def attachRSD(self, vm_name, rsd_filter):
|
BarthaM@8
|
250 |
cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
|
BarthaM@8
|
251 |
print self.execute(cmd)
|
BarthaM@8
|
252 |
|
BarthaM@8
|
253 |
|
BarthaM@8
|
254 |
# return the description set for an existing VM
|
mb@7
|
255 |
def getVMInfo(self, vm_name):
|
mb@7
|
256 |
cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
|
mb@12
|
257 |
results = self.execute(cmd)[1]
|
mb@7
|
258 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
|
mb@7
|
259 |
return props
|
mb@7
|
260 |
|
BarthaM@8
|
261 |
# return the configured USB filter for an existing VM
|
mb@7
|
262 |
def getUSBFilter(self, vm_name):
|
mb@7
|
263 |
props = self.getVMInfo(vm_name)
|
mb@7
|
264 |
keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
|
mb@7
|
265 |
keyset = set(props.keys())
|
mb@7
|
266 |
usb_filter = None
|
mb@7
|
267 |
if keyset.issuperset(keys):
|
mb@7
|
268 |
usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
|
mb@7
|
269 |
return usb_filter
|
mb@7
|
270 |
|
mb@7
|
271 |
#generates ISO containing authorized_keys for use with guest VM
|
mb@7
|
272 |
def genCertificateISO(self, vm_name):
|
mb@7
|
273 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
274 |
# create .ssh folder in vm_name
|
mb@7
|
275 |
cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
|
mb@7
|
276 |
result = self.execute(cmd)
|
mb@7
|
277 |
# generate dvm_key pair in vm_name / .ssh
|
mb@7
|
278 |
cmd = self.cygwin_path+'bash.exe --login -c \"ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\"\"' #'echo -e "y\\n" |',
|
mb@7
|
279 |
result = self.execute(cmd)
|
mb@7
|
280 |
# set permissions for keys
|
mb@7
|
281 |
#TODO: test without chmod
|
mb@7
|
282 |
cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
|
mb@7
|
283 |
result = self.execute(cmd)
|
mb@7
|
284 |
# move out private key
|
mb@7
|
285 |
cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
|
mb@7
|
286 |
result = self.execute(cmd)
|
mb@7
|
287 |
# rename public key to authorized_keys
|
mb@7
|
288 |
cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
|
mb@7
|
289 |
result = self.execute(cmd)
|
mb@7
|
290 |
# generate iso image with .ssh/authorized keys
|
mb@7
|
291 |
cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
|
mb@7
|
292 |
result = self.execute(cmd)
|
mb@7
|
293 |
|
mb@7
|
294 |
# attaches generated ssh public cert to guest vm
|
mb@7
|
295 |
def attachCertificateISO(self, vm_name):
|
mb@7
|
296 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
297 |
cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
|
mb@7
|
298 |
result = self.execute(cmd)
|
mb@7
|
299 |
return result
|
mb@7
|
300 |
|
mb@36
|
301 |
handleDeviceChangeLock = threading.Lock()
|
mb@36
|
302 |
|
mb@7
|
303 |
# handles device change events
|
mb@7
|
304 |
def handleDeviceChange(self):
|
mb@36
|
305 |
if VMManager.handleDeviceChangeLock.acquire(True):
|
mb@36
|
306 |
#destroy unused vms
|
mb@40
|
307 |
new_ip = None
|
mb@36
|
308 |
attached_devices = self.getAttachedRSDs()
|
mb@36
|
309 |
connected_devices = self.listRSDS()
|
mb@36
|
310 |
for vm_name in attached_devices.keys():
|
mb@36
|
311 |
if attached_devices[vm_name] not in connected_devices.values():
|
mb@40
|
312 |
self.unmapNetworkDrive('h:')
|
mb@36
|
313 |
self.stopVM(vm_name)
|
mb@36
|
314 |
self.removeVM(vm_name)
|
mb@36
|
315 |
#create new vm for attached device if any
|
mb@36
|
316 |
attached_devices = self.getAttachedRSDs()
|
mb@36
|
317 |
for connected_device in connected_devices.values():
|
mb@36
|
318 |
if (attached_devices and False) or (connected_device not in attached_devices.values()):
|
mb@36
|
319 |
new_sdvm = self.generateSDVMName()
|
mb@36
|
320 |
self.createVM(new_sdvm)
|
mb@36
|
321 |
self.attachRSD(new_sdvm, connected_device)
|
mb@40
|
322 |
#sleep like method
|
mb@40
|
323 |
self.listSDVM()
|
mb@36
|
324 |
self.startVM(new_sdvm)
|
mb@40
|
325 |
|
mb@40
|
326 |
while new_ip == None:
|
mb@40
|
327 |
time.sleep(1)
|
mb@40
|
328 |
new_ip = self.getHostOnlyIP(new_sdvm)
|
mb@40
|
329 |
while new_ip not in self.startNotifications:
|
mb@40
|
330 |
time.sleep(1)
|
mb@40
|
331 |
#TODO: cleanup notifications somwhere else (eg. machine shutdown)
|
mb@40
|
332 |
self.startNotifications.remove(new_ip)
|
mb@36
|
333 |
VMManager.handleDeviceChangeLock.release()
|
mb@40
|
334 |
return new_ip
|
mb@12
|
335 |
|
mb@12
|
336 |
def handleBrowsingRequest(self):
|
mb@12
|
337 |
new_sdvm = self.generateSDVMName()
|
mb@12
|
338 |
self.createVM(new_sdvm)
|
mb@12
|
339 |
self.genCertificateISO(new_sdvm)
|
mb@12
|
340 |
self.attachCertificateISO(new_sdvm)
|
om@31
|
341 |
return new_sdvm
|
mb@7
|
342 |
|
mb@7
|
343 |
# executes command over ssh on guest vm
|
BarthaM@8
|
344 |
def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
|
mb@7
|
345 |
# get vm ip
|
mb@7
|
346 |
address = self.getHostOnlyIP(vm_name)
|
mb@7
|
347 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
348 |
# run command
|
BarthaM@8
|
349 |
cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
|
mb@7
|
350 |
return self.execute(cmd)
|
mb@7
|
351 |
|
mb@7
|
352 |
# executes command over ssh on guest vm with X forwarding
|
BarthaM@8
|
353 |
def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
|
mb@7
|
354 |
#TODO: verify if X server is running on user account
|
mb@7
|
355 |
#TODO: set DISPLAY accordingly
|
mb@7
|
356 |
address = self.getHostOnlyIP(vm_name)
|
mb@7
|
357 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
358 |
# run command
|
BarthaM@8
|
359 |
cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
|
mb@7
|
360 |
return self.execute(cmd)
|
mb@7
|
361 |
|
mb@40
|
362 |
#Small function to check the availability of network resource.
|
mb@40
|
363 |
def isAvailable(self, path):
|
mb@40
|
364 |
cmd = 'IF EXIST ' + path + ' echo YES'
|
mb@40
|
365 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
366 |
return string.find(str(result), 'YES',)
|
mb@40
|
367 |
|
mb@40
|
368 |
#Small function to check if the mention location is a directory
|
mb@40
|
369 |
def isDirectory(self, path):
|
mb@40
|
370 |
cmd = 'dir ' + path + ' | FIND ".."'
|
mb@40
|
371 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
372 |
return string.find(str(result), 'DIR',)
|
mb@40
|
373 |
|
mb@40
|
374 |
def mapNetworkDrive(self, drive, networkPath, user, password):
|
mb@40
|
375 |
self.unmapNetworkDrive('h:')
|
mb@40
|
376 |
#Check for drive availability
|
mb@40
|
377 |
if self.isAvailable(drive) > -1:
|
mb@40
|
378 |
print "Drive letter is already in use: ", drive
|
mb@40
|
379 |
return -1
|
mb@40
|
380 |
#Check for network resource availability
|
mb@40
|
381 |
while self.isAvailable(networkPath) == -1:
|
mb@40
|
382 |
time.sleep(1)
|
mb@40
|
383 |
print "Path not accessible: ", networkPath, " retrying"
|
mb@40
|
384 |
#return -1
|
mb@40
|
385 |
|
mb@40
|
386 |
#Prepare 'NET USE' commands
|
mb@40
|
387 |
cmd = 'NET USE ' + drive + ' ' + networkPath
|
mb@40
|
388 |
if user != None:
|
mb@40
|
389 |
cmd = cmd + ' ' + password + ' /User' + user
|
mb@40
|
390 |
|
mb@40
|
391 |
print "cmd = ", cmd
|
mb@40
|
392 |
#Execute 'NET USE' command with authentication
|
mb@40
|
393 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
394 |
print "Executed: ", cmd
|
mb@40
|
395 |
if string.find(str(result), 'successfully',) == -1:
|
mb@40
|
396 |
print cmd, " FAILED"
|
mb@40
|
397 |
return -1
|
mb@40
|
398 |
#Mapped with first try
|
mb@40
|
399 |
return 1
|
mb@40
|
400 |
|
mb@40
|
401 |
def unmapNetworkDrive(self, drive):
|
mb@40
|
402 |
#Check if the drive is in use
|
mb@40
|
403 |
if self.isAvailable(drive) == -1:
|
mb@40
|
404 |
#Drive is not in use
|
mb@40
|
405 |
return -1
|
mb@40
|
406 |
#Prepare 'NET USE' command
|
mb@40
|
407 |
cmd = 'net use ' + drive + ' /DELETE'
|
mb@40
|
408 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
409 |
if string.find(str(result), 'successfully',) == -1:
|
mb@40
|
410 |
return -1
|
mb@40
|
411 |
return 1
|
mb@40
|
412 |
|
mb@40
|
413 |
if __name__ == '__main__':
|
mb@40
|
414 |
|
mb@40
|
415 |
man = VMManager.getInstance()
|
mb@40
|
416 |
#man.removeVM('SecurityDVM0')
|
mb@40
|
417 |
#man.netUse('192.168.56.134', 'USB\\')
|
mb@40
|
418 |
ip = '192.168.56.139'
|
mb@40
|
419 |
man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
|
mb@40
|
420 |
|
mb@33
|
421 |
#man.cygwin_path = 'c:\\cygwin64\\bin\\'
|
mb@7
|
422 |
#man.handleDeviceChange()
|
mb@7
|
423 |
#print man.listSDVM()
|
mb@11
|
424 |
#man.configureHostNetworking()
|
mb@33
|
425 |
#new_vm = man.generateSDVMName()
|
mb@33
|
426 |
#man.createVM(new_vm)
|
mb@33
|
427 |
#man.genCertificateISO(new_vm)
|
mb@33
|
428 |
#man.attachCertificateISO(new_vm)
|
mb@11
|
429 |
|
mb@7
|
430 |
#man.attachCertificateISO(vm_name)
|
mb@7
|
431 |
#man.sshGuestExecute(vm_name, "ls")
|
mb@7
|
432 |
#man.sshGuestX11Execute(vm_name, "iceweasel")
|
mb@7
|
433 |
#cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
|
mb@7
|
434 |
#man.execute(cmd)
|
mb@33
|
435 |
|