The Badfile class provides one public method called is_badfile which analyzes a file according to the detection methods outlined here.
There is also a convenance method called isolate_or_clear to handle the file in question.
Their usage is demonstrated below:
1 2 3 4 5 6 7 8 9101112131415161718
frombadfiles.badfilesimportBadfiles,isolate_or_clearb=Badfile()bad=b.is_badfile(f=file)"""returns a named tuple with a classification: (safe, unsafe, unknown, or not implemented) message: A message explaining the classification file: The name of the file being analyzed"""isolate_or_clear(f=file,msg=bad,iso_dir=iso_dir,safe_dir=safe_dir,safe=["safe",])"""The safe parameter is a list of badfile classifications, returned from is_badfile(),that are deemed safe (defaults to ["safe",]). If the classification in the msg parameteris in the safe list the file is moved to safe_dir otherwise it is moved to iso_dir."""
The aim of this library is to use it in larger projects and especially web applications. Here are a few ideas for how you can integrate badfiles into your current projects.
importpathlibfromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportJSONResponsefrombadfiles.badfilesimportBadfileimportpathlibapp=FastAPI()@app.get("/")asyncdefroot():return{"message":"Welcome to the badfiles demo"}@app.post("/")asyncdefpost_file(f:UploadFile=File(...)):upload=pathlib.Path(__file__).parent/"uploads"/f.filenamewithopen(upload,"wb+")asfo:fo.write(f.file.read())b=Badfile()bf=b.is_badfile(upload)pathlib.Path.unlink(upload)# in real life you will not want to delete the file at this pointifbf.classification=="safe":# handle safe files herereturnJSONResponse(status_code=200,content={"message":f"File accepted: {bf.message}"})# handle unsafe files herereturnJSONResponse(status_code=403,content={"message":f"File rejected: {bf.message}"})