OpenSecurity/bin/launch.pyw
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Tue, 04 Feb 2014 13:36:06 +0100
changeset 58 1e1d8ca35988
parent 52 1238895dc6b6
child 70 e1db93adbebf
permissions -rwxr-xr-x
removed superfluous sys.exit(0) in launch.pyw
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # opensecurity-launcher
     6 # 
     7 # launches an application inside a VM
     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 argparse
    36 import os
    37 import subprocess
    38 import sys
    39 import urllib2
    40 
    41 from PyQt4 import QtCore
    42 from PyQt4 import QtGui
    43 
    44 # local
    45 from about import About
    46 from cygwin import Cygwin
    47 from environment import Environment
    48 
    49 
    50 # ------------------------------------------------------------
    51 # code
    52 
    53 
    54 class Chooser(QtGui.QDialog, object):
    55     
    56     """Ask the user what to launch."""
    57     
    58     def __init__(self, parent = None, flags = QtCore.Qt.WindowFlags(0)):
    59     
    60         super(Chooser, self).__init__(parent, flags)
    61         self.setWindowTitle('OpenSecuirty Launch Application')
    62         self.setup_ui()
    63         
    64         # positionate ourself central
    65         screen = QtGui.QDesktopWidget().screenGeometry()
    66         self.resize(self.geometry().width() * 1.25, self.geometry().height())
    67         size = self.geometry()
    68         self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
    69         
    70         # TODO: THIS HERE IS HARD CODED
    71         self._vms = [ { 'name': 'SecurityDVM0' } ]
    72         self._apps = [ { 'name': 'Browser', 'command': '/usr/bin/iceweasel' } ]
    73         
    74         # add the VMs we know
    75         self._cbVM.clear()
    76         for vm in self._vms:
    77             self._cbVM.addItem(vm['name'])
    78             
    79         # add the commands we know
    80         self._cbApplication.clear()
    81         for app in self._apps:
    82             self._cbApplication.addItem(app['name'])
    83         
    84         
    85         
    86     def app_get(self):
    87         """The application of the user."""
    88         a = str(self._cbApplication.currentText())
    89         for app in self._apps:
    90             if a == app['name']:
    91                 return app['command']
    92         return a
    93         
    94     app = property(app_get)
    95         
    96 
    97     def clicked_about(self):
    98         """clicked the about button"""
    99         dlgAbout = About()
   100         dlgAbout.exec_()
   101 
   102 
   103     def clicked_cancel(self):
   104         """clicked the cancel button"""
   105         self.reject()
   106     
   107 
   108     def clicked_ok(self):
   109         """clicked the ok button"""
   110         self.accept()
   111     
   112     
   113     def setup_ui(self):
   114         """Create the widgets."""
   115         
   116         lyMain = QtGui.QVBoxLayout(self)
   117         lyMain.setContentsMargins(8, 8, 8, 8)
   118         
   119         # content area: left pixmap, right text
   120         lyContent = QtGui.QHBoxLayout()
   121         lyMain.addLayout(lyContent)
   122         
   123         # pixmap
   124         lbPix = QtGui.QLabel()
   125         lbPix.setPixmap(QtGui.QPixmapCache.find('opensecurity_icon_64'))
   126         lyContent.addWidget(lbPix, 0, QtCore.Qt.Alignment(QtCore.Qt.AlignTop + QtCore.Qt.AlignHCenter))
   127         lyContent.addSpacing(16)
   128         
   129         # launch ...
   130         lyLaunch = QtGui.QGridLayout()
   131         lyContent.addLayout(lyLaunch)
   132         lbTitle = QtGui.QLabel('Specify details for application to launch.')
   133         lyLaunch.addWidget(lbTitle, 0, 0, 1, 2)
   134         
   135         lbVM = QtGui.QLabel('&VM-ID:')
   136         lyLaunch.addWidget(lbVM, 1, 0)
   137         self._cbVM = QtGui.QComboBox()
   138         self._cbVM.setEditable(True)
   139         self._cbVM.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
   140         lyLaunch.addWidget(self._cbVM, 1, 1)
   141         lbVM.setBuddy(self._cbVM)
   142         
   143         lbApplication = QtGui.QLabel('&Application:')
   144         lyLaunch.addWidget(lbApplication, 2, 0)
   145         self._cbApplication = QtGui.QComboBox()
   146         self._cbApplication.setEditable(True)
   147         self._cbApplication.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
   148         lyLaunch.addWidget(self._cbApplication, 2, 1)
   149         lbApplication.setBuddy(self._cbApplication)
   150         
   151         lyLaunch.addWidget(QtGui.QWidget(), 3, 0, 1, 2)
   152         lyLaunch.setColumnStretch(1, 1)
   153         lyLaunch.setRowStretch(3, 1)
   154         
   155         lyMain.addStretch(1)
   156         
   157         # buttons
   158         lyButton = QtGui.QHBoxLayout()
   159         lyMain.addLayout(lyButton)
   160         
   161         lyButton.addStretch(1)
   162         btnOk = QtGui.QPushButton('&Ok', self)
   163         btnOk.setDefault(True)
   164         btnOk.setMinimumWidth(100)
   165         lyButton.addWidget(btnOk)
   166         btnCancel = QtGui.QPushButton('&Cancel', self)
   167         btnCancel.setMinimumWidth(100)
   168         lyButton.addWidget(btnCancel)
   169         btnAbout = QtGui.QPushButton('&About', self)
   170         btnAbout.setMinimumWidth(100)
   171         lyButton.addWidget(btnAbout)
   172         
   173         button_width = max(btnOk.width(), btnCancel.width(), btnAbout.width())
   174         btnOk.setMinimumWidth(button_width)
   175         btnCancel.setMinimumWidth(button_width)
   176         btnAbout.setMinimumWidth(button_width)
   177         
   178         # reduce to the max
   179         self.resize(lyMain.minimumSize())
   180         
   181         # connectors
   182         btnOk.clicked.connect(self.clicked_ok)
   183         btnCancel.clicked.connect(self.clicked_cancel)
   184         btnAbout.clicked.connect(self.clicked_about)
   185 
   186         
   187     def vm_get(self):
   188         """The vm of choice."""
   189         return str(self._cbVM.currentText())
   190         
   191     vm = property(vm_get)
   192         
   193         
   194 def ask_user():
   195     """ask the user for VM and app to start"""
   196     
   197     # prebuild the pixmap cache: fetch all jpg, png and jpeg images and load them
   198     image_path = os.path.join(Environment("OpenSecurity").data_path, '..', 'gfx')
   199     for file in os.listdir(image_path):
   200         if file.lower().rpartition('.')[2] in ('jpg', 'png', 'jpeg'):
   201             QtGui.QPixmapCache.insert(file.lower().rpartition('.')[0], QtGui.QPixmap(os.path.join(image_path, file)))
   202             
   203     # we should have now our application icon
   204     app.setWindowIcon(QtGui.QIcon(QtGui.QPixmapCache.find('opensecurity_icon_64')))
   205     
   206     # pop up the dialog
   207     dlg = Chooser()
   208     dlg.show()
   209     app.exec_()
   210     
   211     if dlg.result() == QtGui.QDialog.Accepted:
   212         return dlg.vm, dlg.app
   213 
   214     return '', ''
   215     
   216 
   217 def main():
   218     """entry point"""
   219     
   220     # launch Qt
   221     global app
   222     app = QtGui.QApplication(sys.argv)
   223     
   224     # parse command line
   225     parser = argparse.ArgumentParser(description = 'OpenSecurity Launcher: run application in VM')
   226     parser.add_argument('vm', metavar='VM', help='Name of Virtual Machine', nargs='?', type=str, default='')
   227     parser.add_argument('command', metavar='COMMAND', help='Full path of command and arguments to start inside VM', nargs='?', type=str, default='')
   228     args = parser.parse_args()
   229     
   230     # we must have all set
   231     if args.vm == "" or args.command == '':
   232         print('VM and/or COMMAND missing - invoking user dialog')
   233         args.vm, args.command = ask_user()
   234         
   235     # still no VM? --> no chance, over and out!
   236     if args.vm == '':
   237         sys.exit(0)
   238         
   239     # ensure we have our X11 running
   240     Cygwin.start_X11()
   241    
   242     # call the OpenSecurity Admin to launch our progie =)
   243     # TODO: hard coded PORT
   244     url = 'http://127.0.0.1:8080/sdvms/' + args.vm + '/application' + args.command
   245     print('Calling ' + url)
   246     try:
   247         result = urllib2.urlopen(url, None, 5)
   248     except urllib2.HTTPError as e:
   249         # Error, Fail, ... :(
   250         msg = 'Error received from OpenSecurity Subsystem\nError code: ' + str(e.code) + '\nReason: ' + e.reason
   251         QtGui.QMessageBox.critical(None, 'OpenSecurity Error', msg)
   252     
   253     
   254 # start
   255 if __name__ == "__main__":
   256     main()
   257