source: trunk/src/sh_unix.c@ 502

Last change on this file since 502 was 497, checked in by katerina, 9 years ago

Fix for ticket #394 (self-check incorrect message).

File size: 133.2 KB
Line 
1/* SAMHAIN file system integrity testing */
2/* Copyright (C) 1999 Rainer Wichmann */
3/* */
4/* This program is free software; you can redistribute it */
5/* and/or modify */
6/* it under the terms of the GNU General Public License as */
7/* published by */
8/* the Free Software Foundation; either version 2 of the License, or */
9/* (at your option) any later version. */
10/* */
11/* This program is distributed in the hope that it will be useful, */
12/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
13/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
14/* GNU General Public License for more details. */
15/* */
16/* You should have received a copy of the GNU General Public License */
17/* along with this program; if not, write to the Free Software */
18/* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20#include "config_xor.h"
21
22
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <ctype.h>
27#ifdef HAVE_LINUX_FS_H
28#include <linux/fs.h>
29#endif
30
31#ifdef HAVE_MEMORY_H
32#include <memory.h>
33#endif
34
35#ifdef HAVE_UNISTD_H
36#include <errno.h>
37#include <signal.h>
38#include <pwd.h>
39#include <grp.h>
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <sys/resource.h>
43#include <fcntl.h>
44#include <unistd.h>
45/* need to undef these, since the #define's may be picked up from
46 * linux/wait.h, and will clash with a typedef in sys/wait.h
47 */
48#undef P_ALL
49#undef P_PID
50#undef P_PGID
51#include <sys/wait.h>
52
53/*********************
54#ifdef HAVE_SYS_VFS_H
55#include <sys/vfs.h>
56#endif
57**********************/
58#endif
59
60#if TIME_WITH_SYS_TIME
61#include <sys/time.h>
62#include <time.h>
63#else
64#if HAVE_SYS_TIME_H
65#include <sys/time.h>
66#else
67#include <time.h>
68#endif
69#endif
70
71#ifdef HAVE_SYS_SELECT_H
72#include <sys/select.h>
73#endif
74
75#ifndef FD_SET
76#define NFDBITS 32
77#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
78#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
79#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
80#endif /* !FD_SET */
81#ifndef FD_SETSIZE
82#define FD_SETSIZE 32
83#endif
84#ifndef FD_ZERO
85#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p)))
86#endif
87
88
89#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
90#include <sys/mman.h>
91#endif
92
93#include "samhain.h"
94#include "sh_error.h"
95#include "sh_unix.h"
96#include "sh_utils.h"
97#include "sh_mem.h"
98#include "sh_hash.h"
99#include "sh_tools.h"
100#include "sh_restrict.h"
101#include "sh_ipvx.h"
102#include "sh_tiger.h"
103#include "sh_prelink.h"
104#include "sh_pthread.h"
105#include "sh_sem.h"
106
107/* moved here from far below
108 */
109#include <netdb.h>
110
111#define SH_NEED_PWD_GRP
112#define SH_NEED_GETHOSTBYXXX
113#include "sh_static.h"
114
115#ifndef HAVE_LSTAT
116#define lstat stat
117#endif
118
119#if defined(S_IFLNK) && !defined(S_ISLNK)
120#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
121#else
122#if !defined(S_ISLNK)
123#define S_ISLNK(mode) (0)
124#endif
125#endif
126
127#if defined(S_IFSOCK) && !defined(S_ISSOCK)
128#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
129#else
130#if !defined(S_ISSOCK)
131#define S_ISSOCK(mode) (0)
132#endif
133#endif
134
135#if defined(S_IFDOOR) && !defined(S_ISDOOR)
136#define S_ISDOOR(mode) (((mode) & S_IFMT) == S_IFDOOR)
137#else
138#if !defined(S_ISDOOR)
139#define S_ISDOOR(mode) (0)
140#endif
141#endif
142
143#if defined(S_IFPORT) && !defined(S_ISPORT)
144#define S_ISPORT(mode) (((mode) & S_IFMT) == S_IFPORT)
145#else
146#if !defined(S_ISPORT)
147#define S_ISPORT(mode) (0)
148#endif
149#endif
150
151#define SH_KEY_NULL _("000000000000000000000000000000000000000000000000")
152
153#undef FIL__
154#define FIL__ _("sh_unix.c")
155
156unsigned long mask_PRELINK = MASK_PRELINK_;
157unsigned long mask_USER0 = MASK_USER_;
158unsigned long mask_USER1 = MASK_USER_;
159unsigned long mask_USER2 = MASK_USER_;
160unsigned long mask_USER3 = MASK_USER_;
161unsigned long mask_USER4 = MASK_USER_;
162unsigned long mask_ALLIGNORE = MASK_ALLIGNORE_;
163unsigned long mask_ATTRIBUTES = MASK_ATTRIBUTES_;
164unsigned long mask_LOGFILES = MASK_LOGFILES_;
165unsigned long mask_LOGGROW = MASK_LOGGROW_;
166unsigned long mask_READONLY = MASK_READONLY_;
167unsigned long mask_NOIGNORE = MASK_NOIGNORE_;
168
169
170extern char **environ;
171
172int sh_unix_maskreset()
173{
174 mask_PRELINK = MASK_PRELINK_;
175 mask_USER0 = MASK_USER_;
176 mask_USER1 = MASK_USER_;
177 mask_USER2 = MASK_USER_;
178 mask_USER3 = MASK_USER_;
179 mask_USER4 = MASK_USER_;
180 mask_ALLIGNORE = MASK_ALLIGNORE_;
181 mask_ATTRIBUTES = MASK_ATTRIBUTES_;
182 mask_LOGFILES = MASK_LOGFILES_;
183 mask_LOGGROW = MASK_LOGGROW_;
184 mask_READONLY = MASK_READONLY_;
185 mask_NOIGNORE = MASK_NOIGNORE_;
186 return 0;
187}
188
189
190#ifdef SYS_SIGLIST_DECLARED
191/* extern const char * const sys_siglist[]; */
192#else
193char * sh_unix_siglist (int signum)
194{
195 switch (signum)
196 {
197#ifdef SIGHUP
198 case SIGHUP:
199 return _("Hangup");
200#endif
201#ifdef SIGINT
202 case SIGINT:
203 return _("Interrupt");
204#endif
205#ifdef SIGQUIT
206 case SIGQUIT:
207 return _("Quit");
208#endif
209#ifdef SIGILL
210 case SIGILL:
211 return _("Illegal instruction");
212#endif
213#ifdef SIGTRAP
214 case SIGTRAP:
215 return _("Trace/breakpoint trap");
216#endif
217#ifdef SIGABRT
218 case SIGABRT:
219 return _("IOT trap/Abort");
220#endif
221#ifdef SIGBUS
222 case SIGBUS:
223 return _("Bus error");
224#endif
225#ifdef SIGFPE
226 case SIGFPE:
227 return _("Floating point exception");
228#endif
229#ifdef SIGUSR1
230 case SIGUSR1:
231 return _("User defined signal 1");
232#endif
233#ifdef SIGSEGV
234 case SIGSEGV:
235 return _("Segmentation fault");
236#endif
237#ifdef SIGUSR2
238 case SIGUSR2:
239 return _("User defined signal 2");
240#endif
241#ifdef SIGPIPE
242 case SIGPIPE:
243 return _("Broken pipe");
244#endif
245#ifdef SIGALRM
246 case SIGALRM:
247 return _("Alarm clock");
248#endif
249#ifdef SIGTERM
250 case SIGTERM:
251 return _("Terminated");
252#endif
253#ifdef SIGSTKFLT
254 case SIGSTKFLT:
255 return _("Stack fault");
256#endif
257#ifdef SIGCHLD
258 case SIGCHLD:
259 return _("Child exited");
260#endif
261#ifdef SIGCONT
262 case SIGCONT:
263 return _("Continued");
264#endif
265#ifdef SIGSTOP
266 case SIGSTOP:
267 return _("Stopped");
268#endif
269#ifdef SIGTSTP
270 case SIGTSTP:
271 return _("Stop typed at tty");
272#endif
273#ifdef SIGTTIN
274 case SIGTTIN:
275 return _("Stopped (tty input)");
276#endif
277#ifdef SIGTTOU
278 case SIGTTOU:
279 return _("Stopped (tty output)");
280#endif
281#ifdef SIGURG
282 case SIGURG:
283 return _("Urgent condition");
284#endif
285#ifdef SIGXCPU
286 case SIGXCPU:
287 return _("CPU time limit exceeded");
288#endif
289#ifdef SIGXFSZ
290 case SIGXFSZ:
291 return _("File size limit exceeded");
292#endif
293#ifdef SIGVTALRM
294 case SIGVTALRM:
295 return _("Virtual time alarm");
296#endif
297#ifdef SIGPROF
298 case SIGPROF:
299 return _("Profile signal");
300#endif
301#ifdef SIGWINCH
302 case SIGWINCH:
303 return _("Window size changed");
304#endif
305#ifdef SIGIO
306 case SIGIO:
307 return _("Possible I/O");
308#endif
309#ifdef SIGPWR
310 case SIGPWR:
311 return _("Power failure");
312#endif
313#ifdef SIGUNUSED
314 case SIGUNUSED:
315 return _("Unused signal");
316#endif
317 }
318 return _("Unknown");
319}
320#endif
321
322
323/* Log from within a signal handler without using any
324 * functions that are not async signal safe.
325 *
326 * This is the safe_itoa helper function.
327 */
328char * safe_itoa(int i, char * str, int size)
329{
330 unsigned int u;
331 int iisneg = 0;
332 char *p = &str[size-1];
333
334 *p = '\0';
335 if (i < 0) {
336 iisneg = 1;
337 u = ((unsigned int)(-(1+i))) + 1;
338 } else {
339 u = i;
340 }
341 do {
342 --p;
343 *p = '0' + (u % 10);
344 u /= 10;
345 } while (u && (p != str));
346 if ((iisneg == 1) && (p != str)) {
347 --p;
348 *p = '-';
349 }
350 return p;
351}
352
353/* Log from within a signal handler without using any
354 * functions that are not async signal safe.
355 *
356 * This is the safe_logger function.
357 * Arguments: signal (signal number), method (0=logger, 1=stderr), thepid (pid)
358 */
359extern int OnlyStderr;
360
361int safe_logger (int thesignal, int method, char * details)
362{
363 unsigned int i = 0;
364 int status = -1;
365 struct stat buf;
366 pid_t newpid;
367 char str[128];
368 char * p;
369
370 char l0[64], l1[64], l2[64], l3[64];
371 char a0[32];
372 char e0[128];
373 char msg[128];
374
375 char * locations[] = { NULL, NULL, NULL, NULL, NULL };
376 char * envp[] = { NULL, NULL };
377 char * argp[] = { NULL, NULL, NULL };
378
379 pid_t thepid = getpid();
380
381 if ((sh.flag.isdaemon == S_FALSE) || (OnlyStderr == S_TRUE))
382 method = 1;
383
384 /* seems that solaris cc needs this way of initializing ...
385 */
386 locations[0] = l0;
387 locations[1] = l1;
388 locations[2] = l2;
389 locations[3] = l3;
390
391 envp[0] = e0;
392 argp[0] = a0;
393
394 sl_strlcpy(msg, _("samhain["), 128);
395 p = safe_itoa((int) thepid, str, 128);
396 if (p && *p)
397 sl_strlcat(msg, p, 128);
398 if (thesignal == 0)
399 {
400 if (details == NULL) {
401 sl_strlcat(msg, _("]: out of memory"), 128);
402 } else {
403 sl_strlcat(msg, _("]: "), 128);
404 sl_strlcat(msg, details, 128);
405 }
406 }
407 else
408 {
409 sl_strlcat(msg, _("]: exit on signal "), 128);
410 p = safe_itoa(thesignal, str, 128);
411 if (p && *p)
412 sl_strlcat(msg, p, 128);
413 }
414
415 if (method == 1) {
416#ifndef STDERR_FILENO
417#define STDERR_FILENO 2
418#endif
419 int retval = 0;
420 do {
421 retval = write(STDERR_FILENO, msg, strlen(msg));
422 } while (retval < 0 && errno == EINTR);
423 do {
424 retval = write(STDERR_FILENO, "\n", 1);
425 } while (retval < 0 && errno == EINTR);
426 return 0;
427 }
428
429 sl_strlcpy (l0, _("/usr/bin/logger"), 64);
430 sl_strlcpy (l1, _("/usr/sbin/logger"), 64);
431 sl_strlcpy (l2, _("/usr/ucb/logger"), 64);
432 sl_strlcpy (l3, _("/bin/logger"), 64);
433
434 sl_strlcpy (a0, _("logger"), 32);
435 sl_strlcpy (e0,
436 _("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/ucb:/usr/local/bin"),
437 128);
438
439 while (locations[i] != NULL) {
440 status = stat(locations[i], &buf);
441 if (status == 0)
442 break;
443 ++i;
444 }
445
446 if (locations[i] != NULL) {
447 argp[1] = msg;
448 newpid = fork();
449 if (newpid == 0) {
450 execve(locations[i], argp, envp);
451 _exit(1);
452 }
453 else if (newpid > 0) {
454 waitpid(newpid, &status, WUNTRACED);
455 }
456 }
457 return 0;
458}
459
460void safe_fatal (const char * details,
461 const char * file, int line)
462{
463 char msg[128];
464 char str[128];
465 char * p;
466 int thesignal = 0;
467 int method = 0;
468
469 p = safe_itoa((int) line, str, 128);
470 sl_strlcpy(msg, _("FATAL: "), 128);
471 sl_strlcat(msg, file, 128);
472 sl_strlcat(msg, ": ", 128);
473 if (p && (*p)) {
474 sl_strlcat(msg, p , 128);
475 sl_strlcat(msg, ": ", 128);
476 }
477 sl_strlcat(msg, details, 128);
478 (void) safe_logger (thesignal, method, msg);
479
480 close_ipc ();
481 raise(SIGKILL);
482}
483
484extern char sh_sig_msg[64];
485
486volatile int immediate_exit_normal = 0;
487
488#if defined(SA_SIGACTION_WORKS)
489static
490void sh_unix_sigexit (int mysignal, siginfo_t * signal_info, void * signal_add)
491#else
492static
493void sh_unix_sigexit (int mysignal)
494#endif
495{
496
497#if defined(SA_SIGACTION_WORKS)
498 if (signal_info != NULL && signal_info->si_code == SI_USER &&
499 mysignal != SIGTERM && mysignal != SIGINT)
500 {
501 return;
502 }
503
504 /* avoid compiler warning (unused var)
505 */
506 (void) signal_add;
507#endif
508
509 /*
510 * Block re-entry
511 */
512 if (immediate_exit_normal > 0)
513 {
514 ++immediate_exit_normal;
515 if ((skey != NULL) && (immediate_exit_normal == 2))
516 memset (skey, '\0', sizeof(sh_key_t));
517 if (immediate_exit_normal == 2)
518 {
519 int val_return;
520
521 do {
522 val_return = chdir ("/");
523 } while (val_return < 0 && errno == EINTR);
524
525 close_ipc ();
526 safe_logger (mysignal, 0, NULL);
527 }
528 raise(SIGKILL);
529 }
530 else
531 {
532 immediate_exit_normal = 1;
533 }
534
535#ifdef SYS_SIGLIST_DECLARED
536 strncpy (sh_sig_msg, sys_siglist[mysignal], 40);
537#else
538 strncpy (sh_sig_msg, sh_unix_siglist(mysignal), 40);
539#endif
540 sh_sig_msg[63] = '\0';
541
542 ++sig_raised;
543 ++sig_urgent;
544 sig_termfast = 1;
545 return;
546}
547
548volatile int immediate_exit_fast = 0;
549
550#if defined(SA_SIGACTION_WORKS)
551static
552void sh_unix_sigexit_fast (int mysignal, siginfo_t * signal_info,
553 void * signal_add)
554#else
555static
556void sh_unix_sigexit_fast (int mysignal)
557#endif
558{
559#if defined(SL_DEBUG) && (defined(USE_SYSTEM_MALLOC) || !defined(USE_MALLOC_LOCK))
560 int retval;
561#endif
562
563#if defined(SA_SIGACTION_WORKS)
564 if (signal_info != NULL && signal_info->si_code == SI_USER)
565 {
566 return;
567 }
568#endif
569
570 /* avoid compiler warning (unused var)
571 */
572#if defined(SA_SIGACTION_WORKS)
573 (void) signal_add;
574#endif
575
576 /* Check whether the heap is ok; otherwise _exit
577 */
578#if !defined(SL_DEBUG) || (!defined(USE_SYSTEM_MALLOC) && defined(USE_MALLOC_LOCK))
579 ++immediate_exit_fast;
580 if (skey != NULL && immediate_exit_fast < 2)
581 memset (skey, '\0', sizeof(sh_key_t));
582 if (immediate_exit_fast < 2)
583 safe_logger (mysignal, 0, NULL);
584 raise(SIGKILL);
585#else
586
587 /* debug code
588 */
589 if (immediate_exit_fast == 1)
590 {
591 ++immediate_exit_fast;
592 if (skey != NULL)
593 memset (skey, '\0', sizeof(sh_key_t));
594 close_ipc ();
595 safe_logger (mysignal, 0, NULL);
596 do {
597 retval = chdir ("/");
598 } while (retval < 0 && errno == EINTR);
599 raise(SIGFPE);
600 }
601 else if (immediate_exit_fast == 2)
602 {
603 do {
604 retval = chdir ("/");
605 } while (retval < 0 && errno == EINTR);
606 raise(SIGFPE);
607 }
608 else if (immediate_exit_fast != 0)
609 {
610 raise(SIGKILL);
611 }
612
613 ++immediate_exit_fast;
614
615 /* The FPE|BUS|SEGV|ILL signals leave the system in an undefined
616 * state, thus it is best to exit immediately.
617 */
618#ifdef SYS_SIGLIST_DECLARED
619 strncpy (sh_sig_msg, sys_siglist[mysignal], 40);
620#else
621 strncpy (sh_sig_msg, sh_unix_siglist(mysignal), 40);
622#endif
623 sh_sig_msg[63] = '\0';
624
625 sl_stack_print();
626
627 /* Try to push out an error message.
628 */
629 sh_error_handle ((-1), FIL__, __LINE__, mysignal, MSG_EXIT_NORMAL,
630 sh.prg_name, sh_sig_msg);
631
632 if (skey != NULL)
633 memset (skey, '\0', sizeof(sh_key_t));
634 close_ipc ();
635
636 do {
637 retval = chdir ("/");
638 } while (retval < 0 && errno == EINTR);
639
640 raise(SIGFPE);
641#endif
642}
643
644
645static
646void sh_unix_sigaction (int mysignal)
647{
648 ++sig_raised;
649#ifdef SIGUSR1
650 if (mysignal == SIGUSR1)
651 sig_debug_switch = 1;
652#endif
653#ifdef SIGUSR2
654 if (mysignal == SIGUSR2)
655 {
656 ++sig_suspend_switch;
657 ++sig_urgent;
658 }
659#endif
660#ifdef SIGHUP
661 if (mysignal == SIGHUP)
662 sig_config_read_again = 1;
663#endif
664#ifdef SIGTTOU
665 if (mysignal == SIGTTOU) {
666 sig_force_check = 1; sh_sem_trylock(); }
667#endif
668#ifdef SIGTSTP
669 if (mysignal == SIGTSTP) {
670 sig_force_check = 1; sig_force_silent = 1; sh_sem_trylock(); }
671#endif
672#ifdef SIGTTIN
673 if (mysignal == SIGTTIN)
674 sig_fresh_trail = 1;
675#endif
676#ifdef SIGABRT
677 if (mysignal == SIGABRT)
678 sig_fresh_trail = 1;
679#endif
680#ifdef SIGQUIT
681 if (mysignal == SIGQUIT)
682 sig_terminate = 1;
683#endif
684#ifdef SIGTERM
685 if (mysignal == SIGTERM)
686 {
687 strncpy (sh_sig_msg, _("Terminated"), 40);
688 sig_termfast = 1;
689 ++sig_urgent;
690 }
691#endif
692
693 return;
694}
695
696void sh_unix_ign_sigpipe()
697{
698 struct sigaction ignact;
699
700 ignact.sa_handler = SIG_IGN; /* signal action */
701 sigemptyset( &ignact.sa_mask ); /* set an empty mask */
702 ignact.sa_flags = 0; /* init sa_flags */
703
704#ifdef SIGPIPE
705 retry_sigaction(FIL__, __LINE__, SIGPIPE, &ignact, NULL);
706#endif
707
708 return;
709}
710static
711void sh_unix_siginstall (int goDaemon)
712{
713 struct sigaction act, act_fast, act2, oldact, ignact;
714#if defined (SH_WITH_SERVER)
715 (void) goDaemon;
716#endif
717
718 SL_ENTER(_("sh_unix_siginstall"));
719
720 ignact.sa_handler = SIG_IGN; /* signal action */
721 sigemptyset( &ignact.sa_mask ); /* set an empty mask */
722 ignact.sa_flags = 0; /* init sa_flags */
723
724#if defined(SA_SIGACTION_WORKS)
725 act.sa_sigaction = &sh_unix_sigexit; /* signal action */
726#else
727 act.sa_handler = &sh_unix_sigexit; /* signal action */
728#endif
729
730 sigfillset ( &act.sa_mask ); /* set a full mask */
731
732
733 /* Block all but deadly signals.
734 */
735#ifdef SIGILL
736 sigdelset ( &act.sa_mask, SIGILL );
737#endif
738#ifndef SL_DEBUG
739#ifdef SIGFPE
740 sigdelset ( &act.sa_mask, SIGFPE );
741#endif
742#endif
743#ifdef SIGSEGV
744 sigdelset ( &act.sa_mask, SIGSEGV );
745#endif
746#ifdef SIGBUS
747 sigdelset ( &act.sa_mask, SIGBUS );
748#endif
749
750#if defined(SA_SIGACTION_WORKS)
751 act_fast.sa_sigaction = &sh_unix_sigexit_fast; /* signal action */
752#else
753 act_fast.sa_handler = &sh_unix_sigexit_fast; /* signal action */
754#endif
755
756 sigfillset ( &act_fast.sa_mask ); /* set a full mask */
757
758#ifdef SIGILL
759 sigdelset ( &act_fast.sa_mask, SIGILL );
760#endif
761#ifndef SL_DEBUG
762#ifdef SIGFPE
763 sigdelset ( &act_fast.sa_mask, SIGFPE );
764#endif
765#endif
766#ifdef SIGSEGV
767 sigdelset ( &act_fast.sa_mask, SIGSEGV );
768#endif
769#ifdef SIGBUS
770 sigdelset ( &act_fast.sa_mask, SIGBUS );
771#endif
772
773
774 /* Use siginfo to verify origin of signal, if possible.
775 */
776#if defined(SA_SIGACTION_WORKS)
777 act.sa_flags = SA_SIGINFO;
778 act_fast.sa_flags = SA_SIGINFO;
779#else
780 act.sa_flags = 0;
781 act_fast.sa_flags = 0;
782#endif
783
784 /* Do not block the signal from being received in its handler ...
785 * (is this a good or a bad idea ??).
786 */
787#if defined(SA_NOMASK)
788 act_fast.sa_flags |= SA_NOMASK;
789#elif defined(SA_NODEFER)
790 act_fast.sa_flags |= SA_NODEFER;
791#endif
792
793
794 act2.sa_handler = &sh_unix_sigaction; /* signal action */
795 sigemptyset( &act2.sa_mask ); /* set an empty mask */
796 act2.sa_flags = 0; /* init sa_flags */
797
798 /* signals to control the daemon */
799
800#ifdef SIGHUP
801 retry_sigaction(FIL__, __LINE__, SIGHUP, &act2, &oldact);
802#endif
803#ifdef SIGABRT
804 retry_sigaction(FIL__, __LINE__, SIGABRT, &act2, &oldact);
805#endif
806#ifdef SIGUSR1
807 retry_sigaction(FIL__, __LINE__, SIGUSR1, &act2, &oldact);
808#endif
809#ifdef SIGUSR2
810 retry_sigaction(FIL__, __LINE__, SIGUSR2, &act2, &oldact);
811#endif
812#ifdef SIGQUIT
813 retry_sigaction(FIL__, __LINE__, SIGQUIT, &act2, &oldact);
814#endif
815#ifdef SIGTERM
816 retry_sigaction(FIL__, __LINE__, SIGTERM, &act, &oldact);
817#endif
818
819 /* fatal signals that may cause termination */
820
821#ifdef SIGILL
822 retry_sigaction(FIL__, __LINE__, SIGILL, &act_fast, &oldact);
823#endif
824#ifndef SL_DEBUG
825#ifdef SIGFPE
826 retry_sigaction(FIL__, __LINE__, SIGFPE, &act_fast, &oldact);
827#endif
828#endif
829#ifdef SIGSEGV
830 retry_sigaction(FIL__, __LINE__, SIGSEGV, &act_fast, &oldact);
831#endif
832#ifdef SIGBUS
833 retry_sigaction(FIL__, __LINE__, SIGBUS, &act_fast, &oldact);
834#endif
835
836 /* other signals */
837
838#ifdef SIGINT
839 retry_sigaction(FIL__, __LINE__, SIGINT, &act, &oldact);
840#endif
841#ifdef SIGPIPE
842 retry_sigaction(FIL__, __LINE__, SIGPIPE, &ignact, &oldact);
843#endif
844#ifdef SIGALRM
845 retry_sigaction(FIL__, __LINE__, SIGALRM, &ignact, &oldact);
846#endif
847
848#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
849#ifdef SIGTTOU
850 if (goDaemon == 1)
851 retry_sigaction(FIL__, __LINE__, SIGTTOU, &act2, &oldact);
852 else
853 retry_sigaction(FIL__, __LINE__, SIGTTOU, &ignact, &oldact);
854#endif
855#ifdef SIGTSTP
856 if (goDaemon == 1)
857 retry_sigaction(FIL__, __LINE__, SIGTSTP, &act2, &oldact);
858 else
859 retry_sigaction(FIL__, __LINE__, SIGTSTP, &ignact, &oldact);
860#endif
861#ifdef SIGTTIN
862 if (goDaemon == 1)
863 retry_sigaction(FIL__, __LINE__, SIGTTIN, &act2, &oldact);
864 else
865 retry_sigaction(FIL__, __LINE__, SIGTTIN, &ignact, &oldact);
866#endif
867#else
868#ifdef SIGTSTP
869 retry_sigaction(FIL__, __LINE__, SIGTSTP, &ignact, &oldact);
870#endif
871#ifdef SIGTTOU
872 retry_sigaction(FIL__, __LINE__, SIGTTOU, &ignact, &oldact);
873#endif
874#ifdef SIGTTIN
875 retry_sigaction(FIL__, __LINE__, SIGTTIN, &ignact, &oldact);
876#endif
877#endif
878
879#ifdef SIGTRAP
880#if !defined(SCREW_IT_UP)
881 retry_sigaction(FIL__, __LINE__, SIGTRAP, &act, &oldact);
882#endif
883#endif
884
885#ifdef SIGPOLL
886 retry_sigaction(FIL__, __LINE__, SIGPOLL, &ignact, &oldact);
887#endif
888#if defined(SIGPROF) && !defined(SH_PROFILE)
889 retry_sigaction(FIL__, __LINE__, SIGPROF, &ignact, &oldact);
890#endif
891#ifdef SIGSYS
892 retry_sigaction(FIL__, __LINE__, SIGSYS, &act, &oldact);
893#endif
894#ifdef SIGURG
895 retry_sigaction(FIL__, __LINE__, SIGURG, &ignact, &oldact);
896#endif
897#if defined(SIGVTALRM) && !defined(SH_PROFILE)
898 retry_sigaction(FIL__, __LINE__, SIGVTALRM, &ignact, &oldact);
899#endif
900#ifdef SIGXCPU
901 retry_sigaction(FIL__, __LINE__, SIGXCPU, &act, &oldact);
902#endif
903#ifdef SIGXFSZ
904 retry_sigaction(FIL__, __LINE__, SIGXFSZ, &act, &oldact);
905#endif
906
907#ifdef SIGEMT
908 retry_sigaction(FIL__, __LINE__, SIGEMT, &ignact, &oldact);
909#endif
910#ifdef SIGSTKFLT
911 retry_sigaction(FIL__, __LINE__, SIGSTKFLT, &act, &oldact);
912#endif
913#ifdef SIGIO
914 retry_sigaction(FIL__, __LINE__, SIGIO, &ignact, &oldact);
915#endif
916#ifdef SIGPWR
917 retry_sigaction(FIL__, __LINE__, SIGPWR, &act, &oldact);
918#endif
919
920#ifdef SIGLOST
921 retry_sigaction(FIL__, __LINE__, SIGLOST, &ignact, &oldact);
922#endif
923#ifdef SIGUNUSED
924 retry_sigaction(FIL__, __LINE__, SIGUNUSED, &ignact, &oldact);
925#endif
926
927 SL_RET0(_("sh_unix_siginstall"));
928}
929
930/* ---------------------------------------------------------------- */
931
932/* checksum the own binary
933 */
934int sh_unix_self_hash (const char * c)
935{
936 char message[512];
937 char hashbuf[KEYBUF_SIZE];
938
939 SL_ENTER(_("sh_unix_self_hash"));
940
941 if (c == NULL)
942 {
943 sh.exec.path[0] = '\0';
944 SL_RETURN((0), _("sh_unix_self_hash"));
945 }
946 sl_strlcpy(sh.exec.path, c, SH_PATHBUF);
947
948 sl_strlcpy(sh.exec.hash,
949 sh_tiger_hash (c, TIGER_FILE, TIGER_NOLIM, hashbuf, sizeof(hashbuf)),
950 KEY_LEN+1);
951 sl_snprintf(message, 512, _("%s has checksum: %s"),
952 sh.exec.path, sh.exec.hash);
953 message[511] = '\0';
954 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, 0, MSG_E_SUBGEN,
955 message, _("sh_unix_self_hash"));
956 if (0 == sl_strcmp(sh.exec.hash, SH_KEY_NULL ))
957 {
958 dlog(1, FIL__, __LINE__,
959 _("Could not checksum my own executable because of the\nfollowing error: %s: %s\n\nPossible reasons include:\n Wrong path in configure file option SamhainPath=/path/to/executable\n No read permission for the effective UID: %d\n"),
960 sh.exec.path, sl_get_errmsg(), (int) sl_ret_euid());
961 sh_error_handle ((-1), FIL__, __LINE__, EACCES, MSG_NOACCESS,
962 (long) sh.real.uid, c);
963 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
964 }
965 SL_RETURN((0), _("sh_unix_self_hash"));
966}
967
968int sh_unix_self_check ()
969{
970 char newhash[KEY_LEN+1];
971 char message[512];
972 char hashbuf[KEYBUF_SIZE];
973
974 SL_ENTER(_("sh_unix_self_check"));
975 if (sh.exec.path[0] == '\0')
976 SL_RETURN((0), _("sh_unix_self_check"));
977
978 sl_strlcpy(newhash,
979 sh_tiger_hash (sh.exec.path, TIGER_FILE, TIGER_NOLIM, hashbuf, sizeof(hashbuf)),
980 KEY_LEN+1);
981 if (0 == sl_strncmp(sh.exec.hash, newhash, KEY_LEN))
982 {
983 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, 0, MSG_E_SUBGEN,
984 _("Checksum ok"), _("sh_unix_self_check"));
985 SL_RETURN((0), _("sh_unix_self_check"));
986 }
987
988 if (0 == sl_strncmp(SH_KEY_NULL, newhash, KEY_LEN))
989 {
990 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
991 _("Could not read samhain executable"), _("sh_unix_self_check"));
992 SL_RETURN((0), _("sh_unix_self_check"));
993 }
994
995 dlog(1, FIL__, __LINE__,
996 _("The checksum of the executable: %s has changed since startup (%s -> %s).\n"),
997 sh.exec.path, sh.exec.hash, newhash);
998
999 sl_snprintf(message, 512,
1000 _("The checksum of %s has changed since startup (%s -> %s)"),
1001 sh.exec.path, sh.exec.hash, newhash);
1002 message[511] = '\0';
1003
1004 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1005 message, _("sh_unix_self_check"));
1006 sh_error_handle ((-1), FIL__, __LINE__, EACCES, MSG_E_AUTH,
1007 sh.exec.path);
1008 SL_RETURN((-1), _("sh_unix_self_check"));
1009}
1010
1011
1012/* ---------------------------------------------------------------- */
1013
1014long sh_group_to_gid (const char * g, int * fail)
1015{
1016 struct group * w;
1017 gid_t gid = 0;
1018 int status = 0;
1019
1020#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1021 struct group grp;
1022 char * buffer;
1023 static size_t gbufsize = SH_GRBUF_SIZE;
1024#endif
1025
1026 *fail = -1;
1027
1028 if (g)
1029 {
1030 size_t i;
1031 size_t len = strlen(g);
1032
1033 *fail = 0;
1034
1035 for (i = 0; i < len; ++i)
1036 {
1037 char c = g[i];
1038
1039 if (!isdigit((int) c))
1040 goto is_a_name;
1041 }
1042 return atol(g);
1043
1044 is_a_name:
1045
1046#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1047
1048 buffer = SH_ALLOC(gbufsize);
1049 status = sh_getgrnam_r(g, &grp, buffer, gbufsize, &w);
1050
1051 if ((status == ERANGE) && (w == NULL))
1052 {
1053 if (S_TRUE == sl_ok_adds( gbufsize, SH_GRBUF_SIZE ))
1054 {
1055 SH_FREE(buffer);
1056 gbufsize += SH_GRBUF_SIZE;
1057 goto is_a_name;
1058 }
1059 }
1060
1061#else
1062
1063 errno = 0;
1064 w = sh_getgrnam(g);
1065 status = errno;
1066
1067#endif
1068
1069 if ((status == ERANGE) && (w == NULL))
1070 {
1071 static int seen = 0;
1072
1073 if (seen == 0)
1074 {
1075 char errbuf[SH_ERRBUF_SIZE];
1076
1077 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
1078 sh_error_message(status, errbuf, sizeof(errbuf)),
1079 _("sh_group_to_gid"), (long) -1, _("line too long in group entry"));
1080 ++seen;
1081 }
1082 *fail = -1;
1083 }
1084 else if (w == NULL)
1085 {
1086 char * tmp = sh_util_strdup(g);
1087 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
1088 _("sh_group_to_gid"), tmp);
1089 SH_FREE(tmp);
1090 *fail = -1;
1091 }
1092 else
1093 {
1094 gid = w->gr_gid;
1095 }
1096#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1097 SH_FREE(buffer);
1098#endif
1099 }
1100
1101 return gid;
1102}
1103
1104/* ---------------------------------------------------------------- */
1105
1106
1107/* added Tue Feb 22 10:36:44 NFT 2000 Rainer Wichmann */
1108static int tf_add_trusted_user_int(const char * c)
1109{
1110 struct passwd * w;
1111 int count;
1112 uid_t pwid = (uid_t)-1;
1113
1114#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1115 struct passwd pwd;
1116 char * buffer;
1117#endif
1118
1119 SL_ENTER(_("tf_add_trusted_user_int"));
1120
1121 /* First check for a user name.
1122 */
1123#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1124 buffer = SH_ALLOC(SH_PWBUF_SIZE);
1125 sh_getpwnam_r(c, &pwd, buffer, SH_PWBUF_SIZE, &w);
1126#else
1127 w = sh_getpwnam(c);
1128#endif
1129
1130 if ((w != NULL) && ((pwid = w->pw_uid) > 0))
1131 goto succe;
1132
1133 /* Failed, so check for a numerical value.
1134 */
1135 pwid = strtol(c, (char **)NULL, 10);
1136 if (pwid > 0 && pwid < 65535)
1137 goto succe;
1138
1139 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
1140 _("add trusted user"), c);
1141#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1142 SH_FREE(buffer);
1143#endif
1144 SL_RETURN((-1), _("tf_add_trusted_user_int"));
1145
1146 succe:
1147 count = sl_trust_add_user(pwid);
1148#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1149 SH_FREE(buffer);
1150#endif
1151 SL_RETURN((count), _("tf_add_trusted_user_int"));
1152}
1153
1154int tf_add_trusted_user(const char * c)
1155{
1156 int i;
1157 char * q;
1158 char * p = sh_util_strdup (c);
1159#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1160 char * saveptr;
1161#endif
1162
1163 SL_ENTER(_("tf_add_trusted_user"));
1164
1165#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1166 q = strtok_r(p, ", \t", &saveptr);
1167#else
1168 q = strtok(p, ", \t");
1169#endif
1170 if (!q)
1171 {
1172 SH_FREE(p);
1173 SL_RETURN((-1), _("tf_add_trusted_user"));
1174 }
1175 while (q)
1176 {
1177 i = tf_add_trusted_user_int(q);
1178 if (SL_ISERROR(i))
1179 {
1180 SH_FREE(p);
1181 SL_RETURN((i), _("tf_add_trusted_user"));
1182 }
1183#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1184 q = strtok_r(NULL, ", \t", &saveptr);
1185#else
1186 q = strtok(NULL, ", \t");
1187#endif
1188 }
1189 SH_FREE(p);
1190 SL_RETURN((0), _("tf_add_trusted_user"));
1191}
1192
1193extern uid_t sl_trust_baduid(void);
1194extern gid_t sl_trust_badgid(void);
1195
1196#if defined(HOST_IS_CYGWIN) || defined(__cygwin__) || defined(__CYGWIN32__) || defined(__CYGWIN__)
1197int tf_trust_check (const char * file, int mode)
1198{
1199 (void) file;
1200 (void) mode;
1201 return 0;
1202}
1203#else
1204int tf_trust_check (const char * file, int mode)
1205{
1206 char * tmp;
1207 char * tmp2;
1208 char * p;
1209 int status;
1210 int level;
1211 uid_t ff_euid = (uid_t) -1;
1212
1213 SL_ENTER(_("tf_trust_check"));
1214
1215 if (mode == SL_YESPRIV)
1216 sl_get_euid(&ff_euid);
1217 else
1218 sl_get_ruid(&ff_euid);
1219
1220#if defined(SH_WITH_SERVER)
1221 if (0 == sl_ret_euid()) /* privileges not dropped yet */
1222 {
1223#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1224 struct passwd pwd;
1225 char * buffer = SH_ALLOC(SH_PWBUF_SIZE);
1226 struct passwd * tempres;
1227 sh_getpwnam_r(DEFAULT_IDENT, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
1228#else
1229 struct passwd * tempres = sh_getpwnam(DEFAULT_IDENT);
1230#endif
1231
1232 if (!tempres)
1233 {
1234 dlog(1, FIL__, __LINE__,
1235 _("User %s does not exist. Please add the user to your system.\n"),
1236 DEFAULT_IDENT);
1237 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
1238 }
1239 else
1240 {
1241 ff_euid = tempres->pw_uid;
1242 }
1243#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1244 SH_FREE(buffer);
1245#endif
1246 }
1247#endif
1248
1249 status = sl_trustfile_euid(file, ff_euid);
1250
1251 if ( SL_ENONE != status)
1252 {
1253 if (status == SL_ESTAT)
1254 level = SH_ERR_ALL;
1255 else
1256 level = SH_ERR_ERR;
1257
1258 tmp = sh_util_safe_name (file);
1259 p = sl_trust_errfile();
1260 if (p && *p != '\0')
1261 {
1262 tmp2 = sh_util_safe_name (sl_trust_errfile());
1263 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST2,
1264 sl_error_string(status), tmp, tmp2);
1265 SH_FREE(tmp2);
1266 }
1267 else
1268 {
1269 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST1,
1270 sl_error_string(status), tmp);
1271 }
1272 SH_FREE(tmp);
1273
1274 if (status == SL_EBADUID || status == SL_EBADGID ||
1275 status == SL_EBADOTH || status == SL_ETRUNC ||
1276 status == SL_EINTERNAL )
1277 {
1278 switch (status) {
1279 case SL_EINTERNAL:
1280 dlog(1, FIL__, __LINE__,
1281 _("An internal error occured in the trustfile function.\n"));
1282 break;
1283 case SL_ETRUNC:
1284 tmp = sh_util_safe_name (file);
1285 dlog(1, FIL__, __LINE__,
1286 _("A filename truncation occured in the trustfile function.\nProbably the normalized filename for %s\nis too long. This may be due e.g. to deep or circular softlinks.\n"),
1287 tmp);
1288 SH_FREE(tmp);
1289 break;
1290 case SL_EBADOTH:
1291 tmp = sh_util_safe_name (file);
1292 p = sl_trust_errfile();
1293 dlog(1, FIL__, __LINE__,
1294 _("The path element: %s\nin the filename: %s is world writeable.\n"),
1295 p, tmp);
1296 SH_FREE(tmp);
1297 break;
1298 case SL_EBADUID:
1299 tmp = sh_util_safe_name (file);
1300 p = sl_trust_errfile();
1301 dlog(1, FIL__, __LINE__,
1302 _("The owner (UID = %ld) of the path element: %s\nin the filename: %s\nis not in the list of trusted users.\nTo fix the problem, you can:\n - run ./configure again with the option --with-trusted=0,...,UID\n where UID is the UID of the untrusted user, or\n - use the option TrustedUser=UID in the configuration file.\n"),
1303 (UID_CAST)sl_trust_baduid(), p, tmp);
1304 SH_FREE(tmp);
1305 break;
1306 case SL_EBADGID:
1307 tmp = sh_util_safe_name (file);
1308 p = sl_trust_errfile();
1309 dlog(1, FIL__, __LINE__,
1310 _("The path element: %s\nin the filename: %s\nis group writeable (GID = %ld), and at least one of the group\nmembers (UID = %ld) is not in the list of trusted users.\nTo fix the problem, you can:\n - run ./configure again with the option --with-trusted=0,...,UID\n where UID is the UID of the untrusted user, or\n - use the option TrustedUser=UID in the configuration file.\n"),
1311 p, tmp, (UID_CAST)sl_trust_badgid(),
1312 (UID_CAST)sl_trust_baduid());
1313 SH_FREE(tmp);
1314 break;
1315 default:
1316 break;
1317 }
1318
1319 SL_RETURN((-1), _("tf_trust_check"));
1320 }
1321 }
1322
1323 SL_RETURN((0), _("tf_trust_check"));
1324}
1325#endif
1326
1327#ifdef HAVE_INITGROUPS
1328#ifdef HOST_IS_OSF
1329int sh_unix_initgroups ( char * in_user, gid_t in_gid)
1330#else
1331int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1332#endif
1333{
1334 int status = -1;
1335 status = sh_initgroups (in_user, in_gid);
1336 if (status < 0)
1337 {
1338 if (errno == EPERM)
1339 return 0;
1340 if (errno == EINVAL)
1341 return 0;
1342 return -1;
1343 }
1344 return 0;
1345}
1346#else
1347int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1348{
1349 (void) in_user;
1350 (void) in_gid;
1351 return 0;
1352}
1353#endif
1354
1355#ifdef HAVE_INITGROUPS
1356char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len);
1357int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1358{
1359 int status = -1;
1360 char user[SH_MINIBUF];
1361
1362 SL_ENTER(_("sh_unix_initgroups2"));
1363
1364 if (NULL == sh_unix_getUIDname (SH_ERR_ERR, in_pid, user, sizeof(user)))
1365 SL_RETURN((-1), _("sh_unix_initgroups2"));
1366 status = sh_initgroups (user, in_gid);
1367 if (status < 0)
1368 {
1369 if (errno == EPERM)
1370 status = 0;
1371 if (errno == EINVAL)
1372 status = 0;
1373 }
1374 SL_RETURN((status), _("sh_unix_initgroups2"));
1375}
1376#else
1377int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1378{
1379 (void) in_pid;
1380 (void) in_gid;
1381 return 0;
1382}
1383#endif
1384
1385void sh_unix_closeall (int fd, int except, int inchild)
1386{
1387 int fdx = fd;
1388#ifdef _SC_OPEN_MAX
1389 int fdlimit = sysconf (_SC_OPEN_MAX);
1390#else
1391#ifdef OPEN_MAX
1392 int fdlimit = OPEN_MAX;
1393#else
1394 int fdlimit = _POSIX_OPEN_MAX;
1395#endif
1396#endif
1397
1398 SL_ENTER(_("sh_unix_closeall"));
1399
1400 /* can't happen - so fix it :-(
1401 */
1402 if (fdlimit < 0)
1403 fdlimit = 20; /* POSIX lower limit */
1404
1405 if (fdlimit > 65536)
1406 fdlimit = 65536;
1407
1408 if (!inchild)
1409 sl_dropall (fdx, except);
1410 else
1411 sl_dropall_dirty (fdx, except);
1412
1413 /* Close everything from fd (inclusive) up to fdlimit (exclusive).
1414 */
1415 while (fd < fdlimit)
1416 {
1417 if (fd == except)
1418 fd++;
1419 else if (slib_do_trace != 0 && fd == slib_trace_fd)
1420 fd++;
1421 else
1422 sl_close_fd(FIL__, __LINE__, fd++);
1423 }
1424
1425 SL_RET0(_("sh_unix_closeall"));
1426}
1427
1428static void sh_unix_setlimits(void)
1429{
1430 struct rlimit limits;
1431
1432 SL_ENTER(_("sh_unix_setlimits"));
1433
1434 limits.rlim_cur = RLIM_INFINITY;
1435 limits.rlim_max = RLIM_INFINITY;
1436
1437#ifdef RLIMIT_CPU
1438 setrlimit (RLIMIT_CPU, &limits);
1439#endif
1440#ifdef RLIMIT_FSIZE
1441 setrlimit (RLIMIT_FSIZE, &limits);
1442#endif
1443#ifdef RLIMIT_DATA
1444 setrlimit (RLIMIT_DATA, &limits);
1445#endif
1446#ifdef RLIMIT_STACK
1447 setrlimit (RLIMIT_STACK, &limits);
1448#endif
1449#ifdef RLIMIT_RSS
1450 setrlimit (RLIMIT_RSS, &limits);
1451#endif
1452#ifdef RLIMIT_NPROC
1453 setrlimit (RLIMIT_NPROC, &limits);
1454#endif
1455#ifdef RLIMIT_MEMLOCK
1456 setrlimit (RLIMIT_MEMLOCK, &limits);
1457#endif
1458
1459#if !defined(SL_DEBUG)
1460 /* no core dumps
1461 */
1462 limits.rlim_cur = 0;
1463 limits.rlim_max = 0;
1464#ifdef RLIMIT_CORE
1465 setrlimit (RLIMIT_CORE, &limits);
1466#endif
1467#else
1468#ifdef RLIMIT_CORE
1469 setrlimit (RLIMIT_CORE, &limits);
1470#endif
1471#endif
1472
1473 limits.rlim_cur = 1024;
1474 limits.rlim_max = 1024;
1475
1476#if defined(RLIMIT_NOFILE)
1477 setrlimit (RLIMIT_NOFILE, &limits);
1478#elif defined(RLIMIT_OFILE)
1479 setrlimit (RLIMIT_OFILE, &limits);
1480#endif
1481
1482 SL_RET0(_("sh_unix_setlimits"));
1483}
1484
1485static void sh_unix_copyenv(void)
1486{
1487 char ** env0 = environ;
1488 char ** env1;
1489 int envlen = 0;
1490 size_t len;
1491
1492 SL_ENTER(_("sh_unix_copyenv"));
1493
1494 while (env0 != NULL && env0[envlen] != NULL) {
1495 /* printf("%2d: %s\n", envlen, env0[envlen]); */
1496 ++envlen;
1497 }
1498 ++envlen;
1499
1500 /* printf("-> %2d: slots allocated\n", envlen); */
1501 env1 = calloc(1,sizeof(char *) * envlen); /* only once */
1502 if (env1 == NULL)
1503 {
1504 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1505 SL_RET0(_("sh_unix_copyenv"));
1506 }
1507 env0 = environ;
1508 envlen = 0;
1509
1510 while (env0 != NULL && env0[envlen] != NULL) {
1511 len = strlen(env0[envlen]) + 1;
1512 env1[envlen] = calloc(1,len); /* only once */
1513 if (env1[envlen] == NULL)
1514 {
1515 int i;
1516 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1517 for (i = 0; i < envlen; ++i) free(env1[len]);
1518 free(env1);
1519 SL_RET0(_("sh_unix_copyenv"));
1520 }
1521 sl_strlcpy(env1[envlen], env0[envlen], len);
1522 ++envlen;
1523 }
1524 env1[envlen] = NULL;
1525
1526 environ = env1;
1527 SL_RET0(_("sh_unix_copyenv"));
1528}
1529
1530/* delete all environment variables
1531 */
1532static void sh_unix_zeroenv(void)
1533{
1534 char * c;
1535 char ** env;
1536
1537 SL_ENTER(_("sh_unix_zeroenv"));
1538
1539 sh_unix_copyenv();
1540 env = environ;
1541
1542 while (env != NULL && *env != NULL) {
1543 c = strchr ((*env), '=');
1544#ifdef WITH_MYSQL
1545 /*
1546 * Skip the MYSQL_UNIX_PORT environment variable; MySQL may need it.
1547 */
1548 if (0 == sl_strncmp((*env), _("MYSQL_UNIX_PORT="), 16))
1549 {
1550 ++(env);
1551 continue;
1552 }
1553 if (0 == sl_strncmp((*env), _("MYSQL_TCP_PORT="), 15))
1554 {
1555 ++(env);
1556 continue;
1557 }
1558 if (0 == sl_strncmp((*env), _("MYSQL_HOME="), 11))
1559 {
1560 ++(env);
1561 continue;
1562 }
1563#endif
1564#ifdef WITH_ORACLE
1565 /*
1566 * Skip the ORACLE_HOME and TNS_ADMIN environment variables;
1567 * Oracle may need them.
1568 */
1569 if (0 == sl_strncmp((*env), _("ORACLE_HOME="), 12))
1570 {
1571 ++(env);
1572 continue;
1573 }
1574 if (0 == sl_strncmp((*env), _("TNS_ADMIN="), 10))
1575 {
1576 ++(env);
1577 continue;
1578 }
1579#endif
1580 /*
1581 * Skip the TZ environment variable.
1582 */
1583 if (0 == sl_strncmp((*env), _("TZ="), 3))
1584 {
1585 ++(env);
1586 continue;
1587 }
1588 ++(env);
1589 if (c != NULL)
1590 {
1591 ++c;
1592 while ((*c) != '\0') {
1593 (*c) = '\0';
1594 ++c;
1595 }
1596 }
1597 }
1598
1599#ifdef HAVE_TZSET
1600 tzset();
1601#endif
1602
1603 SL_RET0(_("sh_unix_zeroenv"));
1604}
1605
1606
1607static void sh_unix_resettimer(void)
1608{
1609 struct itimerval this_timer;
1610
1611 SL_ENTER(_("sh_unix_resettimer"));
1612
1613 this_timer.it_value.tv_sec = 0;
1614 this_timer.it_value.tv_usec = 0;
1615
1616 this_timer.it_interval.tv_sec = 0;
1617 this_timer.it_interval.tv_usec = 0;
1618
1619 setitimer(ITIMER_REAL, &this_timer, NULL);
1620#if !defined(SH_PROFILE)
1621 setitimer(ITIMER_VIRTUAL, &this_timer, NULL);
1622 setitimer(ITIMER_PROF, &this_timer, NULL);
1623#endif
1624
1625 SL_RET0(_("sh_unix_resettimer"));
1626}
1627
1628static void sh_unix_resetsignals(void)
1629{
1630 int sig_num;
1631#ifdef NSIG
1632 int max_sig = NSIG;
1633#else
1634 int max_sig = 255;
1635#endif
1636 int test;
1637 int status;
1638 struct sigaction act;
1639#if !defined(SH_PROFILE)
1640 struct sigaction oldact;
1641#endif
1642
1643 sigset_t set_proc;
1644
1645 SL_ENTER(_("sh_unix_resetsignals"));
1646 /*
1647 * Reset the current signal mask (inherited from parent process).
1648 */
1649
1650 sigfillset(&set_proc);
1651
1652 do {
1653 errno = 0;
1654 test = SH_SETSIGMASK(SIG_UNBLOCK, &set_proc, NULL);
1655 } while (test < 0 && errno == EINTR);
1656
1657 /*
1658 * Reset signal handling.
1659 */
1660
1661 act.sa_handler = SIG_DFL; /* signal action */
1662 sigemptyset( &act.sa_mask ); /* set an empty mask */
1663 act.sa_flags = 0; /* init sa_flags */
1664
1665 for (sig_num = 1; sig_num <= max_sig; ++sig_num)
1666 {
1667#if !defined(SH_PROFILE)
1668 test = retry_sigaction(FIL__, __LINE__, sig_num, &act, &oldact);
1669#else
1670 test = 0;
1671#endif
1672 if ((test == -1) && (errno != EINVAL))
1673 {
1674 char errbuf[SH_ERRBUF_SIZE];
1675 status = errno;
1676 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_SIG,
1677 sh_error_message (status, errbuf, sizeof(errbuf)), sig_num);
1678 }
1679 }
1680
1681 SL_RET0(_("sh_unix_resetsignals"));
1682}
1683
1684/* Get the local hostname (FQDN)
1685 */
1686static char * sh_tolower (char * s)
1687{
1688 char * ret = s;
1689 if (s)
1690 {
1691 for (; *s; ++s)
1692 {
1693 *s = tolower((unsigned char) *s);
1694 }
1695 }
1696 return ret;
1697}
1698
1699
1700#include <sys/socket.h>
1701
1702/* Required for BSD
1703 */
1704#ifdef HAVE_NETINET_IN_H
1705#include <netinet/in.h>
1706#endif
1707
1708#include <arpa/inet.h>
1709
1710const char * sh_unix_h_name (struct hostent * host_entry)
1711{
1712 char ** p;
1713 if (strchr(host_entry->h_name, '.')) {
1714 return host_entry->h_name;
1715 } else {
1716 for (p = host_entry->h_aliases; *p; ++p) {
1717 if (strchr(*p, '.'))
1718 return *p;
1719 }
1720 }
1721 return host_entry->h_name;
1722}
1723
1724/* uname() on FreeBSD is broken, because the 'nodename' buf is too small
1725 * to hold a valid (leftmost) domain label.
1726 */
1727#if defined(HAVE_UNAME) && !defined(HOST_IS_FREEBSD)
1728#include <sys/utsname.h>
1729void sh_unix_localhost()
1730{
1731 struct utsname buf;
1732 int i;
1733 unsigned int ddot;
1734 int len;
1735 char * p;
1736 char hostname[256];
1737 char numeric[SH_IP_BUF];
1738 char * canonical;
1739
1740
1741 SL_ENTER(_("sh_unix_localhost"));
1742
1743 (void) uname (&buf);
1744 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1745 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1746 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1747 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1748
1749 /* Workaround for cases where nodename could be
1750 * a truncated FQDN.
1751 */
1752 if (strlen(buf.nodename) == (sizeof(buf.nodename)-1))
1753 {
1754 p = strchr(buf.nodename, '.');
1755 if (NULL != p) {
1756 *p = '\0';
1757 sl_strlcpy(hostname, buf.nodename, 256);
1758 } else {
1759#ifdef HAVE_GETHOSTNAME
1760 if (0 != gethostname(hostname, 256))
1761 {
1762 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1763 _("nodename returned by uname may be truncated"),
1764 _("sh_unix_localhost"));
1765 sl_strlcpy (hostname, buf.nodename, 256);
1766 }
1767 else
1768 {
1769 hostname[255] = '\0';
1770 }
1771#else
1772 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1773 _("nodename returned by uname may be truncated"),
1774 _("sh_unix_localhost"));
1775 sl_strlcpy(hostname, buf.nodename, 256);
1776#endif
1777 }
1778 }
1779 else
1780 {
1781 sl_strlcpy(hostname, buf.nodename, 256);
1782 }
1783
1784 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1785
1786 if (canonical == NULL)
1787 {
1788 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1789 sh_tolower (sh.host.name);
1790 }
1791 else
1792 {
1793 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1794 SH_FREE(canonical);
1795 }
1796
1797 /* check whether it looks like a FQDN
1798 */
1799 len = sl_strlen(sh.host.name);
1800 ddot = 0;
1801 for (i = 0; i < len; ++i)
1802 if (sh.host.name[i] == '.') ++ddot;
1803
1804 if (ddot == 0)
1805 {
1806 dlog(1, FIL__, __LINE__,
1807 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1808 hostname, sh.host.name);
1809 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1810 SL_RET0(_("sh_unix_localhost"));
1811 }
1812
1813 if (sh_ipvx_is_numeric(sh.host.name))
1814 {
1815 dlog(1, FIL__, __LINE__,
1816 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1817 hostname, sh.host.name);
1818 }
1819
1820 SL_RET0(_("sh_unix_localhost"));
1821}
1822
1823#else
1824
1825/*
1826 * --FreeBSD code
1827 */
1828#if defined(HAVE_UNAME)
1829#include <sys/utsname.h>
1830#endif
1831void sh_unix_localhost()
1832{
1833#if defined(HAVE_UNAME)
1834 struct utsname buf;
1835#endif
1836 int i;
1837 int ddot;
1838 int len;
1839 char hostname[1024];
1840 char numeric[SH_IP_BUF];
1841 char * canonical;
1842
1843 SL_ENTER(_("sh_unix_localhost"));
1844
1845#if defined(HAVE_UNAME)
1846 (void) uname (&buf);
1847 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1848 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1849 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1850 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1851#endif
1852
1853 (void) gethostname (hostname, 1024);
1854 hostname[1023] = '\0';
1855
1856 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1857
1858 if (canonical == NULL)
1859 {
1860 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1861 sh_tolower (sh.host.name);
1862 }
1863 else
1864 {
1865 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1866 SH_FREE(canonical);
1867 }
1868
1869 /* check whether it looks like a FQDN
1870 */
1871 len = sl_strlen(sh.host.name);
1872 ddot = 0;
1873 for (i = 0; i < len; ++i)
1874 if (sh.host.name[i] == '.') ++ddot;
1875 if (ddot == 0)
1876 {
1877 dlog(1, FIL__, __LINE__,
1878 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1879 hostname, sh.host.name);
1880 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1881 SL_RET0(_("sh_unix_localhost"));
1882 }
1883
1884 if (sh_ipvx_is_numeric(sh.host.name))
1885 {
1886 dlog(1, FIL__, __LINE__,
1887 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1888 hostname, sh.host.name);
1889 }
1890
1891 SL_RET0(_("sh_unix_localhost"));
1892}
1893#endif
1894
1895
1896void sh_unix_memlock()
1897{
1898 SL_ENTER(_("sh_unix_memlock"));
1899
1900 /* do this before dropping privileges
1901 */
1902#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
1903 if (skey->mlock_failed == S_FALSE)
1904 {
1905 if ( (-1) == sh_unix_mlock( FIL__, __LINE__,
1906 (char *) skey, sizeof (sh_key_t)) )
1907 {
1908 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1909 skey->mlock_failed = S_TRUE;
1910 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1911 }
1912 }
1913#else
1914 if (skey->mlock_failed == S_FALSE)
1915 {
1916 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1917 skey->mlock_failed = S_TRUE;
1918 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1919 }
1920#endif
1921
1922 SL_RET0(_("sh_unix_memlock"));
1923}
1924
1925#ifdef SH_WITH_SERVER
1926char * chroot_dir = NULL;
1927
1928int sh_unix_set_chroot(const char * str)
1929{
1930 size_t len;
1931 static int block = 0;
1932
1933 if (block == 1)
1934 return 0;
1935
1936 if (str && *str == '/')
1937 {
1938 len = strlen(str) + 1;
1939 chroot_dir = calloc(1,strlen(str) + 1); /* only once */
1940 if (!chroot_dir)
1941 {
1942 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1943 return 1;
1944 }
1945 sl_strlcpy(chroot_dir, str, len);
1946 block = 1;
1947 return 0;
1948 }
1949 return 1;
1950}
1951
1952int sh_unix_chroot(void)
1953{
1954 int status;
1955
1956 if (chroot_dir != NULL)
1957 {
1958 status = retry_aud_chdir(FIL__, __LINE__, chroot_dir);
1959 if ( (-1) == status )
1960 {
1961 char errbuf[SH_ERRBUF_SIZE];
1962 status = errno;
1963 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1964 sh_error_message (status, errbuf, sizeof(errbuf)), chroot_dir);
1965 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1966 }
1967 /* flawfinder: ignore */
1968 return (chroot(chroot_dir));
1969 }
1970 return 0;
1971}
1972/* #ifdef SH_WITH_SERVER */
1973#else
1974int sh_unix_chroot(void) { return 0; }
1975#endif
1976
1977/* daemon mode
1978 */
1979static int block_setdeamon = 0;
1980
1981int sh_unix_setdeamon(const char * dummy)
1982{
1983 int res = 0;
1984
1985 SL_ENTER(_("sh_unix_setdeamon"));
1986
1987 if (block_setdeamon != 0)
1988 SL_RETURN((0),_("sh_unix_setdeamon"));
1989
1990 if (dummy == NULL)
1991 sh.flag.isdaemon = S_TRUE;
1992 else
1993 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1994
1995 if (sh.flag.opts == S_TRUE)
1996 block_setdeamon = 1;
1997
1998 SL_RETURN(res, _("sh_unix_setdeamon"));
1999}
2000#if defined(HAVE_LIBPRELUDE)
2001#include "sh_prelude.h"
2002#endif
2003
2004int sh_unix_setnodeamon(const char * dummy)
2005{
2006 int res = 0;
2007
2008 SL_ENTER(_("sh_unix_setnodeamon"));
2009
2010 if (block_setdeamon != 0)
2011 SL_RETURN((0),_("sh_unix_setmodeamon"));
2012
2013 if (dummy == NULL)
2014 sh.flag.isdaemon = S_FALSE;
2015 else
2016 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
2017
2018 if (sh.flag.opts == S_TRUE)
2019 block_setdeamon = 1;
2020
2021 SL_RETURN(res, _("sh_unix_setnodeamon"));
2022}
2023
2024int sh_unix_init(int goDaemon)
2025{
2026 int status;
2027 uid_t uid;
2028 pid_t oldpid = getpid();
2029#if defined(SH_WITH_SERVER)
2030 extern int sh_socket_open_int (void);
2031#endif
2032 char errbuf[SH_ERRBUF_SIZE];
2033
2034 extern void sh_kill_sub();
2035
2036 SL_ENTER(_("sh_unix_init"));
2037
2038 /* fork twice, exit the parent process
2039 */
2040 if (goDaemon == 1) {
2041
2042 switch (aud_fork(FIL__, __LINE__)) {
2043 case 0: break; /* child process continues */
2044 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
2045 default: /* parent process exits */
2046 sh_kill_sub();
2047 aud__exit(FIL__, __LINE__, 0);
2048 }
2049
2050 /* Child processes do not inherit page locks across a fork.
2051 * Error in next fork would return in this (?) thread of execution.
2052 */
2053 sh_unix_memlock();
2054
2055 setsid(); /* should not fail */
2056 sh.pid = (UINT64) getpid();
2057
2058 switch (aud_fork(FIL__, __LINE__)) {
2059 case 0: break; /* child process continues */
2060 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
2061 default: /* parent process exits */
2062 sh_kill_sub();
2063 aud__exit(FIL__, __LINE__, 0);
2064 }
2065
2066 /* Child processes do not inherit page locks across a fork.
2067 */
2068 sh_unix_memlock();
2069 sh.pid = (UINT64) getpid();
2070
2071 } else {
2072 setsid(); /* should not fail */
2073 }
2074
2075 /* set working directory
2076 */
2077#ifdef SH_PROFILE
2078 status = 0;
2079#else
2080 status = retry_aud_chdir(FIL__, __LINE__, "/");
2081#endif
2082 if ( (-1) == status )
2083 {
2084 status = errno;
2085 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
2086 sh_error_message (status, errbuf, sizeof(errbuf)), "/");
2087 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2088 }
2089
2090 /* reset timers
2091 */
2092 sh_unix_resettimer();
2093
2094 /* signal handlers
2095 */
2096 sh_unix_resetsignals();
2097#if defined(SCREW_IT_UP)
2098 sh_sigtrap_prepare();
2099#endif
2100 sh_unix_siginstall (goDaemon);
2101
2102 /* set file creation mask
2103 */
2104 (void) umask (0); /* should not fail */
2105
2106 /* set resource limits to maximum, and
2107 * core dump size to zero
2108 */
2109 sh_unix_setlimits();
2110
2111 /* zero out the environment (like PATH='\0')
2112 */
2113 sh_unix_zeroenv();
2114
2115 if (goDaemon == 1)
2116 {
2117 /* Close first tree file descriptors
2118 */
2119 sl_close_fd (FIL__, __LINE__, 0); /* if running as daemon */
2120 sl_close_fd (FIL__, __LINE__, 1); /* if running as daemon */
2121 sl_close_fd (FIL__, __LINE__, 2); /* if running as daemon */
2122
2123 /* Enable full error logging
2124 */
2125 sh_error_only_stderr (S_FALSE);
2126
2127 /* open first three streams to /dev/null
2128 */
2129 status = aud_open(FIL__, __LINE__, SL_NOPRIV, _("/dev/null"), O_RDWR, 0);
2130 if (status < 0)
2131 {
2132 status = errno;
2133 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2134 sh_error_message(status, errbuf, sizeof(errbuf)), _("open"));
2135 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2136 }
2137
2138 status = retry_aud_dup(FIL__, __LINE__, 0);
2139 if (status >= 0)
2140 retry_aud_dup(FIL__, __LINE__, 0);
2141
2142 if (status < 0)
2143 {
2144 status = errno;
2145 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2146 sh_error_message(status, errbuf, sizeof(errbuf)), _("dup"));
2147 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2148 }
2149
2150 sh_error_enable_unsafe (S_TRUE);
2151#if defined(HAVE_LIBPRELUDE)
2152 sh_prelude_reset ();
2153#endif
2154
2155 /* --- wait until parent has exited ---
2156 */
2157 while (1 == 1)
2158 {
2159 errno = 0;
2160 if (0 > aud_kill (FIL__, __LINE__, oldpid, 0) && errno == ESRCH)
2161 {
2162 break;
2163 }
2164 retry_msleep(0, 1);
2165 }
2166
2167 /* write PID file
2168 */
2169 status = sh_unix_write_pid_file();
2170 if (status < 0)
2171 {
2172 sl_get_euid(&uid);
2173 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_PIDFILE,
2174 (long) uid, sh.srvlog.alt);
2175 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2176 }
2177#if defined(SH_WITH_SERVER)
2178 sh_socket_open_int ();
2179#endif
2180 }
2181 else
2182 {
2183 sh_error_enable_unsafe (S_TRUE);
2184#if defined(HAVE_LIBPRELUDE)
2185 sh_prelude_reset ();
2186#endif
2187#if defined(SH_WITH_SERVER)
2188 sh_socket_open_int ();
2189#endif
2190 }
2191
2192 /* chroot (this is a no-op if no chroot dir is specified
2193 */
2194 status = sh_unix_chroot();
2195 if (status < 0)
2196 {
2197 status = errno;
2198 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2199 sh_error_message(status, errbuf, sizeof(errbuf)), _("chroot"));
2200 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2201 }
2202
2203 /* drop capabilities
2204 */
2205 sl_drop_cap();
2206
2207 SL_RETURN((0),_("sh_unix_init"));
2208}
2209
2210/* --- run a command, securely --- */
2211
2212int sh_unix_run_command (const char * str)
2213{
2214 pid_t pid;
2215 char * arg[4];
2216 char * env[5];
2217 char * path = sh_util_strdup(_("/bin/sh"));
2218
2219 int status = -1;
2220
2221 arg[0] = sh_util_strdup(_("/bin/sh"));
2222 arg[1] = sh_util_strdup(_("-c"));
2223 arg[2] = sh_util_strdup(str);
2224 arg[3] = NULL;
2225
2226 env[0] = sh_util_strdup(_("PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/ucb"));
2227 env[1] = sh_util_strdup(_("SHELL=/bin/sh"));
2228 env[2] = sh_util_strdup(_("IFS= \t\n"));
2229 if (getenv("TZ")) { /* flawfinder: ignore */
2230 char * tz = sh_util_strdup(getenv("TZ")); /* flawfinder: ignore */
2231 size_t tzlen = strlen(tz);
2232 if (S_TRUE == sl_ok_adds (4, tzlen)) {
2233 env[3] = SH_ALLOC(4+tzlen);
2234 sl_strlcpy(env[3], "TZ=", 4);
2235 sl_strlcat(env[3], tz , 4+tzlen);
2236 } else {
2237 env[3] = NULL;
2238 }
2239 } else {
2240 env[3] = NULL;
2241 }
2242 env[4] = NULL;
2243
2244 pid = fork();
2245
2246 if (pid == (pid_t)(-1))
2247 {
2248 return -1;
2249 }
2250
2251 else if (pid == 0) /* child */
2252 {
2253 memset(skey, 0, sizeof(sh_key_t));
2254 (void) umask(S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
2255 sh_unix_closeall (3, -1, S_TRUE); /* in child process */
2256 execve(path, arg, env);
2257 _exit(EXIT_FAILURE);
2258 }
2259
2260 else /* parent */
2261 {
2262 int r;
2263
2264 while((r = waitpid(pid, &status, WUNTRACED)) != pid && r != -1) ;
2265
2266#if !defined(USE_UNO)
2267 if (r == -1 || !WIFEXITED(status))
2268 {
2269 status = -1;
2270 }
2271 else
2272 {
2273 status = WEXITSTATUS(status);
2274 }
2275#endif
2276 }
2277
2278 return status;
2279}
2280
2281/********************************************************
2282 *
2283 * TIME
2284 *
2285 ********************************************************/
2286
2287/* Figure out the time offset of the current timezone
2288 * in a portable way.
2289 */
2290char * t_zone(const time_t * xx)
2291{
2292 struct tm aa;
2293 struct tm bb;
2294
2295 struct tm * aptr;
2296 struct tm * bptr;
2297
2298 int sign = 0;
2299 int diff = 0;
2300 int hh, mm;
2301 static char tz[64];
2302
2303 SL_ENTER(_("t_zone"));
2304
2305#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2306 aptr = gmtime_r (xx, &aa);
2307#else
2308 aptr = gmtime(xx);
2309 if (aptr)
2310 memcpy (&aa, aptr, sizeof(struct tm));
2311#endif
2312
2313#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2314 bptr = localtime_r (xx, &bb);
2315#else
2316 bptr = localtime(xx);
2317 if (bptr)
2318 memcpy (&bb, bptr, sizeof(struct tm));
2319#endif
2320
2321 if (bptr && aptr)
2322 {
2323 /* Check for datum wrap-around.
2324 */
2325 if ((aa.tm_mday == 1) && (aa.tm_mday < bb.tm_mday) && (aa.tm_hour < bb.tm_hour))
2326 sign = ( 1);
2327 else if (aa.tm_year < bb.tm_year)
2328 sign = (-1);
2329 else if (aa.tm_mon < bb.tm_mon)
2330 sign = (-1);
2331 else if (aa.tm_mday < bb.tm_mday)
2332 sign = (-1);
2333 else if (bb.tm_year < aa.tm_year)
2334 sign = ( 1);
2335 else if (bb.tm_mon < aa.tm_mon)
2336 sign = ( 1);
2337 else if (bb.tm_mday < aa.tm_mday)
2338 sign = ( 1);
2339
2340 diff = aa.tm_hour * 60 + aa.tm_min;
2341 diff = (bb.tm_hour * 60 + bb.tm_min) - diff;
2342 diff = diff - (sign * 24 * 60); /* datum wrap-around correction */
2343 hh = diff / 60;
2344 mm = diff - (hh * 60);
2345 sprintf (tz, _("%+03d%02d"), hh, mm); /* known to fit */
2346 }
2347 else
2348 {
2349 sprintf (tz, _("%+03d%02d"), 0, 0);
2350 }
2351 SL_RETURN(tz, _("t_zone"));
2352}
2353
2354unsigned long sh_unix_longtime ()
2355{
2356 return ((unsigned long)time(NULL));
2357}
2358
2359#ifdef HAVE_GETTIMEOFDAY
2360unsigned long sh_unix_notime ()
2361{
2362 struct timeval tv;
2363
2364 gettimeofday (&tv, NULL);
2365
2366 return ((unsigned long)(tv.tv_sec + tv.tv_usec * 10835 + getpid() + getppid()));
2367
2368}
2369#endif
2370
2371static int count_dev_time = 0;
2372
2373void reset_count_dev_time(void)
2374{
2375 count_dev_time = 0;
2376 return;
2377}
2378
2379int sh_unix_settimeserver (const char * address)
2380{
2381
2382 SL_ENTER(_("sh_unix_settimeserver"));
2383
2384 if (address != NULL && count_dev_time < 2
2385 && sl_strlen(address) < SH_PATHBUF)
2386 {
2387 if (count_dev_time == 0)
2388 sl_strlcpy (sh.srvtime.name, address, SH_PATHBUF);
2389 else
2390 sl_strlcpy (sh.srvtime.alt, address, SH_PATHBUF);
2391
2392 ++count_dev_time;
2393 SL_RETURN((0), _("sh_unix_settimeserver"));
2394 }
2395 SL_RETURN((-1), _("sh_unix_settimeserver"));
2396}
2397
2398
2399#ifdef HAVE_NTIME
2400#define UNIXEPOCH 2208988800UL /* difference between Unix time and net time
2401 * The UNIX EPOCH starts in 1970.
2402 */
2403#include <sys/socket.h>
2404#include <netinet/in.h>
2405#include <arpa/inet.h>
2406#include <netdb.h>
2407#include <ctype.h>
2408#endif
2409
2410/* Timeserver service. */
2411/* define is missing on HP-UX 10.20 */
2412#ifndef IPPORT_TIMESERVER
2413#define IPPORT_TIMESERVER 37
2414#endif
2415
2416char * sh_unix_time (time_t thetime, char * buffer, size_t len)
2417{
2418
2419 int status;
2420 char AsciiTime[81]; /* local time */
2421 time_t time_now;
2422 struct tm * time_ptr;
2423#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2424 struct tm time_tm;
2425#endif
2426#ifdef SH_USE_XML
2427 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2428#else
2429 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2430#endif
2431
2432#ifdef HAVE_NTIME
2433 int fd; /* network file descriptor */
2434 u_char net_time[4]; /* remote time in network format */
2435 static int failerr = 0; /* no net time */
2436 int fail = 0; /* no net time */
2437 int errflag;
2438 char errmsg[256];
2439 char error_call[SH_MINIBUF];
2440 int error_num;
2441#endif
2442
2443 SL_ENTER(_("sh_unix_time"));
2444
2445#ifdef HAVE_NTIME
2446 if (thetime == 0)
2447 {
2448 if (sh.srvtime.name[0] == '\0')
2449 {
2450 fail = 1;
2451 (void) time (&time_now);
2452 }
2453 else /* have a timeserver address */
2454 {
2455 /* don't call timeserver more than once per second */
2456 static time_t time_old = 0;
2457 time_t time_new;
2458 static time_t time_saved = 0;
2459 (void) time (&time_new);
2460 if ((time_new == time_old) && (time_saved != 0))
2461 {
2462 time_now = time_saved;
2463 goto end;
2464 }
2465 time_old = time_new;
2466
2467
2468 fd = connect_port_2 (sh.srvtime.name, sh.srvtime.alt,
2469 IPPORT_TIMESERVER,
2470 error_call, &error_num, errmsg, sizeof(errmsg));
2471 if (fd >= 0)
2472 {
2473 if (4 != read_port (fd, (char *) net_time, 4, &errflag, 2))
2474 {
2475 fail = 1;
2476 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2477 MSG_E_NLOST,
2478 _("time"), sh.srvtime.name);
2479 }
2480 sl_close_fd(FIL__, __LINE__, fd);
2481 }
2482 else
2483 {
2484 sh_error_handle ((-1), FIL__, __LINE__, error_num,
2485 MSG_E_NET, errmsg, error_call,
2486 _("time"), sh.srvtime.name);
2487 fail = 1;
2488 }
2489
2490 if (fail == 0)
2491 {
2492 unsigned long ltmp;
2493 UINT32 ttmp;
2494 memcpy(&ttmp, net_time, sizeof(UINT32)); ltmp = ttmp;
2495 time_now = ntohl(ltmp) - UNIXEPOCH;
2496 time_saved = time_now;
2497
2498 if (failerr == 1) {
2499 failerr = 0;
2500 sh_error_handle ((-1), FIL__, __LINE__, 0,
2501 MSG_E_NEST,
2502 _("time"), sh.srvtime.name);
2503 }
2504 }
2505 else
2506 {
2507 (void) time (&time_now);
2508 time_saved = 0;
2509
2510 if (failerr == 0)
2511 {
2512 failerr = 1;
2513 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2514 MSG_SRV_FAIL,
2515 _("time"), sh.srvtime.name);
2516 }
2517 }
2518 end:
2519 ; /* 'label at end of compound statement' */
2520 }
2521 }
2522 else
2523 {
2524 time_now = thetime;
2525 }
2526
2527 /* #ifdef HAVE_NTIME */
2528#else
2529
2530 if (thetime == 0)
2531 {
2532 (void) time (&time_now);
2533 }
2534 else
2535 {
2536 time_now = thetime;
2537 }
2538
2539 /* #ifdef HAVE_NTIME */
2540#endif
2541
2542 if (time_now == (-1) )
2543 {
2544 sl_strlcpy(buffer, _(deftime), len);
2545 SL_RETURN(buffer, _("sh_unix_time"));
2546 }
2547 else
2548 {
2549#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2550 time_ptr = localtime_r (&time_now, &time_tm);
2551#else
2552 time_ptr = localtime (&time_now);
2553#endif
2554 }
2555 if (time_ptr != NULL)
2556 {
2557 status = strftime (AsciiTime, sizeof(AsciiTime),
2558#ifdef SH_USE_XML
2559 _("%Y-%m-%dT%H:%M:%S%%s"),
2560#else
2561 _("[%Y-%m-%dT%H:%M:%S%%s]"),
2562#endif
2563 time_ptr);
2564
2565 sl_snprintf(buffer, len, AsciiTime, t_zone(&time_now));
2566
2567 if ( (status == 0) || (status == sizeof(AsciiTime)) )
2568 {
2569 sl_strlcpy(buffer, _(deftime), len);
2570 SL_RETURN( buffer, _("sh_unix_time"));
2571 }
2572 else
2573 {
2574 SL_RETURN(buffer, _("sh_unix_time"));
2575 }
2576 }
2577
2578 /* last resort
2579 */
2580 sl_strlcpy(buffer, _(deftime), len);
2581 SL_RETURN( buffer, _("sh_unix_time"));
2582}
2583
2584static int sh_unix_use_localtime = S_FALSE;
2585
2586/* whether to use localtime for file timestamps in logs
2587 */
2588int sh_unix_uselocaltime (const char * c)
2589{
2590 int i;
2591 SL_ENTER(_("sh_unix_uselocaltime"));
2592 i = sh_util_flagval(c, &(sh_unix_use_localtime));
2593
2594 SL_RETURN(i, _("sh_unix_uselocaltime"));
2595}
2596
2597char * sh_unix_gmttime (time_t thetime, char * buffer, size_t len)
2598{
2599
2600 int status;
2601
2602 struct tm * time_ptr;
2603#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS)
2604 struct tm time_tm;
2605#endif
2606 char AsciiTime[81]; /* GMT time */
2607#ifdef SH_USE_XML
2608 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2609#else
2610 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2611#endif
2612
2613 SL_ENTER(_("sh_unix_gmttime"));
2614
2615 if (sh_unix_use_localtime == S_FALSE)
2616 {
2617#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2618 time_ptr = gmtime_r (&thetime, &time_tm);
2619#else
2620 time_ptr = gmtime (&thetime);
2621#endif
2622 }
2623 else
2624 {
2625#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2626 time_ptr = localtime_r (&thetime, &time_tm);
2627#else
2628 time_ptr = localtime (&thetime);
2629#endif
2630 }
2631 if (time_ptr != NULL)
2632 {
2633 status = strftime (AsciiTime, 80,
2634#ifdef SH_USE_XML
2635 _("%Y-%m-%dT%H:%M:%S"),
2636#else
2637 _("[%Y-%m-%dT%H:%M:%S]"),
2638#endif
2639 time_ptr);
2640
2641 if ( (status == 0) || (status == 80) )
2642 sl_strlcpy(buffer, _(deftime), len);
2643 else
2644 sl_strlcpy(buffer, AsciiTime, len);
2645 SL_RETURN( buffer, _("sh_unix_gmttime"));
2646 }
2647
2648 /* last resort
2649 */
2650 sl_strlcpy(buffer, _(deftime), len);
2651 SL_RETURN( buffer, _("sh_unix_gmttime"));
2652}
2653
2654
2655char * sh_unix_getUIDdir (int level, uid_t uid, char * out, size_t len)
2656{
2657 struct passwd * tempres;
2658 int status = 0;
2659
2660#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2661 struct passwd pwd;
2662 char * buffer;
2663#endif
2664 char errbuf[SH_ERRBUF_SIZE];
2665
2666 SL_ENTER(_("sh_unix_getUIDdir"));
2667
2668#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2669 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2670 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2671#else
2672 errno = 0;
2673 tempres = sh_getpwuid(uid);
2674 status = errno;
2675#endif
2676
2677 if (tempres == NULL) {
2678 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2679 sh_error_message(status, errbuf, sizeof(errbuf)),
2680 _("getpwuid"), (long) uid, _("completely missing"));
2681#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2682 SH_FREE(buffer);
2683#endif
2684 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2685 }
2686
2687 if (tempres->pw_dir != NULL) {
2688 sl_strlcpy(out, tempres->pw_dir, len);
2689#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2690 SH_FREE(buffer);
2691#endif
2692 SL_RETURN( out, _("sh_unix_getUIDdir"));
2693 } else {
2694 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2695 sh_error_message(status, errbuf, sizeof(errbuf)),
2696 _("getpwuid"), (long) uid, _("pw_dir"));
2697#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2698 SH_FREE(buffer);
2699#endif
2700 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2701 }
2702}
2703
2704/* ------------------- Caching ----------------*/
2705#include "zAVLTree.h"
2706
2707#define CACHE_GID 0
2708#define CACHE_UID 1
2709
2710struct user_id {
2711 char * name;
2712 uid_t id;
2713 struct user_id * next;
2714};
2715
2716static struct user_id * uid_list = NULL;
2717static struct user_id * gid_list = NULL;
2718
2719SH_MUTEX_STATIC(mutex_cache, PTHREAD_MUTEX_INITIALIZER);
2720
2721static void sh_userid_free(struct user_id * item)
2722{
2723 while (item)
2724 {
2725 struct user_id * user = item;
2726 item = item->next;
2727
2728 SH_FREE(user->name);
2729 SH_FREE(user);
2730 }
2731 return;
2732}
2733
2734void sh_userid_destroy ()
2735{
2736 struct user_id * tmp_uid;
2737 struct user_id * tmp_gid;
2738
2739 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2740 tmp_gid = gid_list;
2741 gid_list = NULL;
2742 tmp_uid = uid_list;
2743 uid_list = NULL;
2744 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2745
2746 sh_userid_free(tmp_uid);
2747 sh_userid_free(tmp_gid);
2748 return;
2749}
2750
2751static void sh_userid_additem(struct user_id * list, struct user_id * item)
2752{
2753 if (list)
2754 {
2755 while (list && list->next)
2756 list = list->next;
2757 list->next = item;
2758 }
2759 return;
2760}
2761
2762static void sh_userid_add(uid_t id, char * username, int which)
2763{
2764 size_t len;
2765 struct user_id * user = SH_ALLOC(sizeof(struct user_id));
2766
2767 if (username)
2768 len = strlen(username) + 1;
2769 else
2770 len = 1;
2771
2772 user->name = SH_ALLOC(len);
2773 user->id = id;
2774 if (username)
2775 sl_strlcpy(user->name, username, len);
2776 else
2777 user->name[0] = '\0';
2778 user->next = NULL;
2779
2780 SH_MUTEX_LOCK(mutex_cache);
2781 if (which == CACHE_UID)
2782 {
2783 if (!uid_list)
2784 uid_list = user;
2785 else
2786 sh_userid_additem(uid_list, user);
2787 }
2788 else
2789 {
2790 if (!gid_list)
2791 gid_list = user;
2792 else
2793 sh_userid_additem(gid_list, user);
2794 }
2795 SH_MUTEX_UNLOCK(mutex_cache);
2796
2797 return;
2798}
2799
2800static char * sh_userid_search(struct user_id * list, uid_t id)
2801{
2802 while (list)
2803 {
2804 if (list->id == id)
2805 return list->name;
2806 list = list->next;
2807 }
2808 return NULL;
2809}
2810
2811static char * sh_userid_get (uid_t id, int which, char * out, size_t len)
2812{
2813 char * user = NULL;
2814
2815 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2816 if (which == CACHE_UID)
2817 user = sh_userid_search(uid_list, id);
2818 else
2819 user = sh_userid_search(gid_list, id);
2820 if (user)
2821 {
2822 sl_strlcpy(out, user, len);
2823 user = out;
2824 }
2825 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2826
2827 return user;
2828}
2829
2830/* --------- end caching code --------- */
2831
2832char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len)
2833{
2834 struct passwd * tempres;
2835#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2836 struct passwd pwd;
2837 char * buffer;
2838#endif
2839 int status = 0;
2840 char errbuf[SH_ERRBUF_SIZE];
2841 char * tmp;
2842
2843 SL_ENTER(_("sh_unix_getUIDname"));
2844
2845 tmp = sh_userid_get(uid, CACHE_UID, out, len);
2846
2847 if (tmp)
2848 {
2849 if (tmp[0] != '\0')
2850 {
2851 SL_RETURN( out, _("sh_unix_getUIDname"));
2852 }
2853 else
2854 {
2855 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2856 }
2857 }
2858
2859#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2860 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2861 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2862#else
2863 errno = 0;
2864 tempres = sh_getpwuid(uid);
2865 status = errno;
2866#endif
2867
2868 if (tempres == NULL)
2869 {
2870 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2871 sh_error_message(status, errbuf, sizeof(errbuf)),
2872 _("getpwuid"), (long) uid, _("completely missing"));
2873#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2874 SH_FREE(buffer);
2875#endif
2876 sh_userid_add(uid, NULL, CACHE_UID);
2877 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2878 }
2879
2880
2881 if (tempres->pw_name != NULL)
2882 {
2883
2884 sl_strlcpy(out, tempres->pw_name, len);
2885 sh_userid_add(uid, out, CACHE_UID);
2886
2887#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2888 SH_FREE(buffer);
2889#endif
2890
2891 SL_RETURN( out, _("sh_unix_getUIDname"));
2892 }
2893 else
2894 {
2895 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2896 sh_error_message(status, errbuf, sizeof(errbuf)),
2897 _("getpwuid"), (long) uid, _("pw_user"));
2898#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2899 SH_FREE(buffer);
2900#endif
2901 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2902 }
2903 /* notreached */
2904}
2905
2906char * sh_unix_getGIDname (int level, gid_t gid, char * out, size_t len)
2907{
2908 struct group * tempres;
2909 int status = 0;
2910
2911#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2912 struct group grp;
2913 char * buffer;
2914#endif
2915 char errbuf[SH_ERRBUF_SIZE];
2916 char * tmp;
2917
2918 SL_ENTER(_("sh_unix_getGIDname"));
2919
2920 tmp = sh_userid_get((uid_t)gid, CACHE_GID, out, len);
2921
2922 if (tmp)
2923 {
2924 if (tmp[0] != '\0')
2925 {
2926 SL_RETURN( out, _("sh_unix_getGIDname"));
2927 }
2928 else
2929 {
2930 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2931 }
2932 }
2933
2934#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2935 buffer = SH_ALLOC(SH_GRBUF_SIZE);
2936 status = sh_getgrgid_r(gid, &grp, buffer, SH_GRBUF_SIZE, &tempres);
2937#else
2938 errno = 0;
2939 tempres = sh_getgrgid(gid);
2940 status = errno;
2941#endif
2942
2943 if (status == ERANGE)
2944 {
2945 static int seen = 0;
2946
2947 if (seen == 0)
2948 {
2949 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2950 sh_error_message(status, errbuf, sizeof(errbuf)),
2951 _("getgrgid"), (long) gid, _("line too long in group entry"));
2952 ++seen;
2953 }
2954
2955#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2956 SH_FREE(buffer);
2957#endif
2958
2959 sh_userid_add(gid, NULL, CACHE_GID);
2960 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2961 }
2962
2963 if (tempres == NULL)
2964 {
2965 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2966 sh_error_message(status, errbuf, sizeof(errbuf)),
2967 _("getgrgid"), (long) gid, _("completely missing"));
2968
2969#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2970 SH_FREE(buffer);
2971#endif
2972
2973 sh_userid_add(gid, NULL, CACHE_GID);
2974 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2975 }
2976
2977 if (tempres->gr_name != NULL)
2978 {
2979
2980 sl_strlcpy(out, tempres->gr_name, len);
2981 sh_userid_add((uid_t)gid, out, CACHE_GID);
2982
2983#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2984 SH_FREE(buffer);
2985#endif
2986
2987 SL_RETURN( out, _("sh_unix_getGIDname"));
2988 }
2989 else
2990 {
2991 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2992 sh_error_message(status, errbuf, sizeof(errbuf)),
2993 _("getgrgid"), (long) gid, _("gr_name"));
2994
2995#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2996 SH_FREE(buffer);
2997#endif
2998
2999 SL_RETURN( NULL, _("sh_unix_getGIDname"));
3000 }
3001 /* notreached */
3002}
3003
3004int sh_unix_getUser ()
3005{
3006 char * p;
3007 uid_t seuid, sruid;
3008 char user[USER_MAX];
3009 char dir[SH_PATHBUF];
3010
3011 SL_ENTER(_("sh_unix_getUser"));
3012
3013 seuid = geteuid();
3014
3015 sh.effective.uid = seuid;
3016
3017 p = sh_unix_getUIDdir (SH_ERR_ERR, seuid, dir, sizeof(dir));
3018
3019 if (p == NULL)
3020 SL_RETURN((-1), _("sh_unix_getUser"));
3021 else
3022 {
3023 if (sl_strlen(p) >= SH_PATHBUF) {
3024 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
3025 _("getpwuid"), (long) seuid, _("pw_home"));
3026 SL_RETURN((-1), _("sh_unix_getUser"));
3027 } else {
3028 sl_strlcpy ( sh.effective.home, p, SH_PATHBUF);
3029 }
3030 }
3031
3032 sruid = getuid();
3033
3034 sh.real.uid = sruid;
3035
3036 p = sh_unix_getUIDname (SH_ERR_ERR, sruid, user, sizeof(user));
3037 if (p == NULL)
3038 SL_RETURN((-1), _("sh_unix_getUser"));
3039 else
3040 {
3041 if (sl_strlen(p) >= USER_MAX) {
3042 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
3043 _("getpwuid"), (long) sruid, _("pw_user"));
3044 SL_RETURN((-1), _("sh_unix_getUser"));
3045 } else {
3046 sl_strlcpy ( sh.real.user, p, USER_MAX);
3047 }
3048 }
3049
3050 p = sh_unix_getUIDdir (SH_ERR_ERR, sruid, dir, sizeof(dir));
3051
3052 if (p == NULL)
3053 SL_RETURN((-1), _("sh_unix_getUser"));
3054 else
3055 {
3056 if (sl_strlen(p) >= SH_PATHBUF) {
3057 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
3058 _("getpwuid"), (long) sruid, _("pw_home"));
3059 SL_RETURN((-1), _("sh_unix_getUser"));
3060 } else {
3061 sl_strlcpy ( sh.real.home, p, SH_PATHBUF);
3062 }
3063 }
3064
3065 SL_RETURN((0), _("sh_unix_getUser"));
3066
3067 /* notreached */
3068}
3069
3070
3071int sh_unix_getline (SL_TICKET fd, char * line, int sizeofline)
3072{
3073 register int count;
3074 register int n = 0;
3075 char c;
3076
3077 SL_ENTER(_("sh_unix_getline"));
3078
3079 if (sizeofline < 2) {
3080 line[0] = '\0';
3081 SL_RETURN((0), _("sh_unix_getline"));
3082 }
3083
3084 --sizeofline;
3085
3086 while (n < sizeofline) {
3087
3088 count = sl_read (fd, &c, 1);
3089
3090 /* end of file
3091 */
3092 if (count < 1) {
3093 line[n] = '\0';
3094 n = -1;
3095 break;
3096 }
3097
3098 if (/* c != '\0' && */ c != '\n') {
3099 line[n] = c;
3100 ++n;
3101 } else if (c == '\n') {
3102 if (n > 0) {
3103 line[n] = '\0';
3104 break;
3105 } else {
3106 line[n] = '\n'; /* get newline only if only char on line */
3107 ++n;
3108 line[n] = '\0';
3109 break;
3110 }
3111 } else {
3112 line[n] = '\0';
3113 break;
3114 }
3115
3116 }
3117
3118
3119 line[sizeofline] = '\0'; /* make sure line is terminated */
3120 SL_RETURN((n), _("sh_unix_getline"));
3121}
3122
3123
3124#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
3125
3126/**************************************************************
3127 *
3128 * --- FILE INFO ---
3129 *
3130 **************************************************************/
3131
3132#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
3133
3134#if defined(__linux__)
3135
3136/* --- Determine ext2fs file attributes. ---
3137 */
3138#include <sys/ioctl.h>
3139#if defined(HAVE_EXT2FS_EXT2_FS_H)
3140#include <ext2fs/ext2_fs.h>
3141#else
3142#include <linux/ext2_fs.h>
3143#endif
3144
3145/* __linux__ includes */
3146#endif
3147
3148static
3149int sh_unix_getinfo_attr (char * name,
3150 unsigned long * flags,
3151 char * c_attr,
3152 int fd, struct stat * buf)
3153{
3154
3155/* TAKEN FROM:
3156 *
3157 * lsattr.c - List file attributes on an ext2 file system
3158 *
3159 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
3160 * Laboratoire MASI, Institut Blaise Pascal
3161 * Universite Pierre et Marie Curie (Paris VI)
3162 *
3163 * This file can be redistributed under the terms of the GNU General
3164 * Public License
3165 */
3166
3167#ifdef HAVE_STAT_FLAGS
3168
3169 SL_ENTER(_("sh_unix_getinfo_attr"));
3170
3171 *flags = 0;
3172
3173 /* cast to void to avoid compiler warning about unused parameters */
3174 (void) fd;
3175 (void) name;
3176
3177#ifdef UF_NODUMP
3178 if (buf->st_flags & UF_NODUMP) {
3179 *flags |= UF_NODUMP;
3180 c_attr[0] = 'd';
3181 }
3182#endif
3183#ifdef UF_IMMUTABLE
3184 if (buf->st_flags & UF_IMMUTABLE) {
3185 *flags |= UF_IMMUTABLE;
3186 c_attr[1] = 'i';
3187 }
3188#endif
3189#ifdef UF_APPEND
3190 if (buf->st_flags & UF_APPEND) {
3191 *flags |= UF_APPEND;
3192 c_attr[2] = 'a';
3193 }
3194#endif
3195#ifdef UF_NOUNLINK
3196 if (buf->st_flags & UF_NOUNLINK) {
3197 *flags |= UF_NOUNLINK;
3198 c_attr[3] = 'u';
3199 }
3200#endif
3201#ifdef UF_OPAQUE
3202 if (buf->st_flags & UF_OPAQUE) {
3203 *flags |= UF_OPAQUE;
3204 c_attr[4] = 'o';
3205 }
3206#endif
3207#ifdef SF_ARCHIVED
3208 if (buf->st_flags & SF_ARCHIVED) {
3209 *flags |= SF_ARCHIVED;
3210 c_attr[5] = 'R';
3211 }
3212
3213#endif
3214#ifdef SF_IMMUTABLE
3215 if (buf->st_flags & SF_IMMUTABLE) {
3216 *flags |= SF_IMMUTABLE;
3217 c_attr[6] = 'I';
3218 }
3219#endif
3220#ifdef SF_APPEND
3221 if (buf->st_flags & SF_APPEND) {
3222 *flags |= SF_APPEND;
3223 c_attr[7] = 'A';
3224 }
3225#endif
3226#ifdef SF_NOUNLINK
3227 if (buf->st_flags & SF_NOUNLINK) {
3228 *flags |= SF_NOUNLINK;
3229 c_attr[8] = 'U';
3230 }
3231#endif
3232
3233 /* ! HAVE_STAT_FLAGS */
3234#else
3235
3236#ifdef HAVE_EXT2_IOCTLS
3237 int /* fd, */ r, f;
3238
3239 SL_ENTER(_("sh_unix_getinfo_attr"));
3240
3241 *flags = 0;
3242 (void) buf;
3243
3244 /* open() -> aud_open() R.Wichmann
3245 fd = aud_open (FIL__, __LINE__, SL_YESPRIV, name, O_RDONLY|O_NONBLOCK, 0);
3246 */
3247
3248 if (fd == -1 || name == NULL)
3249 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3250
3251
3252 r = ioctl (fd, EXT2_IOC_GETFLAGS, &f);
3253 /* sl_close_fd (FIL__, __LINE__, fd); */
3254
3255 if (r == -1)
3256 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3257
3258 if (f == 0)
3259 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3260
3261 *flags = f;
3262
3263/* ! HAVE_EXT2_IOCTLS */
3264#else
3265
3266 SL_ENTER(_("sh_unix_getinfo_attr"));
3267
3268 *flags = 0; /* modified by R.Wichmann */
3269
3270/* ! HAVE_EXT2_IOCTLS */
3271#endif
3272/*
3273 * END
3274 *
3275 * lsattr.c - List file attributes on an ext2 file system
3276 */
3277
3278 if (*flags == 0)
3279 goto theend;
3280
3281#ifdef EXT2_SECRM_FL
3282 if ( (*flags & EXT2_SECRM_FL) != 0 ) c_attr[0] = 's';
3283#endif
3284#ifdef EXT2_UNRM_FL
3285 if ( (*flags & EXT2_UNRM_FL) != 0 ) c_attr[1] = 'u';
3286#endif
3287#ifdef EXT2_SYNC_FL
3288 if ( (*flags & EXT2_SYNC_FL) != 0 ) c_attr[2] = 'S';
3289#endif
3290#ifdef EXT2_IMMUTABLE_FL
3291 if ( (*flags & EXT2_IMMUTABLE_FL) != 0) c_attr[3] = 'i';
3292#endif
3293#ifdef EXT2_APPEND_FL
3294 if ( (*flags & EXT2_APPEND_FL) != 0 ) c_attr[4] = 'a';
3295#endif
3296#ifdef EXT2_NODUMP_FL
3297 if ( (*flags & EXT2_NODUMP_FL) != 0 ) c_attr[5] = 'd';
3298#endif
3299#ifdef EXT2_NOATIME_FL
3300 if ( (*flags & EXT2_NOATIME_FL) != 0) c_attr[6] = 'A';
3301#endif
3302#ifdef EXT2_COMPR_FL
3303 if ( (*flags & EXT2_COMPR_FL) != 0 ) c_attr[7] = 'c';
3304#endif
3305
3306#ifdef EXT2_TOPDIR_FL
3307 if ( (*flags & EXT2_TOPDIR_FL) != 0 ) c_attr[8] = 'T';
3308#endif
3309#ifdef EXT2_DIRSYNC_FL
3310 if ( (*flags & EXT2_DIRSYNC_FL) != 0 ) c_attr[9] = 'D';
3311#endif
3312#ifdef EXT2_NOTAIL_FL
3313 if ( (*flags & EXT2_NOTAIL_FL) != 0 ) c_attr[10] = 't';
3314#endif
3315#ifdef EXT2_JOURNAL_DATA_FL
3316 if ( (*flags & EXT2_JOURNAL_DATA_FL) != 0) c_attr[11] = 'j';
3317#endif
3318
3319 theend:
3320 /* ext2 */
3321#endif
3322
3323 c_attr[12] = '\0';
3324
3325 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3326}
3327
3328/* defined(__linux__) || defined(HAVE_STAT_FLAGS) */
3329#endif
3330
3331/* determine file type
3332 */
3333static
3334int sh_unix_getinfo_type (struct stat * buf,
3335 ShFileType * type,
3336 char * c_mode)
3337{
3338 SL_ENTER(_("sh_unix_getinfo_type"));
3339
3340 if ( S_ISREG(buf->st_mode) ) {
3341 (*type) = SH_FILE_REGULAR;
3342 c_mode[0] = '-';
3343 }
3344 else if ( S_ISLNK(buf->st_mode) ) {
3345 (*type) = SH_FILE_SYMLINK;
3346 c_mode[0] = 'l';
3347 }
3348 else if ( S_ISDIR(buf->st_mode) ) {
3349 (*type) = SH_FILE_DIRECTORY;
3350 c_mode[0] = 'd';
3351 }
3352 else if ( S_ISCHR(buf->st_mode) ) {
3353 (*type) = SH_FILE_CDEV;
3354 c_mode[0] = 'c';
3355 }
3356 else if ( S_ISBLK(buf->st_mode) ) {
3357 (*type) = SH_FILE_BDEV;
3358 c_mode[0] = 'b';
3359 }
3360 else if ( S_ISFIFO(buf->st_mode) ) {
3361 (*type) = SH_FILE_FIFO;
3362 c_mode[0] = '|';
3363 }
3364 else if ( S_ISSOCK(buf->st_mode) ) {
3365 (*type) = SH_FILE_SOCKET;
3366 c_mode[0] = 's';
3367 }
3368 else if ( S_ISDOOR(buf->st_mode) ) {
3369 (*type) = SH_FILE_DOOR;
3370 c_mode[0] = 'D';
3371 }
3372 else if ( S_ISPORT(buf->st_mode) ) {
3373 (*type) = SH_FILE_PORT;
3374 c_mode[0] = 'P';
3375 }
3376 else {
3377 (*type) = SH_FILE_UNKNOWN;
3378 c_mode[0] = '?';
3379 }
3380
3381 SL_RETURN(0, _("sh_unix_getinfo_type"));
3382}
3383
3384int sh_unix_get_ftype(char * fullpath)
3385{
3386 char c_mode[CMODE_SIZE];
3387 struct stat buf;
3388 ShFileType type;
3389 int res;
3390
3391 SL_ENTER(_("sh_unix_get_ftype"));
3392
3393 res = retry_lstat(FIL__, __LINE__, fullpath, &buf);
3394
3395 if (res < 0)
3396 SL_RETURN(SH_FILE_UNKNOWN, _("sh_unix_getinfo_type"));
3397
3398 sh_unix_getinfo_type (&buf, &type, c_mode);
3399
3400 SL_RETURN(type, _("sh_unix_get_ftype"));
3401}
3402
3403
3404static
3405int sh_unix_getinfo_mode (struct stat *buf,
3406 unsigned int * mode,
3407 char * c_mode)
3408{
3409
3410 SL_ENTER(_("sh_unix_getinfo_mode"));
3411
3412 (*mode) = buf->st_mode;
3413
3414 /* make 'ls'-like string */
3415
3416 if ( (buf->st_mode & S_IRUSR) != 0 ) c_mode[1] = 'r';
3417 if ( (buf->st_mode & S_IWUSR) != 0 ) c_mode[2] = 'w';
3418 if ( (buf->st_mode & S_IXUSR) != 0 ) {
3419 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 's';
3420 else c_mode[3] = 'x';
3421 } else {
3422 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 'S';
3423 }
3424
3425 if ( (buf->st_mode & S_IRGRP) != 0 ) c_mode[4] = 'r';
3426 if ( (buf->st_mode & S_IWGRP) != 0 ) c_mode[5] = 'w';
3427 if ( (buf->st_mode & S_IXGRP) != 0 ) {
3428 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 's';
3429 else c_mode[6] = 'x';
3430 } else {
3431 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 'S';
3432 }
3433
3434 if ( (buf->st_mode & S_IROTH) != 0 ) c_mode[7] = 'r';
3435 if ( (buf->st_mode & S_IWOTH) != 0 ) c_mode[8] = 'w';
3436#ifdef S_ISVTX /* not POSIX */
3437 if ( (buf->st_mode & S_IXOTH) != 0 ) {
3438 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 't';
3439 else c_mode[9] = 'x';
3440 } else {
3441 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 'T';
3442 }
3443#else
3444 if ( (buf->st_mode & S_IXOTH) != 0 ) c_mode[9] = 'x';
3445#endif
3446
3447 SL_RETURN(0, _("sh_unix_getinfo_mode"));
3448}
3449
3450
3451long IO_Limit = 0;
3452
3453void sh_unix_io_pause ()
3454{
3455 long runtime;
3456 float someval;
3457 unsigned long sometime;
3458
3459 if (IO_Limit == 0)
3460 {
3461 return;
3462 }
3463 else
3464 {
3465 runtime = (long) (time(NULL) - sh.statistics.time_start);
3466
3467 if (runtime > 0 && (long)(sh.statistics.bytes_hashed/runtime) > IO_Limit)
3468 {
3469 someval = sh.statistics.bytes_hashed - (IO_Limit * runtime);
3470 someval /= (float) IO_Limit;
3471 if (someval < 1.0)
3472 {
3473 someval *= 1000; /* milliseconds in a second */
3474 sometime = (unsigned long) someval;
3475 retry_msleep(0, sometime);
3476 }
3477 else
3478 {
3479 sometime = (unsigned long) someval;
3480 retry_msleep (sometime, 0);
3481 }
3482 }
3483 }
3484 return;
3485}
3486
3487int sh_unix_set_io_limit (const char * c)
3488{
3489 long val;
3490
3491 SL_ENTER(_("sh_unix_set_io_limit"));
3492
3493 val = strtol (c, (char **)NULL, 10);
3494 if (val < 0)
3495 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
3496 _("set I/O limit"), c);
3497
3498 val = (val < 0 ? 0 : val);
3499
3500 IO_Limit = val * 1024;
3501 SL_RETURN( 0, _("sh_unix_set_io_limit"));
3502}
3503
3504/* obtain file info
3505 */
3506extern int flag_err_debug;
3507
3508#include "sh_ignore.h"
3509
3510int sh_unix_checksum_size (char * filename, off_t size, int is_max_size,
3511 char * fileHash, int alert_timeout, SL_TICKET fd, unsigned long mask)
3512{
3513 file_type * tmpFile;
3514 int status;
3515
3516 SL_ENTER(_("sh_unix_checksum_size"));
3517
3518 tmpFile = SH_ALLOC(sizeof(file_type));
3519 tmpFile->link_path = NULL;
3520
3521 if (sh.flag.checkSum != SH_CHECK_INIT)
3522 {
3523 /* lookup file in database */
3524 if (is_max_size == S_TRUE) {
3525 status = sh_hash_get_it (filename, tmpFile, NULL);
3526 if ((status != 0) || (tmpFile->size > size)) {
3527 goto out;
3528 }
3529 } else {
3530 tmpFile->size = size;
3531 }
3532 }
3533 else
3534 {
3535 tmpFile->size = size;
3536 }
3537
3538 /* if last <= current get checksum */
3539 if (tmpFile->size <= size)
3540 {
3541 char hashbuf[KEYBUF_SIZE];
3542 UINT64 local_length = (UINT64) (tmpFile->size < 0 ? 0 : tmpFile->size);
3543 if (sh.flag.opts == S_TRUE) sh_tiger_set_hashtype_mask(mask);
3544 sl_strlcpy(fileHash,
3545 sh_tiger_generic_hash (filename, fd, &(local_length),
3546 alert_timeout, hashbuf, sizeof(hashbuf)),
3547 KEY_LEN+1);
3548
3549 /* return */
3550 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3551 SH_FREE(tmpFile);
3552 SL_RETURN( 0, _("sh_unix_checksum_size"));
3553 }
3554
3555 out:
3556 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3557 SH_FREE(tmpFile);
3558 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3559 SL_RETURN( -1, _("sh_unix_checksum_size"));
3560}
3561
3562/********************************************************
3563 * Search rotated logfile
3564 */
3565extern char * sh_rotated_log_search(const char * path, struct stat * buf);
3566
3567int sh_check_rotated_log (const char * path,
3568 UINT64 old_size, UINT64 old_inode, const char * old_hash, unsigned long mask)
3569{
3570 struct stat obuf;
3571 UINT64 length_nolim = TIGER_NOLIM;
3572 int retval = S_FALSE;
3573
3574 if (old_size != length_nolim)
3575 {
3576 char hashbuf[KEYBUF_SIZE];
3577 char * rotated_file;
3578
3579 obuf.st_ino = old_inode;
3580 rotated_file = sh_rotated_log_search(path, &obuf);
3581
3582 if (rotated_file && (0 != strcmp(path, rotated_file)))
3583 {
3584 SL_TICKET fd = sl_open_fastread (FIL__, __LINE__, rotated_file, SL_YESPRIV);
3585 if (!SL_ISERROR(fd))
3586 {
3587 sh_unix_checksum_size (rotated_file, old_size, S_FALSE,
3588 hashbuf, 120 /* alert_timeout */, fd, mask);
3589
3590 sl_close(fd);
3591
3592 if (strncmp (old_hash, hashbuf, KEY_LEN) == 0) {
3593 retval = S_TRUE;
3594 }
3595 }
3596 SH_FREE(rotated_file);
3597 }
3598 }
3599 return retval;
3600}
3601
3602
3603int sh_unix_check_selinux = S_FALSE;
3604int sh_unix_check_acl = S_FALSE;
3605
3606#ifdef USE_ACL
3607
3608#include <sys/acl.h>
3609static char * sh_unix_getinfo_acl (char * path, int fd, struct stat * buf)
3610{
3611 /* system.posix_acl_access, system.posix_acl_default
3612 */
3613 char * out = NULL;
3614 char * collect = NULL;
3615 char * tmp;
3616 char * out_compact;
3617 ssize_t len;
3618 acl_t result;
3619
3620 SL_ENTER(_("sh_unix_getinfo_acl"));
3621
3622 result = (fd == -1) ?
3623 acl_get_file (path, ACL_TYPE_ACCESS) :
3624 acl_get_fd (fd);
3625
3626 if (result)
3627 {
3628 out = acl_to_text (result, &len);
3629 if (out && (len > 0)) {
3630 out_compact = sh_util_acl_compact (out, len);
3631 acl_free(out);
3632 if (out_compact)
3633 {
3634 collect = sh_util_strconcat (_("acl_access:"), out_compact, NULL);
3635 SH_FREE(out_compact);
3636 }
3637 }
3638 acl_free(result);
3639 }
3640
3641
3642 if ( S_ISDIR(buf->st_mode) )
3643 {
3644 result = acl_get_file (path, ACL_TYPE_DEFAULT);
3645
3646 if (result)
3647 {
3648 out = acl_to_text (result, &len);
3649 if (out && (len > 0)) {
3650 out_compact = sh_util_acl_compact (out, len);
3651 acl_free(out);
3652 if (out_compact) {
3653 if (collect) {
3654 tmp = sh_util_strconcat (_("acl_default:"),
3655 out_compact, ":", collect, NULL);
3656 SH_FREE(collect);
3657 }
3658 else {
3659 tmp = sh_util_strconcat (_("acl_default:"), out_compact, NULL);
3660 }
3661 SH_FREE(out_compact);
3662 collect = tmp;
3663 }
3664 }
3665 acl_free(result);
3666 }
3667 }
3668
3669 SL_RETURN((collect),_("sh_unix_getinfo_acl"));
3670}
3671#endif
3672
3673#ifdef USE_XATTR
3674
3675#include <attr/xattr.h>
3676static char * sh_unix_getinfo_xattr_int (char * path, int fd, char * name)
3677{
3678 char * out = NULL;
3679 char * tmp = NULL;
3680 size_t size = 256;
3681 ssize_t result;
3682
3683 SL_ENTER(_("sh_unix_getinfo_xattr_int"));
3684
3685 out = SH_ALLOC(size);
3686
3687 result = (fd == -1) ?
3688 lgetxattr (path, name, out, size-1) :
3689 fgetxattr (fd, name, out, size-1);
3690
3691 if (result == -1 && errno == ERANGE)
3692 {
3693 SH_FREE(out);
3694 result = (fd == -1) ?
3695 lgetxattr (path, name, NULL, 0) :
3696 fgetxattr (fd, name, NULL, 0);
3697 size = result + 1;
3698 out = SH_ALLOC(size);
3699 result = (fd == -1) ?
3700 lgetxattr (path, name, out, size-1) :
3701 fgetxattr (fd, name, out, size-1);
3702 }
3703
3704 if ((result > 0) && ((size_t)result < size))
3705 {
3706 out[size-1] = '\0';
3707 tmp = out;
3708 }
3709 else
3710 {
3711 SH_FREE(out);
3712 }
3713
3714 SL_RETURN((tmp),_("sh_unix_getinfo_xattr_int"));
3715}
3716
3717
3718static char * sh_unix_getinfo_xattr (char * path, int fd, struct stat * buf)
3719{
3720 /* system.posix_acl_access, system.posix_acl_default, security.selinux
3721 */
3722 char * tmp;
3723 char * out = NULL;
3724 char * collect = NULL;
3725
3726 SL_ENTER(_("sh_unix_getinfo_xattr"));
3727
3728#ifdef USE_ACL
3729 /*
3730 * we need the acl_get_fd/acl_get_file functions, getxattr will only
3731 * yield the raw bytes
3732 */
3733 if (sh_unix_check_acl == S_TRUE)
3734 {
3735 out = sh_unix_getinfo_acl(path, fd, buf);
3736
3737 if (out)
3738 {
3739 collect = out;
3740 }
3741 }
3742#else
3743 (void) buf;
3744#endif
3745
3746 if (sh_unix_check_selinux == S_TRUE)
3747 {
3748 out = sh_unix_getinfo_xattr_int(path, fd, _("security.selinux"));
3749
3750 if (out)
3751 {
3752 if (collect) {
3753 tmp = sh_util_strconcat(_("selinux:"), out, ":", collect, NULL);
3754 SH_FREE(collect);
3755 }
3756 else {
3757 tmp = sh_util_strconcat(_("selinux:"), out, NULL);
3758 }
3759 SH_FREE(out);
3760 collect = tmp;
3761 }
3762 }
3763
3764 SL_RETURN((collect),_("sh_unix_getinfo_xattr"));
3765}
3766#endif
3767
3768#ifdef USE_XATTR
3769int sh_unix_setcheckselinux (const char * c)
3770{
3771 int i;
3772 SL_ENTER(_("sh_unix_setcheckselinux"));
3773 i = sh_util_flagval(c, &(sh_unix_check_selinux));
3774
3775 SL_RETURN(i, _("sh_unix_setcheckselinux"));
3776}
3777#endif
3778
3779#ifdef USE_ACL
3780int sh_unix_setcheckacl (const char * c)
3781{
3782 int i;
3783 SL_ENTER(_("sh_unix_setcheckacl"));
3784 i = sh_util_flagval(c, &(sh_unix_check_acl));
3785
3786 SL_RETURN(i, _("sh_unix_setcheckacl"));
3787}
3788#endif
3789
3790#ifdef HAVE_LIBZ
3791#include <zlib.h>
3792#endif
3793
3794
3795static void * sh_dummy_filename;
3796static void * sh_dummy_tmp;
3797static void * sh_dummy_tmp2;
3798
3799int sh_unix_getinfo (int level, const char * filename, file_type * theFile,
3800 char * fileHash, int policy)
3801{
3802 char timestr[81];
3803 long runtim;
3804 struct stat buf;
3805 struct stat lbuf;
3806 struct stat fbuf;
3807 volatile int stat_return;
3808 volatile int stat_errno = 0;
3809
3810 ShFileType type;
3811 unsigned int mode;
3812 char * tmp;
3813 char * tmp2;
3814
3815 char * linknamebuf;
3816 volatile int linksize;
3817
3818 extern int get_the_fd (SL_TICKET ticket);
3819
3820 volatile SL_TICKET rval_open;
3821 volatile int err_open = 0;
3822
3823 volatile int fd;
3824 volatile int fstat_return;
3825 volatile int fstat_errno = 0;
3826 volatile int try = 0;
3827
3828 sh_string * content = NULL;
3829
3830 time_t tend;
3831 time_t tstart;
3832
3833
3834 char * path = NULL;
3835
3836 volatile int alert_timeout = 120;
3837
3838 path = theFile->fullpath;
3839
3840 SL_ENTER(_("sh_unix_getinfo"));
3841
3842 if (!MODI_INITIALIZED(theFile->check_flags))
3843 {
3844 tmp2 = sh_util_safe_name (theFile->fullpath);
3845 SH_MUTEX_LOCK(mutex_thread_nolog);
3846 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_E_SUBGPATH,
3847 _("Uninitialized check mask"), _("sh_unix_getinfo"),
3848 tmp2);
3849 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3850 SH_FREE(tmp2);
3851 SL_RETURN((-1),_("sh_unix_getinfo"));
3852 }
3853
3854 /* Take the address to keep gcc from putting it into a register.
3855 * Avoids the 'clobbered by longjmp' warning.
3856 */
3857 sh_dummy_filename = (void *) &filename;
3858 sh_dummy_tmp = (void *) &tmp;
3859 sh_dummy_tmp2 = (void *) &tmp2;
3860
3861 /* --- Stat the file, and get checksum. ---
3862 */
3863 tstart = time(NULL);
3864
3865 stat_return = retry_lstat (FIL__, __LINE__,
3866 path /* theFile->fullpath */, &buf);
3867
3868 if (stat_return)
3869 stat_errno = errno;
3870
3871 theFile->link_path = NULL;
3872
3873 try_again:
3874
3875 fd = -1;
3876 fstat_return = -1;
3877 rval_open = -1;
3878
3879 if (stat_return == 0 && S_ISREG(buf.st_mode))
3880 {
3881 rval_open = sl_open_fastread (FIL__, __LINE__,
3882 path /* theFile->fullpath */, SL_YESPRIV);
3883 if (SL_ISERROR(rval_open))
3884 {
3885 char * stale = sl_check_stale();
3886
3887 if (stale)
3888 {
3889 SH_MUTEX_LOCK(mutex_thread_nolog);
3890 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, err_open, MSG_E_SUBGEN,
3891 stale, _("sh_unix_getinfo_open"));
3892 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3893 }
3894
3895 if (errno == EBADF && try == 0) /* obsolete, but we keep this, just in case */
3896 {
3897 ++try;
3898 goto try_again;
3899 }
3900 err_open = errno;
3901 }
3902
3903 alert_timeout = 120; /* this is per 8K block now ! */
3904
3905 if (path[1] == 'p' && path[5] == '/' && path[2] == 'r' &&
3906 path[3] == 'o' && path[4] == 'c' && path[0] == '/')
3907 {
3908 /* seven is magic */
3909 alert_timeout = 7;
3910 }
3911
3912 fd = get_the_fd(rval_open);
3913 }
3914
3915 tend = time(NULL);
3916
3917 /* An unprivileged user may slow lstat/open to a crawl
3918 * with clever path/symlink setup
3919 */
3920 if ((tend - tstart) > (time_t) /* 60 */ 6)
3921 {
3922 tmp2 = sh_util_safe_name (theFile->fullpath);
3923 SH_MUTEX_LOCK(mutex_thread_nolog);
3924 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_TOOLATE,
3925 (long)(tend - tstart), tmp2);
3926 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3927 SH_FREE(tmp2);
3928 }
3929
3930 if (fd >= 0)
3931 {
3932 fstat_return = retry_fstat (FIL__, __LINE__, fd, &fbuf);
3933
3934 if (fstat_return)
3935 {
3936 char * stale;
3937
3938 fstat_errno = errno;
3939
3940 stale = sl_check_stale();
3941
3942 if (stale)
3943 {
3944 SH_MUTEX_LOCK(mutex_thread_nolog);
3945 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, fstat_errno,
3946 MSG_E_SUBGEN,
3947 stale, _("sh_unix_getinfo_fstat"));
3948 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3949 }
3950
3951 if (try == 0) /* obsolete, but we keep this, just in case */
3952 {
3953 ++try;
3954 sl_close(rval_open);
3955 goto try_again;
3956 }
3957 }
3958 }
3959 else
3960 {
3961 fd = -1;
3962 }
3963
3964
3965 /* --- case 1: lstat failed ---
3966 */
3967 if (stat_return != 0)
3968 {
3969 stat_return = errno;
3970 if (!SL_ISERROR(rval_open))
3971 sl_close(rval_open);
3972 if (sh.flag.checkSum == SH_CHECK_INIT ||
3973 (sh_hash_have_it (theFile->fullpath) >= 0 &&
3974 (!SH_FFLAG_REPORTED_SET(theFile->file_reported))))
3975 {
3976 if (S_FALSE == sh_ignore_chk_del(theFile->fullpath)) {
3977 int flags = sh_hash_getflags (theFile->fullpath);
3978
3979 if ((flags >= 0) && (flags & SH_FFLAG_ENOENT) == 0) {
3980 char errbuf[SH_ERRBUF_SIZE];
3981 uid_t euid;
3982 (void) sl_get_euid(&euid);
3983 tmp2 = sh_util_safe_name (theFile->fullpath);
3984 SH_MUTEX_LOCK(mutex_thread_nolog);
3985 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3986 _("lstat"),
3987 sh_error_message (stat_errno, errbuf, sizeof(errbuf)),
3988 (long) euid,
3989 tmp2);
3990 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3991 SH_FREE(tmp2);
3992 sh_hash_set_flag (theFile->fullpath, SH_FFLAG_ENOENT);
3993 }
3994 }
3995 }
3996 SL_RETURN((-1),_("sh_unix_getinfo"));
3997 }
3998
3999 /* --- case 2: not a regular file ---
4000 */
4001 else if (! S_ISREG(buf.st_mode))
4002 {
4003 if (fileHash != NULL)
4004 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4005 }
4006
4007 /* --- case 3a: a regular file, fstat ok ---
4008 */
4009 else if (fstat_return == 0 &&
4010 buf.st_mode == fbuf.st_mode &&
4011 buf.st_ino == fbuf.st_ino &&
4012 buf.st_uid == fbuf.st_uid &&
4013 buf.st_gid == fbuf.st_gid &&
4014 buf.st_dev == fbuf.st_dev )
4015 {
4016 if (fileHash != NULL)
4017 {
4018 if ((theFile->check_flags & MODI_CHK) == 0 ||
4019 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
4020 (UINT64) fbuf.st_mode, rval_open))
4021 {
4022 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4023 }
4024 else if ((theFile->check_flags & MODI_PREL) != 0 &&
4025 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
4026 alert_timeout, theFile->fullpath))
4027 {
4028 if (0 != sh_prelink_run (theFile->fullpath,
4029 fileHash, alert_timeout, theFile->check_flags))
4030 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4031 }
4032 else
4033 {
4034 char hashbuf[KEYBUF_SIZE];
4035 UINT64 length_current = TIGER_NOLIM;
4036
4037 if (MODI_TXT_ENABLED(theFile->check_flags) && fbuf.st_size < (10 * SH_TXT_MAX))
4038 {
4039 sl_init_content (rval_open, fbuf.st_size);
4040 }
4041
4042 if (sh.flag.opts == S_TRUE) sh_tiger_set_hashtype_mask(theFile->check_flags);
4043 sl_strlcpy(fileHash,
4044 sh_tiger_generic_hash (theFile->fullpath,
4045 rval_open, &length_current,
4046 alert_timeout,
4047 hashbuf, sizeof(hashbuf)),
4048 KEY_LEN+1);
4049
4050 content = sl_get_content(rval_open);
4051 content = sh_string_copy(content);
4052
4053 if ((theFile->check_flags & MODI_SGROW) != 0)
4054 {
4055 /* Update size so it matches the one for which the checksum
4056 has been computed */
4057 fbuf.st_size = length_current;
4058 buf.st_size = fbuf.st_size;
4059 sl_rewind(rval_open);
4060 sh_unix_checksum_size (theFile->fullpath, length_current, S_TRUE,
4061 &fileHash[KEY_LEN + 1],
4062 alert_timeout, rval_open, theFile->check_flags);
4063 }
4064 }
4065 }
4066 }
4067
4068 /* --- case 3b: a regular file, fstat ok, but different ---
4069 */
4070 else if (fstat_return == 0 && S_ISREG(fbuf.st_mode))
4071 {
4072 memcpy (&buf, &fbuf, sizeof( struct stat ));
4073
4074 if (fileHash != NULL)
4075 {
4076 if ((theFile->check_flags & MODI_CHK) == 0 ||
4077 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
4078 (UINT64) fbuf.st_mode, rval_open))
4079 {
4080 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4081 }
4082 else if (policy == SH_LEVEL_PRELINK &&
4083 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
4084 alert_timeout, theFile->fullpath))
4085 {
4086 if (0 != sh_prelink_run (theFile->fullpath,
4087 fileHash, alert_timeout, theFile->check_flags))
4088 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4089 }
4090 else
4091 {
4092 char hashbuf[KEYBUF_SIZE];
4093 UINT64 length_current = TIGER_NOLIM;
4094
4095 if (MODI_TXT_ENABLED(theFile->check_flags) && fbuf.st_size < (10 * SH_TXT_MAX))
4096 {
4097 sl_init_content (rval_open, fbuf.st_size);
4098 }
4099
4100 if (sh.flag.opts == S_TRUE) sh_tiger_set_hashtype_mask(theFile->check_flags);
4101 sl_strlcpy(fileHash,
4102 sh_tiger_generic_hash (theFile->fullpath, rval_open,
4103 &length_current,
4104 alert_timeout,
4105 hashbuf, sizeof(hashbuf)),
4106 KEY_LEN + 1);
4107
4108 content = sl_get_content(rval_open);
4109 content = sh_string_copy(content);
4110
4111 if ((theFile->check_flags & MODI_SGROW) != 0)
4112 {
4113 /* Update size so it matches the one for which the checksum
4114 has been computed */
4115 fbuf.st_size = length_current;
4116 buf.st_size = fbuf.st_size;
4117 sl_rewind(rval_open);
4118 sh_unix_checksum_size (theFile->fullpath, length_current, S_TRUE,
4119 &fileHash[KEY_LEN + 1],
4120 alert_timeout, rval_open, theFile->check_flags);
4121 }
4122 }
4123 }
4124 }
4125
4126 /* --- case 4: a regular file, fstat failed ---
4127 */
4128
4129 else /* fstat_return != 0 or !S_ISREG(fbuf.st_mode) or open() failed */
4130 {
4131 uid_t euid;
4132
4133 if (fileHash != NULL)
4134 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
4135
4136 if ((theFile->check_flags & MODI_CHK) != 0)
4137 {
4138 tmp2 = sh_util_safe_name (theFile->fullpath);
4139
4140
4141 if (fd >= 0 && fstat_return != 0)
4142 {
4143 char errbuf[SH_ERRBUF_SIZE];
4144 (void) sl_get_euid(&euid);
4145
4146 SH_MUTEX_LOCK(mutex_thread_nolog);
4147 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
4148 _("fstat"),
4149 sh_error_message (fstat_errno, errbuf, sizeof(errbuf)),
4150 (long) euid,
4151 tmp2);
4152 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4153 }
4154 else if (fd >= 0 && !S_ISREG(fbuf.st_mode))
4155 {
4156 SH_MUTEX_LOCK(mutex_thread_nolog);
4157 sh_error_handle (level, FIL__, __LINE__, fstat_errno,
4158 MSG_E_NOTREG, tmp2);
4159 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4160 }
4161 else
4162 {
4163 char errbuf[SH_ERRBUF_SIZE];
4164 char errbuf2[SH_ERRBUF_SIZE];
4165 sl_strlcpy(errbuf, sl_error_string(rval_open), sizeof(errbuf));
4166 sh_error_message(err_open, errbuf2, sizeof(errbuf2));
4167 SH_MUTEX_LOCK(mutex_thread_nolog);
4168 sh_error_handle (level, FIL__, __LINE__, err_open,
4169 MSG_E_READ, errbuf, errbuf2, tmp2);
4170 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4171 }
4172 SH_FREE(tmp2);
4173 }
4174 }
4175
4176
4177 /* --- Determine file type. ---
4178 */
4179 memset (theFile->c_mode, '-', CMODE_SIZE-1);
4180 theFile->c_mode[CMODE_SIZE-1] = '\0';
4181
4182 memset (theFile->link_c_mode, '-', CMODE_SIZE-1);
4183 theFile->link_c_mode[CMODE_SIZE-1] = '\0';
4184
4185 sh_unix_getinfo_type (&buf, &type, theFile->c_mode);
4186 theFile->type = type;
4187
4188#if defined(__linux__) || defined(HAVE_STAT_FLAGS)
4189
4190 /* --- Determine file attributes. ---
4191 */
4192 memset (theFile->c_attributes, '-', ATTRBUF_SIZE);
4193 theFile->c_attributes[ATTRBUF_USED] = '\0';
4194 theFile->attributes = 0;
4195
4196#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
4197 if (theFile->c_mode[0] != 'c' && theFile->c_mode[0] != 'b' &&
4198 theFile->c_mode[0] != 'l' )
4199 sh_unix_getinfo_attr(theFile->fullpath,
4200 &theFile->attributes, theFile->c_attributes,
4201 fd, &buf);
4202#endif
4203#endif
4204
4205#if defined(USE_XATTR) && defined(USE_ACL)
4206 if (sh_unix_check_selinux == S_TRUE || sh_unix_check_acl == S_TRUE)
4207 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4208#elif defined(USE_XATTR)
4209 if (sh_unix_check_selinux == S_TRUE)
4210 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4211#elif defined(USE_ACL)
4212 if (sh_unix_check_acl == S_TRUE)
4213 theFile->attr_string = sh_unix_getinfo_acl (theFile->fullpath, fd, &buf);
4214#else
4215 theFile->attr_string = NULL;
4216#endif
4217
4218 if (!SL_ISERROR(rval_open))
4219 sl_close(rval_open);
4220
4221
4222 /* --- I/O limit. ---
4223 */
4224 if (IO_Limit > 0)
4225 {
4226 runtim = (long) (time(NULL) - sh.statistics.time_start);
4227
4228 if (runtim > 0 && (long)(sh.statistics.bytes_hashed/runtim) > IO_Limit)
4229 retry_msleep(1, 0);
4230 }
4231
4232 /* --- Determine permissions. ---
4233 */
4234 sh_unix_getinfo_mode (&buf, &mode, theFile->c_mode);
4235
4236 /* --- Trivia. ---
4237 */
4238 theFile->dev = buf.st_dev;
4239 theFile->ino = buf.st_ino;
4240 theFile->mode = buf.st_mode;
4241 theFile->hardlinks = buf.st_nlink;
4242 theFile->owner = buf.st_uid;
4243 theFile->group = buf.st_gid;
4244 theFile->rdev = buf.st_rdev;
4245 theFile->size = buf.st_size;
4246 theFile->blksize = (unsigned long) buf.st_blksize;
4247 theFile->blocks = (unsigned long) buf.st_blocks;
4248 theFile->atime = buf.st_atime;
4249 theFile->mtime = buf.st_mtime;
4250 theFile->ctime = buf.st_ctime;
4251
4252
4253 /* --- Owner and group. ---
4254 */
4255
4256 if (NULL == sh_unix_getGIDname(SH_ERR_ALL, buf.st_gid, theFile->c_group, GROUP_MAX+1)) {
4257
4258 tmp2 = sh_util_safe_name (theFile->fullpath);
4259
4260 if (policy == SH_LEVEL_ALLIGNORE)
4261 {
4262 SH_MUTEX_LOCK(mutex_thread_nolog);
4263 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4264 MSG_FI_NOGRP,
4265 (long) buf.st_gid, tmp2);
4266 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4267 }
4268 else
4269 {
4270 SH_MUTEX_LOCK(mutex_thread_nolog);
4271 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4272 MSG_FI_NOGRP,
4273 (long) buf.st_gid, tmp2);
4274 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4275 }
4276 SH_FREE(tmp2);
4277 sl_snprintf(theFile->c_group, GROUP_MAX+1, "%d", (long) buf.st_gid);
4278 }
4279
4280
4281 if (NULL == sh_unix_getUIDname(SH_ERR_ALL, buf.st_uid, theFile->c_owner, USER_MAX+1)) {
4282
4283 tmp2 = sh_util_safe_name (theFile->fullpath);
4284
4285 if (policy == SH_LEVEL_ALLIGNORE)
4286 {
4287 SH_MUTEX_LOCK(mutex_thread_nolog);
4288 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4289 MSG_FI_NOUSR,
4290 (long) buf.st_uid, tmp2);
4291 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4292 }
4293 else
4294 {
4295 SH_MUTEX_LOCK(mutex_thread_nolog);
4296 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4297 MSG_FI_NOUSR,
4298 (long) buf.st_uid, tmp2);
4299 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4300 }
4301 SH_FREE(tmp2);
4302 sl_snprintf(theFile->c_owner, USER_MAX+1, "%d", (long) buf.st_uid);
4303 }
4304
4305 /* --- Output the file. ---
4306 */
4307 if (flag_err_debug == S_TRUE)
4308 {
4309 tmp2 = sh_util_safe_name ((filename == NULL) ?
4310 theFile->fullpath : filename);
4311 (void) sh_unix_time(theFile->mtime, timestr, sizeof(timestr));
4312 SH_MUTEX_LOCK(mutex_thread_nolog);
4313 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LIST,
4314 theFile->c_mode,
4315 theFile->hardlinks,
4316 theFile->c_owner,
4317 theFile->c_group,
4318 (unsigned long) theFile->size,
4319 timestr,
4320 tmp2);
4321 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4322 SH_FREE(tmp2);
4323 }
4324
4325 /* --- Check for links. ---
4326 */
4327 if (theFile->c_mode[0] == 'l')
4328 {
4329 linknamebuf = SH_ALLOC(PATH_MAX);
4330
4331 /* flawfinder: ignore */
4332 linksize = readlink (theFile->fullpath, linknamebuf, PATH_MAX-1);
4333
4334 if (linksize < (PATH_MAX-1) && linksize >= 0)
4335 linknamebuf[linksize] = '\0';
4336 else
4337 linknamebuf[PATH_MAX-1] = '\0';
4338
4339 if (linksize < 0)
4340 {
4341 char errbuf[SH_ERRBUF_SIZE];
4342 linksize = errno;
4343 tmp2 = sh_util_safe_name (theFile->fullpath);
4344 SH_MUTEX_LOCK(mutex_thread_nolog);
4345 sh_error_handle (level, FIL__, __LINE__, linksize, MSG_FI_RDLNK,
4346 sh_error_message (linksize, errbuf, sizeof(errbuf)), tmp2);
4347 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4348 SH_FREE(tmp2);
4349 SH_FREE(linknamebuf);
4350 theFile->link_path = sh_util_strdup("-");
4351 SL_RETURN((-1),_("sh_unix_getinfo"));
4352 }
4353
4354 if (linknamebuf[0] == '/')
4355 {
4356 theFile->link_path = sh_util_strdup (linknamebuf);
4357 }
4358 else
4359 {
4360 tmp = sh_util_dirname(theFile->fullpath);
4361 if (tmp) {
4362 theFile->link_path = SH_ALLOC(PATH_MAX);
4363 sl_strlcpy (theFile->link_path, tmp, PATH_MAX);
4364 SH_FREE(tmp);
4365 } else {
4366 theFile->link_path = SH_ALLOC(PATH_MAX);
4367 theFile->link_path[0] = '\0';
4368 }
4369 /*
4370 * Only attach '/' if not root directory. Handle "//", which
4371 * according to POSIX is implementation-defined, and may be
4372 * different from "/" (however, three or more '/' will collapse
4373 * to one).
4374 */
4375 tmp = theFile->link_path; while (*tmp == '/') ++tmp;
4376 if (*tmp != '\0')
4377 {
4378 sl_strlcat (theFile->link_path, "/", PATH_MAX);
4379 }
4380 sl_strlcat (theFile->link_path, linknamebuf, PATH_MAX);
4381 }
4382
4383 /* stat the link
4384 */
4385 stat_return = retry_lstat (FIL__, __LINE__, theFile->link_path, &lbuf);
4386
4387 /* check for error
4388 */
4389 if (stat_return != 0)
4390 {
4391 stat_return = errno;
4392 tmp = sh_util_safe_name (theFile->fullpath);
4393 tmp2 = sh_util_safe_name (theFile->link_path);
4394 if (stat_return != ENOENT)
4395 {
4396 uid_t euid;
4397 char errbuf[SH_ERRBUF_SIZE];
4398
4399 (void) sl_get_euid(&euid);
4400 SH_MUTEX_LOCK(mutex_thread_nolog);
4401 sh_error_handle (level, FIL__, __LINE__, stat_return,
4402 MSG_FI_STAT,
4403 _("lstat (link target)"),
4404 sh_error_message (stat_return,errbuf, sizeof(errbuf)),
4405 (long) euid,
4406 tmp2);
4407 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4408 }
4409 else
4410 {
4411 /* a dangling link -- everybody seems to have plenty of them
4412 */
4413 SH_MUTEX_LOCK(mutex_thread_nolog);
4414 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_DLNK,
4415 tmp, tmp2);
4416 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4417 }
4418 theFile->linkisok = BAD;
4419 SH_FREE(tmp);
4420 SH_FREE(tmp2);
4421 SH_FREE(linknamebuf);
4422 /*
4423 * changed Tue Feb 10 16:16:13 CET 2004:
4424 * add dangling symlinks into database
4425 * SL_RETURN((-1),_("sh_unix_getinfo"));
4426 */
4427 theFile->linkmode = 0;
4428 SL_RETURN((0),_("sh_unix_getinfo"));
4429 }
4430
4431 theFile->linkisok = GOOD;
4432
4433
4434 /* --- Determine file type. ---
4435 */
4436 sh_unix_getinfo_type (&lbuf, &type, theFile->link_c_mode);
4437 theFile->type = type;
4438
4439 /* --- Determine permissions. ---
4440 */
4441 sh_unix_getinfo_mode (&lbuf, &mode, theFile->link_c_mode);
4442 theFile->linkmode = lbuf.st_mode;
4443
4444 /* --- Output the link. ---
4445 */
4446 if (theFile->linkisok == GOOD)
4447 {
4448 tmp2 = sh_util_safe_name (linknamebuf);
4449 SH_MUTEX_LOCK(mutex_thread_nolog);
4450 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LLNK,
4451 theFile->link_c_mode, tmp2);
4452 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4453 SH_FREE(tmp2);
4454 }
4455 SH_FREE(linknamebuf);
4456 }
4457 else /* not a link, theFile->c_mode[0] != 'l' */
4458 {
4459 if (content)
4460 {
4461#ifdef HAVE_LIBZ
4462 unsigned long clen;
4463 unsigned char * compressed;
4464#ifdef HAVE_COMPRESSBOUND
4465 clen = compressBound(sh_string_len(content));
4466#else
4467 if (sh_string_len(content) > 10*SH_TXT_MAX)
4468 clen = SH_TXT_MAX;
4469 else
4470 clen = 13 + (int)(1.0001*sh_string_len(content));
4471#endif
4472 compressed = SH_ALLOC(clen);
4473 if (Z_OK == compress(compressed, &clen,
4474 (unsigned char *) sh_string_str(content),
4475 sh_string_len(content)))
4476 {
4477 if (clen < SH_TXT_MAX)
4478 {
4479 sh_util_base64_enc_alloc (&(theFile->link_path),
4480 (char *) compressed, clen);
4481 }
4482 else
4483 {
4484 char tmsg[128];
4485 char * tpath = sh_util_safe_name (theFile->fullpath);
4486 sl_snprintf(tmsg, sizeof(tmsg),
4487 _("compressed file too large (%lu bytes)"),
4488 clen);
4489 SH_MUTEX_LOCK(mutex_thread_nolog);
4490 sh_error_handle (SH_ERR_WARN, FIL__, __LINE__, -1,
4491 MSG_E_SUBGPATH, tmsg,
4492 _("sh_unix_getinfo"), tpath);
4493 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4494 SH_FREE(tpath);
4495 }
4496 }
4497 SH_FREE(compressed);
4498#endif
4499 sh_string_destroy(&content);
4500 }
4501 }
4502 SL_RETURN((0),_("sh_unix_getinfo"));
4503}
4504
4505/* #if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE) */
4506#endif
4507
4508int sh_unix_unlock(char * lockfile, char * flag)
4509{
4510 int error = 0;
4511
4512 SL_ENTER(_("sh_unix_unlock"));
4513
4514 if (sh.flag.isdaemon == S_FALSE && flag == NULL)
4515 SL_RETURN((0),_("sh_unix_unlock"));
4516
4517 /* --- Logfile is not locked to us. ---
4518 */
4519 if (sh.flag.islocked == BAD && flag != NULL)
4520 SL_RETURN((-1),_("sh_unix_unlock"));
4521
4522 /* --- Check whether the directory is secure. ---
4523 */
4524 if (0 != tf_trust_check (lockfile, SL_YESPRIV))
4525 SL_RETURN((-1),_("sh_unix_unlock"));
4526
4527 /* --- Delete the lock file. ---
4528 */
4529 error = retry_aud_unlink (FIL__, __LINE__, lockfile);
4530
4531 if (error == 0)
4532 {
4533 if (flag != NULL)
4534 sh.flag.islocked = BAD; /* not locked anymore */
4535 }
4536 else if (flag != NULL)
4537 {
4538 char errbuf[SH_ERRBUF_SIZE];
4539 error = errno;
4540 sh_error_handle ((-1), FIL__, __LINE__, error, MSG_E_UNLNK,
4541 sh_error_message(error, errbuf, sizeof(errbuf)),
4542 lockfile);
4543 SL_RETURN((-1),_("sh_unix_unlock"));
4544 }
4545 SL_RETURN((0),_("sh_unix_unlock"));
4546}
4547
4548int sh_unix_check_piddir (char * pidpath)
4549{
4550 static struct stat buf;
4551 int status = 0;
4552 char * pid_dir;
4553
4554 SL_ENTER(_("sh_unix_check_piddir"));
4555
4556 pid_dir = sh_util_dirname (pidpath);
4557
4558 status = retry_lstat (FIL__, __LINE__, pid_dir, &buf);
4559
4560 if (status < 0 && errno == ENOENT)
4561 {
4562 status = mkdir (pid_dir, 0777);
4563 if (status < 0)
4564 {
4565 sh_error_handle ((-1), FIL__, __LINE__, status,
4566 MSG_E_SUBGEN,
4567 _("Cannot create PID directory"),
4568 _("sh_unix_check_piddir"));
4569 SH_FREE(pid_dir);
4570 SL_RETURN((-1),_("sh_unix_check_piddir"));
4571 }
4572 }
4573 else if (!S_ISDIR(buf.st_mode))
4574 {
4575 sh_error_handle ((-1), FIL__, __LINE__, status,
4576 MSG_E_SUBGEN,
4577 _("Path of PID directory refers to a non-directory object"),
4578 _("sh_unix_check_piddir"));
4579 SH_FREE(pid_dir);
4580 SL_RETURN((-1),_("sh_unix_check_piddir"));
4581 }
4582 SH_FREE(pid_dir);
4583 SL_RETURN((0),_("sh_unix_check_piddir"));
4584}
4585
4586int sh_unix_lock (char * lockfile, char * flag)
4587{
4588 int filed;
4589 int errnum;
4590 char myPid[64];
4591 SL_TICKET fd;
4592 extern int get_the_fd (SL_TICKET ticket);
4593
4594 SL_ENTER(_("sh_unix_lock"));
4595
4596 sprintf (myPid, "%ld\n", (long) sh.pid); /* known to fit */
4597
4598 if (flag == NULL) /* PID file, check for directory */
4599 {
4600 if (0 != sh_unix_check_piddir (lockfile))
4601 {
4602 SL_RETURN((-1),_("sh_unix_lock"));
4603 }
4604 }
4605
4606 fd = sl_open_safe_rdwr (FIL__, __LINE__,
4607 lockfile, SL_YESPRIV); /* fails if file exists */
4608
4609 if (!SL_ISERROR(fd))
4610 {
4611 errnum = sl_write (fd, myPid, sl_strlen(myPid));
4612 filed = get_the_fd(fd);
4613 fchmod (filed, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
4614 sl_close (fd);
4615
4616 if (!SL_ISERROR(errnum))
4617 {
4618 if (flag != NULL)
4619 sh.flag.islocked = GOOD;
4620 SL_RETURN((0),_("sh_unix_lock"));
4621 }
4622 }
4623
4624 TPT((0, FIL__, __LINE__, _("msg=<open pid file failed>\n")));
4625 if (flag != NULL)
4626 sh.flag.islocked = BAD;
4627 SL_RETURN((-1),_("sh_unix_lock"));
4628
4629 /* notreached */
4630}
4631
4632
4633/* check whether file is locked
4634 */
4635int sh_unix_test_and_lock (char * filename, char * lockfile)
4636{
4637 static struct stat buf;
4638 int status = 0;
4639
4640
4641 SL_TICKET fd;
4642 char line_in[128];
4643
4644 SL_ENTER(_("sh_unix_test_and_lock"));
4645
4646 status = retry_lstat (FIL__, __LINE__, lockfile, &buf);
4647
4648 /* --- No lock file found, try to lock. ---
4649 */
4650
4651 if (status < 0 && errno == ENOENT)
4652 {
4653 if (0 == sh_unix_lock (lockfile, filename))
4654 {
4655 if (filename != NULL)
4656 sh.flag.islocked = GOOD;
4657 SL_RETURN((0),_("sh_unix_test_and_lock"));
4658 }
4659 else
4660 {
4661 sh_error_handle ((-1), FIL__, __LINE__, status,
4662 MSG_E_SUBGEN,
4663 (filename == NULL) ? _("Cannot create PID file (1)") : _("Cannot create lock file (1)"),
4664 _("sh_unix_test_and_lock"));
4665 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4666 }
4667 }
4668 else if (status == 0 && buf.st_size == 0)
4669 {
4670 if (filename != NULL)
4671 sh.flag.islocked = GOOD;
4672 sh_unix_unlock (lockfile, filename);
4673 if (filename != NULL)
4674 sh.flag.islocked = BAD;
4675 if (0 == sh_unix_lock (lockfile, filename))
4676 {
4677 if (filename != NULL)
4678 sh.flag.islocked = GOOD;
4679 SL_RETURN((0),_("sh_unix_test_and_lock"));
4680 }
4681 else
4682 {
4683 sh_error_handle ((-1), FIL__, __LINE__, status,
4684 MSG_E_SUBGEN,
4685 (filename == NULL) ? _("Cannot create PID file (2)") : _("Cannot create lock file (2)"),
4686 _("sh_unix_test_and_lock"));
4687 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4688 }
4689 }
4690
4691 /* --- Check on lock. ---
4692 */
4693
4694 if (status >= 0)
4695 {
4696 fd = sl_open_read (FIL__, __LINE__, lockfile, SL_YESPRIV);
4697 if (SL_ISERROR(fd))
4698 sh_error_handle ((-1), FIL__, __LINE__, fd,
4699 MSG_E_SUBGEN,
4700 (filename == NULL) ? _("Cannot open PID file for read") : _("Cannot open lock file for read"),
4701 _("sh_unix_test_and_lock"));
4702 }
4703 else
4704 fd = -1;
4705
4706 if (!SL_ISERROR(fd))
4707 {
4708 /* read the PID in the lock file
4709 */
4710 status = sl_read (fd, line_in, sizeof(line_in));
4711 line_in[sizeof(line_in)-1] = '\0';
4712
4713 /* convert to numeric
4714 */
4715 if (status > 0)
4716 {
4717 errno = 0;
4718 status = strtol(line_in, (char **)NULL, 10);
4719 if (errno == ERANGE || status <= 0)
4720 {
4721 sh_error_handle ((-1), FIL__, __LINE__, status,
4722 MSG_E_SUBGEN,
4723 (filename == NULL) ? _("Bad PID in PID file") : _("Bad PID in lock file"),
4724 _("sh_unix_test_and_lock"));
4725
4726 status = -1;
4727 }
4728 }
4729 else
4730 {
4731 sh_error_handle ((-1), FIL__, __LINE__, status,
4732 MSG_E_SUBGEN,
4733 (filename == NULL) ? _("Cannot read PID file") : _("Cannot read lock file"),
4734 _("sh_unix_test_and_lock"));
4735 }
4736 sl_close(fd);
4737
4738 if (status > 0 && (unsigned int) status == sh.pid)
4739 {
4740 if (filename != NULL)
4741 sh.flag.islocked = GOOD;
4742 SL_RETURN((0),_("sh_unix_test_and_lock"));
4743 }
4744
4745
4746 /* --- Check whether the process exists. ---
4747 */
4748 if (status > 0)
4749 {
4750 errno = 0;
4751 status = aud_kill (FIL__, __LINE__, status, 0);
4752
4753 /* Does not exist, so remove the stale lock
4754 * and create a new one.
4755 */
4756 if (status < 0 && errno == ESRCH)
4757 {
4758 if (filename != NULL)
4759 sh.flag.islocked = GOOD;
4760 if (0 != sh_unix_unlock(lockfile, filename) && (filename !=NULL))
4761 sh.flag.islocked = BAD;
4762 else
4763 {
4764 if (0 == sh_unix_lock (lockfile, filename))
4765 {
4766 if (filename != NULL)
4767 sh.flag.islocked = GOOD;
4768 SL_RETURN((0),_("sh_unix_test_and_lock"));
4769 }
4770 else
4771 {
4772 sh_error_handle ((-1), FIL__, __LINE__, status,
4773 MSG_E_SUBGEN,
4774 (filename == NULL) ? _("Cannot create PID file (3)") : _("Cannot create lock file (3)"),
4775 _("sh_unix_test_and_lock"));
4776 }
4777 if (filename != NULL)
4778 sh.flag.islocked = BAD;
4779 }
4780 }
4781 else
4782 {
4783 sh_error_handle ((-1), FIL__, __LINE__, status,
4784 MSG_E_SUBGEN,
4785 (filename == NULL) ? _("Cannot remove stale PID file, PID may be a running process") : _("Cannot remove stale lock file, PID may be a running process"),
4786 _("sh_unix_test_and_lock"));
4787 if (filename != NULL)
4788 sh.flag.islocked = BAD;
4789 }
4790 }
4791 }
4792 SL_RETURN((-1),_("sh_unix_testlock"));
4793}
4794
4795/* write the PID file
4796 */
4797int sh_unix_write_pid_file()
4798{
4799 return sh_unix_test_and_lock(NULL, sh.srvlog.alt);
4800}
4801
4802/* write lock for filename
4803 */
4804int sh_unix_write_lock_file(char * filename)
4805{
4806 size_t len;
4807 int res;
4808 char * lockfile;
4809
4810 if (filename == NULL)
4811 return (-1);
4812
4813 len = sl_strlen(filename);
4814 if (sl_ok_adds(len, 6))
4815 len += 6;
4816 lockfile = SH_ALLOC(len);
4817 sl_strlcpy(lockfile, filename, len);
4818 sl_strlcat(lockfile, _(".lock"), len);
4819 res = sh_unix_test_and_lock(filename, lockfile);
4820 SH_FREE(lockfile);
4821 return res;
4822}
4823
4824/* rm lock for filename
4825 */
4826int sh_unix_rm_lock_file(char * filename)
4827{
4828 size_t len;
4829 int res;
4830 char * lockfile;
4831
4832 if (filename == NULL)
4833 return (-1);
4834
4835 len = sl_strlen(filename);
4836 if (sl_ok_adds(len, 6))
4837 len += 6;
4838 lockfile = SH_ALLOC(len);
4839 sl_strlcpy(lockfile, filename, len);
4840 sl_strlcat(lockfile, _(".lock"), len);
4841
4842 res = sh_unix_unlock(lockfile, filename);
4843 SH_FREE(lockfile);
4844 return res;
4845}
4846
4847/* rm lock for filename
4848 */
4849int sh_unix_rm_pid_file()
4850{
4851 return sh_unix_unlock(sh.srvlog.alt, NULL);
4852}
4853
4854/* Test whether file exists
4855 */
4856int sh_unix_file_exists(char * path)
4857{
4858 struct stat buf;
4859
4860 SL_ENTER(_("sh_unix_file_exists"));
4861
4862 if (0 == retry_lstat(FIL__, __LINE__, path, &buf))
4863 SL_RETURN( S_TRUE, _("sh_unix_file_exists"));
4864 else
4865 SL_RETURN( S_FALSE, _("sh_unix_file_exists"));
4866}
4867
4868
4869/* Test whether file exists, is a character device, and allows read
4870 * access.
4871 */
4872int sh_unix_device_readable(int fd)
4873{
4874 struct stat buf;
4875
4876 SL_ENTER(_("sh_unix_device_readable"));
4877
4878 if (retry_fstat(FIL__, __LINE__, fd, &buf) == -1)
4879 SL_RETURN( (-1), _("sh_unix_device_readable"));
4880 else if ( S_ISCHR(buf.st_mode) && 0 != (S_IROTH & buf.st_mode) )
4881 SL_RETURN( (0), _("sh_unix_device_readable"));
4882 else
4883 SL_RETURN( (-1), _("sh_unix_device_readable"));
4884}
4885
4886static char preq[16];
4887
4888/* return true if database is remote
4889 */
4890int file_is_remote ()
4891{
4892 static int init = 0;
4893 struct stat buf;
4894
4895 SL_ENTER(_("file_is_remote"));
4896
4897 if (init == 0)
4898 {
4899 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4900 ++init;
4901 }
4902 if (0 == sl_strncmp (sh.data.path, preq, 15))
4903 {
4904 if (sh.data.path[15] != '\0') /* should be start of path */
4905 {
4906 if (0 == stat(&(sh.data.path[15]), &buf))
4907 {
4908 SL_RETURN( S_FALSE, _("file_is_remote"));
4909 }
4910 else
4911 {
4912 char * tmp = sh_util_safe_name (&(sh.data.path[15]));
4913 sh_error_handle((-1), FIL__, __LINE__, S_FALSE, MSG_E_SUBGPATH,
4914 _("No local baseline database at expected path"),
4915 _("file_is_remote"),
4916 tmp);
4917 SH_FREE(tmp);
4918 }
4919 }
4920 else
4921 {
4922 sh_error_handle((-1), FIL__, __LINE__, S_FALSE, MSG_E_SUBGEN,
4923 _("No local baseline database path known"),
4924 _("file_is_remote"));
4925 }
4926 SL_RETURN( S_TRUE, _("file_is_remote"));
4927 }
4928 SL_RETURN( S_FALSE, _("file_is_remote"));
4929}
4930
4931/* Return the path to the configuration/database file.
4932 */
4933char * file_path(char what, char flag)
4934{
4935 static int init = 0;
4936
4937 SL_ENTER(_("file_path"));
4938
4939 if (init == 0)
4940 {
4941 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4942 ++init;
4943 }
4944
4945 switch (what)
4946 {
4947
4948 case 'C':
4949 if (0 == sl_strncmp (sh.conf.path, preq, 15))
4950 {
4951#if defined(SH_WITH_SERVER)
4952 if (sh.flag.isserver == S_TRUE && sl_strlen(sh.conf.path) == 15)
4953 SL_RETURN( NULL, _("file_path"));
4954 if (sh.flag.isserver == S_TRUE)
4955 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4956#endif
4957 if (flag == 'R')
4958 SL_RETURN( preq, _("file_path"));
4959 if (flag == 'I')
4960 {
4961 if (sl_strlen(sh.conf.path) == 15)
4962 SL_RETURN( NULL, _("file_path"));
4963 else
4964 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4965 }
4966 SL_RETURN ( preq, _("file_path"));
4967 }
4968 else
4969 SL_RETURN( sh.conf.path, _("file_path"));
4970 /* break; *//* unreachable */
4971
4972 case 'D':
4973 if (0 == sl_strncmp (sh.data.path, preq, 15))
4974 {
4975 if (flag == 'R')
4976 SL_RETURN( preq, _("file_path"));
4977 if (flag == 'W' && sl_strlen(sh.data.path) == 15)
4978 SL_RETURN (NULL, _("file_path"));
4979 if (flag == 'W')
4980 SL_RETURN( &(sh.data.path[15]), _("file_path"));
4981 }
4982 else
4983 SL_RETURN( sh.data.path, _("file_path"));
4984 break;
4985
4986 default:
4987 SL_RETURN( NULL, _("file_path"));
4988 }
4989
4990 return NULL; /* notreached */
4991}
4992/************************************************/
4993/**** Mlock Utilities ****/
4994/************************************************/
4995
4996#include <limits.h>
4997
4998int sh_unix_pagesize()
4999{
5000 int pagesize = 4096;
5001#if defined(_SC_PAGESIZE)
5002 pagesize = sysconf(_SC_PAGESIZE);
5003#elif defined(_SC_PAGE_SIZE)
5004 pagesize = sysconf(_SC_PAGE_SIZE);
5005#elif defined(HAVE_GETPAGESIZE)
5006 pagesize = getpagesize();
5007#elif defined(PAGESIZE)
5008 pagesize = PAGESIZE;
5009#endif
5010
5011 return ((pagesize > 0) ? pagesize : 4096);
5012}
5013
5014typedef struct sh_page_lt {
5015 unsigned long page_start;
5016 int page_refcount;
5017 char file[64];
5018 int line;
5019 struct sh_page_lt * next;
5020} sh_page_l;
5021
5022sh_page_l * sh_page_locked = NULL;
5023volatile int page_locking = 0;
5024
5025unsigned long sh_unix_lookup_page (void * in_addr, size_t len, int * num_pages)
5026{
5027 int pagesize = sh_unix_pagesize();
5028 unsigned long addr = (unsigned long) in_addr;
5029
5030 unsigned long pagebase;
5031 unsigned long pagediff;
5032 unsigned long pagenum = addr / pagesize;
5033
5034 SL_ENTER(_("sh_unix_lookup_page"));
5035#if 0
5036 fprintf(stderr, "mlock: --> base %ld, pagenum: %ld\n",
5037 addr, pagenum);
5038#endif
5039
5040 /* address of first page
5041 */
5042 pagebase = pagenum * pagesize;
5043
5044 /* number of pages
5045 */
5046 pagediff = (addr + len) - pagebase;
5047 pagenum = pagediff / pagesize;
5048 if (pagenum * pagesize < pagediff)
5049 ++pagenum;
5050
5051#if 0
5052 fprintf(stderr, "mlock: --> pagebase %ld, pagediff %ld, (addr + len) %ld\n",
5053 pagebase, pagediff, (addr + len));
5054#endif
5055
5056 *num_pages = pagenum;
5057 SL_RETURN((pagebase), _("sh_unix_lookup_page"));
5058}
5059
5060
5061#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5062
5063SH_MUTEX_STATIC(mutex_mlock,PTHREAD_MUTEX_INITIALIZER);
5064
5065int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
5066{
5067 int num_pages;
5068 int status = 0;
5069 int pagesize;
5070 sh_page_l * page_list;
5071 unsigned long addr;
5072#ifdef TEST_MLOCK
5073 int i = 0;
5074#endif
5075
5076 SL_ENTER(_("sh_unix_mlock"));
5077
5078 /* There's no cancellation point here, except if tracing is on
5079 */
5080 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5081
5082 page_list = sh_page_locked;
5083
5084 if (0 != page_locking)
5085 {
5086 status = -1;
5087 goto exit_mlock;
5088 }
5089
5090 page_locking = 1;
5091
5092 pagesize = sh_unix_pagesize();
5093 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
5094
5095#ifdef TEST_MLOCK
5096 fprintf(stderr, "mlock: addr %ld, base %ld, pages: %d, length %d\n",
5097 (unsigned long) in_addr, addr, num_pages, len);
5098#endif
5099
5100 /* increase refcount of locked pages
5101 * addr is first page; num_pages is #(consecutive pages) to lock
5102 */
5103
5104 while ((page_list != NULL) && (num_pages > 0))
5105 {
5106#ifdef TEST_MLOCK
5107 fprintf(stderr, "mlock: check page %d: %ld [%d]\n",
5108 i, page_list->page_start, page_list->page_refcount);
5109#endif
5110 if (page_list->page_start == addr)
5111 {
5112 page_list->page_refcount += 1;
5113 num_pages -= 1;
5114 addr += pagesize;
5115#ifdef TEST_MLOCK
5116 fprintf(stderr, "mlock: found page %d: %ld [%d], next page %ld\n",
5117 i, page_list->page_start, page_list->page_refcount, addr);
5118#endif
5119 }
5120#ifdef TEST_MLOCK
5121 ++i;
5122#endif
5123 page_list = page_list->next;
5124 }
5125
5126 /* mlock some more pages, if needed
5127 */
5128 while (num_pages > 0)
5129 {
5130#ifdef TEST_MLOCK
5131 fprintf(stderr, "mlock: lock page %d: mlock %ld [num_pages %d]\n",
5132 i, addr, num_pages);
5133 ++i;
5134#endif
5135 page_list = SH_ALLOC(sizeof(sh_page_l));
5136 page_list->page_start = addr;
5137 page_list->page_refcount = 1;
5138 sl_strlcpy(page_list->file, file, 64);
5139 page_list->line = line;
5140 status = mlock( (void *) addr, pagesize);
5141 if (status != 0)
5142 {
5143#ifdef TEST_MLOCK
5144 char errbuf[SH_ERRBUF_SIZE];
5145 fprintf(stderr, "mlock: error: %s\n",
5146 sh_error_message(errno, errbuf, sizeof(errbuf)));
5147#endif
5148 SH_FREE(page_list);
5149 page_locking = 0;
5150 goto exit_mlock;
5151 }
5152 page_list->next = sh_page_locked;
5153 sh_page_locked = page_list;
5154 num_pages -= 1;
5155 addr += pagesize;
5156 }
5157 page_locking = 0;
5158
5159 exit_mlock:
5160 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5161
5162 SL_RETURN((status), _("sh_unix_mlock"));
5163}
5164#else
5165int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
5166{
5167 (void) file; (void) line;
5168 (void) in_addr; (void) len;
5169 return -1;
5170}
5171#endif
5172
5173#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5174int sh_unix_munlock (void * in_addr, size_t len)
5175{
5176 int num_pages;
5177 int unlocked;
5178 int status;
5179 int pagesize;
5180 sh_page_l * page_list;
5181 sh_page_l * page_last;
5182 unsigned long addr;
5183
5184 int test_count;
5185 int test_status;
5186 int test_pages;
5187
5188#ifdef TEST_MLOCK
5189 int i = 0;
5190#endif
5191
5192 SL_ENTER(_("sh_unix_munlock"));
5193
5194 /* There's no cancellation point here, except if tracing is on
5195 */
5196 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5197
5198 unlocked = 0;
5199 status = 0;
5200 page_list = sh_page_locked;
5201
5202 if (0 != page_locking)
5203 {
5204 status = -1;
5205 goto exit_munlock;
5206 }
5207 page_locking = 1;
5208
5209 pagesize = sh_unix_pagesize();
5210 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
5211
5212#ifdef TEST_MLOCK
5213 fprintf(stderr, "munlock: in_addr %ld, addr %ld, pages: %d, length %d\n",
5214 (unsigned long) in_addr, addr, num_pages, len);
5215#endif
5216
5217 test_pages = num_pages;
5218
5219 /* reduce refcount of locked pages
5220 * addr is first page; num_pages is #(consecutive pages) to lock
5221 */
5222 while ((page_list != NULL) && (num_pages > 0))
5223 {
5224#ifdef TEST_MLOCK
5225 fprintf(stderr, "munlock: page %d: %ld [%d]\n",
5226 i, page_list->page_start, page_list->page_refcount);
5227#endif
5228
5229 test_status = 0;
5230 for (test_count = 0; test_count < test_pages; ++test_count)
5231 {
5232 if (page_list->page_start == (addr + (test_count * pagesize)))
5233 {
5234 test_status = 1;
5235 break;
5236 }
5237 }
5238
5239 if (test_status == 1)
5240 {
5241 page_list->page_refcount -= 1;
5242 if (page_list->page_refcount == 0)
5243 {
5244 status = munlock ( (void *) addr, pagesize);
5245 ++unlocked;
5246 }
5247 num_pages -= 1;
5248#ifdef TEST_MLOCK
5249 fprintf(stderr,
5250 "munlock: page %d: %ld [refcount %d], refcount reduced\n",
5251 i, page_list->page_start, page_list->page_refcount);
5252#endif
5253 }
5254#ifdef TEST_MLOCK
5255 ++i;
5256#endif
5257 page_list = page_list->next;
5258 }
5259
5260#ifdef TEST_MLOCK
5261 i = 0;
5262#endif
5263
5264 if (unlocked > 0)
5265 {
5266 page_list = sh_page_locked;
5267 page_last = sh_page_locked;
5268
5269 while ((page_list != NULL) && (unlocked > 0))
5270 {
5271 if (page_list->page_refcount == 0)
5272 {
5273#ifdef TEST_MLOCK
5274 fprintf(stderr, "munlock: remove page %d: %ld [refcount %d]\n",
5275 i, page_list->page_start, page_list->page_refcount);
5276#endif
5277 if (page_last != page_list)
5278 {
5279 page_last->next = page_list->next;
5280 SH_FREE(page_list);
5281 page_list = page_last->next;
5282 }
5283 else
5284 {
5285 page_last = page_list->next;
5286 if (page_list == sh_page_locked)
5287 sh_page_locked = page_list->next;
5288 SH_FREE(page_list);
5289 page_list = page_last;
5290 }
5291 --unlocked;
5292 }
5293 else
5294 {
5295#ifdef TEST_MLOCK
5296 fprintf(stderr, "munlock: skip page %d: %ld [refcount %d]\n",
5297 i, page_list->page_start, page_list->page_refcount);
5298#endif
5299
5300 page_last = page_list;
5301 page_list = page_list->next;
5302 }
5303#ifdef TEST_MLOCK
5304 ++i;
5305#endif
5306 }
5307 }
5308
5309 page_locking = 0;
5310
5311 exit_munlock:
5312 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5313 SL_RETURN((status), _("sh_unix_munlock"));
5314}
5315#else
5316int sh_unix_munlock (void * in_addr, size_t len)
5317{
5318 (void) in_addr; (void) len;
5319 return -1;
5320}
5321#endif
5322
5323int sh_unix_count_mlock()
5324{
5325 unsigned int i = 0;
5326 char str[32][64];
5327 sh_page_l * page_list;
5328
5329 SL_ENTER(_("sh_unix_count_mlock"));
5330
5331#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5332 /* There's no cancellation point here, except if tracing is on
5333 */
5334 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5335#endif
5336
5337 page_list = sh_page_locked;
5338
5339 while (page_list != NULL)
5340 {
5341#ifdef WITH_TPT
5342 if (i < 32)
5343 sl_snprintf(str[i], 64, _("file: %s line: %d page: %d"),
5344 page_list->file, page_list->line, i+1);
5345#endif
5346 page_list = page_list->next;
5347 ++i;
5348 }
5349
5350#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5351 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5352#endif
5353
5354#ifdef WITH_TPT
5355 {
5356 unsigned int j = 0;
5357 while (j < i && j < 32)
5358 {
5359 sh_error_handle(SH_ERR_ALL, FIL__, __LINE__, j, MSG_E_SUBGEN,
5360 str[j], _("sh_unix_count_mlock"));
5361 ++j;
5362 }
5363 }
5364#endif
5365
5366 sl_snprintf(str[0], 64, _("%d pages locked"), i);
5367 sh_error_handle(SH_ERR_ALL, FIL__, __LINE__, i, MSG_E_SUBGEN,
5368 str[0], _("sh_unix_count_mlock"));
5369 SL_RETURN((i), _("sh_unix_count_mlock"));
5370}
5371
5372/************************************************/
5373/************************************************/
5374/**** Stealth Utilities ****/
5375/************************************************/
5376/************************************************/
5377#ifdef SH_STEALTH
5378
5379void sh_unix_xor_code (char * str, int len)
5380{
5381 register int i;
5382
5383 for (i = 0; i < len; ++i) str[i] ^= (char) XOR_CODE;
5384 return;
5385}
5386
5387#if !defined(SH_STEALTH_MICRO)
5388
5389
5390int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5391 unsigned long * bytes_read);
5392unsigned long first_hex_block(SL_TICKET fd, unsigned long * max);
5393
5394/*
5395 * --- Get hidden data from a block of hex data. ---
5396 */
5397int sh_unix_getline_stealth (SL_TICKET fd, char * str, int len)
5398{
5399 int add_off = 0, llen;
5400 static unsigned long off_data = 0;
5401 static unsigned long max_data = 0;
5402 static unsigned long bytes_read = 0;
5403 static int stealth_init = BAD;
5404
5405 SL_ENTER(_("sh_unix_getline_stealth"));
5406
5407 if (str == NULL)
5408 {
5409 off_data = 0;
5410 max_data = 0;
5411 bytes_read = 0;
5412 stealth_init = BAD;
5413 SL_RETURN(0, _("sh_unix_getline_stealth"));
5414 }
5415
5416 /* --- Initialize. ---
5417 */
5418 if (stealth_init == BAD)
5419 {
5420 off_data = first_hex_block(fd, &max_data);
5421 if (off_data == 0)
5422 {
5423 dlog(1, FIL__, __LINE__,
5424 _("The stealth config file does not contain any steganographically\nhidden data. This file must be an image file in _uncompressed_\npostscript format.\nTo hide data in it, use:\n samhain_stealth -s postscript_file orig_config_file\n mv postscript_file /path/to/config/file\n"));
5425 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5426 _("Stealth config file."));
5427 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5428 }
5429 stealth_init = GOOD;
5430 max_data += off_data;
5431 }
5432
5433 /* --- Seek to proper position. ---
5434 */
5435 if (bytes_read >= max_data || add_off < 0)
5436 {
5437 dlog(1, FIL__, __LINE__,
5438 _("The capacity of the container image file for the stealth config file seems to be too small. Your config file is likely truncated.\n"));
5439 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5440 _("Stealth config file."));
5441 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5442 }
5443 sl_seek(fd, off_data);
5444
5445 /* --- Read one line. ---
5446 */
5447 add_off = hideout_hex_block(fd, (unsigned char *) str, len, &bytes_read);
5448 off_data += add_off;
5449
5450 llen = sl_strlen(str);
5451 SL_RETURN(llen, _("sh_unix_getline_stealth"));
5452}
5453
5454int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5455 unsigned long * bytes_read)
5456{
5457
5458 register int i, j, k;
5459 unsigned char c, e;
5460 register int num;
5461 unsigned char mask[9] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
5462 unsigned long here = 0;
5463 unsigned long retval = 0;
5464 unsigned long bread = 0;
5465
5466 SL_ENTER(_("hideout_hex_block"));
5467
5468 ASSERT_RET((len > 1), _("len > 1"), (0));
5469
5470 --len;
5471
5472 i = 0;
5473 while (i < len)
5474 {
5475 for (j = 0; j < 8; ++j)
5476 {
5477
5478 /* --- Get a low byte, modify, read back. ---
5479 */
5480 for (k = 0; k < 2; ++k)
5481 {
5482 /* -- Skip whitespace. ---
5483 */
5484 c = ' ';
5485 do {
5486 do {
5487 num = sl_read (fd, &c, 1);
5488 } while (num == 0 && errno == EINTR);
5489 if (num > 0)
5490 ++here;
5491 else if (num == 0)
5492 SL_RETURN((0), _("hideout_hex_block"));
5493 else
5494 SL_RETURN((-1), _("hideout_hex_block"));
5495 } while (c == '\n' || c == '\t' || c == '\r' ||
5496 c == ' ');
5497 }
5498
5499
5500 /* --- e is the value of the low byte. ---
5501 */
5502 e = (unsigned char) sh_util_hexchar( c );
5503 if ((e & mask[7]) != 0) /* bit is set */
5504 str[i] |= mask[j];
5505 else /* bit is not set */
5506 str[i] &= ~mask[j];
5507
5508 bread += 1;
5509 }
5510 if (str[i] == '\n') break;
5511 ++i;
5512 }
5513
5514 if (i != 0)
5515 str[i] = '\0';
5516 else
5517 str[i+1] = '\0'; /* keep newline and terminate */
5518 retval += here;
5519 *bytes_read += (bread/8);
5520
5521 SL_RETURN(retval, _("hideout_hex_block"));
5522}
5523
5524/* --- Get offset of first data block. ---
5525 */
5526unsigned long first_hex_block(SL_TICKET fd, unsigned long * max)
5527{
5528 unsigned int i;
5529 long num = 1;
5530 unsigned long lnum;
5531 char c;
5532 int nothex = 0;
5533 unsigned long retval = 0;
5534 unsigned int this_line = 0;
5535 char theline[SH_BUFSIZE];
5536
5537 SL_ENTER(_("first_hex_block"));
5538
5539 *max = 0;
5540
5541 while (1)
5542 {
5543 theline[0] = '\0';
5544 this_line = 0;
5545 c = '\0';
5546 while (c != '\n' && this_line < (sizeof(theline)-1))
5547 {
5548 do {
5549 num = sl_read (fd, &c, 1);
5550 } while (num == 0 && errno == EINTR);
5551 if (num > 0)
5552 theline[this_line] = c;
5553 else
5554 SL_RETURN((0), _("first_hex_block"));
5555 ++this_line;
5556 }
5557 theline[this_line] = '\0';
5558
5559 /* not only 'newline' */
5560 if (this_line > 60)
5561 {
5562 nothex = 0;
5563 i = 0;
5564 while (nothex == 0 && i < (this_line-1))
5565 {
5566 if (! isxdigit((int)theline[i])) nothex = 1;
5567 ++i;
5568 }
5569 if (nothex == 1) retval += this_line;
5570 }
5571 else
5572 {
5573 nothex = 1;
5574 retval += this_line;
5575 }
5576
5577 if (nothex == 0)
5578 {
5579 *max = 0;
5580 do {
5581 do {
5582 num = sl_read (fd, theline, SH_BUFSIZE);
5583 } while (num == 0 && errno == EINTR);
5584 if (num > 0)
5585 {
5586 lnum = (unsigned long) num;
5587 for (i = 0; i < lnum; ++i)
5588 {
5589 c = theline[i];
5590 if (c == '\n' || c == '\t' || c == '\r' || c == ' ')
5591 ;
5592 else if (!isxdigit((int)c))
5593 break;
5594 else
5595 *max += 1;
5596 }
5597 }
5598 } while (num > 0);
5599
5600 *max /= 16;
5601 SL_RETURN((retval), _("first_hex_block"));
5602 }
5603
5604 }
5605 /* SL_RETURN((0), _("first_hex_block")); *//* unreachable */
5606}
5607
5608 /* if !defined(SH_STEALTH_MICRO) */
5609#endif
5610
5611 /* ifdef SH_STEALTH */
5612#endif
5613
5614/*
5615 * anti-debugger code
5616 */
5617#if defined(SCREW_IT_UP)
5618
5619#if defined(HAVE_PTHREAD)
5620
5621static pthread_key_t gSigtrapVariables_key;
5622static pthread_once_t gSigtrapVariables_key_once = PTHREAD_ONCE_INIT;
5623
5624static inline void make_gSigtrapVariables_key()
5625{
5626 (void) pthread_key_create(&gSigtrapVariables_key, free);
5627}
5628
5629struct sh_sigtrap_variables * sh_sigtrap_variables_get()
5630{
5631 void * ptr;
5632
5633 (void) pthread_once(&gSigtrapVariables_key_once, make_gSigtrapVariables_key);
5634
5635 ptr = pthread_getspecific(gSigtrapVariables_key);
5636 if (ptr == NULL) {
5637 ptr = calloc(1,sizeof(struct sh_sigtrap_variables));
5638 if (ptr == NULL) {
5639 return NULL;
5640 }
5641 (void) pthread_setspecific(gSigtrapVariables_key, ptr);
5642 }
5643
5644 return (struct sh_sigtrap_variables *) ptr;
5645}
5646
5647/* !defined(HAVE_PTHREAD) */
5648#else
5649
5650static struct sh_sigtrap_variables global_sigtrap_variables;
5651struct sh_sigtrap_variables * sh_sigtrap_variables_get()
5652{
5653 return &global_sigtrap_variables;
5654}
5655
5656#endif
5657
5658int sh_sigtrap_max_duration_set (const char * str)
5659{
5660 /* For security (prevent reloading with larger value)
5661 * this value can only be set once.
5662 */
5663 static int once = 0;
5664 int i;
5665
5666 SL_ENTER(_("sh_sigtrap_max_duration_set"));
5667
5668 i = atoi (str);
5669
5670 if (i >= 0 && once == 0)
5671 {
5672 sh.sigtrap_max_duration = i;
5673 once = 1;
5674 }
5675 else
5676 {
5677 SL_RETURN ((-1), _("sh_sigtrap_max_duration_set"));
5678 }
5679 SL_RETURN( (0), _("sh_sigtrap_max_duration_set"));
5680}
5681
5682void sh_sigtrap_handler (int signum)
5683{
5684 struct sh_sigtrap_variables * sigtrap_variables;
5685 sigtrap_variables = sh_sigtrap_variables_get();
5686 if (sigtrap_variables == NULL) {
5687 /* Perhaps, it's better to not die, and to continue using Samhain,
5688 even if this part does not work. */
5689 return;
5690 }
5691
5692#ifdef HAVE_GETTIMEOFDAY
5693 {
5694 struct timeval tv;
5695 long difftv;
5696
5697 gettimeofday(&tv, NULL);
5698 difftv = (tv.tv_sec - sigtrap_variables->save_tv.tv_sec) * 1000000 +
5699 (tv.tv_usec - sigtrap_variables->save_tv.tv_usec);
5700 if (difftv > sh.sigtrap_max_duration)
5701 raise(SIGKILL);
5702 }
5703#endif
5704
5705 sigtrap_variables->not_traced = signum;
5706 /* cppcheck-suppress memleak */
5707 return;
5708}
5709#endif
Note: See TracBrowser for help on using the repository browser.