2 # -*- coding: utf-8 -*-
4 # ------------------------------------------------------------
7 # the opensecurityd as RESTful server
9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
11 # Copyright (C) 2013 AIT Austrian Institute of Technology
12 # AIT Austrian Institute of Technology GmbH
13 # Donau-City-Strasse 1 | 1220 Vienna | Austria
14 # http://www.ait.ac.at
16 # This program is free software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License
18 # as published by the Free Software Foundation version 2.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 # Boston, MA 02110-1301, USA.
29 # ------------------------------------------------------------
32 # ------------------------------------------------------------
46 import __init__ as opensecurity
47 from cygwin import Cygwin
48 from environment import Environment
49 from opensecurity_util import logger, showTrayMessage
53 # ------------------------------------------------------------
56 """All the URLs we know mapping to class handler"""
58 '/browsing', 'os_browsing', # http://localhost:8080/browsing GET
59 '/fetch_initial_image', 'os_fetch_image', # http://localhost:8080/fetch_initial_image GET
60 '/init', 'os_init', # http://localhost:8080/init GET
61 '/initial_image', 'os_initial_image', # http://localhost:8080/initial_image GET
62 '/sdvms', 'os_sdvms', # http://localhost:8080/sdvms GET, PUT
63 '/sdvms/(.*)/application/(.*)', 'os_sdvm_application', # http://localhost:8080/sdvms/[VMNAME]/application/[COMMAND] GET
64 '/sdvms/(.*)/ip', 'os_sdvm_ip', # http://localhost:8080/sdvms/[VMNAME]/ip GET
65 '/sdvms/(.*)/start', 'os_sdvm_start', # http://localhost:8080/sdvms/[VMNAME]/start GET
66 '/sdvms/(.*)/stop', 'os_sdvm_stop', # http://localhost:8080/sdvms/[VMNAME]/stop GET
67 '/sdvms/(.*)', 'os_sdvm', # http://localhost:8080/sdvms/[VMNAME] GET, DELETE
68 '/setup', 'os_setup', # http://localhost:8080/setup GET
69 '/vms', 'os_vms', # http://localhost:8080/vms GET
70 '/vms/(.*)', 'os_vm', # http://localhost:8080/vms/[VMNAME] GET
71 '/update_template', 'os_update_template', # http://localhost:8080/update_template GET
72 '/terminate', 'os_terminate', # http://localhost:8080/terminate GET
73 '/', 'os_root' # http://localhost:8080/ GET
77 # ------------------------------------------------------------
80 # Global VMManager instance
87 # ------------------------------------------------------------
92 """OpenSecurity '/browsing' handler
94 - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
98 log_call(web.ctx.environ)
101 result = gvm_mgr.handleBrowsingRequest()
104 raise web.internalerror()
107 class os_fetch_image:
108 """OpenSecurity '/fetch_initial_image' handler
110 - GET: fetch the initial image from the X-Net Servers
111 The initial image is stored in the
112 Virtual Box default machine path.
113 The result to this call is a temprary file
114 which shows the progress (or error state)
120 log_call(web.ctx.environ)
123 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_fetch_image.log')
124 trace_file = open(trace_file_name, 'w+')
126 machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder())
127 download_initial_image_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'download_initial_image.sh')))
128 Cygwin.bashExecute('\\"' + download_initial_image_script + '\\" \'' + machine_folder + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
130 res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
135 """OpenSecurity '/init' handler
137 - GET: Do initial import of OsecVM.ova
141 log_call(web.ctx.environ)
147 if gvm_mgr.vmRootName in gvm_mgr.listVM():
148 gvm_mgr.poweroffVM(gvm_mgr.vmRootName)
149 tmplateUUID = gvm_mgr.getTemplateUUID()
150 if tmplateUUID != None:
151 logger.debug('found parent uuid ' + tmplateUUID)
152 gvm_mgr.storageDetach(gvm_mgr.vmRootName)
153 gvm_mgr.removeSnapshots(tmplateUUID)
154 gvm_mgr.removeImage(tmplateUUID)
156 logger.debug('parent uuid not found')
157 gvm_mgr.removeVM(gvm_mgr.vmRootName)
159 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_initial_import.log')
160 trace_file = open(trace_file_name, 'w+')
162 vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
163 initial_import_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'initial_vm.sh')))
164 Cygwin.bashExecute('\\"' + initial_import_script + '\\" \'' + vm_image + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
166 res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
170 class os_initial_image:
171 """OpenSecurity '/initial_image' handler
173 - GET: Return what we have as initial image.
177 log_call(web.ctx.environ)
179 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
181 if os.path.isfile(t):
182 res = '{"initial_template": { '
183 res += '"name": "OsecVM.ova", '
184 res += '"path": "' + t.replace('\\', '\\\\') + '", '
185 res += '"size": ' + str(os.path.getsize(t)) + ', '
186 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)
235 """OpenSecurity '/sdvms/[VM]' handler
237 - GET: Information about a specific SecurityVM
238 - DELETE: Remove a specific
242 log_call(web.ctx.environ)
244 return gvm_mgr.getVMInfo(name)
246 def DELETE(self, name):
247 log_call(web.ctx.environ)
249 return gvm_mgr.removeVM(name)
252 class os_sdvm_application:
253 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
255 - GET: start application with given command in the VM.
258 def GET(self, name, command):
259 log_call(web.ctx.environ)
261 command = '/' + command
262 showTrayMessage('Launching application in isolated VM...', 7000)
263 result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
264 return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
268 """OpenSecurity '/sdvms/[VM]/ip' handler
270 - GET: give IP of SecurityVM.
274 log_call(web.ctx.environ)
276 return gvm_mgr.getHostOnlyIP(name)
280 """OpenSecurity '/sdvms/[VM]/start' handler
282 - GET: Start specific SecuirtyVM.
286 log_call(web.ctx.environ)
288 return gvm_mgr.startVM(name)
292 """OpenSecurity '/sdvms/[VM]/stop' handler
294 - GET: stop specific Secuirty VM.
298 log_call(web.ctx.environ)
300 return gvm_mgr.stopVM(name)
304 """OpenSecurity '/sdvms' handler
306 - GET: list all available secuirty VMs.
307 - POST: create new security vm.
311 """get the list of SDVMs"""
312 log_call(web.ctx.environ)
314 return gvm_mgr.listSDVM()
317 """create a new SDVM"""
318 log_call(web.ctx.environ)
322 name = gvm_mgr.generateSDVMName()
324 gvm_mgr.createVM(name)
326 raise web.internalerror()
332 """OpenSecurity '/setup' handler
334 - GET: Give user some info how to setup the OpenSecurity environment
339 log_call(web.ctx.environ)
344 <h1>Setup OpenSecurity</h1>
345 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
347 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
348 <li>Import initial VM: <a href="/init">init</a>
357 """OpenSecurity '/terminate' handler
359 - GET: terminate the opensecurityd.
361 TODO: need to find a better way doing this, and not via the
362 REST api. Maybe hack web.py server code?
366 log_call(web.ctx.environ)
375 class os_update_template:
376 """OpenSecurity '/update_template' handler
378 - GET: update template vm
382 #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
384 log_call(web.ctx.environ)
385 return gvm_mgr.updateTemplate()
389 """OpenSecurity '/vms/[VM]' handler
391 - GET: list information of arbitrary VM.
395 log_call(web.ctx.environ)
397 return gvm_mgr.getVMInfo(name)
401 """OpenSecurity '/vms' handler
403 - GET: list all (also non Security) VMs.
407 log_call(web.ctx.environ)
409 return str(gvm_mgr.listVM()).replace("'",'"')
412 def log_call(web_environ):
413 """log the incoming call to the REST api"""
415 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
422 """main startup for the opensecuirityd"""
427 logger.debug('Starting OpenSecurity REST server')
429 # ensure a VMManger is yet loaded
430 gvm_mgr = vmmanager.VMManager.getInstance()
432 # tweak sys.argv to control wep.py server start behavior
433 sys.argv = [__file__, "8080"]
434 server = web.application(opensecurity_urls, globals(), autoreload = False)
437 logger.debug('Stopped OpenSecurity REST server')
441 """stop the opensecuirityd"""
443 # calling sys.exit() raises a SystemExit exception
444 # of the WSGI Server to let it wind down
449 if __name__ == "__main__":