Skip to content

Instantly share code, notes, and snippets.

@dmknght
Created February 7, 2022 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmknght/c9ce01f5ea8e715b49a7865d46ba9bc0 to your computer and use it in GitHub Desktop.
Save dmknght/c9ce01f5ea8e715b49a7865d46ba9bc0 to your computer and use it in GitHub Desktop.
Compare md5sum of a file with md5sum db of Debian's packages
#[
Work on Debian based only
Tested with Parrot 5.0
Compile: nim c -d:danger <file_name.nim>
Compare md5sum of a file with Debian's packages database.
]#
import os
import strutils
import posix
import md5
type
FileSum = object
path: string
md5sum: string
DebCheck = enum
FileNotInDb, FileNotMatched, FileMatched
const checksumDir = "/var/lib/dpkg/info/"
var SumDb: seq[FileSum]
proc getFileMd5(file_path: string): string =
# Safe calculating md5sum without eating memory
if access(file_path, R_OK) != F_OK:
echo "[!] File is not readable. Exit!"
result = ""
else:
const szBuff = 16384 # 2 ** 14
var
f: File
context: MD5Context
buffer = newString(szBuff)
context.md5Init()
f = open(file_path, fmRead)
while true:
let readBytes = f.readChars(buffer.toOpenArray(0, szBuff - 1))
context.md5Update(cstring(buffer), readBytes)
if readBytes < szBuff:
break
var digest: MD5Digest
context.md5Final(digest)
result = $digest
proc cmp_db(file_info: FileSum, db_info: seq[FileSum]): DebCheck =
for each_file_info in db_info:
if each_file_info.md5sum == file_info.md5sum:
echo "Matched checksum with ", each_file_info.md5sum
return FileMatched
elif each_file_info.path == file_info.path:
return FileNotMatched
return FileNotInDb
for kind, path in walkDir(checksumDir):
if path.endsWith(".md5sums"):
for line in lines(path):
let
tmpLine = line.split(" ")
tmpFileInfo = FileSum(
path: "/" & tmpLine[1],
md5sum: tmpLine[0]
)
SumDb.add(tmpFileInfo)
echo "Loading db"
echo "Loaded db size: ", len(SumDb)
let
checkpath = "/usr/bin/bash"
toCheck = FileSum(
path: checkpath,
md5sum: getFileMd5(checkpath),
)
echo "File path: ", toCheck.path
echo "File Sum: ", toCheck.md5sum
echo cmp_db(toCheck, SumDb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment