-
Notifications
You must be signed in to change notification settings - Fork 0
/
runns.c
459 lines (396 loc) · 11.8 KB
/
runns.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* vim:et:sw=2:
*
* Copyright (c) 2019-2024 Nikita (sh1r4s3) Ermakov <[email protected]>
* SPDX-License-Identifier: MIT
*/
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
#include <grp.h>
#include <syslog.h>
#include <fcntl.h>
#include "runns.h"
#include <sched.h>
#include <libgen.h>
#include <limits.h>
// Emit log message
#define ERR(format, ...) \
do { \
syslog(LOG_INFO | LOG_DAEMON, "runns.c:%d / errno=%d / " format "\n", __LINE__, errno, ##__VA_ARGS__); \
stop_daemon(0); \
} while (0)
#define WARN(format, ...) \
do { \
syslog(LOG_INFO | LOG_DAEMON, "runns.c:%d / warning / " format "\n", __LINE__, ##__VA_ARGS__); \
} while (0)
#define INFO(format, ...) \
{ \
syslog(LOG_INFO | LOG_DAEMON, "runns.c:%d / info / " format "\n", __LINE__, ##__VA_ARGS__); \
} while (0)
struct runns_header hdr = {0};
int sockfd = 0;
struct runns_child childs[MAX_CHILDS] = {0};
unsigned int childs_run = 0;
char *program = 0;
char *netns = 0;
char **args = 0;
char **envs = 0;
int *glob_pid = 0;
char runns_socket[PATH_MAX] = DEFAULT_RUNNS_SOCKET;
char runns_socket_dir[PATH_MAX] = {0};
enum is_default_dir {default_dir, not_default_dir} defdir = default_dir;
struct ucred cred;
int drop_priv(uid_t _uid);
void stop_daemon(int flag);
int clean_pids();
void free_tvars();
int create_ptms();
int clean_socket();
int parse_flag(int data_sockfd);
int do_netns(int data_sockfd);
struct option opts[] =
{
{ .name = "help", .has_arg = 0, .flag = 0, .val = 'h' },
{ .name = "dir", .has_arg = 1, .flag = 0, .val = 'd' },
{ .name = "socket", .has_arg = 1, .flag = 0, .val = 's' },
{ 0, 0, 0, 0 }
};
void help_me() {
const char *hstr = \
"runns [options]\n" \
"Options:\n" \
"-h|--help help\n" \
"-s|--socket override default runns socket path (" DEFAULT_RUNNS_SOCKET ")\n";
puts(hstr);
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv) {
const char *optstring = "hs:";
int opt;
int len;
while ((opt = getopt_long(argc, argv, optstring, opts, 0)) != -1) {
switch (opt) {
case 'h':
help_me();
break;
case 's':
// Get absolute path
if (!realpath(dirname(optarg), runns_socket)) {
fputs("Can't get a real path\n", stderr);
ERR("Can't get a real path of the socket filename");
}
len = strlen(runns_socket);
runns_socket[len] = '/';
runns_socket[++len] = '\0';
strncat(runns_socket,
basename(optarg),
PATH_MAX - len - 1 /* subtract len and new line */);
len = strlen(runns_socket);
if (len >= RUNNS_MAXLEN) {
fputs("Socket file name is too long > " STR_TOKEN(RUNNS_MAXLEN) "\n", stderr);
ERR("Socket file name length is greater than " STR_TOKEN(RUNNS_MAXLEN));
}
defdir = not_default_dir;
break;
default:
ERR("Wrong option: %c", (char)opt);
}
}
struct sockaddr_un addr = {.sun_family = AF_UNIX, .sun_path = {0}};
memcpy(addr.sun_path, runns_socket, strlen(runns_socket) + 1);
char *last_slash = strrchr(runns_socket, '/');
if (!last_slash)
ERR("Can't deduce directory name in %s", runns_socket);
memcpy(runns_socket_dir, runns_socket, last_slash - runns_socket);
// Check the root
if (getuid() != 0) {
extern FILE *stderr;
fputs("Please run as a root user\n", stderr);
ERR("Only root can run the runns daemon");
}
glob_pid = mmap(NULL, sizeof(glob_pid), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (!glob_pid)
ERR("Can't allocate memory");
if (daemon(0, 0))
ERR("Can't daemonize the process");
// Set safe umask and create directory.
umask(0022);
if (defdir == default_dir) {
if (!access(runns_socket, F_OK)) {
WARN("Old socket file %s has been found", runns_socket);
if (unlink(runns_socket))
ERR("Can't remove the socket file");
else
INFO("Old socket file has been removed");
}
else {
if (access(runns_socket_dir, F_OK)) {
if (mkdir(runns_socket_dir, 0755) < 0)
ERR("Can't create directory %s", runns_socket_dir);
}
}
}
// Up daemon socket.
sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (sockfd == -1)
ERR("Something gone very wrong, socket = %d", sockfd);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
ERR("Can't bind socket to %s", addr.sun_path);
// Switch permissions and group.
struct group *group;
group = getgrnam("runns");
if (!group)
ERR("Can't get runns group\n");
if (chown(addr.sun_path, 0, group->gr_gid) ||
chmod(addr.sun_path, 0775)) {
ERR("Can't chown/chmod");
}
INFO("runns daemon has started");
while (1) {
if (listen(sockfd, 16) == -1)
ERR("Can't start listen socket %d (%s)", sockfd, addr.sun_path);
int data_sockfd = accept(sockfd, 0, 0);
if (data_sockfd == -1)
ERR("Can't accept connection");
const socklen_t cred_len = (socklen_t)sizeof(struct ucred);
if (getsockopt(data_sockfd, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) == -1) {
WARN("Can't get user credentials");
close(data_sockfd);
continue;
}
int ret = read(data_sockfd, (void *)&hdr, sizeof(hdr));
if (ret == -1)
WARN("Can't read data");
if (parse_flag(data_sockfd))
continue;
// Read the operational mode
INFO("op mode = %d", hdr.op_mode);
switch (hdr.op_mode) {
case OP_MODE_FWD_PORT:
// TODO: Handle OP_MODE_FWD_PORT
INFO("Nothing can be done for OP_MODE_FWD_PORT yet. Skip");
break;
case OP_MODE_NETNS:
do_netns(data_sockfd);
break;
default:
WARN("Skipping. Unknown op mode");
}
}
return 0;
}
int drop_priv(uid_t _uid) {
struct passwd *pw = getpwuid(_uid);
if (pw) {
uid_t uid = pw->pw_uid;
gid_t gid = pw->pw_gid;
if (initgroups(pw->pw_name, gid) != 0)
ERR("Couldn't initialize the supplementary group list");
endpwent();
if (setgid(gid) != 0 || setuid(uid) != 0) {
ERR("Couldn't change to '%.32s' uid=%lu gid=%lu",
pw->pw_name,
(unsigned long)uid,
(unsigned long)gid);
}
if (chdir(pw->pw_dir)) {
ERR("Couldn't chdir to %s for '%.32s' uid=%lu gid=%lu",
pw->pw_dir,
pw->pw_name,
(unsigned long)uid,
(unsigned long)gid);
}
}
else
ERR("Couldn't find a user with UID=%d", _uid);
}
void stop_daemon(int flag) {
INFO("runns daemon going down");
if (sockfd) {
close(sockfd);
unlink(runns_socket);
if (defdir == default_dir)
rmdir(runns_socket_dir);
}
free_tvars();
munmap(glob_pid, sizeof(glob_pid));
int ret = flag ? flag & RUNNS_STOP : EXIT_FAILURE;
exit(ret);
}
int clean_pids() {
for (unsigned int i = childs_run; i > 0 ; i--)
{
if (kill(childs[i - 1].pid, 0))
{
if (i != childs_run)
{
memcpy(childs + i - 1, childs + childs_run - 1, sizeof(struct runns_child));
}
--childs_run;
}
}
}
void free_tvars() {
free(program);
free(netns);
if (args)
for (size_t i = 1; i < hdr.args_sz - 3; free(args[i++]));
if (envs)
for (size_t i = 0; i < hdr.env_sz - 2; free(envs[i++]));
free(envs);
free(args);
memset((void *)&hdr, 1, sizeof(hdr));
}
int create_ptms() {
int ptmfd = open("/dev/ptmx", O_RDWR);
char ptsname[0xff];
if (ptsname_r(ptmfd, ptsname, 0xff)) {
WARN("Fail to get ptsname, errno=%d", errno);
return errno;
}
if (grantpt(ptmfd)) {
WARN("Fail to grant access to the slave pt, errno=%d", errno);
return errno;
}
if (unlockpt(ptmfd)) {
WARN("Fail to unlock a pt, errno=%d", errno);
return errno;
}
int ptsfd = open(ptsname, O_RDWR);
tcsetattr(ptsfd, TCSANOW, &hdr.tmode);
if (dup2(ptsfd, STDIN_FILENO) == -1) {
WARN("Fail to dup2 pt for stdin, errno=%d", errno);
return errno;
}
if (dup2(ptsfd, STDOUT_FILENO) == -1) {
WARN("Fail to dup2 pt for stdout, errno=%d", errno);
return errno;
}
if (dup2(ptsfd, STDERR_FILENO) == -1) {
WARN("Fail to dup2 pt for stderr, errno=%d", errno);
return errno;
}
return 0;
}
int parse_flag(int data_sockfd) {
// Stop daemon on demand.
if (hdr.flag & RUNNS_STOP) {
if (cred.uid == 0) {
INFO("closing");
close(data_sockfd);
stop_daemon(hdr.flag); // Should never returns
}
else {
WARN("Client with %d UID tried to kill the daemon ", cred.uid);
return 1;
}
}
// Transfer list of childs
if (hdr.flag & RUNNS_LIST) {
// TODO rets
INFO("uid=%d ask for pid list", cred.uid);
clean_pids();
// Count the number of jobs for uid
unsigned int jobs = 0;
for (int i = 0; i < childs_run; i++) {
if (childs[i].uid == cred.uid)
++jobs;
}
if (write(data_sockfd, (void *)&jobs, sizeof(jobs)) == -1)
ERR("Can't send number of jobs to the client %d", cred.uid);
for (unsigned int i = 0; i < jobs; i++) {
if (write(data_sockfd, (void *)&childs[i], sizeof(struct runns_child)) == -1)
ERR("Can't send child info to the client %d", cred.uid);
}
close(data_sockfd);
return 1;
}
return 0;
}
int do_netns(int data_sockfd) {
int ret;
// Read program name and network namespace name
program = (char *)malloc(hdr.prog_sz);
netns = (char *)malloc(hdr.netns_sz);
if (!program || !netns)
ERR("Can't allocate memory (program=%p, netns=%p", program, netns);
ret = read(data_sockfd, (void *)program, hdr.prog_sz);
ret = read(data_sockfd, (void *)netns, hdr.netns_sz);
INFO("uid=%d program=%s netns=%s", cred.uid, program, netns);
// Read argv for the program
if (hdr.args_sz) {
hdr.args_sz += 2; // program name + null at the end
args = (char **)malloc(hdr.args_sz*sizeof(char *));
if (!args)
ERR("Can't allocate memory (args = %p)", args);
args[0] = program;
args[hdr.args_sz - 1] = 0;
for (int i = 1; i < hdr.args_sz - 1; i++) {
size_t sz;
ret = read(data_sockfd, (void *)&sz, sizeof(size_t));
args[i] = (char *)malloc(sz);
ret = read(data_sockfd, (void *)args[i], sz);
}
}
else
args = 0;
// Read environment variables
if (hdr.env_sz) {
envs = (char **)malloc(++hdr.env_sz*sizeof(char *));
for (int i = 0; i < hdr.env_sz - 1; i++) {
size_t env_sz;
ret = read(data_sockfd, (void *)&env_sz, sizeof(size_t));
envs[i] = (char *)malloc(env_sz);
ret = read(data_sockfd, (void *)envs[i], env_sz);
}
envs[hdr.env_sz - 1] = 0;
}
else
envs = 0;
close(data_sockfd);
clean_pids();
if (childs_run < MAX_CHILDS) {
// Make fork
pid_t child = fork();
if (child == -1)
ERR("Fail on fork");
// Child
if (child == 0) {
child = fork();
if (child != 0) {
*glob_pid = child;
exit(0);
}
// Un-map shared memory from the parent.
munmap(glob_pid, sizeof(glob_pid));
// Detach child from parent
setsid();
// Redirect stdin, stdout, stderr to new PTS
if (hdr.flag & RUNNS_NPTMS) {
int err;
if (err = create_ptms()) {
exit(err);
}
}
int netfd = open(netns, 0);
setns(netfd, CLONE_NEWNET);
drop_priv(cred.uid);
if (execve(program, (char * const *)args, (char * const *)envs) == -1) {
WARN("Can not run %s, execve failed with errno=%d", program, errno);
return EXIT_FAILURE;
}
}
else
waitpid(child, 0, 0);
// Save child.
INFO("Forked %d", *glob_pid);
childs[childs_run].uid = cred.uid;
childs[childs_run].pid = *glob_pid;
++childs_run;
free_tvars();
}
else
INFO("Maximum number of childs has been reached.");
}