简体   繁体   中英

C - Running a program in RAM

I have a program that XORs two files together using one time pad encryption. As the keyfile is of such sensitive nature I don't want any traces of the keyfile to appear on the computers hard drive as that could compromise security.

The question is, how do I run the program in RAM so as to avoid any traces being left on the HD? Alternatively, will running the program from a flash drive contain traces of the keyfile to the flash drive?

Below is how the keyfile is treated in the program:

/* Check if keyfile can be opened. */
if((keyfile = fopen(argv[3], "rb"))== NULL)
{
printf("Can't open keyfile.\n");
printf("Please enter a valid filename.\n"); 
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
perror("Error");
return(1);
}                               

/* Get size of keyfile */
fstat(fileno(keyfile), &keybuf);

/* Check if keyfile is the same size as, or bigger than the sourcefile */
if((keybuf.st_size) < (statbuf.st_size))
{
printf("Source file is larger than keyfile.\n");
printf("This significantly reduces cryptographic strength.\n");
printf("Do you wish to continue? (Y/N)\n");
fgets(buffer, 20, stdin);
sscanf(buffer, "%c", &ans);
if(ans == 'n' || ans == 'N')
{
return (1);
}
if(ans == 'y' || ans == 'Y')
{
    printf("Proceeding with Encryption/Decryption.\n");
    }

/* Encrypt/Decrypt and write to output file. */
while(count < (statbuf.st_size))
{
key=fgetc(keyfile);
data=fgetc(sourcefile);

output=(key^data);

fputc(output,destfile);
count++;
}

/* Close files. */
fclose(keyfile);
fclose(sourcefile);
fclose(destfile); 

I came across an inram function when googling this, but that didn't seem to be what I needed.

I assume you're reading the keyfile from some external media and you are worried about the process being swapped to disk along with the I/O buffers containing the OTP. You are probably equally concerned about the plaintext being written. If you are on a posix system (like linux) then you should look into the mlock and mlockall functions. These calls will lock memory pages into RAM and prohibit their swapping to disk. The man page specifically calls out the security use case for these calls. Another option might be to mmap the files. Though it doesn't carry the same guarantee, since the mapped pages will be backed by the external media I doubt they'd appear in the swap space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM