Addded http proxy server support.
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)
105 if 'ProxyServer' in args:
106 proxy = args['ProxyServer']
107 result = gvm_mgr.handleBrowsingRequest(proxy)
110 raise web.internalerror()
113 class os_fetch_image:
114 """OpenSecurity '/fetch_initial_image' handler
116 - GET: fetch the initial image from the X-Net Servers
117 The initial image is stored in the
118 Virtual Box default machine path.
119 The result to this call is a temprary file
120 which shows the progress (or error state)
126 log_call(web.ctx.environ)
129 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_fetch_image.log')
130 trace_file = open(trace_file_name, 'w+')
132 machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder())
133 download_initial_image_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'download_initial_image.sh')))
134 Cygwin.bashExecute('\\"' + download_initial_image_script + '\\" \'' + machine_folder + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
136 res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
141 """OpenSecurity '/init' handler
143 - GET: Do initial import of OsecVM.ova
147 log_call(web.ctx.environ)
153 if gvm_mgr.vmRootName in gvm_mgr.listVM():
154 gvm_mgr.poweroffVM(gvm_mgr.vmRootName)
155 tmplateUUID = gvm_mgr.getTemplateUUID()
156 if tmplateUUID != None:
157 logger.debug('found parent uuid ' + tmplateUUID)
158 gvm_mgr.storageDetach(gvm_mgr.vmRootName)
159 gvm_mgr.removeSnapshots(tmplateUUID)
160 gvm_mgr.removeImage(tmplateUUID)
162 logger.debug('parent uuid not found')
163 gvm_mgr.removeVM(gvm_mgr.vmRootName)
165 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_initial_import.log')
166 trace_file = open(trace_file_name, 'w+')
168 vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
169 initial_import_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'initial_vm.sh')))
170 Cygwin.bashExecute('\\"' + initial_import_script + '\\" \'' + vm_image + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
172 res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
176 class os_initial_image:
177 """OpenSecurity '/initial_image' handler
179 - GET: Return what we have as initial image.
183 log_call(web.ctx.environ)
185 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
187 if os.path.isfile(t):
188 res = '{"initial_template": { '
189 res += '"name": "OsecVM.ova", '
190 res += '"path": "' + t.replace('\\', '\\\\') + '", '
191 res += '"size": ' + str(os.path.getsize(t)) + ', '
192 res += '"date": ' + str(os.path.getmtime(t)) + ''
198 """OpenSecurity '/' handler
200 - GET: give information about current installation.
204 log_call(web.ctx.environ)
207 # create a json string and pretty print it
208 res = '{"os_server": { '
209 res += '"version": "' + opensecurity.__version__ + '" '
210 res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"')
211 res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
212 res += ', "current log folder": "' + Environment('OpenSecurity').log_path.replace('\\', '\\\\') + '"'
215 res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
217 res += ', "whoami": "FAILED"'
220 res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
222 res += ', "mount": "FAILED"'
225 res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
227 res += ', "cygpath --windows ~": "FAILED"'
230 res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
234 # loading it into json and print it again ensures
235 # we really do have a valid RFC conform json string
236 # created (as long as the python json module is RFC conform)
237 return json.dumps(json.loads(res), indent = 4)
242 """OpenSecurity '/sdvms/[VM]' handler
244 - GET: Information about a specific SecurityVM
245 - DELETE: Remove a specific
249 log_call(web.ctx.environ)
251 return json.dumps(gvm_mgr.getVMInfo(name), indent = 4)
253 def DELETE(self, name):
254 log_call(web.ctx.environ)
256 return gvm_mgr.removeVM(name)
259 class os_sdvm_application:
260 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
262 - GET: start application with given command in the VM.
265 def GET(self, name, command):
266 log_call(web.ctx.environ)
268 command = '/' + command
269 showTrayMessage('Launching application in isolated VM...', 7000)
270 result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
271 return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
275 """OpenSecurity '/sdvms/[VM]/ip' handler
277 - GET: give IP of SecurityVM.
281 log_call(web.ctx.environ)
283 return gvm_mgr.getHostOnlyIP(name)
287 """OpenSecurity '/sdvms/[VM]/start' handler
289 - GET: Start specific SecuirtyVM.
293 log_call(web.ctx.environ)
295 return gvm_mgr.startVM(name)
299 """OpenSecurity '/sdvms/[VM]/stop' handler
301 - GET: stop specific Secuirty VM.
305 log_call(web.ctx.environ)
307 return gvm_mgr.stopVM(name)
311 """OpenSecurity '/sdvms' handler
313 - GET: list all available secuirty VMs.
314 - POST: create new security vm.
318 """get the list of SDVMs"""
319 log_call(web.ctx.environ)
323 for sdvm in gvm_mgr.listSDVM():
324 d[sdvm] = gvm_mgr.getHostOnlyIP(sdvm)
326 return json.dumps(d, indent = 4)
329 """create a new SDVM"""
330 log_call(web.ctx.environ)
334 name = gvm_mgr.generateSDVMName()
336 gvm_mgr.createVM(name)
338 raise web.internalerror()
344 """OpenSecurity '/setup' handler
346 - GET: Give user some info how to setup the OpenSecurity environment
351 log_call(web.ctx.environ)
356 <h1>Setup OpenSecurity</h1>
357 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
359 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
360 <li>Import initial VM: <a href="/init">init</a>
369 """OpenSecurity '/terminate' handler
371 - GET: terminate the opensecurityd.
373 TODO: need to find a better way doing this, and not via the
374 REST api. Maybe hack web.py server code?
378 log_call(web.ctx.environ)
387 """OpenSecurity '/initialize' handler
389 - GET: initialize / starts the vmmanager.
394 log_call(web.ctx.environ)
402 class os_update_template:
403 """OpenSecurity '/update_template' handler
405 - GET: update template vm
409 #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
411 log_call(web.ctx.environ)
412 return gvm_mgr.updateTemplate()
416 """OpenSecurity '/vms/[VM]' handler
418 - GET: list information of arbitrary VM.
422 log_call(web.ctx.environ)
424 return gvm_mgr.getVMInfo(name)
428 """OpenSecurity '/vms' handler
430 - GET: list all (also non Security) VMs.
434 log_call(web.ctx.environ)
436 return str(gvm_mgr.listVM()).replace("'",'"')
439 def log_call(web_environ):
440 """log the incoming call to the REST api"""
442 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
449 """main startup for the opensecuirityd"""
454 logger.debug('Starting OpenSecurity REST server')
456 # ensure a VMManger is yet loaded
457 gvm_mgr = vmmanager.VMManager.getInstance()
459 # tweak sys.argv to control wep.py server start behavior
460 sys.argv = [__file__, "8080"]
461 server = web.application(opensecurity_urls, globals(), autoreload = False)
464 logger.debug('Stopped OpenSecurity REST server')
468 """stop the opensecuirityd"""
470 # calling sys.exit() raises a SystemExit exception
471 # of the WSGI Server to let it wind down
476 if __name__ == "__main__":