OpenSecurity/bin/launch.py
author om
Tue, 10 Dec 2013 14:04:11 +0100
changeset 31 d95fe93d7a83
parent 16 e16d64b5e008
permissions -rwxr-xr-x
opensecurityd can now invoke applications on vm
     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 urllib
    40 import urllib2
    41 
    42 from PyQt4 import QtCore
    43 from PyQt4 import QtGui
    44 
    45 # local
    46 from about import About
    47 from cygwin import Cygwin
    48 from environment import Environment
    49 
    50 
    51 # ------------------------------------------------------------
    52 # code
    53 
    54 
    55 class Chooser(QtGui.QDialog, object):
    56     
    57     """Ask the user what to launch."""
    58     
    59     def __init__(self, parent = None, flags = QtCore.Qt.WindowFlags(0)):
    60     
    61         super(Chooser, self).__init__(parent, flags)
    62         self.setWindowTitle('OpenSecuirty Launch Application')
    63         self.setup_ui()
    64         
    65         # positionate ourself central
    66         screen = QtGui.QDesktopWidget().screenGeometry()
    67         self.resize(self.geometry().width() * 1.25, self.geometry().height())
    68         size = self.geometry()
    69         self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
    70         
    71         self._vms = [ { 'name': 'SecurityDVM0', 'ip': '192.168.56.101' } ]
    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         v = str(self._cbVM.currentText())
   190         for vm in self._vms:
   191             if v == vm['name']:
   192                 return vm['ip']
   193         return v
   194         
   195     vm = property(vm_get)
   196         
   197         
   198 def ask_user():
   199     """ask the user for VM and app to start"""
   200     
   201     # launch Qt
   202     app = QtGui.QApplication(sys.argv)
   203     
   204     # prebuild the pixmap cache: fetch all jpg, png and jpeg images and load them
   205     image_path = os.path.join(Environment("OpenSecurity").data_path, '..', 'gfx')
   206     for file in os.listdir(image_path):
   207         if file.lower().rpartition('.')[2] in ('jpg', 'png', 'jpeg'):
   208             QtGui.QPixmapCache.insert(file.lower().rpartition('.')[0], QtGui.QPixmap(os.path.join(image_path, file)))
   209             
   210     # we should have now our application icon
   211     app.setWindowIcon(QtGui.QIcon(QtGui.QPixmapCache.find('opensecurity_icon_64')))
   212     
   213     # pop up the dialog
   214     dlg = Chooser()
   215     dlg.show()
   216     app.exec_()
   217     
   218     if dlg.result() == QtGui.QDialog.Accepted:
   219         return dlg.vm, dlg.app
   220 
   221     return '', ''
   222     
   223 
   224 def main():
   225     """entry point"""
   226     
   227     # parse command line
   228     parser = argparse.ArgumentParser(description = 'OpenSecurity Launcher: run application in VM')
   229     parser.add_argument('ip', metavar='IP', help='IP of Virtual Machine', nargs='?', type=str, default='')
   230     parser.add_argument('command', metavar='COMMAND', help='Full path of command and arguments to start inside VM', nargs='?', type=str, default='')
   231     args = parser.parse_args()
   232     
   233     # we must have at least all or none set
   234     set_ip = args.ip != ''
   235     set_command = args.command != ''
   236     set_ALL = set_ip and set_command
   237     set_NONE = (not set_ip) and (not set_command)
   238     if (not set_ALL) and (not set_NONE):
   239         sys.stderr.write("Please specify ip and command or none.\n")
   240         sys.stderr.write("Type '--help' for help.\n")
   241         sys.exit(1)
   242         
   243     # check if we need to ask the user
   244     if set_NONE:
   245         args.ip, args.command = ask_user()
   246         
   247     # still no IP? --> no chance, over and out!
   248     if args.ip == '':
   249         sys.exit(0)
   250         
   251     # ensure we have our X11 running
   252     #Cygwin.start_X11()
   253     
   254     # call the OpenSecurity Admin to launch our progie =)
   255     url_vm = urllib.quote(args.ip)
   256     url_command = urllib.quote(args.command)
   257     print(url_vm)
   258     print(url_command)
   259     
   260     # user_at_guest = args.user + '@' + args.ip
   261     # ssh = 'DISPLAY=:0 /usr/bin/ssh -Y ' + user_at_guest + ' ' + args.command
   262     # print(ssh)
   263     
   264     # # off we go!
   265     # Cygwin()(['/bin/bash', '--login', '-i', '-c', ssh], None, None, None)
   266 
   267     
   268 # start
   269 if __name__ == "__main__":
   270     main()
   271