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
52 # ------------------------------------------------------------
55 """All the URLs we know mapping to class handler"""
57 '/browsing', 'os_browsing', # http://localhost:8080/browsing GET
58 '/fetch_initial_image', 'os_fetch_image', # http://localhost:8080/fetch_initial_image GET
59 '/init', 'os_init', # http://localhost:8080/init GET
60 '/initial_image', 'os_initial_image', # http://localhost:8080/initial_image GET
61 '/sdvms', 'os_sdvms', # http://localhost:8080/sdvms GET, PUT
62 '/sdvms/(.*)/application/(.*)', 'os_sdvm_application', # http://localhost:8080/sdvms/[VMNAME]/application/[COMMAND] GET
63 '/sdvms/(.*)/ip', 'os_sdvm_ip', # http://localhost:8080/sdvms/[VMNAME]/ip GET
64 '/sdvms/(.*)/start', 'os_sdvm_start', # http://localhost:8080/sdvms/[VMNAME]/start GET
65 '/sdvms/(.*)/stop', 'os_sdvm_stop', # http://localhost:8080/sdvms/[VMNAME]/stop GET
66 '/sdvms/(.*)', 'os_sdvm', # http://localhost:8080/sdvms/[VMNAME] GET, DELETE
67 '/setup', 'os_setup', # http://localhost:8080/setup GET
68 '/vms', 'os_vms', # http://localhost:8080/vms GET
69 '/vms/(.*)', 'os_vm', # http://localhost:8080/vms/[VMNAME] GET
70 '/update_template', 'os_update_template', # http://localhost:8080/update_template GET
71 '/terminate', 'os_terminate', # http://localhost:8080/terminate GET
72 '/', 'os_root' # http://localhost:8080/ GET
76 # ------------------------------------------------------------
79 # Global VMManager instance
86 # ------------------------------------------------------------
91 """OpenSecurity '/browsing' handler
93 - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
97 log_call(web.ctx.environ)
100 result = gvm_mgr.handleBrowsingRequest()
103 raise web.internalerror()
106 class os_fetch_image:
107 """OpenSecurity '/fetch_initial_image' handler
109 - GET: fetch the initial image from the X-Net Servers
110 The initial image is stored in the
111 Virtual Box default machine path.
112 The result to this call is a temprary file
113 which shows the progress (or error state)
119 log_call(web.ctx.environ)
122 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_fetch_image.log')
123 trace_file = open(trace_file_name, 'w+')
125 machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder())
126 download_initial_image_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'download_initial_image.sh')))
127 Cygwin.bashExecute('\\"' + download_initial_image_script + '\\" \'' + machine_folder + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
129 res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
134 """OpenSecurity '/init' handler
136 - GET: Do initial import of OsecVM.ova
140 log_call(web.ctx.environ)
146 if gvm_mgr.vmRootName in gvm_mgr.listVM():
147 gvm_mgr.poweroffVM(gvm_mgr.vmRootName)
148 tmplateUUID = gvm_mgr.getTemplateUUID()
149 if tmplateUUID != None:
150 logger.debug('found parent uuid ' + tmplateUUID)
151 gvm_mgr.storageDetach(gvm_mgr.vmRootName)
152 gvm_mgr.removeSnapshots(tmplateUUID)
153 gvm_mgr.removeImage(tmplateUUID)
155 logger.debug('parent uuid not found')
156 gvm_mgr.removeVM(gvm_mgr.vmRootName)
158 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_initial_import.log')
159 trace_file = open(trace_file_name, 'w+')
161 vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
162 initial_import_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'initial_vm.sh')))
163 Cygwin.bashExecute('\\"' + initial_import_script + '\\" \'' + vm_image + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
165 res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
169 class os_initial_image:
170 """OpenSecurity '/initial_image' handler
172 - GET: Return what we have as initial image.
176 log_call(web.ctx.environ)
178 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
180 if os.path.isfile(t):
181 res = '{"initial_template": { '
182 res += '"name": "OsecVM.ova", '
183 res += '"path": "' + t.replace('\\', '\\\\') + '", '
184 res += '"size": ' + str(os.path.getsize(t)) + ', '
185 res += '"date": ' + str(os.path.getmtime(t)) + ''
191 """OpenSecurity '/' handler
193 - GET: give information about current installation.
197 log_call(web.ctx.environ)
200 # create a json string and pretty print it
201 res = '{"os_server": { '
202 res += '"version": "' + opensecurity.__version__ + '" '
203 res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"')
204 res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
205 res += ', "current log folder": "' + Environment('OpenSecurity').log_path.replace('\\', '\\\\') + '"'
208 res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
210 res += ', "whoami": "FAILED"'
213 res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
215 res += ', "mount": "FAILED"'
218 res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
220 res += ', "cygpath --windows ~": "FAILED"'
223 res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
227 # loading it into json and print it again ensures
228 # we really do have a valid RFC conform json string
229 # created (as long as the python json module is RFC conform)
230 return json.dumps(json.loads(res), indent = 4)
234 """OpenSecurity '/sdvms/[VM]' handler
236 - GET: Information about a specific SecurityVM
237 - DELETE: Remove a specific
241 log_call(web.ctx.environ)
243 return gvm_mgr.getVMInfo(name)
245 def DELETE(self, name):
246 log_call(web.ctx.environ)
248 return gvm_mgr.removeVM(name)
251 class os_sdvm_application:
252 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
254 - GET: start application with given command in the VM.
257 def GET(self, name, command):
258 log_call(web.ctx.environ)
260 command = '/' + command
261 result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
262 return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
266 """OpenSecurity '/sdvms/[VM]/ip' handler
268 - GET: give IP of SecurityVM.
272 log_call(web.ctx.environ)
274 return gvm_mgr.getHostOnlyIP(name)
278 """OpenSecurity '/sdvms/[VM]/start' handler
280 - GET: Start specific SecuirtyVM.
284 log_call(web.ctx.environ)
286 return gvm_mgr.startVM(name)
290 """OpenSecurity '/sdvms/[VM]/stop' handler
292 - GET: stop specific Secuirty VM.
296 log_call(web.ctx.environ)
298 return gvm_mgr.stopVM(name)
302 """OpenSecurity '/sdvms' handler
304 - GET: list all available secuirty VMs.
305 - POST: create new security vm.
309 """get the list of SDVMs"""
310 log_call(web.ctx.environ)
312 return gvm_mgr.listSDVM()
315 """create a new SDVM"""
316 log_call(web.ctx.environ)
320 name = gvm_mgr.generateSDVMName()
322 gvm_mgr.createVM(name)
324 raise web.internalerror()
330 """OpenSecurity '/setup' handler
332 - GET: Give user some info how to setup the OpenSecurity envvironment
337 log_call(web.ctx.environ)
342 <h1>Setup OpenSecurity</h1>
343 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
345 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
346 <li>Import initial VM: <a href="/init">init</a>
355 """OpenSecurity '/terminate' handler
357 - GET: terminate the opensecurityd.
359 TODO: need to find a better way doing this, and not via the
360 REST api. Maybe hack web.py server code?
364 log_call(web.ctx.environ)
373 class os_update_template:
374 """OpenSecurity '/update_template' handler
376 - GET: update template vm
380 #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
382 log_call(web.ctx.environ)
383 return gvm_mgr.updateTemplate()
387 """OpenSecurity '/vms/[VM]' handler
389 - GET: list information of arbitrary VM.
393 log_call(web.ctx.environ)
395 return gvm_mgr.getVMInfo(name)
399 """OpenSecurity '/vms' handler
401 - GET: list all (also non Security) VMs.
405 log_call(web.ctx.environ)
407 return str(gvm_mgr.listVM()).replace("'",'"')
410 def log_call(web_environ):
411 """log the incoming call to the REST api"""
413 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
420 """main startup for the opensecuirityd"""
425 logger.debug('Starting OpenSecurity REST server')
427 # ensure a VMManger is yet loaded
428 gvm_mgr = vmmanager.VMManager.getInstance()
430 # tweak sys.argv to control wep.py server start behavior
431 sys.argv = [__file__, "8080"]
432 server = web.application(opensecurity_urls, globals(), autoreload = False)
435 logger.debug('Stopped OpenSecurity REST server')
439 """stop the opensecuirityd"""
441 # calling sys.exit() raises a SystemExit exception
442 # of the WSGI Server to let it wind down
447 if __name__ == "__main__":