Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/src/exec_pty.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2009-2025 Todd C. Miller <[email protected]>
5
*
6
* Permission to use, copy, modify, and distribute this software for any
7
* purpose with or without fee is hereby granted, provided that the above
8
* copyright notice and this permission notice appear in all copies.
9
*
10
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
*/
18
19
#include <config.h>
20
21
#include <sys/types.h>
22
#include <sys/stat.h>
23
#include <sys/socket.h>
24
#include <sys/wait.h>
25
#include <sys/ioctl.h>
26
27
#if defined(HAVE_STDINT_H)
28
# include <stdint.h>
29
#elif defined(HAVE_INTTYPES_H)
30
# include <inttypes.h>
31
#endif
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <unistd.h>
36
#include <errno.h>
37
#include <fcntl.h>
38
#include <signal.h>
39
#include <termios.h> /* for struct winsize on HP-UX */
40
41
#include <sudo.h>
42
#include <sudo_exec.h>
43
#include <sudo_plugin.h>
44
#include <sudo_plugin_int.h>
45
46
/* Tail queue of messages to send to the monitor. */
47
struct monitor_message {
48
TAILQ_ENTRY(monitor_message) entries;
49
struct command_status cstat;
50
};
51
TAILQ_HEAD(monitor_message_list, monitor_message);
52
static struct monitor_message_list monitor_messages =
53
TAILQ_HEAD_INITIALIZER(monitor_messages);
54
static unsigned int term_raw_flags;
55
static struct exec_closure pty_ec;
56
57
static void sync_ttysize(struct exec_closure *ec);
58
static void schedule_signal(struct exec_closure *ec, int signo);
59
static void send_command_status(struct exec_closure *ec, int type, int val);
60
61
/*
62
* Restore user's terminal settings and update utmp, as needed.
63
*/
64
static void
65
pty_cleanup(struct exec_closure *ec, int wstatus)
66
{
67
debug_decl(pty_cleanup, SUDO_DEBUG_EXEC);
68
69
/* Restore terminal settings. */
70
if (ec->term_raw) {
71
/* Only restore the terminal if sudo is the foreground process. */
72
const pid_t tcpgrp = tcgetpgrp(io_fds[SFD_USERTTY]);
73
if (tcpgrp == ec->ppgrp) {
74
if (!sudo_term_restore(io_fds[SFD_USERTTY], false))
75
sudo_warn("%s", U_("unable to restore terminal settings"));
76
ec->term_raw = false;
77
}
78
}
79
80
/* Update utmp */
81
if (ISSET(ec->details->flags, CD_SET_UTMP) && ec->ptyname != NULL)
82
utmp_logout(ec->ptyname, wstatus);
83
84
debug_return;
85
}
86
87
/*
88
* Cleanup hook for sudo_fatal()/sudo_fatalx()
89
*/
90
static void
91
pty_cleanup_hook(void)
92
{
93
pty_cleanup(&pty_ec, 0);
94
}
95
96
/*
97
* Allocate a pty if /dev/tty is a tty.
98
* Fills in io_fds[SFD_USERTTY], io_fds[SFD_LEADER] and io_fds[SFD_FOLLOWER].
99
* Returns the dynamically allocated pty name on success, NULL on failure.
100
*/
101
static bool
102
pty_setup(struct exec_closure *ec)
103
{
104
struct command_details *details = ec->details;
105
debug_decl(pty_setup, SUDO_DEBUG_EXEC);
106
107
io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR);
108
if (io_fds[SFD_USERTTY] == -1) {
109
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: no %s, not allocating a pty",
110
__func__, _PATH_TTY);
111
debug_return_bool(false);
112
}
113
114
ec->ptyname = get_pty(&io_fds[SFD_LEADER], &io_fds[SFD_FOLLOWER],
115
details->cred.euid);
116
if (ec->ptyname == NULL)
117
sudo_fatal("%s", U_("unable to allocate pty"));
118
119
/* Add entry to utmp/utmpx? */
120
if (ISSET(details->flags, CD_SET_UTMP)) {
121
utmp_login(details->tty, ec->ptyname, io_fds[SFD_FOLLOWER],
122
details->utmp_user);
123
}
124
125
/* Update tty name in command details (used by monitor, SELinux, AIX). */
126
details->tty = ec->ptyname;
127
128
/* Register cleanup function. */
129
sudo_fatal_callback_register(pty_cleanup_hook);
130
131
sudo_debug_printf(SUDO_DEBUG_INFO,
132
"%s: %s fd %d, pty leader fd %d, pty follower fd %d",
133
__func__, _PATH_TTY, io_fds[SFD_USERTTY], io_fds[SFD_LEADER],
134
io_fds[SFD_FOLLOWER]);
135
136
debug_return_bool(true);
137
}
138
139
/*
140
* Check whether sudo is running in the foreground.
141
* Updates the foreground flag in the closure.
142
* Returns 0 if there is no tty, the foreground process group ID
143
* on success, or -1 on failure (tty revoked).
144
*/
145
static pid_t
146
check_foreground(struct exec_closure *ec)
147
{
148
int ret = 0;
149
debug_decl(check_foreground, SUDO_DEBUG_EXEC);
150
151
if (io_fds[SFD_USERTTY] != -1) {
152
if ((ret = tcgetpgrp(io_fds[SFD_USERTTY])) != -1) {
153
ec->foreground = ret == ec->ppgrp;
154
}
155
}
156
debug_return_int(ret);
157
}
158
159
/*
160
* Restore the terminal when sudo is resumed in response to SIGCONT.
161
*/
162
static bool
163
resume_terminal(struct exec_closure *ec)
164
{
165
debug_decl(resume_terminal, SUDO_DEBUG_EXEC);
166
167
if (check_foreground(ec) == -1) {
168
/* User's tty was revoked. */
169
debug_return_bool(false);
170
}
171
172
/* Update the pty settings based on the user's terminal. */
173
if (!sudo_term_copy(io_fds[SFD_USERTTY], io_fds[SFD_LEADER])) {
174
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO,
175
"%s: unable to copy terminal settings to pty", __func__);
176
debug_return_bool(false);
177
}
178
sync_ttysize(ec);
179
180
sudo_debug_printf(SUDO_DEBUG_INFO, "parent is in %s (%s -> %s)",
181
ec->foreground ? "foreground" : "background",
182
ec->term_raw ? "raw" : "cooked",
183
ec->foreground ? "raw" : "cooked");
184
185
if (ec->foreground) {
186
/* Foreground process, set tty to raw mode. */
187
ec->term_raw = sudo_term_raw(io_fds[SFD_USERTTY], term_raw_flags);
188
} else {
189
/* Background process, no access to tty. */
190
ec->term_raw = false;
191
}
192
193
debug_return_bool(true);
194
}
195
196
/*
197
* Suspend sudo if the underlying command is suspended.
198
* Returns SIGCONT_FG if the command should be resumed in the
199
* foreground or SIGCONT_BG if it is a background process.
200
*/
201
static int
202
suspend_sudo_pty(struct exec_closure *ec, int signo)
203
{
204
char signame[SIG2STR_MAX];
205
struct sigaction sa, osa, saved_sigcont;
206
int ret = 0;
207
debug_decl(suspend_sudo_pty, SUDO_DEBUG_EXEC);
208
209
/*
210
* Ignore SIGCONT when we suspend to avoid calling resume_terminal()
211
* multiple times.
212
*/
213
memset(&sa, 0, sizeof(sa));
214
sigemptyset(&sa.sa_mask);
215
sa.sa_flags = SA_RESTART;
216
sa.sa_handler = SIG_DFL;
217
if (sudo_sigaction(SIGCONT, &sa, &saved_sigcont) != 0)
218
sudo_warn("%s", U_("unable to set handler for SIGCONT"));
219
220
if (sig2str(signo, signame) == -1)
221
(void)snprintf(signame, sizeof(signame), "%d", signo);
222
223
switch (signo) {
224
case SIGTTOU:
225
case SIGTTIN:
226
/*
227
* If sudo is already the foreground process, just resume the command
228
* in the foreground. If not, we'll suspend sudo and resume later.
229
*/
230
if (!ec->foreground) {
231
if (check_foreground(ec) == -1) {
232
/* User's tty was revoked. */
233
break;
234
}
235
}
236
if (ec->foreground) {
237
sudo_debug_printf(SUDO_DEBUG_INFO,
238
"%s: command received SIG%s, parent running in the foreground",
239
__func__, signame);
240
if (!ec->term_raw) {
241
if (sudo_term_raw(io_fds[SFD_USERTTY], term_raw_flags))
242
ec->term_raw = true;
243
}
244
ret = SIGCONT_FG; /* resume command in foreground */
245
break;
246
}
247
FALLTHROUGH;
248
case SIGSTOP:
249
case SIGTSTP:
250
default:
251
/* Flush any remaining output and deschedule I/O events. */
252
del_io_events(true);
253
254
/* Restore original tty mode before suspending. */
255
if (ec->term_raw) {
256
if (!sudo_term_restore(io_fds[SFD_USERTTY], false))
257
sudo_warn("%s", U_("unable to restore terminal settings"));
258
ec->term_raw = false;
259
}
260
261
/* Log the suspend event. */
262
log_suspend(ec, signo);
263
264
/* Suspend self and continue command when we resume. */
265
if (signo != SIGSTOP) {
266
if (sudo_sigaction(signo, &sa, &osa) != 0)
267
sudo_warn(U_("unable to set handler for SIG%s"), signame);
268
}
269
270
/*
271
* We stop sudo's process group, even if sudo is not the process
272
* group leader. If we only send the signal to sudo itself,
273
* the shell will not notice if it is not in monitor mode.
274
* This can happen when sudo is run from a shell script, for
275
* example. In this case we need to signal the shell itself.
276
* If the process group leader is no longer present, we must kill
277
* the command since there will be no one to resume us.
278
*/
279
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: killpg(%d, SIG%s) [parent]",
280
__func__, (int)ec->ppgrp, signame);
281
if ((ec->ppgrp != ec->sudo_pid && kill(ec->ppgrp, 0) == -1) ||
282
killpg(ec->ppgrp, signo) == -1) {
283
sudo_debug_printf(SUDO_DEBUG_ERROR,
284
"%s: no parent to suspend, terminating command.", __func__);
285
terminate_command(ec->cmnd_pid, true);
286
ec->cmnd_pid = -1;
287
}
288
289
if (signo != SIGSTOP) {
290
if (sudo_sigaction(signo, &osa, NULL) != 0)
291
sudo_warn(U_("unable to restore handler for SIG%s"), signame);
292
}
293
294
/* If we failed to suspend, the command is no longer running. */
295
if (ec->cmnd_pid == -1)
296
break;
297
298
/* Log the resume event. */
299
log_suspend(ec, SIGCONT);
300
301
/* Update the pty's terminal settings and restore /dev/tty settings. */
302
if (!resume_terminal(ec))
303
break;
304
305
/*
306
* We always resume the command in the foreground if sudo itself
307
* is the foreground process (and we were able to set /dev/tty to
308
* raw mode). This helps work around poorly behaved programs that
309
* catch SIGTTOU/SIGTTIN but suspend themselves with SIGSTOP. At
310
* worst, sudo will go into the background but upon resume the
311
* command will be runnable. Otherwise, we can get into a
312
* situation where the command will immediately suspend itself.
313
*/
314
ret = ec->term_raw ? SIGCONT_FG : SIGCONT_BG;
315
break;
316
}
317
318
if (sudo_sigaction(SIGCONT, &saved_sigcont, NULL) != 0)
319
sudo_warn("%s", U_("unable to restore handler for SIGCONT"));
320
321
debug_return_int(ret);
322
}
323
324
/*
325
* SIGTTIN signal handler for read_callback that just sets a flag.
326
*/
327
static volatile sig_atomic_t got_sigttin;
328
329
static void
330
sigttin(int signo)
331
{
332
got_sigttin = 1;
333
}
334
335
/*
336
* Close the leader fd to revoke the pty and signal the foreground pgrp.
337
* We send SIGHUP to the foreground process group (or the command's
338
* process group if no pty) after closing the leader fd. We cannot
339
* just forward the SIGHUP we receive from the kernel since the
340
* command may not be the foreground process. This fixes a problem
341
* on Linux with, e.g. "sudo su" where su(1) blocks SIGHUP.
342
*/
343
static void
344
revoke_pty(struct exec_closure *ec)
345
{
346
pid_t pgrp = ec->cmnd_pid;
347
debug_decl(revoke_pty, SUDO_DEBUG_EXEC);
348
349
sudo_debug_printf(SUDO_DEBUG_NOTICE, "user's tty revoked");
350
if (io_fds[SFD_LEADER] != -1) {
351
const pid_t tcpgrp = tcgetpgrp(io_fds[SFD_LEADER]);
352
if (tcpgrp != -1)
353
pgrp = tcpgrp;
354
close(io_fds[SFD_LEADER]);
355
}
356
if (pgrp != -1) {
357
sudo_debug_printf(SUDO_DEBUG_NOTICE, "%s: killpg(%d, SIGHUP)",
358
__func__, (int)pgrp);
359
killpg(pgrp, SIGHUP);
360
}
361
}
362
363
/*
364
* Read an iobuf that is ready.
365
*/
366
static void
367
read_callback(int fd, int what, void *v)
368
{
369
struct io_buffer *iob = v;
370
struct sudo_event_base *evbase = sudo_ev_get_base(iob->revent);
371
struct sigaction sa, osa;
372
int saved_errno;
373
ssize_t n;
374
debug_decl(read_callback, SUDO_DEBUG_EXEC);
375
376
/*
377
* We ignore SIGTTIN by default but we need to handle it when reading
378
* from the terminal. A signal event won't work here because the
379
* read() would be restarted, preventing the callback from running.
380
*/
381
memset(&sa, 0, sizeof(sa));
382
sigemptyset(&sa.sa_mask);
383
sa.sa_handler = sigttin;
384
got_sigttin = 0;
385
sigaction(SIGTTIN, &sa, &osa);
386
n = read(fd, iob->buf + iob->len, sizeof(iob->buf) - iob->len);
387
saved_errno = errno;
388
sigaction(SIGTTIN, &osa, NULL);
389
errno = saved_errno;
390
391
switch (n) {
392
case -1:
393
if (got_sigttin) {
394
/* Schedule SIGTTIN to be forwarded to the command. */
395
schedule_signal(iob->ec, SIGTTIN);
396
}
397
if (errno == EAGAIN || errno == EINTR) {
398
/* Not an error, retry later. */
399
break;
400
}
401
/* Treat read error as fatal and close the fd. */
402
sudo_debug_printf(SUDO_DEBUG_ERROR,
403
"error reading fd %d: %s", fd, strerror(errno));
404
FALLTHROUGH;
405
case 0:
406
/* got EOF or pty has gone away */
407
if (n == 0) {
408
sudo_debug_printf(SUDO_DEBUG_INFO,
409
"read EOF from fd %d", fd);
410
}
411
safe_close(fd);
412
ev_free_by_fd(evbase, fd);
413
/* If writer already consumed the buffer, close it too. */
414
if (iob->wevent != NULL && iob->off == iob->len) {
415
/*
416
* Don't close the pty leader yet, it will invalidate the pty.
417
* We ask the monitor to signal the running process first.
418
*/
419
const int wfd = sudo_ev_get_fd(iob->wevent);
420
if (wfd == io_fds[SFD_LEADER]) {
421
revoke_pty(iob->ec);
422
} else {
423
safe_close(wfd);
424
}
425
ev_free_by_fd(evbase, wfd);
426
iob->off = iob->len = 0;
427
}
428
break;
429
default:
430
sudo_debug_printf(SUDO_DEBUG_INFO,
431
"read %zd bytes from fd %d", n, fd);
432
if (!iob->action(iob->buf + iob->len, (unsigned int)n, iob)) {
433
terminate_command(iob->ec->cmnd_pid, true);
434
iob->ec->cmnd_pid = -1;
435
}
436
iob->len += (unsigned int)n;
437
/* Disable reader if buffer is full. */
438
if (iob->len == sizeof(iob->buf))
439
sudo_ev_del(evbase, iob->revent);
440
/* Enable writer now that there is new data in the buffer. */
441
if (iob->wevent != NULL) {
442
if (sudo_ev_add(evbase, iob->wevent, NULL, false) == -1)
443
sudo_fatal("%s", U_("unable to add event to queue"));
444
}
445
break;
446
}
447
448
debug_return;
449
}
450
451
/*
452
* SIGTTOU signal handler for write_callback that just sets a flag.
453
*/
454
static volatile sig_atomic_t got_sigttou;
455
456
static void
457
sigttou(int signo)
458
{
459
got_sigttou = 1;
460
}
461
462
/*
463
* Write an iobuf that is ready.
464
*/
465
static void
466
write_callback(int fd, int what, void *v)
467
{
468
struct io_buffer *iob = v;
469
struct sudo_event_base *evbase = sudo_ev_get_base(iob->wevent);
470
struct sigaction sa, osa;
471
int saved_errno;
472
ssize_t n;
473
debug_decl(write_callback, SUDO_DEBUG_EXEC);
474
475
/*
476
* We ignore SIGTTOU by default but we need to handle it when writing
477
* to the terminal. A signal event won't work here because the
478
* write() would be restarted, preventing the callback from running.
479
*/
480
memset(&sa, 0, sizeof(sa));
481
sigemptyset(&sa.sa_mask);
482
sa.sa_handler = sigttou;
483
got_sigttou = 0;
484
sigaction(SIGTTOU, &sa, &osa);
485
n = write(fd, iob->buf + iob->off, iob->len - iob->off);
486
saved_errno = errno;
487
sigaction(SIGTTOU, &osa, NULL);
488
errno = saved_errno;
489
490
if (n == -1) {
491
switch (errno) {
492
case EPIPE:
493
case ENXIO:
494
case EIO:
495
case EBADF:
496
/* other end of pipe closed or pty revoked */
497
sudo_debug_printf(SUDO_DEBUG_INFO,
498
"unable to write %u bytes to fd %d",
499
iob->len - iob->off, fd);
500
/* Close reader if there is one. */
501
if (iob->revent != NULL) {
502
/*
503
* Don't close the pty leader, it will invalidate the pty.
504
* We ask the monitor to signal the running process first.
505
*/
506
const int rfd = sudo_ev_get_fd(iob->revent);
507
if (rfd == io_fds[SFD_LEADER]) {
508
revoke_pty(iob->ec);
509
} else {
510
safe_close(rfd);
511
}
512
ev_free_by_fd(evbase, rfd);
513
}
514
safe_close(fd);
515
ev_free_by_fd(evbase, fd);
516
break;
517
case EINTR:
518
if (got_sigttou) {
519
/* Schedule SIGTTOU to be forwarded to the command. */
520
schedule_signal(iob->ec, SIGTTOU);
521
}
522
FALLTHROUGH;
523
case EAGAIN:
524
/* Not an error, retry later. */
525
break;
526
default:
527
/* XXX - need a way to distinguish non-exec error. */
528
iob->ec->cstat->type = CMD_ERRNO;
529
iob->ec->cstat->val = errno;
530
sudo_debug_printf(SUDO_DEBUG_ERROR,
531
"error writing fd %d: %s", fd, strerror(errno));
532
sudo_ev_loopbreak(evbase);
533
break;
534
}
535
} else {
536
sudo_debug_printf(SUDO_DEBUG_INFO,
537
"wrote %zd of %u bytes to fd %d", n, iob->len - iob->off, fd);
538
iob->off += (unsigned int)n;
539
/* Disable writer and reset the buffer if fully consumed. */
540
if (iob->off == iob->len) {
541
iob->off = iob->len = 0;
542
sudo_ev_del(evbase, iob->wevent);
543
/* Forward the EOF from reader to writer. */
544
if (iob->revent == NULL) {
545
safe_close(fd);
546
ev_free_by_fd(evbase, fd);
547
}
548
}
549
/*
550
* Enable reader if buffer is not full but avoid reading /dev/tty
551
* if not in raw mode or the command is no longer running.
552
*/
553
if (iob->revent != NULL && iob->len != sizeof(iob->buf)) {
554
if (!USERTTY_EVENT(iob->revent) ||
555
(iob->ec->term_raw && iob->ec->cmnd_pid != -1)) {
556
if (sudo_ev_add(evbase, iob->revent, NULL, false) == -1)
557
sudo_fatal("%s", U_("unable to add event to queue"));
558
}
559
}
560
}
561
562
debug_return;
563
}
564
565
/*
566
* We already closed the follower so reads from the leader will not block.
567
*/
568
static void
569
pty_finish(struct exec_closure *ec, struct command_status *cstat)
570
{
571
int flags;
572
debug_decl(pty_finish, SUDO_DEBUG_EXEC);
573
574
/* Flush any remaining output (the plugin already got it) and free bufs. */
575
if (io_fds[SFD_USERTTY] != -1) {
576
flags = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
577
if (flags != -1 && ISSET(flags, O_NONBLOCK)) {
578
CLR(flags, O_NONBLOCK);
579
(void) fcntl(io_fds[SFD_USERTTY], F_SETFL, flags);
580
}
581
}
582
del_io_events(false);
583
free_io_bufs();
584
585
/* Restore terminal settings and update utmp. */
586
pty_cleanup(ec, cstat->type == CMD_WSTATUS ? cstat->val : 0);
587
588
debug_return;
589
}
590
591
/*
592
* Send command status to the monitor (currently just signal forwarding).
593
*/
594
static void
595
send_command_status(struct exec_closure *ec, int type, int val)
596
{
597
struct monitor_message *msg;
598
debug_decl(send_command_status, SUDO_DEBUG_EXEC);
599
600
if ((msg = calloc(1, sizeof(*msg))) == NULL)
601
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
602
msg->cstat.type = type;
603
msg->cstat.val = val;
604
TAILQ_INSERT_TAIL(&monitor_messages, msg, entries);
605
606
if (sudo_ev_add(ec->evbase, ec->fwdchannel_event, NULL, true) == -1)
607
sudo_fatal("%s", U_("unable to add event to queue"));
608
609
/* Restart event loop to send the command immediately. */
610
sudo_ev_loopcontinue(ec->evbase);
611
612
debug_return;
613
}
614
615
/*
616
* Schedule a signal to be forwarded.
617
*/
618
static void
619
schedule_signal(struct exec_closure *ec, int signo)
620
{
621
debug_decl(schedule_signal, SUDO_DEBUG_EXEC);
622
623
if (signo == 0)
624
debug_return;
625
626
if (sudo_debug_needed(SUDO_DEBUG_DIAG)) {
627
char signame[SIG2STR_MAX];
628
if (signo == SIGCONT_FG)
629
strlcpy(signame, "CONT_FG", sizeof(signame));
630
else if (signo == SIGCONT_BG)
631
strlcpy(signame, "CONT_BG", sizeof(signame));
632
else if (sig2str(signo, signame) == -1)
633
(void)snprintf(signame, sizeof(signame), "%d", signo);
634
sudo_debug_printf(SUDO_DEBUG_DIAG, "scheduled SIG%s for command",
635
signame);
636
}
637
638
send_command_status(ec, CMD_SIGNO, signo);
639
640
debug_return;
641
}
642
643
/*
644
* Free any remaining monitor messages in the queue.
645
*/
646
static void
647
flush_monitor_messages(void)
648
{
649
struct monitor_message *msg;
650
debug_decl(flush_monitor_messages, SUDO_DEBUG_EXEC);
651
652
while ((msg = TAILQ_FIRST(&monitor_messages)) != NULL) {
653
TAILQ_REMOVE(&monitor_messages, msg, entries);
654
free(msg);
655
}
656
657
debug_return;
658
}
659
660
static void
661
backchannel_cb(int fd, int what, void *v)
662
{
663
struct exec_closure *ec = v;
664
struct command_status cstat;
665
ssize_t nread;
666
debug_decl(backchannel_cb, SUDO_DEBUG_EXEC);
667
668
/*
669
* Read command status from the monitor.
670
* Note that the backchannel is a *blocking* socket.
671
*/
672
nread = recv(fd, &cstat, sizeof(cstat), MSG_WAITALL);
673
switch (nread) {
674
case -1:
675
switch (errno) {
676
case EINTR:
677
case EAGAIN:
678
/* Nothing ready. */
679
break;
680
default:
681
if (ec->cstat->val == CMD_INVALID) {
682
ec->cstat->type = CMD_ERRNO;
683
ec->cstat->val = errno;
684
sudo_debug_printf(SUDO_DEBUG_ERROR,
685
"%s: failed to read command status: %s",
686
__func__, strerror(errno));
687
sudo_ev_loopbreak(ec->evbase);
688
}
689
break;
690
}
691
break;
692
case 0:
693
/* EOF, monitor exited or was killed. */
694
sudo_debug_printf(SUDO_DEBUG_INFO,
695
"EOF on backchannel, monitor dead?");
696
if (ec->cstat->type == CMD_INVALID) {
697
/* XXX - need new CMD_ type for monitor errors. */
698
ec->cstat->type = CMD_ERRNO;
699
ec->cstat->val = ECONNRESET;
700
}
701
sudo_ev_loopexit(ec->evbase);
702
break;
703
case sizeof(cstat):
704
/* Check command status. */
705
switch (cstat.type) {
706
case CMD_ERRNO:
707
/* Monitor was unable to execute command or broken pipe. */
708
sudo_debug_printf(SUDO_DEBUG_INFO, "errno from monitor: %s",
709
strerror(cstat.val));
710
sudo_ev_loopbreak(ec->evbase);
711
*ec->cstat = cstat;
712
break;
713
case CMD_PID:
714
ec->cmnd_pid = cstat.val;
715
sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d",
716
ec->details->command, (int)ec->cmnd_pid);
717
if (ISSET(ec->details->flags, CD_USE_PTRACE)) {
718
/* Try to seize control of the command using ptrace(2). */
719
int rc = exec_ptrace_seize(ec->cmnd_pid);
720
if (rc == 0) {
721
/* There is another tracer present. */
722
CLR(ec->details->flags, CD_INTERCEPT|CD_LOG_SUBCMDS|CD_USE_PTRACE);
723
} else if (rc == -1) {
724
if (ec->cstat->type == CMD_INVALID) {
725
ec->cstat->type = CMD_ERRNO;
726
ec->cstat->val = errno;
727
}
728
sudo_ev_loopbreak(ec->evbase);
729
}
730
}
731
break;
732
case CMD_WSTATUS:
733
if (WIFSTOPPED(cstat.val)) {
734
int signo;
735
736
/* Suspend parent and tell monitor how to resume on return. */
737
sudo_debug_printf(SUDO_DEBUG_INFO,
738
"command stopped, suspending parent");
739
signo = suspend_sudo_pty(ec, WSTOPSIG(cstat.val));
740
schedule_signal(ec, signo);
741
/* Re-enable I/O events */
742
add_io_events(ec);
743
} else {
744
/* Command exited or was killed, either way we are done. */
745
sudo_debug_printf(SUDO_DEBUG_INFO, "command exited or was killed");
746
sudo_ev_loopexit(ec->evbase);
747
*ec->cstat = cstat;
748
}
749
break;
750
}
751
/* Keep reading command status messages until EAGAIN or EOF. */
752
break;
753
default:
754
/* Short read, should not happen. */
755
if (ec->cstat->val == CMD_INVALID) {
756
ec->cstat->type = CMD_ERRNO;
757
ec->cstat->val = EIO;
758
sudo_debug_printf(SUDO_DEBUG_ERROR,
759
"%s: failed to read command status: short read", __func__);
760
sudo_ev_loopbreak(ec->evbase);
761
}
762
break;
763
}
764
debug_return;
765
}
766
767
/*
768
* Handle changes to the monitor's status (SIGCHLD).
769
*/
770
static void
771
handle_sigchld_pty(struct exec_closure *ec)
772
{
773
int n, status;
774
pid_t pid;
775
debug_decl(handle_sigchld_pty, SUDO_DEBUG_EXEC);
776
777
/* There may be multiple children in intercept mode. */
778
for (;;) {
779
do {
780
pid = waitpid(-1, &status, __WALL|WUNTRACED|WNOHANG);
781
} while (pid == -1 && errno == EINTR);
782
switch (pid) {
783
case -1:
784
if (errno != ECHILD) {
785
sudo_warn(U_("%s: %s"), __func__, "waitpid");
786
debug_return;
787
}
788
FALLTHROUGH;
789
case 0:
790
/* Nothing left to wait for. */
791
debug_return;
792
}
793
794
if (WIFEXITED(status)) {
795
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: process %d exited: %d",
796
__func__, (int)pid, WEXITSTATUS(status));
797
if (pid == ec->monitor_pid)
798
ec->monitor_pid = -1;
799
} else if (WIFSIGNALED(status)) {
800
if (sudo_debug_needed(SUDO_DEBUG_INFO)) {
801
char signame[SIG2STR_MAX];
802
if (sig2str(WTERMSIG(status), signame) == -1) {
803
(void)snprintf(signame, sizeof(signame), "%d",
804
WTERMSIG(status));
805
}
806
sudo_debug_printf(SUDO_DEBUG_INFO,
807
"%s: process %d killed, SIG%s",
808
__func__, (int)pid, signame);
809
}
810
if (pid == ec->monitor_pid)
811
ec->monitor_pid = -1;
812
} else if (WIFSTOPPED(status)) {
813
if (pid != ec->monitor_pid) {
814
if (ISSET(ec->details->flags, CD_USE_PTRACE))
815
exec_ptrace_stopped(pid, status, ec->intercept);
816
continue;
817
}
818
819
/*
820
* If the monitor dies we get notified via backchannel_cb().
821
* If it was stopped, we should stop too (the command keeps
822
* running in its pty) and continue it when we come back.
823
*/
824
sudo_debug_printf(SUDO_DEBUG_INFO,
825
"monitor stopped, suspending sudo");
826
n = suspend_sudo_pty(ec, WSTOPSIG(status));
827
kill(pid, SIGCONT);
828
schedule_signal(ec, n);
829
/* Re-enable I/O events */
830
add_io_events(ec);
831
} else {
832
sudo_debug_printf(SUDO_DEBUG_WARN,
833
"%s: unexpected wait status 0x%x for process (%d)",
834
__func__, status, (int)pid);
835
}
836
}
837
}
838
839
/* Signal callback */
840
static void
841
signal_cb_pty(int signo, int what, void *v)
842
{
843
struct sudo_ev_siginfo_container *sc = v;
844
struct exec_closure *ec = sc->closure;
845
debug_decl(signal_cb_pty, SUDO_DEBUG_EXEC);
846
847
if (ec->monitor_pid == -1)
848
debug_return;
849
850
if (sudo_debug_needed(SUDO_DEBUG_DIAG)) {
851
char signame[SIG2STR_MAX];
852
if (sig2str(signo, signame) == -1)
853
(void)snprintf(signame, sizeof(signame), "%d", signo);
854
sudo_debug_printf(SUDO_DEBUG_DIAG,
855
"%s: evbase %p, monitor: %d, signo %s(%d), cstat %p", __func__,
856
ec->evbase, (int)ec->monitor_pid, signame, signo, ec->cstat);
857
}
858
859
switch (signo) {
860
case SIGCHLD:
861
handle_sigchld_pty(ec);
862
break;
863
case SIGCONT:
864
resume_terminal(ec);
865
break;
866
case SIGWINCH:
867
sync_ttysize(ec);
868
break;
869
case SIGHUP:
870
/*
871
* Avoid forwarding SIGHUP sent by the kernel, it probably means
872
* that the user's terminal was revoked. When we detect that the
873
* terminal has been revoked, the monitor will send SIGHUP itself.
874
*/
875
if (!USER_SIGNALED(sc->siginfo))
876
break;
877
FALLTHROUGH;
878
default:
879
/*
880
* Do not forward signals sent by the command itself or a member of the
881
* command's process group (but only when either sudo or the command is
882
* the process group leader). We don't want the command to indirectly
883
* kill itself. For example, this can happen with some versions of
884
* reboot that call kill(-1, SIGTERM) to kill all other processes.
885
*/
886
if (USER_SIGNALED(sc->siginfo) && sc->siginfo->si_pid != 0) {
887
pid_t si_pgrp;
888
889
if (sc->siginfo->si_pid == ec->cmnd_pid)
890
debug_return;
891
si_pgrp = getpgid(sc->siginfo->si_pid);
892
if (si_pgrp != -1) {
893
if (si_pgrp == ec->cmnd_pid || si_pgrp == ec->sudo_pid)
894
debug_return;
895
}
896
}
897
/* Schedule signal to be forwarded to the command. */
898
schedule_signal(ec, signo);
899
break;
900
}
901
902
debug_return;
903
}
904
905
/*
906
* Forward signals in monitor_messages to the monitor so it can
907
* deliver them to the command.
908
*/
909
static void
910
fwdchannel_cb(int sock, int what, void *v)
911
{
912
struct exec_closure *ec = v;
913
struct monitor_message *msg;
914
ssize_t nsent;
915
debug_decl(fwdchannel_cb, SUDO_DEBUG_EXEC);
916
917
while ((msg = TAILQ_FIRST(&monitor_messages)) != NULL) {
918
switch (msg->cstat.type) {
919
case CMD_SIGNO:
920
if (sudo_debug_needed(SUDO_DEBUG_INFO)) {
921
char signame[SIG2STR_MAX];
922
if (msg->cstat.val == SIGCONT_FG)
923
strlcpy(signame, "CONT_FG", sizeof(signame));
924
else if (msg->cstat.val == SIGCONT_BG)
925
strlcpy(signame, "CONT_BG", sizeof(signame));
926
else if (sig2str(msg->cstat.val, signame) == -1) {
927
(void)snprintf(signame, sizeof(signame), "%d",
928
msg->cstat.val);
929
}
930
sudo_debug_printf(SUDO_DEBUG_INFO,
931
"sending SIG%s to monitor over backchannel", signame);
932
}
933
break;
934
default:
935
sudo_debug_printf(SUDO_DEBUG_INFO,
936
"sending cstat type %d, value %d to monitor over backchannel",
937
msg->cstat.type, msg->cstat.val);
938
break;
939
}
940
TAILQ_REMOVE(&monitor_messages, msg, entries);
941
nsent = send(sock, &msg->cstat, sizeof(msg->cstat), 0);
942
if (nsent != sizeof(msg->cstat)) {
943
if (errno == EPIPE) {
944
sudo_debug_printf(SUDO_DEBUG_ERROR,
945
"broken pipe writing to monitor over backchannel");
946
/* Other end of socket gone, empty out monitor_messages. */
947
free(msg);
948
flush_monitor_messages();
949
/* XXX - need new CMD_ type for monitor errors. */
950
ec->cstat->type = CMD_ERRNO;
951
ec->cstat->val = errno;
952
sudo_ev_loopbreak(ec->evbase);
953
}
954
break;
955
}
956
free(msg);
957
}
958
}
959
960
/*
961
* Fill in the non-event part of the exec closure.
962
*/
963
static void
964
init_exec_closure(struct exec_closure *ec, struct command_status *cstat,
965
struct command_details *details, const struct user_details *user_details,
966
pid_t sudo_pid, pid_t ppgrp)
967
{
968
debug_decl(init_exec_closure, SUDO_DEBUG_EXEC);
969
970
/* Fill in the non-event part of the closure. */
971
memset(ec, 0, sizeof(*ec));
972
ec->sudo_pid = sudo_pid;
973
ec->ppgrp = ppgrp;
974
ec->cmnd_pid = -1;
975
ec->cstat = cstat;
976
ec->details = details;
977
ec->rows = user_details->ts_rows;
978
ec->cols = user_details->ts_cols;
979
980
debug_return;
981
}
982
983
/*
984
* Allocate and set events for the signal pipe and backchannel.
985
* Forwarded signals on the backchannel are enabled on demand.
986
*/
987
static void
988
init_exec_events(struct exec_closure *ec, struct sudo_event_base *evbase,
989
int backchannel)
990
{
991
debug_decl(init_exec_events, SUDO_DEBUG_EXEC);
992
993
/* Setup event base and events. */
994
ec->evbase = evbase;
995
996
/* Event for command status via backchannel. */
997
ec->backchannel_event = sudo_ev_alloc(backchannel,
998
SUDO_EV_READ|SUDO_EV_PERSIST, backchannel_cb, ec);
999
if (ec->backchannel_event == NULL)
1000
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1001
if (sudo_ev_add(ec->evbase, ec->backchannel_event, NULL, false) == -1)
1002
sudo_fatal("%s", U_("unable to add event to queue"));
1003
sudo_debug_printf(SUDO_DEBUG_INFO, "backchannel fd %d\n", backchannel);
1004
1005
/* Events for local signals. */
1006
ec->sigint_event = sudo_ev_alloc(SIGINT,
1007
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1008
if (ec->sigint_event == NULL)
1009
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1010
if (sudo_ev_add(ec->evbase, ec->sigint_event, NULL, false) == -1)
1011
sudo_fatal("%s", U_("unable to add event to queue"));
1012
1013
ec->sigquit_event = sudo_ev_alloc(SIGQUIT,
1014
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1015
if (ec->sigquit_event == NULL)
1016
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1017
if (sudo_ev_add(ec->evbase, ec->sigquit_event, NULL, false) == -1)
1018
sudo_fatal("%s", U_("unable to add event to queue"));
1019
1020
ec->sigtstp_event = sudo_ev_alloc(SIGTSTP,
1021
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1022
if (ec->sigtstp_event == NULL)
1023
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1024
if (sudo_ev_add(ec->evbase, ec->sigtstp_event, NULL, false) == -1)
1025
sudo_fatal("%s", U_("unable to add event to queue"));
1026
1027
ec->sigterm_event = sudo_ev_alloc(SIGTERM,
1028
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1029
if (ec->sigterm_event == NULL)
1030
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1031
if (sudo_ev_add(ec->evbase, ec->sigterm_event, NULL, false) == -1)
1032
sudo_fatal("%s", U_("unable to add event to queue"));
1033
1034
ec->sighup_event = sudo_ev_alloc(SIGHUP,
1035
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1036
if (ec->sighup_event == NULL)
1037
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1038
if (sudo_ev_add(ec->evbase, ec->sighup_event, NULL, false) == -1)
1039
sudo_fatal("%s", U_("unable to add event to queue"));
1040
1041
ec->sigalrm_event = sudo_ev_alloc(SIGALRM,
1042
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1043
if (ec->sigalrm_event == NULL)
1044
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1045
if (sudo_ev_add(ec->evbase, ec->sigalrm_event, NULL, false) == -1)
1046
sudo_fatal("%s", U_("unable to add event to queue"));
1047
1048
ec->sigusr1_event = sudo_ev_alloc(SIGUSR1,
1049
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1050
if (ec->sigusr1_event == NULL)
1051
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1052
if (sudo_ev_add(ec->evbase, ec->sigusr1_event, NULL, false) == -1)
1053
sudo_fatal("%s", U_("unable to add event to queue"));
1054
1055
ec->sigusr2_event = sudo_ev_alloc(SIGUSR2,
1056
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1057
if (ec->sigusr2_event == NULL)
1058
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1059
if (sudo_ev_add(ec->evbase, ec->sigusr2_event, NULL, false) == -1)
1060
sudo_fatal("%s", U_("unable to add event to queue"));
1061
1062
ec->sigchld_event = sudo_ev_alloc(SIGCHLD,
1063
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1064
if (ec->sigchld_event == NULL)
1065
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1066
if (sudo_ev_add(ec->evbase, ec->sigchld_event, NULL, false) == -1)
1067
sudo_fatal("%s", U_("unable to add event to queue"));
1068
1069
ec->sigcont_event = sudo_ev_alloc(SIGCONT,
1070
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1071
if (ec->sigcont_event == NULL)
1072
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1073
if (sudo_ev_add(ec->evbase, ec->sigcont_event, NULL, false) == -1)
1074
sudo_fatal("%s", U_("unable to add event to queue"));
1075
1076
ec->sigwinch_event = sudo_ev_alloc(SIGWINCH,
1077
SUDO_EV_SIGINFO, signal_cb_pty, ec);
1078
if (ec->sigwinch_event == NULL)
1079
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1080
if (sudo_ev_add(ec->evbase, ec->sigwinch_event, NULL, false) == -1)
1081
sudo_fatal("%s", U_("unable to add event to queue"));
1082
1083
/* The signal forwarding event gets added on demand. */
1084
ec->fwdchannel_event = sudo_ev_alloc(backchannel,
1085
SUDO_EV_WRITE, fwdchannel_cb, ec);
1086
if (ec->fwdchannel_event == NULL)
1087
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1088
1089
/* Set the default event base. */
1090
sudo_ev_base_setdef(ec->evbase);
1091
1092
debug_return;
1093
}
1094
1095
/*
1096
* Execute a command in a pty, potentially with I/O logging, and
1097
* wait for it to finish.
1098
* This is a little bit tricky due to how POSIX job control works and
1099
* the fact that we have two different controlling terminals to deal with.
1100
*/
1101
bool
1102
exec_pty(struct command_details *details,
1103
const struct user_details *user_details, struct sudo_event_base *evbase,
1104
struct command_status *cstat)
1105
{
1106
int io_pipe[3][2] = { { -1, -1 }, { -1, -1 }, { -1, -1 } };
1107
bool interpose[3] = { false, false, false };
1108
struct stat sb;
1109
int sv[2], intercept_sv[2] = { -1, -1 };
1110
struct exec_closure *ec = &pty_ec;
1111
struct plugin_container *plugin;
1112
const pid_t sudo_pid = getpid();
1113
const pid_t ppgrp = getpgrp();
1114
int evloop_retries = -1;
1115
bool cmnd_foreground;
1116
sigset_t set, oset;
1117
struct sigaction sa;
1118
debug_decl(exec_pty, SUDO_DEBUG_EXEC);
1119
1120
/*
1121
* Allocate a pty if sudo is running in a terminal. The exec
1122
* closure must be set for pty_setup() and pty_cleanup_hook().
1123
*/
1124
init_exec_closure(ec, cstat, details, user_details, sudo_pid, ppgrp);
1125
if (!pty_setup(ec))
1126
debug_return_bool(false);
1127
1128
/*
1129
* We communicate with the monitor over a bi-directional pair of sockets.
1130
* Parent sends signal info to monitor and monitor sends back wait status.
1131
*/
1132
if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1 ||
1133
fcntl(sv[0], F_SETFD, FD_CLOEXEC) == -1 ||
1134
fcntl(sv[1], F_SETFD, FD_CLOEXEC) == -1)
1135
sudo_fatal("%s", U_("unable to create sockets"));
1136
1137
if (ISSET(details->flags, CD_INTERCEPT|CD_LOG_SUBCMDS)) {
1138
if (!ISSET(details->flags, CD_USE_PTRACE)) {
1139
/*
1140
* Allocate a socketpair for communicating with sudo_intercept.so.
1141
* This must be inherited across exec, hence no FD_CLOEXEC.
1142
*/
1143
if (socketpair(PF_UNIX, SOCK_STREAM, 0, intercept_sv) == -1)
1144
sudo_fatal("%s", U_("unable to create sockets"));
1145
}
1146
}
1147
1148
/*
1149
* We don't want to receive SIGTTIN/SIGTTOU.
1150
* XXX - this affects tcsetattr() and tcsetpgrp() too.
1151
*/
1152
memset(&sa, 0, sizeof(sa));
1153
sigemptyset(&sa.sa_mask);
1154
sa.sa_flags = SA_RESTART;
1155
sa.sa_handler = SIG_IGN;
1156
if (sudo_sigaction(SIGTTIN, &sa, NULL) != 0)
1157
sudo_warn(U_("unable to set handler for signal %d"), SIGTTIN);
1158
if (sudo_sigaction(SIGTTOU, &sa, NULL) != 0)
1159
sudo_warn(U_("unable to set handler for signal %d"), SIGTTOU);
1160
1161
/*
1162
* The policy plugin's session init must be run before we fork
1163
* or certain pam modules won't be able to track their state.
1164
*/
1165
if (policy_init_session(details) != true)
1166
sudo_fatalx("%s", U_("policy plugin failed session initialization"));
1167
1168
/*
1169
* Child will run the command in the pty, parent will pass data
1170
* to and from pty.
1171
*/
1172
init_ttyblock();
1173
1174
/* Determine whether any of std{in,out,err} should be logged. */
1175
TAILQ_FOREACH(plugin, &io_plugins, entries) {
1176
if (plugin->u.io->log_stdin)
1177
interpose[STDIN_FILENO] = true;
1178
if (plugin->u.io->log_stdout)
1179
interpose[STDOUT_FILENO] = true;
1180
if (plugin->u.io->log_stderr)
1181
interpose[STDERR_FILENO] = true;
1182
}
1183
1184
/*
1185
* Setup stdin/stdout/stderr for command, to be duped after forking.
1186
*/
1187
io_fds[SFD_STDIN] = io_fds[SFD_FOLLOWER];
1188
io_fds[SFD_STDOUT] = io_fds[SFD_FOLLOWER];
1189
io_fds[SFD_STDERR] = io_fds[SFD_FOLLOWER];
1190
1191
if (io_fds[SFD_USERTTY] != -1) {
1192
/* Read from /dev/tty, write to pty leader */
1193
if (!ISSET(details->flags, CD_BACKGROUND)) {
1194
io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_LEADER],
1195
log_ttyin, read_callback, write_callback, ec);
1196
}
1197
1198
/* Read from pty leader, write to /dev/tty */
1199
io_buf_new(io_fds[SFD_LEADER], io_fds[SFD_USERTTY],
1200
log_ttyout, read_callback, write_callback, ec);
1201
1202
/* Are we the foreground process? */
1203
ec->foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
1204
sudo_debug_printf(SUDO_DEBUG_INFO, "sudo is running in the %s",
1205
ec->foreground ? "foreground" : "background");
1206
}
1207
1208
/*
1209
* If stdin, stdout or stderr is not the user's tty and logging is
1210
* enabled, use a pipe to interpose ourselves instead of using the
1211
* pty fd. We always use a pipe for stdin when in background mode.
1212
*/
1213
if (!fd_matches_pgrp(STDIN_FILENO, ppgrp, &sb)) {
1214
if (!interpose[STDIN_FILENO]) {
1215
/* Not logging stdin, do not interpose. */
1216
sudo_debug_printf(SUDO_DEBUG_INFO,
1217
"stdin not user's tty, not logging");
1218
if (S_ISFIFO(sb.st_mode))
1219
SET(details->flags, CD_EXEC_BG);
1220
io_fds[SFD_STDIN] = dup(STDIN_FILENO);
1221
if (io_fds[SFD_STDIN] == -1)
1222
sudo_fatal("dup");
1223
} else {
1224
sudo_debug_printf(SUDO_DEBUG_INFO,
1225
"stdin not user's tty, creating a pipe");
1226
SET(details->flags, CD_EXEC_BG);
1227
if (pipe2(io_pipe[STDIN_FILENO], O_CLOEXEC) != 0)
1228
sudo_fatal("%s", U_("unable to create pipe"));
1229
io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
1230
log_stdin, read_callback, write_callback, ec);
1231
io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
1232
}
1233
1234
if (ec->foreground && ppgrp != sudo_pid) {
1235
/*
1236
* If sudo is not the process group leader and stdin is not
1237
* a tty we may be running as a background job via a shell
1238
* script. Start the command in the background to avoid
1239
* changing the terminal mode from a background process.
1240
*/
1241
SET(details->flags, CD_EXEC_BG);
1242
}
1243
} else if (ISSET(details->flags, CD_BACKGROUND)) {
1244
/*
1245
* Running in background (sudo -b), no access to terminal input.
1246
* In non-pty mode, the command runs in an orphaned process
1247
* group and reads from the controlling terminal fail with EIO.
1248
* We cannot do the same while running in a pty but if we set
1249
* stdin to a half-closed pipe, reads from it will get EOF.
1250
*/
1251
sudo_debug_printf(SUDO_DEBUG_INFO,
1252
"terminal input not available, creating empty pipe");
1253
SET(details->flags, CD_EXEC_BG);
1254
if (pipe2(io_pipe[STDIN_FILENO], O_CLOEXEC) != 0)
1255
sudo_fatal("%s", U_("unable to create pipe"));
1256
io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
1257
close(io_pipe[STDIN_FILENO][1]);
1258
io_pipe[STDIN_FILENO][1] = -1;
1259
}
1260
if (!fd_matches_pgrp(STDOUT_FILENO, ppgrp, &sb)) {
1261
if (!interpose[STDOUT_FILENO]) {
1262
/* Not logging stdout, do not interpose. */
1263
sudo_debug_printf(SUDO_DEBUG_INFO,
1264
"stdout not user's tty, not logging");
1265
if (S_ISFIFO(sb.st_mode)) {
1266
SET(details->flags, CD_EXEC_BG);
1267
term_raw_flags = SUDO_TERM_OFLAG;
1268
}
1269
io_fds[SFD_STDOUT] = dup(STDOUT_FILENO);
1270
if (io_fds[SFD_STDOUT] == -1)
1271
sudo_fatal("dup");
1272
} else {
1273
sudo_debug_printf(SUDO_DEBUG_INFO,
1274
"stdout not user's tty, creating a pipe");
1275
SET(details->flags, CD_EXEC_BG);
1276
term_raw_flags = SUDO_TERM_OFLAG;
1277
if (pipe2(io_pipe[STDOUT_FILENO], O_CLOEXEC) != 0)
1278
sudo_fatal("%s", U_("unable to create pipe"));
1279
io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
1280
log_stdout, read_callback, write_callback, ec);
1281
io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
1282
}
1283
}
1284
if (!fd_matches_pgrp(STDERR_FILENO, ppgrp, &sb)) {
1285
if (!interpose[STDERR_FILENO]) {
1286
/* Not logging stderr, do not interpose. */
1287
sudo_debug_printf(SUDO_DEBUG_INFO,
1288
"stderr not user's tty, not logging");
1289
io_fds[SFD_STDERR] = dup(STDERR_FILENO);
1290
if (io_fds[SFD_STDERR] == -1)
1291
sudo_fatal("dup");
1292
} else {
1293
sudo_debug_printf(SUDO_DEBUG_INFO,
1294
"stderr not user's tty, creating a pipe");
1295
if (pipe2(io_pipe[STDERR_FILENO], O_CLOEXEC) != 0)
1296
sudo_fatal("%s", U_("unable to create pipe"));
1297
io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
1298
log_stderr, read_callback, write_callback, ec);
1299
io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
1300
}
1301
}
1302
1303
/*
1304
* Copy terminal settings from user tty -> pty. If sudo is a
1305
* background process, we'll re-init the pty when foregrounded.
1306
*/
1307
if (!sudo_term_copy(io_fds[SFD_USERTTY], io_fds[SFD_LEADER])) {
1308
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO,
1309
"%s: unable to copy terminal settings to pty", __func__);
1310
ec->foreground = false;
1311
}
1312
/* Start in raw mode unless the command will run in the background. */
1313
cmnd_foreground = ec->foreground && !ISSET(details->flags, CD_EXEC_BG);
1314
if (cmnd_foreground) {
1315
if (sudo_term_raw(io_fds[SFD_USERTTY], 0))
1316
ec->term_raw = true;
1317
}
1318
1319
sudo_debug_printf(SUDO_DEBUG_INFO,
1320
"%s: follower: %d, stdin: %d, stdout: %d, stderr: %d", __func__,
1321
io_fds[SFD_FOLLOWER], io_fds[SFD_STDIN], io_fds[SFD_STDOUT],
1322
io_fds[SFD_STDERR]);
1323
1324
/*
1325
* Block signals until we have our handlers setup in the parent so
1326
* we don't miss SIGCHLD if the command exits immediately.
1327
*/
1328
sigfillset(&set);
1329
sigprocmask(SIG_BLOCK, &set, &oset);
1330
1331
/* Check for early termination or suspend signals before we fork. */
1332
if (sudo_terminated(cstat)) {
1333
sigprocmask(SIG_SETMASK, &oset, NULL);
1334
debug_return_bool(true);
1335
}
1336
1337
ec->monitor_pid = sudo_debug_fork();
1338
switch (ec->monitor_pid) {
1339
case -1:
1340
sudo_fatal("%s", U_("unable to fork"));
1341
break;
1342
case 0:
1343
/* child */
1344
close(sv[0]);
1345
if (intercept_sv[0] != -1)
1346
close(intercept_sv[0]);
1347
/* Close the other end of the stdin/stdout/stderr pipes and exec. */
1348
if (io_pipe[STDIN_FILENO][1] != -1)
1349
close(io_pipe[STDIN_FILENO][1]);
1350
if (io_pipe[STDOUT_FILENO][0] != -1)
1351
close(io_pipe[STDOUT_FILENO][0]);
1352
if (io_pipe[STDERR_FILENO][0] != -1)
1353
close(io_pipe[STDERR_FILENO][0]);
1354
1355
/* Only run the cleanup hook in the parent. */
1356
sudo_fatal_callback_deregister(pty_cleanup_hook);
1357
1358
/*
1359
* If stdin/stdout is not the user's tty, start the command in
1360
* the background since it might be part of a pipeline that reads
1361
* from /dev/tty. In this case, we rely on the command receiving
1362
* SIGTTOU or SIGTTIN when it needs access to the controlling tty.
1363
*/
1364
exec_monitor(details, &oset, cmnd_foreground, sv[1], intercept_sv[1]);
1365
cstat->type = CMD_ERRNO;
1366
cstat->val = errno;
1367
if (send(sv[1], cstat, sizeof(*cstat), 0) == -1) {
1368
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO,
1369
"%s: unable to send status to parent", __func__);
1370
}
1371
_exit(EXIT_FAILURE);
1372
/* NOTREACHED */
1373
}
1374
1375
/*
1376
* We close the pty follower so only the monitor and command have a
1377
* reference to it. This ensures that we can don't block reading
1378
* from the leader when the command and monitor have exited.
1379
*/
1380
if (io_fds[SFD_FOLLOWER] != -1) {
1381
close(io_fds[SFD_FOLLOWER]);
1382
io_fds[SFD_FOLLOWER] = -1;
1383
}
1384
1385
/* Tell the monitor to continue now that the follower is closed. */
1386
cstat->type = CMD_SIGNO;
1387
cstat->val = 0;
1388
if (send(sv[0], cstat, sizeof(*cstat), 0) == -1)
1389
sudo_fatal("%s", U_("unable to send message to monitor process"));
1390
1391
/* Close the other end of the stdin/stdout/stderr pipes and socketpair. */
1392
if (io_pipe[STDIN_FILENO][0] != -1)
1393
close(io_pipe[STDIN_FILENO][0]);
1394
if (io_pipe[STDOUT_FILENO][1] != -1)
1395
close(io_pipe[STDOUT_FILENO][1]);
1396
if (io_pipe[STDERR_FILENO][1] != -1)
1397
close(io_pipe[STDERR_FILENO][1]);
1398
close(sv[1]);
1399
1400
/* No longer need execfd. */
1401
if (details->execfd != -1) {
1402
close(details->execfd);
1403
details->execfd = -1;
1404
}
1405
1406
/* Set command timeout if specified. */
1407
if (ISSET(details->flags, CD_SET_TIMEOUT))
1408
alarm(details->timeout);
1409
1410
/* Allocate and set signal events and the backchannel event. */
1411
init_exec_events(ec, evbase, sv[0]);
1412
1413
/* Create event and closure for intercept mode. */
1414
if (ISSET(details->flags, CD_INTERCEPT|CD_LOG_SUBCMDS)) {
1415
ec->intercept = intercept_setup(intercept_sv[0], ec->evbase, details);
1416
if (ec->intercept == NULL)
1417
terminate_command(ec->cmnd_pid, true);
1418
}
1419
1420
/* Reset cstat for running the command. */
1421
cstat->type = CMD_INVALID;
1422
cstat->val = 0;
1423
1424
/* Restore signal mask now that signal handlers are setup. */
1425
sigprocmask(SIG_SETMASK, &oset, NULL);
1426
1427
/*
1428
* I/O logging must be in the C locale for floating point numbers
1429
* to be logged consistently.
1430
*/
1431
setlocale(LC_ALL, "C");
1432
1433
/*
1434
* In the event loop we pass input from user tty to leader
1435
* and pass output from leader to stdout and IO plugin.
1436
* Try to recover on ENXIO, it means the tty was revoked.
1437
*/
1438
add_io_events(ec);
1439
do {
1440
if (sudo_ev_dispatch(ec->evbase) == -1)
1441
sudo_warn("%s", U_("error in event loop"));
1442
if (sudo_ev_got_break(ec->evbase)) {
1443
/* error from callback */
1444
sudo_debug_printf(SUDO_DEBUG_ERROR, "event loop exited prematurely");
1445
/* XXX: no good way to know if we should terminate the command. */
1446
if (cstat->val == CMD_INVALID && ec->cmnd_pid != -1) {
1447
/* no status message, kill command */
1448
terminate_command(ec->cmnd_pid, true);
1449
ec->cmnd_pid = -1;
1450
/* TODO: need way to pass an error to the sudo front end */
1451
cstat->type = CMD_WSTATUS;
1452
cstat->val = W_EXITCODE(1, SIGKILL);
1453
}
1454
} else if (!sudo_ev_got_exit(ec->evbase)) {
1455
switch (errno) {
1456
case ENXIO:
1457
case EIO:
1458
case EBADF:
1459
/* /dev/tty was revoked, remove tty events and retry (once) */
1460
if (evloop_retries == -1 && io_fds[SFD_USERTTY] != -1) {
1461
ev_free_by_fd(ec->evbase, io_fds[SFD_USERTTY]);
1462
evloop_retries = 1;
1463
}
1464
break;
1465
}
1466
}
1467
} while (evloop_retries-- > 0);
1468
1469
/* De-register cleanup hook, the pty is going away. */
1470
sudo_fatal_callback_deregister(pty_cleanup_hook);
1471
1472
/* Flush any remaining output, free I/O bufs and events, do logout. */
1473
pty_finish(ec, cstat);
1474
1475
/* Free things up. */
1476
free_exec_closure(ec);
1477
1478
debug_return_bool(true);
1479
}
1480
1481
/*
1482
* Propagate tty size change to pty being used by the command, pass
1483
* new window size to I/O plugins and deliver SIGWINCH to the command.
1484
*/
1485
static void
1486
sync_ttysize(struct exec_closure *ec)
1487
{
1488
struct winsize wsize;
1489
debug_decl(sync_ttysize, SUDO_DEBUG_EXEC);
1490
1491
if (ioctl(io_fds[SFD_USERTTY], TIOCGWINSZ, &wsize) == 0) {
1492
if (wsize.ws_row != ec->rows || wsize.ws_col != ec->cols) {
1493
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: %d x %d -> %hd x %hd",
1494
__func__, ec->rows, ec->cols, wsize.ws_row, wsize.ws_col);
1495
1496
/* Log window change event. */
1497
log_winchange(ec, wsize.ws_row, wsize.ws_col);
1498
1499
/* Update pty window size and send command SIGWINCH. */
1500
(void)ioctl(io_fds[SFD_LEADER], IOCTL_REQ_CAST TIOCSWINSZ, &wsize);
1501
killpg(ec->cmnd_pid, SIGWINCH);
1502
1503
/* Update rows/cols. */
1504
ec->rows = wsize.ws_row;
1505
ec->cols = wsize.ws_col;
1506
}
1507
}
1508
1509
debug_return;
1510
}
1511
1512