source: trunk/src/sh_unix.c@ 583

Last change on this file since 583 was 583, checked in by katerina, 27 hours ago

Fix for ticket #471 (autoreconf throws warnings/errors).

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