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