def config_init(self, *args, **kw): """ config:init [] Initializes a default configuration in the current config path we've opened. """ host = self.__config.add_section('lsso') host.set('api_endpoint', 'https://example.org/auth/api') redc = self.__config.add_section('redis') redc.set('host', 'example.org') redc.set('port', 6379) redc.set('secret', 'secret') redc.set('database', 0) redc.set('key_prefix', 'lsso:') credential = self.__config.add_section('credentials') credential.set('username', 'admin') credential.set('token', 'lsso auth token') lb = self.__config.add_section('log_buckets') lb.set('auth', 'log:auth') lb.set('session', 'log:session') lb.set('api', 'log:api') print "{}".format( ascii.style_text( ascii.STYLE_BOLD, "Configuration initialized at {}.".format( ascii.style_text(ascii.FG_GREEN, self.__config_path)))) self.__config.save(self.__config_path)
def config_init(self, *args, **kw): """ config:init [] Initializes a default configuration in the current config path we've opened. """ host = self.__config.add_section('lsso') host.set('api_endpoint', 'https://example.org/auth/api') redc = self.__config.add_section('redis') redc.set('host', 'example.org') redc.set('port', 6379) redc.set('secret', 'secret') redc.set('database', 0) redc.set('key_prefix', 'lsso:') credential = self.__config.add_section('credentials') credential.set('username', 'admin') credential.set('token', 'lsso auth token') lb = self.__config.add_section('log_buckets') lb.set('auth', 'log:auth') lb.set('session', 'log:session') lb.set('api', 'log:api') print "{}".format( ascii.style_text(ascii.STYLE_BOLD, "Configuration initialized at {}.".format( ascii.style_text(ascii.FG_GREEN, self.__config_path)))) self.__config.save(self.__config_path)
def session_info(self, *args, **kw): """ session:info [session_id] Show all information for a session. Requires config section [redis] to be populated and valid. """ if 'args' in kw: argparser = kw['args'] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section('redis') rdc = redis.StrictRedis(host=redis_conf.get_string( 'host', 'localhost'), port=redis_conf.get_int('port', 6379), password=redis_conf.get_string('secret', None), db=redis_conf.get_int('database', 0)) rd_prefix = redis_conf.get_string('key_prefix', 'lsso:') try: session_id = argparser.parameters[2] except (IndexError) as e: print ascii.style_text( ascii.FG_RED, "session:info requires a session_id to query.") return False session_key = rd_prefix + "session:" + session_id session = rdc.hgetall(session_key) if not session: print ascii.style_text(ascii.FG_RED, "No such session: %s" % (session_id)) return False # Convert session[created] to datetime from Unix TS creat_ts = float(session['created']) try: session.update({ "created": datetime.datetime.fromtimestamp(creat_ts), }) except ValueError: pass expire_time = datetime.datetime.now() + datetime.timedelta( milliseconds=rdc.pttl(session_key)) session.update({"expires": expire_time}) print "%s ->" % (session_id) for k, v in session.iteritems(): print " %12s => %s" % (k, v)
def session_list(self, *args, **kw): """ session:list [--no-table] Lists all open LSSO sessions in Redis. Requires config section [redis] to be populated and valid. """ if 'args' in kw: argparser = kw['args'] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section('redis') rdc = redis.StrictRedis(host=redis_conf.get_string( 'host', 'localhost'), port=redis_conf.get_int('port', 6379), password=redis_conf.get_string('secret', None), db=redis_conf.get_int('database', 0)) rd_prefix = redis_conf.get_string('key_prefix', 'lsso:') session_list = rdc.keys(rd_prefix + "session:*") sessions = {} for session in session_list: stok = session.split(':')[2] session_data = rdc.hgetall(session) sessions.update({stok: session_data}) if len(sessions) == 0: print ascii.style_text(ascii.FG_RED, "No sessions open.") return False if argparser.options.get('no-table', False): for stok, sdat in sessions.iteritems(): print "%s\t%s\t%s" % (stok, sdat.get( 'username', 'unknown'), sdat.get('created', 'unknown')) else: headers = ["Session Token", "User", "Created"] tt = table.TextTable() tt.add_header_list(headers) rows = [] for stok, sdat in sessions.iteritems(): rows.append(( stok, sdat.get('username', 'unknown'), sdat.get('created', 'unknown'), )) tt.add_data_ztup(rows) for line in tt.format(): print line
def session_list(self, *args, **kw): """ session:list [--no-table] Lists all open LSSO sessions in Redis. Requires config section [redis] to be populated and valid. """ if "args" in kw: argparser = kw["args"] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section("redis") rdc = redis.StrictRedis( host=redis_conf.get_string("host", "localhost"), port=redis_conf.get_int("port", 6379), password=redis_conf.get_string("secret", None), db=redis_conf.get_int("database", 0), ) rd_prefix = redis_conf.get_string("key_prefix", "lsso:") session_list = rdc.keys(rd_prefix + "session:*") sessions = {} for session in session_list: stok = session.split(":")[2] session_data = rdc.hgetall(session) sessions.update({stok: session_data}) if len(sessions) == 0: print ascii.style_text(ascii.FG_RED, "No sessions open.") return False if argparser.options.get("no-table", False): for stok, sdat in sessions.iteritems(): print "%s\t%s\t%s" % (stok, sdat.get("username", "unknown"), sdat.get("created", "unknown")) else: headers = ["Session Token", "User", "Created"] tt = table.TextTable() tt.add_header_list(headers) rows = [] for stok, sdat in sessions.iteritems(): rows.append((stok, sdat.get("username", "unknown"), sdat.get("created", "unknown"))) tt.add_data_ztup(rows) for line in tt.format(): print line
def session_info(self, *args, **kw): """ session:info [session_id] Show all information for a session. Requires config section [redis] to be populated and valid. """ if "args" in kw: argparser = kw["args"] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section("redis") rdc = redis.StrictRedis( host=redis_conf.get_string("host", "localhost"), port=redis_conf.get_int("port", 6379), password=redis_conf.get_string("secret", None), db=redis_conf.get_int("database", 0), ) rd_prefix = redis_conf.get_string("key_prefix", "lsso:") try: session_id = argparser.parameters[2] except (IndexError) as e: print ascii.style_text(ascii.FG_RED, "session:info requires a session_id to query.") return False session_key = rd_prefix + "session:" + session_id session = rdc.hgetall(session_key) if not session: print ascii.style_text(ascii.FG_RED, "No such session: %s" % (session_id)) return False # Convert session[created] to datetime from Unix TS creat_ts = float(session["created"]) try: session.update({"created": datetime.datetime.fromtimestamp(creat_ts)}) except ValueError: pass expire_time = datetime.datetime.now() + datetime.timedelta(milliseconds=rdc.pttl(session_key)) session.update({"expires": expire_time}) print "%s ->" % (session_id) for k, v in session.iteritems(): print " %12s => %s" % (k, v)
def config_show(self, *args, **kw): """ config:show [] Prints the current configuration. """ for section_name in self.__config.sections: section = self.__config.get_section(section_name) print 'Section [{}]:'.format( ascii.style_text(ascii.FG_GREEN, section_name)) for key, value in section.iteritems(): print ' {} -> {}'.format( ascii.style_text(ascii.FG_LCYAN, key), ascii.style_text(ascii.FG_LPURPLE, value)) print ''
def config_get(self, *args, **kw): """ config:get [section].[key] Returns the named variable from the loaded configuration. """ args = args[1:] try: var_path = args[0] except: raise CommandModuleException("Missing argument(s).") var_path = var_path.split('.') if len(var_path) > 2: var_path = var_path[0:2] if len(var_path) == 1: # Only the section specifier is given section_name = var_path[0] if not self.__config.has_section(section_name): print "Unknown configuration section '{}'.".format( ascii.style_text(ascii.FG_GREEN, section_name)) return else: section = self.__config.get_section(section_name) print 'Section [{}]:'.format( ascii.style_text(ascii.FG_GREEN, section_name)) for key, value in section.iteritems(): print ' {} -> {}'.format(key, value) print elif len(var_path) == 2: # Section and key specifier were given. section_name = var_path[0] if not self.__config.has_section(section_name): print "Unknown configuration section '{}'.".format( ascii.style_text(ascii.FG_YELLOW, section_name)) return else: section = self.__config.get_section(section_name) print 'Section [{}]:'.format( ascii.style_text(ascii.FG_GREEN, section_name)) key = var_path[1] value = section.get_string(key, None) if not value: value = ascii.style_text(ascii.FG_RED, 'unset') print ' {} -> {}'.format(key, value)
def session_revoke(self, *args, **kw): """ session:revoke [session_id] Revoke a session with the given id. Requires config section [redis] to be populated and valid. """ if 'args' in kw: argparser = kw['args'] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section('redis') rdc = redis.StrictRedis(host=redis_conf.get_string( 'host', 'localhost'), port=redis_conf.get_int('port', 6379), password=redis_conf.get_string('secret', None), db=redis_conf.get_int('database', 0)) rd_prefix = redis_conf.get_string('key_prefix', 'lsso:') try: session_id = argparser.parameters[2] except (IndexError) as e: print ascii.style_text( ascii.FG_RED, "session:revoke requires a session_id to revoke.") return False session_key = rd_prefix + "session:" + session_id session_exists = rdc.exists(session_key) if not session_exists: print ascii.style_text(ascii.FG_RED, "No such session: %s" % (session_id)) return False deleted = rdc.delete(session_key) if deleted != 1: print ascii.style_text( ascii.FG_RED, "Could not revoke session: %s" % (session_id)) return False print ascii.style_text(ascii.FG_GREEN, "Revoked session: %s" % (session_id))
def show_module(self, *args, **kw): """ Displays help for a single module. """ if 'args' in kw: argparser = kw['args'] else: argparser = self.__loader.get_argument_parser() try: mod_name = args[1] except: self.all_help(args = argparser) return if len(mod_name) == 0: self.all_help(args = argparser) return exec_name = sys.argv[0] print "{:4s}: version {:s}: {:s}".format( ascii.style_text(ascii.STYLE_BOLD, exec_name), ascii.style_text(ascii.STYLE_UNDERSCORE, lssoctl.__version__), ascii.style_text(ascii.FG_GREEN, lssoctl.__description__)) print "{:>24s}".format( ascii.style_text(ascii.FG_GREEN, 'Subcommands')) modules = self.__loader.modules for module in modules: if module.get_base() == mod_name: for sub, helpstr in module.get_help().iteritems(): command = ':'.join([module.get_base(), sub]) helplst = helpstr.splitlines() if len(helplst) == 1: print "{:>36s} {:<64s}".format( ascii.style_text(ascii.STYLE_UNDERSCORE, command), helpstr) else: print "{:>36s} {:<64s}".format( ascii.style_text(ascii.STYLE_UNDERSCORE, command), ascii.style_text(ascii.STYLE_OFF, helplst[0].lstrip())) for line in helplst[1:]: print "{:>28s} {:<64s}".format( "", ascii.style_text(ascii.STYLE_OFF, line.lstrip())) print ""
def session_revoke(self, *args, **kw): """ session:revoke [session_id] Revoke a session with the given id. Requires config section [redis] to be populated and valid. """ if "args" in kw: argparser = kw["args"] else: argparser = self.__loader.get_argument_parser() redis_conf = self.__config.get_section("redis") rdc = redis.StrictRedis( host=redis_conf.get_string("host", "localhost"), port=redis_conf.get_int("port", 6379), password=redis_conf.get_string("secret", None), db=redis_conf.get_int("database", 0), ) rd_prefix = redis_conf.get_string("key_prefix", "lsso:") try: session_id = argparser.parameters[2] except (IndexError) as e: print ascii.style_text(ascii.FG_RED, "session:revoke requires a session_id to revoke.") return False session_key = rd_prefix + "session:" + session_id session_exists = rdc.exists(session_key) if not session_exists: print ascii.style_text(ascii.FG_RED, "No such session: %s" % (session_id)) return False deleted = rdc.delete(session_key) if deleted != 1: print ascii.style_text(ascii.FG_RED, "Could not revoke session: %s" % (session_id)) return False print ascii.style_text(ascii.FG_GREEN, "Revoked session: %s" % (session_id))
def config_set(self, *args, **kw): """ config:set [section].[key] [value] Sets the named variable in the user configuration. """ args = args[1:] try: var_path = args[0] except: raise CommandModuleException("Missing argument(s).") try: var_value = ' '.join(args[1:]) except: raise CommandModuleException("Missing argument(s).") var_path = var_path.split('.') if len(var_path) > 2: var_path = var_path[0:2] if len(var_path) == 1: # Only the section specifier is given print 'Must provide a configuration node in the form of {} to set a value.'.format( ascii.style_text(ascii.BG_YELLOW, "section.key")) return elif len(var_path) == 2: # Section and key specifier were given. section_name = var_path[0] if not self.__config.has_section(section_name): print "Unknown configuration section '{}'.".format( ascii.style_text(ascii.FG_YELLOW, section_name)) return else: section = self.__config.get_section(section_name) print 'Section [{}]:'.format( ascii.style_text(ascii.FG_GREEN, section_name)) key = var_path[1] value = section.get_string(key, None) if not value: value = ascii.style_text(ascii.FG_RED, 'unset') section.set(key, var_value) print ' {} => {} -> {}'.format( key, ascii.style_text(ascii.FG_RED, value), ascii.style_text(ascii.FG_GREEN, var_value)) self.__config.save(self.__config_path)
def all_help(self, *args, **kw): """ Displays help for all registered modules. """ if 'args' in kw: argparser = kw['args'] else: argparser = self.__loader.get_argument_parser() exec_name = sys.argv[0] if not argparser.exec_file else argparser.exec_file print "{:4s}: version {:s}: {:s}".format( ascii.style_text(ascii.STYLE_BOLD, exec_name), ascii.style_text(ascii.STYLE_UNDERSCORE, lssoctl.__version__), ascii.style_text(ascii.FG_GREEN, lssoctl.__description__)) print "{:>24s}".format( ascii.style_text(ascii.FG_GREEN, 'Arguments')) args = argparser.get_option_descriptions() for option, description in args.iteritems(): print "{:>36s} {:<64s}".format( ascii.style_text(ascii.STYLE_BOLD, option), ascii.style_text(ascii.STYLE_OFF, description)) print "{:>24s}".format( ascii.style_text(ascii.FG_GREEN, 'Subcommands')) modules = self.__loader.modules for module in sorted(modules, key = lambda module: module.BASE): for sub, helpstr in module.get_help().iteritems(): command = ':'.join([module.get_base(), sub]) helplst = helpstr.splitlines() if len(helplst) == 1: print "{:>36s} {:<64s}".format( ascii.style_text(ascii.STYLE_UNDERSCORE, command), helpstr) else: print "{:>36s} {:<64s}".format( ascii.style_text(ascii.STYLE_UNDERSCORE, command), ascii.style_text(ascii.STYLE_OFF, helplst[0].lstrip())) for line in helplst[1:]: print "{:>28s} {:<64s}".format( "", ascii.style_text(ascii.STYLE_OFF, line.lstrip())) print ""