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