File: ttysnoops.c

package info (click to toggle)
ttysnoop 0.12d-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 396 kB
  • ctags: 460
  • sloc: ansic: 5,419; makefile: 172
file content (702 lines) | stat: -rw-r--r-- 14,653 bytes parent folder | download
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
/*
	ttysnoops.c
	
	ttysnoops sets up a pseudo-tty for the specified program and
	redirects its stdin/stdout/stderr to/from the current ctty 
	and a specified snoop device (usually another tty or a socket)
	
	v0.00	4-1-94 Carl Declerck	- first version
	v0.01	6-1-94	     ""		- added /etc/snooptab file
	v0.02	9-1-94	     ""		- added socket support
	v0.10	8-8-94	     ""		- various bug fixes
	v0.11	9-8-94       ""		- password authentication added
	v0.11a 23-8-94 Ulrich Callmeier - shadow support hacked in
	v0.12	6-9-94 Carl Declerck	- added suspend/resume key
	v0.12a	6-8-95 Josh Bailey		- fixed lingering utmp-entry bug
	v0.12b	6-3-96 Carl Declerck	- minor cleanups
	v0.12c 21-3-96 Carl Declerck	- fixed bug to exit when telnetd exits
	v0.12d  8-4-98 Carl Declerck	- updated #includes a bit
*/

#ifndef __sun__
#  define _XOPEN_SOURCE 600 /* ptsname(), posix_openpt() */
#  define _BSD_SOURCE   /* SUN_LEN from <sys/un.h> */
#else /* __sun__ */
#  define __EXTENSIONS__
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <syslog.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <termios.h>
#include <time.h>
#include <grp.h>
#include <pwd.h>
#include <utmp.h>
#include <errno.h>
#include <string.h>
#include <crypt.h>
#ifdef SHADOW_PWD
#include <shadow.h>
#endif
#include "config.h"
#include "common.h"
#ifndef __GLIBC__
#  include "logwtmp.h"
#endif

#define BUFF_SIZE	256
#define PASS_SIZE	256

char buff[BUFF_SIZE];

int snoopfd = -1, authfd = -1;
int pgmpid = -1, authpid = -1, servpid = -1;
int use_socket = 0, fdmax = 0, proctype = DEAD_PROCESS;
char snoopdev[32], ptynam[32], childproc[128], sockname[128];
char *short_ptynam, *shorter_ptynam;


/* read a single line from a stream, ignoring all irrelevant stuff */

int  read_line (char *buff, FILE *f)
{
    int b, i;

    *buff = 0;
    do
    {
        while ((b = fgetc(f)) != EOF && isspace(b));
        if (b == EOF) return (0);
        for (i = 0; b != EOF && b != '\n' && b != '\r'; i++)
        {
            buff[i] = (b == '\t') ? ' ': b;
            b = fgetc(f);
        }
        buff[i] = 0;
    }
    while (*buff == '#');

    return (1);
}

/* extract the first word from a string */

char *parse_arg (char *arg, char *buff)
{
	int i = 0, j = 0, quote = 0;

	*arg = 0;
	if (buff == NULL)
		return (NULL);
		
	while (buff[i] && buff[i] == ' ') i++;
	while (buff[i] && (buff[i] != ' ' || quote))
	{
		switch (buff[i])
		{
			case '\\' :	arg[j++] = buff[++i]; break;
			case '"'  :	quote = !quote; break;
			default   :	arg[j++] = buff[i];
		}
		i++;
   	}	
	while (buff[i] && buff[i] == ' ') i++;
	arg[j] = 0;

	return (j ? buff + i : NULL);
}

/* process the snooptab file */

int process_snooptab (void)
{
	FILE *f;
	char line[1024], arg[128], tty[16], *tail;
	
	if ((f = fopen(SNOOPTAB, "r")) == NULL)
		errorf ("can't open %s\n", SNOOPTAB);
	
	strcpy (tty, leafname(ttyname(STDIN_FILENO)));
	
	while (read_line(line, f))
	{
		tail = parse_arg(arg, line);
		
		if ((strcmp(arg, tty) == 0) || (*arg == '*'))
		{
			tail = parse_arg(snoopdev, tail);
			tail = parse_arg(arg, tail);
			tail = parse_arg(childproc, tail);
			
			if (strcmp(arg, "init") == 0)
				proctype = INIT_PROCESS;
			else if (strcmp(arg, "login") == 0)
				proctype = LOGIN_PROCESS;
			else if (strcmp(arg, "user") == 0)
				proctype = USER_PROCESS;
				
			if (strcmp(snoopdev, "socket") == 0)
				use_socket = 1;
				
			fclose (f);
			return (1);
		}
	}
			
	fclose (f);
	errorf ("no entry for %s in %s\n", tty, SNOOPTAB);
	return (0); /* Is still ignored. */
}

/* find & open a pty to be used by the pty-master */
int open_unix98_master (char *ptyname)
{
	int fd = posix_openpt(O_RDWR);
	char *name = "unknown";

	if (fd >= 0)
		name = ptsname(fd);
	if (name)
		strcpy(ptyname, name);
	return fd;
}
int find_ptyxx (char *ptyname)
{
	int fd, i, j;
	static char *s1 = "pqrs", *s2 = "0123456789abcdef";
	
	strcpy (ptyname, "/dev/ptyxx");
	
	for (i = 0; s1[i]; i++)
	{
		ptyname[8] = s1[i];
		
		for (j = 0; s2[j]; j++)
		{
			ptyname[9] = s2[j];
			
			if ((fd = open(ptyname, O_RDWR)) >= 0)
			{
				ptyname[5] = 't';
				return (fd);
			}
			
			if (errno == ENOENT)
				return (-1);
		}
	}
	
	return (-1);
}

/* find & open a pty (tty) to be used by pty-client */

int open_unix98_slave (int ptyfd)
{
	int fd;
	char *name = ptsname(ptyfd);

	grantpt(ptyfd);
	unlockpt(ptyfd);

	if ((fd = open(name, O_RDWR)) >= 0)
	{
#ifdef TIOCSCTTY /* GNU/kFreeBSD */
		(void) ioctl(fd, TIOCSCTTY, 0);
#endif
		return fd;
	}

	close(ptyfd);
	return -1;
}
int find_ttyxx (char *ttyname, int ptyfd)
{
	struct group *grp;
	int gid, fd;
	
	if ((grp = getgrnam("tty")) != NULL)
		gid = grp->gr_gid;
	else
		gid = -1;
	
	/* Abort on failure to set owner or access mode.  */
	if (chown (ttyname, getuid(), gid)
	    || chmod (ttyname, S_IRUSR | S_IWUSR | S_IWGRP))
	{
		close (ptyfd);
		return (-1);
	}
	
	if ((fd = open(ttyname, O_RDWR)) >= 0)
		return (fd);
	
	close (ptyfd);
	return (-1);
}

void abbreviate_ptyname (char *name, char **shortname, char **shortername)
{
	*shortname = *shortername = name;
	if (!name)
		return;
	if (strncmp(name, "/dev/", 5))
		return;
	*shortname = *shortername = name + 5;
	if (!strncmp(name, "/dev/tty", 8))
		*shortername = name + 8;
	else if (!strncmp(name, "/dev/pts", 8))
		*shortername = name + 8;
}

/* fork off the pty-client and redirect its stdin/out/err to the pty */

int fork_pty (int *ptyfd, char *ttynam)
{
	struct termios term;
	struct winsize twin;
	int ttyfd, pid, is_unix98 = 0;
	
	tcgetattr (STDIN_FILENO, &term);
	ioctl (STDIN_FILENO, TIOCGWINSZ, (char *) &twin);

	if ((*ptyfd = open_unix98_master(ttynam)) >= 0)
		is_unix98 = 1;
	else if ((*ptyfd = find_ptyxx(ttynam)) < 0)
		errorf ("can't open pty\n");
	
	if ((pid = fork()) < 0)
		errorf ("can't fork\n");
	
	if (pid == 0)       /* child */
	{
		if (setsid() < 0)
			errorf ("setsid failed\n");

		if (is_unix98)
			ttyfd = open_unix98_slave(*ptyfd);
		else
			ttyfd = find_ttyxx(ttynam, *ptyfd);
		if (ttyfd < 0)
			errorf ("can't open tty\n");
			
		close (*ptyfd);

		if (tcsetattr(ttyfd, TCSANOW, &term) < 0)
			errorf ("can't set termios\n");
		
		if (ioctl(ttyfd, TIOCSWINSZ, &twin) < 0)
			errorf ("can't set winsize\n");
		
		if (dup2(ttyfd, STDIN_FILENO) != STDIN_FILENO)
			errorf ("can't dup2 into stdin\n");
		
		if (dup2(ttyfd, STDOUT_FILENO) != STDOUT_FILENO)
			errorf ("can't dup2 into stdout\n");
		
		if (dup2(ttyfd, STDERR_FILENO) != STDERR_FILENO)
			errorf ("can't dup2 into stderr\n");
		
		if (ttyfd > STDERR_FILENO)
			close (ttyfd);
	}

	return (pid);
}		

void beep (void)
{
	fputc (7, stdout);
	fflush (stdout);
}

void sigalrm (int sig)
{
	sig = sig;

	printf ("\r\nPassword timeout\r\n");
	exit (0);
}

int inputs (char *buff, int max, FILE *f)
{
	int b, l;

	*buff = 0; max--;
	signal (SIGALRM, sigalrm);

	while (1)
	{
		alarm (10);
		if ((b = fgetc(f)) != EOF)
			switch (b)
			{
				case '\r' :
					alarm (0);
					return (0);

				case 8 :
				case 127 :
					if (*buff == 0)
						beep ();
					else
						buff[strlen(buff) - 1] = 0;
					break;

				case 0 :
					break;

				default :
					if ((b >= 32) && (b < 127))
					{
						if ((l = strlen(buff)) < max)
						{
							buff[l] = b;
							buff[l + 1] = 0;
						}
						else
							beep ();
					}
			}
	}

	return (0);
}
					
void authenticate (int fd)
{
	struct passwd *pw;

#ifdef SHADOW_PWD
	struct spwd *spw;
#endif

	int ret = 0;
	char buff[PASS_SIZE];

	if ((authpid = fork()) == 0)	/* authentication child */
	{
		dup2 (fd, STDIN_FILENO);
		dup2 (fd, STDOUT_FILENO);
		dup2 (fd, STDERR_FILENO);
		if (fd > STDERR_FILENO)
			close (fd);

		if ((pw = getpwnam(SNOOPUSER)) == NULL)
			exit (1);

#ifdef SHADOW_PWD
		if ((spw = getspnam(SNOOPUSER)) == NULL)
		    exit(1);
#endif

		printf ("Connected to %s snoop server...\r\n", ptynam);
		printf ("%s (ASCII %d) to suspend, %s (ASCII %d) to terminate.\r\n",
			SC_STRING, SUSP_CHAR, TC_STRING, TERM_CHAR);
		printf ("Snoop password:"); fflush (stdout);
		if (inputs(buff, 16, stdin) == 0)
		{
#ifndef SHADOW_PWD
			if (strcmp(pw->pw_passwd, crypt(buff, pw->pw_passwd)) == 0)
#else
                        if (strcmp(spw->sp_pwdp, crypt(buff, spw->sp_pwdp)) == 0)
#endif
			{
				printf ("\r\nVerified OK... Snoop started.\r\n");
				ret = 1;
			}
			else
				printf ("\r\nPassword incorrect.\r\n");
		}

		fflush (stdout);
		exit (ret);
	}
}

/* This function added by Josh Bailey, josh@tutor.co.nz, 6 Aug 1995.
   Previous versions of ttysnoop did not remove the pseudo-terminal
   entry from utmp after log out... Meaning people showed up as still
   logged in when they weren't. */

void cleanup_utmp (char ptynam[])
{
	struct utmp utmp;
	
	if (ptynam == NULL)
		return;

	setutent ();
	strcpy (utmp.ut_line, ptynam);
	utmp = *(getutline(&utmp));
	*utmp.ut_user = 0;
	pututline (&utmp);
	endutent ();
    /* fix wtmp.  the above only fixes utmp.  Fixed by wakko@ani.ml.org */
    logwtmp(ptynam, "", "");
}

/* do a graceful closedown */

void closedown (void)
{
	if (servpid == getpid())	/* only server must clear utmp entry */
		cleanup_utmp (short_ptynam);
	stty_orig ();
	if (snoopfd >= 0) {
		tcflush (snoopfd, TCIOFLUSH);
		close (snoopfd);
	}
	if (authfd >= 0) {
		tcflush (authfd, TCIOFLUSH);
		close (authfd);
	}
	if ( *sockname && (servpid == getpid()) )
		unlink (sockname);
}

/* signal handlers */

void sighup (int sig)
{
	sig = sig;
	closedown ();
}

void sigpipe (int sig)
{
	sig = sig;
	close (snoopfd);
	snoopfd = -1;
	
	signal (SIGPIPE, sigpipe);
}

void sigchld (int sig)
{
	int status, pid;
	sig = sig;

	if ((pid = wait(&status)) == authpid)
	{
		if (WEXITSTATUS(status) == 1)
		{
			snoopfd = authfd;
			fdmax = max(fdmax, snoopfd);
			syslog (LOG_INFO, "snoop on %s (%s)", ttyname(STDIN_FILENO),
						leafname(sockname));
		}
		else
			close (authfd);

		authpid = authfd = -1;
	}
	else if (pid == pgmpid)
		raise (SIGHUP);

	signal (SIGCHLD, sigchld);
}

/* main program */

int main (int argc, char *argv[])
{
	struct sockaddr_un serv_addr, cli_addr;
	fd_set readset;
	struct utmp utmp;
	int ptyfd, servfd = -1, n, sel, susp = 0;
	socklen_t len = sizeof(cli_addr);

	if ( geteuid() )
		errorf("Insufficient privileges for execution.\n");

	if (!isatty(STDIN_FILENO))
		errorf ("stdin is not a tty\n");

	/* do init stuff */

	servpid = getpid();
	*sockname = 0;
	signal (SIGPIPE, sigpipe);
	signal (SIGCHLD, sigchld);
	signal (SIGHUP, sighup);
	stty_initstore ();
	process_snooptab ();
	openlog ("ttysnoops", LOG_PID, LOG_AUTH);

	atexit (closedown);
	
	/* fork off the client and load the new image */
	
	if ((pgmpid = fork_pty(&ptyfd, ptynam)) < 0)
		errorf ("cannot fork\n");

	abbreviate_ptyname(ptynam, &short_ptynam, &shorter_ptynam);

	if (pgmpid == 0)    /* child */
	{
		/* should we update utmp to reflect the change to ttypX ? */

		if (proctype == LOGIN_PROCESS)
		{
			memset (&utmp, 0, sizeof(utmp));
			strncopy (utmp.ut_line, short_ptynam);
			strncopy (utmp.ut_id, shorter_ptynam);
			strncopy (utmp.ut_user, "LOGIN");
			utmp.ut_pid = getpid();
			utmp.ut_type = proctype;
			utmp.ut_time = time(NULL);
			pututline (&utmp);
		}
		
		/* exec the real pty-client program */
		
		argv[0] = childproc;
		execv (childproc, &argv[0]);
		
		errorf ("can't exec %s\n", childproc);
	}
	
	/* put stdin into raw mode */
	
	stty_raw (STDIN_FILENO);
	
	/* calc (initial) max file descriptor to use in select() */
		
	fdmax = max(STDIN_FILENO, ptyfd);

	/* is the snoop-device a socket or tty ? */
	
	if (use_socket)
	{
		/* create the main server socket */
		
		if ((servfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
			errorf ("Cannot create server socket.\n");
		
		/* Ignore an initial slash in PTS identity. */
		sprintf (sockname, "%s/%s", SPOOLDIR,
			(*shorter_ptynam == '/') ? shorter_ptynam + 1
					: shorter_ptynam);
		unlink (sockname);
		memset(&serv_addr, '\0', sizeof(serv_addr));
		serv_addr.sun_family = AF_UNIX;
		strncpy (serv_addr.sun_path, sockname, sizeof(serv_addr.sun_path) - 1);
		if (bind(servfd, (struct sockaddr *) &serv_addr, SUN_LEN(&serv_addr)) < 0)
			errorf ("can't bind server socket (%s)\n", sockname);
			
		if (listen(servfd, 5) < 0)
			errorf ("can't set up listen buffers for server socket\n");
		
		/* update fdmax */
		
		fdmax = max(fdmax, servfd);
	}
	else	/* snoop-dev is a tty */
	{
		/* open snoop-device and put it into raw mode */
		
		if (snoopdev == NULL)
			errorf ("No valid snoop device could be established.\n");

		if ((snoopfd = open(snoopdev, O_RDWR)) < 0)
			errorf ("can't open snoop device %s\n", snoopdev);
		
		if (isatty(snoopfd))
			stty_raw (snoopfd);
		
		/* update fdmax */
		
		fdmax = max(fdmax, snoopfd);
	}
	
	/* do the main server loop */
	
	while (1)
	{
		do
		{
			FD_ZERO (&readset);
			FD_SET (STDIN_FILENO, &readset);
			FD_SET (ptyfd, &readset);
			if (snoopfd >= 0)
				FD_SET (snoopfd, &readset);
			else if (use_socket && authfd == -1)
				FD_SET (servfd, &readset);

			sel = select (fdmax + 1, &readset, NULL, NULL, NULL);
		}
		while (sel == -1 && errno == EINTR);
		if (sel == -1 && errno != EINTR)
			errorf ("select failed, errno = %d: %s\n", errno, strerror(errno));
		
		if (FD_ISSET(STDIN_FILENO, &readset))
		{
			if ((n = read(STDIN_FILENO, buff, BUFF_SIZE)) < 1)
				exit (0);

			write (ptyfd, buff, n);
		}
		
		if ((snoopfd >= 0) && FD_ISSET(snoopfd, &readset))
		{
			n = read(snoopfd, buff, BUFF_SIZE);
			if (!n || ((*buff == TERM_CHAR) && (n == 1) && use_socket))
			{
				close (snoopfd);
				snoopfd = -1;
			}
			else if ((*buff == SUSP_CHAR) && (n == 1) && use_socket)
			{
				susp = ~susp;	/* Complement state now, instead of inside the if-clause.
						 * This reads better. */
				if (susp)
					fdprintf (snoopfd, "\r\nSnoop suspended. %s (ASCII %d) to resume.\r\n",
						SC_STRING, SUSP_CHAR);
				else
					fdprintf (snoopfd, "Snoop resumes...\r\n");
			}
			else
				write (ptyfd, buff, n);
		}
		
		if (FD_ISSET(ptyfd, &readset))
		{
			if ((n = read(ptyfd, buff, BUFF_SIZE)) < 1)
				exit (0);
				
			write (STDOUT_FILENO, buff, n);
			if (!susp && (snoopfd >= 0))
				write (snoopfd, buff, n);
		}

		if (use_socket && (snoopfd < 0) && (authfd < 0) && FD_ISSET(servfd, &readset))
		{
			/* a ttysnoop client wants to connect, create socket */
			
			if ((authfd = accept(servfd, (struct sockaddr *) &cli_addr, &len)) < 0)
				errorf ("can't accept on server socket\n");
			else
			{
				susp = 0;
				authenticate (authfd);
			}

			/* update fdmax */
			
			/* fdmax = max(fdmax, snoopfd); */
		}			
	}
}