A little script for malware self-defense

Do you spend your days working from home? Last week I was rushed to the scene for the first time in a while The inside of the train looked like a lie

What is Corona ...: thinking:

Increasing security demand

Aside from that, the security of terminals has increased in recent years. I think I have more thoughts.

Recently, I heard and heard news about malware such as EMOTET. I think that if you are scared, your alertness may temporarily increase.

However, when the date and time came, such alertness diminished, and I visited strange sites. There is also the possibility of embedding strange things in your favorite site It's not without it.

How such malware can do bad things on our devices You need to register for automatic startup. So, by checking the programs that are automatically started every day, If you get a chance to notice a suspicious person sneaking into us ...!

bouhan_camera_dorobou[1].png

So using a handy tool called "autorunsc.exe" I wrote a script to collect logs for the auto-start program.

import part

import subprocess
import zipfile
import os
import sys
import urllib.request as req
import pandas as pd
from glob import glob
from plyer import notification
from alittleuseful import loglotate

# pip install pandas
# pip install plyer
# pip install git+https://github.com/ardnico/main

alittleuseful I personally publish on github, A library to write logs We have published other weird features, but if you like, please use them. I'm happy. .. ..

Naming definition

csv_file = f'{os.getcwd()}\\out.csv'
rcsv_file = f'{os.getcwd()}\\out_old.csv'
enc = "utf-16"
URL = "https://download.sysinternals.com/files/Autoruns.zip"
zip_file = "A.zip"
path='.'
logger = loglotate(
    logname = "StartUpSec",
    outputdir = [os.getcwd()],
    lsize = 100000,
    num = 20,
    timestanp = 1 # 1:on other:off
)

Static naming and function calling part

Function: Download autorunsc.exe

def download_tool(tf:bool):
    # file download
    if tf == False:
        logger.write('[INFO]Because the tool has not existed, the one will download')
        req.urlretrieve(URL,zip_file)
        with zipfile.ZipFile(zip_file, 'r') as z_file:
            try:
                z_file.extractall(path=path)
                logger.write("[SUCCESS]Tool download succeeded")
            except Exception as e:
                logger.write('[ERROR]Failed to download or unzip autorunsc.exe')
                logger.write(f'[ERROR]{e}')
                sys.exit(0)

If "autorunsc.exe" does not exist, use request Download the tool. The download will be done until ZIP decompression.

Function: From execution of "autorunsc.exe" to comparison of auto-start programs

def get_log():
    if os.path.exists(rcsv_file) == True:
        try:
            os.remove(rcsv_file)
        except Exception as e:
            logger.write('[ERROR]Failed to remove oldcsvfile')
            logger.write(f'[ERROR]{e}')
            sys.exit(0)
    if os.path.exists(csv_file) == True:
        try:
            os.rename(csv_file,rcsv_file)
            df_old = pd.read_csv(rcsv_file,encoding=enc)
        except Exception as e:
            logger.write('[ERROR]Failed to rename oldcsvfile')
            logger.write(f'[ERROR]{e}')
            sys.exit(0)
    else:
        df_old = ''
    with open(csv_file, mode='w', encoding=enc) as fp:
        cp = subprocess.run([f'{os.getcwd()}\\autorunsc.exe','-nobanner','-c','-a','*'], encoding=enc, stdout=fp)
    try:
        if df_old == '':
            flag = 0
        else:
            flag = 2
    except:
        if len(df_old.index) <= 0:
            flag = 0
        else:
            flag = 1
    if flag==0 or flag==2:
        logger.write("[INFO]StartUp Program's log has created")
    else:
        with open(csv_file,encoding=enc) as f:
            data = f.read().split('\n')
        with open(rcsv_file,encoding=enc) as f:
            data2 = f.read().split('\n')
        l_diff = list(set(data)^set(data2))
        if len(l_diff) > 0:
            logger.write("[DIFF INFO]The difference of the startup program has existed")
            for i in l_diff:
                logger.write(f"[DIFF]{i}")
                notification.notify(
                    title='The difference of startup program has existed',
                    message=i,
                    app_name='Diff notify'
                )
        else:
            logger.write("[INFO]The difference did not exsist")

It has become a little long due to the handling of CSV files, The movement is as follows.

  1. Rotate CSV file
  2. Compare the contents of the latest CSV and the previous CSV file
  3. If there is a difference, write to log + pop notification

Execution part

if __name__ == "__main__":
    os.chdir(r"C:\python\notebooks\StartUpProgramSec")
    tooltf = os.path.exists(f"{os.getcwd()}\\autorunsc.exe")
    download_tool(tooltf)
    get_log()
    logger.write("[INFO]The process completed")

that's all.

Make your work at home safer, even a little I hope it will spread ... tomneko1215B1328_TP_V.jpg

Recommended Posts

A little script for malware self-defense
Tips for opening a scene with a broken reference with a script
(For myself) Flask_2 (list and for, extends, and a little more)
A note for embedding the scripting language in a bash script
Note 2 for embedding the scripting language in a bash script
Create a Python script for Wake on LAN (NAT traversal Wake on LAN [5])
Let's try a shell script
Made a command for FizzBuzz
A little more about FIFO
A little stuck with chainer