コード例 #1
0
def os_getalerts(ossec_handle, init_time = 0, final_time = 0, max_count = 30):
    file = ""
    alert_list = Ossec_AlertList()
    curr_time = datetime.now()

    log_file = ossec_handle['dir'] + "/logs/alerts/alerts.log"

    fobj = open(log_file, 'rb')
    #fobj = open(log_file, 'r')

    #   If times are set to zero, we monitor the last *count files. */
    if init_time == 0  and final_time == 0:
        # clearstatcache()
        # os_cleanstored()

        # Getting file size
        info = os.stat(log_file)
        f_size = info.st_size

        # Average size of every event: 300-350
        f_point = max_count * 325

        #  If file size is large than the counter fseek to the average place in the file.

        if f_size > f_point:
            seek_place = f_size - f_point
            fobj.seek(seek_place, 0)
            # 1行だけ捨てても無意味なので注意
            #tmpbuf_to_discard = fobj.readline()
            #print(tmpbuf_to_discard)
        pass

        while True:
            alert = __os_parsealert(fobj, curr_time, init_time, final_time, 0, None, None,
                                                        None, None, None, None, None, None, None, None)
            #);

            if alert:
                alert.dump()

            if alert is None:
                break

            alert_list.addAlert(alert)
            pass

    fobj.close()
    return alert_list
    pass
コード例 #2
0
def os_searchalerts(ossec_handle,
                        search_id,
                         init_time,   final_time,
                         max_count = 1000,  min_level = 7,   rule_id = None,
                         location_pattern = None,  str_pattern = None,  group_pattern = None,
                         srcip_pattern = None,   user_pattern = None,  log_pattern = None)  :

    """
     *  @param integer $min_level
     *  Used to constrain events by level. Events with levels lower than this value
     *  will not be returned. Passed directly to __os_parsealert.
    """

    if False:
        print (">> IN os_searchalerts in os_lib_alerts.py\n")

        fmt_init_time  = datetime.fromtimestamp(init_time)
        fmt_final_time = datetime.fromtimestamp(final_time)
        in_args = """\
init_time : %s
final_time : %s
max_count : %s
min_level : %s
rule_id : %s
location_pattern %s
str_pattern : %s
group_pattern : %s
srcip_pattern : %s
user_pattern : %s
log_pattern : %s
""" % (fmt_init_time, fmt_final_time, max_count, min_level, rule_id, location_pattern,
            str_pattern, group_pattern, srcip_pattern, user_pattern, log_pattern)

        print (in_args)

        """
        init_time : 2015-07-23 07:38:00
        final_time : 2015-07-24 11:38:00
        max_count : 5000
        min_level : 3
        rule_id : 111
        location_pattern loc_pattern
        str_pattern : pattern_abc
        group_pattern : web_scan
        srcip_pattern : 192.168.0.50
        user_pattern : root
        log_pattern : sshd
        """

    alert_list = Ossec_AlertList()

    file_count = 0
    file_list = []
    #file_list[0] = ""
    #     $file_list[0] = array();

    """
output_file[0]
array(1) { ["count"]=> int(1000) }
output_file[1]
string(60) "./tmp/output-tmp.1-1000-f95606de5c49b31df3348c8001ae0ab4.php"

output_file[0]
array(2) { ["count"]=> int(2000) [1]=> int(999) }
output_file[2]
string(60) "./tmp/output-tmp.2-1000-f95606de5c49b31df3348c8001ae0ab4.php"

output_file[0]
array(3) { ["count"]=> int(3000) [1]=> int(999) [2]=> int(999) }
output_file[3]
string(60) "./tmp/output-tmp.3-1000-f95606de5c49b31df3348c8001ae0ab4.php"

output_file[0]
array(4) { ["count"]=> int(4000) [1]=> int(999) [2]=> int(999) [3]=> int(999) }
output_file[4]
string(60) "./tmp/output-tmp.4-1000-f95606de5c49b31df3348c8001ae0ab4.php"
    """

    output_count = 1
    output_file = []
    output_file.append(OrderedDict())
    output_file.append(None)
    #output_file.append(None)
    #output_file.append(OrderedDict())
    #output_file[0] = ""
    #output_file[1] = ""

    curr_time = int(time.time())

    # added by masao
    rc_code_hash = OrderedDict()

    # Clearing arguments
    if rule_id is not None:
        rule_id = "/%s/" % rule_id

    group_regex = None
    if (group_pattern is not None) and (group_pattern.find("|") != -1):
        group_regex = "/%s/" % group_pattern
        group_pattern = None

    log_regex = None
    if (log_pattern is not None) and (log_pattern.find("|") != -1):
        log_regex = "/%s/" % log_pattern
        log_pattern = None

    # Setting rc code
    if (user_pattern is not None) and user_pattern and (user_pattern[0] == '!'):
        user_pattern = user_pattern[1:]
        rc_code_hash['user_pattern'] = True
    else:
        rc_code_hash['user_pattern'] = False

    # str
    if (str_pattern is not None) and str_pattern and (str_pattern[0] == '!'):
        str_pattern = str_pattern[1:]
        rc_code_hash['str_pattern'] = True #  TODO : True?
        # rc_code_hash['str_pattern'] = False #  TODO : True?
    else:
        rc_code_hash['str_pattern'] = False
        # rc_code_hash['str_pattern'] = True

    # srcip
    if (srcip_pattern is not None) and srcip_pattern and (srcip_pattern[0] == '!'):
        srcip_pattern = srcip_pattern[1:]
        rc_code_hash['srcip_pattern'] = True
    else:
        rc_code_hash['srcip_pattern'] = False

    # location
    if (location_pattern is not None) and location_pattern and (location_pattern[0] == '!'):
        location_pattern = location_pattern[1:]
        rc_code_hash['location_pattern'] = True
    else:
        rc_code_hash['location_pattern'] = False

    # Cleaning old entries
    os_cleanstored(None)

    global gcounter_alerts
    gcounter_alerts = 0

    # Getting first file
    init_loop = init_time
    while init_loop <= final_time:
        l_year_month = datetime.fromtimestamp(init_loop).strftime("%Y/%b") # 2015/Jul
        l_day = datetime.fromtimestamp(init_loop).strftime("%d")

        file_list.append("logs/alerts/%s/ossec-alerts-%s.log" % (l_year_month, l_day))
        #file_list.appned(None)
        #file_list[file_count] = "logs/alerts/%s/ossec-alerts-%s.log" % (l_year_month, l_day)

        # Adding one day
        init_loop+=86400
        file_count += 1

    # Getting each file
    for file in file_list:
        print ("Let's check a file %s" % file)
        # If the file does not exist, it must be gzipped so switch to a
        # compressed stream for reading and try again. If that also fails,
        # abort this log file and continue on to the next one.
        log_file = ossec_handle['dir'] + "/" + file

        fobj = None
        try:
            fobj = open(log_file, "rb")
        except Exception as e:
            try:
                fobj = gzip.open(log_file + ".gz", "rb")
            except Exception as e:
                continue

        # Reading all the entries
        while True:
            # Dont get more than max count alerts per page
            if alert_list.size() >= max_count:
                # output_file[1]
                # string(60) "./tmp/output-tmp.1-1000-f95606de5c49b31df3348c8001ae0ab4.php"
                #  in python : ./tmp/output-tmp.1-1000-917f3b294dd1a044411b45813c06b58d.php

                output_file[output_count] = "/tmp/output-tmp.%03d-%s-%s.py" % (output_count, alert_list.size(), search_id)
                #output_file[output_count] = "/tmp/output-tmp.%s-%s-%s.py" % (output_count, alert_list.size(), search_id)

                __os_createresults(output_file[output_count], alert_list)

                output_file[0][output_count] = alert_list.size()-1
                alert_list = Ossec_AlertList()
                output_count += 1
                output_file.append(None)

            alert = __os_parsealert(fobj, curr_time, init_time,
                                     final_time, min_level,
                                     rule_id, location_pattern,
                                     str_pattern, group_pattern,
                                     group_regex,
                                     srcip_pattern, user_pattern,
                                     log_pattern, log_regex,
                                     rc_code_hash);

            # final time を超えると、None が返される
            if alert is None:
                print("Let's break")
                break

            if not 'count' in output_file[0]:
                output_file[0]['count'] = 0

            output_file[0]['count'] += 1

            # Adding alert
            alert_list.addAlert(alert)

        # Closing file
        if fobj:
            print("goint to close %s" % fobj)
            fobj.close()

    print("gcounter_alerts is %s" % gcounter_alerts)

    # Creating last entry
    output_file[output_count] = "/tmp/output-tmp.%03d-%s-%s.py" % (output_count, alert_list.size(), search_id)
    #output_file[output_count] = "/tmp/output-tmp.%s-%s-%s.py" % (output_count, alert_list.size(), search_id)

    # output_file.append("./tmp/output-tmp.%s-%s-%s.php" % (output_count, alert_list.size(), search_id))

    output_file[0][output_count] = alert_list.size() - 1
    output_file.append(None)

    __os_createresults(output_file[output_count], alert_list)

    output_file[0]['pg'] = output_count

    print(output_file)

    return output_file