1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/python

# Written by Daniel Schmidt, GPLv3 or later
# Simple CGI I wrote to parse the AAA log into readable information
# Not perfect
# Job == Networker; Job != Programmer


# Import the CGI module
import cgi, sys, re, datetime, sha
from socket import gethostbyname,gethostbyaddr
import cgitb; cgitb.enable()

# Required header that tells the browser how to render the HTML.
print "Content-Type: text/html\n\n"

dict_month = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul',
        8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
ignore_ciscoworks = True
# Users that should be ignored
ignore_users = ['rancid']
# Ignore the lines we don't care about
# Still used somewhere
ignore_keys =\
['start_time','stop_time','elapsed_time','service','reason','timezone']
# Encrypted password.  
# How to get it:
#$ python
#Python 2.4.3 (#1, Jan  9 2013, 06:47:03) 
#[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
#Type "help", "copyright", "credits" or "license" for more
#information.
#>>> import sha
#>>> sha.new("stupid_pass").hexdigest()
#'591d0ed247f1b8f2cdb4755abea927bf6db9a4a2'
#>>> 

glob_pass = '<Fill_THIS_IN>'
tac_log = "/var/log/tacacs"

# Define function to generate HTML form.
def generate_form():
    today = datetime.date.today()
    print "<HTML>\n"
    print "<HEAD>\n"
    print "\t<TITLE>Search Tacacs</TITLE>\n"
    print "</HEAD>\n"
    print "<BODY BGCOLOR = white>\n"
    print "\t<H3>Search Tacacs Log for Any Device</H3>\n"
    print "\t<TABLE BORDER = 0>\n"
    print "\t\t<FORM METHOD = post ACTION = \
    \"parse.cgi\">\n"
    print "\t\t<TR><TH>Security Password:</TH><TD><INPUT type = password \
    name = \"ourpass\" value = \"\"></TD><TR>\n"
    print "\t\t<TR><TH>Loopback address of Device?(blank for any):</TH><TD><INPUT type = text \
    name = \"device\" value = \"\"></TD><TR>\n"
    print "\t\t<TR><TH>Please enter the month(1-12), NO regular expressions:</TH><TD><INPUT type = text \
    name = \"month\" value = \"%s\"></TD><TR>\n" % (today.month)
    print "\t\t<TR><TH>Please enter the day(1-31) OR regular expression:</TH><TD><INPUT type = text name = \
    \"day\" value = \"%s\"></TD></TR>\n" % (today.day)
    print "\t</TABLE>\n"
    print "\t<INPUT TYPE = hidden NAME = \"action\" VALUE = \
    \"display\">\n"
    print "\t<INPUT TYPE = submit VALUE = \"Enter\">\n"
    print "\t<INPUT TYPE = hidden NAME = \"help\" VALUE = \
    \"example\">\n"
    # To figure out: No seperate file for help.py!!
    print "\t<INPUT TYPE = button VALUE = \"Examples\" onClick = \"window.open('help.py','Examples', \
    'width=600,height=420')\">"
    print "\t<INPUT TYPE = checkbox  NAME = \"ignore_user\" VALUE = \"on\">Show rancid/others (Long output)"
    print "\t</FORM>\n"
    print "</BODY>\n"
    print "</HTML>\n"

def nslooky(ip):
        try:
                output = gethostbyname(ip)
                return output
        except:
                output = "not found"
                return output

def nslooky2(ip):
        try:
                output = gethostbyaddr(ip)
                splt = output[0]
                splt = splt.split('.')
                return splt[0]
        except:
                output = "not found"
                return output

# Simple fix tabs function
# thrown together in 5 minutes
# If I had more than 5 minutes, I write better
def fix_tabs(the_word, the_limit):
    word_len = len(the_word)
    if word_len < the_limit:
        return (the_word + '\t')
    else:
        return the_word

# Trivial check of glob_password
def check_pass(the_pass):
    global glob_pass
    return (glob_pass == sha.new(the_pass).hexdigest())

def check_input(device,month,day,the_pass):
    ip_addr = device #lazy
    if not (check_pass(the_pass)):
        return None, "Wrong Password"
    if not month.isdigit():
        return None, (str(month) + "? That month is not even a digit!")
    month = int(month)
    if month > 12 or month < 1:
        return (None, str(month) + "? Look at that month again, fool!")
    if day.isdigit():
        if int(day) > 31 or int(day) < 1:
            return None, (str(day) + "? Look at that day again, fool!")
    if not ignore_ciscoworks:
        if not day.isdigit():
            return None, "NO!  Bad User!  You could have crashed the process!  \
                Uncheck 'Show rancid' if you want \
                to get results for more than 1 day!"
    if not device :
        if not day.isdigit():
            return None, "NO!  Bad User!  You could have crashed the process!  \
                We only use regular expression on the day for exact devices. \
                If you REALLY want to do a search like that, do it from \
                command line."
    if device :
        if not ip_addr[0].isdigit():
            ip_addr = nslooky(ip_addr)
            if ip_addr == "not found":
                return None, "Error in reslolving that dns."
            print device, " resolves to ", str(ip_addr), '<br>'
    return ip_addr, None

# Exact, but much more processor hungry
def match_it(line, match_comp):
        splt2 = line.split('\t')
        if len(splt2) > 2:
                if ((splt2[2] in ignore_users) and ignore_ciscoworks):
                        return False
                date = splt2[0]
                splt_date = date.split()
                short_line = (splt_date[1] + ' ' + splt_date[2])
                if match_comp.search(short_line):
                        return True
        return False

def do_search(ip_addr,month,day):
    f2 = open(tac_log)
    int_month = int(month)
    our_month = dict_month[int_month]
    is_fast = False
    if day.isdigit():
        is_fast = True
        if int(day) < 10:
            day = day.rjust(2)
    if is_fast:
        match = ("%s %s") % (our_month, day)
        lines = ''.join(line for line in f2 if match in line)
    else:   #better results, MUCH slower
        match = ("%s %s") % (our_month, day)
        match_comp = re.compile(match)
        lines = ''
        lines += ''.join(line for line in f2 if match_it(line,match_comp))
    splt = lines.split('\n')
    if ip_addr:
        compile_this = (".*%s %s.*%s\t") % (our_month, day, ip_addr)
        p = re.compile(compile_this)
#       lines2 = ''.join(line for line in splt if (re.match(p,line))) That don't work
        splt = [line for line in splt if p.search(line)]
#       NOW... I COULD make it slightly faster if I didn't use re at all
#       But, regular expression on the ip addr are useful
    return_lines = []
    prev_line = '' # Nexus sends duplicate entries
    for line in splt:
        if line == prev_line:
            continue
        prev_line = line
        if line.find(' (REDIRECT)') > -1:
            continue # Actually, nexus send triple entires
        splt2 = line.split('\t')
        if len(splt2) > 1:
            if ((splt2[2] in ignore_users) and ignore_ciscoworks):
                continue
            date = splt2[0]
            device = splt2[1]
            device = '%s(%s)' % (device,nslooky2(device))
            device = fix_tabs(device, 33)
            device = fix_tabs(device, 26)
            user = splt2[2]
            source = splt2[4]
            if source == "unknown":
                temp_split = splt2[6].split('=') # stupid nexus
                if temp_split[0] == "task_id":
                    if len(temp_split) > 1:
                        source = temp_split[1].split('@')[0]
            source = fix_tabs(source, 13)
            source = fix_tabs(source, 4)
            command = splt2[-1]
            command = command.split('=')
            # I'd make this cleaner, but I can't remember why I added it
            # and I don't have a Pix to test
            if command[0] != "cmd": # Stupid pix firewalls
                # And now that nexus is out, it's different too!
                if command[0] in ['service', 'addr']: # It's a nexus or WLC
                    command = splt2[-2]
                    command = command.split('=')
                    if command[0] in ignore_keys:
                        continue
                else:
                    command = splt2[-3] # Where PIX command is
                    command = command.split('=')
                    if command[0] != "cmd": # Stupid pix firewalls
                        continue
            command = command[1]
            command = command.replace('configure terminal ; ', '')
            command = command.rstrip()
            return_lines.append("%s\tDevice:%s\tUser:%s\tat:%s\t%s\n"
               % (date, device, user, source, command)),
    f2.close()
    return return_lines

# Define function display data.
def display_data(device,month,day,the_pass):
    print "<HTML>\n"
    print "<HEAD>\n"
    print "\t<TITLE>Info Form</TITLE>\n"
    print "</HEAD>\n"
    print "<BODY BGCOLOR = white>\n"
    ip_addr, checked = check_input(device,month,day,the_pass)
    if checked:
        print checked
    else:
        print "Device:", ip_addr, ", Month:", month, ", Day:", day, "<br>"
        results = do_search(ip_addr,month,day)
        print "<pre>"
        for line in results:
            print line,
    print "</pre>"
    print "</BODY>\n"
    print "</HTML>\n"

# Define main function.
def main():
#DEBUG
#    print check_input("stupid", '3', '18')
#    debug_lines = do_search(None, '[8-9]', '5')
#    debug_lines = do_search("10.3.1.150", '10', '25')
#    for line in debug_lines:
#        print line, "<br>"
#    sys.exit()
    form = cgi.FieldStorage()
    global ignore_ciscoworks
    if (form.has_key("month") and form.has_key("day")and form.has_key("ourpass")):
        if (form.getvalue("ignore_user")):
            ignore_ciscoworks = False
        if (form["action"].value == "display"):
            if not (form.has_key("device")):
                display_data(None,  form["month"].value, form["day"].value, 
                             form["ourpass"].value)
            else:
                display_data(form["device"].value, form["month"].value, 
                             form["day"].value, form["ourpass"].value)

    else:
        generate_form()
    

# Call main function.
main()