87d4be71d783906d5980f540d75ccad859410539
   1#
   2#   sudo.py
   3#   
   4#   Get number of sudo sessions for each user
   5#
   6
   7import re
   8
   9from ..formatting import *
  10from ..util import readlog, resolve
  11from .. import config
  12
  13import logging
  14logger = logging.getLogger(__name__)
  15
  16def parse_log():
  17    logger.debug("Starting sudo section")
  18    section = Section("sudo")
  19    logger.debug("Searching for matches in {0}".format(config.prefs['logs']['auth']))
  20    umatches = re.findall('.*sudo:session\): session opened.*', readlog(config.prefs['logs']['auth']))
  21    num = sum(1 for line in umatches)    # total number of sessions
  22    users = []
  23    data = []
  24    for match in umatches:
  25        user = re.search('.*session opened for user root by (\S*)\(uid=.*\)', match).group(1)
  26        exists = [i for i, item in enumerate(users) if re.search(user, item[0])]
  27        if (exists == []):
  28            users.append([user, 1])
  29        else:
  30            users[exists[0]][1] += 1
  31    commands = []
  32    cmatches = re.findall('sudo:.*COMMAND\=(.*)', readlog(config.prefs['logs']['auth']))
  33    for cmd in cmatches:
  34        commands.append(cmd)
  35    logger.debug("Finished parsing sudo sessions")
  36
  37    auth_data = Data(subtitle=plural("sudo session", num) + " for")
  38
  39    if (len(users) == 1):
  40        logger.debug("found " + str(num) + " sudo session(s) for user " + str(users[0]))
  41        auth_data.subtitle += ' ' + users[0][0]
  42    else:
  43        for user in users:
  44            auth_data.items.append(user[0] + ' (' + str(user[1]) + ')')
  45        logger.debug("found " + str(num) + " sudo sessions for users " + str(data))
  46    section.append_data(auth_data)
  47
  48    if (len(commands) > 0):
  49        command_data = Data(subtitle="top sudo commands")
  50        commands = backticks(commands)
  51        command_data.items = commands
  52        command_data.orderbyfreq()
  53        command_data.truncl(config.prefs['maxcmd'])
  54        section.append_data(command_data)
  55
  56    logger.info("Finished sudo section")
  57
  58    return section