8b58b0c45477df66609f2d334bb2539e6d57202f
1#
2# sshd.py
3#
4# Find number of ssh logins and authorised users
5#
6
7import re
8from systemd import journal
9
10from logparse.formatting import *
11from logparse.util import resolve
12from logparse import config
13
14import logging
15logger = logging.getLogger(__name__)
16
17def parse_log():
18
19 logger.debug("Starting sshd section")
20 section = Section("ssh")
21
22 j = journal.Reader()
23 j.this_boot()
24 j.log_level(journal.LOG_DEBUG)
25 j.add_match(_COMM="sshd")
26
27 messages = [entry["MESSAGE"] for entry in j if "MESSAGE" in entry]
28
29 login_data = Data("successful", [])
30 invalid_data = Data("invalid", [])
31 failed_data = Data("failed", [])
32
33 for msg in messages:
34
35 if "Accepted publickey" in msg:
36 entry = re.search('^.*publickey\sfor\s(\w*)\sfrom\s(\S*)', msg) # [('user', 'ip')]
37 user = entry.group(1)
38 ip = entry.group(2)
39
40 userhost = user + '@' + resolve(ip, fqdn=config.prefs['sshd']['resolve-domains'])
41 login_data.items.append(userhost)
42
43 elif "Connection closed by authenticating user root" in msg:
44 entry = re.search('^.*Connection closed by authenticating user (\S+) (\S+)', msg) # [('user', 'ip')]
45 user = entry.group(1)
46 ip = entry.group(2)
47
48 userhost = user + '@' + resolve(ip, fqdn=config.prefs['sshd']['resolve-domains'])
49 failed_data.items.append(userhost)
50
51 elif "Invalid user" in msg:
52 entry = re.search('^.*Invalid user (\S+) from (\S+).*', msg) # [('user', 'ip')]
53 user = entry.group(1)
54 ip = entry.group(2)
55
56 userhost = user + '@' + resolve(ip, fqdn=config.prefs['sshd']['resolve-domains'])
57 invalid_data.items.append(userhost)
58
59 login_data.subtitle = plural("successful login", len(login_data.items)) + " from"
60 login_data.orderbyfreq()
61 login_data.truncl(config.prefs['maxlist'])
62
63 invalid_data.subtitle = plural("attempted login", len(invalid_data.items))
64 invalid_data.orderbyfreq()
65 invalid_data.subtitle += plural(" from invalid user", len(invalid_data.items), False)
66 invalid_data.truncl(config.prefs['maxlist'])
67
68 failed_data.subtitle = plural("failed login", len(failed_data.items)) + " from"
69 failed_data.orderbyfreq()
70 failed_data.truncl(config.prefs['maxlist'])
71
72 section.append_data(login_data)
73 section.append_data(invalid_data)
74 section.append_data(failed_data)
75
76 logger.info("Finished sshd section")
77 return section