forked from sudo-project/sudo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec_pty.c
More file actions
1510 lines (1360 loc) · 46.2 KB
/
exec_pty.c
File metadata and controls
1510 lines (1360 loc) · 46.2 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-License-Identifier: ISC
*
* Copyright (c) 2009-2025 Todd C. Miller <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#if defined(HAVE_STDINT_H)
# include <stdint.h>
#elif defined(HAVE_INTTYPES_H)
# include <inttypes.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <termios.h> /* for struct winsize on HP-UX */
#include <sudo.h>
#include <sudo_exec.h>
#include <sudo_plugin.h>
#include <sudo_plugin_int.h>
/* Tail queue of messages to send to the monitor. */
struct monitor_message {
TAILQ_ENTRY(monitor_message) entries;
struct command_status cstat;
};
TAILQ_HEAD(monitor_message_list, monitor_message);
static struct monitor_message_list monitor_messages =
TAILQ_HEAD_INITIALIZER(monitor_messages);
static unsigned int term_raw_flags;
static struct exec_closure pty_ec;
static void sync_ttysize(struct exec_closure *ec);
static void schedule_signal(struct exec_closure *ec, int signo);
static void send_command_status(struct exec_closure *ec, int type, int val);
/*
* Restore user's terminal settings and update utmp, as needed.
*/
static void
pty_cleanup(struct exec_closure *ec, int wstatus)
{
debug_decl(pty_cleanup, SUDO_DEBUG_EXEC);
/* Restore terminal settings. */
if (ec->term_raw) {
/* Only restore the terminal if sudo is the foreground process. */
const pid_t tcpgrp = tcgetpgrp(io_fds[SFD_USERTTY]);
if (tcpgrp == ec->ppgrp) {
if (!sudo_term_restore(io_fds[SFD_USERTTY], false))
sudo_warn("%s", U_("unable to restore terminal settings"));
ec->term_raw = false;
}
}
/* Update utmp */
if (ISSET(ec->details->flags, CD_SET_UTMP) && ec->ptyname != NULL)
utmp_logout(ec->ptyname, wstatus);
debug_return;
}
/*
* Cleanup hook for sudo_fatal()/sudo_fatalx()
*/
static void
pty_cleanup_hook(void)
{
pty_cleanup(&pty_ec, 0);
}
/*
* Allocate a pty if /dev/tty is a tty.
* Fills in io_fds[SFD_USERTTY], io_fds[SFD_LEADER] and io_fds[SFD_FOLLOWER].
* Returns the dynamically allocated pty name on success, NULL on failure.
*/
static bool
pty_setup(struct exec_closure *ec)
{
struct command_details *details = ec->details;
debug_decl(pty_setup, SUDO_DEBUG_EXEC);
io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR);
if (io_fds[SFD_USERTTY] == -1) {
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: no %s, not allocating a pty",
__func__, _PATH_TTY);
debug_return_bool(false);
}
ec->ptyname = get_pty(&io_fds[SFD_LEADER], &io_fds[SFD_FOLLOWER],
details->cred.euid);
if (ec->ptyname == NULL)
sudo_fatal("%s", U_("unable to allocate pty"));
/* Add entry to utmp/utmpx? */
if (ISSET(details->flags, CD_SET_UTMP)) {
utmp_login(details->tty, ec->ptyname, io_fds[SFD_FOLLOWER],
details->utmp_user);
}
/* Update tty name in command details (used by monitor, SELinux, AIX). */
details->tty = ec->ptyname;
/* Register cleanup function. */
sudo_fatal_callback_register(pty_cleanup_hook);
sudo_debug_printf(SUDO_DEBUG_INFO,
"%s: %s fd %d, pty leader fd %d, pty follower fd %d",
__func__, _PATH_TTY, io_fds[SFD_USERTTY], io_fds[SFD_LEADER],
io_fds[SFD_FOLLOWER]);
debug_return_bool(true);
}
/*
* Check whether sudo is running in the foreground.
* Updates the foreground flag in the closure.
* Returns 0 if there is no tty, the foreground process group ID
* on success, or -1 on failure (tty revoked).
*/
static pid_t
check_foreground(struct exec_closure *ec)
{
int ret = 0;
debug_decl(check_foreground, SUDO_DEBUG_EXEC);
if (io_fds[SFD_USERTTY] != -1) {
if ((ret = tcgetpgrp(io_fds[SFD_USERTTY])) != -1) {
ec->foreground = ret == ec->ppgrp;
}
}
debug_return_int(ret);
}
/*
* Restore the terminal when sudo is resumed in response to SIGCONT.
*/
static bool
resume_terminal(struct exec_closure *ec)
{
debug_decl(resume_terminal, SUDO_DEBUG_EXEC);
if (check_foreground(ec) == -1) {
/* User's tty was revoked. */
debug_return_bool(false);
}
/* Update the pty settings based on the user's terminal. */
if (!sudo_term_copy(io_fds[SFD_USERTTY], io_fds[SFD_LEADER])) {
sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO,
"%s: unable to copy terminal settings to pty", __func__);
debug_return_bool(false);
}
sync_ttysize(ec);
sudo_debug_printf(SUDO_DEBUG_INFO, "parent is in %s (%s -> %s)",
ec->foreground ? "foreground" : "background",
ec->term_raw ? "raw" : "cooked",
ec->foreground ? "raw" : "cooked");
if (ec->foreground) {
/* Foreground process, set tty to raw mode. */
ec->term_raw = sudo_term_raw(io_fds[SFD_USERTTY], term_raw_flags);
} else {
/* Background process, no access to tty. */
ec->term_raw = false;
}
debug_return_bool(true);
}
/*
* Suspend sudo if the underlying command is suspended.
* Returns SIGCONT_FG if the command should be resumed in the
* foreground or SIGCONT_BG if it is a background process.
*/
static int
suspend_sudo_pty(struct exec_closure *ec, int signo)
{
char signame[SIG2STR_MAX];
struct sigaction sa, osa, saved_sigcont;
int ret = 0;
debug_decl(suspend_sudo_pty, SUDO_DEBUG_EXEC);
/*
* Ignore SIGCONT when we suspend to avoid calling resume_terminal()
* multiple times.
*/
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = SIG_DFL;
if (sudo_sigaction(SIGCONT, &sa, &saved_sigcont) != 0)
sudo_warn("%s", U_("unable to set handler for SIGCONT"));
if (sig2str(signo, signame) == -1)
(void)snprintf(signame, sizeof(signame), "%d", signo);
switch (signo) {
case SIGTTOU:
case SIGTTIN:
/*
* If sudo is already the foreground process, just resume the command
* in the foreground. If not, we'll suspend sudo and resume later.
*/
if (!ec->foreground) {
if (check_foreground(ec) == -1) {
/* User's tty was revoked. */
break;
}
}
if (ec->foreground) {
sudo_debug_printf(SUDO_DEBUG_INFO,
"%s: command received SIG%s, parent running in the foreground",
__func__, signame);
if (!ec->term_raw) {
if (sudo_term_raw(io_fds[SFD_USERTTY], term_raw_flags))
ec->term_raw = true;
}
ret = SIGCONT_FG; /* resume command in foreground */
break;
}
FALLTHROUGH;
case SIGSTOP:
case SIGTSTP:
default:
/* Flush any remaining output and deschedule I/O events. */
del_io_events(true);
/* Restore original tty mode before suspending. */
if (ec->term_raw) {
if (!sudo_term_restore(io_fds[SFD_USERTTY], false))
sudo_warn("%s", U_("unable to restore terminal settings"));
ec->term_raw = false;
}
/* Log the suspend event. */
log_suspend(ec, signo);
/* Suspend self and continue command when we resume. */
if (signo != SIGSTOP) {
if (sudo_sigaction(signo, &sa, &osa) != 0)
sudo_warn(U_("unable to set handler for SIG%s"), signame);
}
/*
* We stop sudo's process group, even if sudo is not the process
* group leader. If we only send the signal to sudo itself,
* the shell will not notice if it is not in monitor mode.
* This can happen when sudo is run from a shell script, for
* example. In this case we need to signal the shell itself.
* If the process group leader is no longer present, we must kill
* the command since there will be no one to resume us.
*/
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: killpg(%d, SIG%s) [parent]",
__func__, (int)ec->ppgrp, signame);
if ((ec->ppgrp != ec->sudo_pid && kill(ec->ppgrp, 0) == -1) ||
killpg(ec->ppgrp, signo) == -1) {
sudo_debug_printf(SUDO_DEBUG_ERROR,
"%s: no parent to suspend, terminating command.", __func__);
terminate_command(ec->cmnd_pid, true);
ec->cmnd_pid = -1;
}
if (signo != SIGSTOP) {
if (sudo_sigaction(signo, &osa, NULL) != 0)
sudo_warn(U_("unable to restore handler for SIG%s"), signame);
}
/* If we failed to suspend, the command is no longer running. */
if (ec->cmnd_pid == -1)
break;
/* Log the resume event. */
log_suspend(ec, SIGCONT);
/* Update the pty's terminal settings and restore /dev/tty settings. */
if (!resume_terminal(ec))
break;
/*
* We always resume the command in the foreground if sudo itself
* is the foreground process (and we were able to set /dev/tty to
* raw mode). This helps work around poorly behaved programs that
* catch SIGTTOU/SIGTTIN but suspend themselves with SIGSTOP. At
* worst, sudo will go into the background but upon resume the
* command will be runnable. Otherwise, we can get into a
* situation where the command will immediately suspend itself.
*/
ret = ec->term_raw ? SIGCONT_FG : SIGCONT_BG;
break;
}
if (sudo_sigaction(SIGCONT, &saved_sigcont, NULL) != 0)
sudo_warn("%s", U_("unable to restore handler for SIGCONT"));
debug_return_int(ret);
}
/*
* SIGTTIN signal handler for read_callback that just sets a flag.
*/
static volatile sig_atomic_t got_sigttin;
static void
sigttin(int signo)
{
got_sigttin = 1;
}
/*
* Close the leader fd to revoke the pty and signal the foreground pgrp.
* We send SIGHUP to the foreground process group (or the command's
* process group if no pty) after closing the leader fd. We cannot
* just forward the SIGHUP we receive from the kernel since the
* command may not be the foreground process. This fixes a problem
* on Linux with, e.g. "sudo su" where su(1) blocks SIGHUP.
*/
static void
revoke_pty(struct exec_closure *ec)
{
pid_t pgrp = ec->cmnd_pid;
debug_decl(revoke_pty, SUDO_DEBUG_EXEC);
sudo_debug_printf(SUDO_DEBUG_NOTICE, "user's tty revoked");
if (io_fds[SFD_LEADER] != -1) {
const pid_t tcpgrp = tcgetpgrp(io_fds[SFD_LEADER]);
if (tcpgrp != -1)
pgrp = tcpgrp;
close(io_fds[SFD_LEADER]);
}
if (pgrp != -1) {
sudo_debug_printf(SUDO_DEBUG_NOTICE, "%s: killpg(%d, SIGHUP)",
__func__, (int)pgrp);
killpg(pgrp, SIGHUP);
}
}
/*
* Read an iobuf that is ready.
*/
static void
read_callback(int fd, int what, void *v)
{
struct io_buffer *iob = v;
struct sudo_event_base *evbase = sudo_ev_get_base(iob->revent);
struct sigaction sa, osa;
int saved_errno;
ssize_t n;
debug_decl(read_callback, SUDO_DEBUG_EXEC);
/*
* We ignore SIGTTIN by default but we need to handle it when reading
* from the terminal. A signal event won't work here because the
* read() would be restarted, preventing the callback from running.
*/
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = sigttin;
got_sigttin = 0;
sigaction(SIGTTIN, &sa, &osa);
n = read(fd, iob->buf + iob->len, sizeof(iob->buf) - iob->len);
saved_errno = errno;
sigaction(SIGTTIN, &osa, NULL);
errno = saved_errno;
switch (n) {
case -1:
if (got_sigttin) {
/* Schedule SIGTTIN to be forwarded to the command. */
schedule_signal(iob->ec, SIGTTIN);
}
if (errno == EAGAIN || errno == EINTR) {
/* Not an error, retry later. */
break;
}
/* Treat read error as fatal and close the fd. */
sudo_debug_printf(SUDO_DEBUG_ERROR,
"error reading fd %d: %s", fd, strerror(errno));
FALLTHROUGH;
case 0:
/* got EOF or pty has gone away */
if (n == 0) {
sudo_debug_printf(SUDO_DEBUG_INFO,
"read EOF from fd %d", fd);
}
safe_close(fd);
ev_free_by_fd(evbase, fd);
/* If writer already consumed the buffer, close it too. */
if (iob->wevent != NULL && iob->off == iob->len) {
/*
* Don't close the pty leader yet, it will invalidate the pty.
* We ask the monitor to signal the running process first.
*/
const int wfd = sudo_ev_get_fd(iob->wevent);
if (wfd == io_fds[SFD_LEADER]) {
revoke_pty(iob->ec);
} else {
safe_close(wfd);
}
ev_free_by_fd(evbase, wfd);
iob->off = iob->len = 0;
}
break;
default:
sudo_debug_printf(SUDO_DEBUG_INFO,
"read %zd bytes from fd %d", n, fd);
if (!iob->action(iob->buf + iob->len, (unsigned int)n, iob)) {
terminate_command(iob->ec->cmnd_pid, true);
iob->ec->cmnd_pid = -1;
}
iob->len += (unsigned int)n;
/* Disable reader if buffer is full. */
if (iob->len == sizeof(iob->buf))
sudo_ev_del(evbase, iob->revent);
/* Enable writer now that there is new data in the buffer. */
if (iob->wevent != NULL) {
if (sudo_ev_add(evbase, iob->wevent, NULL, false) == -1)
sudo_fatal("%s", U_("unable to add event to queue"));
}
break;
}
debug_return;
}
/*
* SIGTTOU signal handler for write_callback that just sets a flag.
*/
static volatile sig_atomic_t got_sigttou;
static void
sigttou(int signo)
{
got_sigttou = 1;
}
/*
* Write an iobuf that is ready.
*/
static void
write_callback(int fd, int what, void *v)
{
struct io_buffer *iob = v;
struct sudo_event_base *evbase = sudo_ev_get_base(iob->wevent);
struct sigaction sa, osa;
int saved_errno;
ssize_t n;
debug_decl(write_callback, SUDO_DEBUG_EXEC);
/*
* We ignore SIGTTOU by default but we need to handle it when writing
* to the terminal. A signal event won't work here because the
* write() would be restarted, preventing the callback from running.
*/
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = sigttou;
got_sigttou = 0;
sigaction(SIGTTOU, &sa, &osa);
n = write(fd, iob->buf + iob->off, iob->len - iob->off);
saved_errno = errno;
sigaction(SIGTTOU, &osa, NULL);
errno = saved_errno;
if (n == -1) {
switch (errno) {
case EPIPE:
case ENXIO:
case EIO:
case EBADF:
/* other end of pipe closed or pty revoked */
sudo_debug_printf(SUDO_DEBUG_INFO,
"unable to write %u bytes to fd %d",
iob->len - iob->off, fd);
/* Close reader if there is one. */
if (iob->revent != NULL) {
/*
* Don't close the pty leader, it will invalidate the pty.
* We ask the monitor to signal the running process first.
*/
const int rfd = sudo_ev_get_fd(iob->revent);
if (rfd == io_fds[SFD_LEADER]) {
revoke_pty(iob->ec);
} else {
safe_close(rfd);
}
ev_free_by_fd(evbase, rfd);
}
safe_close(fd);
ev_free_by_fd(evbase, fd);
break;
case EINTR:
if (got_sigttou) {
/* Schedule SIGTTOU to be forwarded to the command. */
schedule_signal(iob->ec, SIGTTOU);
}
FALLTHROUGH;
case EAGAIN:
/* Not an error, retry later. */
break;
default:
/* XXX - need a way to distinguish non-exec error. */
iob->ec->cstat->type = CMD_ERRNO;
iob->ec->cstat->val = errno;
sudo_debug_printf(SUDO_DEBUG_ERROR,
"error writing fd %d: %s", fd, strerror(errno));
sudo_ev_loopbreak(evbase);
break;
}
} else {
sudo_debug_printf(SUDO_DEBUG_INFO,
"wrote %zd of %u bytes to fd %d", n, iob->len - iob->off, fd);
iob->off += (unsigned int)n;
/* Disable writer and reset the buffer if fully consumed. */
if (iob->off == iob->len) {
iob->off = iob->len = 0;
sudo_ev_del(evbase, iob->wevent);
/* Forward the EOF from reader to writer. */
if (iob->revent == NULL) {
safe_close(fd);
ev_free_by_fd(evbase, fd);
}
}
/*
* Enable reader if buffer is not full but avoid reading /dev/tty
* if not in raw mode or the command is no longer running.
*/
if (iob->revent != NULL && iob->len != sizeof(iob->buf)) {
if (!USERTTY_EVENT(iob->revent) ||
(iob->ec->term_raw && iob->ec->cmnd_pid != -1)) {
if (sudo_ev_add(evbase, iob->revent, NULL, false) == -1)
sudo_fatal("%s", U_("unable to add event to queue"));
}
}
}
debug_return;
}
/*
* We already closed the follower so reads from the leader will not block.
*/
static void
pty_finish(struct exec_closure *ec, struct command_status *cstat)
{
int flags;
debug_decl(pty_finish, SUDO_DEBUG_EXEC);
/* Flush any remaining output (the plugin already got it) and free bufs. */
if (io_fds[SFD_USERTTY] != -1) {
flags = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
if (flags != -1 && ISSET(flags, O_NONBLOCK)) {
CLR(flags, O_NONBLOCK);
(void) fcntl(io_fds[SFD_USERTTY], F_SETFL, flags);
}
}
del_io_events(false);
free_io_bufs();
/* Restore terminal settings and update utmp. */
pty_cleanup(ec, cstat->type == CMD_WSTATUS ? cstat->val : 0);
debug_return;
}
/*
* Send command status to the monitor (currently just signal forwarding).
*/
static void
send_command_status(struct exec_closure *ec, int type, int val)
{
struct monitor_message *msg;
debug_decl(send_command_status, SUDO_DEBUG_EXEC);
if ((msg = calloc(1, sizeof(*msg))) == NULL)
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
msg->cstat.type = type;
msg->cstat.val = val;
TAILQ_INSERT_TAIL(&monitor_messages, msg, entries);
if (sudo_ev_add(ec->evbase, ec->fwdchannel_event, NULL, true) == -1)
sudo_fatal("%s", U_("unable to add event to queue"));
/* Restart event loop to send the command immediately. */
sudo_ev_loopcontinue(ec->evbase);
debug_return;
}
/*
* Schedule a signal to be forwarded.
*/
static void
schedule_signal(struct exec_closure *ec, int signo)
{
debug_decl(schedule_signal, SUDO_DEBUG_EXEC);
if (signo == 0)
debug_return;
if (sudo_debug_needed(SUDO_DEBUG_DIAG)) {
char signame[SIG2STR_MAX];
if (signo == SIGCONT_FG)
strlcpy(signame, "CONT_FG", sizeof(signame));
else if (signo == SIGCONT_BG)
strlcpy(signame, "CONT_BG", sizeof(signame));
else if (sig2str(signo, signame) == -1)
(void)snprintf(signame, sizeof(signame), "%d", signo);
sudo_debug_printf(SUDO_DEBUG_DIAG, "scheduled SIG%s for command",
signame);
}
send_command_status(ec, CMD_SIGNO, signo);
debug_return;
}
/*
* Free any remaining monitor messages in the queue.
*/
static void
flush_monitor_messages(void)
{
struct monitor_message *msg;
debug_decl(flush_monitor_messages, SUDO_DEBUG_EXEC);
while ((msg = TAILQ_FIRST(&monitor_messages)) != NULL) {
TAILQ_REMOVE(&monitor_messages, msg, entries);
free(msg);
}
debug_return;
}
static void
backchannel_cb(int fd, int what, void *v)
{
struct exec_closure *ec = v;
struct command_status cstat;
ssize_t nread;
debug_decl(backchannel_cb, SUDO_DEBUG_EXEC);
/*
* Read command status from the monitor.
* Note that the backchannel is a *blocking* socket.
*/
nread = recv(fd, &cstat, sizeof(cstat), MSG_WAITALL);
switch (nread) {
case -1:
switch (errno) {
case EINTR:
case EAGAIN:
/* Nothing ready. */
break;
default:
if (ec->cstat->type == CMD_INVALID) {
ec->cstat->type = CMD_ERRNO;
ec->cstat->val = errno;
sudo_debug_printf(SUDO_DEBUG_ERROR,
"%s: failed to read command status: %s",
__func__, strerror(errno));
sudo_ev_loopbreak(ec->evbase);
}
break;
}
break;
case 0:
/* EOF, monitor exited or was killed. */
sudo_debug_printf(SUDO_DEBUG_INFO,
"EOF on backchannel, monitor dead?");
if (ec->cstat->type == CMD_INVALID) {
/* XXX - need new CMD_ type for monitor errors. */
ec->cstat->type = CMD_ERRNO;
ec->cstat->val = ECONNRESET;
}
sudo_ev_loopexit(ec->evbase);
break;
case sizeof(cstat):
/* Check command status. */
switch (cstat.type) {
case CMD_ERRNO:
/* Monitor was unable to execute command or broken pipe. */
sudo_debug_printf(SUDO_DEBUG_INFO, "errno from monitor: %s",
strerror(cstat.val));
sudo_ev_loopbreak(ec->evbase);
*ec->cstat = cstat;
break;
case CMD_PID:
ec->cmnd_pid = cstat.val;
sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d",
ec->details->command, (int)ec->cmnd_pid);
if (ISSET(ec->details->flags, CD_USE_PTRACE)) {
/* Try to seize control of the command using ptrace(2). */
int rc = exec_ptrace_seize(ec->cmnd_pid);
if (rc == 0) {
/* There is another tracer present. */
CLR(ec->details->flags, CD_INTERCEPT|CD_LOG_SUBCMDS|CD_USE_PTRACE);
} else if (rc == -1) {
if (ec->cstat->type == CMD_INVALID) {
ec->cstat->type = CMD_ERRNO;
ec->cstat->val = errno;
}
sudo_ev_loopbreak(ec->evbase);
}
}
break;
case CMD_WSTATUS:
if (WIFSTOPPED(cstat.val)) {
int signo;
/* Suspend parent and tell monitor how to resume on return. */
sudo_debug_printf(SUDO_DEBUG_INFO,
"command stopped, suspending parent");
signo = suspend_sudo_pty(ec, WSTOPSIG(cstat.val));
schedule_signal(ec, signo);
/* Re-enable I/O events */
add_io_events(ec);
} else {
/* Command exited or was killed, either way we are done. */
sudo_debug_printf(SUDO_DEBUG_INFO, "command exited or was killed");
sudo_ev_loopexit(ec->evbase);
*ec->cstat = cstat;
}
break;
}
/* Keep reading command status messages until EAGAIN or EOF. */
break;
default:
/* Short read, should not happen. */
if (ec->cstat->type == CMD_INVALID) {
ec->cstat->type = CMD_ERRNO;
ec->cstat->val = EIO;
sudo_debug_printf(SUDO_DEBUG_ERROR,
"%s: failed to read command status: short read", __func__);
sudo_ev_loopbreak(ec->evbase);
}
break;
}
debug_return;
}
/*
* Handle changes to the monitor's status (SIGCHLD).
*/
static void
handle_sigchld_pty(struct exec_closure *ec)
{
int n, status;
pid_t pid;
debug_decl(handle_sigchld_pty, SUDO_DEBUG_EXEC);
/* There may be multiple children in intercept mode. */
for (;;) {
do {
pid = waitpid(-1, &status, __WALL|WUNTRACED|WNOHANG);
} while (pid == -1 && errno == EINTR);
switch (pid) {
case -1:
if (errno != ECHILD) {
sudo_warn(U_("%s: %s"), __func__, "waitpid");
debug_return;
}
FALLTHROUGH;
case 0:
/* Nothing left to wait for. */
debug_return;
}
if (WIFEXITED(status)) {
sudo_debug_printf(SUDO_DEBUG_INFO, "%s: process %d exited: %d",
__func__, (int)pid, WEXITSTATUS(status));
if (pid == ec->monitor_pid)
ec->monitor_pid = -1;
} else if (WIFSIGNALED(status)) {
if (sudo_debug_needed(SUDO_DEBUG_INFO)) {
char signame[SIG2STR_MAX];
if (sig2str(WTERMSIG(status), signame) == -1) {
(void)snprintf(signame, sizeof(signame), "%d",
WTERMSIG(status));
}
sudo_debug_printf(SUDO_DEBUG_INFO,
"%s: process %d killed, SIG%s",
__func__, (int)pid, signame);
}
if (pid == ec->monitor_pid)
ec->monitor_pid = -1;
} else if (WIFSTOPPED(status)) {
if (pid != ec->monitor_pid) {
if (ISSET(ec->details->flags, CD_USE_PTRACE))
exec_ptrace_stopped(pid, status, ec->intercept);
continue;
}
/*
* If the monitor dies we get notified via backchannel_cb().
* If it was stopped, we should stop too (the command keeps
* running in its pty) and continue it when we come back.
*/
sudo_debug_printf(SUDO_DEBUG_INFO,
"monitor stopped, suspending sudo");
n = suspend_sudo_pty(ec, WSTOPSIG(status));
kill(pid, SIGCONT);
schedule_signal(ec, n);
/* Re-enable I/O events */
add_io_events(ec);
} else {
sudo_debug_printf(SUDO_DEBUG_WARN,
"%s: unexpected wait status 0x%x for process (%d)",
__func__, status, (int)pid);
}
}
}
/* Signal callback */
static void
signal_cb_pty(int signo, int what, void *v)
{
struct sudo_ev_siginfo_container *sc = v;
struct exec_closure *ec = sc->closure;
debug_decl(signal_cb_pty, SUDO_DEBUG_EXEC);
if (ec->monitor_pid == -1)
debug_return;
if (sudo_debug_needed(SUDO_DEBUG_DIAG)) {
char signame[SIG2STR_MAX];
if (sig2str(signo, signame) == -1)
(void)snprintf(signame, sizeof(signame), "%d", signo);
sudo_debug_printf(SUDO_DEBUG_DIAG,
"%s: evbase %p, monitor: %d, signo %s(%d), cstat %p", __func__,
ec->evbase, (int)ec->monitor_pid, signame, signo, ec->cstat);
}
switch (signo) {
case SIGCHLD:
handle_sigchld_pty(ec);
break;
case SIGCONT:
resume_terminal(ec);
break;
case SIGWINCH:
sync_ttysize(ec);
break;
case SIGHUP:
/*
* Avoid forwarding SIGHUP sent by the kernel, it probably means
* that the user's terminal was revoked. When we detect that the
* terminal has been revoked, the monitor will send SIGHUP itself.
*/
if (!USER_SIGNALED(sc->siginfo))
break;
FALLTHROUGH;
default:
/*
* Do not forward signals sent by the command itself or a member of the
* command's process group (but only when either sudo or the command is
* the process group leader). We don't want the command to indirectly
* kill itself. For example, this can happen with some versions of
* reboot that call kill(-1, SIGTERM) to kill all other processes.
*/
if (USER_SIGNALED(sc->siginfo) && sc->siginfo->si_pid != 0) {
pid_t si_pgrp;
if (sc->siginfo->si_pid == ec->cmnd_pid)
debug_return;
si_pgrp = getpgid(sc->siginfo->si_pid);
if (si_pgrp != -1) {
if (si_pgrp == ec->cmnd_pid || si_pgrp == ec->sudo_pid)
debug_return;
}
}
/* Schedule signal to be forwarded to the command. */
schedule_signal(ec, signo);
break;
}
debug_return;
}
/*
* Forward signals in monitor_messages to the monitor so it can
* deliver them to the command.
*/
static void
fwdchannel_cb(int sock, int what, void *v)
{
struct exec_closure *ec = v;
struct monitor_message *msg;
ssize_t nsent;
debug_decl(fwdchannel_cb, SUDO_DEBUG_EXEC);
while ((msg = TAILQ_FIRST(&monitor_messages)) != NULL) {
switch (msg->cstat.type) {
case CMD_SIGNO:
if (sudo_debug_needed(SUDO_DEBUG_INFO)) {
char signame[SIG2STR_MAX];
if (msg->cstat.val == SIGCONT_FG)
strlcpy(signame, "CONT_FG", sizeof(signame));
else if (msg->cstat.val == SIGCONT_BG)
strlcpy(signame, "CONT_BG", sizeof(signame));
else if (sig2str(msg->cstat.val, signame) == -1) {
(void)snprintf(signame, sizeof(signame), "%d",
msg->cstat.val);
}
sudo_debug_printf(SUDO_DEBUG_INFO,
"sending SIG%s to monitor over backchannel", signame);
}
break;
default:
sudo_debug_printf(SUDO_DEBUG_INFO,
"sending cstat type %d, value %d to monitor over backchannel",
msg->cstat.type, msg->cstat.val);
break;
}
TAILQ_REMOVE(&monitor_messages, msg, entries);
nsent = send(sock, &msg->cstat, sizeof(msg->cstat), 0);
if (nsent != sizeof(msg->cstat)) {
if (errno == EPIPE) {
sudo_debug_printf(SUDO_DEBUG_ERROR,
"broken pipe writing to monitor over backchannel");
/* Other end of socket gone, empty out monitor_messages. */
free(msg);
flush_monitor_messages();
/* XXX - need new CMD_ type for monitor errors. */
ec->cstat->type = CMD_ERRNO;
ec->cstat->val = errno;
sudo_ev_loopbreak(ec->evbase);
}
break;
}
free(msg);
}
}
/*
* Fill in the non-event part of the exec closure.
*/
static void
init_exec_closure(struct exec_closure *ec, struct command_status *cstat,
struct command_details *details, const struct user_details *user_details,
pid_t sudo_pid, pid_t ppgrp)
{
debug_decl(init_exec_closure, SUDO_DEBUG_EXEC);
/* Fill in the non-event part of the closure. */
memset(ec, 0, sizeof(*ec));
ec->sudo_pid = sudo_pid;
ec->ppgrp = ppgrp;
ec->cmnd_pid = -1;
ec->cstat = cstat;
ec->details = details;
ec->rows = user_details->ts_rows;
ec->cols = user_details->ts_cols;
debug_return;
}
/*
* Allocate and set events for the signal pipe and backchannel.
* Forwarded signals on the backchannel are enabled on demand.
*/
static void
init_exec_events(struct exec_closure *ec, struct sudo_event_base *evbase,
int backchannel)
{
debug_decl(init_exec_events, SUDO_DEBUG_EXEC);
/* Setup event base and events. */
ec->evbase = evbase;
/* Event for command status via backchannel. */
ec->backchannel_event = sudo_ev_alloc(backchannel,
SUDO_EV_READ|SUDO_EV_PERSIST, backchannel_cb, ec);
if (ec->backchannel_event == NULL)
sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));