OpenSecurity/bin/opensecurityd.pyw
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Wed, 02 Apr 2014 10:27:38 +0200
changeset 115 56a79fe30085
parent 112 9cd4654c040b
child 116 eb2c1260134e
permissions -rwxr-xr-x
working on GUI
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # opensecurityd
     6 # 
     7 # the opensecurityd as RESTful server
     8 #
     9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    10 #
    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
    15 #
    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.
    19 # 
    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.
    24 # 
    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 # ------------------------------------------------------------
    30 
    31 
    32 # ------------------------------------------------------------
    33 # imports
    34 
    35 import os
    36 import os.path
    37 import subprocess
    38 import sys
    39 import tempfile
    40 import web
    41 
    42 import vmmanager
    43 
    44 # local
    45 from cygwin import Cygwin
    46 from environment import Environment
    47 from opensecurity_util import logger
    48 
    49 
    50 # ------------------------------------------------------------
    51 # const
    52 
    53 __version__ = "0.2.4"
    54 
    55 
    56 """All the URLs we know mapping to class handler"""
    57 opensecurity_urls = (
    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
    74 )
    75 
    76 
    77 # ------------------------------------------------------------
    78 # vars
    79 
    80 # Global VMManager instance
    81 gvm_mgr = None
    82 
    83 
    84 # ------------------------------------------------------------
    85 # code
    86 
    87 
    88 class os_browsing:
    89     """OpenSecurity '/browsing' handler
    90     
    91     - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
    92     """
    93     
    94     def GET(self):
    95         log_call(web.ctx.environ)
    96         global gvm_mgr
    97         try:
    98             result = gvm_mgr.handleBrowsingRequest()
    99             return result
   100         except:
   101             raise web.internalerror()
   102 
   103        
   104 class os_fetch_image:
   105     """OpenSecurity '/fetch_initial_image' handler
   106     
   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)
   112             of this call.
   113     """
   114     
   115     def GET(self):
   116         
   117         log_call(web.ctx.environ)
   118         global gvm_mgr
   119 
   120         trace_file_name = os.path.join(tempfile.gettempdir(), 'OpenSecurity_fetch_image.log')
   121         trace_file = open(trace_file_name, 'w+')
   122 
   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) 
   126 
   127         res = '{ "fetch.log": " ' + trace_file_name.replace('\\', '\\\\') + '" }'
   128         return res
   129 
   130 class os_init:
   131     """OpenSecurity '/init' handler
   132     
   133     - GET: Do initial import of OsecVM.ova
   134     """
   135     
   136     def GET(self):
   137         log_call(web.ctx.environ)
   138         global gvm_mgr
   139 
   140         trace_file_name = os.path.join(tempfile.gettempdir(), 'OpenSecurity_initial_import.log')
   141         trace_file = open(trace_file_name, 'w+')
   142 
   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) 
   146 
   147         res = '{ "init.log": " ' + trace_file_name.replace('\\', '\\\\') + '" }'
   148         return res
   149 
   150 
   151 class os_initial_image:
   152     """OpenSecurity '/initial_image' handler
   153     
   154     - GET: Return what we have as initial image.
   155     """
   156     
   157     def GET(self):
   158         log_call(web.ctx.environ)
   159         global gvm_mgr
   160         t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
   161         res = ''
   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)) + ''
   168             res += '}}'
   169         return res
   170 
   171 
   172 class os_root:
   173     """OpenSecurity '/' handler
   174     
   175     - GET: give information about current installation.
   176     """
   177     
   178     def GET(self):
   179         log_call(web.ctx.environ)
   180         global gvm_mgr
   181         res = '{"os_server": { '
   182         res += '"version": "' + __version__ + '", '
   183         res += '"virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"') + ', '
   184         res += '"current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '" '
   185         res += '}}'
   186         return res
   187 
   188 
   189 class os_sdvm:
   190     """OpenSecurity '/sdvms/[VM]' handler
   191     
   192     - GET: Information about a specific SecurityVM
   193     - DELETE: Remove a specific
   194     """
   195     
   196     def GET(self, name):
   197         log_call(web.ctx.environ)
   198         global gvm_mgr
   199         return gvm_mgr.getVMInfo(name)
   200 
   201     def DELETE(self, name):
   202         log_call(web.ctx.environ)
   203         global gvm_mgr
   204         return gvm_mgr.removeVM(name)
   205             
   206 
   207 class os_sdvm_application:
   208     """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
   209     
   210     - GET: start application with given command in the VM.
   211     """
   212     
   213     def GET(self, name, command):
   214         log_call(web.ctx.environ)
   215         global gvm_mgr
   216         command = '/' + command
   217         result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key'  )
   218         self.poweroffVM(name)
   219         return gvm_mgr.removeVM(name)
   220     
   221 
   222 class os_sdvm_ip:
   223     """OpenSecurity '/sdvms/[VM]/ip' handler
   224     
   225     - GET: give IP of SecurityVM.
   226     """
   227     
   228     def GET(self, name):
   229         log_call(web.ctx.environ)
   230         global gvm_mgr
   231         return gvm_mgr.getHostOnlyIP(name)
   232             
   233 
   234 class os_sdvm_start:
   235     """OpenSecurity '/sdvms/[VM]/start' handler
   236     
   237     - GET: Start specific SecuirtyVM.
   238     """
   239     
   240     def GET(self, name):
   241         log_call(web.ctx.environ)
   242         global gvm_mgr
   243         return gvm_mgr.startVM(name)
   244             
   245 
   246 class os_sdvm_stop:
   247     """OpenSecurity '/sdvms/[VM]/stop' handler
   248     
   249     - GET: stop specific Secuirty VM.
   250     """
   251     
   252     def GET(self, name):
   253         log_call(web.ctx.environ)
   254         global gvm_mgr
   255         return gvm_mgr.stopVM(name)
   256             
   257 
   258 class os_sdvms:
   259     """OpenSecurity '/sdvms' handler
   260     
   261     - GET: list all available secuirty VMs.
   262     - POST: create new security vm.
   263     """
   264     
   265     def GET(self):
   266         """get the list of SDVMs"""
   267         log_call(web.ctx.environ)
   268         global gvm_mgr
   269         return gvm_mgr.listSDVM() 
   270             
   271     def POST(self):
   272         """create a new SDVM"""
   273         log_call(web.ctx.environ)
   274         global gvm_mgr
   275         
   276         # get a new vm-name
   277         name = gvm_mgr.generateSDVMName()
   278         try:
   279             gvm_mgr.createVM(name)
   280         except:
   281             raise web.internalerror()
   282             
   283         return name
   284             
   285 
   286 class os_setup:
   287     """OpenSecurity '/setup' handler
   288     
   289     - GET: Give user some info how to setup the OpenSecurity envvironment
   290     """
   291     
   292     def GET(self):
   293 
   294         log_call(web.ctx.environ)
   295 
   296         page = """
   297         <html>
   298         <body>
   299         <h1>Setup OpenSecurity</h1>
   300         In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
   301         <ul>
   302             <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
   303             <li>Import initial VM: <a href="/init">init</a>
   304         </ul>
   305         </body>
   306         </html>
   307         """
   308         return page
   309 
   310 
   311 class os_terminate:
   312     """OpenSecurity '/terminate' handler
   313     
   314     - GET: terminate the opensecurityd.
   315 
   316     YES: this here is bonkers. But the web.py http
   317     server runs infinite until a SystemExit exception
   318     or KeyboardInterrupt exception is raised.
   319 
   320     see: site-packages/web/httpserver.py - line 157ff
   321     see: site-packages/web/wsgiserver/__init__.py - line 1682ff
   322 
   323     So, we invoke a sys.exit(0) here to trigger server.stop().
   324 
   325     TODO: need to find a better way doing this, and not via the
   326           REST api. Maybe hack web.py server code?
   327     """
   328     
   329     def GET(self):
   330         log_call(web.ctx.environ)
   331         global gvm_mgr
   332         gvm_mgr.stop()
   333         gvm_mgr.cleanup()
   334         sys.exit(0)
   335         return None
   336 
   337 
   338 class os_update_template:
   339     """OpenSecurity '/update_template' handler
   340     
   341     - GET: update template vm
   342     """
   343     
   344     def GET(self):
   345         #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
   346         global gvm_mgr
   347         log_call(web.ctx.environ)
   348         return gvm_mgr.updateTemplate()
   349 
   350 
   351 class os_vm:
   352     """OpenSecurity '/vms/[VM]' handler
   353     
   354     - GET: list information of arbitrary VM.
   355     """
   356     
   357     def GET(self, name):
   358         log_call(web.ctx.environ)
   359         global gvm_mgr
   360         return gvm_mgr.getVMInfo(name)
   361             
   362 
   363 class os_vms:
   364     """OpenSecurity '/vms' handler
   365     
   366     - GET: list all (also non Security) VMs.
   367     """
   368     
   369     def GET(self):
   370         log_call(web.ctx.environ)
   371         global gvm_mgr
   372         return str(gvm_mgr.listVM()).replace("'",'"')
   373             
   374 
   375 def log_call(web_environ):
   376     """log the incoming call to the REST api"""
   377     try:
   378         call = 'REST ' +  web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
   379         logger.debug(call)
   380     except:
   381         pass
   382 
   383 
   384 def main():
   385     """main startup for the opensecuirityd"""
   386 
   387     logger.debug('Starting OpenSecurity REST server')
   388 
   389     # ensure a VMManger is yet loaded
   390     global gvm_mgr
   391     gvm_mgr = vmmanager.VMManager.getInstance()
   392     
   393     # tweak sys.argv to control wep.py server start behavior
   394     sys.argv = [__file__, "8080"]
   395     server = web.application(opensecurity_urls, globals(), autoreload = False)
   396     server.run()
   397     
   398     logger.debug('Stopped OpenSecurity REST server')
   399 
   400 
   401 def stop():
   402     """stop the opensecuirityd"""
   403 
   404     # calling sys.exit() raises a SystemExit exception
   405     # of the WSGI Server to let it wind down
   406     # gracefully
   407     sys.exit(0)
   408 
   409 
   410 
   411 # start
   412 if __name__ == "__main__":
   413     main()
   414