【发布时间】:2015-09-12 16:34:06
【问题描述】:
我是 C 新手,遇到了一些问题。这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int read_password(FILE *file, char *password, size_t n) {
fgets(password, n, file);
password[strcspn(password, "\n")] = '\0';
}
void elevated_shell(){
gid_t gid = getegid();
setresgid(gid,gid,gid);
fflush(stdout);
system("/bin/bash");
}
void regular_shell(){
gid_t gid = getgid();
setresgid(gid,gid,gid);
fflush(stdout);
system("/bin/bash");
}
int main(int argc, char **argv){
char flag[100];
char password[100];
FILE *file;
printf("Hi! Welcome to my secure shell software!\n");
// Read in the root password
file = fopen("flag.txt", "r");
if(file == NULL) {
printf("FAIL: Failed to open the password file\n");
return -3;
} else {
read_password(file, flag, sizeof(flag));
}
// Read in the user's password
printf("Please enter the password: ");
fflush(stdout);
read_password(stdin, password, sizeof(password));
if(strcmp(flag,password) == 0) {
printf("Correct! Here's an elevated shell :)\n");
elevated_shell();
} else {
printf("Incorrect! No elevated shell for you >:)\n");
regular_shell();
}
}
所以,我已经编译了这个文件并运行了。当我直接运行它时它工作正常,但每当我尝试使用 gdb 检查内存时它就会崩溃。例如,当在 main 函数处设置断点并运行程序时,fopen 函数返回 Null,因为程序打印输出 FAIL:打开密码文件失败并退出。希望你能帮忙。
【问题讨论】:
-
没有打开预期的文件是“崩溃”吗?找不到文件可能是有原因的。
-
也许您在另一个目录中运行 gdb?该程序在此目录中查找
flag.txt,但没有找到任何内容。在这种情况下,问题与 gdb 无关。 -
txt文件在这个目录下
-
无法复制。您的代码在 gdb 或我的 FreeBSD 10 系统下运行良好(一旦我将
read_password声明为void,并将 bash 替换为 sh) -
如果你的程序打印“FAIL: Failed to open the password file\n”,那么文件由于某种原因无法打开,可能是因为你不在正确的目录中。
标签: c