示例#1
0
def main():
    import os_lib_handle
    import os_lib_agent
    import os_lib_syscheck
    import os_lib_alerts
    import ossec_conf
    import datetime
    ossec_handle = os_lib_handle.os_handle_start(ossec_conf.ossec_dir)
    if ossec_handle is None:
        print("Unable to access ossec directory.\n")
        return(1)

    agent_list = os_lib_agent.os_getagents(ossec_handle)
    agent_list2 = []
    agent_count = 0

    for agent in agent_list:
        agent['id'] = agent_count
        agent_count += 1

        agent['change_time_fmt'] = datetime.datetime.fromtimestamp(agent['change_time']).strftime("%m/%d/%Y %H:%M:%S")

        atitle = ""
        aclass = ""
        amsg = ""

        #If agent is connected
        if agent['connected']:
            atitle = "Agent active"
            aclass = "bluez"
        else:
            atitle = "Agent Inactive"
            aclass = "red"
            amsg = " - Inactive"

        agent['atitle'] = atitle
        agent['aclass'] = aclass
        agent['amsg'] = amsg

        agent_list2.append(agent)

    syscheck_list = os_lib_syscheck.os_getsyscheck(ossec_handle)

    syscheck_count = 0
    syscheck_list2 = []
    # {'time_stamp':time_stamp, '_name':_name, 'sk_file_name':sk_file_name}
    for syscheck in syscheck_list['global_list']['files']:
        ts = datetime.datetime.fromtimestamp(int(syscheck['time_stamp'])).strftime("%m/%d/%Y %H:%M:%S")
        syscheck_list2.append({'id':syscheck_count, 'ts':ts, 'name':syscheck['_name'], 'filename':syscheck['sk_file_name']})
        syscheck_count += 1
        if syscheck_count >= 10:
            break
        pass

    alert_list = os_lib_alerts.os_getalerts(ossec_handle, 0, 0, 30)

    alert_count = alert_list.size() - 1
    alert_array  = alert_list.alerts()

    alert_list_html = ""
    while (alert_count>=0):
        alert_list_html += alert_array[alert_count].toHtml()
        alert_count -= 1

    now = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
    return render_template("main.html", now=now, agent_list=agent_list2,
                                                syscheck_global_list = syscheck_list2,
                                                alert_list_html=alert_list_html)
示例#2
0
    def _make_contents(self):
        req       = self.request
        is_post = self.is_post
        form     = req.form

        # Starting handle
        ossec_handle = os_lib_handle.os_handle_start(ossec_conf.ossec_dir)

        # Current date values (day : 05, month : 07, year : 2015)
        curr_time = int(time.time())
        curr_day =  datetime.fromtimestamp(curr_time).strftime("%d")
        curr_month = datetime.fromtimestamp(curr_time).strftime("%m")
        curr_year = datetime.fromtimestamp(curr_time).strftime("%Y")

        #  datetime.fromtimestamp(curr_time).strftime("%Y-%m-%d %H:%M")

        # Getting user values
        USER_day = None
        USER_month = None
        USER_year = None

        if is_post and ('day' in form):
            strday = form.get('day')
            if strday.isdigit():
                if (int(strday) >= 0) and (int(strday) <=31 ):
                    USER_day = strday
                    # USER_day = "%02d" % int(strday)  # TODO : キーをどうするか
                    print (USER_day)

        if is_post and ('month' in form):
            strmonth = form.get('month')
            if strmonth.isdigit():
                if (int(strmonth) > 0) and (int(strmonth) <=12):
                    USER_month = strmonth

        if is_post and ('year' in form):
            stryear = form.get('year')
            if stryear.isdigit():
                if (int(stryear) >= 1) and (int(stryear) <= 3000):
                    USER_year = stryear

        init_time = 0
        final_time = 0

        # Bulding stat time_stamp
        if (USER_year is not None) and (USER_month is not None) and (USER_day is not None):
            print ("UESR_day is %s" % USER_day)
            # Stat for whole month
            if int(USER_day) == 0:
                print ("OKOK")
                init_time = int(time.mktime((int(USER_year), int(USER_month), 1, 0, 0, 0, 0, 0, -1)))
                final_time = int(time.mktime((int(USER_year), int(USER_month) + 1, 0, 0, 0, 0, 0, 0, -1)))
                # 2015-12-01 00:00:00
                # 2015-12-31 00:00:00
                # print(datetime.fromtimestamp(init_time))
                # print(datetime.fromtimestamp(final_time))

            else:
                init_time = int(time.mktime((int(USER_year), int(USER_month), int(USER_day), 0, 0, 0, 0, 0, -1)))
                final_time = int(time.mktime((int(USER_year), int(USER_month), int(USER_day), 0, 0, 10, 0, 0, -1)))

        else:
            init_time = curr_time - 1
            final_time = curr_time

            # Setting user values
            USER_month = curr_month
            USER_day = curr_day
            USER_year = curr_year

        buffer = ""

        # Day option
        buffer += "<h2>Stats options</h2><br />\n"

        buffer += """\
        <form name="dosearch" method="post" action="stats">

Day:  <select name="day" class="formSelect">
    <option value="0">All days</option>
        """

        for l_counter in range(1, 32):
            tmp_msg = ""
            if l_counter == int(USER_day):
                tmp_msg = ' selected="selected"'
            buffer += """<option value="%s" %s>%s</option>""" % (l_counter, tmp_msg, l_counter)

        buffer += "</select>"

        # Monthly
        months = OrderedDict([
            ("January", "Jan"),
            ("February", "Feb"),
            ("March", "Mar"),
            ("April", "Apr"),
            ("May", "May"),
            ("June", "Jun"),
            ("July", "Jul"),
            ("August", "Aug"),
            ("September", "Sep"),
            ("October", "Oct"),
            ("November", "Nov"),
            ("December", "Dec")
        ])

        buffer += ' Month: <select name="month" class="formSelect">'

        mnt_ct = 1
        for tmp_month, tmp_month_v in months.items():
            if int(USER_month) == mnt_ct:
                buffer += """    <option value="%s" selected="selected">%s</option>""" % (mnt_ct, tmp_month)
            else:
                buffer += """    <option value="%s">%s</option>""" % (mnt_ct, tmp_month)

            mnt_ct += 1

        buffer += "</select>"

        # year
        buffer += """ Year: <select name="year" class="formSelect">
        <option value="%s" selected="selected">%s</option>
        <option value="%s">%s</option>
        <option value="%s">%s</option>
        </select> <input type="submit" name="Stats" value="Change options" class="button" /></form>""" % (curr_year, curr_year, int(curr_year) - 1, int(curr_year) -1, int(curr_year) -2, int(curr_year) -2)

        # Getting daily stats
        # 2015/Jul
        l_year_month = datetime.fromtimestamp(init_time).strftime("%Y/%b")

        print ("INIT_TIME")
        print (init_time)
        print(final_time)
        print (datetime.fromtimestamp(init_time).strftime("%Y/%m/%d %H:%M:%S"))
        print (datetime.fromtimestamp(final_time).strftime("%Y/%m/%d %H:%M:%S"))
        """
        1435676400
1438268400
2015/07/01 00:00:00
2015/07/31 00:00:00

        """


        stats_list = os_lib_stats.os_getstats(ossec_handle, init_time, final_time)

        print ("stats_list")
        print (stats_list)
        print ("USER_day %s"  % USER_day)

        daily_stats = OrderedDict()
        all_stats = None

        if l_year_month in stats_list.keys():
            for k in stats_list[l_year_month].keys():
                print ("key is : %s" %k)
            if str(USER_day) in stats_list[l_year_month].keys():
                print ("found ")
                daily_stats = stats_list[l_year_month][str(USER_day)]
                all_stats = stats_list[l_year_month]

        print (daily_stats)

        if not 'total' in daily_stats.keys():
            buffer += """<br/>
                <b class="red">No stats available.</b>
            """
            self.contents += buffer
            return

        else:
            buffer += "<br />"

        # Day 0 == month stats
        if USER_day == 0:
            buffer += "<h2>Ossec Stats for: <b id='blue'>%s</b></h2><br />\n" % l_year_month
        else:
            buffer += "<h2>Ossec Stats for: <b id='blue'>%s/%s</b> </h2><br /><br />\n\n" % (l_year_month, USER_day)



        buffer += "<b>Total</b>: " + format_decimal(daily_stats['total'], locale='en_US')+ "<br/>"
        buffer += "<b>Alerts</b>: " + format_decimal(daily_stats['alerts'], locale='en_US') + "<br/>"
        buffer += "<b>Syscheck</b>: " + format_decimal(daily_stats['syscheck'], locale='en_US') + "<br/>"
        buffer += "<b>Firewall</b>: " + format_decimal(daily_stats['firewall'], locale='en_US') + "<br/>"

        if USER_day != 0:
            h_avg = int(daily_stats['total']) / 24.0
            print (h_avg)
            buffer += "<b>Average</b>: " + "%.02f" % h_avg + " events per hour."

        buffer += """<br /><br />
<br /><div class="statssmall">
<table align="center"><tr valign="top"><td width="50%">

<table summary="Total values">
    <caption><strong>Aggregate values by severity</strong></caption>
    <tr>
    <th>Option</th>
    <th>Value</th>
    <th>Percentage</th>
    </tr>
        """

        """
        OrderedDict([('total', 24150), ('alerts', 18798), ('syscheck', 3), ('firewall', 0),
         ('level', OrderedDict([('5', 1), ('3', 17127), ('0', 1659), ('10', 1), ('7', 6), ('1', 3), ('2', 1)])),
         ('rule', OrderedDict([('5503', 1), ('5501', 4893), ('5521', 45), ('5502', 4892), ('5522', 45), ('5401', 1), ('5402', 7338), ('530', 1531), ('533', 6), ('535', 3), ('31100', 5), ('31108', 9), ('509', 22), ('12100', 2), ('591', 4), ('1002', 1)])), ('alerts_by_hour', OrderedDict([('0', '1344'), ('1', '1345'), ('2', '1341'), ('3', '1341'), ('4', '1361'), ('5', '1334'), ('6', '1345'), ('7', '1343'), ('8', '1340'), ('9', '1343'), ('10', '1341'), ('11', '1334'), ('12', '1342'), ('13', '1344')])), ('total_by_hour', OrderedDict([('0', '1724'), ('1', '1724'), ('2', '1722'), ('3', '1722'), ('4', '1741'), ('5', '1713'), ('6', '1728'), ('7', '1729'), ('8', '1739'), ('9', '1727'), ('10', '1721'), ('11', '1713'), ('12', '1723'), ('13', '1724')])), ('syscheck_by_hour', OrderedDict([('0', '0'), ('1', '0'), ('2', '0'), ('3', '0'), ('4', '0'), ('5', '0'), ('6', '0'), ('7', '0'), ('8', '0'), ('9', '3'), ('10', '0'), ('11', '0'), ('12', '0'), ('13', '0')])), ('firewall_by_hour', OrderedDict([('0', '0'), ('1', '0'), ('2', '0'), ('3', '0'), ('4', '0'), ('5', '0'), ('6', '0'), ('7', '0'), ('8', '0'), ('9', '0'), ('10', '0'), ('11', '0'), ('12', '0'), ('13', '0')]))])
[('5', 1), ('10', 1), ('2', 1), ('1', 3), ('7', 6), ('0', 1659), ('3', 17127)]

        """

        #sorted_daily_stats_level = None  # OrderedDict()

        odd_count = 0
        odd_msg = ""

        if 'level' in daily_stats.keys():
            #sorted_daily_stats_level = sorted(daily_stats['level'].items(), key=lambda x: x[1])
            #print (sorted_daily_stats_level)

            # 最初にキーでソートしておく。(同じ値の時に、キー順に並べるため)
            # TODO : 文字列ソートのため、10 -> 2 になっている。
            # 数字でソート
            level_dict = OrderedDict()
            for k, v in sorted(daily_stats['level'].items()):
                level_dict[k] = v

            for  l_level, v_level in sorted(level_dict.items(), key=lambda x: x[1]):
            # 10, 2, 5, 1, 7, 0, 3
            #for  l_level, v_level in sorted(daily_stats['level'].items(), key=lambda x: x[1]):
            # 5, 10, 2, 1, 7, 0, 3

                level_pct = (v_level*100)/daily_stats['alerts']
                if (odd_count %2) == 0:
                    odd_msg = ' class="odd"'
                else:
                    odd_msg = ""

                odd_count += 1

                buffer += """
                <tr %s>
                    <td>Total for level%s</td>
                    <td>%s</td>
                    <td>%s %%</td>
                """ % (odd_msg, l_level, format_decimal(v_level, locale='en_US'), "%.01f" % level_pct)

        #print ("result is :")
        #print(sorted_daily_stats_level)

        if (odd_count % 2) == 0:
            odd_msg =  ' class="odd"'
        else:
            odd_msg = ""

        buffer += """
        <tr %s>
<td>Total for all levels</td>
<td>%s</td>
<td>100%%</td>
</tr>
</table>

</td>

<td width="50%%">
<table summary="Total values">
    <caption><strong>Aggregate values by rule</strong></caption>
    <tr>
    <th>Option</th>
    <th>Value</th>
    <th>Percentage</th>
    </tr>
        """ % (odd_msg, format_decimal(daily_stats['alerts'], locale='en_US'))


        if 'rule' in daily_stats.keys():

            rule_dict = OrderedDict()
            for k, v in sorted(daily_stats['rule'].items()):
                rule_dict[k] = v

            for  l_rule, v_rule in sorted(rule_dict.items(), key=lambda x: x[1]):
                rule_pct = (v_rule*100)/daily_stats['alerts']
                if (odd_count %2) == 0:
                    odd_msg = ' class="odd"'
                else:
                    odd_msg = ""

                odd_count += 1

                buffer += """
                	    <tr %s>
	    <td>Total for Rule %s</td>
	    <td>%s</td>
	    <td>%s %%</td>
	    </tr>
                """ % (odd_msg, l_rule,  format_decimal(v_rule, locale='en_US'), "%.01f" % rule_pct)

        if (odd_count % 2) == 0:
            odd_msg =  ' class="odd"'
        else:
            odd_msg = ""

        buffer += """
        <tr %s>
<td>Total for all rules</td>
<td>%s</td>
<td>100%%</td>
</tr>
        """ % (odd_msg, format_decimal(daily_stats['alerts'], locale='en_US'))

        buffer += """
        </table>
</td></tr></table>
        """

        # Monthly stats
        if int(USER_day) == 0:
            buffer += """
                    <br /><br />
        <table align="center" summary="Total by day">
        <caption><strong>Total values per Day</strong></caption>
        <tr>
        <th>Day</th>
        <th>Alerts</th>
        <th>Alerts %</th>
        <th>Syscheck</th>
        <th>Syscheck %</th>
        <th>Firewall</th>
        <th>Firewall %</th>
        <th>Total</th>
        <th>Total %</th>
        </tr>

            """

            odd_count = 0
            odd_msg = ""

            for i in range(1, 32):
                # key は string であり、0 padding されていない
                if (str(i) in all_stats.keys()) and ('total' in all_stats[str(i)].keys()):
                    pass
                else:
                    continue

                d_total = int(all_stats[str(i)]['total'])
                d_alerts = int(all_stats[str(i)]['alerts'])
                d_syscheck = int(all_stats[str(i)]['syscheck'])
                d_firewall = int(all_stats[str(i)]['firewall'])

                total_pct = "%.01f" % (d_total*100/max(int(daily_stats['total']), 1))
                alerts_pct = "%.01f" % (d_alerts*100/max(int(daily_stats['alerts']), 1))
                syscheck_pct = "%.01f" % (d_syscheck*100/max(int(daily_stats['syscheck']), 1))
                firewall_pct = "%.01f" % (d_firewall*100/max(int(daily_stats['firewall']), 1))

                if (odd_count % 2) == 0:
                    odd_msg = ' class="odd"'
                else:
                    odd_msg = ""

                odd_count += 1

                buffer += """
            <tr %s>
            <td>Day %s</td>
            <td>%s</td>
            <td>%s %%</td>
            <td>%s</td>
            <td>%s %%</td>
            <td>%s</td>
            <td>%s %%</td>
            <td>%s</td>
            <td>%s %%</td>

            </tr>
                """ % (odd_msg, i,
                                format_decimal(d_alerts, locale='en_US'), alerts_pct,
                                format_decimal(d_syscheck, locale='en_US'), syscheck_pct,
                                format_decimal(d_firewall, locale='en_US'), firewall_pct,
                                format_decimal(d_total, locale='en_US'), total_pct

                                )

        # Daily stats
        else:
            buffer += """
                    <br /><br />
        <table align="center" summary="Total by hour">
        <caption><strong>Total values per hour</strong></caption>
        <tr>
        <th>Hour</th>
        <th>Alerts</th>
        <th>Alerts %</th>
        <th>Syscheck</th>
        <th>Syscheck %</th>
        <th>Firewall</th>
        <th>Firewall %</th>
        <th>Total</th>
        <th>Total %</th>
        </tr>
            """

            odd_count = 0
            odd_msg = ""

            for i in range(0, 24):
                if 'total_by_hour' in daily_stats.keys():
                    print ("OK")
                    print(daily_stats['total_by_hour'].keys())
                    if str(i) in daily_stats['total_by_hour'].keys():
                        pass
                    else:
                        print ("not found")
                        continue
                else:
                    continue

                print(" got it ?")

                hour_total = int(daily_stats['total_by_hour'][str(i)])
                hour_alerts = int(daily_stats['alerts_by_hour'][str(i)])
                hour_syscheck = int(daily_stats['syscheck_by_hour'][str(i)])
                hour_firewall = int(daily_stats['firewall_by_hour'][str(i)])

                total_pct = (hour_total*100)/max(daily_stats['total'], 1)
                alerts_pct = (hour_alerts*100)/max(daily_stats['alerts'], 1)
                syscheck_pct = (hour_syscheck*100)/max(daily_stats['syscheck'], 1)
                firewall_pct = (hour_firewall*100)/max(daily_stats['firewall'], 1)


                if (odd_count % 2) == 0:
                    odd_msg = ' class="odd"'
                else:
                    odd_msg = ""

                odd_count += 1

                buffer += """
            <tr.$odd_msg>
            <td>Hour %s</td>
            <td>%s</td>
            <td>%s %%</td>

            <td>%s</td>
            <td>%s %%</td>

            <td>%s</td>
            <td>%s %%</td>

            <td>%s</td>
            <td>%s %%</td>
            </tr>
                """ % (i,
                            format_decimal(hour_alerts, locale='en_US'), "%.01f" % alerts_pct,
                            format_decimal(hour_syscheck, locale='en_US'), "%.01f" % syscheck_pct,
                            format_decimal(hour_firewall, locale='en_US'), "%.01f" % firewall_pct,
                            format_decimal(hour_total, locale='en_US'), "%.01f" % total_pct
                        )




        buffer += "</table></div>"

        self.contents = buffer
示例#3
0
    def _make_contents(self):

        #<form name="dosearch" method="post" action="index.php?f=i">
        #<table><tr valign="top">
        #<td>
        #Agent name: </td><td><select name="agentpattern" class="formText"><option value="ossec-server"  selected="selected"> &nbsp; ossec-server</option>
        #</select></td>
        #<td><input type="submit" name="ss" value="Dump database" class="button"/>
        #</td>
        #</tr></table>
        #</form>

        # Initializing variables
        u_agent = "ossec-server"
        u_file = ""
        USER_agent = None
        USER_file = None

        # Getting user patterns
        strpattern = "^[0-9a-zA-Z._^ -]{1,128}$"
        if request.method == 'POST':
            agentpattern = request.form.get('agentpattern')
            if not agentpattern:
                raise Exception("something is wrong in agentpattern")
            if re.search(strpattern, agentpattern):
                USER_agent = agentpattern
                u_agent = USER_agent

            #filepattern
            pass

        # Starting handle
        ossec_handle = os_lib_handle.os_handle_start(ossec_conf.ossec_dir)

        # Getting syscheck information
        syscheck_list = os_lib_syscheck.os_getsyscheck(ossec_handle)

        buffer = ""

        # Creating form
        buffer += """\
        <form name="dosearch" method="post" action="syscheck">
        <table><tr valign="top">
        <td>Agent name: </td>
        <td><select name="agentpattern" class="formText">
"""

        for agent in syscheck_list.keys():   # global_list, ossec-server
            print(agent)
            #agent = str(agent)
            sl = ""
            if agent == "global_list":
                break
            elif u_agent == agent:
                sl = ' selected ="selected"'

            buffer += """<option value="%s" %s> &nbsp; %s</option>""" % (agent, sl, agent)

        buffer += "</select></td>"

        buffer += """    <td><input type="submit" name="ss" value="Dump database" class="button"/>"""

        if USER_agent is not None:
            buffer += """&nbsp; &nbsp;<a class="bluez" href="syscheck"> &lt;&lt;back</a>"""

        buffer += """\
            </td>
    </tr></table>
    </form>
    """

        # Dumping database
        if request.method == 'POST':
            if (request.form.get('ss') == "Dump database") and (USER_agent is not None):
                print("Let's go!!!!!!!!!!!!!!!!!!!!")
                dump_buffer = os_lib_syscheck.os_syscheck_dumpdb(ossec_handle, USER_agent)

                self.contents = buffer + dump_buffer
                return
            pass

        buffer += "<br /><h2>Latest modified files (for all agents): </h2>\n\n"

        last_mod_date = ""
        sk_count = 0

        for syscheck in syscheck_list['global_list']['files']:
            sk_count += 1

            ffile_name = ""
            ffile_name2 = ""

            ffile_name = syscheck['sk_file_name']

            # Setting the database
            ts = int(syscheck['time_stamp'])
            dt   = datetime.datetime.fromtimestamp(ts).strftime("%m/%d/%Y")
            dt2 = datetime.datetime.fromtimestamp(ts).strftime("%m/%d/%Y %H:%M:%S")
            if last_mod_date != dt:
                last_mod_date = dt
                buffer += "<br/><b>%s</b><br/>" % last_mod_date

            # ts = datetime.datetime.fromtimestamp(int(syscheck['time_stamp'])).strftime("%m/%d/%Y %H:%M:%S")

            buffer += """\
               <span id="togglesk%s">
               <a  href="#" class="bluez" title="Expand %s"
               onclick="ShowSection(\'sk%s\');return false;"><span class="bluez">+
               %s</span></a><br />
               </span>
            """ % (sk_count, ffile_name, sk_count, ffile_name)

            buffer += """\
                <div id="contentsk%d" style="display: none">

               <a  href="#" title="Hide %s"
               onclick="HideSection(\'sk%d\');return false;">-%s</a>
               <br />
               <div class="smaller">
               &nbsp;&nbsp;<b>File:</b> %s<br />
               &nbsp;&nbsp;<b>Agent:</b> %s<br />
               &nbsp;&nbsp;<b>Modification time:</b>
               %s<br />
               </div>

               </div>
            """ % (sk_count, ffile_name, sk_count, ffile_name, ffile_name, syscheck['_name'], dt2)

            pass

        buffer += "</td></tr></table>"
        buffer += "<br /> <br />\n"

        #syscheck_count = 0
        #syscheck_list2 = []
        ## {'time_stamp':time_stamp, '_name':_name, 'sk_file_name':sk_file_name}
        #for syscheck in syscheck_list['global_list']['files']:
        #    ts = datetime.datetime.fromtimestamp(int(syscheck['time_stamp'])).strftime("%m/%d/%Y %H:%M:%S")
        #    syscheck_list2.append({'id':syscheck_count, 'ts':ts, 'name':syscheck['_name'], 'filename':syscheck['sk_file_name']})
        #    syscheck_count += 1
        #pass

        self.contents = buffer
示例#4
0
    def _make_contents(self):

        # Starting handle
        ossec_handle = os_lib_handle.os_handle_start(ossec_conf.ossec_dir)

        # Iniitializing some variables
        u_final_time = int(time.time())
        #u_final_time = int(time.mktime(datetime.now().timetuple()))
        u_init_time   = int(u_final_time  - ossec_conf.ossec_search_time) # 14400 = 3600 * 4

        u_level = ossec_conf.ossec_search_level   # 7
        u_pattern = ""
        u_rule = ""
        u_srcip = ""
        u_user = ""
        u_location = ""

        # masao added the folloings :
        USER_final = 0
        USER_init = 0
        USER_level = ""

        USER_pattern = None
        LOCATION_pattern = None
        USER_group = None
        USER_log = None
        USER_rule = None
        USER_srcip = None
        USER_user = None
        USER_page = int(1)
        USER_searchid = 0
        USER_monitoring = 0
        used_stored = 0

        buffer = ""

        # Getting search id
        if self.is_post and ('searchid' in self.request.form):
            str_searchid = self.request.form.get('searchid')
            if re.search("[a-z0-9]+", str_searchid):
                USER_searchid = str_searchid   # It might be hex. dont use int().

        is_rt_monitoring = False

        # TODO : real time monitoring t.b. implemented.
        rt_sk = ""
        sv_sk = 'checked="checked"'
        if self.is_post and ('monitoring' in self.request.form):
            str_monitoring = self.request.form.get('monitoring')
            if int(str_monitoring) == 1:
                is_rt_monitoring = True

                rt_sk = 'checked="checked"'
                sv_sk = "";

                # Cleaning up time
                USER_final = u_final_time
                USER_init = u_init_time
                USER_monitoring = 1

                # Cleaning up fields
                # $_POST['search'] = "Search";
                # unset($_POST['initdate']);
                # unset($_POST['finaldate']);

                # Deleting search
                if USER_searchid != 0:
                    os_lib_alerts.os_cleanstored(USER_searchid)

                # Refreshing every 90 seconds by default */
                m_ossec_refresh_time = ossec_conf.ossec_refresh_time * 1000;

                buffer += """\
<script language="javascript">
    setTimeout("document.dosearch.submit()", %d);
</script>\n""" % m_ossec_refresh_time

        # Reading user input -- being very careful parsing it

        # Initial Date
        datepattern = "^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2})$";
        if is_rt_monitoring:
            pass
        elif self.is_post and ('initdate' in self.request.form):
            str_initdate = self.request.form.get('initdate')
            mobj = re.search(datepattern, str_initdate)
            if mobj:
                year = int(mobj.group(1))
                month = int(mobj.group(2))
                day = int(mobj.group(3))
                hour = int(mobj.group(4))
                minute = int(mobj.group(5))

                USER_init = int(time.mktime((year, month, day, hour, minute, 0, 0, 0, -1)))
                u_init_time = USER_init
                # to check :
                # print(datetime.fromtimestamp(u_init_time))

        # Final Date
        if is_rt_monitoring:
            pass
        elif self.is_post and ('finaldate' in self.request.form):
            str_finaldate = self.request.form.get('finaldate')
            mobj = re.search(datepattern, str_finaldate)
            if mobj:
                year = int(mobj.group(1))
                month = int(mobj.group(2))
                day = int(mobj.group(3))
                hour = int(mobj.group(4))
                minute = int(mobj.group(5))
                USER_final = int(time.mktime((year, month, day, hour, minute, 0, 0, 0, -1)))
                u_final_time = USER_final

        # Level
        if self.is_post and ('level' in self.request.form):
            str_level = self.request.form.get('level')
            if str_level and str_level.isdigit() and (int(str_level) > 0) and (int(str_level) < 16):
                USER_level = str_level
                u_level = str_level

        # Page
        if self.is_post and ('page' in self.request.form):
            str_page = self.request.form.get('page')
            if str_page and str_page.isdigit() and (int(str_page) > 0) and (int(str_page) <= 999):
                USER_page = str_page

        # Pattern
        strpattern = "^[0-9a-zA-Z. _|^!\-()?]{1,128}$"
        intpattern = "^[0-9]{1,8}$"

        if self.is_post and ('strpattern' in self.request.form):
            str_strpattern = self.request.form.get('strpattern')
            if re.search(strpattern, str_strpattern):
                USER_pattern = str_strpattern
                u_pattern = USER_pattern

        # Getting location
        if self.is_post and ('locationpattern' in self.request.form):
            lcpattern = "^[0-9a-zA-Z. _|^!>\/\\-]{1,156}$"
            str_locationpattern = self.request.form.get('locationpattern')
            if re.search(lcpattern, str_locationpattern):
                LOCATION_pattern = str_locationpattern
                u_location = LOCATION_pattern

        # Group pattern
        if self.is_post and ('grouppattern' in self.request.form):
            str_grouppattern = self.request.form.get('grouppattern')
            if str_grouppattern == "ALL":
                USER_group = None
            elif re.search(strpattern, str_grouppattern):
                USER_group = str_grouppattern
            pass

        # Log pattern
        if self.is_post and ('logpattern' in self.request.form):
            str_logpattern = self.request.form.get('logpattern')
            if str_logpattern == "ALL":
                USER_log = None
            elif re.search(strpattern, str_logpattern):
                USER_log = str_logpattern

        # Rule pattern
        if self.is_post and ('rulepattern' in self.request.form):
            str_rulepattern = self.request.form.get('rulepattern')
            if re.search(strpattern, str_rulepattern):
                USER_rule = str_rulepattern
                u_rule = USER_rule

        # Src ip pattern
        if self.is_post and ('srcippattern' in self.request.form):
            str_srcippattern = self.request.form.get('srcippattern')
            if re.search(strpattern, str_srcippattern):
                USER_srcip = str_srcippattern
                u_srcip = USER_srcip

        # User pattern
        if self.is_post and ('userpattern' in self.request.form):
            str_userpattern = self.request.form.get('userpattern')
            if re.search(strpattern, str_userpattern):
                USER_user = str_userpattern
                u_user = USER_user

        # Maximum number of alerts
        if self.is_post and ('max_alerts_per_page' in self.request.form):
            str_max_alerts_per_page = self.request.form.get('max_alerts_per_page')
            if re.search(intpattern, str_max_alerts_per_page):
                int_max_alerts_per_page = int (str_max_alerts_per_page)
                if (int_max_alerts_per_page > 200) and (int_max_alerts_per_page < 10000):
                    ossec_conf.ossec_max_alerts_per_page = int_max_alerts_per_page


        # Getting search id -- should be enough to avoid duplicates
        if is_rt_monitoring: # 'get('search')  is "Search"
            m = hashlib.md5()
            m.update(str(uuid.uuid4()).encode('UTF-8'))
            USER_searchid = m.hexdigest()
            USER_page = 1

        elif self.is_post and ('search' in self.request.form):
            str_search = self.request.form.get('search')
            # ImmutableMultiDict([('initdate', '2015-07-21 15:00'), ('level', '3'), ('search', 'Search'), ('monitoring', '0'), ('finaldate', '2015-07-21 19:00'), ('searchid', '0')])
            if str_search == "Search":
                # Creating new search id
                #  (in php)       $USER_searchid = md5(uniqid(rand(), true));
                m = hashlib.md5()
                m.update(str(uuid.uuid4()).encode('UTF-8'))
                USER_searchid = m.hexdigest()
                USER_page = 1

            elif str_search == "<< First":
                USER_page = 1

            elif str_search == "< Prev":
                if int(USER_page) > 1:
                    UESR_page = int(USER_page) - 1

            elif str_search ==  "Next >":
                USER_page = int(USER_page) + 1

            elif str_search == "Last >>":
                USER_page = 999

            elif str_search == "":
                pass

            else:
                buffer += "<b class='red'>Invalid search. </b><br />\n"
                self.contents = buffer
                return

        # Printing current date
        buffer += """<div class="smaller2">%s<br/>""" % datetime.now().strftime("%m/%d/%Y %H:%M:%S")
        if USER_monitoring == 1:
            buffer +=  """ -- Refreshing every %s secs</div><br />""" % ossec_conf.ossec_refresh_time
        else:
            buffer += "</div><br/>"

        # Getting all agents
        agent_list = os_lib_agent.os_getagents(ossec_handle)


        buffer += "<h2>Alert search options:</h2>\n"


        #################
        ### Search forms ###
        #################

        buffer += """\
        <form name="dosearch" method="post" action="/search">
        <table><tr valign="top">
            <td><input type="radio" name="monitoring" value="0" checked="checked"/></td>
            <td>From: &nbsp;<input type="text" name="initdate"   id="i_date_a" size="17" value="%s"  maxlength="16"  class="formText" />
                <img src="static/img/calendar.gif" id="i_trigger" title="Date selector"  alt="Date selector" class="formText" /></td>
            <td>&nbsp;&nbsp;&nbsp;To: &nbsp;<input type="text" name="finaldate" id="f_date_a" size="17" value="%s"  maxlength="16"  class="formText" />
                <img src="static/img/calendar.gif" id="f_trigger" title="Date selector" alt="Date selector" class="formText" /></td>
        </tr>
        """ % (
                    datetime.fromtimestamp(u_init_time).strftime("%Y-%m-%d %H:%M"),
                    datetime.fromtimestamp(u_final_time).strftime("%Y-%m-%d %H:%M")
                )


        buffer += """<tr><td><input type="radio" name="monitoring" value="1" %s/></td>
              <td>Real time monitoring</td></tr>
              </table>
              <br />
              <table>
              """ % rt_sk

        # Minimum Level
        buffer += """<tr><td>Minimum level:</td><td><select name="level" class="formText">"""
        if int(u_level) == 1:
            buffer +=  '  <option value="1" selected="selected">All</option>'
        else:
            buffer += '   <option value="1">All</option>'

        for l_counter in range(15, 1, -1):
            if l_counter == int(u_level):
                buffer += '   <option value="%s" selected="selected">%s</option>' % (l_counter, l_counter)
            else:
                buffer += '   <option value="%s">%s</option>' % (l_counter, l_counter)

        buffer += "</select>"


        # Category
        buffer += """</td><td>
            Category: </td><td><select name="grouppattern" class="formText">"""
        buffer += '<option value="ALL" class="bluez">All categories</option>'

        for _cat_name, _cat in global_categories.items():
            for cat_name, cat_val  in _cat.items():
                sl = ""
                if USER_group == cat_val:
                    sl = ' selected="selected"'
                if cat_name.find("(all)") != -1:
                    buffer += """<option class="bluez" %s value="%s">%s</option>""" % (sl, cat_val, cat_name)
                else:
                    buffer += """<option value="%s" %s> &nbsp; %s</option>""" % (cat_val, sl, cat_name)

        buffer += '</select>'


        # Str pattern
        buffer += """</td></tr><tr><td>
            Pattern: </td><td><input type="text" name="strpattern" size="16"
            value="%s" class="formText" /></td>""" % u_pattern

        # Log formats
        buffer += '<td>Log formats: </td><td><select name="logpattern" class="formText">'
        buffer += '<option value="ALL" class="bluez">All log formats</option>'

        for _cat_name, _cat in log_categories.items():
            for cat_name, cat_val  in _cat.items():
                sl = ""
                if USER_log == cat_val:
                    sl = ' selected="selected"'
                if cat_name.find("(all)") != -1:
                    buffer += """<option class="bluez" %s value="%s">%s</option>"""% (sl, cat_val, cat_name)
                else:
                    buffer += """<option value="%s" %s> &nbsp; %s</option>""" % (cat_val, sl, cat_name)

        buffer += '</select>'

        # Srcip pattern
        buffer += """</td></tr><tr><td>
            Srcip: </td><td>
            <input type="text" name="srcippattern" size="16" class="formText"
                value="%s"/>&nbsp;&nbsp;""" % u_srcip

        # Rule pattern
        buffer += """</td><td>
            User: </td><td><input type="text" name="userpattern" size="8"
                value="%s" class="formText" /></td></tr>""" % u_user

        # Location
        buffer += """<tr><td>
            Location:</td><td>
            <input type="text" name="locationpattern" size="16" class="formText"
                value="%s"/>&nbsp;&nbsp;""" % u_location

        # Rule pattern
        buffer += """</td><td>
            Rule id: </td><td><input type="text" name="rulepattern" size="8"
                value="%s" class="formText"/>""" % u_rule

        # Max alerts
        buffer += """'</td></tr><tr><td>
            Max Alerts:</td>
            <td><input type="text" name="max_alerts_per_page" size="8" value="%s" class="formText" /></td></tr>
        """ % ossec_conf.ossec_max_alerts_per_page

        # Agent
        # seems not implemented

        # Final form
        buffer += """\
            <tr><td>
            <input type="submit" name="search" value="Search" class="button" />
        """

        buffer += """</td></tr></table>
            <input type="hidden" name="searchid" value="%s" />
            </form><br /> <br />""" % USER_searchid

        # Java script for date
        buffer += """\
<script type="text/javascript">
Calendar.setup({
button          :   "i_trigger",
inputField     :    "i_date_a",
ifFormat       :    "%Y-%m-%d %H:%M",
showsTime      :    true,
timeFormat     :    "24"
});
Calendar.setup({
button          :   "f_trigger",
inputField     :    "f_date_a",
ifFormat       :    "%Y-%m-%d %H:%M",
showsTime      :    true,
timeFormat     :    "24"
});
</script>

        """

        buffer += "<h2>Results:</h2>\n"

        if (not USER_init) or (not USER_final) or (not USER_level):
            buffer += "<b>No search performed.</b><br/>\n"
            self.contents = buffer
            return

        output_list = None

        # Getting stored alerts
        if is_rt_monitoring:
            # Getting alerts
            output_list = os_lib_alerts.os_searchalerts(ossec_handle,
                                                USER_searchid,
                                                USER_init,
                                                USER_final,
                                                ossec_conf.ossec_max_alerts_per_page,
                                                USER_level,
                                                USER_rule,
                                                LOCATION_pattern,
                                                USER_pattern,
                                                USER_group,
                                                USER_srcip,
                                                USER_user,
                                                USER_log)

        elif self.is_post and ('search' in request.form):
            str_search = self.request.form.get("search")

            if str_search != "Search":
                output_list = os_lib_alerts.os_getstoredalerts(ossec_handle, USER_searchid)
                used_stored = 1
            else:  # Searchiing for new ones
                # Getting alerts
                output_list = os_lib_alerts.os_searchalerts(ossec_handle,
                                    USER_searchid,
                                    USER_init,
                                    USER_final,
                                    ossec_conf.ossec_max_alerts_per_page,
                                    USER_level,
                                    USER_rule,
                                    LOCATION_pattern,
                                    USER_pattern,
                                    USER_group,
                                    USER_srcip,
                                    USER_user,
                                    USER_log)

        if (output_list is None) or (output_list[1] is None):
            if used_stored == 1:
                buffer += "<b class='red'>Nothing returned (search expired). </b><br />\n"
            else:
                buffer += "<b class='red'>Nothing returned. </b><br />\n"

            self.contents = buffer
            return

        # Checking for no return
        if not 'count' in output_list[0]:
            buffer += "<b class='red'>Nothing returned. </b><br />\n"
            self.contents = buffer
            return

        # Checking maximum page size
        if int(USER_page) >= int(output_list[0]['pg']):
            USER_page = output_list[0]['pg']

        # Page 1 will become the latest and the latest, page 1
        real_page = (output_list[0]['pg'] + 1) - USER_page

        buffer += "<b>Total alerts found: </b>%s<br />" % output_list[0]['count']

        if output_list[0]['pg'] > 1:
            buffer += "<b>Output divided in </b>%s pages.<br/>" % output_list[0]['pg']

            buffer += '<br /><form name="dopage" method="post" action="/search">'

            buffer += """\
                <input type="submit" name="search" value="<< First" class="button" class="formText" />

                <input type="submit" name="search" value="< Prev" class="button" class="formText" />

                Page <b>%s</b> (%s alerts)""" % (USER_page, output_list[0][real_page])

        # Currently page
        buffer += """\
<input type="hidden" name="initdate"  value="%s" />
<input type="hidden" name="finaldate" value="%s" />
<input type="hidden" name="rulepattern" value="%s" />
<input type="hidden" name="srcippattern" value="%s" />
<input type="hidden" name="userpattern" value="'%s" />
<input type="hidden" name="locationpattern" value="%s" />
<input type="hidden" name="level" value="%s" />
<input type="hidden" name="page" value="%s" />
<input type="hidden" name="searchid" value="%s" />
<input type="hidden" name="monitoring" value="%s" />
<input type="hidden" name="max_alerts_per_page"     value="%s" />
        """ % (
                    datetime.fromtimestamp(u_init_time).strftime("%Y-%m-%d %H:%M"),
                    datetime.fromtimestamp(u_final_time).strftime("%Y-%m-%d %H:%M"),
                    u_rule, u_srcip, u_user, u_location, u_level, USER_page, USER_searchid, USER_monitoring, ossec_conf.ossec_max_alerts_per_page
                )

        if output_list[0]['pg'] > 1:
            buffer += """\
&nbsp;&nbsp;
<input type="submit" name="search" value="Next >" class="button" class="formText" />
<input type="submit" name="search" value="Last >>" class="button"  class="formText" />
</form>
            """

        # Checking if page exists
        target = output_list[real_page]
        target_file = os.environ['CCPRISM_HOME'] + target
        print("real_page is %s" %real_page)
        print("target_file is " + target_file)
        print(output_list[0].keys())
        if 'count' in output_list[0].keys():
            print("count key exists.")
        if 'pg' in output_list[0].keys():
            print ('pg key exists')
        if real_page in output_list[0].keys():
            print("real_page key exists.")
        if (not real_page in  output_list[0].keys()) or (len(target) < 5) or (not os.path.exists(target_file)):
        #if (not output_list[0][real_page]) or (len(target) < 5) or (not os.path.exists(target_file)):
            print("heyheyhey")
            buffer += "<b class='red'>Nothing returned (or search expired). (* 1)</b><br />\n"

            self.contents = buffer
            return

        buffer += "<br/><br/>"

        # Printing page
        # TODO: There are functions for slurping file contents.

        fobj = open(target_file, 'r')

        target_buffer = fobj.read()

        fobj.close()

        buffer += target_buffer

        self.contents = buffer