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