Buffer Overflow: Format String - string-formatting

Which input string should an attacker enter to get exactely the content of pw ?
void func(char *in)
{
char *pw = "53cr37p455";
printf(in);
}
void func2(void)
{
printf("Dummy string.\n");
}
int main(int argc, char *argv[])
{
char in[512];
printf("Buffer located at: 0x%x\n", &in[0]);
printf("Type in data: ");
fgets(in, 511, stdin);
func(in);
return 0;
}
Thanks in advance

Related

How to copy file in buffer without a string

I would like to copy a file in a buffer without a certain string
Here's the code
void remove_line(FILE *fp, char *string, char *output) {
char buff[6];
output = malloc(500);
int i = 0;
while (fgets(buff, 6, fp) != NULL) {
char temp[6];
strcpy(temp, buff);
temp[strcspn(temp, "\n")] = 0;
if (strcmp(temp, string) != 0) {
memcpy(output + i * 6, buff, 6);
i++;
}
}
printf("%s", output);
}
int main(int argc, char *argv[])
{
FILE *f;
f = fopen("file", "a+");
char *output = NULL;
char line[] = "hello";
remove_line(f, line, output);
fclose(f);
}
and the file contains :
hello
world
My goal is to only have "world" in buffer, but currently I have nothing.
Thanks you !

Replace a word in C

can you advice me? I have a string from a file. When i see the string on my console, i need to write the word on which i want to change, and output the result in another file. For example: "Hello my girl" the word i want change "girl" on another word "boy". I can use the library
Can you advice me the algorithm which helps me to change the word?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char my_string[256];
char* ptr;
FILE *f;
if ((f = fopen("test.txt", "r"))==NULL) {
printf("Cannot open test file.\n");
exit(1);}
FILE *out;
if((out=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
fgets (my_string,256,f);
printf ("result: %s\n",my_string);
ptr = strtok (my_string," ");
while (ptr != NULL)
{
printf ("%s \n",ptr);
ptr = strtok (NULL," ");
}
char old_word [10];
char new_word [10];
char* ptr_old;
char* ptr_new;
printf ("Enter your old word:\n");
ptr_old= gets (old_word);
printf ("Your old word:%s\n",old_word);
printf ("Enter new old word:\n");
ptr_new = gets (new_word);
printf ("Your new word:%s\n",new_word);
fclose(f);
fclose(out);
return 0;
}
i tried to split inputting string into words. Now its dead end.
This code will help you. you have to pass 4 args at runtime.
./a.out "oldword" "newword" "file name from take the old word" "file name where to copy"
$ ./a.out girl boy test.txt result.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int args, char *argv[4])
{
FILE *f1;
FILE *f2;
char *strings=0;
char *newstrings=0;
char *token=NULL;
strings=(char *)malloc(1000);
newstrings=(char *)malloc(1000);
if((strings==NULL)||(newstrings==NULL))
{
printf("Memory allocation was not successfull.");
return 0;
}
if(args<4)
{
puts("Error: Not enough input parameters");
puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
return 0;
}
f1=fopen(argv[3],"r");
f2=fopen(argv[4],"w");
if(f1==NULL)
{
puts("No such file exists");
return 0;
}
while(fgets(strings,1000,f1)!=NULL)
{
if(strstr(strings,argv[1])!=NULL)
{
token=strtok(strings,"\n\t ");
while(token!=NULL)
{
if(strcmp(token,argv[1])==0)
{
strcat(newstrings,argv[2]);
strcat(newstrings," ");
}
else
{
strcat(newstrings,token);
strcat(newstrings," ");
}
token=strtok(NULL,"\n\t ");
}
}
else
{
strcpy(newstrings,strings);
}
fputs(newstrings,f2);
}
free(strings);
free(newstrings);
printf("New file <%s> generated!\n",argv[4]);
fclose(f1);
fclose(f2);
return 0;
}
You can use a function like the shown function in the demonstrative program below
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * replace(const char *s, const char *src, const char *dsn)
{
size_t n = 0;
size_t src_len = strlen(src);
size_t dsn_len = strlen(dsn);
for (const char *p = s; (p = strstr(p, src)) != NULL; p += src_len)
{
n++;
}
char *result = malloc(strlen(s) + n * (src_len - dsn_len) + 1);
const char *p = s;
char *t = result;
if (n != 0)
{
for (const char *q; (q = strstr(p, src)) != NULL; p = q + src_len)
{
memcpy(t, p, q - p);
t += q - p;
memcpy(t, dsn, dsn_len);
t += dsn_len;
}
}
strcpy(t, p);
return result;
}
int main( void )
{
char s[] = " the girl and boy are relatives";
char *p = replace(s, "girl", "boy");
puts(s);
puts(p);
free(p);
}
The program output is
the girl and boy are relatives
the boy and boy are relatives
#include <stdio.h>
#include <string.h>
int main ()
{
char file_path[40] = { 0 }, stf[255] = { 0 }, rtf[255] = { 0 }, str[255] = { 0 };
FILE* file = NULL;
FILE *e_f;
if((e_f=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
do
{
printf("Enter file path: ");
fgets(file_path, 40, stdin);
file_path[strlen(file_path) - 1] = '\0';
file = fopen(file_path, "r+");
}
while(file == NULL);
printf("Enter text to find: ");
fgets(stf, 255, stdin);
stf[strlen(stf) - 1] = '\0';
printf("Enter text to replace: ");
fgets(rtf, 255, stdin);
rtf[strlen(rtf) - 1] = '\0';
while(fgets(str, 255, file) != NULL)
{
char* tmp_ptr = strstr(str, stf);
while(tmp_ptr != NULL)
{
char tmp_str[255];
strcpy(tmp_str, tmp_ptr + strlen(stf));
strcpy(str + strlen(str) - strlen(tmp_ptr), rtf);
strcat(str, tmp_str);
tmp_ptr = strstr(str, stf);
}
printf("%s", str);
}
fclose(file);
fclose(e_f);
return 0;
}
That was i need. Thanks everybody for helping!
I did a function:
#include <stdio.h>
#include <string.h>
#define MAX 50
void Change (char x[], char cx, char nu){
int i;
for(i=0;i<strlen(x);i++) {
if (x[i]==cx){
x[i] = nu;
}
}
}
int main () {
char str[MAX];
char ch;
char new;
printf("Insert the string\n");
scanf("%s",str);
printf("Insert the word that you want to change\n");
scanf(" %c",&ch);
printf("the new word\n");
scanf(" %c",&new);
Change(str, ch, new);
printf("The new word is %s\n",str );
return 0;
}

Read from a text file and use each line to compare if they are anagrams

I must modify my program to accept input from
a file called anagrams.txt.This file should have two strings per line, separated by the # character. My program should read
each pair of strings and report back if each pair of strings is an anagram. For example consider the following content of anagrams.txt:
hello#elloh
man#nam
Astro#Oastrrasd
Your program should print out the following:
hello#elloh - Anagrams!
man#nam - Anagrams!
Astro#Oastrrasd- Not anagrams!
I should compile in g++
Here is the code to read from text:
int main()
{
char input[30];
if(access( "anagrams.txt", F_OK ) != -1) {
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("anagrams.txt","r"); if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
printf("%s",buf);
fclose(ptr_file);
printf("\n");
}
else{ //if file does not exist
printf("\nFile not found!\n");
}
return 0;
}
Code to find if the text are anagrams:
#include <stdio.h>
int find_anagram(char [], char []);
int main()
{
char array1[100], array2[100];
int flag;
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
flag = find_anagram(array1, array2);
if (flag == 1)
printf(" %s and %s are anagrams.\n", array1, array2);
else
printf("%s and %s are not anagrams.\n", array1, array2);
return 0;
}
int find_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while (array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while (array2[i] != '\0')
{
num2[array2[i] -'a']++;
i++;
}
for (i = 0; i < 26; i++)
{
if (num1[i] != num2[i])
return 0;
}
return 1;
}
You can try something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXLINE 1000
#define MAXLETTER 256
int is_anagram(char *word1, char *word2);
void check_lines(FILE *filename);
int cmpfunc(const void *a, const void *b);
void convert_to_lowercase(char *word);
int
main(int argc, char const *argv[]) {
FILE *filename;
if ((filename = fopen("anagram.txt", "r")) == NULL) {
fprintf(stderr, "Error opening file\n");
exit(EXIT_FAILURE);
}
check_lines(filename);
fclose(filename);
return 0;
}
void
check_lines(FILE *filename) {
char line[MAXLINE];
char *word1, *word2, *copy1, *copy2;
while (fgets(line, MAXLINE, filename) != NULL) {
word1 = strtok(line, "#");
word2 = strtok(NULL, "\n");
copy1 = strdup(word1);
copy2 = strdup(word2);
convert_to_lowercase(copy1);
convert_to_lowercase(copy2);
if (is_anagram(copy1, copy2)) {
printf("%s#%s - Anagrams!\n", word1, word2);
} else {
printf("%s#%s - Not Anagrams!\n", word1, word2);
}
}
}
void
convert_to_lowercase(char *word) {
int i;
for (i = 0; word[i] != '\0'; i++) {
word[i] = tolower(word[i]);
}
}
int
is_anagram(char *word1, char *word2) {
qsort(word1, strlen(word1), sizeof(*word1), cmpfunc);
qsort(word2, strlen(word2), sizeof(*word2), cmpfunc);
if (strcmp(word1, word2) == 0) {
return 1;
}
return 0;
}
int
cmpfunc(const void *a, const void *b) {
if ((*(char*)a) < (*(char*)b)) {
return -1;
}
if ((*(char*)a) > (*(char*)b)) {
return +1;
}
return 0;
}
Since this looks like a University question, I won't provide a full solution, only a hint.
All you have to do is replace the stdin input part of the anagram-finding file with the code you wrote to read from a file: it's as simple as changing
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
to
// before program:
#define SIZE 1000
// inside main
if (access("anagrams.txt", F_OK) == -1){
printf("\nFile not found!\n");
return 1; // Abort the program early if we can't find the file
}
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("anagrams.txt","r");
if (!ptr_file)
return 1;
char array1[SIZE], array2[SIZE];
while (fgets(buf, 1000, ptr_file)!=NULL){
// do all your anagram stuff here!
// there is currently one line of the input file stored in buf
// Hint: You need to split buf into array_1 and array_2 using '#' to separate it.
}
fclose(ptr_file);
printf("\n");
Additional comments:
Don't ever ever ever use gets. gets doesn't check that the string it writes to can hold the data, which will cause your program to crash if it gets input bigger than the array size. Use fgets(buf, BUF_SIZE, stdin) instead.
Beautiful code is good code. People are more likely to help if they can read your code easily. (fix your brackets)
Just for interest, a more efficient algorithm for checking anagrams is to use qsort to sort both arrays, then a simple string matcher to compare them. This will have cost O(mnlog(m+n)), as opposed to O(m^2 n^2), awith the current algorithm
You need to split every line you read by fgets (as you did) in to two strings, and pass them to your find_anagram function. You can do that using strtok:
int main()
{
int flag;
char buf[1000];
FILE *ptr_file;
//Check file existence
//Open the file for reading
while (fgets (buf, 1000, ptr_file) != NULL)
{
char *array1 = strtok(buf, "#");
char *array2 = strtok(NULL, "\n");
flag = find_anagram (array1, array2);
//Check flag value to print your message
}
return 0;
}
//put your find_anagram function
Don't forget to #include <string.h> to use strtok().

Opening and Reading files fails

I am currently trying to read a file and count the number of instances of a user-specified string in an input file and output them to another file,.
However when I try to open the file, fopen returns NULL. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
//printf("string entered: %s\n%s\n%s", in, out, target);
return 0;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin);
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o,50,stdin);
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin);
return 1;
}
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char *data = NULL;
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(!feof(f))
{
fgets(data, sizeof(data), f);
p = strstr(data,t);
while (p != NULL)
{
c++;
p = strstr(p , t);
}
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}
Edit:
I've made some changes to the code following the responses and now, my program crashes on reading the file. New code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char data[1024];
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(fgets(data, sizeof(data), f))
{
fgets(data, sizeof(data), f);
p = strstr(data,t);
while (p != NULL)
c++; p = strstr(p+1 , t);
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin); i[strcspn(i, "\n")] = 0;
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o, 50, stdin); o[strcspn(o, "\n")] = 0;
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin); t[strcspn(t, "\n")] = 0;
return 1;
}
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
return 0;
}
try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getIns(char *i, char *o, char *t);
int Search(char *i, char *o, char *t);
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
//printf("string entered: %s\n%s\n%s", in, out, target);
return 0;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin);
i[strcspn(i, "\n")] = 0;
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o,50,stdin);
o[strcspn(o, "\n")] = 0;
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin);
t[strcspn(t, "\n")] = 0;
return 1;
}
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char data[1024];
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(fgets(data, sizeof(data), f)){
p = strstr(data,t);
while (p != NULL)
{
c++;
p = strstr(p+1 , t);
}
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}

how do i test to see if my program is storing info or writing over it

ok i have incluced my structure as well as my pointer, here is what i am trying to figure out, i need to store up to 5 peoples profiles, but i do not know how to store these in my array while using a pointer
if i don't have the pointer i can do it like this:
strcpy(user[0].UserName,"whatevername");
strcpy(user[0].UserName,"whateverpwd");
but how do i specify where in the array i want the info while using a point that points to my structure.. i hope this makes sense i don't think i can explain it any better
struct profile
{
char First[15];
char Last[15];
char Pwd[10];
char UserName[10];
};
struct profile user[100];
struct profile *puser;
puser=&user[0];
void add_user(struct profile *puser)
{
int i = 0;
int j = 0;
int quit = 0;
char fname[30];
char lname[30];
char username[30];
char password[30];
do
{
printf("Enter the first name of the user:\n");
fgets((puser+i)->First,15, stdin);
printf("Enter the last name of the user:\n");
fgets((puser+i)->Last, 15, stdin);
printf("Enter the username:\n");
fgets((puser+i)->UserName, 30, stdin);
printf("Enter the password:\n");
fgets((puser+i)->Pwd, 30, stdin);
printf("the first name is: %s\n", (puser+i)->First);
printf("the last name is: %s\n", (puser+i)->Last);
printf("the user name is: %s\n", (puser+i)->UserName);
printf("the password name is: %s\n", (puser+i)->Pwd);
j++;
printf("enter 0 to exit 1 to continue:");
scanf("%d", &quit);
if(quit == 0)
printf("goodbye");
i++;
getchar();
}while(quit == 1);
}
Try this:
#include <stdio.h>
typedef struct
{
char First[15];
char Last[15];
char Pwd[10];
char UserName[10];
}profile;
profile user[100];
profile *puser = user;
void add_user(profile *puser);
void add_user(profile *puser)
{
int i = 0;
int j = 0;
int quit = 0;
char fname[30];
char lname[30];
char username[30];
char password[30];
do
{
printf("Enter the first name of the user:\n");
fgets(puser[i].First,15, stdin);
printf("Enter the last name of the user:\n");
fgets(puser[i].Last, 15, stdin);
printf("Enter the username:\n");
fgets(puser[i].UserName, 30, stdin);
printf("Enter the password:\n");
fgets(puser[i].Pwd, 30, stdin);
printf("enter 0 to exit 1 to continue:");
scanf("%d", &quit);
getchar();
i++;
}while(quit == 1);
for( j = 0; j < i; j++ )
{
printf("first name[%d] is: %s\n", j,(puser+j)->First);
printf("last name[%d] is: %s\n", j,(puser+j)->Last);
printf("user name[%d] is: %s\n", j,(puser+j)->UserName);
printf("password[%d] is: %s\n", j,(puser+j)->Pwd);
}
printf("Goodbye\n");
}
int main(int argc, char *argv[])
{
add_user(puser);
return 0;
}

Resources