Added WPAD proxy support.
Not fully tested
2 # -*- coding: utf-8 -*-
4 # ------------------------------------------------------------
7 # the opensecurityd as RESTful server
9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
10 # Mihai Bartha, <mihai.bartha@ait.ac.at>
12 # Copyright (C) 2013 AIT Austrian Institute of Technology
13 # AIT Austrian Institute of Technology GmbH
14 # Donau-City-Strasse 1 | 1220 Vienna | Austria
15 # http://www.ait.ac.at
17 # This program is free software; you can redistribute it and/or
18 # modify it under the terms of the GNU General Public License
19 # as published by the Free Software Foundation version 2.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor,
29 # Boston, MA 02110-1301, USA.
30 # ------------------------------------------------------------
33 # ------------------------------------------------------------
47 import __init__ as opensecurity
48 from cygwin import Cygwin
49 from environment import Environment
50 from opensecurity_util import logger, showTrayMessage
54 # ------------------------------------------------------------
57 """All the URLs we know mapping to class handler"""
59 '/browsing', 'os_browsing', # http://localhost:8080/browsing GET
60 '/fetch_initial_image', 'os_fetch_image', # http://localhost:8080/fetch_initial_image GET
61 '/init', 'os_init', # http://localhost:8080/init GET
62 '/initial_image', 'os_initial_image', # http://localhost:8080/initial_image GET
63 '/sdvms', 'os_sdvms', # http://localhost:8080/sdvms GET, PUT
64 '/sdvms/(.*)/application/(.*)', 'os_sdvm_application', # http://localhost:8080/sdvms/[VMNAME]/application/[COMMAND] GET
65 '/sdvms/(.*)/ip', 'os_sdvm_ip', # http://localhost:8080/sdvms/[VMNAME]/ip GET
66 '/sdvms/(.*)/start', 'os_sdvm_start', # http://localhost:8080/sdvms/[VMNAME]/start GET
67 '/sdvms/(.*)/stop', 'os_sdvm_stop', # http://localhost:8080/sdvms/[VMNAME]/stop GET
68 '/sdvms/(.*)', 'os_sdvm', # http://localhost:8080/sdvms/[VMNAME] GET, DELETE
69 '/setup', 'os_setup', # http://localhost:8080/setup GET
70 '/vms', 'os_vms', # http://localhost:8080/vms GET
71 '/vms/(.*)', 'os_vm', # http://localhost:8080/vms/[VMNAME] GET
72 '/update_template', 'os_update_template', # http://localhost:8080/update_template GET
73 '/terminate', 'os_terminate', # http://localhost:8080/terminate GET
74 '/initialize', 'os_initialize', # http://localhost:8080/initialize GET
75 '/', 'os_root' # http://localhost:8080/ GET
79 # ------------------------------------------------------------
82 # Global VMManager instance
89 # ------------------------------------------------------------
94 """OpenSecurity '/browsing' handler
96 - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
101 log_call(web.ctx.environ)
106 if 'ProxyServer' in args:
107 proxy = args['ProxyServer']
108 if 'ProxyAutoConfigURL' in args:
109 wpad = args['ProxyAutoConfigURL']
110 result = gvm_mgr.handleBrowsingRequest(proxy, wpad)
113 raise web.internalerror()
116 class os_fetch_image:
117 """OpenSecurity '/fetch_initial_image' handler
119 - GET: fetch the initial image from the X-Net Servers
120 The initial image is stored in the
121 Virtual Box default machine path.
122 The result to this call is a temprary file
123 which shows the progress (or error state)
129 log_call(web.ctx.environ)
132 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_fetch_image.log')
133 trace_file = open(trace_file_name, 'w+')
135 machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder())
136 download_initial_image_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'download_initial_image.sh')))
137 Cygwin.bashExecute('\\"' + download_initial_image_script + '\\" \'' + machine_folder + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
139 res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
144 """OpenSecurity '/init' handler
146 - GET: Do initial import of OsecVM.ova
151 log_call(web.ctx.environ)
153 gvm_mgr.startInitialImport()
154 res = '{ "init_log": "' + (Environment('OpenSecurity').log_path+'\\OpenSecurity_initial_import.log').replace('\\', '\\\\') + '" }'
157 class os_update_template:
158 """OpenSecurity '/update_template' handler
160 - GET: update template vm
165 log_call(web.ctx.environ)
167 gvm_mgr.startUpdateTemplate()
168 res = '{ "init_log": "' + (Environment('OpenSecurity').log_path+'\\OpenSecurity_initial_import.log').replace('\\', '\\\\') + '" }'
171 class os_initial_image:
172 """OpenSecurity '/initial_image' handler
174 - GET: Return what we have as initial image.
178 log_call(web.ctx.environ)
180 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
182 if os.path.isfile(t):
183 res = '{"initial_template": { '
184 res += '"name": "OsecVM.ova", '
185 res += '"path": "' + t.replace('\\', '\\\\') + '", '
186 res += '"size": ' + str(os.path.getsize(t)) + ', '
187 res += '"date": ' + str(os.path.getmtime(t)) + ''
192 """OpenSecurity '/' handler
194 - GET: give information about current installation.
198 log_call(web.ctx.environ)
201 # create a json string and pretty print it
202 res = '{"os_server": { '
203 res += '"version": "' + opensecurity.__version__ + '" '
204 res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"')
205 res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
206 res += ', "current log folder": "' + Environment('OpenSecurity').log_path.replace('\\', '\\\\') + '"'
209 res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
211 res += ', "whoami": "FAILED"'
214 res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
216 res += ', "mount": "FAILED"'
219 res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
221 res += ', "cygpath --windows ~": "FAILED"'
224 res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
228 # loading it into json and print it again ensures
229 # we really do have a valid RFC conform json string
230 # created (as long as the python json module is RFC conform)
231 return json.dumps(json.loads(res), indent = 4)
236 """OpenSecurity '/sdvms/[VM]' handler
238 - GET: Information about a specific SecurityVM
239 - DELETE: Remove a specific
243 log_call(web.ctx.environ)
245 return json.dumps(gvm_mgr.getVMInfo(name), indent = 4)
247 def DELETE(self, name):
248 log_call(web.ctx.environ)
250 return gvm_mgr.removeVM(name)
253 class os_sdvm_application:
254 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
256 - GET: start application with given command in the VM.
259 def GET(self, name, command):
260 log_call(web.ctx.environ)
262 command = '/' + command
263 showTrayMessage('Launching application in isolated VM...', 7000)
264 Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
265 return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
269 """OpenSecurity '/sdvms/[VM]/ip' handler
271 - GET: give IP of SecurityVM.
275 log_call(web.ctx.environ)
277 return gvm_mgr.getHostOnlyIP(name)
281 """OpenSecurity '/sdvms/[VM]/start' handler
283 - GET: Start specific SecuirtyVM.
287 log_call(web.ctx.environ)
289 return gvm_mgr.startVM(name)
293 """OpenSecurity '/sdvms/[VM]/stop' handler
295 - GET: stop specific Secuirty VM.
299 log_call(web.ctx.environ)
301 return gvm_mgr.stopVM(name)
305 """OpenSecurity '/sdvms' handler
307 - GET: list all available secuirty VMs.
308 - POST: create new security vm.
312 """get the list of SDVMs"""
313 log_call(web.ctx.environ)
317 for sdvm in gvm_mgr.listSDVM():
318 d[sdvm] = gvm_mgr.getHostOnlyIP(sdvm)
320 return json.dumps(d, indent = 4)
323 """create a new SDVM"""
324 log_call(web.ctx.environ)
328 name = gvm_mgr.generateSDVMName()
330 gvm_mgr.createVM(name)
332 raise web.internalerror()
338 """OpenSecurity '/setup' handler
340 - GET: Give user some info how to setup the OpenSecurity environment
345 log_call(web.ctx.environ)
350 <h1>Setup OpenSecurity</h1>
351 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
353 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
354 <li>Import initial VM: <a href="/init">init</a>
363 """OpenSecurity '/terminate' handler
365 - GET: terminate the opensecurityd.
367 TODO: need to find a better way doing this, and not via the
368 REST api. Maybe hack web.py server code?
372 log_call(web.ctx.environ)
381 """OpenSecurity '/initialize' handler
383 - GET: initialize / starts the vmmanager.
388 log_call(web.ctx.environ)
397 """OpenSecurity '/vms/[VM]' handler
399 - GET: list information of arbitrary VM.
403 log_call(web.ctx.environ)
405 return gvm_mgr.getVMInfo(name)
409 """OpenSecurity '/vms' handler
411 - GET: list all (also non Security) VMs.
415 log_call(web.ctx.environ)
417 return str(gvm_mgr.listVM()).replace("'",'"')
420 def log_call(web_environ):
421 """log the incoming call to the REST api"""
423 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
430 """main startup for the opensecuirityd"""
435 logger.debug('Starting OpenSecurity REST server')
437 # ensure a VMManger is yet loaded
438 gvm_mgr = vmmanager.VMManager.getInstance()
440 # tweak sys.argv to control wep.py server start behavior
441 sys.argv = [__file__, "8080"]
442 server = web.application(opensecurity_urls, globals(), autoreload = False)
445 logger.debug('Stopped OpenSecurity REST server')
449 """stop the opensecuirityd"""
451 # calling sys.exit() raises a SystemExit exception
452 # of the WSGI Server to let it wind down
457 if __name__ == "__main__":