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