VMManager Backend check and status messages.
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 from cygwin import Cygwin
47 from environment import Environment
48 from opensecurity_util import logger
51 # ------------------------------------------------------------
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 '/', 'os_root' # http://localhost:8080/ GET
78 # ------------------------------------------------------------
81 # Global VMManager instance
84 # ------------------------------------------------------------
89 """OpenSecurity '/browsing' handler
91 - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
95 log_call(web.ctx.environ)
98 result = gvm_mgr.handleBrowsingRequest()
101 raise web.internalerror()
104 class os_fetch_image:
105 """OpenSecurity '/fetch_initial_image' handler
107 - GET: fetch the initial image from the X-Net Servers
108 The initial image is stored in the
109 Virtual Box default machine path.
110 The result to this call is a temprary file
111 which shows the progress (or error state)
117 log_call(web.ctx.environ)
120 trace_file_name = os.path.join(tempfile.gettempdir(), 'OpenSecurity_fetch_image.log')
121 trace_file = open(trace_file_name, 'w+')
123 machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder())
124 download_initial_image_script = '/OpenSecurity/bin/download_initial_image.sh \'' + machine_folder + '\''
125 Cygwin.bashExecute(download_initial_image_script, wait_return = False, stdout = trace_file, stderr = trace_file)
127 res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
131 """OpenSecurity '/init' handler
133 - GET: Do initial import of OsecVM.ova
137 log_call(web.ctx.environ)
140 trace_file_name = os.path.join(tempfile.gettempdir(), 'OpenSecurity_initial_import.log')
141 trace_file = open(trace_file_name, 'w+')
143 vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
144 initial_import_script = '/OpenSecurity/bin/initial_vm.sh \'' + vm_image + '\''
145 Cygwin.bashExecute(initial_import_script, wait_return = False, stdout = trace_file, stderr = trace_file)
147 res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
151 class os_initial_image:
152 """OpenSecurity '/initial_image' handler
154 - GET: Return what we have as initial image.
158 log_call(web.ctx.environ)
160 t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
162 if os.path.isfile(t):
163 res = '{"initial_template": { '
164 res += '"name": "OsecVM.ova", '
165 res += '"path": "' + t.replace('\\', '\\\\') + '", '
166 res += '"size": ' + str(os.path.getsize(t)) + ', '
167 res += '"date": ' + str(os.path.getmtime(t)) + ''
173 """OpenSecurity '/' handler
175 - GET: give information about current installation.
179 log_call(web.ctx.environ)
182 # create a json string and pretty print it
183 res = '{"os_server": { '
184 res += '"version": "' + __version__ + '" '
185 res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"')
186 res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
189 res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
191 res += ', "whoami": "FAILED"'
194 res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
196 res += ', "mount": "FAILED"'
199 res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
201 res += ', "cygpath --windows ~": "FAILED"'
204 res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
208 # loading it into json and print it again ensures
209 # we really do have a valid RFC conform json string
210 # created (as long as the python json module is RFC conform)
211 return json.dumps(json.loads(res), indent = 4)
215 """OpenSecurity '/sdvms/[VM]' handler
217 - GET: Information about a specific SecurityVM
218 - DELETE: Remove a specific
222 log_call(web.ctx.environ)
224 return gvm_mgr.getVMInfo(name)
226 def DELETE(self, name):
227 log_call(web.ctx.environ)
229 return gvm_mgr.removeVM(name)
232 class os_sdvm_application:
233 """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
235 - GET: start application with given command in the VM.
238 def GET(self, name, command):
239 log_call(web.ctx.environ)
241 command = '/' + command
242 result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key' )
243 self.poweroffVM(name)
244 return gvm_mgr.removeVM(name)
248 """OpenSecurity '/sdvms/[VM]/ip' handler
250 - GET: give IP of SecurityVM.
254 log_call(web.ctx.environ)
256 return gvm_mgr.getHostOnlyIP(name)
260 """OpenSecurity '/sdvms/[VM]/start' handler
262 - GET: Start specific SecuirtyVM.
266 log_call(web.ctx.environ)
268 return gvm_mgr.startVM(name)
272 """OpenSecurity '/sdvms/[VM]/stop' handler
274 - GET: stop specific Secuirty VM.
278 log_call(web.ctx.environ)
280 return gvm_mgr.stopVM(name)
284 """OpenSecurity '/sdvms' handler
286 - GET: list all available secuirty VMs.
287 - POST: create new security vm.
291 """get the list of SDVMs"""
292 log_call(web.ctx.environ)
294 return gvm_mgr.listSDVM()
297 """create a new SDVM"""
298 log_call(web.ctx.environ)
302 name = gvm_mgr.generateSDVMName()
304 gvm_mgr.createVM(name)
306 raise web.internalerror()
312 """OpenSecurity '/setup' handler
314 - GET: Give user some info how to setup the OpenSecurity envvironment
319 log_call(web.ctx.environ)
324 <h1>Setup OpenSecurity</h1>
325 In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
327 <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
328 <li>Import initial VM: <a href="/init">init</a>
337 """OpenSecurity '/terminate' handler
339 - GET: terminate the opensecurityd.
341 YES: this here is bonkers. But the web.py http
342 server runs infinite until a SystemExit exception
343 or KeyboardInterrupt exception is raised.
345 see: site-packages/web/httpserver.py - line 157ff
346 see: site-packages/web/wsgiserver/__init__.py - line 1682ff
348 So, we invoke a sys.exit(0) here to trigger server.stop().
350 TODO: need to find a better way doing this, and not via the
351 REST api. Maybe hack web.py server code?
355 log_call(web.ctx.environ)
362 class os_update_template:
363 """OpenSecurity '/update_template' handler
365 - GET: update template vm
369 #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
371 log_call(web.ctx.environ)
372 return gvm_mgr.updateTemplate()
376 """OpenSecurity '/vms/[VM]' handler
378 - GET: list information of arbitrary VM.
382 log_call(web.ctx.environ)
384 return gvm_mgr.getVMInfo(name)
388 """OpenSecurity '/vms' handler
390 - GET: list all (also non Security) VMs.
394 log_call(web.ctx.environ)
396 return str(gvm_mgr.listVM()).replace("'",'"')
399 def log_call(web_environ):
400 """log the incoming call to the REST api"""
402 call = 'REST ' + web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
409 """main startup for the opensecuirityd"""
411 logger.debug('Starting OpenSecurity REST server')
413 # ensure a VMManger is yet loaded
415 gvm_mgr = vmmanager.VMManager.getInstance()
417 # tweak sys.argv to control wep.py server start behavior
418 sys.argv = [__file__, "8080"]
419 server = web.application(opensecurity_urls, globals(), autoreload = False)
422 logger.debug('Stopped OpenSecurity REST server')
426 """stop the opensecuirityd"""
428 # calling sys.exit() raises a SystemExit exception
429 # of the WSGI Server to let it wind down
436 if __name__ == "__main__":