#!/usr/bin/python # # Copyright (C) 2014 Simo Sorce # # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from ipsilon.login.common import LoginMgrsInstall from ipsilon.info.common import InfoProviderInstall from ipsilon.providers.common import ProvidersInstall from ipsilon.helpers.common import EnvHelpersInstall from ipsilon.util.data import UserStore from ipsilon.tools import files import ConfigParser import argparse import cherrypy import logging import os import pwd import shutil import socket import subprocess import sys import time TEMPLATES = '/usr/share/ipsilon/templates/install' CONFDIR = '/etc/ipsilon' DATADIR = '/var/lib/ipsilon' HTTPDCONFD = '/etc/httpd/conf.d' BINDIR = '/usr/sbin' STATICDIR = '/usr/share/ipsilon' WSGI_SOCKET_PREFIX = None class ConfigurationError(Exception): def __init__(self, message): super(ConfigurationError, self).__init__(message) self.message = message def __str__(self): return repr(self.message) #Silence cherrypy logging to screen cherrypy.log.screen = False # Regular logging LOGFILE = '/var/log/ipsilon-install.log' logger = logging.getLogger() def openlogs(): global logger # pylint: disable=W0603 if os.path.isfile(LOGFILE): try: created = '%s' % time.ctime(os.path.getctime(LOGFILE)) shutil.move(LOGFILE, '%s.%s' % (LOGFILE, created)) except IOError: pass logger = logging.getLogger() try: lh = logging.FileHandler(LOGFILE) except IOError, e: print >> sys.stderr, 'Unable to open %s (%s)' % (LOGFILE, str(e)) lh = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('[%(asctime)s] %(message)s') lh.setFormatter(formatter) logger.addHandler(lh) def install(plugins, args): logger.info('Installation initiated') now = time.strftime("%Y%m%d%H%M%S", time.gmtime()) instance_conf = os.path.join(CONFDIR, args['instance']) logger.info('Installing default config files') ipsilon_conf = os.path.join(instance_conf, 'ipsilon.conf') idp_conf = os.path.join(instance_conf, 'idp.conf') args['httpd_conf'] = os.path.join(HTTPDCONFD, 'ipsilon-%s.conf' % args['instance']) args['data_dir'] = os.path.join(DATADIR, args['instance']) args['public_data_dir'] = os.path.join(args['data_dir'], 'public') args['wellknown_dir'] = os.path.join(args['public_data_dir'], 'well-known') if os.path.exists(ipsilon_conf): shutil.move(ipsilon_conf, '%s.bakcup.%s' % (ipsilon_conf, now)) if os.path.exists(idp_conf): shutil.move(idp_conf, '%s.backup.%s' % (idp_conf, now)) if not os.path.exists(instance_conf): os.makedirs(instance_conf, 0700) confopts = {'instance': args['instance'], 'datadir': args['data_dir'], 'publicdatadir': args['public_data_dir'], 'wellknowndir': args['wellknown_dir'], 'sysuser': args['system_user'], 'ipsilondir': BINDIR, 'staticdir': STATICDIR, 'admindb': args['database_url'] % { 'datadir': args['data_dir'], 'dbname': 'adminconfig'}, 'usersdb': args['database_url'] % { 'datadir': args['data_dir'], 'dbname': 'userprefs'}, 'transdb': args['database_url'] % { 'datadir': args['data_dir'], 'dbname': 'transactions'}, 'secure': "False" if args['secure'] == "no" else "True", 'debugging': "True" if args['server_debugging'] else "False"} # Testing database sessions if 'session_type' in args: confopts['sesstype'] = args['session_type'] else: confopts['sesstype'] = 'file' if 'session_dburi' in args: confopts['sessopt'] = 'dburi' confopts['sessval'] = args['session_dburi'] else: confopts['sessopt'] = 'path' confopts['sessval'] = os.path.join(args['data_dir'], 'sessions') # Whetehr to disable security (for testing) if args['secure'] == 'no': confopts['secure'] = "False" confopts['sslrequiressl'] = "" else: confopts['secure'] = "True" confopts['sslrequiressl'] = " SSLRequireSSL" if WSGI_SOCKET_PREFIX: confopts['wsgi_socket'] = 'WSGISocketPrefix %s' % WSGI_SOCKET_PREFIX else: confopts['wsgi_socket'] = '' files.write_from_template(ipsilon_conf, os.path.join(TEMPLATES, 'ipsilon.conf'), confopts) files.write_from_template(idp_conf, os.path.join(TEMPLATES, 'idp.conf'), confopts) if not os.path.exists(args['httpd_conf']): os.symlink(idp_conf, args['httpd_conf']) if not os.path.exists(args['public_data_dir']): os.makedirs(args['public_data_dir'], 0755) if not os.path.exists(args['wellknown_dir']): os.makedirs(args['wellknown_dir'], 0755) sessdir = os.path.join(args['data_dir'], 'sessions') if not os.path.exists(sessdir): os.makedirs(sessdir, 0700) data_conf = os.path.join(args['data_dir'], 'ipsilon.conf') if not os.path.exists(data_conf): os.symlink(ipsilon_conf, data_conf) # Load the cherrypy config from the newly installed file so # that db paths and all is properly set before configuring # components cherrypy.config.update(ipsilon_conf) # Move pre-existing admin db away admin_db = cherrypy.config['admin.config.db'] if os.path.exists(admin_db): shutil.move(admin_db, '%s.backup.%s' % (admin_db, now)) # Rebuild user db users_db = cherrypy.config['user.prefs.db'] if os.path.exists(users_db): shutil.move(users_db, '%s.backup.%s' % (users_db, now)) db = UserStore() db.save_user_preferences(args['admin_user'], {'is_admin': 1}) logger.info('Configuring environment helpers') for plugin_name in plugins['Environment Helpers']: plugin = plugins['Environment Helpers'][plugin_name] if plugin.configure_server(args) == False: print 'Configuration of environment helper %s failed' % plugin_name logger.info('Configuring login managers') for plugin_name in args['lm_order']: plugin = plugins['Login Managers'][plugin_name] if plugin.configure(args) == False: print 'Configuration of login manager %s failed' % plugin_name logger.info('Configuring Info provider') for plugin_name in plugins['Info Provider']: plugin = plugins['Info Provider'][plugin_name] if plugin.configure(args) == False: print 'Configuration of info provider %s failed' % plugin_name logger.info('Configuring Authentication Providers') for plugin_name in plugins['Auth Providers']: plugin = plugins['Auth Providers'][plugin_name] if plugin.configure(args) == False: print 'Configuration of auth provider %s failed' % plugin_name # Fixup permissions so only the ipsilon user can read these files files.fix_user_dirs(instance_conf, opts['system_user']) files.fix_user_dirs(args['data_dir'], opts['system_user']) try: subprocess.call(['/usr/sbin/restorecon', '-R', args['data_dir']]) except Exception: # pylint: disable=broad-except pass def uninstall(plugins, args): logger.info('Uninstallation initiated') instance_conf = os.path.join(CONFDIR, args['instance']) httpd_conf = os.path.join(HTTPDCONFD, 'ipsilon-%s.conf' % args['instance']) data_dir = os.path.join(DATADIR, args['instance']) if not os.path.exists(instance_conf): raise Exception('Could not find instance %s configuration' % args['instance']) if not os.path.exists(httpd_conf): raise Exception('Could not find instance %s httpd configuration' % args['instance']) if not args['yes']: sure = raw_input(('Are you certain you want to erase instance %s ' + '[yes/NO]: ') % args['instance']) if sure != 'yes': raise Exception('Aborting') logger.info('Removing environment helpers') for plugin_name in plugins['Environment Helpers']: plugin = plugins['Environment Helpers'][plugin_name] if plugin.unconfigure(args) == False: print 'Removal of environment helper %s failed' % plugin_name logger.info('Removing login managers') for plugin_name in args['lm_order']: plugin = plugins['Login Managers'][plugin_name] if plugin.unconfigure(args) == False: print 'Removal of login manager %s failed' % plugin_name logger.info('Removing Info providers') for plugin_name in plugins['Info Provider']: plugin = plugins['Info Provider'][plugin_name] if plugin.unconfigure(args) == False: print 'Removal of info provider %s failed' % plugin_name logger.info('Removing Authentication Providers') for plugin_name in plugins['Auth Providers']: plugin = plugins['Auth Providers'][plugin_name] if plugin.unconfigure(args) == False: print 'Removal of auth provider %s failed' % plugin_name logger.info('Removing httpd configuration') os.remove(httpd_conf) logger.info('Erasing instance configuration') shutil.rmtree(instance_conf) logger.info('Erasing instance data') shutil.rmtree(data_dir) logger.info('Uninstalled instance %s' % args['instance']) def find_plugins(): plugins = { 'Environment Helpers': EnvHelpersInstall().plugins, 'Login Managers': LoginMgrsInstall().plugins, 'Info Provider': InfoProviderInstall().plugins, 'Auth Providers': ProvidersInstall().plugins } return plugins def parse_config_profile(args): config = ConfigParser.RawConfigParser() files = config.read(args['config_profile']) if len(files) == 0: raise ConfigurationError('Config Profile file %s not found!' % args['config_profile']) if 'globals' in config.sections(): G = config.options('globals') for g in G: val = config.get('globals', g) if g in globals(): globals()[g] = val else: for k in globals().keys(): if k.lower() == g.lower(): globals()[k] = val break if 'arguments' in config.sections(): A = config.options('arguments') for a in A: args[a] = config.get('arguments', a) return args def parse_args(plugins): parser = argparse.ArgumentParser(description='Ipsilon Install Options') parser.add_argument('--version', action='version', version='%(prog)s 0.1') parser.add_argument('-o', '--login-managers-order', dest='lm_order', help='Comma separated list of login managers') parser.add_argument('--hostname', help="Machine's fully qualified host name") parser.add_argument('--instance', default='idp', help="IdP instance name, each is a separate idp") parser.add_argument('--system-user', default='ipsilon', help="User account used to run the server") parser.add_argument('--admin-user', default='admin', help="User account that is assigned admin privileges") parser.add_argument('--database-url', default='sqlite:///%(datadir)s/%(dbname)s.sqlite', help="The (templatized) database URL to use") parser.add_argument('--secure', choices=['yes', 'no'], default='yes', help="Turn on all security checks") parser.add_argument('--config-profile', default=None, help="File containing install options") parser.add_argument('--server-debugging', action='store_true', help="Enable debugging") parser.add_argument('--uninstall', action='store_true', help="Uninstall the server and all data") parser.add_argument('--yes', action='store_true', help="Always answer yes") lms = [] for plugin_group in plugins: group = parser.add_argument_group(plugin_group) for plugin_name in plugins[plugin_group]: plugin = plugins[plugin_group][plugin_name] if plugin.ptype == 'login': lms.append(plugin.name) plugin.install_args(group) args = vars(parser.parse_args()) if args['config_profile']: args = parse_config_profile(args) if not args['hostname']: args['hostname'] = socket.getfqdn() if len(args['hostname'].split('.')) < 2: raise ConfigurationError('Hostname: %s is not a FQDN') try: pwd.getpwnam(args['system_user']) except KeyError: raise ConfigurationError('User: %s not found on the system') if args['lm_order'] is None: args['lm_order'] = [] for name in lms: if args[name] == 'yes': args['lm_order'].append(name) else: args['lm_order'] = args['lm_order'].split(',') if len(args['lm_order']) == 0: #force the basic pam provider if nothing else is selected if 'pam' not in args: parser.print_help() sys.exit(-1) args['lm_order'] = ['pam'] args['pam'] = 'yes' #FIXME: check instance is only alphanums return args if __name__ == '__main__': opts = [] out = 0 openlogs() try: fplugins = find_plugins() opts = parse_args(fplugins) logger.setLevel(logging.DEBUG) logger.info('Intallation arguments:') for k in sorted(opts.iterkeys()): logger.info('%s: %s', k, opts[k]) if 'uninstall' in opts and opts['uninstall'] is True: if not os.path.exists(os.path.join(CONFDIR, opts['instance'])): print 'Instance %s could not be found' % opts['instance'] sys.exit(0) uninstall(fplugins, opts) else: install(fplugins, opts) except Exception, e: # pylint: disable=broad-except logger.exception(e) if 'uninstall' in opts and opts['uninstall'] is True: print 'Uninstallation aborted.' else: print 'Installation aborted.' print 'See log file %s for details' % LOGFILE out = 1 finally: if out == 0: if 'uninstall' in opts and opts['uninstall'] is True: print 'Uninstallation complete.' else: print 'Installation complete.' print 'Please restart HTTPD to enable the IdP instance.' sys.exit(out) uration */ #define MAX3100_RC (1 << 14) /* read configuration */ #define MAX3100_WD (2 << 14) /* write data */ #define MAX3100_RD (0 << 14) /* read data */ /* configuration register bits */ #define MAX3100_FEN (1 << 13) /* FIFO enable */ #define MAX3100_SHDN (1 << 12) /* shutdown bit */ #define MAX3100_TM (1 << 11) /* T bit irq mask */ #define MAX3100_RM (1 << 10) /* R bit irq mask */ #define MAX3100_PM (1 << 9) /* P bit irq mask */ #define MAX3100_RAM (1 << 8) /* mask for RA/FE bit */ #define MAX3100_IR (1 << 7) /* IRDA timing mode */ #define MAX3100_ST (1 << 6) /* transmit stop bit */ #define MAX3100_PE (1 << 5) /* parity enable bit */ #define MAX3100_L (1 << 4) /* Length bit */ #define MAX3100_B_MASK (0x000F) /* baud rate bits mask */ #define MAX3100_B(x) ((x) & 0x000F) /* baud rate select bits */ /* data register bits (write) */ #define MAX3100_TE (1 << 10) /* transmit enable bit (active low) */ #define MAX3100_RTS (1 << 9) /* request-to-send bit (inverted ~RTS pin) */ /* data register bits (read) */ #define MAX3100_RA (1 << 10) /* receiver activity when in shutdown mode */ #define MAX3100_FE (1 << 10) /* framing error when in normal mode */ #define MAX3100_CTS (1 << 9) /* clear-to-send bit (inverted ~CTS pin) */ /* data register bits (both directions) */ #define MAX3100_R (1 << 15) /* receive bit */ #define MAX3100_T (1 << 14) /* transmit bit */ #define MAX3100_P (1 << 8) /* parity bit */ #define MAX3100_D_MASK 0x00FF /* data bits mask */ #define MAX3100_D(x) ((x) & 0x00FF) /* data bits */ /* these definitions are valid only for fOSC = 3.6864MHz */ #define MAX3100_B_230400 MAX3100_B(0) #define MAX3100_B_115200 MAX3100_B(1) #define MAX3100_B_57600 MAX3100_B(2) #define MAX3100_B_38400 MAX3100_B(9) #define MAX3100_B_19200 MAX3100_B(10) #define MAX3100_B_9600 MAX3100_B(11) #define MAX3100_B_4800 MAX3100_B(12) #define MAX3100_B_2400 MAX3100_B(13) #define MAX3100_B_1200 MAX3100_B(14) #define MAX3100_B_600 MAX3100_B(15) /**************************************************************/ static inline unsigned int max3100_transfer(unsigned int val) { unsigned int rx; int b; MAX3100_SPI_CLK(0); MAX3100_CS(0); rx = 0; b = 16; while (--b >= 0) { MAX3100_SPI_TXD(val & 0x8000); val <<= 1; MAX3100_SPI_CLK_TOGGLE(); udelay(1); rx <<= 1; if (MAX3100_SPI_RXD()) rx |= 1; MAX3100_SPI_CLK_TOGGLE(); udelay(1); } MAX3100_SPI_CLK(1); MAX3100_CS(1); return rx; } /**************************************************************/ /* must be power of 2 */ #define RXFIFO_SZ 16 static int rxfifo_cnt; static int rxfifo_in; static int rxfifo_out; static unsigned char rxfifo_buf[16]; static void max3100_serial_putc_raw(int c) { unsigned int rx; while (((rx = max3100_transfer(MAX3100_RC)) & MAX3100_T) == 0) WATCHDOG_RESET(); rx = max3100_transfer(MAX3100_WD | (c & 0xff)); if ((rx & MAX3100_RD) != 0 && rxfifo_cnt < RXFIFO_SZ) { rxfifo_cnt++; rxfifo_buf[rxfifo_in++] = rx & 0xff; rxfifo_in &= RXFIFO_SZ - 1; } } static int max3100_serial_getc(void) { int c; unsigned int rx; while (rxfifo_cnt == 0) { rx = max3100_transfer(MAX3100_RD); if ((rx & MAX3100_R) != 0) { do { rxfifo_cnt++; rxfifo_buf[rxfifo_in++] = rx & 0xff; rxfifo_in &= RXFIFO_SZ - 1; if (rxfifo_cnt >= RXFIFO_SZ) break; } while (((rx = max3100_transfer(MAX3100_RD)) & MAX3100_R) != 0); } WATCHDOG_RESET(); }