xref: /freebsd/crypto/openssh/loginrec.c (revision 8e28d84935f2f0ee081d44f9803f3052b960e50b)
1 /*
2  * Copyright (c) 2000 Andre Lucas.  All rights reserved.
3  * Portions copyright (c) 1998 Todd C. Miller
4  * Portions copyright (c) 1996 Jason Downs
5  * Portions copyright (c) 1996 Theo de Raadt
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /**
29  ** loginrec.c:  platform-independent login recording and lastlog retrieval
30  **/
31 
32 /*
33  *  The new login code explained
34  *  ============================
35  *
36  *  This code attempts to provide a common interface to login recording
37  *  (utmp and friends) and last login time retrieval.
38  *
39  *  Its primary means of achieving this is to use 'struct logininfo', a
40  *  union of all the useful fields in the various different types of
41  *  system login record structures one finds on UNIX variants.
42  *
43  *  We depend on autoconf to define which recording methods are to be
44  *  used, and which fields are contained in the relevant data structures
45  *  on the local system. Many C preprocessor symbols affect which code
46  *  gets compiled here.
47  *
48  *  The code is designed to make it easy to modify a particular
49  *  recording method, without affecting other methods nor requiring so
50  *  many nested conditional compilation blocks as were commonplace in
51  *  the old code.
52  *
53  *  For login recording, we try to use the local system's libraries as
54  *  these are clearly most likely to work correctly. For utmp systems
55  *  this usually means login() and logout() or setutent() etc., probably
56  *  in libutil, along with logwtmp() etc. On these systems, we fall back
57  *  to writing the files directly if we have to, though this method
58  *  requires very thorough testing so we do not corrupt local auditing
59  *  information. These files and their access methods are very system
60  *  specific indeed.
61  *
62  *  For utmpx systems, the corresponding library functions are
63  *  setutxent() etc. To the author's knowledge, all utmpx systems have
64  *  these library functions and so no direct write is attempted. If such
65  *  a system exists and needs support, direct analogues of the [uw]tmp
66  *  code should suffice.
67  *
68  *  Retrieving the time of last login ('lastlog') is in some ways even
69  *  more problemmatic than login recording. Some systems provide a
70  *  simple table of all users which we seek based on uid and retrieve a
71  *  relatively standard structure. Others record the same information in
72  *  a directory with a separate file, and others don't record the
73  *  information separately at all. For systems in the latter category,
74  *  we look backwards in the wtmp or wtmpx file for the last login entry
75  *  for our user. Naturally this is slower and on busy systems could
76  *  incur a significant performance penalty.
77  *
78  *  Calling the new code
79  *  --------------------
80  *
81  *  In OpenSSH all login recording and retrieval is performed in
82  *  login.c. Here you'll find working examples. Also, in the logintest.c
83  *  program there are more examples.
84  *
85  *  Internal handler calling method
86  *  -------------------------------
87  *
88  *  When a call is made to login_login() or login_logout(), both
89  *  routines set a struct logininfo flag defining which action (log in,
90  *  or log out) is to be taken. They both then call login_write(), which
91  *  calls whichever of the many structure-specific handlers autoconf
92  *  selects for the local system.
93  *
94  *  The handlers themselves handle system data structure specifics. Both
95  *  struct utmp and struct utmpx have utility functions (see
96  *  construct_utmp*()) to try to make it simpler to add extra systems
97  *  that introduce new features to either structure.
98  *
99  *  While it may seem terribly wasteful to replicate so much similar
100  *  code for each method, experience has shown that maintaining code to
101  *  write both struct utmp and utmpx in one function, whilst maintaining
102  *  support for all systems whether they have library support or not, is
103  *  a difficult and time-consuming task.
104  *
105  *  Lastlog support proceeds similarly. Functions login_get_lastlog()
106  *  (and its OpenSSH-tuned friend login_get_lastlog_time()) call
107  *  getlast_entry(), which tries one of three methods to find the last
108  *  login time. It uses local system lastlog support if it can,
109  *  otherwise it tries wtmp or wtmpx before giving up and returning 0,
110  *  meaning "tilt".
111  *
112  *  Maintenance
113  *  -----------
114  *
115  *  In many cases it's possible to tweak autoconf to select the correct
116  *  methods for a particular platform, either by improving the detection
117  *  code (best), or by presetting DISABLE_<method> or CONF_<method>_FILE
118  *  symbols for the platform.
119  *
120  *  Use logintest to check which symbols are defined before modifying
121  *  configure.ac and loginrec.c. (You have to build logintest yourself
122  *  with 'make logintest' as it's not built by default.)
123  *
124  *  Otherwise, patches to the specific method(s) are very helpful!
125  */
126 
127 #include "includes.h"
128 
129 #include <sys/types.h>
130 #include <sys/stat.h>
131 #include <sys/socket.h>
132 #ifdef HAVE_SYS_TIME_H
133 # include <sys/time.h>
134 #endif
135 
136 #include <netinet/in.h>
137 
138 #include <stdlib.h>
139 #include <errno.h>
140 #include <fcntl.h>
141 #ifdef HAVE_PATHS_H
142 # include <paths.h>
143 #endif
144 #include <pwd.h>
145 #include <stdarg.h>
146 #include <stdio.h>
147 #include <string.h>
148 #include <time.h>
149 #include <unistd.h>
150 
151 #include "xmalloc.h"
152 #include "sshkey.h"
153 #include "hostfile.h"
154 #include "ssh.h"
155 #include "loginrec.h"
156 #include "log.h"
157 #include "atomicio.h"
158 #include "packet.h"
159 #include "canohost.h"
160 #include "auth.h"
161 #include "sshbuf.h"
162 #include "ssherr.h"
163 #include "misc.h"
164 
165 #ifdef HAVE_UTIL_H
166 # include <util.h>
167 #endif
168 
169 #ifdef USE_WTMPDB
170 # include <wtmpdb.h>
171 #endif
172 
173 /**
174  ** prototypes for helper functions in this file
175  **/
176 
177 #if HAVE_UTMP_H
178 void set_utmp_time(struct logininfo *li, struct utmp *ut);
179 void construct_utmp(struct logininfo *li, struct utmp *ut);
180 #endif
181 
182 #ifdef HAVE_UTMPX_H
183 void set_utmpx_time(struct logininfo *li, struct utmpx *ut);
184 void construct_utmpx(struct logininfo *li, struct utmpx *ut);
185 #endif
186 
187 int utmp_write_entry(struct logininfo *li);
188 int utmpx_write_entry(struct logininfo *li);
189 int wtmp_write_entry(struct logininfo *li);
190 int wtmpx_write_entry(struct logininfo *li);
191 int lastlog_write_entry(struct logininfo *li);
192 int syslogin_write_entry(struct logininfo *li);
193 #ifdef USE_WTMPDB
194 int wtmpdb_write_entry(struct logininfo *li);
195 #endif
196 
197 int getlast_entry(struct logininfo *li);
198 int lastlog_get_entry(struct logininfo *li);
199 int utmpx_get_entry(struct logininfo *li);
200 int wtmp_get_entry(struct logininfo *li);
201 int wtmpx_get_entry(struct logininfo *li);
202 
203 extern struct sshbuf *loginmsg;
204 
205 /* pick the shortest string */
206 #define MIN_SIZEOF(s1,s2) (sizeof(s1) < sizeof(s2) ? sizeof(s1) : sizeof(s2))
207 
208 /**
209  ** platform-independent login functions
210  **/
211 
212 /*
213  * login_login(struct logininfo *) - Record a login
214  *
215  * Call with a pointer to a struct logininfo initialised with
216  * login_init_entry() or login_alloc_entry()
217  *
218  * Returns:
219  *  >0 if successful
220  *  0  on failure (will use OpenSSH's logging facilities for diagnostics)
221  */
222 int
login_login(struct logininfo * li)223 login_login(struct logininfo *li)
224 {
225 	li->type = LTYPE_LOGIN;
226 	return (login_write(li));
227 }
228 
229 
230 /*
231  * login_logout(struct logininfo *) - Record a logout
232  *
233  * Call as with login_login()
234  *
235  * Returns:
236  *  >0 if successful
237  *  0  on failure (will use OpenSSH's logging facilities for diagnostics)
238  */
239 int
login_logout(struct logininfo * li)240 login_logout(struct logininfo *li)
241 {
242 	li->type = LTYPE_LOGOUT;
243 	return (login_write(li));
244 }
245 
246 /*
247  * login_get_lastlog_time(int) - Retrieve the last login time
248  *
249  * Retrieve the last login time for the given uid. Will try to use the
250  * system lastlog facilities if they are available, but will fall back
251  * to looking in wtmp/wtmpx if necessary
252  *
253  * Returns:
254  *   0 on failure, or if user has never logged in
255  *   Time in seconds from the epoch if successful
256  *
257  * Useful preprocessor symbols:
258  *   DISABLE_LASTLOG: If set, *never* even try to retrieve lastlog
259  *                    info
260  *   USE_LASTLOG: If set, indicates the presence of system lastlog
261  *                facilities. If this and DISABLE_LASTLOG are not set,
262  *                try to retrieve lastlog information from wtmp/wtmpx.
263  */
264 unsigned int
login_get_lastlog_time(const uid_t uid)265 login_get_lastlog_time(const uid_t uid)
266 {
267 	struct logininfo li;
268 
269 	if (login_get_lastlog(&li, uid))
270 		return (li.tv_sec);
271 	else
272 		return (0);
273 }
274 
275 /*
276  * login_get_lastlog(struct logininfo *, int)   - Retrieve a lastlog entry
277  *
278  * Retrieve a logininfo structure populated (only partially) with
279  * information from the system lastlog data, or from wtmp/wtmpx if no
280  * system lastlog information exists.
281  *
282  * Note this routine must be given a pre-allocated logininfo.
283  *
284  * Returns:
285  *  >0: A pointer to your struct logininfo if successful
286  *  0  on failure (will use OpenSSH's logging facilities for diagnostics)
287  */
288 struct logininfo *
login_get_lastlog(struct logininfo * li,const uid_t uid)289 login_get_lastlog(struct logininfo *li, const uid_t uid)
290 {
291 	struct passwd *pw;
292 
293 	memset(li, '\0', sizeof(*li));
294 	li->uid = uid;
295 
296 	/*
297 	 * If we don't have a 'real' lastlog, we need the username to
298 	 * reliably search wtmp(x) for the last login (see
299 	 * wtmp_get_entry().)
300 	 */
301 	pw = getpwuid(uid);
302 	if (pw == NULL)
303 		fatal("%s: Cannot find account for uid %ld", __func__,
304 		    (long)uid);
305 
306 	if (strlcpy(li->username, pw->pw_name, sizeof(li->username)) >=
307 	    sizeof(li->username)) {
308 		error("%s: username too long (%lu > max %lu)", __func__,
309 		    (unsigned long)strlen(pw->pw_name),
310 		    (unsigned long)sizeof(li->username) - 1);
311 		return NULL;
312 	}
313 
314 	if (getlast_entry(li))
315 		return (li);
316 	else
317 		return (NULL);
318 }
319 
320 /*
321  * login_alloc_entry(int, char*, char*, char*)    - Allocate and initialise
322  *                                                  a logininfo structure
323  *
324  * This function creates a new struct logininfo, a data structure
325  * meant to carry the information required to portably record login info.
326  *
327  * Returns a pointer to a newly created struct logininfo. If memory
328  * allocation fails, the program halts.
329  */
330 struct
login_alloc_entry(pid_t pid,const char * username,const char * hostname,const char * line)331 logininfo *login_alloc_entry(pid_t pid, const char *username,
332     const char *hostname, const char *line)
333 {
334 	struct logininfo *newli;
335 
336 	newli = xmalloc(sizeof(*newli));
337 	login_init_entry(newli, pid, username, hostname, line);
338 	return (newli);
339 }
340 
341 
342 /* login_free_entry(struct logininfo *)    - free struct memory */
343 void
login_free_entry(struct logininfo * li)344 login_free_entry(struct logininfo *li)
345 {
346 	free(li);
347 }
348 
349 
350 /* login_init_entry(struct logininfo *, int, char*, char*, char*)
351  *                                        - initialise a struct logininfo
352  *
353  * Populates a new struct logininfo, a data structure meant to carry
354  * the information required to portably record login info.
355  *
356  * Returns: 1
357  */
358 int
login_init_entry(struct logininfo * li,pid_t pid,const char * username,const char * hostname,const char * line)359 login_init_entry(struct logininfo *li, pid_t pid, const char *username,
360     const char *hostname, const char *line)
361 {
362 	struct passwd *pw;
363 
364 	memset(li, 0, sizeof(*li));
365 
366 	li->pid = pid;
367 
368 	/* set the line information */
369 	if (line)
370 		line_fullname(li->line, line, sizeof(li->line));
371 
372 	if (username) {
373 		strlcpy(li->username, username, sizeof(li->username));
374 		pw = getpwnam(li->username);
375 		if (pw == NULL) {
376 			fatal("%s: Cannot find user \"%s\"", __func__,
377 			    li->username);
378 		}
379 		li->uid = pw->pw_uid;
380 	}
381 
382 	if (hostname)
383 		strlcpy(li->hostname, hostname, sizeof(li->hostname));
384 
385 	return (1);
386 }
387 
388 /*
389  * login_set_current_time(struct logininfo *)    - set the current time
390  *
391  * Set the current time in a logininfo structure. This function is
392  * meant to eliminate the need to deal with system dependencies for
393  * time handling.
394  */
395 void
login_set_current_time(struct logininfo * li)396 login_set_current_time(struct logininfo *li)
397 {
398 	struct timeval tv;
399 
400 	gettimeofday(&tv, NULL);
401 
402 	li->tv_sec = tv.tv_sec;
403 	li->tv_usec = tv.tv_usec;
404 }
405 
406 /* copy a sockaddr_* into our logininfo */
407 void
login_set_addr(struct logininfo * li,const struct sockaddr * sa,const unsigned int sa_size)408 login_set_addr(struct logininfo *li, const struct sockaddr *sa,
409     const unsigned int sa_size)
410 {
411 	unsigned int bufsize = sa_size;
412 
413 	/* make sure we don't overrun our union */
414 	if (sizeof(li->hostaddr) < sa_size)
415 		bufsize = sizeof(li->hostaddr);
416 
417 	memcpy(&li->hostaddr.sa, sa, bufsize);
418 }
419 
420 
421 /**
422  ** login_write: Call low-level recording functions based on autoconf
423  ** results
424  **/
425 int
login_write(struct logininfo * li)426 login_write(struct logininfo *li)
427 {
428 #ifndef HAVE_CYGWIN
429 	if (geteuid() != 0) {
430 		logit("Attempt to write login records by non-root user (aborting)");
431 		return (1);
432 	}
433 #endif
434 
435 	/* set the timestamp */
436 	login_set_current_time(li);
437 #ifdef USE_LOGIN
438 	syslogin_write_entry(li);
439 #endif
440 #ifdef USE_LASTLOG
441 	if (li->type == LTYPE_LOGIN)
442 		lastlog_write_entry(li);
443 #endif
444 #ifdef USE_UTMP
445 	utmp_write_entry(li);
446 #endif
447 #ifdef USE_WTMP
448 	wtmp_write_entry(li);
449 #endif
450 #ifdef USE_UTMPX
451 	utmpx_write_entry(li);
452 #endif
453 #ifdef USE_WTMPX
454 	wtmpx_write_entry(li);
455 #endif
456 #ifdef USE_WTMPDB
457 	wtmpdb_write_entry(li);
458 #endif
459 #ifdef CUSTOM_SYS_AUTH_RECORD_LOGIN
460 	if (li->type == LTYPE_LOGIN &&
461 	    !sys_auth_record_login(li->username,li->hostname,li->line,
462 	    loginmsg))
463 		logit("Writing login record failed for %s", li->username);
464 #endif
465 #ifdef SSH_AUDIT_EVENTS
466 	if (li->type == LTYPE_LOGIN)
467 		audit_session_open(li);
468 	else if (li->type == LTYPE_LOGOUT)
469 		audit_session_close(li);
470 #endif
471 	return (0);
472 }
473 
474 #ifdef LOGIN_NEEDS_UTMPX
475 int
login_utmp_only(struct logininfo * li)476 login_utmp_only(struct logininfo *li)
477 {
478 	li->type = LTYPE_LOGIN;
479 	login_set_current_time(li);
480 # ifdef USE_UTMP
481 	utmp_write_entry(li);
482 # endif
483 # ifdef USE_WTMP
484 	wtmp_write_entry(li);
485 # endif
486 # ifdef USE_UTMPX
487 	utmpx_write_entry(li);
488 # endif
489 # ifdef USE_WTMPX
490 	wtmpx_write_entry(li);
491 # endif
492 	return (0);
493 }
494 #endif
495 
496 /**
497  ** getlast_entry: Call low-level functions to retrieve the last login
498  **                time.
499  **/
500 
501 /* take the uid in li and return the last login time */
502 int
getlast_entry(struct logininfo * li)503 getlast_entry(struct logininfo *li)
504 {
505 #ifdef USE_LASTLOG
506 	return(lastlog_get_entry(li));
507 #else /* !USE_LASTLOG */
508 #if defined(USE_UTMPX) && defined(HAVE_SETUTXDB) && \
509     defined(UTXDB_LASTLOGIN) && defined(HAVE_GETUTXUSER)
510 	return (utmpx_get_entry(li));
511 #endif
512 
513 #if defined(DISABLE_LASTLOG)
514 	/* On some systems we shouldn't even try to obtain last login
515 	 * time, e.g. AIX */
516 	return (0);
517 # elif defined(USE_WTMP) && \
518     (defined(HAVE_TIME_IN_UTMP) || defined(HAVE_TV_IN_UTMP))
519 	/* retrieve last login time from utmp */
520 	return (wtmp_get_entry(li));
521 # elif defined(USE_WTMPX) && \
522     (defined(HAVE_TIME_IN_UTMPX) || defined(HAVE_TV_IN_UTMPX))
523 	/* If wtmp isn't available, try wtmpx */
524 	return (wtmpx_get_entry(li));
525 # else
526 	/* Give up: No means of retrieving last login time */
527 	return (0);
528 # endif /* DISABLE_LASTLOG */
529 #endif /* USE_LASTLOG */
530 }
531 
532 
533 
534 /*
535  * 'line' string utility functions
536  *
537  * These functions process the 'line' string into one of three forms:
538  *
539  * 1. The full filename (including '/dev')
540  * 2. The stripped name (excluding '/dev')
541  * 3. The abbreviated name (e.g. /dev/ttyp00 -> yp00
542  *                               /dev/pts/1  -> ts/1 )
543  *
544  * Form 3 is used on some systems to identify a .tmp.? entry when
545  * attempting to remove it. Typically both addition and removal is
546  * performed by one application - say, sshd - so as long as the choice
547  * uniquely identifies a terminal it's ok.
548  */
549 
550 
551 /*
552  * line_fullname(): add the leading '/dev/' if it doesn't exist make
553  * sure dst has enough space, if not just copy src (ugh)
554  */
555 char *
line_fullname(char * dst,const char * src,u_int dstsize)556 line_fullname(char *dst, const char *src, u_int dstsize)
557 {
558 	memset(dst, '\0', dstsize);
559 	if ((strncmp(src, "/dev/", 5) == 0) || (dstsize < (strlen(src) + 5)))
560 		strlcpy(dst, src, dstsize);
561 	else {
562 		strlcpy(dst, "/dev/", dstsize);
563 		strlcat(dst, src, dstsize);
564 	}
565 	return (dst);
566 }
567 
568 /* line_stripname(): strip the leading '/dev' if it exists, return dst */
569 char *
line_stripname(char * dst,const char * src,int dstsize)570 line_stripname(char *dst, const char *src, int dstsize)
571 {
572 	memset(dst, '\0', dstsize);
573 	if (strncmp(src, "/dev/", 5) == 0)
574 		strlcpy(dst, src + 5, dstsize);
575 	else
576 		strlcpy(dst, src, dstsize);
577 	return (dst);
578 }
579 
580 /*
581  * line_abbrevname(): Return the abbreviated (usually four-character)
582  * form of the line (Just use the last <dstsize> characters of the
583  * full name.)
584  *
585  * NOTE: use strncpy because we do NOT necessarily want zero
586  * termination
587  */
588 char *
line_abbrevname(char * dst,const char * src,int dstsize)589 line_abbrevname(char *dst, const char *src, int dstsize)
590 {
591 	size_t len;
592 
593 	memset(dst, '\0', dstsize);
594 
595 	if (strcmp(src, "ssh:notty") == 0)
596 		return dst;
597 
598 	/* Always skip prefix if present */
599 	if (strncmp(src, "/dev/", 5) == 0)
600 		src += 5;
601 
602 #ifdef WITH_ABBREV_NO_TTY
603 	if (strncmp(src, "tty", 3) == 0)
604 		src += 3;
605 #endif
606 
607 	len = strlen(src);
608 
609 	if (len > 0) {
610 		if (((int)len - dstsize) > 0)
611 			src +=  ((int)len - dstsize);
612 
613 		/* note: _don't_ change this to strlcpy */
614 		strncpy(dst, src, (size_t)dstsize);
615 	}
616 
617 	return (dst);
618 }
619 
620 /**
621  ** utmp utility functions
622  **
623  ** These functions manipulate struct utmp, taking system differences
624  ** into account.
625  **/
626 
627 #if defined(USE_BTMP) || defined(USE_UTMP) || defined (USE_WTMP) || defined (USE_LOGIN)
628 
629 /* build the utmp structure */
630 void
set_utmp_time(struct logininfo * li,struct utmp * ut)631 set_utmp_time(struct logininfo *li, struct utmp *ut)
632 {
633 # if defined(HAVE_TV_IN_UTMP)
634 	ut->ut_tv.tv_sec = li->tv_sec;
635 	ut->ut_tv.tv_usec = li->tv_usec;
636 # elif defined(HAVE_TIME_IN_UTMP)
637 	ut->ut_time = li->tv_sec;
638 # endif
639 }
640 
641 void
construct_utmp(struct logininfo * li,struct utmp * ut)642 construct_utmp(struct logininfo *li,
643 		    struct utmp *ut)
644 {
645 # ifdef HAVE_ADDR_V6_IN_UTMP
646 	struct sockaddr_in6 *sa6;
647 # endif
648 
649 	memset(ut, '\0', sizeof(*ut));
650 
651 	/* First fill out fields used for both logins and logouts */
652 
653 # ifdef HAVE_ID_IN_UTMP
654 	line_abbrevname(ut->ut_id, li->line, sizeof(ut->ut_id));
655 # endif
656 
657 # ifdef HAVE_TYPE_IN_UTMP
658 	/* This is done here to keep utmp constants out of struct logininfo */
659 	switch (li->type) {
660 	case LTYPE_LOGIN:
661 		ut->ut_type = USER_PROCESS;
662 		break;
663 	case LTYPE_LOGOUT:
664 		ut->ut_type = DEAD_PROCESS;
665 		break;
666 	}
667 # endif
668 	set_utmp_time(li, ut);
669 
670 	line_stripname(ut->ut_line, li->line, sizeof(ut->ut_line));
671 
672 # ifdef HAVE_PID_IN_UTMP
673 	ut->ut_pid = li->pid;
674 # endif
675 
676 	/* If we're logging out, leave all other fields blank */
677 	if (li->type == LTYPE_LOGOUT)
678 		return;
679 
680 	/*
681 	 * These fields are only used when logging in, and are blank
682 	 * for logouts.
683 	 */
684 
685 	/* Use strncpy because we don't necessarily want null termination */
686 	strncpy(ut->ut_name, li->username,
687 	    MIN_SIZEOF(ut->ut_name, li->username));
688 # ifdef HAVE_HOST_IN_UTMP
689 	strncpy(ut->ut_host, li->hostname,
690 	    MIN_SIZEOF(ut->ut_host, li->hostname));
691 # endif
692 # ifdef HAVE_ADDR_IN_UTMP
693 	/* this is just a 32-bit IP address */
694 	if (li->hostaddr.sa.sa_family == AF_INET)
695 		ut->ut_addr = li->hostaddr.sa_in.sin_addr.s_addr;
696 # endif
697 # ifdef HAVE_ADDR_V6_IN_UTMP
698 	/* this is just a 128-bit IPv6 address */
699 	if (li->hostaddr.sa.sa_family == AF_INET6) {
700 		sa6 = ((struct sockaddr_in6 *)&li->hostaddr.sa);
701 		memcpy(ut->ut_addr_v6, sa6->sin6_addr.s6_addr, 16);
702 		if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
703 			ut->ut_addr_v6[0] = ut->ut_addr_v6[3];
704 			ut->ut_addr_v6[1] = 0;
705 			ut->ut_addr_v6[2] = 0;
706 			ut->ut_addr_v6[3] = 0;
707 		}
708 	}
709 # endif
710 }
711 #endif /* USE_BTMP || USE_UTMP || USE_WTMP || USE_LOGIN */
712 
713 /**
714  ** utmpx utility functions
715  **
716  ** These functions manipulate struct utmpx, accounting for system
717  ** variations.
718  **/
719 
720 #if defined(USE_UTMPX) || defined (USE_WTMPX)
721 /* build the utmpx structure */
722 void
set_utmpx_time(struct logininfo * li,struct utmpx * utx)723 set_utmpx_time(struct logininfo *li, struct utmpx *utx)
724 {
725 # if defined(HAVE_TV_IN_UTMPX)
726 	utx->ut_tv.tv_sec = li->tv_sec;
727 	utx->ut_tv.tv_usec = li->tv_usec;
728 # elif defined(HAVE_TIME_IN_UTMPX)
729 	utx->ut_time = li->tv_sec;
730 # endif
731 }
732 
733 void
construct_utmpx(struct logininfo * li,struct utmpx * utx)734 construct_utmpx(struct logininfo *li, struct utmpx *utx)
735 {
736 # ifdef HAVE_ADDR_V6_IN_UTMPX
737 	struct sockaddr_in6 *sa6;
738 #  endif
739 	memset(utx, '\0', sizeof(*utx));
740 
741 # ifdef HAVE_ID_IN_UTMPX
742 	line_abbrevname(utx->ut_id, li->line, sizeof(utx->ut_id));
743 # endif
744 
745 	/* this is done here to keep utmp constants out of loginrec.h */
746 	switch (li->type) {
747 	case LTYPE_LOGIN:
748 		utx->ut_type = USER_PROCESS;
749 		break;
750 	case LTYPE_LOGOUT:
751 		utx->ut_type = DEAD_PROCESS;
752 		break;
753 	}
754 	line_stripname(utx->ut_line, li->line, sizeof(utx->ut_line));
755 	set_utmpx_time(li, utx);
756 	utx->ut_pid = li->pid;
757 
758 	/* strncpy(): Don't necessarily want null termination */
759 	strncpy(utx->ut_user, li->username,
760 	    MIN_SIZEOF(utx->ut_user, li->username));
761 
762 	if (li->type == LTYPE_LOGOUT)
763 		return;
764 
765 	/*
766 	 * These fields are only used when logging in, and are blank
767 	 * for logouts.
768 	 */
769 
770 # ifdef HAVE_HOST_IN_UTMPX
771 	strncpy(utx->ut_host, li->hostname,
772 	    MIN_SIZEOF(utx->ut_host, li->hostname));
773 # endif
774 # ifdef HAVE_SS_IN_UTMPX
775 	utx->ut_ss = li->hostaddr.sa_storage;
776 # endif
777 # ifdef HAVE_ADDR_IN_UTMPX
778 	/* this is just a 32-bit IP address */
779 	if (li->hostaddr.sa.sa_family == AF_INET)
780 		utx->ut_addr = li->hostaddr.sa_in.sin_addr.s_addr;
781 # endif
782 # ifdef HAVE_ADDR_V6_IN_UTMPX
783 	/* this is just a 128-bit IPv6 address */
784 	if (li->hostaddr.sa.sa_family == AF_INET6) {
785 		sa6 = ((struct sockaddr_in6 *)&li->hostaddr.sa);
786 		memcpy(utx->ut_addr_v6, sa6->sin6_addr.s6_addr, 16);
787 		if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
788 			utx->ut_addr_v6[0] = utx->ut_addr_v6[3];
789 			utx->ut_addr_v6[1] = 0;
790 			utx->ut_addr_v6[2] = 0;
791 			utx->ut_addr_v6[3] = 0;
792 		}
793 	}
794 # endif
795 # ifdef HAVE_SYSLEN_IN_UTMPX
796 	/* ut_syslen is the length of the utx_host string */
797 	utx->ut_syslen = MINIMUM(strlen(li->hostname), sizeof(utx->ut_host));
798 # endif
799 }
800 #endif /* USE_UTMPX || USE_WTMPX */
801 
802 /**
803  ** Low-level utmp functions
804  **/
805 
806 /* FIXME: (ATL) utmp_write_direct needs testing */
807 #ifdef USE_UTMP
808 
809 /* if we can, use pututline() etc. */
810 # if !defined(DISABLE_PUTUTLINE) && defined(HAVE_SETUTENT) && \
811 	defined(HAVE_PUTUTLINE)
812 #  define UTMP_USE_LIBRARY
813 # endif
814 
815 
816 /* write a utmp entry with the system's help (pututline() and pals) */
817 # ifdef UTMP_USE_LIBRARY
818 static int
utmp_write_library(struct logininfo * li,struct utmp * ut)819 utmp_write_library(struct logininfo *li, struct utmp *ut)
820 {
821 	setutent();
822 	pututline(ut);
823 #  ifdef HAVE_ENDUTENT
824 	endutent();
825 #  endif
826 	return (1);
827 }
828 # else /* UTMP_USE_LIBRARY */
829 
830 /*
831  * Write a utmp entry direct to the file
832  * This is a slightly modification of code in OpenBSD's login.c
833  */
834 static int
utmp_write_direct(struct logininfo * li,struct utmp * ut)835 utmp_write_direct(struct logininfo *li, struct utmp *ut)
836 {
837 	struct utmp old_ut;
838 	register int fd;
839 	int tty;
840 
841 	/* FIXME: (ATL) ttyslot() needs local implementation */
842 
843 #if defined(HAVE_GETTTYENT)
844 	struct ttyent *ty;
845 
846 	tty=0;
847 	setttyent();
848 	while (NULL != (ty = getttyent())) {
849 		tty++;
850 		if (!strncmp(ty->ty_name, ut->ut_line, sizeof(ut->ut_line)))
851 			break;
852 	}
853 	endttyent();
854 
855 	if (NULL == ty) {
856 		logit("%s: tty not found", __func__);
857 		return (0);
858 	}
859 #else /* FIXME */
860 
861 	tty = ttyslot(); /* seems only to work for /dev/ttyp? style names */
862 
863 #endif /* HAVE_GETTTYENT */
864 
865 	if (tty > 0 && (fd = open(UTMP_FILE, O_RDWR|O_CREAT, 0644)) >= 0) {
866 		off_t pos, ret;
867 
868 		pos = (off_t)tty * sizeof(struct utmp);
869 		if ((ret = lseek(fd, pos, SEEK_SET)) == -1) {
870 			logit("%s: lseek: %s", __func__, strerror(errno));
871 			close(fd);
872 			return (0);
873 		}
874 		if (ret != pos) {
875 			logit("%s: Couldn't seek to tty %d slot in %s",
876 			    __func__, tty, UTMP_FILE);
877 			close(fd);
878 			return (0);
879 		}
880 		/*
881 		 * Prevent luser from zero'ing out ut_host.
882 		 * If the new ut_line is empty but the old one is not
883 		 * and ut_line and ut_name match, preserve the old ut_line.
884 		 */
885 		if (atomicio(read, fd, &old_ut, sizeof(old_ut)) == sizeof(old_ut) &&
886 		    (ut->ut_host[0] == '\0') && (old_ut.ut_host[0] != '\0') &&
887 		    (strncmp(old_ut.ut_line, ut->ut_line, sizeof(ut->ut_line)) == 0) &&
888 		    (strncmp(old_ut.ut_name, ut->ut_name, sizeof(ut->ut_name)) == 0))
889 			memcpy(ut->ut_host, old_ut.ut_host, sizeof(ut->ut_host));
890 
891 		if ((ret = lseek(fd, pos, SEEK_SET)) == -1) {
892 			logit("%s: lseek: %s", __func__, strerror(errno));
893 			close(fd);
894 			return (0);
895 		}
896 		if (ret != pos) {
897 			logit("%s: Couldn't seek to tty %d slot in %s",
898 			    __func__, tty, UTMP_FILE);
899 			close(fd);
900 			return (0);
901 		}
902 		if (atomicio(vwrite, fd, ut, sizeof(*ut)) != sizeof(*ut)) {
903 			logit("%s: error writing %s: %s", __func__,
904 			    UTMP_FILE, strerror(errno));
905 			close(fd);
906 			return (0);
907 		}
908 
909 		close(fd);
910 		return (1);
911 	} else {
912 		return (0);
913 	}
914 }
915 # endif /* UTMP_USE_LIBRARY */
916 
917 static int
utmp_perform_login(struct logininfo * li)918 utmp_perform_login(struct logininfo *li)
919 {
920 	struct utmp ut;
921 
922 	construct_utmp(li, &ut);
923 # ifdef UTMP_USE_LIBRARY
924 	if (!utmp_write_library(li, &ut)) {
925 		logit("%s: utmp_write_library() failed", __func__);
926 		return (0);
927 	}
928 # else
929 	if (!utmp_write_direct(li, &ut)) {
930 		logit("%s: utmp_write_direct() failed", __func__);
931 		return (0);
932 	}
933 # endif
934 	return (1);
935 }
936 
937 
938 static int
utmp_perform_logout(struct logininfo * li)939 utmp_perform_logout(struct logininfo *li)
940 {
941 	struct utmp ut;
942 
943 	construct_utmp(li, &ut);
944 # ifdef UTMP_USE_LIBRARY
945 	if (!utmp_write_library(li, &ut)) {
946 		logit("%s: utmp_write_library() failed", __func__);
947 		return (0);
948 	}
949 # else
950 	if (!utmp_write_direct(li, &ut)) {
951 		logit("%s: utmp_write_direct() failed", __func__);
952 		return (0);
953 	}
954 # endif
955 	return (1);
956 }
957 
958 
959 int
utmp_write_entry(struct logininfo * li)960 utmp_write_entry(struct logininfo *li)
961 {
962 	switch(li->type) {
963 	case LTYPE_LOGIN:
964 		return (utmp_perform_login(li));
965 
966 	case LTYPE_LOGOUT:
967 		return (utmp_perform_logout(li));
968 
969 	default:
970 		logit("%s: invalid type field", __func__);
971 		return (0);
972 	}
973 }
974 #endif /* USE_UTMP */
975 
976 
977 /**
978  ** Low-level utmpx functions
979  **/
980 
981 /* not much point if we don't want utmpx entries */
982 #ifdef USE_UTMPX
983 
984 /* if we have the wherewithall, use pututxline etc. */
985 # if !defined(DISABLE_PUTUTXLINE) && defined(HAVE_SETUTXENT) && \
986 	defined(HAVE_PUTUTXLINE)
987 #  define UTMPX_USE_LIBRARY
988 # endif
989 
990 
991 /* write a utmpx entry with the system's help (pututxline() and pals) */
992 # ifdef UTMPX_USE_LIBRARY
993 static int
utmpx_write_library(struct logininfo * li,struct utmpx * utx)994 utmpx_write_library(struct logininfo *li, struct utmpx *utx)
995 {
996 	setutxent();
997 	pututxline(utx);
998 
999 #  ifdef HAVE_ENDUTXENT
1000 	endutxent();
1001 #  endif
1002 	return (1);
1003 }
1004 
1005 # else /* UTMPX_USE_LIBRARY */
1006 
1007 /* write a utmp entry direct to the file */
1008 static int
utmpx_write_direct(struct logininfo * li,struct utmpx * utx)1009 utmpx_write_direct(struct logininfo *li, struct utmpx *utx)
1010 {
1011 	logit("%s: not implemented!", __func__);
1012 	return (0);
1013 }
1014 # endif /* UTMPX_USE_LIBRARY */
1015 
1016 static int
utmpx_perform_login(struct logininfo * li)1017 utmpx_perform_login(struct logininfo *li)
1018 {
1019 	struct utmpx utx;
1020 
1021 	construct_utmpx(li, &utx);
1022 # ifdef UTMPX_USE_LIBRARY
1023 	if (!utmpx_write_library(li, &utx)) {
1024 		logit("%s: utmp_write_library() failed", __func__);
1025 		return (0);
1026 	}
1027 # else
1028 	if (!utmpx_write_direct(li, &utx)) {
1029 		logit("%s: utmp_write_direct() failed", __func__);
1030 		return (0);
1031 	}
1032 # endif
1033 	return (1);
1034 }
1035 
1036 
1037 static int
utmpx_perform_logout(struct logininfo * li)1038 utmpx_perform_logout(struct logininfo *li)
1039 {
1040 	struct utmpx utx;
1041 
1042 	construct_utmpx(li, &utx);
1043 # ifdef HAVE_ID_IN_UTMPX
1044 	line_abbrevname(utx.ut_id, li->line, sizeof(utx.ut_id));
1045 # endif
1046 # ifdef HAVE_TYPE_IN_UTMPX
1047 	utx.ut_type = DEAD_PROCESS;
1048 # endif
1049 
1050 # ifdef UTMPX_USE_LIBRARY
1051 	utmpx_write_library(li, &utx);
1052 # else
1053 	utmpx_write_direct(li, &utx);
1054 # endif
1055 	return (1);
1056 }
1057 
1058 int
utmpx_write_entry(struct logininfo * li)1059 utmpx_write_entry(struct logininfo *li)
1060 {
1061 	switch(li->type) {
1062 	case LTYPE_LOGIN:
1063 		return (utmpx_perform_login(li));
1064 	case LTYPE_LOGOUT:
1065 		return (utmpx_perform_logout(li));
1066 	default:
1067 		logit("%s: invalid type field", __func__);
1068 		return (0);
1069 	}
1070 }
1071 #endif /* USE_UTMPX */
1072 
1073 
1074 /**
1075  ** Low-level wtmp functions
1076  **/
1077 
1078 #ifdef USE_WTMP
1079 
1080 /*
1081  * Write a wtmp entry direct to the end of the file
1082  * This is a slight modification of code in OpenBSD's logwtmp.c
1083  */
1084 static int
wtmp_write(struct logininfo * li,struct utmp * ut)1085 wtmp_write(struct logininfo *li, struct utmp *ut)
1086 {
1087 	struct stat buf;
1088 	int fd, ret = 1;
1089 
1090 	if ((fd = open(WTMP_FILE, O_WRONLY|O_APPEND, 0)) < 0) {
1091 		logit("%s: problem writing %s: %s", __func__,
1092 		    WTMP_FILE, strerror(errno));
1093 		return (0);
1094 	}
1095 	if (fstat(fd, &buf) == 0)
1096 		if (atomicio(vwrite, fd, ut, sizeof(*ut)) != sizeof(*ut)) {
1097 			ftruncate(fd, buf.st_size);
1098 			logit("%s: problem writing %s: %s", __func__,
1099 			    WTMP_FILE, strerror(errno));
1100 			ret = 0;
1101 		}
1102 	close(fd);
1103 	return (ret);
1104 }
1105 
1106 static int
wtmp_perform_login(struct logininfo * li)1107 wtmp_perform_login(struct logininfo *li)
1108 {
1109 	struct utmp ut;
1110 
1111 	construct_utmp(li, &ut);
1112 	return (wtmp_write(li, &ut));
1113 }
1114 
1115 
1116 static int
wtmp_perform_logout(struct logininfo * li)1117 wtmp_perform_logout(struct logininfo *li)
1118 {
1119 	struct utmp ut;
1120 
1121 	construct_utmp(li, &ut);
1122 	return (wtmp_write(li, &ut));
1123 }
1124 
1125 
1126 int
wtmp_write_entry(struct logininfo * li)1127 wtmp_write_entry(struct logininfo *li)
1128 {
1129 	switch(li->type) {
1130 	case LTYPE_LOGIN:
1131 		return (wtmp_perform_login(li));
1132 	case LTYPE_LOGOUT:
1133 		return (wtmp_perform_logout(li));
1134 	default:
1135 		logit("%s: invalid type field", __func__);
1136 		return (0);
1137 	}
1138 }
1139 
1140 
1141 /*
1142  * Notes on fetching login data from wtmp/wtmpx
1143  *
1144  * Logouts are usually recorded with (amongst other things) a blank
1145  * username on a given tty line.  However, some systems (HP-UX is one)
1146  * leave all fields set, but change the ut_type field to DEAD_PROCESS.
1147  *
1148  * Since we're only looking for logins here, we know that the username
1149  * must be set correctly. On systems that leave it in, we check for
1150  * ut_type==USER_PROCESS (indicating a login.)
1151  *
1152  * Portability: Some systems may set something other than USER_PROCESS
1153  * to indicate a login process. I don't know of any as I write. Also,
1154  * it's possible that some systems may both leave the username in
1155  * place and not have ut_type.
1156  */
1157 
1158 /* return true if this wtmp entry indicates a login */
1159 static int
wtmp_islogin(struct logininfo * li,struct utmp * ut)1160 wtmp_islogin(struct logininfo *li, struct utmp *ut)
1161 {
1162 	if (strncmp(li->username, ut->ut_name,
1163 	    MIN_SIZEOF(li->username, ut->ut_name)) == 0) {
1164 # ifdef HAVE_TYPE_IN_UTMP
1165 		if (ut->ut_type & USER_PROCESS)
1166 			return (1);
1167 # else
1168 		return (1);
1169 # endif
1170 	}
1171 	return (0);
1172 }
1173 
1174 int
wtmp_get_entry(struct logininfo * li)1175 wtmp_get_entry(struct logininfo *li)
1176 {
1177 	struct stat st;
1178 	struct utmp ut;
1179 	int fd, found = 0;
1180 
1181 	/* Clear the time entries in our logininfo */
1182 	li->tv_sec = li->tv_usec = 0;
1183 
1184 	if ((fd = open(WTMP_FILE, O_RDONLY)) < 0) {
1185 		logit("%s: problem opening %s: %s", __func__,
1186 		    WTMP_FILE, strerror(errno));
1187 		return (0);
1188 	}
1189 	if (fstat(fd, &st) != 0) {
1190 		logit("%s: couldn't stat %s: %s", __func__,
1191 		    WTMP_FILE, strerror(errno));
1192 		close(fd);
1193 		return (0);
1194 	}
1195 
1196 	/* Seek to the start of the last struct utmp */
1197 	if (lseek(fd, -(off_t)sizeof(struct utmp), SEEK_END) == -1) {
1198 		/* Looks like we've got a fresh wtmp file */
1199 		close(fd);
1200 		return (0);
1201 	}
1202 
1203 	while (!found) {
1204 		if (atomicio(read, fd, &ut, sizeof(ut)) != sizeof(ut)) {
1205 			logit("%s: read of %s failed: %s", __func__,
1206 			    WTMP_FILE, strerror(errno));
1207 			close (fd);
1208 			return (0);
1209 		}
1210 		if (wtmp_islogin(li, &ut) ) {
1211 			found = 1;
1212 			/*
1213 			 * We've already checked for a time in struct
1214 			 * utmp, in login_getlast()
1215 			 */
1216 # ifdef HAVE_TIME_IN_UTMP
1217 			li->tv_sec = ut.ut_time;
1218 # else
1219 #  if HAVE_TV_IN_UTMP
1220 			li->tv_sec = ut.ut_tv.tv_sec;
1221 #  endif
1222 # endif
1223 			line_fullname(li->line, ut.ut_line,
1224 			    MIN_SIZEOF(li->line, ut.ut_line));
1225 # ifdef HAVE_HOST_IN_UTMP
1226 			strlcpy(li->hostname, ut.ut_host,
1227 			    MIN_SIZEOF(li->hostname, ut.ut_host));
1228 # endif
1229 			continue;
1230 		}
1231 		/* Seek back 2 x struct utmp */
1232 		if (lseek(fd, -(off_t)(2 * sizeof(struct utmp)), SEEK_CUR) == -1) {
1233 			/* We've found the start of the file, so quit */
1234 			close(fd);
1235 			return (0);
1236 		}
1237 	}
1238 
1239 	/* We found an entry. Tidy up and return */
1240 	close(fd);
1241 	return (1);
1242 }
1243 # endif /* USE_WTMP */
1244 
1245 
1246 /**
1247  ** Low-level wtmpx functions
1248  **/
1249 
1250 #ifdef USE_WTMPX
1251 /*
1252  * Write a wtmpx entry direct to the end of the file
1253  * This is a slight modification of code in OpenBSD's logwtmp.c
1254  */
1255 static int
wtmpx_write(struct logininfo * li,struct utmpx * utx)1256 wtmpx_write(struct logininfo *li, struct utmpx *utx)
1257 {
1258 #ifndef HAVE_UPDWTMPX
1259 	struct stat buf;
1260 	int fd, ret = 1;
1261 
1262 	if ((fd = open(WTMPX_FILE, O_WRONLY|O_APPEND, 0)) < 0) {
1263 		logit("%s: problem opening %s: %s", __func__,
1264 		    WTMPX_FILE, strerror(errno));
1265 		return (0);
1266 	}
1267 
1268 	if (fstat(fd, &buf) == 0)
1269 		if (atomicio(vwrite, fd, utx, sizeof(*utx)) != sizeof(*utx)) {
1270 			ftruncate(fd, buf.st_size);
1271 			logit("%s: problem writing %s: %s", __func__,
1272 			    WTMPX_FILE, strerror(errno));
1273 			ret = 0;
1274 		}
1275 	close(fd);
1276 
1277 	return (ret);
1278 #else
1279 	updwtmpx(WTMPX_FILE, utx);
1280 	return (1);
1281 #endif
1282 }
1283 
1284 
1285 static int
wtmpx_perform_login(struct logininfo * li)1286 wtmpx_perform_login(struct logininfo *li)
1287 {
1288 	struct utmpx utx;
1289 
1290 	construct_utmpx(li, &utx);
1291 	return (wtmpx_write(li, &utx));
1292 }
1293 
1294 
1295 static int
wtmpx_perform_logout(struct logininfo * li)1296 wtmpx_perform_logout(struct logininfo *li)
1297 {
1298 	struct utmpx utx;
1299 
1300 	construct_utmpx(li, &utx);
1301 	return (wtmpx_write(li, &utx));
1302 }
1303 
1304 
1305 int
wtmpx_write_entry(struct logininfo * li)1306 wtmpx_write_entry(struct logininfo *li)
1307 {
1308 	switch(li->type) {
1309 	case LTYPE_LOGIN:
1310 		return (wtmpx_perform_login(li));
1311 	case LTYPE_LOGOUT:
1312 		return (wtmpx_perform_logout(li));
1313 	default:
1314 		logit("%s: invalid type field", __func__);
1315 		return (0);
1316 	}
1317 }
1318 
1319 /* Please see the notes above wtmp_islogin() for information about the
1320    next two functions */
1321 
1322 /* Return true if this wtmpx entry indicates a login */
1323 static int
wtmpx_islogin(struct logininfo * li,struct utmpx * utx)1324 wtmpx_islogin(struct logininfo *li, struct utmpx *utx)
1325 {
1326 	if (strncmp(li->username, utx->ut_user,
1327 	    MIN_SIZEOF(li->username, utx->ut_user)) == 0 ) {
1328 # ifdef HAVE_TYPE_IN_UTMPX
1329 		if (utx->ut_type == USER_PROCESS)
1330 			return (1);
1331 # else
1332 		return (1);
1333 # endif
1334 	}
1335 	return (0);
1336 }
1337 
1338 
1339 int
wtmpx_get_entry(struct logininfo * li)1340 wtmpx_get_entry(struct logininfo *li)
1341 {
1342 	struct stat st;
1343 	struct utmpx utx;
1344 	int fd, found=0;
1345 
1346 	/* Clear the time entries */
1347 	li->tv_sec = li->tv_usec = 0;
1348 
1349 	if ((fd = open(WTMPX_FILE, O_RDONLY)) < 0) {
1350 		logit("%s: problem opening %s: %s", __func__,
1351 		    WTMPX_FILE, strerror(errno));
1352 		return (0);
1353 	}
1354 	if (fstat(fd, &st) != 0) {
1355 		logit("%s: couldn't stat %s: %s", __func__,
1356 		    WTMPX_FILE, strerror(errno));
1357 		close(fd);
1358 		return (0);
1359 	}
1360 
1361 	/* Seek to the start of the last struct utmpx */
1362 	if (lseek(fd, -(off_t)sizeof(struct utmpx), SEEK_END) == -1 ) {
1363 		/* probably a newly rotated wtmpx file */
1364 		close(fd);
1365 		return (0);
1366 	}
1367 
1368 	while (!found) {
1369 		if (atomicio(read, fd, &utx, sizeof(utx)) != sizeof(utx)) {
1370 			logit("%s: read of %s failed: %s", __func__,
1371 			    WTMPX_FILE, strerror(errno));
1372 			close (fd);
1373 			return (0);
1374 		}
1375 		/*
1376 		 * Logouts are recorded as a blank username on a particular
1377 		 * line. So, we just need to find the username in struct utmpx
1378 		 */
1379 		if (wtmpx_islogin(li, &utx)) {
1380 			found = 1;
1381 # if defined(HAVE_TV_IN_UTMPX)
1382 			li->tv_sec = utx.ut_tv.tv_sec;
1383 # elif defined(HAVE_TIME_IN_UTMPX)
1384 			li->tv_sec = utx.ut_time;
1385 # endif
1386 			line_fullname(li->line, utx.ut_line, sizeof(li->line));
1387 # if defined(HAVE_HOST_IN_UTMPX)
1388 			strlcpy(li->hostname, utx.ut_host,
1389 			    MIN_SIZEOF(li->hostname, utx.ut_host));
1390 # endif
1391 			continue;
1392 		}
1393 		if (lseek(fd, -(off_t)(2 * sizeof(struct utmpx)), SEEK_CUR) == -1) {
1394 			close(fd);
1395 			return (0);
1396 		}
1397 	}
1398 
1399 	close(fd);
1400 	return (1);
1401 }
1402 #endif /* USE_WTMPX */
1403 
1404 #ifdef USE_WTMPDB
1405 static int
wtmpdb_perform_login(struct logininfo * li)1406 wtmpdb_perform_login(struct logininfo *li)
1407 {
1408 	uint64_t login_time = li->tv_sec * ((uint64_t) 1000000ULL) +
1409 	    li->tv_usec;
1410 	const char *tty;
1411 
1412 	if (strncmp(li->line, "/dev/", 5) == 0)
1413 		tty = &(li->line[5]);
1414 	else
1415 		tty = li->line;
1416 
1417 	li->wtmpdb_id = wtmpdb_login(NULL, USER_PROCESS, li->username,
1418 	    login_time, tty, li->hostname, 0, 0);
1419 
1420 	if (li->wtmpdb_id < 0)
1421 		return (0);
1422 
1423 	return (1);
1424 }
1425 
1426 static int
wtmpdb_perform_logout(struct logininfo * li)1427 wtmpdb_perform_logout(struct logininfo *li)
1428 {
1429 	uint64_t logout_time = li->tv_sec * ((uint64_t) 1000000ULL) +
1430 	   li->tv_usec;
1431 
1432 	if (li->wtmpdb_id == 0) {
1433 		const char *tty;
1434 
1435 		if (strncmp(li->line, "/dev/", 5) == 0)
1436 			tty = &(li->line[5]);
1437 		else
1438 			tty = li->line;
1439 
1440 		li->wtmpdb_id = wtmpdb_get_id(NULL, tty, NULL);
1441 	}
1442 	wtmpdb_logout(NULL, li->wtmpdb_id, logout_time, NULL);
1443 
1444 	return (1);
1445 }
1446 
1447 int
wtmpdb_write_entry(struct logininfo * li)1448 wtmpdb_write_entry(struct logininfo *li)
1449 {
1450 	switch(li->type) {
1451 	case LTYPE_LOGIN:
1452 		return (wtmpdb_perform_login(li));
1453 	case LTYPE_LOGOUT:
1454 		return (wtmpdb_perform_logout(li));
1455 	default:
1456 		logit("%s: invalid type field", __func__);
1457 		return (0);
1458 	}
1459 }
1460 #endif
1461 
1462 /**
1463  ** Low-level libutil login() functions
1464  **/
1465 
1466 #ifdef USE_LOGIN
1467 static int
syslogin_perform_login(struct logininfo * li)1468 syslogin_perform_login(struct logininfo *li)
1469 {
1470 	struct utmp *ut;
1471 
1472 	ut = xmalloc(sizeof(*ut));
1473 	construct_utmp(li, ut);
1474 	login(ut);
1475 	free(ut);
1476 
1477 	return (1);
1478 }
1479 
1480 static int
syslogin_perform_logout(struct logininfo * li)1481 syslogin_perform_logout(struct logininfo *li)
1482 {
1483 # ifdef HAVE_LOGOUT
1484 	char line[UT_LINESIZE];
1485 
1486 	(void)line_stripname(line, li->line, sizeof(line));
1487 
1488 	if (!logout(line))
1489 		logit("%s: logout() returned an error", __func__);
1490 #  ifdef HAVE_LOGWTMP
1491 	else
1492 		logwtmp(line, "", "");
1493 #  endif
1494 	/* FIXME: (ATL - if the need arises) What to do if we have
1495 	 * login, but no logout?  what if logout but no logwtmp? All
1496 	 * routines are in libutil so they should all be there,
1497 	 * but... */
1498 # endif
1499 	return (1);
1500 }
1501 
1502 int
syslogin_write_entry(struct logininfo * li)1503 syslogin_write_entry(struct logininfo *li)
1504 {
1505 	switch (li->type) {
1506 	case LTYPE_LOGIN:
1507 		return (syslogin_perform_login(li));
1508 	case LTYPE_LOGOUT:
1509 		return (syslogin_perform_logout(li));
1510 	default:
1511 		logit("%s: Invalid type field", __func__);
1512 		return (0);
1513 	}
1514 }
1515 #endif /* USE_LOGIN */
1516 
1517 /* end of file log-syslogin.c */
1518 
1519 /**
1520  ** Low-level lastlog functions
1521  **/
1522 
1523 #ifdef USE_LASTLOG
1524 
1525 #if !defined(LASTLOG_WRITE_PUTUTXLINE) || !defined(HAVE_GETLASTLOGXBYNAME)
1526 /* open the file (using filemode) and seek to the login entry */
1527 static int
lastlog_openseek(struct logininfo * li,int * fd,int filemode)1528 lastlog_openseek(struct logininfo *li, int *fd, int filemode)
1529 {
1530 	off_t offset;
1531 	char lastlog_file[1024];
1532 	struct stat st;
1533 
1534 	if (stat(LASTLOG_FILE, &st) != 0) {
1535 		logit("%s: Couldn't stat %s: %s", __func__,
1536 		    LASTLOG_FILE, strerror(errno));
1537 		return (0);
1538 	}
1539 	if (S_ISDIR(st.st_mode)) {
1540 		snprintf(lastlog_file, sizeof(lastlog_file), "%s/%s",
1541 		    LASTLOG_FILE, li->username);
1542 	} else if (S_ISREG(st.st_mode)) {
1543 		strlcpy(lastlog_file, LASTLOG_FILE, sizeof(lastlog_file));
1544 	} else {
1545 		logit("%s: %.100s is not a file or directory!", __func__,
1546 		    LASTLOG_FILE);
1547 		return (0);
1548 	}
1549 
1550 	*fd = open(lastlog_file, filemode, 0600);
1551 	if (*fd < 0) {
1552 		debug("%s: Couldn't open %s: %s", __func__,
1553 		    lastlog_file, strerror(errno));
1554 		return (0);
1555 	}
1556 
1557 	if (S_ISREG(st.st_mode)) {
1558 		/* find this uid's offset in the lastlog file */
1559 		offset = (off_t) ((u_long)li->uid * sizeof(struct lastlog));
1560 
1561 		if (lseek(*fd, offset, SEEK_SET) != offset) {
1562 			logit("%s: %s->lseek(): %s", __func__,
1563 			    lastlog_file, strerror(errno));
1564 			close(*fd);
1565 			return (0);
1566 		}
1567 	}
1568 
1569 	return (1);
1570 }
1571 #endif /* !LASTLOG_WRITE_PUTUTXLINE || !HAVE_GETLASTLOGXBYNAME */
1572 
1573 #ifdef LASTLOG_WRITE_PUTUTXLINE
1574 int
lastlog_write_entry(struct logininfo * li)1575 lastlog_write_entry(struct logininfo *li)
1576 {
1577 	switch(li->type) {
1578 	case LTYPE_LOGIN:
1579 		return 1; /* lastlog written by pututxline */
1580 	default:
1581 		logit("lastlog_write_entry: Invalid type field");
1582 		return 0;
1583 	}
1584 }
1585 #else /* LASTLOG_WRITE_PUTUTXLINE */
1586 int
lastlog_write_entry(struct logininfo * li)1587 lastlog_write_entry(struct logininfo *li)
1588 {
1589 	struct lastlog last;
1590 	int fd;
1591 
1592 	switch(li->type) {
1593 	case LTYPE_LOGIN:
1594 		/* create our struct lastlog */
1595 		memset(&last, '\0', sizeof(last));
1596 		line_stripname(last.ll_line, li->line, sizeof(last.ll_line));
1597 		strlcpy(last.ll_host, li->hostname,
1598 		    MIN_SIZEOF(last.ll_host, li->hostname));
1599 		last.ll_time = li->tv_sec;
1600 
1601 		if (!lastlog_openseek(li, &fd, O_RDWR|O_CREAT))
1602 			return (0);
1603 
1604 		/* write the entry */
1605 		if (atomicio(vwrite, fd, &last, sizeof(last)) != sizeof(last)) {
1606 			close(fd);
1607 			logit("%s: Error writing to %s: %s", __func__,
1608 			    LASTLOG_FILE, strerror(errno));
1609 			return (0);
1610 		}
1611 
1612 		close(fd);
1613 		return (1);
1614 	default:
1615 		logit("%s: Invalid type field", __func__);
1616 		return (0);
1617 	}
1618 }
1619 #endif /* LASTLOG_WRITE_PUTUTXLINE */
1620 
1621 #ifdef HAVE_GETLASTLOGXBYNAME
1622 int
lastlog_get_entry(struct logininfo * li)1623 lastlog_get_entry(struct logininfo *li)
1624 {
1625 	struct lastlogx l, *ll;
1626 
1627 	if ((ll = getlastlogxbyname(li->username, &l)) == NULL) {
1628 		memset(&l, '\0', sizeof(l));
1629 		ll = &l;
1630 	}
1631 	line_fullname(li->line, ll->ll_line, sizeof(li->line));
1632 	strlcpy(li->hostname, ll->ll_host,
1633 		MIN_SIZEOF(li->hostname, ll->ll_host));
1634 	li->tv_sec = ll->ll_tv.tv_sec;
1635 	li->tv_usec = ll->ll_tv.tv_usec;
1636 	return (1);
1637 }
1638 #else /* HAVE_GETLASTLOGXBYNAME */
1639 int
lastlog_get_entry(struct logininfo * li)1640 lastlog_get_entry(struct logininfo *li)
1641 {
1642 	struct lastlog last;
1643 	int fd, ret;
1644 
1645 	if (!lastlog_openseek(li, &fd, O_RDONLY))
1646 		return (0);
1647 
1648 	ret = atomicio(read, fd, &last, sizeof(last));
1649 	close(fd);
1650 
1651 	switch (ret) {
1652 	case 0:
1653 		memset(&last, '\0', sizeof(last));
1654 		/* FALLTHRU */
1655 	case sizeof(last):
1656 		line_fullname(li->line, last.ll_line, sizeof(li->line));
1657 		strlcpy(li->hostname, last.ll_host,
1658 		    MIN_SIZEOF(li->hostname, last.ll_host));
1659 		li->tv_sec = last.ll_time;
1660 		return (1);
1661 	case -1:
1662 		error("%s: Error reading from %s: %s", __func__,
1663 		    LASTLOG_FILE, strerror(errno));
1664 		return (0);
1665 	default:
1666 		error("%s: Error reading from %s: Expecting %d, got %d",
1667 		    __func__, LASTLOG_FILE, (int)sizeof(last), ret);
1668 		return (0);
1669 	}
1670 
1671 	/* NOTREACHED */
1672 	return (0);
1673 }
1674 #endif /* HAVE_GETLASTLOGXBYNAME */
1675 #endif /* USE_LASTLOG */
1676 
1677 #if defined(USE_UTMPX) && defined(HAVE_SETUTXDB) && \
1678     defined(UTXDB_LASTLOGIN) && defined(HAVE_GETUTXUSER)
1679 int
utmpx_get_entry(struct logininfo * li)1680 utmpx_get_entry(struct logininfo *li)
1681 {
1682 	struct utmpx *utx;
1683 
1684 	if (setutxdb(UTXDB_LASTLOGIN, NULL) != 0)
1685 		return (0);
1686 	utx = getutxuser(li->username);
1687 	if (utx == NULL) {
1688 		endutxent();
1689 		return (0);
1690 	}
1691 
1692 	line_fullname(li->line, utx->ut_line,
1693 	    MIN_SIZEOF(li->line, utx->ut_line));
1694 	strlcpy(li->hostname, utx->ut_host,
1695 	    MIN_SIZEOF(li->hostname, utx->ut_host));
1696 	li->tv_sec = utx->ut_tv.tv_sec;
1697 	li->tv_usec = utx->ut_tv.tv_usec;
1698 	endutxent();
1699 	return (1);
1700 }
1701 #endif /* USE_UTMPX && HAVE_SETUTXDB && UTXDB_LASTLOGIN && HAVE_GETUTXUSER */
1702 
1703 #ifdef USE_BTMP
1704 /*
1705  * Logs failed login attempts in _PATH_BTMP if that exists.
1706  * The most common login failure is to give password instead of username.
1707  * So the _PATH_BTMP file checked for the correct permission, so that only
1708  * root can read it.
1709  */
1710 void
record_failed_login(struct ssh * ssh,const char * username,const char * hostname,const char * ttyn)1711 record_failed_login(struct ssh *ssh, const char *username, const char *hostname,
1712     const char *ttyn)
1713 {
1714 	int fd;
1715 	struct utmp ut;
1716 	struct logininfo li;
1717 	socklen_t fromlen = sizeof(li.hostaddr);
1718 	time_t t;
1719 	struct stat fst;
1720 
1721 	if (geteuid() != 0)
1722 		return;
1723 	if ((fd = open(_PATH_BTMP, O_WRONLY | O_APPEND)) < 0) {
1724 		debug("Unable to open the btmp file %s: %s", _PATH_BTMP,
1725 		    strerror(errno));
1726 		return;
1727 	}
1728 	if (fstat(fd, &fst) < 0) {
1729 		logit("%s: fstat of %s failed: %s", __func__, _PATH_BTMP,
1730 		    strerror(errno));
1731 		goto out;
1732 	}
1733 	if ((fst.st_mode & (S_IXGRP | S_IRWXO)) || fst.st_uid != 0) {
1734 		logit("Excess permission or bad ownership on file %s",
1735 		    _PATH_BTMP);
1736 		goto out;
1737 	}
1738 
1739 	/* Construct a logininfo and turn it into a utmp */
1740 	memset(&li, 0, sizeof(li));
1741 	li.type = LTYPE_LOGIN;
1742 	li.pid = getpid();
1743 	strlcpy(li.line, "ssh:notty", sizeof(li.line));
1744 	strlcpy(li.username, username, sizeof(li.username));
1745 	strlcpy(li.hostname, hostname, sizeof(li.hostname));
1746 	time(&t);
1747 	li.tv_sec = t > 0 ? (unsigned long)t : 0;
1748 	if (ssh_packet_connection_is_on_socket(ssh)) {
1749 		(void)getpeername(ssh_packet_get_connection_in(ssh),
1750 		    &li.hostaddr.sa, &fromlen);
1751 	}
1752 	construct_utmp(&li, &ut);
1753 
1754 	if (atomicio(vwrite, fd, &ut, sizeof(ut)) != sizeof(ut)) {
1755 		error("Failed to write to %s: %s", _PATH_BTMP,
1756 		    strerror(errno));
1757 	}
1758 out:
1759 	close(fd);
1760 }
1761 #endif	/* USE_BTMP */
1762