Ejemplo n.º 1
0
def parse_print_logs(print_log_file_path):
    event_log = evtx_2_json(print_log_file_path)
    for event in event_log['Events']['Event']:
        EventID = event['System']['EventID']['#text']
        timestmp = event['System']['TimeCreated']
        if EventID == '307':
            user = event['UserData']['DocumentPrinted']['Param3']
            document = event['UserData']['DocumentPrinted']['Param2']
            msg = "User {} printed {}".format(user, document)
            add_action(timestmp, 21, msg)
def scan_for_modifications(classified_data_folder):
    # warning: linux does not report proper creation time, but attribute change.
    # so we assume our company data have both times the same and we'll spot any modification comparing them
    for root, dirs, files in os.walk(classified_data_folder):
        for filename in files:
            path = os.path.join(root, filename)
            mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
            ctime = datetime.datetime.fromtimestamp(os.path.getctime(path))
            if ctime != mtime:
                msg = "Company classified file {} modified!".format(filename)
                # print(msg)
                add_action(mtime, 11, msg)
def scan_for_copy_in_team_viewer(logfile, classified_data_folder):
    # TODO: take any *_Logfile.log files in that dir if exists
    if os.path.exists(logfile):
        with open(logfile, 'r') as logf:
            for line in logf.readlines():
                fldr = str(classified_data_folder).replace('/', '\\')
                if fldr in line:
                    parts = line.split()
                    timestamp = datetime.strptime(parts[0],
                                                  '%a %b %d %H:%M:%S %Y')
                    add_action(timestamp, 6,
                               "File copied using TeamViewer: {}".format(line))
    else:
        print("TeamViewer log not present.")
def scan_recycle_bin(recycle_bin_path, company_folder_path):
    if os.path.isdir(recycle_bin_path):
        # instead of entering user if folder (cd S-1-5-21-3138777187-1060959929-2752825879-1000) I just crawl everything
        for root, dirs, files in os.walk(recycle_bin_path):
            for filename in files:
                if filename.startswith('$I'):
                    trashedfilepath = os.path.join(root, filename)
                    fi = open(trashedfilepath, 'rb')
                    results = read_dollar_i(fi)
                    fi.close()
                    if company_folder_path.replace(
                            '/', '\\') in results['file_path']:
                        msg = "Company data was deleted into Recycle Bin! ({})".format(
                            results['file_path'])
                        # print(msg)
                        add_action(results['deleted_time'], 10, msg)
Ejemplo n.º 5
0
def parse_defender_logs(defender_log_file_path):
    event_log = evtx_2_json(defender_log_file_path)
    for event in event_log['Events']['Event']:
        EventID = event['System']['EventID']['#text']
        timestmp = event['System']['TimeCreated']
        if EventID == "1102":
            msg = "Windows Logs got deleted!"
            #print(msg)
            add_action(timestmp, 15, msg)
        msg = None
        if EventID == '5001':
            msg = 'Real-time protection is disabled.'
        if EventID == '5010':
            msg = 'Scanning for malware and other potentially unwanted software is disabled.'
        if EventID == '5012':
            msg = 'Scanning for viruses is disabled.'
        if EventID == '1013':
            msg = 'The antimalware platform deleted history of malware and other potentially'
        if msg:
            add_action(timestmp, 14, msg)
Ejemplo n.º 6
0
def analyse_usb_devices():
    #
    # Could manually iterate over SYSTEM\CurrentControlSet\Enum\USBSTOR (src: SANS Poster)
    # but there is a usbstor3 module for RegRipper :)
    #
    hive = config['DEFAULT']['IMAGE_PATH'] + hives['SYSTEM']
    if os.path.exists(hive):
        cmd = [config['3RD_PARTY']['REGRIPPER_PATH'], "-p", "usbstor3", "-r", hive]
        # print(' '.join(cmd))
        out = subprocess.check_output(cmd)
        out = str(out)
        for line in out.split("\\n"):
            if "," in line:
                Name, LastWrite1, SN, LastWrite2, FriendlyName, nothing = line.split(",")
                LastWriteTime = datetime.strptime(LastWrite2, '%a %b %d %H:%M:%S %Y')
                msg = "User wrote to USB Device: {} (S/N:{})".format(FriendlyName, SN)
                add_action(LastWriteTime, 3, msg)

    else:
        print('Could not find SYSTEM hive ({})!!!'.format(hive))
def downloads_analysis(download_folder, API_KEY):
    """
    Uploading all files from Download folder to VirusTotal server for scanning
    and querying for scan results as described in
    https://www.virustotal.com/pl/documentation/public-api/
    and storing potentially malicious results in PMA_DB
    """

    cnt = 0
    for root, dirs, files in os.walk(download_folder):
        for filename in files:
            cnt += 1
    print("{} files will be scanned.".format(cnt))
    for root, dirs, files in os.walk(download_folder):
        for filename in files:
            cnt -= 1
            filepath = os.path.join(root, filename)
            ctime = os.path.getctime(
                filepath)  # maybe getmtime better on linux??
            timestamp = time.gmtime(ctime)
            fsize = os.path.getsize(filepath)
            if fsize < 32000000:  # public API has 32MB file size limit
                response = send_file_2_virustotal(filename, filepath, API_KEY)
                print('  {}:'.format(cnt) + response['verbose_msg'])
                if response['response_code'] == 1:
                    response2 = query_virustotal_4_report(
                        API_KEY, response['resource'])
                    if response2:
                        print(' ' + response2['verbose_msg'])
                        # TODO: implement sth for 'Scan request successfully queued, come back later for the report'
                        if 'positives' in response2:
                            if response2['positives'] == 0:
                                print(' Clean :)')
                            else:
                                print(' {} positives!'.format(
                                    response2['positives']))
                                av_res = beautify_positives(response2['scans'])
                                print(av_res)
                                if 'shell' in str(av_res).lower():
                                    add_action(timestamp, 7,
                                               "Bind Shell code found!")
                                elif 'backdoor' in str(av_res).lower():
                                    add_action(timestamp, 8,
                                               "Reverse Shell code found!")
                                else:
                                    add_action(
                                        timestamp, 12,
                                        "Downloaded file '{}' containing malware. ({})"
                                        .format(filename, av_res))
Ejemplo n.º 8
0
def parse_security_events(winlogfile, user):
    event_log = evtx_2_json(winlogfile)

    # print('Saving results to ElasticSearch...')
    for event in event_log['Events']['Event']:
        # We could index all possible events with their entire body for future analysis with sth like:
        # idxstat = es.index(index='events_security_raw', doc_type='events', id=i, body=event)
        EventID = event['System']['EventID']['#text']
        if EventID == '4624':
            luser = event['EventData']['TargetUserName']
            timestmp = event['System']['TimeCreated']
            LogonType = event['EventData']['LogonType']
            logon_type_msg = ""
            if LogonType == '2':
                logon_type_msg = "Logon at keyboard and screen of system."
            if LogonType == '7':
                logon_type_msg = "Unlock (i.e. after screen saver)"
            if LogonType == '10':
                logon_type_msg = "Remote Logon."
            if luser == user:
                if timestmp.weekday() < 5:
                    start = time(8, 30)
                    end = time(17, 30)
                    if start <= timestmp.time() <= end:
                        # print("User {} logged during normal working hours. {}".format(luser, logon_type_msg))
                        add_action(timestmp, 0, msg)
                    else:
                        msg = "User {} logged after working hours! {}".format(
                            luser, logon_type_msg)
                        # print(msg)
                        add_action(timestmp, 1, msg)
                else:
                    msg = "User {} logged outside working days! {}".format(
                        luser, logon_type_msg)
                    # print(msg)
                    add_action(timestmp, 2, msg)
        if EventID == "1102":
            dtimestmp = event['System']['TimeCreated']
            msg = "Some of the Windows Logs got deleted!"
            print(msg)
            add_action(dtimestmp, 15, msg)
        if EventID == "4698":
            timestmp = event['System']['TimeCreated']
            msg = "A scheduled task was created!"
            #print(msg)
            add_action(timestmp, 22, msg)
        if EventID == "5140":  # TODO: to be tested!!!
            timestmp = event['System']['TimeCreated']
            user = event['EventData']['ShareName']
            msg = "A notwork share was accessed!"
            #print(msg)
            add_action(timestmp, 17, msg)

        if EventID == "4802":
            timestmp: datetime = event['System']['TimeCreated']
            msg = "Screensaver invoked"
            #print(msg)
            add_action(timestmp, 25, msg)
            scr_started = timestmp
        if EventID == "4803":
            timestmp: datetime = event['System']['TimeCreated']
            msg = "Screensaver dismissed"
            #print(msg)
            add_action(timestmp, -25, msg)
            scr_ended = timestmp
            if scr_started.day == scr_ended.day:
                duration = scr_ended - scr_started
                if duration.seconds < 60 * 60 * 8:
                    #msg = "Screensaver was on for {} seconds.".format(duration.seconds)
                    timepoint = scr_started
                    for s in range(duration.seconds):
                        msg = "Screensaver second {} of {}".format(
                            s, duration.seconds)
                        timepoint = timepoint + timedelta(seconds=1)
                        add_action(timepoint, 2500, msg)