I have written some code, and the Vigenere encryption is used in it. This is a simple program for encrypting/decrypting any files.
#include<stdio.h>
/*
LANGUAGE: C.
STANDARD: C89.
ABOUT PROGRAM:
This is a simple program for encrypting/decrypting any files.
The size of source file coincide with size of result file.
For encryption of file are use any string key. For decrypting,
you must to use the same key, which was used for encryption.
NOTES:
The Vigenere encryption are used in it.
Info at the site: http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher.
This simple algorithm is often used at commercial products. The
Vigenere's algorithm are using a string key, and 'XOR' for
encrypting/decrypting information.
WARNING!
The use of this method, doesn't give 100% of a warranty
for protection of your information. Don't create the keys,
consisting of identical characters, for example" "aaaaa",
"zzz", "xxxx" e.t.c. - it is very feeble protection!
Don't forget your encrypting keys... :)
SYNTAX OF USING:
vigenere StringKey SourceFileName ResultFileName
where:
vigenere - program name;
StringKey - string key for encrypting/decrypting;
SourceFileName - source file name;
ResultFileName - result file name;
EXAMPLE OF USING:
vigenere "G5$hj4*df7f3+x" "c:\temp\source.txt" "c:\temp\result.txt"
*/
int main(int argc, char *args[]){
/****************************************************/
/* All variables must be defined on top in function, otherwise
some compilers can't compile this code (for example - MS
Visual Studio 2012. */
char ch; /* The next char for encrypting/decrypting. */
char *x; /* String key. */
FILE *srcFile; /* Source file. */
FILE *trgFile; /* Result file. */
/****************************************************/
/* The first argument always is a program file name. */
if (4 != argc)
return 1; /* Invalid arguments count. */
if (!*args[1] || !*args[2] || !*args[3])
return 2; /* Contains the empty argument. */
x = args[1];
if ((srcFile = fopen(args[2], "rb")) != NULL){
if ((trgFile = fopen(args[3], "wb")) != NULL){
while((ch = getc(srcFile)) != EOF){
if(!*x++)
x = args[1];
putc((ch ^= *x), trgFile);
}
fclose(trgFile);
}
else
return 4; /* Result file wasn't created. */
fclose(srcFile);
}
else
return 3; /* Source file wasn't opened. */
return 0; /* Successful operation. */
}
But this code does not always work well. I don't understand why it occurs. I do XOR for each byte. I have tested this code on such TXT files. Where is my mistake?
char ch;
/* ... */
while((ch = getc(srcFile)) != EOF)
ch must be an int. EOF is defined as a negative int.
In addition to ouah's answer, the pointer value increment looks off.
your if statement, if(!*x++), is bad for two reasons:
By doing an increment before the actual XOR operation, you're skipping the first character of your key in the initial loop.
There's no point in incrementing the pointer if you already reach the null-terminating character.
The better code would be:
while((ch = getc(srcFile)) != EOF){
putc((ch ^= *x), trgFile);
if(!*++x)
x = args[1];
}
Related
I'm currently trying to read some star data from the BSC. I've managed to read in the header and that shows up more or less correct, but I'm having trouble reading in the star data itself. The specification states that values are stored as 4/8-byte "Real" numbers, which I assumed meant floats/doubles, but the Ascension and Declination I get are all wrong, a good bit above the trillions for one and zero for the other. The magnitude is also wrong, despite it just being an integer, which I could read fine in the header. Here's and image of the output thus far. Any know what I'm doing wrong?
Alright, after some more testing, I managed to solve my problem. The crucial step was to abandon the binary file altogether and use the ASCII file instead. I had some problems reading from it before due to how it was formatted, but I came up with a method that worked:
/* Struct to store all the attributes I'm interested in */
struct StarData_t{
char Name[11];
char SpType[21];
float GLON, GLAT, Vmag;
};
int main()
{
/* Allocate a list of the structs
(the BSC has 9110 entries) */
struct StarData_t stars[9110];
/* Open the catalog */
FILE *fptr = fopen("catalog", "r");
if(fptr != NULL){
/* Create a buffer for storing the star entries.
The ASCII file has one entry per line.
Each line has a max length of 197,
which becomes 199 with the newline and null terminator,
so I round up to 200. */
size_t star_size = 200;
char *star_buffer;
star_buffer = (char *)malloc(star_size * sizeof(char));
/* Create a buffer for reading in the numbers.
The catalog has no numbers longer than 6 characters,
So I allocate 7 to account for the newline. */
char data_buffer[7];
/* For each entry in the BSC... */
for(int i = 0; i < 9110; i++){
/* Read the line to the buffer */
getline(&star_buffer, &star_size, fptr);
/* And put the data in the matching index,
Using the data buffer to create the floats */
// GLON
strncpy(data_buffer, &(star_buffer[90]), 6);
data_buffer[6] = '\0';
stars[i].GLON = fmod(atof(data_buffer)+180, 360)-180;
// GLAT
strncpy(data_buffer, &(star_buffer[96]), 6);
data_buffer[6] = '\0';
stars[i].GLAT = atof(data_buffer);
// Vmag
strncpy(data_buffer, &(star_buffer[102]), 5);
data_buffer[5] = '\0';
stars[i].Vmag = atof(data_buffer);
// Name
strncpy(stars[i].Name, &(star_buffer[4]), 10);
stars[i].Name[10] = '\0';
// Spectral Type
strncpy(stars[i].SpType, &(star_buffer[127]), 20);
stars[i].SpType[20] = '\0';
printf("Name: %s, Long: %7.2f, Lat: %6.2f, Vmag: %4.2f, SpType: %s\n", stars[i].Name, stars[i].GLON, stars[i].GLAT, stars[i].Vmag, stars[i].SpType);
}
free(star_buffer);
}
}
Hope this is useful!
Using associative arrays implented via the POSIX hcreate/hsearch functions (as described here, I struggled some unexpected behaviour finding keys I've never entered or the other way around.
I tracked it down to some instance of store-by-reference-instead-of-value.
This was surprising to me, since in the example uses string literals as keys:
store("red", 0xff0000);
store("orange", 0x123456); /* Insert wrong value! */
store("green", 0x008000);
store("blue", 0x0000ff);
store("white", 0xffffff);
store("black", 0x000000);
store("orange", 0xffa500); /* Replace with correct value. */
Here is an MWE that shows my problem:
#include <inttypes.h> /* intptr_t */
#include <search.h> /* hcreate(), hsearch() */
#include <stdio.h> /* perror() */
#include <stdlib.h> /* exit() */
#include <string.h> /* strcpy() */
void exit_with_error(const char* error_message){
perror(error_message);
exit(EXIT_FAILURE);
}
int fetch(const char* key, intptr_t* value){
ENTRY e,*p;
e.key=(char*)key;
p=hsearch(e, FIND);
if(!p) return 0;
*value=(intptr_t)p->data;
return 1;
}
void store(const char *key, intptr_t value){
ENTRY e,*p;
e.key=(char*)key;
p = hsearch(e, ENTER);
if(!p) exit_with_error("hash full");
p->data = (void *)value;
}
void main(){
char a[4]="foo";
char b[4]="bar";
char c[4]="";
intptr_t x=NULL;
if(!hcreate(50)) exit_with_error("no hash");
store(a,1); /* a --> 1 */
strcpy(c,a); /* remember a */
strcpy(a,b); /* set a to b */
store(a,-1); /* b --> -1 */
strcpy(a,c); /* reset a */
if(fetch(a,&x)&&x==1) puts("a is here.");
if(!fetch(b,&x)) puts("b is not.");
strcpy(a,b); printf("But if we adjust a to match b");
if(fetch(a,&x)&&x==-1&&fetch(b,&x)&&x==-1) puts(", we find both.");
exit(EXIT_SUCCESS);
}
Compiling and executing above C code results in the following output:
a is here.
b is not.
But if we adjust a to match b, we find both.
I will need to read a file and store a a large number of string:int pairs and then I will need to read a second file to check an even larger number of strings for previously stored values.
I don't see how this would be possible if keys are compared by reference.
How can I change my associative array implementation to store keys by value?
And if that's not possible, how can I work around that problem given the above use case?
edit:
This question just deals with keys entered but not found.
The opposite problem also appears and is described in detail in this question.
edit:
It turned out that store() needs to strdup() key to fix this and another problem.
I found out that by using the same variable for storage & lookup, I can actually retrieve all the values in the array:
void main(){
char a[4]="foo";
char b[4]="bar";
char c[4]="baz";
char t[4]="";
intptr_t x=NULL;
if(!hcreate(50)) exit_with_error("no hash");
strcpy(t,a); store(t, 1); /* a --> 1 */
strcpy(t,b); store(t,-1); /* b --> -1 */
strcpy(t,c); store(t, 0); /* c --> 0 */
if(!fetch(a,&x)) puts("a is not here.");
if(!fetch(b,&x)) puts("Neither is b.");
if( fetch(c,&x)) puts("c is in (and equal to t).");
strcpy(t,a); if(fetch(t,&x)&&x== 1) puts("t can retrieve a.");
strcpy(t,b); if(fetch(t,&x)&&x==-1) puts("It also finds b.");
strcpy(t,c); if(fetch(t,&x)&&x== 0) puts("And as expected c.");
exit(EXIT_SUCCESS);
}
This results in the following output:
a is not here.
Neither is b.
c is in (and equal to t).
t can retrieve a.
It also finds b.
And as expected c.
However, I still don't understand why this is happening.
Somehow it seems the key needs to be at the same location (reference) and contain the same content (value) to be found.
I'm writing a program in C for my beaglebone black to manipulate the gpio pins. This is a very crude program but its just a "beta" if you will. Just to get it up and running. My problem is that I have two character arrays. One holding a command to be passed to the system() function and another holding the path of the file that I am going to be editing, it goes to the fopen function. These character arrays are manipulated to change two numbers depending on what is passed to them from the calling function. For some reason the filename character array is being concatenated with the command. I'm skimming through the program but i don't see any obvious errors.
Here is my code
/*
* gpio.c
*
* Created on: Aug 26, 2014
* Author: Christian Macias
*
* Description: This will control your GPIO (General Purpose IO) pins on the beagle bone. Please
* ensure you are on a kernel that supports device trees.
*
* Usage: gpio(PIN, Value "1" or "0", Inverted? "0" false or "1" for true)
*
* The return value is 0 for success and -1 for failure
*
* GO UTEP!!
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int gpio(int pin, int value, int inv)
{
int sucfail=0;
int pinInt1, pinInt2=-1;
int counterOne=NULL;
char filename[28]= "/sys/class/gpio/gpio00/value";//27 characters
/*
* Checks if file is within the gpio pin range.
*/
if(pin<0 || pin>=99)
{
fprintf(stderr, "\n%s\n\t%s\n\t%s\n", "Error in gpio.c(GPIO): ", "The gpio pin selected is not "
"within the availabilty of the app", "Please select a pin from 0-99");
return -1;
}
/*
* checks to see if value is boolean aka 1 or 0
*/
if(value<0 || value>1)
{
fprintf(stderr, "\n%s\n\t%s\n\t%s", "Error in gpio.c(GPIO): ", "The Selected value is invalid", "Please"
" select a 1 or a 0");
return -1;
}
/*
* Writes the pin to a file so that it can used later
*/
FILE *PINWRITE;
PINWRITE=fopen("pinWRITE", "w+");
fprintf(PINWRITE,"%i", pin);
fclose(PINWRITE);
/*
* This section will check for pre-existence of the the PIN file to prevent errors. or
* opens it if it doesnt exist.
* First it will set up the filenames
*/
PINWRITE=fopen("pinWRITE","r");
fscanf(PINWRITE, "%1i%1i", &pinInt1, &pinInt2);//Checks the pin and sets each digit to its according variable
fclose(PINWRITE);
filename[20]='0'+pinInt1;
if(pinInt2==-1)//If it is a one digit pin, it will move the letters to fit the file name correctly and remove one of the digits
{
for(counterOne=21;counterOne<28;counterOne++)
{
filename[counterOne]=filename[counterOne+1];
}
filename[27]='\0';
}
else//If two digits it will just change the second digit
{
filename[21]='0'+pinInt2;
}
FILE *PINVALUE;//FILE pointer to the files with the value
PINVALUE=fopen(filename,"w+");
/*
* At this point the the actual checking and creation occurs
*/
char exportCommand[32]="echo 00 > /sys/class/gpio/export";//31 characters
if(PINVALUE==NULL)
{
//this runs if the file didnt exist.
exportCommand[5]='0'+pinInt1;
if(pinInt2==-1)//If it is a one digit pin, it will move the letters to fit the file name correctly and remove one of the digits
{
for(counterOne=6;counterOne<32;counterOne++)
{
exportCommand[counterOne]=exportCommand[counterOne+1];
}
exportCommand[31]='\0';
}
else//If two digits it will just change the second digit
{
exportCommand[6]='0'+pinInt2;
exportCommand[32]='\0';
}
system(exportCommand);
printf("\n%s\n", exportCommand);
printf("\n%s\n", filename);
PINVALUE=fopen(filename,"w+");
}
if(PINVALUE==NULL)
{
fprintf(stderr,"\n%s\n\t%s", "Error in gpio.c(GPIO)", "The PINVALUE (.../gpioXX/value) could not be opened");
return -1;
}
/*
* Some pins may be set up backward... on is off and off is on. To correct this we must adjust a file...
* This takes to long and i dont have the time for it so i'm doing a hot fix... sorry but its 11 and i have
* school tomorrow. The correction process it too long and i want to finish today :)
*/
if(inv==1 && value==1)
{
value=0;
}
else if(inv==1 && value==0)
{
value=1;
}
/*
* At this point the file is set up and ready to be written to.
* We will write the value now and close it.
*/
fprintf(PINVALUE, "%i", value);
fclose(PINVALUE);
return sucfail;
}
You are underestimating the length of string literals you want to copy into arrays, leaving no space for the nul terminator. For example, here
char filename[28]= "/sys/class/gpio/gpio00/value"; //27 characters
the literal actually has 28+1 characters (28 visible, plus a nul terminator).
You need to make the array of size 29. You can do this explicitly,
char filename[29] = "/sys/class/gpio/gpio00/value";
or implicitly:
char filename[] = "/sys/class/gpio/gpio00/value";
Similarly here, where you need the array to be of length 33:
char exportCommand[32]="echo 00 > /sys/class/gpio/export";
There may well be other errors. I would start by fixing those first. It will make finding the other ones easier.
This program is running with root privileges on my machine and I need to perform a Stack overflow attack on the following code and get root privileges:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <openssl/sha.h>
void sha256(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
int i = 0;
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int password_check(char *userpass)
{
char text[20] = "thisisasalt";
unsigned int password_match = 0;
char output[65] = { 0, };
// >>> hashlib.sha256("Hello, world!").hexdigest()
char pass[] = "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3";
text[0] = 'a';
text[1] = 't';
text[2] = 'j';
text[3] = '5';
text[4] = '3';
text[5] = 'k';
text[6] = '$';
text[7] = 'g';
text[8] = 'f';
text[9] = '[';
text[10] = ']';
text[11] = '\0';
strcat(text, userpass);
sha256(text, output);
if (strcmp(output, pass) == 0)
{
password_match = 1;
}
return (password_match == 1);
}
int main(int argc, char **argv)
{
if (argc < 3)
{
printf("Usage: %s <pass> <command>\n", argv[0]);
exit(1);
}
if (strlen((const char *) argv[1]) > 10)
{
printf("Error: pasword too long\n");
exit(1);
}
if (password_check(argv[1]))
{
printf("Running command as root: %s\n", argv[2]);
setuid(0);
setgid(0);
system(argv[2]);
}
else
{
printf("Authentication failed! This activity will be logged!\n");
}
return 0;
}
So I try to analyse the program with IDA and I see the text segment going from the lower addresses to the higher addresses, higher than that I see the data and then the bss and finally external commands.
Now as far as I know the stack should be just above that, but I'm not certain how to view it, how exactly am I supposed to view the stack in order to know what I'm writing on? (Do I even need it or am I completely clueless?)
Second question is considering the length of the input, how do i get around this check in the code:
if (strlen((const char *) argv[1]) > 10)
{
printf("Error: pasword too long\n");
exit(1);
}
Can I somehow give the string to the program by reference? If so how do I do it? (Again, hoping I'm not completely clueless)
Now as far as I know the stack should be just above that, but I'm not certain how to view it, how exactly am I supposed to view the stack in order to know what I'm writing on? (Do I even need it or am I completely clueless?)
The stack location varies all the time - you need to look at the value of the ESP/RSP register, its value is the current address of the top of the stack. Typically, variable addressing will be based on EBP rather then ESP, but they both will point to the same general area of memory.
During analysis, IDA sets up a stack frame for each function, which acts much like a struct - you can define variables with types and names in it. This frame is summarized at the top of the function:
Double-clicking it or any local variable in the function body will open a more detailed window. That's as good as you can get without actually running your program in a debugger.
You can see that text is right next to password_match, and judging from the addresses, there are 0x14 bytes allocated for text, as one would expect. However, this is not guaranteed and the compiler can freely shuffle the variables around, pad them or optimize them into registers.
Second question is considering the length of the input, how do i get around this check in the code:
if (strlen((const char *) argv[1]) > 10)
{
printf("Error: pasword too long\n");
exit(1);
}
You don't need to get around this check, it's already broken enough. There's an off-by-one error.
Stop reading here if you want to figure out the overflow yourself.
The valid range of indices for text spans from text[0] through text[19]. In the code, user input is written to the memory area starting at text[11]. The maximum input length allowed by the strlen check is 10 symbols + the NULL terminator. Unfortunately, that means text[19] contains the 9th user-entered symbol, and the 10th symbol + the terminator overflow into adjacent memory space. Under certain circumstances, that allows you to overwrite the least significant byte of password_match with an arbitrary value, and the second least significant byte with a 0. Your function accepts the password if password_match equals 1, which means the 10th character in your password needs to be '\x01' (note that this is not the same character as '1').
Here are two screenshots from IDA running as a debugger. text is highlighted in yellow, password_match is in green.
The password I entered was 123456789\x01.
Stack before user entered password is strcat'd into text.
Stack after strcat. Notice that password_match changed.
I am working with libmcrypt in c and attempting to implement a simple test of encryption and decryption using rijndael-256 as the algorithm of choice. I have mirrored this test implementation pretty closely to the man pages examples with rijndael as opposed to their chosen algorithms. When compiled with the string gcc -o encryption_test main.c -lmcrypt, the following source code produces output similar to:
The encrypted message buffer contains j��A��8 �qj��%`��jh���=ZЁ�j
The original string was ��m"�C��D�����Y�G�v6��s��zh�
Obviously, the decryption part is failing, but as it is just a single function call it leads me to believe the encryption scheme is not behaving correctly as well. I have several questions for the libmcrypt gurus out there if you could point me in the right direction.
First, what is causing this code to produce this broken output?
Second, when dealing with mandatory fixed-sizes such as the key size and block-size, for example a 256-bit key does the function expect 32-bytes of key + a trailing null byte, 31-bytes of key + a trailing null byte, or 32-bytes of key with the 33rd byte being irrelevant? The same question holds true for block-size as well.
Lastly, one of the examples I noted used mhash to generate a hash of the key-text to supply to the encryption call, this is of course preferable but it was commented out and linking in mhash seems to fail. What is the accepted way of handling this type of key-conversion when working with libmcrypt? I have chosen to leave any such complexities out as to prevent further complicating already broken code, but I would like to incorporate this into the final design. Below is the source code in question:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mcrypt.h>
int main(int argc, char *argv[])
{
MCRYPT mfd;
char *key;
char *plaintext;
char *IV;
unsigned char *message, *buffered_message, *ptr;
int i, blocks, key_size = 32, block_size = 32;
message = "Test Message";
/** Buffer message for encryption */
blocks = (int) (strlen(message) / block_size) + 1;
buffered_message = calloc(1, (blocks * block_size));
key = calloc(1, key_size);
strcpy(key, "&*GHLKPK7G1SD4CF%6HJ0(IV#X6f0(PK");
mfd = mcrypt_module_open(MCRYPT_RIJNDAEL_256, NULL, "cbc", NULL);
if(mfd == MCRYPT_FAILED)
{
printf("Mcrypt module open failed.\n");
return 1;
}
/** Generate random IV */
srand(time(0));
IV = malloc(mcrypt_enc_get_iv_size(mfd));
for(i = 0; i < mcrypt_enc_get_iv_size(mfd); i++)
{
IV[i] = rand();
}
/** Initialize cipher with key and IV */
i = mcrypt_generic_init(mfd, key, key_size, IV);
if(i < 0)
{
mcrypt_perror(i);
return 1;
}
strncpy(buffered_message, message, strlen(message));
mcrypt_generic(mfd, buffered_message, block_size);
printf("The encrypted message buffer contains %s\n", buffered_message);
mdecrypt_generic(mfd, buffered_message, block_size);
printf("The original string was %s\n", buffered_message);
mcrypt_generic_deinit(mfd);
mcrypt_module_close(mfd);
return 0;
}
You need to re-initialize the descriptor mfd for decryption, you cannot use the same descriptor for both encryption and decryption.