corrected terminate / update template / etc.
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 gvm_mgr.storageDetach(gvm_mgr.vmRootName)
149 gvm_mgr.removeSnapshots(gvm_mgr.vmRootName)
150 #TODO:// unregister vmdk with the vbox
151 gvm_mgr.removeVMFolder(gvm_mgr.vmRootName)
153 trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_initial_import.log')
154 trace_file = open(trace_file_name, 'w+')
156 vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
157 initial_import_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'initial_vm.sh')))
158 Cygwin.bashExecute('\\"' + initial_import_script + '\\" \'' + vm_image + '\'', wait_return = False, stdout = trace_file, stderr = trace_file)
160 res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
164 class os_initial_image:
165 """OpenSecurity '/initial_image' handler
167 - GET: Return what we have as initial image.
171 log_call(web.ctx.environ)
173 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
175 if os.path.isfile(t):
176 res = '{"initial_template": { '
177 res += '"name": "OsecVM.ova", '
178 res += '"path": "' + t.replace('\\', '\\\\') + '", '
179 res += '"size": ' + str(os.path.getsize(t)) + ', '
180 res += '"date": ' + str(os.path.getmtime(t)) + ''
186 """OpenSecurity '/' handler
188 - GET: give information about current installation.
192 log_call(web.ctx.environ)
195 # create a json string and pretty print it
196 res = '{"os_server": { '
197 res += '"version": "' + opensecurity.__version__ + '" '
198 res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"')
199 res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
200 res += ', "current log folder": "' + Environment('OpenSecurity').log_path.replace('\\', '\\\\') + '"'
203 res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
205 res += ', "whoami": "FAILED"'
208 res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
210 res += ', "mount": "FAILED"'
213 res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
215 res += ', "cygpath --windows ~": "FAILED"'
218 res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
222 # loading it into json and print it again ensures
223 # we really do have a valid RFC conform json string
224 # created (as long as the python json module is RFC conform)
225 return json.dumps(json.loads(res), indent = 4)
229 """OpenSecurity '/sdvms/[VM]' handler
231 - GET: Information about a specific SecurityVM
232 - DELETE: Remove a specific
236 log_call(web.ctx.environ)
238 return gvm_mgr.getVMInfo(name)
240 def DELETE(self, name):
241 log_call(web.ctx.environ)
243 return gvm_mgr.removeVM(name)
246 class os_sdvm_application:
247 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
249 - GET: start application with given command in the VM.
252 def GET(self, name, command):
253 log_call(web.ctx.environ)
255 command = '/' + command
256 result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
257 return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
261 """OpenSecurity '/sdvms/[VM]/ip' handler
263 - GET: give IP of SecurityVM.
267 log_call(web.ctx.environ)
269 return gvm_mgr.getHostOnlyIP(name)
273 """OpenSecurity '/sdvms/[VM]/start' handler
275 - GET: Start specific SecuirtyVM.
279 log_call(web.ctx.environ)
281 return gvm_mgr.startVM(name)
285 """OpenSecurity '/sdvms/[VM]/stop' handler
287 - GET: stop specific Secuirty VM.
291 log_call(web.ctx.environ)
293 return gvm_mgr.stopVM(name)
297 """OpenSecurity '/sdvms' handler
299 - GET: list all available secuirty VMs.
300 - POST: create new security vm.
304 """get the list of SDVMs"""
305 log_call(web.ctx.environ)
307 return gvm_mgr.listSDVM()
310 """create a new SDVM"""
311 log_call(web.ctx.environ)
315 name = gvm_mgr.generateSDVMName()
317 gvm_mgr.createVM(name)
319 raise web.internalerror()
325 """OpenSecurity '/setup' handler
327 - GET: Give user some info how to setup the OpenSecurity envvironment
332 log_call(web.ctx.environ)
337 <h1>Setup OpenSecurity</h1>
338 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
340 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
341 <li>Import initial VM: <a href="/init">init</a>
350 """OpenSecurity '/terminate' handler
352 - GET: terminate the opensecurityd.
354 TODO: need to find a better way doing this, and not via the
355 REST api. Maybe hack web.py server code?
359 log_call(web.ctx.environ)
368 class os_update_template:
369 """OpenSecurity '/update_template' handler
371 - GET: update template vm
375 #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
377 log_call(web.ctx.environ)
378 return gvm_mgr.updateTemplate()
382 """OpenSecurity '/vms/[VM]' handler
384 - GET: list information of arbitrary VM.
388 log_call(web.ctx.environ)
390 return gvm_mgr.getVMInfo(name)
394 """OpenSecurity '/vms' handler
396 - GET: list all (also non Security) VMs.
400 log_call(web.ctx.environ)
402 return str(gvm_mgr.listVM()).replace("'",'"')
405 def log_call(web_environ):
406 """log the incoming call to the REST api"""
408 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
415 """main startup for the opensecuirityd"""
420 logger.debug('Starting OpenSecurity REST server')
422 # ensure a VMManger is yet loaded
423 gvm_mgr = vmmanager.VMManager.getInstance()
425 # tweak sys.argv to control wep.py server start behavior
426 sys.argv = [__file__, "8080"]
427 server = web.application(opensecurity_urls, globals(), autoreload = False)
430 logger.debug('Stopped OpenSecurity REST server')
434 """stop the opensecuirityd"""
436 # calling sys.exit() raises a SystemExit exception
437 # of the WSGI Server to let it wind down
442 if __name__ == "__main__":