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