/** * @file encryption.c * @author syxhe (https://t.me/syxhe) * @brief A collection of all encryption related functions * @version 0.1 * @date 2025-06-09 * * @copyright Copyright (c) 2025 * */ // TODO: Go back and make sure every function has proper error handling // Oh fucking christ what have I done // I need to make sure every single function in this file returns with an indicated error instead of nuking the whole program with // error() #define _GNU_SOURCE 1 #ifndef __VXGG_REWRITE___ENCRYPTION_C___1481879318188___ #define __VXGG_REWRITE___ENCRYPTION_C___1481879318188___ 1 #define TPSIZE (1<<13) #include "shared.c" #include "threadpool.c" #include #include #include #include #include #include #include #include #include #include #include /// Runs sodium_init() before every call of a sodium function. Use is discouraged as this may cause unexpected early exits #define ___VXGG___ALWAYS_CHECK_LIBSODIUM___ 0 /// Defines `vxgg_setsodiumfailcb` function, which is used to set a custom callback for handling a failed libsodium init #define ___VXGG___USE_CLS_CALLBACK___ 0 /// Chunk size for encryption/decryption #define CHUNKSIZE (1 << 9) //! A list of possible words for password creation #define PASSWORD_WORDS ((const char * const []){\ "the", "of", "to", "and", "for", "our", "their", "has", "in", "he", "a", "them", "that", "these", "by", "have", "we", \ "us", "people", "which", "all", "is", "with", "laws", "be", "are", "his", "states", "on", "they", "right", "it", "from", \ "government", "such", "among", "powers", "most", "an", "time", "should", "new", "as", "been", "colonies", "assent", \ "large", "at", "independent", "free", "united", "when", "mankind", "hold", "rights", "governments", "consent", "its", \ "long", "themselves", "abolishing", "usurpations", "absolute", "repeated", "this", "world", "refused", "pass", "other", \ "others", "without", "justice", "peace", "power", "seas", "war", "do", "declaration", "america", "becomes", "necessary", \ "political", "equal", "declare", "causes", "separation", "men", "happiness", "any", "form", "alter", "or", "will", \ "forms", "same", "object", "off", "necessity", "history", "great", "britain", "tyranny", "over", "public", "good", \ "unless", "suspended", "so", "would", "legislature", "only", "legislative", "bodies", "purpose", "into", "dissolved", \ "state", "endeavoured", "refusing", "hither", "conditions", "establishing", "offices", "out", "armies", "legislatures", \ "render", "jurisdiction", "foreign", "acts", "pretended", "trial", "inhabitants", "cases", "transporting", "rule", \ "declaring", "here", "protection", "against", "lives", "circumstances", "ages", "totally", "friends", "brethren", "whose", \ "every", "may", "therefore", "ought", "unanimous", "thirteen", "course", "human", "events", "one", "dissolve", "bands", \ "connected", "another", "assume", "earth", "separate", "station", "nature", "natures", "god", "entitle", "decent", \ "respect", "opinions", "requires", "impel", "truths", "self", "evident", "created", "endowed", "creator", "certain", \ "unalienable", "life", "liberty", "pursuit", "secure", "instituted", "deriving", "just", "governed", "whenever", \ "destructive", "ends", "abolish", "institute", "laying", "foundation", "principles", "organizing", "shall", "seem", \ "likely", "effect", "safety", "prudence", "indeed", "dictate", "established", "not", "changed", "light", "transient", \ "accordingly", "experience", "hath", "shewn", "more", "disposed", "suffer", "while", "evils", "sufferable", "than", \ "accustomed", "but", "train", "abuses", "pursuing", "invariably", "evinces", "design", "reduce", "under", "despotism", \ "duty", "throw", "provide", "guards", "future", "security", "patient", "sufferance", "now", "constrains", "former", \ "systems", "present", "king", "injuries", "having", "direct", "establishment", "prove", "let", "facts", "submitted", \ "candid", "wholesome", "forbidden", "governors", "immediate", "pressing", "importance", "operation", "till", "obtained", \ "utterly", "neglected", "attend", "accommodation", "districts", "those", "relinquish", "representation", "inestimable", \ "formidable", "tyrants", "called", "together", "places", "unusual", "uncomfortable", "distant", "depository", "records", \ "sole", "fatiguing", "compliance", "measures", "representative", "houses", "repeatedly", "opposing", "manly", "firmness", \ "invasions", "after", "dissolutions", "cause", "elected", "whereby", "incapable", "annihilation", "returned", "exercise", \ "remaining", "mean", "exposed", "dangers", "invasion", "convulsions", "within", "prevent", "population", "obstructing", \ "naturalization", "foreigners", "encourage", "migrations", "raising", "appropriations", "lands", "obstructed", \ "administration", "judiciary", "made", "judges", "dependent", "alone", "tenure", "amount", "payment", "salaries", \ "erected", "multitude", "sent", "swarms", "officers", "harrass", "eat", "substance", "kept", "times", "standing", \ "affected", "military", "superior", "civil", "combined", "subject", "constitution", "unacknowledged", "giving", \ "legislation", "quartering", "armed", "troops", "protecting", "mock", "punishment", "murders", "commit", "cutting", \ "trade", "parts", "imposing", "taxes", "depriving", "many", "benefits", "jury", "beyond", "tried", "offences", "system", \ "english", "neighbouring", "province", "therein", "arbitrary", "enlarging", "boundaries", "once", "example", "fit", \ "instrument", "introducing", "taking", "away", "charters", "valuable", "altering", "fundamentally", "suspending", "own", \ "invested", "legislate", "whatsoever", "abdicated", "waging", "plundered", "ravaged", "coasts", "burnt", "towns", \ "destroyed", "mercenaries", "compleat", "works", "death", "desolation", "already", "begun", "cruelty", "perfidy", \ "scarcely", "paralleled", "barbarous", "unworthy", "head", "civilized", "nation", "constrained", "fellow", "citizens", \ "taken", "captive", "high", "bear", "arms", "country", "become", "executioners", "fall", "hands", "excited", "domestic", \ "insurrections", "amongst", "bring", "frontiers", "merciless", "indian", "savages", "known", "warfare", "undistinguished", \ "destruction", "sexes", "stage", "oppressions", "petitioned", "redress", "humble", "terms", "petitions", "answered", \ "injury", "prince", "character", "thus", "marked", "act", "define", "tyrant", "unfit", "ruler", "nor", "wanting", \ "attentions", "brittish", "warned", "attempts", "extend", "unwarrantable", "reminded", "emigration", "settlement", \ "appealed", "native", "magnanimity", "conjured", "ties", "common", "kindred", "disavow", "inevitably", "interrupt", \ "connections", "correspondence", "too", "deaf", "voice", "consanguinity", "must", "acquiesce", "denounces", "rest", \ "enemies", "representatives", "general", "congress", "assembled", "appealing", "supreme", "judge", "rectitude", \ "intentions", "name", "authority", "solemnly", "publish", "absolved", "allegiance", "british", "crown", "connection", \ "between", "full", "levy", "conclude", "contract", "alliances", "establish", "commerce", "things", "support", "firm", \ "reliance", "divine", "providence", "mutually", "pledge", "each", "fortunes", "sacred", "honor"\ }) //! Short macro for getting the `PASSWORD_WORDS` array size #define PASSWORD_WORDS_LEN (STATIC_ARRAY_LEN(PASSWORD_WORDS)) #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 #if ___VXGG___USE_CLS_CALLBACK___ > 0 //! Definition for the callback function that fires when a call to checksodium fails typedef void (*vxgg_naclfailcb)(void*); /** * @brief Default sodium init fail callback for use in `checksodiumcb()` * * @param none Unused param to fit callback spec */ static void naclfaildefault(void *none) { none = none; // Makes gcc happy if(___VXGG___VERBOSE_ERRORS___) error(1, ENOTSUP, " Couldn't initialize sodium for some reason. Quitting..."); exit(EXIT_FAILURE); } /** * @brief Internal function to deal with the `___VXGG___USE_CLS_CALLBACK___` macro * * `checksodiumcb()` runs the sodium function `sodium_init()` and on error calls the provided callback with the provided data. The * callback and data default to `naclfaildefault` and `NULL`, but can be changed when the `set` parameter is non-zero. When `set` * is zero, the sodium init check is preformed * * @note `checksodiumcb()` is ran when these conditions are true - 1: The `___VXGG___ALWAYS_CHECK_LIBSODIUM___` and `___VXGG___USE_CLS_CALLBACK___` * macros are both greater than 0 when compiling, and 2: a function in `encryption.c` calls a function originating from sodium. This * function exists as a way to deal with sodium failing yourself, instead of instantly calling `exit()`. If you don't care to handle * it, or are initializing sodium yourself, this is unnecessary * * @param callback A callback to be ran when sodium fails to initialize itself. Ignored if `set` is zero. Must be non-null when `set` is non-zero * @param data Data to be passed to the callback when it is fired. Ignored if `set` is zero. May be null * @param set Flag on whether to check sodium or to set a new callback and data pair. Checks sodium when zero, sets callback & data when non-zero * @retval int */ static int checksodiumcb(vxgg_naclfailcb const callback, void *data, unsigned char set) { static vxgg_naclfailcb cb = naclfaildefault; static void *usr = NULL; int ret; if(set) { if(cb == NULL) ERRRET(EINVAL, -1); cb = callback; usr = data; return 2; // libsodium normally returns 1 if the library is already initialized, so this is to signal that the callback has been updated } if((ret = sodium_init()) < 0) { if(cb == NULL) error(0, EINVAL, " refusing to run a null callback"); else cb(usr); } return ret; } void vxgg_setsodiumfailcb(vxgg_naclfailcb cb, void *data) { checksodiumcb(cb, data, 1); } #endif /** * @brief Simple function to check if sodium has been properly initialized * * `checksodium()` will run in functions located in `encryption.h` only when the macro `___VXGG___ALWAYS_CHECK_LIBSODIUM___` is greater * than zero when compiling. It will call the `checksodiumcb()` function if compiled with the `___VXGG___USE_CLS_CALLBACK___` macro. * When called, checksodium will run `sodium_init()`, and will either run the user-defined callback or `XALLOC_EXIT`. * */ static void checksodium(void) { #if ___VXGG___USE_CLS_CALLBACK___ > 0 checksodiumcb(NULL, NULL, 0); #else if(sodium_init() < 0) { errno = ENOTSUP; XALLOC_EXIT(" Couldn't initialize sodium for some reason. Quitting..."); } #endif return; } #endif /** * @brief open() with the flags O_TMPFILE, O_WRONLY, O_CLOEXEC, and O_SYNC. Opened with mode S_IRUSR, S_IWUSR * * @param dest The filename the new descriptor should have. Must be non-null * @retval (int)[-1,int] A new file descriptor. -1 on error */ int maketmp(const char * const dest) { if(!dest) ERRRET(EINVAL, -1); return open(dest, (O_TMPFILE | O_WRONLY | O_CLOEXEC | O_SYNC), (S_IRUSR | S_IWUSR)); } /** * @brief Link a file descriptor into the filesystem * * @param target New filename the descriptor should have * @param tgfd The file descriptor to link * @retval (int)[-1, 0] 0 on success, -1 on error */ int linkto(const char * const target, int tgfd) { if(!target || tgfd < 0 || access(target, F_OK) != -1) ERRRET(EINVAL, -1); char *path = NULL; asprintf(&path, "/proc/self/fd/%d", tgfd); if(!path) ERROR(1, errno, " Couldn't get path to move file into system",); int res = linkat(AT_FDCWD, path, AT_FDCWD, target, AT_SYMLINK_FOLLOW); free(path); return res; } static void __ucl_close(void *fd) { if(!fd) return; close(*(int*)fd); return; } static void __ucl_fclose(void *file) { if(!file) return; fclose((FILE*)file); return; } /** * @brief Encrypt src to dst using libsodium's xchacha encryption suite * * @param src File to encrypt * @param dst Destination to write encrypted file * @param key Key for encryption * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error */ int encrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { if(!src || !dst || !key) ERRRET(EINVAL, -1); #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif unsigned char buf[CHUNKSIZE], cbuf[CHUNKSIZE + crypto_secretstream_xchacha20poly1305_ABYTES]; unsigned char header[crypto_secretstream_xchacha20poly1305_HEADERBYTES]; crypto_secretstream_xchacha20poly1305_state state; unsigned long long cbuflen; unsigned char tag; size_t bytesread; int eof; // Write the header crypto_secretstream_xchacha20poly1305_init_push(&state, header, key); if(fwrite(header, 1, sizeof(header), dst) < sizeof(header)) { if(ferror(dst)) { WARN(errno, " Could not write header",); return -1; } } // Encrypt each chunk do { if((bytesread = fread(buf, 1, sizeof(buf), src)) < sizeof(buf)) if(ferror(src)) { WARN(errno, " Could not read from source",); return -1; } eof = feof(src); tag = eof ? crypto_secretstream_xchacha20poly1305_TAG_FINAL : 0; crypto_secretstream_xchacha20poly1305_push(&state, cbuf, &cbuflen, buf, bytesread, NULL, 0, tag); if(fwrite(cbuf, 1, (size_t)cbuflen, dst) < (size_t)cbuflen) if(ferror(dst)) { WARN(errno, " Could not write to target",); return -1; } } while (!eof); return 0; } /** * @brief Decrypt src to dst using libsodium's xchacha encryption suite * * @param src File to decrypt * @param dst Destination to write decrypted file * @param key Key used to encrypt * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error */ int decrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { if(!src || !dst || !key) ERRRET(EINVAL, -1); #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif unsigned char cbuf[CHUNKSIZE + crypto_secretstream_xchacha20poly1305_ABYTES], buf[CHUNKSIZE]; unsigned char header[crypto_secretstream_xchacha20poly1305_HEADERBYTES]; crypto_secretstream_xchacha20poly1305_state state; unsigned long long buflen; unsigned char tag; size_t bytesread; int eof; // Read the header if(fread(header, 1, sizeof(header), src) < sizeof(header)) { if(ferror(src)) { WARN(errno, " Couldn't read header", ); return -1; } } // Make sure the header isn't fuckey if(crypto_secretstream_xchacha20poly1305_init_pull(&state, header, key) != 0) { WARN(errno, " Incomplete header", ); return -1; } // Decrypt each chunk do { if((bytesread = fread(cbuf, 1, sizeof(cbuf), src)) < sizeof(cbuf)) { if(ferror(src)) { WARN(errno, " Ran into problem reading for decryption", ); return -1; } } eof = feof(src); if (crypto_secretstream_xchacha20poly1305_pull(&state, buf, &buflen, &tag, cbuf, bytesread, NULL, 0) != 0) { WARN(errno, " Corrupted chunk", ); return -1; } if(tag == crypto_secretstream_xchacha20poly1305_TAG_FINAL && !eof) { WARN(errno, " End of stream before end of file", ); return -1; } if(eof && tag != crypto_secretstream_xchacha20poly1305_TAG_FINAL) { WARN(errno, " End of file before end of stream", ); return -1; } fwrite(buf, 1, (size_t)buflen, dst); } while(! eof); return 0; } /** * @brief Encrypt file at `target` to `output` using Linux's named temp file system to do it in the background * * @param target * @param output * @param key * @retval (int)[,] */ int encryptviatmp(const char * const target, const char * const output, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif cleanup_CREATE(10); int fd = -1, tfd = -1; FILE *src, *dst; char *targetdir; // Open the target file if((fd = open(target, O_RDONLY)) < 0) return -1; cleanup_REGISTER(__ucl_close, (void*)&fd); // Create a temp file for writing targetdir = vxdirname(output); if(!targetdir) cleanup_MARK(); cleanup_CNDREGISTER(free, targetdir); // Actually get the file descriptor for the temp file cleanup_CNDEXEC( tfd = maketmp(targetdir); if(tfd < 0) cleanup_MARK(); cleanup_CNDREGISTER(__ucl_close, (void*)&tfd); ); // Create a FILE* version of the source fd cleanup_CNDEXEC( if(!(src = fdopen(fd, "rb"))) { WARN(errno, " Couldn't open \"%s\"", , target); cleanup_MARK(); } cleanup_CNDREGISTER(__ucl_fclose, (void*)&src); ) // Create a FILE* version of the target fd cleanup_CNDEXEC( if(!(dst = fdopen(tfd, "wb"))) { WARN(errno, " Couldn't open \"%s\"", , output); cleanup_MARK(); } cleanup_CNDREGISTER(__ucl_fclose, (void*)dst); ); // Do the encryption now that everything has been set up cleanup_CNDEXEC( // Not going to bother changing this, it probably is catastrophic if an error happens when it shouldn't if(encrypttofile(src, dst, key) < 0) ERROR(1, ENOTRECOVERABLE, " I don't even have a way to cause an error here. How did you do it?",); // Link the temp file into the system if(linkto(output, tfd) < 0) WARN(errno, " Could not link \"%s\" into system after encryption", , output); free(targetdir); fclose(dst); fclose(src); // fclose alco closes fd and tfd, as fdopen does not dup the file descriptors ); cleanup_CNDFIRE(); if(cleanup_ERRORFLAGGED) return -1; return 0; } /** * @brief Decrypt the file at `encrypted` to `target` * * @param encrypted * @param target * @param key * @retval (int)[,] */ int decryptto(const char * const target, const char * const output, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { if(!target || !output || !key) ERRRET(EINVAL, -1); #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif cleanup_CREATE(10); FILE *src, *dst; int fdst; // Open the source file if(!(src = fopen(target, "rb"))) { WARN(errno, " Could not open \"%s\" for decryption", , target); return -1; } cleanup_REGISTER(__ucl_fclose, src); // Get a temp descriptor for the temp file cleanup_CNDEXEC( fdst = maketmp(output); if(!fdst) { WARN(errno, " Could not get temp file for decryption", ); cleanup_MARK(); } cleanup_CNDREGISTER(__ucl_close, (void*)&fdst); ); // Open a FILE* version of the temp file cleanup_CNDEXEC( if(!(dst = fdopen(fdst, "wb"))) { WARN(errno, " Could not open \"%s\" for writing decrypted data", , output); cleanup_MARK(); } cleanup_CNDREGISTER(__ucl_fclose, dst); ); // Follow through with the rest of the decryption cleanup_CNDEXEC( if(decrypttofile(src, dst, key) < 0) ERROR(1, errno, " How did you even cause an error?",); // Link temp into system if(linkto(output, fdst) < 0) WARN(errno, " Could not link \"%s\" into system", , output); fclose(dst); fclose(src); // fclose alco closes fd and tfd, as fdopen does not dup the file descriptors ); cleanup_CNDFIRE(); if(cleanup_ERRORFLAGGED) return -1; // Note: If an error were to theoretically occur, which shouldn't be possible but I'm covering my bases here, after the // `dst = fdopen` line, a double close on the temp file descriptor would occur. I've been told that this is not catastrophic, // and considering how my multithreading works it *should* be fine, but it very well could cause problems. The easy solution is // to man up and just write another cleanup function to pop the last thing off the stack, but again this is an error I can't // actually trigger so it's fine for now return 0; } /** * @brief Generate a password viable for use in the derivation of a key * * @param str Pointer to a string. This will be filled by a malloc'ed string of words (the password). Must be non-null * @param words The number of words to include in the password. A password of at least 20 words and probably not more than 40 is recommended * @retval (int)[-1, words] On success, returns the number of words requested. On error, returns -1 and sets errno */ int genpassword(char **str, unsigned int words) { // Early returns if(words < 1) return 0; if(!str) ERRRET(EINVAL, -1); #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif // Bootstrap the first word char *lstr = NULL, *tmp = NULL; if(asprintf(&lstr, "%s", PASSWORD_WORDS[randombytes_uniform(PASSWORD_WORDS_LEN)]) < 0) return -1; // Concat the rest of the words into the password (without leaking memory) int ret; for(unsigned int i = 1; i < words; i++) { ret = asprintf(&tmp, "%s %s", lstr, PASSWORD_WORDS[randombytes_uniform(PASSWORD_WORDS_LEN)]); sodium_memzero(lstr, strlen(lstr) + 1); free(lstr); if(ret < 0) return -1; lstr = tmp; } *str = lstr; return words; } /** * @brief sodium_malloc wrapper. * * Calls `error()` or `abort()` depnding on the value of `___VXGG___XALLOC_EXIT_ON_ERROR___`. Will make sure libsodium is initialized if `___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0` * * @param size * @retval (void*) A pointer to some data allocated via `sodium_malloc()` */ void* xsodium_malloc(size_t size) { #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 checksodium(); #endif void *mem = sodium_malloc(size); if(mem == NULL) XALLOC_EXIT(" could not allocate memory... Quitting", ); return mem; } // TODO: Rewrite this to use the threadpool. Each newly scanned file should be pushed onto the threadpool as an encryption task // #include // dlinkedlist * scandirlist(const char * const dir, int (*selector)(const struct dirent *), int (*cmp)(const struct dirent **, const struct dirent **)) { // if(!dir || selector == NULL || cmp == NULL) ERRRET(EINVAL, NULL); // struct dirent **namelist = NULL; // dlinkedlist *list = NULL; // int numentries = -1; // if((numentries = scandir(dir, &namelist, selector, cmp)) < 0) // ERRRET(errno, NULL); // list = dlinkedlist_init(); // for(int i = 0; i < numentries; i++) // if(dlinkedlist_append(list, (void *)(namelist[i]), free) < 0) { // dlinkedlist_free(list); // for(int j = i; j < numentries; j++) // free(namelist[j]); // free(namelist); // ERRRET(errno, NULL); // } // free(namelist); // return list; // } // Above implementation is flawed and would not actually scan the entire system. The process must be recursive: // Step 1 - Create directory list // Step 2 - Create --cryption ctq // Step 3 - Scan initial starting dir. This will be /home/ // Step 4 - Iterate over scan results // Step 4.1 - For all directory dirent objects, add them to the directory list // Step 4.2 - For all file dirent objects, add them to the --cryption ctq // Step 5 - Scan next entry in the dirlist, removing it once done. Repeat Step 4 // Step 6 - Free dirlist once empty, return newly populated --cryption ctq // Idea: Create 2 ctqs. Use one for the actual scanning, and the other as the return result. That way, not only will scanning be // fast, but I can also just reuse code I've already written and not make some absolute spaghetti mess trying to do everything // linearly int __cscan_worker(void *data) { if(!data) return -1; return 0; } ctqueue * cryptscan() { ctqueue *res = ctqueue_init(TPSIZE), *working = ctqueue_init(TPSIZE); if(!res || !working) ERRRET(errno, NULL); task *start = task_init(__cscan_worker, free, NULL); if(!start) ERRRET(errno, NULL); ctqueue_waitpush(working, start); return res; } #endif