Check if a file exists on a given path in C - c

I'm writing a C program that functions like a shell. What it does is when user gives it a path, such as /bin, it needs to be able to check if a given executable program is on that path and if so, execute that program. From another question, I know I can check if a file exists using stat() function:
int file_exist (char *filename){
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it such as like this:
if (file_exist ("myfile.txt")) {
printf ("It exists\n");
}
But I have a path variable:
char* path = "/bin";
How do I search for an executable program is on this path, with the purpose of trying to execute it later on?

Related

Exploiting c - linux setuid and system commands

I have the following code as an executable that I want to exploit for a course in order to spawn a shell with elevated privileges. I am a user of levelX and the executable has setgid of levelX+1. I am not allowed to alter any of the code.
As I do not have root privileges, setguid(0) fails. I was not able to change the return address of the function or main function. Could anyone point to the right direction?
int main (int argc, char** argv)
{
if (exec(argv[1]) != 0)
{
fprintf(stderr, "Cannot execute your command\n");
return -1;
}
return 0;
}
int exec(char *command)
{
FILE *f = NULL;
char entry[64];
char line[256];
f = fopen("log", "a");
if (f == NULL)
{
fprintf(stderr, "Can't open file\n");
return -1;
}
snprintf(entry, 64, "%d: %s\n", getuid(), command);
fprintf(f, entry, NULL);
fclose(f);
f = fopen("sudoers", "r");
if (f == NULL)
{
fprintf(stderr, "Can't open\n");
return -1;
}
while(fgets(line, 256, f) != NULL)
{
if (atoi(line) == getuid())
{
if (setuid(0) == 0) {
system(command);
} else {
fprintf(stderr, "check permissions\n");
}
fclose(f);
return 0;
}
}
fprintf(stderr, "Error\n");
fclose(f);
return -1;
}
From the code you posted, it appears you are supposed to write your own sudoers file to any directory you have write access to, then run this program in that directory, so it reads your file.
So, simply write your own UID to this fake sudoers file, and then give a command parameter such as bash to get a shell. There's no need to do any buffer overflow exploitation.
Presumably the real exploitable program has suid bit set in the file permissions, so it can perform the setuid(0) call. I guess the purpose of the exercise is to demonstrate how all input needs to be sanitized when you are dealing with suid programs, including things like relative paths (which effectively take current working directory as input) like any user-supplied paths and other input.
But, since the program only has setgid bit (as said in comment), you need find something you do with just the group id. That something could be that log file write. You could create a symbolic link with file name log, pointing to whatever file you want to append to, which that group has write permissions for. Also, that file needs to have format such, that the log line format does not make the file corrupted. Remember, you can put newlines etc into command line arguments!
After all it was a format string exploit on fprintf(f, entry, NULL); inside int exec(char *command) where you overwrite the return address with %n format.

How to retrieve the file that is outside of current directory using format specifier?

char * read_file(char * filename) {
char * file_contents = malloc(4096 * sizeof(char));
FILE * file;
file = fopen(filename, "r");
fread(file_contents, 4096, sizeof(char), file);
fclose(file);
return file_contents;
}
char * read_flag() {
return read_file("/flag.txt"); // outside of current working directory ;)
}
int main(int argc, char* argv[]) {
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
char * flag = read_flag();
char input_filename[40];
//Current directory is /home/problem
printf("Current working directory is: ");
system("pwd");
printf("Enter a filename to print the contents of the file => ");
scanf("%39s", input_filename);
while ((directory_entry = readdir(directory)) != NULL) {
if (strcmp(input_filename, directory_entry->d_name) == 0) {
printf("File contents:\n");
printf("%s\n", read_file(input_filename));
return 0;
}
}
}
I need to open a file that is outside of this directory ("/flag.txt"). I have tried something like "../" in the input to get out from this directory but it is not working. I am not sure how do i enter the filename such that it can retrieve the file that is outside of the /home/problem directory. I am currently using Ubuntu to do this. I think the idea should be using something like %s%d when i enter my input. Is this possible to use any specifier or exploit this program in order to read the entire contents?
You need to pass the full path to your file if it is outside the solution directory either with \\ or one /. On a windows based system this would be for example C:\\folder\\file.txt. I do not use linux currently, but it should be /home/folder/file.txt.
The fopen function can fail, and you should handle that. Read fopen(3), open(2), path_resolution(7), errno(3) to understand the possible failure reasons. Details could be file system and computer specific (and could include hardware failures).
I recommend using perror(3) and exit(3) on failure (don't forget to include both <stdio.h> for perror and <stdlib.h> for exit):
FILE* file = fopen(filename, "r");
if (!file) {
perror(filename);
exit(EXIT_FAILURE);
}
then you'll get a meaningful error message (into stderr) on failure
My guess: your root file system (and root directory / ...) don't have a flag.txt file and you might want to retrieve what your shell understands from ~/flag.txt. Perhaps you want to retrieve it in your home directory (then build its file path, using getenv("HOME") on Linux or Unix; see this).
Read also about globbing, and glob(7).
Read also some Linux programming book, perhaps the old ALP.

check if something exists and is executable in C, using stat function

For example, I have directory a and b under my current working directory. I'm trying to locate file X, how can I modify the stat() command so that it checks both directory a and b instead of just current working directory? would stat(a/file, &buf) work? also, to check if it's executable, I know the code is buf.S_IXUSR, does if (buf.S_IXUSR) work?
thanks!
I suggest you consult the stat(2) man page.
Here's an example of how to use stat:
struct stat buf;
if (stat("a/file", &buf) != 0) {
// handle failure
}
// Check the `st_mode` field to see if the `S_IXUSR` bit is set
if (buf.st_mode & S_IXUSR) {
// Executable by user
}
However, for your use case, you might consider access(2) instead:
if (access("/path/to/file", X_OK) == 0) {
// File exists and is executable by the calling process's
// _real_ UID / GID.
}

'fopen' in C can't open existing file in current directoy on Unix

I am using fopen(3) in C to read file and process it. The file is present in current working directory where the binary exists, but I am unable to read the file (Linux environment / Cygwin environment).
Here is the sample code:
C code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *inFile;
static char fileName[255];
int process_file(FILE *inFile)
{
char ch;
inFile = fopen(fileName,"r");
if (inFile == NULL)
{
perror(fileName);
exit(1);
}
else
{
// Process file
}
fclose(inFile);
return 0;
}
int main(int argc, char *argv[])
{
printf("Enter filename to process \n");
scanf("%s", fileName);
process_file(inFile);
getchar();
return 0;
}
I have file permissions set to 777 in the current directory. The resulting binary as well as my source code reside in this directory where the input file exits. Why is the file not opened?
Update :
This question was written in few years back and this code could be improved a lot.
1. The process file should accept char * or char array instead of file pointer
2. unused variables can be removed
3. unused libraries or include files can be removed
4. Can make use of argv to accept filename with path from cmdline
5. return instead of exit in process_file and also proper return code instead of returning 0 from process_file.
I should have asked this question little more elaborate...
I had three functions to process the same file, like process_fil1e1(), process_file2() and process_file3() even though I called fclose() in all three functions. Somehow the file handle was not closed that properly or the file pointer pointed to EOF or some undefined behavior. It was not working fine.
When I used a single process file and rewind() together, it worked fine...
Be sure to input file name with its extension. This may cause problems with reading the file.
If you know the extension of the file you can input only the name and after that make the program add the extension. After scanf("%s", fileName); add strcat(fileName, ".txt"); if you want to enter only the name without extension and the file you read has extension .txt.
Your inFile and fileName variables are extern so you don't need to have arguments for the function process_file();, any function can access those variables.
You can change function int process_file(); to void process_file(); and delete return 0, you don't need that.
You have declared the inFile and fileName as global. You should change your function prototype from
int process_file(FILE *inFile)
to
int process_file()
This would at least make your program more clear. Now regarding your problem: It would almost certain be that you are doing something wrong in the input file (like not putting in the file extension) in your input. Remember, you need to pass the complete file name (including the extension which on some systems like Windows (by default) would be hidden). Otherwise, the logic looks correct to me, and it should work fine.

C Test For File Existence Before Calling execvp

I'm writing a UNIX minishell on ubuntu, and am trying to add built-in commands at this point. When it's not a built-in command I fork and then the child executes it, however for built-in commands I'll just execute it in the current process.
So, I need a way to see if the files exist(if they do it's not a built-in command), however execvp uses the environment PATH variable to automatically look for them, so I have no idea how I would manually check beforehand.
So, do you guys know how I could test an argument to see if it's a built-in command simply by supplying the name?
Thanks guys.
I have tested the answer by Tom
It contained a number of problems. I have fixed them here and provided a test program.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int is_file(const char* path) {
struct stat buf;
stat(path, &buf);
return S_ISREG(buf.st_mode);
}
/*
* returns non-zero if the file is a file in the system path, and executable
*/
int is_executable_in_path(char *name)
{
char *path = getenv("PATH");
char *item = NULL;
int found = 0;
if (!path)
return 0;
path = strdup(path);
char real_path[4096]; // or PATH_MAX or something smarter
for (item = strtok(path, ":"); (!found) && item; item = strtok(NULL, ":"))
{
sprintf(real_path, "%s/%s", item, name);
// printf("Testing %s\n", real_path);
if ( is_file(real_path) && !(
access(real_path, F_OK)
|| access(real_path, X_OK))) // check if the file exists and is executable
{
found = 1;
}
}
free(path);
return found;
}
int main()
{
if (is_executable_in_path("."))
puts(". is executable");
if (is_executable_in_path("echo"))
puts("echo is executable");
}
Notes
the test for access return value was reversed
the second strtok call had the wrong delimiter
strtok changed the path argument. My sample uses a copy
there was nothing to guarantee a proper path separator char in the concatenated real_path
there was no check whether the matched file was actually a file (directories can be 'executable' too). This leads to strange things like . being recognized as an external binary
What you can do is you can change the path to the particular directory and then use #include<dirent.h> header file and its readdir and scandir functions to walk through the directory or stat structure to see if the file exists in the directory or not.
You can iterate yourself through the PATH directories, and for each entry in PATH (You will have to split PATH with :, probably using strtok) concatenate at the end of each path the name of the command called. When you have create this path, check if the file exists and if it is executable using access.
int is_built_in(char *path, char *name)
{
char *item = strtok(path, ":");
do {
char real_path[4096] = strcat(item, name); // you would normally alloc exactly the size needed but lets stick to it for the sake of the example
if (!access(real_path, F_OK) && !access(real_path, X_OK)) // check if the file exists and is executable
return 0;
} while ((item = strtok(NULL, ":")) != NULL);
return 1;
}
Why do you want to test before calling execvp? That's the wrong approach. Just call execvp and it will tell you if the program does not exist.

Resources