// Python

File check script with Python

Let’s say you have a file upload feature on your website. You’ve put all the checks in place, but there was a security vulnerability you overlooked, and an unwanted file was uploaded to your site—how do you catch it?

When you encounter an annoying situation like this, you can increase your security with the Python script whose example I share below.

Before sharing the code, let me explain how it works.

As soon as the code runs, it will create 3 files in the folder where it is located.

"dosya_beyazliste.txt" 
File names to be ignored during scanning Example: index.php, upload.php
"uzanti_beyazliste.txt"
File extensions to be ignored during scanning Example: png,jpg,gif
"log.txt"
Outputs of the scan result.

You’ll also need to set some parameters in the script; I’ll explain them below.

yol = "./dosyaKontrol/"

The folder where the script will run; if you want to run it in the directory where it is located, you can set it to “./”.

karantinaKlasoru = "../k/" #scriptin çalıştığı klasörde olmaması önerilir. en azından bir üst klasörde olmalı.

The quarantine folder to which files found as threats will be moved.

wlFileName = "dosya_beyazliste.txt"
wlExFileName = "uzanti_beyazliste.txt"
logFileName = "log.txt"

I already explained these above 🙂

karantinaGonder = 'h' #[ e | h ]

Approval for moving files found as threats to the folder you set as the quarantine folder. When you first run the script, it’s best to leave it as “h”. Then, after looking at log.txt and adding the extensions and files you will exclude to “dosya_beyazliste.txt” and “uzanti_beyazliste.txt”, mark it as “e”. (remember, lowercase e or h)

 

By the way, I’d also like to remind you that after uploading the Python script, the folder permissions should be “0744”. You can do this either after a PHP upload process or by attaching this script to a ChronJob and running it periodically.

I’m also sharing the screenshots. The first screenshot is the output of calling the Python script from within PHP.

The log.txt output after the Python script runs.

The status of the folder where you uploaded the script file

The situation where the file detected as a threat is moved to quarantine.

The approximate content that your “dosya_beyazliste.txt” and “uzanti_beyazliste.txt” should have

If you share it somewhere, or use the Python script, or just out of respect for the effort, I’d appreciate it if you cite the source 🙂

DijitalTurk.com | File Control

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import shutil
from datetime import datetime

#DijitalTurk.com

now = datetime.now()
 #print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
#print("date and time =", dt_string)



#yol = "./"
yol = "./dosyaKontrol/"
karantinaKlasoru = "../k/" #scriptin çalıştığı klasörde olmaması önerilir. en azından bir üst klasörde olmalı.
wlFileName = "dosya_beyazliste.txt"
wlExFileName = "uzanti_beyazliste.txt"
logFileName = "log.txt"

karantinaGonder = 'h' #[ e | h ]

warnMsg = ' [KONTROL] '
warnCreateFile = ' dosyası oluşturuldu [SİSTEM] '
myNameIs = 'DosyaKontrolV2.py'

karantinaYol = yol+karantinaKlasoru
whiteListFile = yol+wlFileName
whiteListExtention = yol+wlExFileName
logFile = yol+logFileName
tarananDosyaSayisi = 0

logList = []
fileNameWhiteList = []
fileExtentionWhiteList = []
allList = os.listdir(yol)

#print("**** allList ****")
#print(allList)
print("n -------- START --------- n")

if not os.path.isdir(karantinaYol):
    os.mkdir(karantinaYol)



if os.path.isfile(whiteListExtention):
    f1 = open(whiteListExtention, "r")
    fileExtentionWhiteList = f1.readlines()
    f1.close()
else:
    print(whiteListExtention + warnCreateFile)
    f1 = open(whiteListExtention, "w")

if os.path.isfile(whiteListFile):
    f2 = open(whiteListFile, "r")
    fileNameWhiteList = f2.readlines()
    f2.close()
else:
    print(whiteListFile + warnCreateFile)
    f2 = open(whiteListFile, "w")

fileNameWhiteList.append(whiteListExtention)
fileNameWhiteList.append(whiteListFile)
fileNameWhiteList.append(myNameIs)
fileNameWhiteList.append(wlFileName)
fileNameWhiteList.append(wlExFileName)
fileNameWhiteList.append(logFileName)

new_fileNameWhiteList = [s.replace('rn', '') for s in fileNameWhiteList]
new_fileExtentionWhiteList = [s.replace('rn', '') for s in fileExtentionWhiteList]

print("n **** Dikkate alınmayan dosya ve uzantılar**** n")
print(new_fileExtentionWhiteList)
print(new_fileNameWhiteList)
print("n ----------------- n")


def isDeleteFile(root,fileName):
    if fileName.split('.')[-1].lower() not in new_fileExtentionWhiteList:
              if fileName not in new_fileNameWhiteList:
                logList.append( warnMsg + root + fileName)
                print( warnMsg  + root  + fileName)
                if karantinaGonder == 'e':
                    shutil.move(root + fileName, karantinaYol + fileName + "_sec")

for root, dirs, file in os.walk(yol):
      for fileName in file:
        tarananDosyaSayisi = tarananDosyaSayisi+1
        isDeleteFile(root , fileName)

forLog = open(logFile,"w")#KONTROL ET
#forLog.write("Now the file has more content!")
#print(logList)
forLog.write('n Zaman: ' + dt_string + ' n  Toplam taranan dosya sayısı: ' + str( tarananDosyaSayisi ) + ' n Kontrol edilmesi gereken dosya sayısı: ' +  str( len(logList) )+ 'n')
for l in logList:
    forLog.write(l + 'n')
    #forLog.write(" ".join(l) + "n")
    #print(l)
forLog.close()


print( 'n Zaman: ' + dt_string + ' Toplam taranan dosya sayısı: ' + str( tarananDosyaSayisi ) + ' Kontrol edilmesi gereken dosya sayısı: ' +  str( len(logList) ) )

 

// JOIN THE CONVERSATION

Share your experience

Bir sorunun, farklı bir çözümün veya eklemek istediğin bir notun var mı? Giriş yapmadan da yazabilirsin.

// KEEP READING

One more note.

All posts ↗︎