diff options
Diffstat (limited to '')
30 files changed, 4781 insertions, 0 deletions
diff --git a/lib/eventlog/Makefile.in b/lib/eventlog/Makefile.in new file mode 100644 index 0000000..8bfd959 --- /dev/null +++ b/lib/eventlog/Makefile.in @@ -0,0 +1,350 @@ +# +# SPDX-License-Identifier: ISC +# +# Copyright (c) 2020-2023 Todd C. Miller <Todd.Miller@sudo.ws> +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# +# @configure_input@ +# + +#### Start of system configuration section. #### + +srcdir = @srcdir@ +abs_srcdir = @abs_srcdir@ +top_srcdir = @top_srcdir@ +abs_top_srcdir = @abs_top_srcdir@ +top_builddir = @top_builddir@ +abs_top_builddir = @abs_top_builddir@ +devdir = @devdir@ +scriptdir = $(top_srcdir)/scripts +incdir = $(top_srcdir)/include + +# Compiler & tools to use +CC = @CC@ +LIBTOOL = @LIBTOOL@ +EGREP = @EGREP@ +SED = @SED@ + +# C preprocessor flags +CPPFLAGS = -I$(incdir) -I$(top_builddir) -I$(srcdir) -I$(top_srcdir) @CPPFLAGS@ + +# Usually -O and/or -g +CFLAGS = @CFLAGS@ + +# Flags to pass to the link stage +LDFLAGS = @LDFLAGS@ + +# Flags to pass to libtool +LTFLAGS = @LT_STATIC@ + +# Libraries +LIBUTIL = $(top_builddir)/lib/util/libsudo_util.la +LT_LIBS = $(LIBUTIL) +LIBS = $(LT_LIBS) + +# Address sanitizer flags +ASAN_CFLAGS = @ASAN_CFLAGS@ +ASAN_LDFLAGS = @ASAN_LDFLAGS@ + +# PIE flags +PIE_CFLAGS = @PIE_CFLAGS@ +PIE_LDFLAGS = @PIE_LDFLAGS@ + +# Stack smashing protection flags +HARDENING_CFLAGS = @HARDENING_CFLAGS@ +HARDENING_LDFLAGS = @HARDENING_LDFLAGS@ + +# cppcheck options, usually set in the top-level Makefile +CPPCHECK_OPTS = -q --enable=warning,performance,portability --suppress=constStatement --suppress=compareBoolExpressionWithInt --error-exitcode=1 --inline-suppr -Dva_copy=va_copy -U__cplusplus -UQUAD_MAX -UQUAD_MIN -UUQUAD_MAX -U_POSIX_HOST_NAME_MAX -U_POSIX_PATH_MAX -U__NBBY -DNSIG=64 + +# splint options, usually set in the top-level Makefile +SPLINT_OPTS = -D__restrict= -checks + +# PVS-studio options +PVS_CFG = $(top_srcdir)/PVS-Studio.cfg +PVS_IGNORE = 'V707,V011,V002,V536' +PVS_LOG_OPTS = -a 'GA:1,2' -e -t errorfile -d $(PVS_IGNORE) + +# Set to non-empty for development mode +DEVEL = @DEVEL@ + +#### End of system configuration section. #### + +SHELL = @SHELL@ + +TEST_PROGS = check_wrap check_parse_json store_json_test store_sudo_test +TEST_VERBOSE = + +LIBEVENTLOG_OBJS = eventlog.lo eventlog_conf.lo eventlog_free.lo logwrap.lo \ + parse_json.lo + +IOBJS = $(LIBEVENTLOG_OBJS:.lo=.i) + +POBJS = $(IOBJS:.i=.plog) + +CHECK_WRAP_OBJS = check_wrap.lo logwrap.lo + +CHECK_PARSE_JSON_OBJS = check_parse_json.lo parse_json.lo + +STORE_JSON_TEST_OBJS = store_json_test.lo + +STORE_SUDO_TEST_OBJS = store_sudo_test.lo + +all: libsudo_eventlog.la + +depend: + $(scriptdir)/mkdep.pl --srcdir=$(abs_top_srcdir) \ + --builddir=$(abs_top_builddir) lib/eventlog/Makefile.in + cd $(top_builddir) && ./config.status --file lib/eventlog/Makefile + +Makefile: $(srcdir)/Makefile.in + cd $(top_builddir) && ./config.status --file lib/eventlog/Makefile + +.SUFFIXES: .c .h .i .lo .plog + +.c.lo: + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $< + +.c.i: + $(CC) -E -o $@ $(CPPFLAGS) $< + +.i.plog: + ifile=$<; rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $${ifile%i}c --i-file $< --output-file $@ + +libsudo_eventlog.la: $(LIBEVENTLOG_OBJS) $(LT_LIBS) + $(LIBTOOL) $(LTFLAGS) --mode=link $(CC) -o $@ $(LIBEVENTLOG_OBJS) $(LT_LIBS) + +check_parse_json: $(CHECK_PARSE_JSON_OBJS) $(LIBUTIL) + $(LIBTOOL) $(LTFLAGS) --mode=link $(CC) -o $@ $(CHECK_PARSE_JSON_OBJS) $(LDFLAGS) $(ASAN_LDFLAGS) $(PIE_LDFLAGS) $(HARDENING_LDFLAGS) $(LIBS) + +check_wrap: $(CHECK_WRAP_OBJS) $(LIBUTIL) $(LIBUTIL) + $(LIBTOOL) $(LTFLAGS) --mode=link $(CC) -o $@ $(CHECK_WRAP_OBJS) $(LDFLAGS) $(ASAN_LDFLAGS) $(PIE_LDFLAGS) $(HARDENING_LDFLAGS) $(LIBS) + +store_json_test: $(STORE_JSON_TEST_OBJS) $(LIBUTIL) libsudo_eventlog.la + $(LIBTOOL) $(LTFLAGS) --mode=link $(CC) -o $@ $(STORE_JSON_TEST_OBJS) $(LDFLAGS) $(ASAN_LDFLAGS) $(PIE_LDFLAGS) $(HARDENING_LDFLAGS) $(LIBS) libsudo_eventlog.la + +store_sudo_test: $(STORE_SUDO_TEST_OBJS) $(LIBUTIL) libsudo_eventlog.la + $(LIBTOOL) $(LTFLAGS) --mode=link $(CC) -o $@ $(STORE_SUDO_TEST_OBJS) $(LDFLAGS) $(ASAN_LDFLAGS) $(PIE_LDFLAGS) $(HARDENING_LDFLAGS) $(LIBS) libsudo_eventlog.la + +pre-install: + +install: + +install-binaries: + +install-includes: + +install-doc: + +install-plugin: + +install-fuzzer: + +uninstall: + +splint: + splint $(SPLINT_OPTS) -I$(incdir) -I$(top_builddir) -I$(top_srcdir) $(srcdir)/*.c + +cppcheck: + cppcheck $(CPPCHECK_OPTS) -I$(incdir) -I$(top_builddir) -I$(top_srcdir) $(srcdir)/*.c + +pvs-log-files: $(POBJS) + +pvs-studio: $(POBJS) + plog-converter $(PVS_LOG_OPTS) $(POBJS) + +fuzz: + +check-fuzzer: + +check: $(TEST_PROGS) check-fuzzer + @if test X"$(cross_compiling)" != X"yes"; then \ + l=`locale -a 2>&1 | $(EGREP) -i '^C\.UTF-?8$$' | $(SED) 1q` || true; \ + test -n "$$l" || l="C"; \ + LC_ALL="$$l"; export LC_ALL; \ + unset LANG || LANG=; \ + unset LANGUAGE || LANGUAGE=; \ + MALLOC_OPTIONS=S; export MALLOC_OPTIONS; \ + MALLOC_CONF="abort:true,junk:true"; export MALLOC_CONF; \ + umask 022; \ + rval=0; \ + ./check_parse_json $(TEST_VERBOSE) $(srcdir)/regress/parse_json/*.in || rval=`expr $$rval + $$?`; \ + ./store_json_test $(TEST_VERBOSE) $(srcdir)/regress/eventlog_store/*.json.in || rval=`expr $$rval + $$?`; \ + ./store_sudo_test $(TEST_VERBOSE) $(srcdir)/regress/eventlog_store/*.json.in || rval=`expr $$rval + $$?`; \ + mkdir -p regress/logwrap; \ + ./check_wrap $(TEST_VERBOSE) $(srcdir)/regress/logwrap/check_wrap.in > regress/logwrap/check_wrap.out; \ + diff regress/logwrap/check_wrap.out $(srcdir)/regress/logwrap/check_wrap.out.ok || rval=`expr $$rval + $$?`; \ + exit $$rval; \ + fi + +check-verbose: + exec $(MAKE) $(MFLAGS) TEST_VERBOSE=-v FUZZ_VERBOSE=-verbosity=1 check + +clean: + -$(LIBTOOL) $(LTFLAGS) --mode=clean rm -f *.lo *.o *.la $(TEST_PROGS) + -rm -f *.i *.plog stamp-* core *.core core.* regress/*/*.out + +mostlyclean: clean + +distclean: clean + -rm -rf Makefile .libs + +clobber: distclean + +realclean: distclean + rm -f TAGS tags + +cleandir: realclean + +.PHONY: clean mostlyclean distclean cleandir clobber realclean + +# Autogenerated dependencies, do not modify +check_parse_json.lo: $(srcdir)/regress/parse_json/check_parse_json.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_json.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(srcdir)/parse_json.h $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/regress/parse_json/check_parse_json.c +check_parse_json.i: $(srcdir)/regress/parse_json/check_parse_json.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_json.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(srcdir)/parse_json.h $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +check_parse_json.plog: check_parse_json.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/regress/parse_json/check_parse_json.c --i-file $< --output-file $@ +check_wrap.lo: $(srcdir)/regress/logwrap/check_wrap.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_util.h \ + $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/regress/logwrap/check_wrap.c +check_wrap.i: $(srcdir)/regress/logwrap/check_wrap.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_util.h \ + $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +check_wrap.plog: check_wrap.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/regress/logwrap/check_wrap.c --i-file $< --output-file $@ +eventlog.lo: $(srcdir)/eventlog.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_lbuf.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(top_builddir)/config.h $(top_builddir)/pathnames.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/eventlog.c +eventlog.i: $(srcdir)/eventlog.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_lbuf.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(top_builddir)/config.h $(top_builddir)/pathnames.h + $(CC) -E -o $@ $(CPPFLAGS) $< +eventlog.plog: eventlog.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/eventlog.c --i-file $< --output-file $@ +eventlog_conf.lo: $(srcdir)/eventlog_conf.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h \ + $(top_builddir)/pathnames.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/eventlog_conf.c +eventlog_conf.i: $(srcdir)/eventlog_conf.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h \ + $(top_builddir)/pathnames.h + $(CC) -E -o $@ $(CPPFLAGS) $< +eventlog_conf.plog: eventlog_conf.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/eventlog_conf.c --i-file $< --output-file $@ +eventlog_free.lo: $(srcdir)/eventlog_free.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/eventlog_free.c +eventlog_free.i: $(srcdir)/eventlog_free.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +eventlog_free.plog: eventlog_free.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/eventlog_free.c --i-file $< --output-file $@ +logwrap.lo: $(srcdir)/logwrap.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/logwrap.c +logwrap.i: $(srcdir)/logwrap.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +logwrap.plog: logwrap.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/logwrap.c --i-file $< --output-file $@ +parse_json.lo: $(srcdir)/parse_json.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(srcdir)/parse_json.h \ + $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/parse_json.c +parse_json.i: $(srcdir)/parse_json.c $(incdir)/compat/stdbool.h \ + $(incdir)/sudo_compat.h $(incdir)/sudo_debug.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_gettext.h $(incdir)/sudo_json.h \ + $(incdir)/sudo_plugin.h $(incdir)/sudo_queue.h \ + $(incdir)/sudo_util.h $(srcdir)/parse_json.h \ + $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +parse_json.plog: parse_json.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/parse_json.c --i-file $< --output-file $@ +store_json_test.lo: $(srcdir)/regress/eventlog_store/store_json_test.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_json.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(srcdir)/parse_json.h $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/regress/eventlog_store/store_json_test.c +store_json_test.i: $(srcdir)/regress/eventlog_store/store_json_test.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_json.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_queue.h $(incdir)/sudo_util.h \ + $(srcdir)/parse_json.h $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +store_json_test.plog: store_json_test.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/regress/eventlog_store/store_json_test.c --i-file $< --output-file $@ +store_sudo_test.lo: $(srcdir)/regress/eventlog_store/store_sudo_test.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_lbuf.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(LIBTOOL) $(LTFLAGS) --mode=compile $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $(ASAN_CFLAGS) $(PIE_CFLAGS) $(HARDENING_CFLAGS) $(srcdir)/regress/eventlog_store/store_sudo_test.c +store_sudo_test.i: $(srcdir)/regress/eventlog_store/store_sudo_test.c \ + $(incdir)/compat/stdbool.h $(incdir)/sudo_compat.h \ + $(incdir)/sudo_eventlog.h $(incdir)/sudo_fatal.h \ + $(incdir)/sudo_lbuf.h $(incdir)/sudo_plugin.h \ + $(incdir)/sudo_util.h $(top_builddir)/config.h + $(CC) -E -o $@ $(CPPFLAGS) $< +store_sudo_test.plog: store_sudo_test.i + rm -f $@; pvs-studio --cfg $(PVS_CFG) --sourcetree-root $(top_srcdir) --skip-cl-exe yes --source-file $(srcdir)/regress/eventlog_store/store_sudo_test.c --i-file $< --output-file $@ diff --git a/lib/eventlog/eventlog.c b/lib/eventlog/eventlog.c new file mode 100644 index 0000000..ab27227 --- /dev/null +++ b/lib/eventlog/eventlog.c @@ -0,0 +1,1462 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 1994-1996, 1998-2023 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ + +/* + * This is an open source non-commercial project. Dear PVS-Studio, please check it. + * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + */ + +#include <config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <netinet/in.h> + +#include <ctype.h> +#include <errno.h> +#include <fcntl.h> +#include <grp.h> +#include <locale.h> +#include <pwd.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <syslog.h> +#include <time.h> +#include <unistd.h> + +#include <pathnames.h> +#include <sudo_compat.h> +#include <sudo_debug.h> +#include <sudo_eventlog.h> +#include <sudo_lbuf.h> +#include <sudo_fatal.h> +#include <sudo_gettext.h> +#include <sudo_json.h> +#include <sudo_queue.h> +#include <sudo_util.h> + +#define IS_SESSID(s) ( \ + isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \ + (s)[2] == '/' && \ + isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \ + (s)[5] == '/' && \ + isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \ + (s)[8] == '\0') + +struct eventlog_args { + const char *reason; + const char *errstr; + const struct timespec *event_time; + eventlog_json_callback_t json_info_cb; + void *json_info; +}; + +/* + * Allocate and fill in a new logline. + */ +static bool +new_logline(int event_type, int flags, struct eventlog_args *args, + const struct eventlog *evlog, struct sudo_lbuf *lbuf) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const char *iolog_file; + const char *tty, *tsid = NULL; + char exit_str[STRLEN_MAX_SIGNED(int) + 1]; + char sessid[7], offsetstr[64] = ""; + size_t i; + debug_decl(new_logline, SUDO_DEBUG_UTIL); + + if (ISSET(flags, EVLOG_RAW) || evlog == NULL) { + if (args->reason != NULL) { + if (args->errstr != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "%s: %s", + args->reason, args->errstr); + } else { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "%s", args->reason); + } + if (sudo_lbuf_error(lbuf)) + goto oom; + } + debug_return_bool(true); + } + + /* A TSID may be a sudoers-style session ID or a free-form string. */ + iolog_file = evlog->iolog_file; + if (iolog_file != NULL) { + if (IS_SESSID(iolog_file)) { + sessid[0] = iolog_file[0]; + sessid[1] = iolog_file[1]; + sessid[2] = iolog_file[3]; + sessid[3] = iolog_file[4]; + sessid[4] = iolog_file[6]; + sessid[5] = iolog_file[7]; + sessid[6] = '\0'; + tsid = sessid; + } else { + tsid = iolog_file; + } + if (sudo_timespecisset(&evlog->iolog_offset)) { + /* Only write up to two significant digits for the decimal part. */ + if (evlog->iolog_offset.tv_nsec > 10000000) { + (void)snprintf(offsetstr, sizeof(offsetstr), "@%lld.%02ld", + (long long)evlog->iolog_offset.tv_sec, + evlog->iolog_offset.tv_nsec / 10000000); + } else if (evlog->iolog_offset.tv_sec != 0) { + (void)snprintf(offsetstr, sizeof(offsetstr), "@%lld", + (long long)evlog->iolog_offset.tv_sec); + } + } + } + + /* Sudo-format logs use the short form of the ttyname. */ + if ((tty = evlog->ttyname) != NULL) { + if (strncmp(tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) + tty += sizeof(_PATH_DEV) - 1; + } + + /* + * Format the log line as an lbuf, escaping control characters in + * octal form (#0nn). Error checking (ENOMEM) is done at the end. + */ + if (args->reason != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "%s%s", args->reason, + args->errstr ? " : " : " ; "); + } + if (args->errstr != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "%s ; ", args->errstr); + } + if (evlog->submithost != NULL && !evl_conf->omit_hostname) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "HOST=%s ; ", + evlog->submithost); + } + if (tty != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "TTY=%s ; ", tty); + } + if (evlog->runchroot != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "CHROOT=%s ; ", + evlog->runchroot); + } + if (evlog->runcwd != NULL || evlog->cwd != NULL) { + if (ISSET(flags, EVLOG_CWD)) { + /* For sudoreplay -l output format. */ + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "CWD=%s ; ", + evlog->runcwd ? evlog->runcwd : evlog->cwd); + } else if (evlog->runcwd != NULL) { + /* For backwards compatibility with sudo log format. */ + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "PWD=%s ; ", + evlog->runcwd); + } + } + if (evlog->runuser != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "USER=%s ; ", + evlog->runuser); + } + if (evlog->rungroup != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "GROUP=%s ; ", + evlog->rungroup); + } + if (tsid != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "TSID=%s%s ; ", tsid, + offsetstr); + } + if (evlog->env_add != NULL && evlog->env_add[0] != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "ENV=%s", + evlog->env_add[0]); + for (i = 1; evlog->env_add[i] != NULL; i++) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, " %s", + evlog->env_add[i]); + } + sudo_lbuf_append(lbuf, " ; "); + } + if (evlog->command != NULL && evlog->runargv != NULL) { + /* Command plus argv. */ + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_BLANK, + "COMMAND=%s", evlog->command); + if (evlog->runargv[0] != NULL) { + for (i = 1; evlog->runargv[i] != NULL; i++) { + sudo_lbuf_append(lbuf, " "); + if (strchr(evlog->runargv[i], ' ') != NULL) { + /* Wrap args containing spaces in single quotes. */ + sudo_lbuf_append(lbuf, "'"); + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_QUOTE, + "%s", evlog->runargv[i]); + sudo_lbuf_append(lbuf, "'"); + } else { + /* Escape quotes here too for consistency. */ + sudo_lbuf_append_esc(lbuf, + LBUF_ESC_CNTRL|LBUF_ESC_BLANK|LBUF_ESC_QUOTE, + "%s", evlog->runargv[i]); + } + } + } + if (event_type == EVLOG_EXIT) { + if (evlog->signal_name != NULL) { + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, " ; SIGNAL=%s", + evlog->signal_name); + } + if (evlog->exit_value != -1) { + (void)snprintf(exit_str, sizeof(exit_str), "%d", + evlog->exit_value); + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, " ; EXIT=%s", + exit_str); + } + } + } else if (evlog->command != NULL) { + /* Just the command, no argv. */ + sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, "COMMAND=%s", + evlog->command); + } + + if (!sudo_lbuf_error(lbuf)) + debug_return_bool(true); +oom: + sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); + debug_return_bool(false); +} + +bool +eventlog_store_sudo(int event_type, const struct eventlog *evlog, + struct sudo_lbuf *lbuf) +{ + struct eventlog_args args = { NULL }; + + return new_logline(event_type, EVLOG_CWD, &args, evlog, lbuf); +} + +static void +closefrom_nodebug(int lowfd) +{ + unsigned char *debug_fds; + int fd, startfd; + debug_decl(closefrom_nodebug, SUDO_DEBUG_UTIL); + + startfd = sudo_debug_get_fds(&debug_fds) + 1; + if (lowfd > startfd) + startfd = lowfd; + + /* Close fds higher than the debug fds. */ + sudo_debug_printf(SUDO_DEBUG_DEBUG|SUDO_DEBUG_LINENO, + "closing fds >= %d", startfd); + closefrom(startfd); + + /* Close fds [lowfd, startfd) that are not in debug_fds. */ + for (fd = lowfd; fd < startfd; fd++) { + if (sudo_isset(debug_fds, fd)) + continue; + sudo_debug_printf(SUDO_DEBUG_DEBUG|SUDO_DEBUG_LINENO, + "closing fd %d", fd); +#ifdef __APPLE__ + /* Avoid potential libdispatch crash when we close its fds. */ + (void) fcntl(fd, F_SETFD, FD_CLOEXEC); +#else + (void) close(fd); +#endif + } + debug_return; +} + +#define MAX_MAILFLAGS 63 + +sudo_noreturn static void +exec_mailer(int pipein) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + char *last, *mflags, *p, *argv[MAX_MAILFLAGS + 1]; + const char *mpath = evl_conf->mailerpath; + size_t i; + const char * const root_envp[] = { + "HOME=/", + "PATH=/usr/bin:/bin:/usr/sbin:/sbin", + "LOGNAME=root", + "USER=root", +# ifdef _AIX + "LOGIN=root", +# endif + NULL + }; + debug_decl(exec_mailer, SUDO_DEBUG_UTIL); + + /* Set stdin to read side of the pipe. */ + if (dup3(pipein, STDIN_FILENO, 0) == -1) { + syslog(LOG_ERR, _("unable to dup stdin: %m")); // -V618 + sudo_debug_printf(SUDO_DEBUG_ERROR, + "unable to dup stdin: %s", strerror(errno)); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(127); + } + + /* Build up an argv based on the mailer path and flags */ + if ((mflags = strdup(evl_conf->mailerflags)) == NULL) { + syslog(LOG_ERR, _("unable to allocate memory")); // -V618 + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(127); + } + argv[0] = sudo_basename(mpath); + + i = 1; + for (p = strtok_r(mflags, " \t", &last); p != NULL; + p = strtok_r(NULL, " \t", &last)) { + if (i < MAX_MAILFLAGS) + argv[i++] = p; + } + argv[i] = NULL; + + /* + * Depending on the config, either run the mailer as root + * (so user cannot kill it) or as the user (for the paranoid). + */ + if (setuid(ROOT_UID) != 0) { + sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to change uid to %u", + ROOT_UID); + } + if (evl_conf->mailuid != ROOT_UID) { + if (setuid(evl_conf->mailuid) != 0) { + sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to change uid to %u", + (unsigned int)evl_conf->mailuid); + } + } + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + if (evl_conf->mailuid == ROOT_UID) + execve(mpath, argv, (char **)root_envp); + else + execv(mpath, argv); + syslog(LOG_ERR, _("unable to execute %s: %m"), mpath); // -V618 + sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to execute %s: %s", + mpath, strerror(errno)); + _exit(127); +} + +/* Send a message to the mailto user */ +static bool +send_mail(const struct eventlog *evlog, const char *message) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const char *cp, *timefmt = evl_conf->time_fmt; + struct sigaction sa; + char timebuf[1024]; + sigset_t chldmask; + struct tm tm; + time_t now; + FILE *mail; + int fd, pfd[2], status; + size_t len; + pid_t pid, rv; + struct stat sb; +#if defined(HAVE_NL_LANGINFO) && defined(CODESET) + char *locale; +#endif + debug_decl(send_mail, SUDO_DEBUG_UTIL); + + /* If mailer is disabled just return. */ + if (evl_conf->mailerpath == NULL || evl_conf->mailto == NULL) + debug_return_bool(true); + + /* Make sure the mailer exists and is a regular file. */ + if (stat(evl_conf->mailerpath, &sb) != 0 || !S_ISREG(sb.st_mode)) + debug_return_bool(false); + + time(&now); + if (localtime_r(&now, &tm) == NULL) + debug_return_bool(false); + + /* Block SIGCHLD for the duration since we call waitpid() below. */ + sigemptyset(&chldmask); + sigaddset(&chldmask, SIGCHLD); + (void)sigprocmask(SIG_BLOCK, &chldmask, NULL); + + /* Fork and return, child will daemonize. */ + switch (pid = sudo_debug_fork()) { + case -1: + /* Error. */ + sudo_warn("%s", U_("unable to fork")); + + /* Unblock SIGCHLD and return. */ + (void)sigprocmask(SIG_UNBLOCK, &chldmask, NULL); + debug_return_bool(false); + case 0: + /* Child. */ + switch (fork()) { + case -1: + /* Error. */ + syslog(LOG_ERR, _("unable to fork: %m")); // -V618 + sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s", + strerror(errno)); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(EXIT_FAILURE); + /* NOTREACHED */ + case 0: + /* Grandchild continues below. */ + sudo_debug_enter(__func__, __FILE__, __LINE__, sudo_debug_subsys); + break; + default: + /* Parent will wait for us. */ + _exit(EXIT_SUCCESS); + /* NOTREACHED */ + } + break; + default: + /* Parent. */ + for (;;) { + rv = waitpid(pid, &status, 0); + if (rv == -1 && errno != EINTR) + break; + if (rv != -1 && !WIFSTOPPED(status)) + break; + } + sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO, + "child (%d) exit value %d", (int)rv, status); + + /* Unblock SIGCHLD and return. */ + (void)sigprocmask(SIG_UNBLOCK, &chldmask, NULL); + debug_return_bool(true); + } + + /* Reset SIGCHLD to default and unblock it. */ + memset(&sa, 0, sizeof(sa)); + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + sa.sa_handler = SIG_DFL; + (void)sigaction(SIGCHLD, &sa, NULL); + (void)sigprocmask(SIG_UNBLOCK, &chldmask, NULL); + + /* Daemonize - disassociate from session/tty. */ + if (setsid() == -1) + sudo_warn("setsid"); + if (chdir("/") == -1) + sudo_warn("chdir(/)"); + fd = open(_PATH_DEVNULL, O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); + if (fd != -1) { + (void) dup2(fd, STDIN_FILENO); + (void) dup2(fd, STDOUT_FILENO); + (void) dup2(fd, STDERR_FILENO); + } + + /* Close non-debug fds so we don't leak anything. */ + closefrom_nodebug(STDERR_FILENO + 1); + + if (pipe2(pfd, O_CLOEXEC) == -1) { + syslog(LOG_ERR, _("unable to open pipe: %m")); // -V618 + sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to open pipe: %s", + strerror(errno)); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(EXIT_FAILURE); + } + + switch (pid = sudo_debug_fork()) { + case -1: + /* Error. */ + syslog(LOG_ERR, _("unable to fork: %m")); // -V618 + sudo_debug_printf( + SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to fork"); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(EXIT_FAILURE); + /* NOTREACHED */ + case 0: + /* Child. */ + exec_mailer(pfd[0]); + /* NOTREACHED */ + } + + (void) close(pfd[0]); + if ((mail = fdopen(pfd[1], "w")) == NULL) { + syslog(LOG_ERR, "fdopen: %m"); + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to fdopen pipe"); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(EXIT_FAILURE); + } + + /* Pipes are all setup, send message. */ + (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ", + evl_conf->mailto, + evl_conf->mailfrom ? evl_conf->mailfrom : + (evlog ? evlog->submituser : "root"), + "auto-generated"); + for (cp = _(evl_conf->mailsub); *cp; cp++) { + /* Expand escapes in the subject */ + if (*cp == '%' && *(cp+1) != '%') { + switch (*(++cp)) { + case 'h': + if (evlog != NULL) + (void) fputs(evlog->submithost, mail); + break; + case 'u': + if (evlog != NULL) + (void) fputs(evlog->submituser, mail); + break; + default: + cp--; + break; + } + } else + (void) fputc(*cp, mail); + } + +#if defined(HAVE_NL_LANGINFO) && defined(CODESET) + locale = setlocale(LC_ALL, NULL); + if (locale[0] != 'C' || locale[1] != '\0') + (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET)); +#endif /* HAVE_NL_LANGINFO && CODESET */ + + timebuf[sizeof(timebuf) - 1] = '\0'; + len = strftime(timebuf, sizeof(timebuf), timefmt, &tm); + if (len == 0 || timebuf[sizeof(timebuf) - 1] != '\0') { + sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_ERROR, + "strftime() failed to format time: %s", timefmt); + /* Fall back to default time format string. */ + timebuf[sizeof(timebuf) - 1] = '\0'; + len = strftime(timebuf, sizeof(timebuf), "%h %e %T", &tm); + if (len == 0 || timebuf[sizeof(timebuf) - 1] != '\0') { + timebuf[0] = '\0'; /* give up */ + } + } + if (evlog != NULL) { + (void) fprintf(mail, "\n\n%s : %s : %s : ", evlog->submithost, timebuf, + evlog->submituser); + } else { + (void) fprintf(mail, "\n\n%s : ", timebuf); + } + fputs(message, mail); + fputs("\n\n", mail); + + fclose(mail); + for (;;) { + rv = waitpid(pid, &status, 0); + if (rv == -1 && errno != EINTR) + break; + if (rv != -1 && !WIFSTOPPED(status)) + break; + } + sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO, + "child (%d) exit value %d", (int)rv, status); + sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys); + _exit(EXIT_SUCCESS); +} + +static bool +json_add_timestamp(struct json_container *jsonc, const char *name, + const struct timespec *ts, bool format_timestamp) +{ + struct json_value json_value; + size_t len; + debug_decl(json_add_timestamp, SUDO_DEBUG_PLUGIN); + + if (!sudo_json_open_object(jsonc, name)) + goto oom; + + json_value.type = JSON_NUMBER; + json_value.u.number = ts->tv_sec; + if (!sudo_json_add_value(jsonc, "seconds", &json_value)) + goto oom; + + json_value.type = JSON_NUMBER; + json_value.u.number = ts->tv_nsec; + if (!sudo_json_add_value(jsonc, "nanoseconds", &json_value)) + goto oom; + + if (format_timestamp) { + const struct eventlog_config *evl_conf = eventlog_getconf(); + const char *timefmt = evl_conf->time_fmt; + time_t secs = ts->tv_sec; + char timebuf[1024]; + struct tm tm; + + if (gmtime_r(&secs, &tm) != NULL) { + timebuf[sizeof(timebuf) - 1] = '\0'; + len = strftime(timebuf, sizeof(timebuf), "%Y%m%d%H%M%SZ", &tm); + if (len != 0 && timebuf[sizeof(timebuf) - 1] == '\0') { + json_value.type = JSON_STRING; + json_value.u.string = timebuf; // -V507 + if (!sudo_json_add_value(jsonc, "iso8601", &json_value)) + goto oom; + } + } + + if (localtime_r(&secs, &tm) != NULL) { + timebuf[sizeof(timebuf) - 1] = '\0'; + len = strftime(timebuf, sizeof(timebuf), timefmt, &tm); + if (len != 0 && timebuf[sizeof(timebuf) - 1] == '\0') { + json_value.type = JSON_STRING; + json_value.u.string = timebuf; // -V507 + if (!sudo_json_add_value(jsonc, "localtime", &json_value)) + goto oom; + } + } + } + + if (!sudo_json_close_object(jsonc)) + goto oom; + + debug_return_bool(true); +oom: + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO|SUDO_DEBUG_LINENO, + "%s: %s", __func__, "unable to allocate memory"); + debug_return_bool(false); +} + +/* + * Store the contents of struct eventlog as JSON. + * The submit_time and iolog_path members are not stored, they should + * be stored and formatted by the caller. + */ +bool +eventlog_store_json(struct json_container *jsonc, const struct eventlog *evlog) +{ + struct json_value json_value; + size_t i; + char *cp; + debug_decl(eventlog_store_json, SUDO_DEBUG_UTIL); + + /* Required settings. */ + if (evlog == NULL || evlog->submituser == NULL) + debug_return_bool(false); + + /* + * The most important values are written first in case + * the log record gets truncated. + * Note: submit_time and iolog_path are not stored here. + */ + + json_value.type = JSON_STRING; + json_value.u.string = evlog->submituser; + if (!sudo_json_add_value(jsonc, "submituser", &json_value)) + goto oom; + + if (evlog->command != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->command; + if (!sudo_json_add_value(jsonc, "command", &json_value)) + goto oom; + } + + if (evlog->runuser != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->runuser; + if (!sudo_json_add_value(jsonc, "runuser", &json_value)) + goto oom; + } + + if (evlog->rungroup != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->rungroup; + if (!sudo_json_add_value(jsonc, "rungroup", &json_value)) + goto oom; + } + + if (evlog->runchroot != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->runchroot; + if (!sudo_json_add_value(jsonc, "runchroot", &json_value)) + goto oom; + } + + if (evlog->runcwd != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->runcwd; + if (!sudo_json_add_value(jsonc, "runcwd", &json_value)) + goto oom; + } + + if (evlog->source != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->source; + if (!sudo_json_add_value(jsonc, "source", &json_value)) + goto oom; + } + + if (evlog->ttyname != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->ttyname; + if (!sudo_json_add_value(jsonc, "ttyname", &json_value)) + goto oom; + } + + if (evlog->submithost != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->submithost; + if (!sudo_json_add_value(jsonc, "submithost", &json_value)) + goto oom; + } + + if (evlog->cwd != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->cwd; + if (!sudo_json_add_value(jsonc, "submitcwd", &json_value)) + goto oom; + } + + if (evlog->rungroup!= NULL && evlog->rungid != (gid_t)-1) { + json_value.type = JSON_ID; + json_value.u.id = evlog->rungid; + if (!sudo_json_add_value(jsonc, "rungid", &json_value)) + goto oom; + } + + if (evlog->runuid != (uid_t)-1) { + json_value.type = JSON_ID; + json_value.u.id = evlog->runuid; + if (!sudo_json_add_value(jsonc, "runuid", &json_value)) + goto oom; + } + + json_value.type = JSON_NUMBER; + json_value.u.number = evlog->columns; + if (!sudo_json_add_value(jsonc, "columns", &json_value)) + goto oom; + + json_value.type = JSON_NUMBER; + json_value.u.number = evlog->lines; + if (!sudo_json_add_value(jsonc, "lines", &json_value)) + goto oom; + + if (evlog->runargv != NULL) { + if (!sudo_json_open_array(jsonc, "runargv")) + goto oom; + for (i = 0; (cp = evlog->runargv[i]) != NULL; i++) { + json_value.type = JSON_STRING; + json_value.u.string = cp; + if (!sudo_json_add_value(jsonc, NULL, &json_value)) + goto oom; + } + if (!sudo_json_close_array(jsonc)) + goto oom; + } + + if (evlog->runenv != NULL) { + if (!sudo_json_open_array(jsonc, "runenv")) + goto oom; + for (i = 0; (cp = evlog->runenv[i]) != NULL; i++) { + json_value.type = JSON_STRING; + json_value.u.string = cp; + if (!sudo_json_add_value(jsonc, NULL, &json_value)) + goto oom; + } + if (!sudo_json_close_array(jsonc)) + goto oom; + } + + if (evlog->submitenv != NULL) { + if (!sudo_json_open_array(jsonc, "submitenv")) + goto oom; + for (i = 0; (cp = evlog->submitenv[i]) != NULL; i++) { + json_value.type = JSON_STRING; + json_value.u.string = cp; + if (!sudo_json_add_value(jsonc, NULL, &json_value)) + goto oom; + } + if (!sudo_json_close_array(jsonc)) + goto oom; + } + + debug_return_bool(true); + +oom: + sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); + debug_return_bool(false); +} + +static bool +default_json_cb(struct json_container *jsonc, void *v) +{ + return eventlog_store_json(jsonc, v); +} + +static char * +format_json(int event_type, struct eventlog_args *args, + const struct eventlog *evlog, bool compact) +{ + eventlog_json_callback_t info_cb = args->json_info_cb; + void *info = args->json_info; + struct json_container jsonc = { 0 }; + struct json_value json_value; + const char *time_str, *type_str; + struct timespec now; + debug_decl(format_json, SUDO_DEBUG_UTIL); + + if (info_cb == NULL) { + info_cb = default_json_cb; + info = (void *)evlog; + } + + if (sudo_gettime_real(&now) == -1) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to read the clock"); + debug_return_str(NULL); + } + + switch (event_type) { + case EVLOG_ACCEPT: + type_str = "accept"; + time_str = "submit_time"; + break; + case EVLOG_REJECT: + type_str = "reject"; + time_str = "submit_time"; + break; + case EVLOG_ALERT: + type_str = "alert"; + time_str = "alert_time"; + break; + case EVLOG_EXIT: + type_str = "exit"; + time_str = "exit_time"; + break; + default: + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unexpected event type %d", event_type); + debug_return_str(NULL); + } + + if (!sudo_json_init(&jsonc, 4, compact, false, false)) + goto bad; + if (!sudo_json_open_object(&jsonc, type_str)) + goto bad; + + if (evlog != NULL && evlog->uuid_str[0] != '\0') { + json_value.type = JSON_STRING; + json_value.u.string = evlog->uuid_str; + if (!sudo_json_add_value(&jsonc, "uuid", &json_value)) + goto bad; + } + + /* Reject and Alert events include a reason and optional error string. */ + if (args->reason != NULL) { + char *ereason = NULL; + + if (args->errstr != NULL) { + const int len = asprintf(&ereason, _("%s: %s"), args->reason, + args->errstr); + if (len == -1) { + sudo_warnx(U_("%s: %s"), __func__, + U_("unable to allocate memory")); + goto bad; + } + } + json_value.type = JSON_STRING; + json_value.u.string = ereason ? ereason : args->reason; + if (!sudo_json_add_value(&jsonc, "reason", &json_value)) { + free(ereason); + goto bad; + } + free(ereason); + } + + /* Log event time on server (set earlier) */ + if (!json_add_timestamp(&jsonc, "server_time", &now, true)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable format timestamp"); + goto bad; + } + + /* Log event time from client */ + if (args->event_time != NULL) { + if (!json_add_timestamp(&jsonc, time_str, args->event_time, true)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable format timestamp"); + goto bad; + } + } + + if (event_type == EVLOG_EXIT && evlog != NULL) { + /* Exit events don't need evlog details if there is a UUID. */ + if (evlog->uuid_str[0] != '\0') { + if (args->json_info == NULL) + info = NULL; + } + + if (sudo_timespecisset(&evlog->run_time)) { + if (!json_add_timestamp(&jsonc, "run_time", &evlog->run_time, false)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable format timestamp"); + goto bad; + } + } + if (evlog->signal_name != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->signal_name; + if (!sudo_json_add_value(&jsonc, "signal", &json_value)) + goto bad; + + json_value.type = JSON_BOOL; + json_value.u.boolean = evlog->dumped_core; + if (!sudo_json_add_value(&jsonc, "dumped_core", &json_value)) + goto bad; + } + json_value.type = JSON_NUMBER; + json_value.u.number = evlog->exit_value; + if (!sudo_json_add_value(&jsonc, "exit_value", &json_value)) + goto bad; + } + + /* Event log info may be missing for alert messages. */ + if (evlog != NULL) { + if (evlog->peeraddr != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->peeraddr; + if (!sudo_json_add_value(&jsonc, "peeraddr", &json_value)) + goto bad; + } + + if (evlog->iolog_path != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->iolog_path; + if (!sudo_json_add_value(&jsonc, "iolog_path", &json_value)) + goto bad; + + if (sudo_timespecisset(&evlog->iolog_offset)) { + if (!json_add_timestamp(&jsonc, "iolog_offset", &evlog->iolog_offset, false)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable format timestamp"); + goto bad; + } + } + } + + if (event_type == EVLOG_EXIT) { + /* Exit events don't need evlog details if there is a UUID. */ + if (evlog->uuid_str[0] != '\0') { + if (args->json_info == NULL) + info = NULL; + } + + if (sudo_timespecisset(&evlog->run_time)) { + if (!json_add_timestamp(&jsonc, "run_time", &evlog->run_time, + false)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable format timestamp"); + goto bad; + } + } + if (evlog->signal_name != NULL) { + json_value.type = JSON_STRING; + json_value.u.string = evlog->signal_name; + if (!sudo_json_add_value(&jsonc, "signal", &json_value)) + goto bad; + + json_value.type = JSON_BOOL; + json_value.u.boolean = evlog->dumped_core; + if (!sudo_json_add_value(&jsonc, "dumped_core", &json_value)) + goto bad; + } + json_value.type = JSON_NUMBER; + json_value.u.number = evlog->exit_value; + if (!sudo_json_add_value(&jsonc, "exit_value", &json_value)) + goto bad; + } + } + + /* Write log info. */ + if (info != NULL) { + if (!info_cb(&jsonc, info)) + goto bad; + } + + if (!sudo_json_close_object(&jsonc)) + goto bad; + + /* Caller is responsible for freeing the buffer. */ + debug_return_str(sudo_json_get_buf(&jsonc)); + +bad: + sudo_json_free(&jsonc); + debug_return_str(NULL); +} + +/* + * Log a message to syslog, prepending the username and splitting the + * message into parts if it is longer than syslog_maxlen. + */ +static bool +do_syslog_sudo(int pri, char *logline, const struct eventlog *evlog) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + size_t len, maxlen; + char *p, *tmp, save; + const char *fmt; + debug_decl(do_syslog_sudo, SUDO_DEBUG_UTIL); + + evl_conf->open_log(EVLOG_SYSLOG, NULL); + + if (evlog == NULL) { + /* Not a command, just log it as-is. */ + syslog(pri, "%s", logline); + goto done; + } + + /* + * Log the full line, breaking into multiple syslog(3) calls if necessary + */ + fmt = _("%8s : %s"); + maxlen = evl_conf->syslog_maxlen - + (strlen(fmt) - 5 + strlen(evlog->submituser)); + for (p = logline; *p != '\0'; ) { + len = strlen(p); + if (len > maxlen) { + /* + * Break up the line into what will fit on one syslog(3) line + * Try to avoid breaking words into several lines if possible. + */ + tmp = memrchr(p, ' ', maxlen); + if (tmp == NULL) + tmp = p + maxlen; + + /* NULL terminate line, but save the char to restore later */ + save = *tmp; + *tmp = '\0'; + + syslog(pri, fmt, evlog->submituser, p); + + *tmp = save; /* restore saved character */ + + /* Advance p and eliminate leading whitespace */ + for (p = tmp; *p == ' '; p++) + continue; + } else { + syslog(pri, fmt, evlog->submituser, p); + p += len; + } + fmt = _("%8s : (command continued) %s"); + maxlen = evl_conf->syslog_maxlen - + (strlen(fmt) - 5 + strlen(evlog->submituser)); + } +done: + evl_conf->close_log(EVLOG_SYSLOG, NULL); + + debug_return_bool(true); +} + +static bool +do_syslog_json(int pri, int event_type, struct eventlog_args *args, + const struct eventlog *evlog) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + char *json_str; + debug_decl(do_syslog_json, SUDO_DEBUG_UTIL); + + /* Format as a compact JSON message (no newlines) */ + json_str = format_json(event_type, args, evlog, true); + if (json_str == NULL) + debug_return_bool(false); + + /* Syslog it in a sudo object with a @cee: prefix. */ + /* TODO: use evl_conf->syslog_maxlen to break up long messages. */ + evl_conf->open_log(EVLOG_SYSLOG, NULL); + syslog(pri, "@cee:{\"sudo\":{%s}}", json_str); + evl_conf->close_log(EVLOG_SYSLOG, NULL); + free(json_str); + debug_return_bool(true); +} + +/* + * Log a message to syslog in either sudo or JSON format. + */ +static bool +do_syslog(int event_type, int flags, struct eventlog_args *args, + const struct eventlog *evlog) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + struct sudo_lbuf lbuf; + bool ret = false; + int pri; + debug_decl(do_syslog, SUDO_DEBUG_UTIL); + + sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0); + + /* Sudo format logs and mailed logs use the same log line format. */ + if (evl_conf->format == EVLOG_SUDO || ISSET(flags, EVLOG_MAIL)) { + if (!new_logline(event_type, flags, args, evlog, &lbuf)) + goto done; + + if (ISSET(flags, EVLOG_MAIL)) { + if (!send_mail(evlog, lbuf.buf)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable to mail log line"); + } + if (ISSET(flags, EVLOG_MAIL_ONLY)) { + ret = true; + goto done; + } + } + } + + switch (event_type) { + case EVLOG_ACCEPT: + case EVLOG_EXIT: + pri = evl_conf->syslog_acceptpri; + break; + case EVLOG_REJECT: + pri = evl_conf->syslog_rejectpri; + break; + case EVLOG_ALERT: + pri = evl_conf->syslog_alertpri; + break; + default: + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unexpected event type %d", event_type); + pri = -1; + break; + } + if (pri == -1) { + /* syslog disabled for this message type */ + ret = true; + goto done; + } + + switch (evl_conf->format) { + case EVLOG_SUDO: + ret = do_syslog_sudo(pri, lbuf.buf, evlog); + break; + case EVLOG_JSON: + ret = do_syslog_json(pri, event_type, args, evlog); + break; + default: + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unexpected eventlog format %d", evl_conf->format); + break; + } +done: + sudo_lbuf_destroy(&lbuf); + debug_return_bool(ret); +} + +static bool +do_logfile_sudo(const char *logline, const struct eventlog *evlog, + const struct timespec *event_time) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + char *full_line, timebuf[8192], *timestr = NULL; + const char *timefmt = evl_conf->time_fmt; + const char *logfile = evl_conf->logpath; + struct tm tm; + bool ret = false; + FILE *fp; + int len; + debug_decl(do_logfile_sudo, SUDO_DEBUG_UTIL); + + if ((fp = evl_conf->open_log(EVLOG_FILE, logfile)) == NULL) + debug_return_bool(false); + + if (!sudo_lock_file(fileno(fp), SUDO_LOCK)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to lock log file %s", logfile); + goto done; + } + + if (event_time != NULL) { + time_t tv_sec = event_time->tv_sec; + if (localtime_r(&tv_sec, &tm) != NULL) { + /* strftime() does not guarantee to NUL-terminate so we must check. */ + timebuf[sizeof(timebuf) - 1] = '\0'; + if (strftime(timebuf, sizeof(timebuf), timefmt, &tm) != 0 && + timebuf[sizeof(timebuf) - 1] == '\0') { + timestr = timebuf; + } + } + } + if (evlog != NULL) { + len = asprintf(&full_line, "%s : %s : %s", + timestr ? timestr : "invalid date", evlog->submituser, logline); + } else { + len = asprintf(&full_line, "%s : %s", + timestr ? timestr : "invalid date", logline); + } + if (len == -1) { + sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); + goto done; + } + eventlog_writeln(fp, full_line, (size_t)len, evl_conf->file_maxlen); + free(full_line); + (void)fflush(fp); + if (ferror(fp)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to write log file %s", logfile); + goto done; + } + ret = true; + +done: + (void)sudo_lock_file(fileno(fp), SUDO_UNLOCK); + evl_conf->close_log(EVLOG_FILE, fp); + debug_return_bool(ret); +} + +static bool +do_logfile_json(int event_type, struct eventlog_args *args, + const struct eventlog *evlog) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const char *logfile = evl_conf->logpath; + struct stat sb; + char *json_str; + int ret = false; + FILE *fp; + debug_decl(do_logfile_json, SUDO_DEBUG_UTIL); + + if ((fp = evl_conf->open_log(EVLOG_FILE, logfile)) == NULL) + debug_return_bool(false); + + json_str = format_json(event_type, args, evlog, false); + if (json_str == NULL) + goto done; + + if (!sudo_lock_file(fileno(fp), SUDO_LOCK)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to lock log file %s", logfile); + goto done; + } + + /* Note: assumes file ends in "\n}\n" */ + if (fstat(fileno(fp), &sb) == -1) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO|SUDO_DEBUG_LINENO, + "unable to stat %s", logfile); + goto done; + } + if (sb.st_size == 0) { + /* New file */ + putc('{', fp); + } else if (fseeko(fp, -3, SEEK_END) == 0) { + /* Continue file, overwrite the final "\n}\n" */ + putc(',', fp); + } else { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_ERRNO|SUDO_DEBUG_LINENO, + "unable to seek %s", logfile); + goto done; + } + fputs(json_str, fp); + fputs("\n}\n", fp); /* close JSON */ + fflush(fp); + /* XXX - check for file error and recover */ + + ret = true; + +done: + free(json_str); + (void)sudo_lock_file(fileno(fp), SUDO_UNLOCK); + evl_conf->close_log(EVLOG_FILE, fp); + debug_return_bool(ret); +} + +static bool +do_logfile(int event_type, int flags, struct eventlog_args *args, + const struct eventlog *evlog) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + struct sudo_lbuf lbuf; + bool ret = false; + debug_decl(do_logfile, SUDO_DEBUG_UTIL); + + sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0); + + /* Sudo format logs and mailed logs use the same log line format. */ + if (evl_conf->format == EVLOG_SUDO || ISSET(flags, EVLOG_MAIL)) { + if (!new_logline(event_type, flags, args, evlog, &lbuf)) + goto done; + + if (ISSET(flags, EVLOG_MAIL)) { + if (!send_mail(evlog, lbuf.buf)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable to mail log line"); + } + if (ISSET(flags, EVLOG_MAIL_ONLY)) { + ret = true; + goto done; + } + } + } + + switch (evl_conf->format) { + case EVLOG_SUDO: + ret = do_logfile_sudo(lbuf.buf ? lbuf.buf : args->reason, evlog, + args->event_time); + break; + case EVLOG_JSON: + ret = do_logfile_json(event_type, args, evlog); + break; + default: + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unexpected eventlog format %d", evl_conf->format); + break; + } + +done: + sudo_lbuf_destroy(&lbuf); + debug_return_bool(ret); +} + +bool +eventlog_accept(const struct eventlog *evlog, int flags, + eventlog_json_callback_t info_cb, void *info) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const int log_type = evl_conf->type; + struct eventlog_args args = { NULL }; + bool ret = true; + debug_decl(eventlog_accept, SUDO_DEBUG_UTIL); + + args.event_time = &evlog->submit_time; + args.json_info_cb = info_cb; + args.json_info = info; + + if (ISSET(log_type, EVLOG_SYSLOG)) { + if (!do_syslog(EVLOG_ACCEPT, flags, &args, evlog)) + ret = false; + CLR(flags, EVLOG_MAIL); + } + if (ISSET(log_type, EVLOG_FILE)) { + if (!do_logfile(EVLOG_ACCEPT, flags, &args, evlog)) + ret = false; + } + + debug_return_bool(ret); +} + +bool +eventlog_reject(const struct eventlog *evlog, int flags, const char *reason, + eventlog_json_callback_t info_cb, void *info) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const int log_type = evl_conf->type; + struct eventlog_args args = { NULL }; + bool ret = true; + debug_decl(eventlog_reject, SUDO_DEBUG_UTIL); + + args.reason = reason; + args.event_time = &evlog->submit_time; + args.json_info_cb = info_cb; + args.json_info = info; + + if (ISSET(log_type, EVLOG_SYSLOG)) { + if (!do_syslog(EVLOG_REJECT, flags, &args, evlog)) + ret = false; + CLR(flags, EVLOG_MAIL); + } + if (ISSET(log_type, EVLOG_FILE)) { + if (!do_logfile(EVLOG_REJECT, flags, &args, evlog)) + ret = false; + } + + debug_return_bool(ret); +} + +bool +eventlog_alert(const struct eventlog *evlog, int flags, + struct timespec *alert_time, const char *reason, const char *errstr) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const int log_type = evl_conf->type; + struct eventlog_args args = { NULL }; + bool ret = true; + debug_decl(eventlog_alert, SUDO_DEBUG_UTIL); + + args.reason = reason; + args.errstr = errstr; + args.event_time = alert_time; + + if (ISSET(log_type, EVLOG_SYSLOG)) { + if (!do_syslog(EVLOG_ALERT, flags, &args, evlog)) + ret = false; + CLR(flags, EVLOG_MAIL); + } + if (ISSET(log_type, EVLOG_FILE)) { + if (!do_logfile(EVLOG_ALERT, flags, &args, evlog)) + ret = false; + } + + debug_return_bool(ret); +} + +bool +eventlog_mail(const struct eventlog *evlog, int flags, + struct timespec *event_time, const char *reason, const char *errstr, + char * const extra[]) +{ + struct eventlog_args args = { NULL }; + struct sudo_lbuf lbuf; + bool ret = false; + debug_decl(eventlog_mail, SUDO_DEBUG_UTIL); + + args.reason = reason; + args.errstr = errstr; + args.event_time = event_time; + + sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0); + if (!new_logline(EVLOG_ALERT, flags, &args, evlog, &lbuf)) + goto done; + + if (extra != NULL) { + /* Each extra message is written on its own line. */ + while (*extra != NULL) { + sudo_lbuf_append(&lbuf, "\n"); + sudo_lbuf_append_esc(&lbuf, LBUF_ESC_CNTRL, "%s", *extra); + if (sudo_lbuf_error(&lbuf)) { + sudo_debug_printf( + SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO|SUDO_DEBUG_ERRNO, + "unable to format mail message"); + goto done; + } + extra++; + } + } + + ret = send_mail(evlog, lbuf.buf); + if (!ret) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable to mail log line"); + } + +done: + sudo_lbuf_destroy(&lbuf); + debug_return_bool(ret); +} + +bool +eventlog_exit(const struct eventlog *evlog, int flags) +{ + const struct eventlog_config *evl_conf = eventlog_getconf(); + const int log_type = evl_conf->type; + struct eventlog_args args = { NULL }; + struct timespec exit_time; + bool ret = true; + debug_decl(eventlog_exit, SUDO_DEBUG_UTIL); + + if (sudo_timespecisset(&evlog->run_time)) { + sudo_timespecadd(&evlog->submit_time, &evlog->run_time, &exit_time); + args.event_time = &exit_time; + } + + if (ISSET(log_type, EVLOG_SYSLOG)) { + if (!do_syslog(EVLOG_EXIT, flags, &args, evlog)) + ret = false; + CLR(flags, EVLOG_MAIL); + } + if (ISSET(log_type, EVLOG_FILE)) { + if (!do_logfile(EVLOG_EXIT, flags, &args, evlog)) + ret = false; + } + + debug_return_bool(ret); +} diff --git a/lib/eventlog/eventlog_conf.c b/lib/eventlog/eventlog_conf.c new file mode 100644 index 0000000..0663a38 --- /dev/null +++ b/lib/eventlog/eventlog_conf.c @@ -0,0 +1,226 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 1994-1996, 1998-2020 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ + +/* + * This is an open source non-commercial project. Dear PVS-Studio, please check it. + * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + */ + +#include <config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <netinet/in.h> + +#include <ctype.h> +#include <errno.h> +#include <fcntl.h> +#include <grp.h> +#include <locale.h> +#include <pwd.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <syslog.h> +#include <time.h> +#include <unistd.h> + +#include <pathnames.h> +#include <sudo_compat.h> +#include <sudo_debug.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_gettext.h> +#include <sudo_json.h> +#include <sudo_queue.h> +#include <sudo_util.h> + +static FILE *eventlog_stub_open_log(int type, const char *logfile); +static void eventlog_stub_close_log(int type, FILE *fp); + +/* Eventlog config settings (default values). */ +static struct eventlog_config evl_conf = { + EVLOG_NONE, /* type */ + EVLOG_SUDO, /* format */ + LOG_NOTICE, /* syslog_acceptpri */ + LOG_ALERT, /* syslog_rejectpri */ + LOG_ALERT, /* syslog_alertpri */ + MAXSYSLOGLEN, /* syslog_maxlen */ + 0, /* file_maxlen */ + ROOT_UID, /* mailuid */ + false, /* omit_hostname */ + _PATH_SUDO_LOGFILE, /* logpath */ + "%h %e %T", /* time_fmt */ +#ifdef _PATH_SUDO_SENDMAIL + _PATH_SUDO_SENDMAIL, /* mailerpath */ +#else + NULL, /* mailerpath (disabled) */ +#endif + "-t", /* mailerflags */ + NULL, /* mailfrom */ + MAILTO, /* mailto */ + N_(MAILSUBJECT), /* mailsub */ + eventlog_stub_open_log, /* open_log */ + eventlog_stub_close_log /* close_log */ +}; + +static FILE * +eventlog_stub_open_log(int type, const char *logfile) +{ + debug_decl(eventlog_stub_open_log, SUDO_DEBUG_UTIL); + sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO, + "open_log not set, using stub"); + debug_return_ptr(NULL); +} + +static void +eventlog_stub_close_log(int type, FILE *fp) +{ + debug_decl(eventlog_stub_close_log, SUDO_DEBUG_UTIL); + sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO, + "close_log not set, using stub"); + debug_return; +} + +/* + * eventlog config setters. + */ + +void +eventlog_set_type(int type) +{ + evl_conf.type = type; +} + +void +eventlog_set_format(enum eventlog_format format) +{ + evl_conf.format = format; +} + +void +eventlog_set_syslog_acceptpri(int pri) +{ + evl_conf.syslog_acceptpri = pri; +} + +void +eventlog_set_syslog_rejectpri(int pri) +{ + evl_conf.syslog_rejectpri = pri; +} + +void +eventlog_set_syslog_alertpri(int pri) +{ + evl_conf.syslog_alertpri = pri; +} + +void +eventlog_set_syslog_maxlen(size_t len) +{ + evl_conf.syslog_maxlen = len; +} + +void +eventlog_set_file_maxlen(size_t len) +{ + evl_conf.file_maxlen = len; +} + +void +eventlog_set_mailuid(uid_t uid) +{ + evl_conf.mailuid = uid; +} + +void +eventlog_set_omit_hostname(bool omit_hostname) +{ + evl_conf.omit_hostname = omit_hostname; +} + +void +eventlog_set_logpath(const char *path) +{ + evl_conf.logpath = path; +} + +void +eventlog_set_time_fmt(const char *fmt) +{ + evl_conf.time_fmt = fmt; +} + +void +eventlog_set_mailerpath(const char *path) +{ + evl_conf.mailerpath = path; +} + +void +eventlog_set_mailerflags(const char *mflags) +{ + evl_conf.mailerflags = mflags; +} + +void +eventlog_set_mailfrom(const char *from_addr) +{ + evl_conf.mailfrom = from_addr; +} + +void +eventlog_set_mailto(const char *to_addr) +{ + evl_conf.mailto = to_addr; +} + +void +eventlog_set_mailsub(const char *subject) +{ + evl_conf.mailsub = subject; +} + +void +eventlog_set_open_log(FILE *(*fn)(int type, const char *)) +{ + evl_conf.open_log = fn; +} + +void +eventlog_set_close_log(void (*fn)(int type, FILE *)) +{ + evl_conf.close_log = fn; +} + +/* + * get eventlog config. + */ +const struct eventlog_config * +eventlog_getconf(void) +{ + return &evl_conf; +} diff --git a/lib/eventlog/eventlog_free.c b/lib/eventlog/eventlog_free.c new file mode 100644 index 0000000..7643f52 --- /dev/null +++ b/lib/eventlog/eventlog_free.c @@ -0,0 +1,86 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ + +/* + * This is an open source non-commercial project. Dear PVS-Studio, please check it. + * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> + +#include <sudo_compat.h> +#include <sudo_debug.h> +#include <sudo_eventlog.h> +#include <sudo_util.h> + +/* + * Free the strings in a struct eventlog. + */ +void +eventlog_free(struct eventlog *evlog) +{ + size_t i; + debug_decl(eventlog_free, SUDO_DEBUG_UTIL); + + if (evlog != NULL) { + free(evlog->iolog_path); + free(evlog->command); + free(evlog->cwd); + free(evlog->runchroot); + free(evlog->runcwd); + free(evlog->rungroup); + free(evlog->runuser); + free(evlog->peeraddr); + free(evlog->signal_name); + free(evlog->source); + if (evlog->submitenv != NULL) { + for (i = 0; evlog->submitenv[i] != NULL; i++) + free(evlog->submitenv[i]); + free(evlog->submitenv); + } + free(evlog->submithost); + free(evlog->submituser); + free(evlog->submitgroup); + free(evlog->ttyname); + if (evlog->runargv != NULL) { + for (i = 0; evlog->runargv[i] != NULL; i++) + free(evlog->runargv[i]); + free(evlog->runargv); + } + if (evlog->runenv != NULL) { + for (i = 0; evlog->runenv[i] != NULL; i++) + free(evlog->runenv[i]); + free(evlog->runenv); + } + if (evlog->env_add != NULL) { + for (i = 0; evlog->env_add[i] != NULL; i++) + free(evlog->env_add[i]); + free(evlog->env_add); + } + free(evlog); + } + + debug_return; +} diff --git a/lib/eventlog/logwrap.c b/lib/eventlog/logwrap.c new file mode 100644 index 0000000..849ccb4 --- /dev/null +++ b/lib/eventlog/logwrap.c @@ -0,0 +1,90 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2011, 2014-2020 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * This is an open source non-commercial project. Dear PVS-Studio, please check it. + * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <sudo_compat.h> +#include <sudo_debug.h> +#include <sudo_util.h> +#include <sudo_eventlog.h> + +size_t +eventlog_writeln(FILE * restrict fp, char * restrict line, size_t linelen, size_t maxlen) +{ + const char *indent = ""; + char *beg = line; + char *end; + int len; + size_t outlen = 0; + debug_decl(eventlog_writeln, SUDO_DEBUG_UTIL); + + if (maxlen < sizeof(EVENTLOG_INDENT)) { + /* Maximum length too small, disable wrapping. */ + outlen = fwrite(line, 1, linelen, fp); + if (outlen != linelen) + debug_return_size_t((size_t)-1); + if (fputc('\n', fp) == EOF) + debug_return_size_t((size_t)-1); + debug_return_size_t(outlen + 1); + } + + /* + * Print out line with word wrap around maxlen characters. + */ + while (linelen > maxlen) { + end = beg + maxlen; + while (end != beg && *end != ' ') + end--; + if (beg == end) { + /* Unable to find word break within maxlen, look beyond. */ + end = strchr(beg + maxlen, ' '); + if (end == NULL) + break; /* no word break */ + } + len = fprintf(fp, "%s%.*s\n", indent, (int)(end - beg), beg); + if (len < 0) + debug_return_size_t((size_t)-1); + outlen += (size_t)len; + while (*end == ' ') + end++; + linelen -= (size_t)(end - beg); + beg = end; + if (indent[0] == '\0') { + indent = EVENTLOG_INDENT; + maxlen -= sizeof(EVENTLOG_INDENT) - 1; + } + } + /* Print remainder, if any. */ + if (linelen) { + len = fprintf(fp, "%s%s\n", indent, beg); + if (len < 0) + debug_return_size_t((size_t)-1); + outlen += (size_t)len; + } + + debug_return_size_t(outlen); +} diff --git a/lib/eventlog/parse_json.c b/lib/eventlog/parse_json.c new file mode 100644 index 0000000..9b5a168 --- /dev/null +++ b/lib/eventlog/parse_json.c @@ -0,0 +1,1071 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020-2023 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * This is an open source non-commercial project. Dear PVS-Studio, please check it. + * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#ifdef HAVE_STDBOOL_H +# include <stdbool.h> +#else +# include <compat/stdbool.h> +#endif /* HAVE_STDBOOL_H */ +#include <string.h> +#include <unistd.h> +#include <ctype.h> +#include <limits.h> +#include <fcntl.h> +#include <time.h> + +#include <sudo_compat.h> +#include <sudo_debug.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_gettext.h> +#include <sudo_util.h> + +#include <parse_json.h> + +struct json_stack { + unsigned int depth; + unsigned int maxdepth; + struct eventlog_json_object *frames[64]; +}; +#define JSON_STACK_INTIALIZER(s) { 0, nitems((s).frames) }; + +static char *iolog_file; + +static bool +json_store_columns(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_columns, SUDO_DEBUG_UTIL); + + if (item->u.number < 1 || item->u.number > INT_MAX) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "tty cols %lld: out of range", item->u.number); + evlog->columns = 0; + debug_return_bool(false); + } + + evlog->columns = (int)item->u.number; + debug_return_bool(true); +} + +static bool +json_store_command(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_command, SUDO_DEBUG_UTIL); + + /* + * Note: struct eventlog must store command + args. + * We don't have argv yet so we append the args later. + */ + free(evlog->command); + evlog->command = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_dumped_core(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_dumped_core, SUDO_DEBUG_UTIL); + + evlog->dumped_core = item->u.boolean; + debug_return_bool(true); +} + +static bool +json_store_exit_value(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_exit_value, SUDO_DEBUG_UTIL); + + if (item->u.number < 0 || item->u.number > INT_MAX) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "exit value %lld: out of range", item->u.number); + evlog->exit_value = -1; + debug_return_bool(false); + } + + evlog->exit_value = (int)item->u.number; + debug_return_bool(true); +} + +static bool +json_store_iolog_file(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_iolog_file, SUDO_DEBUG_UTIL); + + /* Do set evlog->iolog_file directly, it is a substring of iolog_path. */ + free(iolog_file); + iolog_file = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_iolog_path(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_iolog_path, SUDO_DEBUG_UTIL); + + free(evlog->iolog_path); + evlog->iolog_path = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_lines(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_lines, SUDO_DEBUG_UTIL); + + if (item->u.number < 1 || item->u.number > INT_MAX) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "tty lines %lld: out of range", item->u.number); + evlog->lines = 0; + debug_return_bool(false); + } + + evlog->lines = (int)item->u.number; + debug_return_bool(true); +} + +static bool +json_store_peeraddr(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_peeraddr, SUDO_DEBUG_UTIL); + + free(evlog->peeraddr); + evlog->peeraddr = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static char ** +json_array_to_strvec(struct eventlog_json_object *array) +{ + struct json_item *item; + size_t len = 0; + char **ret; + debug_decl(json_array_to_strvec, SUDO_DEBUG_UTIL); + + TAILQ_FOREACH(item, &array->items, entries) { + /* Can only convert arrays of string. */ + if (item->type != JSON_STRING) { + sudo_warnx(U_("expected JSON_STRING, got %d"), item->type); + debug_return_ptr(NULL); + } + /* Prevent integer overflow. */ + if (++len == INT_MAX) { + sudo_warnx("%s", U_("JSON_ARRAY too large")); + debug_return_ptr(NULL); + } + } + if ((ret = reallocarray(NULL, len + 1, sizeof(char *))) == NULL) { + sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); + debug_return_ptr(NULL); + } + len = 0; + TAILQ_FOREACH(item, &array->items, entries) { + ret[len++] = item->u.string; + item->u.string = NULL; + } + ret[len] = NULL; + + debug_return_ptr(ret); +} + +static bool +json_store_submitenv(struct json_item *item, struct eventlog *evlog) +{ + size_t i; + debug_decl(json_store_submitenv, SUDO_DEBUG_UTIL); + + if (evlog->submitenv != NULL) { + for (i = 0; evlog->submitenv[i] != NULL; i++) + free(evlog->submitenv[i]); + free(evlog->submitenv); + } + evlog->submitenv = json_array_to_strvec(&item->u.child); + + debug_return_bool(evlog->submitenv != NULL); +} + +static bool +json_store_runargv(struct json_item *item, struct eventlog *evlog) +{ + size_t i; + debug_decl(json_store_runargv, SUDO_DEBUG_UTIL); + + if (evlog->runargv != NULL) { + for (i = 0; evlog->runargv[i] != NULL; i++) + free(evlog->runargv[i]); + free(evlog->runargv); + } + evlog->runargv = json_array_to_strvec(&item->u.child); + + debug_return_bool(evlog->runargv != NULL); +} + +static bool +json_store_runenv(struct json_item *item, struct eventlog *evlog) +{ + size_t i; + debug_decl(json_store_runenv, SUDO_DEBUG_UTIL); + + if (evlog->runenv != NULL) { + for (i = 0; evlog->runenv[i] != NULL; i++) + free(evlog->runenv[i]); + free(evlog->runenv); + } + evlog->runenv = json_array_to_strvec(&item->u.child); + + debug_return_bool(evlog->runenv != NULL); +} + +static bool +json_store_runenv_override(struct json_item *item, struct eventlog *evlog) +{ + size_t i; + debug_decl(json_store_runenv_override, SUDO_DEBUG_UTIL); + + if (evlog->env_add != NULL) { + for (i = 0; evlog->env_add[i] != NULL; i++) + free(evlog->env_add[i]); + free(evlog->env_add); + } + evlog->env_add = json_array_to_strvec(&item->u.child); + + debug_return_bool(evlog->env_add != NULL); +} + +static bool +json_store_rungid(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_rungid, SUDO_DEBUG_UTIL); + + evlog->rungid = (gid_t)item->u.number; + debug_return_bool(true); +} + +static bool +json_store_rungroup(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_rungroup, SUDO_DEBUG_UTIL); + + free(evlog->rungroup); + evlog->rungroup = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_runuid(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_runuid, SUDO_DEBUG_UTIL); + + evlog->runuid = (uid_t)item->u.number; + debug_return_bool(true); +} + +static bool +json_store_runuser(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_runuser, SUDO_DEBUG_UTIL); + + free(evlog->runuser); + evlog->runuser = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_runchroot(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_runchroot, SUDO_DEBUG_UTIL); + + free(evlog->runchroot); + evlog->runchroot = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_runcwd(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_runcwd, SUDO_DEBUG_UTIL); + + free(evlog->runcwd); + evlog->runcwd = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_signal(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_signal, SUDO_DEBUG_UTIL); + + free(evlog->signal_name); + evlog->signal_name = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_source(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_source, SUDO_DEBUG_UTIL); + + free(evlog->source); + evlog->source = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_submitcwd(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_submitcwd, SUDO_DEBUG_UTIL); + + free(evlog->cwd); + evlog->cwd = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_submithost(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_submithost, SUDO_DEBUG_UTIL); + + free(evlog->submithost); + evlog->submithost = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_submituser(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_submituser, SUDO_DEBUG_UTIL); + + free(evlog->submituser); + evlog->submituser = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_submitgroup(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_submitgroup, SUDO_DEBUG_UTIL); + + free(evlog->submitgroup); + evlog->submitgroup = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_timespec(struct json_item *item, struct timespec *ts) +{ + struct eventlog_json_object *object; + debug_decl(json_store_timespec, SUDO_DEBUG_UTIL); + + object = &item->u.child; + TAILQ_FOREACH(item, &object->items, entries) { + if (item->type != JSON_NUMBER) + continue; + if (strcmp(item->name, "seconds") == 0) { + ts->tv_sec = (time_t)item->u.number; + continue; + } + if (strcmp(item->name, "nanoseconds") == 0) { + ts->tv_nsec = (long)item->u.number; + continue; + } + } + debug_return_bool(true); +} + +static bool +json_store_iolog_offset(struct json_item *item, struct eventlog *evlog) +{ + return json_store_timespec(item, &evlog->iolog_offset); +} + +static bool +json_store_run_time(struct json_item *item, struct eventlog *evlog) +{ + return json_store_timespec(item, &evlog->run_time); +} + +static bool +json_store_timestamp(struct json_item *item, struct eventlog *evlog) +{ + return json_store_timespec(item, &evlog->submit_time); +} + +static bool +json_store_ttyname(struct json_item *item, struct eventlog *evlog) +{ + debug_decl(json_store_ttyname, SUDO_DEBUG_UTIL); + + free(evlog->ttyname); + evlog->ttyname = item->u.string; + item->u.string = NULL; + debug_return_bool(true); +} + +static bool +json_store_uuid(struct json_item *item, struct eventlog *evlog) +{ + bool ret = false; + debug_decl(json_store_uuid, SUDO_DEBUG_UTIL); + + if (strlen(item->u.string) == sizeof(evlog->uuid_str) - 1) { + memcpy(evlog->uuid_str, item->u.string, sizeof(evlog->uuid_str)); + ret = true; + } + free(item->u.string); + item->u.string = NULL; + debug_return_bool(ret); +} + +static struct evlog_json_key { + const char *name; + enum json_value_type type; + bool (*setter)(struct json_item *, struct eventlog *); +} evlog_json_keys[] = { + { "columns", JSON_NUMBER, json_store_columns }, + { "command", JSON_STRING, json_store_command }, + { "dumped_core", JSON_BOOL, json_store_dumped_core }, + { "exit_value", JSON_NUMBER, json_store_exit_value }, + { "iolog_file", JSON_STRING, json_store_iolog_file }, + { "iolog_path", JSON_STRING, json_store_iolog_path }, + { "iolog_offset", JSON_OBJECT, json_store_iolog_offset }, + { "lines", JSON_NUMBER, json_store_lines }, + { "peeraddr", JSON_STRING, json_store_peeraddr }, + { "run_time", JSON_OBJECT, json_store_run_time }, + { "runargv", JSON_ARRAY, json_store_runargv }, + { "runenv", JSON_ARRAY, json_store_runenv }, + { "runenv_override", JSON_ARRAY, json_store_runenv_override }, + { "rungid", JSON_ID, json_store_rungid }, + { "rungroup", JSON_STRING, json_store_rungroup }, + { "runuid", JSON_ID, json_store_runuid }, + { "runuser", JSON_STRING, json_store_runuser }, + { "runchroot", JSON_STRING, json_store_runchroot }, + { "runcwd", JSON_STRING, json_store_runcwd }, + { "source", JSON_STRING, json_store_source }, + { "signal", JSON_STRING, json_store_signal }, + { "submitcwd", JSON_STRING, json_store_submitcwd }, + { "submitenv", JSON_ARRAY, json_store_submitenv }, + { "submithost", JSON_STRING, json_store_submithost }, + { "submitgroup", JSON_STRING, json_store_submitgroup }, + { "submituser", JSON_STRING, json_store_submituser }, + { "timestamp", JSON_OBJECT, json_store_timestamp }, + { "ttyname", JSON_STRING, json_store_ttyname }, + { "uuid", JSON_STRING, json_store_uuid }, + { NULL } +}; + +static struct json_item * +new_json_item(enum json_value_type type, char *name, unsigned int lineno) +{ + struct json_item *item; + debug_decl(new_json_item, SUDO_DEBUG_UTIL); + + if ((item = malloc(sizeof(*item))) == NULL) { + sudo_warnx(U_("%s: %s"), __func__, + U_("unable to allocate memory")); + debug_return_ptr(NULL); + } + item->name = name; + item->type = type; + item->lineno = lineno; + + debug_return_ptr(item); +} + +static char * +json_parse_string(char **strp) +{ + char *dst, *end, *ret, *src = *strp + 1; + size_t len; + debug_decl(json_parse_string, SUDO_DEBUG_UTIL); + + for (end = src; *end != '"' && *end != '\0'; end++) { + if (end[0] == '\\' && end[1] == '"') + end++; + } + if (*end != '"') { + sudo_warnx("%s", U_("missing double quote in name")); + debug_return_str(NULL); + } + len = (size_t)(end - src); + + /* Copy string, flattening escaped chars. */ + dst = ret = malloc(len + 1); + if (dst == NULL) { + sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); + debug_return_str(NULL); + } + while (src < end) { + int ch = *src++; + if (ch == '\\') { + switch (*src) { + case 'b': + ch = '\b'; + break; + case 'f': + ch = '\f'; + break; + case 'n': + ch = '\n'; + break; + case 'r': + ch = '\r'; + break; + case 't': + ch = '\t'; + break; + case 'u': + /* Only currently handles 8-bit ASCII. */ + if (src[1] == '0' && src[2] == '0') { + ch = sudo_hexchar(&src[3]); + if (ch != -1) { + src += 4; + break; + } + } + /* Not in \u00XX format. */ + FALLTHROUGH; + case '"': + case '\\': + default: + /* Note: a bare \ at the end of a string will be removed. */ + ch = *src; + break; + } + src++; + } + *dst++ = (char)ch; + } + *dst = '\0'; + + /* Trim trailing whitespace. */ + do { + end++; + } while (isspace((unsigned char)*end)); + *strp = end; + + debug_return_str(ret); +} + +static void +free_json_items(struct json_item_list *items) +{ + struct json_item *item; + debug_decl(free_json_items, SUDO_DEBUG_UTIL); + + while ((item = TAILQ_FIRST(items)) != NULL) { + TAILQ_REMOVE(items, item, entries); + switch (item->type) { + case JSON_STRING: + free(item->u.string); + break; + case JSON_ARRAY: + case JSON_OBJECT: + free_json_items(&item->u.child.items); + break; + case JSON_ID: + case JSON_NUMBER: + case JSON_BOOL: + case JSON_NULL: + /* Nothing to free. */ + break; + default: + sudo_warnx("%s: internal error, invalid JSON type %d", + __func__, item->type); + break; + } + free(item->name); + free(item); + } + + debug_return; +} + +void +eventlog_json_free(struct eventlog_json_object *root) +{ + debug_decl(eventlog_json_free, SUDO_DEBUG_UTIL); + if (root != NULL) { + free_json_items(&root->items); + free(root); + } + debug_return; +} + +bool +eventlog_json_parse(struct eventlog_json_object *object, struct eventlog *evlog) +{ + struct json_item *item; + bool ret = false; + debug_decl(eventlog_json_parse, SUDO_DEBUG_UTIL); + + /* First object holds all the actual data. */ + item = TAILQ_FIRST(&object->items); + if (item == NULL) { + sudo_warnx("%s", U_("missing JSON_OBJECT")); + goto done; + } + if (item->type != JSON_OBJECT) { + sudo_warnx(U_("expected JSON_OBJECT, got %d"), item->type); + goto done; + } + object = &item->u.child; + + TAILQ_FOREACH(item, &object->items, entries) { + struct evlog_json_key *key; + + /* expecting key:value pairs */ + if (item->name == NULL) { + sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO, + "%s: missing object name", __func__); + goto done; + } + + /* lookup name */ + for (key = evlog_json_keys; key->name != NULL; key++) { + if (strcmp(item->name, key->name) == 0) + break; + } + if (key->name == NULL) { + sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO, + "%s: unknown key %s", __func__, item->name); + } else if (key->type != item->type && + (key->type != JSON_ID || item->type != JSON_NUMBER)) { + sudo_debug_printf(SUDO_DEBUG_WARN|SUDO_DEBUG_LINENO, + "%s: key mismatch %s type %d, expected %d", __func__, + item->name, item->type, key->type); + goto done; + } else { + /* Matched name and type. */ + if (!key->setter(item, evlog)) { + sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, + "unable to store %s", key->name); + goto done; + } + } + } + + /* + * iolog_file must be a substring of iolog_path. + */ + if (iolog_file != NULL && evlog->iolog_path != NULL) { + const size_t filelen = strlen(iolog_file); + const size_t pathlen = strlen(evlog->iolog_path); + if (filelen <= pathlen) { + const char *cp = &evlog->iolog_path[pathlen - filelen]; + if (strcmp(cp, iolog_file) == 0) { + evlog->iolog_file = cp; + } + } + } + + ret = true; + +done: + free(iolog_file); + iolog_file = NULL; + + debug_return_bool(ret); +} + +static bool +json_insert_bool(struct json_item_list *items, char *name, bool value, + unsigned int lineno) +{ + struct json_item *item; + debug_decl(json_insert_bool, SUDO_DEBUG_UTIL); + + if ((item = new_json_item(JSON_BOOL, name, lineno)) == NULL) + debug_return_bool(false); + item->u.boolean = value; + TAILQ_INSERT_TAIL(items, item, entries); + + debug_return_bool(true); +} + +static bool +json_insert_null(struct json_item_list *items, char *name, unsigned int lineno) +{ + struct json_item *item; + debug_decl(json_insert_null, SUDO_DEBUG_UTIL); + + if ((item = new_json_item(JSON_NULL, name, lineno)) == NULL) + debug_return_bool(false); + TAILQ_INSERT_TAIL(items, item, entries); + + debug_return_bool(true); +} + +static bool +json_insert_num(struct json_item_list *items, char *name, long long value, + unsigned int lineno) +{ + struct json_item *item; + debug_decl(json_insert_num, SUDO_DEBUG_UTIL); + + if ((item = new_json_item(JSON_NUMBER, name, lineno)) == NULL) + debug_return_bool(false); + item->u.number = value; + TAILQ_INSERT_TAIL(items, item, entries); + + debug_return_bool(true); +} + +static bool +json_insert_str(struct json_item_list *items, char *name, char **strp, + unsigned int lineno) +{ + struct json_item *item; + debug_decl(json_insert_str, SUDO_DEBUG_UTIL); + + if ((item = new_json_item(JSON_STRING, name, lineno)) == NULL) + debug_return_bool(false); + item->u.string = json_parse_string(strp); + if (item->u.string == NULL) { + free(item); + debug_return_bool(false); + } + TAILQ_INSERT_TAIL(items, item, entries); + + debug_return_bool(true); +} + +static struct eventlog_json_object * +json_stack_push(struct json_stack *stack, struct json_item_list *items, + struct eventlog_json_object *frame, enum json_value_type type, char *name, + unsigned int lineno) +{ + struct json_item *item; + debug_decl(json_stack_push, SUDO_DEBUG_UTIL); + + /* We limit the stack size rather than expanding it. */ + if (stack->depth >= stack->maxdepth) { + sudo_warnx(U_("json stack exhausted (max %u frames)"), stack->maxdepth); + debug_return_ptr(NULL); + } + + /* Allocate a new item and insert it into the list. */ + if ((item = new_json_item(type, name, lineno)) == NULL) + debug_return_ptr(NULL); + TAILQ_INIT(&item->u.child.items); + item->u.child.parent = item; + TAILQ_INSERT_TAIL(items, item, entries); + + /* Push the current frame onto the stack (depth check performed above). */ + stack->frames[stack->depth++] = frame; + + /* Return the new frame */ + debug_return_ptr(&item->u.child); +} + +/* Only expect a value if a name is defined or we are in an array. */ +#define expect_value (name != NULL || (frame->parent != NULL && frame->parent->type == JSON_ARRAY)) + +struct eventlog_json_object * +eventlog_json_read(FILE *fp, const char *filename) +{ + struct eventlog_json_object *frame, *root; + struct json_stack stack = JSON_STACK_INTIALIZER(stack); + unsigned int lineno = 0; + char *name = NULL; + char *cp, *line = NULL; + size_t len, linesize = 0; + ssize_t linelen; + bool saw_comma = false; + long long num; + char ch; + debug_decl(eventlog_json_read, SUDO_DEBUG_UTIL); + + root = malloc(sizeof(*root)); + if (root == NULL) + goto bad; + + root->parent = NULL; + TAILQ_INIT(&root->items); + + frame = root; + while ((linelen = getdelim(&line, &linesize, '\n', fp)) != -1) { + char *ep = line + linelen - 1; + cp = line; + + lineno++; + + /* Trim trailing whitespace. */ + while (ep > cp && isspace((unsigned char)*ep)) + ep--; + ep[1] = '\0'; + + for (;;) { + const char *errstr; + + /* Trim leading whitespace, skip blank lines. */ + while (isspace((unsigned char)*cp)) + cp++; + + /* Check for comma separator and strip it out. */ + if (*cp == ',') { + saw_comma = true; + cp++; + while (isspace((unsigned char)*cp)) + cp++; + } + + /* End of line? */ + if (*cp == '\0') + break; + + switch (*cp) { + case '{': + if (name == NULL && frame->parent != NULL) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("objects must consist of name:value pairs")); + goto bad; + } + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + cp++; + saw_comma = false; + frame = json_stack_push(&stack, &frame->items, frame, + JSON_OBJECT, name, lineno); + if (frame == NULL) + goto bad; + name = NULL; + break; + case '}': + if (stack.depth == 0 || frame->parent == NULL || + frame->parent->type != JSON_OBJECT) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unmatched close brace")); + goto bad; + } + cp++; + frame = stack.frames[--stack.depth]; + saw_comma = false; + break; + case '[': + if (frame->parent == NULL) { + /* Must have an enclosing object. */ + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected array")); + goto bad; + } + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + cp++; + saw_comma = false; + frame = json_stack_push(&stack, &frame->items, frame, + JSON_ARRAY, name, lineno); + if (frame == NULL) + goto bad; + name = NULL; + break; + case ']': + if (stack.depth == 0 || frame->parent == NULL || + frame->parent->type != JSON_ARRAY) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unmatched close bracket")); + goto bad; + } + cp++; + frame = stack.frames[--stack.depth]; + saw_comma = false; + break; + case '"': + if (frame->parent == NULL) { + /* Must have an enclosing object. */ + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected string")); + goto bad; + } + + if (!expect_value) { + /* Parse "name": */ + if ((name = json_parse_string(&cp)) == NULL) + goto bad; + /* TODO: allow colon on next line? */ + if (*cp != ':') { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing colon after name")); + goto bad; + } + cp++; + } else { + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + saw_comma = false; + if (!json_insert_str(&frame->items, name, &cp, lineno)) + goto bad; + name = NULL; + } + break; + case 't': + if (strncmp(cp, "true", sizeof("true") - 1) != 0) + goto parse_error; + if (!expect_value) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected boolean")); + goto bad; + } + cp += sizeof("true") - 1; + if (*cp != ',' && !isspace((unsigned char)*cp) && *cp != '\0') + goto parse_error; + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + saw_comma = false; + + if (!json_insert_bool(&frame->items, name, true, lineno)) + goto bad; + name = NULL; + break; + case 'f': + if (strncmp(cp, "false", sizeof("false") - 1) != 0) + goto parse_error; + if (!expect_value) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected boolean")); + goto bad; + } + cp += sizeof("false") - 1; + if (*cp != ',' && !isspace((unsigned char)*cp) && *cp != '\0') + goto parse_error; + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + saw_comma = false; + + if (!json_insert_bool(&frame->items, name, false, lineno)) + goto bad; + name = NULL; + break; + case 'n': + if (strncmp(cp, "null", sizeof("null") - 1) != 0) + goto parse_error; + if (!expect_value) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected null")); + goto bad; + } + cp += sizeof("null") - 1; + if (*cp != ',' && !isspace((unsigned char)*cp) && *cp != '\0') + goto parse_error; + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + saw_comma = false; + + if (!json_insert_null(&frame->items, name, lineno)) + goto bad; + name = NULL; + break; + case '+': case '-': case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': case '8': case '9': + if (!expect_value) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unexpected number")); + goto bad; + } + /* XXX - strtonumx() would be simpler here. */ + len = strcspn(cp, " \f\n\r\t\v,"); + ch = cp[len]; + cp[len] = '\0'; + if (!saw_comma && !TAILQ_EMPTY(&frame->items)) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("missing separator between values")); + goto bad; + } + saw_comma = false; + num = sudo_strtonum(cp, LLONG_MIN, LLONG_MAX, &errstr); + if (errstr != NULL) { + sudo_warnx("%s:%u:%td: %s: %s", filename, lineno, cp - line, + cp, U_(errstr)); + goto bad; + } + cp += len; + *cp = ch; + + if (!json_insert_num(&frame->items, name, num, lineno)) + goto bad; + name = NULL; + break; + default: + goto parse_error; + } + } + } + if (stack.depth != 0) { + frame = stack.frames[stack.depth - 1]; + if (frame->parent == NULL || frame->parent->type == JSON_OBJECT) { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unmatched close brace")); + } else { + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, + U_("unmatched close bracket")); + } + goto bad; + } + + goto done; + +parse_error: + sudo_warnx("%s:%u:%td: %s", filename, lineno, cp - line, U_("parse error")); +bad: + eventlog_json_free(root); + root = NULL; +done: + free(line); + free(name); + + debug_return_ptr(root); +} diff --git a/lib/eventlog/parse_json.h b/lib/eventlog/parse_json.h new file mode 100644 index 0000000..e04efea --- /dev/null +++ b/lib/eventlog/parse_json.h @@ -0,0 +1,46 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020, 2023 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef PARSE_JSON_H +#define PARSE_JSON_H + +#include <sudo_json.h> +#include <sudo_queue.h> + +TAILQ_HEAD(json_item_list, json_item); + +struct eventlog_json_object { + struct json_item *parent; + struct json_item_list items; +}; + +struct json_item { + TAILQ_ENTRY(json_item) entries; + char *name; /* may be NULL for first brace */ + unsigned int lineno; + enum json_value_type type; + union { + struct eventlog_json_object child; + char *string; + long long number; + id_t id; + bool boolean; + } u; +}; + +#endif /* PARSE_JSON_H */ diff --git a/lib/eventlog/regress/eventlog_store/store_json_test.c b/lib/eventlog/regress/eventlog_store/store_json_test.c new file mode 100644 index 0000000..5c8f6fe --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/store_json_test.c @@ -0,0 +1,199 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020, 2023 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include <unistd.h> + +#define SUDO_ERROR_WRAP 0 + +#include <sudo_compat.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_util.h> + +#include <parse_json.h> + +sudo_dso_public int main(int argc, char *argv[]); + +sudo_noreturn static void +usage(void) +{ + fprintf(stderr, "usage: %s [-cv] input_file ...\n", + getprogname()); + exit(EXIT_FAILURE); +} + +static bool +compare(FILE *fp, const char *infile, struct json_container *jsonc) +{ + const char *cp; + unsigned int lineno = 0; + size_t linesize = 0; + char *line = NULL; + ssize_t len; + + cp = sudo_json_get_buf(jsonc); + + while ((len = getdelim(&line, &linesize, '\n', fp)) != -1) { + lineno++; + + /* skip open/close brace, not present in formatted output */ + if (lineno == 1 && strcmp(line, "{\n") == 0) + continue; + if (*cp == '\0' && strcmp(line, "}\n") == 0) + continue; + + /* Ignore newlines in output to make comparison easier. */ + if (*cp == '\n') + cp++; + if (line[len - 1] == '\n') + len--; + + if (strncmp(line, cp, (size_t)len) != 0) { + fprintf(stderr, "%s: mismatch on line %u\n", infile, lineno); + fprintf(stderr, "expected: %s", line); + fprintf(stderr, "got : %.*s\n", (int)len, cp); + return false; + } + cp += len; + } + free(line); + + return true; +} + +int +main(int argc, char *argv[]) +{ + int ch, i, ntests = 0, errors = 0; + bool cat = false; + + initprogname(argc > 0 ? argv[0] : "store_json_test"); + + while ((ch = getopt(argc, argv, "cv")) != -1) { + switch (ch) { + case 'c': + cat = true; + break; + case 'v': + /* ignored */ + break; + default: + usage(); + /* NOTREACHED */ + } + } + argc -= optind; + argv += optind; + + if (argc < 1) + usage(); + + for (i = 0; i < argc; i++) { + struct eventlog_json_object *root; + struct eventlog *evlog = NULL; + struct json_container jsonc; + const char *infile = argv[i]; + const char *outfile = argv[i]; + const char *cp; + char pathbuf[PATH_MAX]; + FILE *infp = NULL; + FILE *outfp = NULL; + + ntests++; + + if (!sudo_json_init(&jsonc, 4, false, true, true)) { + errors++; + continue; + } + + /* Parse input file. */ + if ((infp = fopen(infile, "r")) == NULL) { + sudo_warn("%s", argv[i]); + errors++; + continue; + } + root = eventlog_json_read(infp, infile); + if (root == NULL) { + errors++; + goto next; + } + + /* Convert JSON to event log. */ + evlog = calloc(1, sizeof(*evlog)); + if (evlog == NULL) { + sudo_warnx("%s: %s", __func__, "unable to allocate memory"); + errors++; + goto next; + } + if (!eventlog_json_parse(root, evlog)) { + errors++; + goto next; + } + + /* Format event log as JSON. */ + if (!eventlog_store_json(&jsonc, evlog)) { + errors++; + goto next; + } + + /* Check for a .out.ok file in the same location as the .in file. */ + cp = strrchr(infile, '.'); + if (cp != NULL && strcmp(cp, ".in") == 0) { + snprintf(pathbuf, sizeof(pathbuf), "%.*s.out.ok", + (int)(cp - infile), infile); + if ((outfp = fopen(pathbuf, "r")) != NULL) + outfile = pathbuf; + } + if (outfp == NULL) + outfp = infp; + + /* Compare output to expected output. */ + rewind(outfp); + if (!compare(outfp, outfile, &jsonc)) + errors++; + + /* Write the formatted output to stdout for -c (cat) */ + if (cat) { + fprintf(stdout, "{%s\n}\n", sudo_json_get_buf(&jsonc)); + fflush(stdout); + } + +next: + eventlog_free(evlog); + eventlog_json_free(root); + sudo_json_free(&jsonc); + if (infp != NULL) + fclose(infp); + if (outfp != NULL && outfp != infp) + fclose(outfp); + } + + if (ntests != 0) { + printf("%s: %d test%s run, %d errors, %d%% success rate\n", + getprogname(), ntests, ntests == 1 ? "" : "s", errors, + (ntests - errors) * 100 / ntests); + } + + return errors; +} diff --git a/lib/eventlog/regress/eventlog_store/store_sudo_test.c b/lib/eventlog/regress/eventlog_store/store_sudo_test.c new file mode 100644 index 0000000..f873cd5 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/store_sudo_test.c @@ -0,0 +1,209 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020, 2023 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include <unistd.h> + +#define SUDO_ERROR_WRAP 0 + +#include <sudo_compat.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_lbuf.h> +#include <sudo_util.h> + +sudo_dso_public int main(int argc, char *argv[]); + +sudo_noreturn static void +usage(void) +{ + fprintf(stderr, "usage: %s [-cv] input_file ...\n", + getprogname()); + exit(EXIT_FAILURE); +} + +static bool +compare(FILE *fp, const char *infile, const char *output) +{ + static size_t linesize = 0; + static char *line = NULL; + int i; + + /* Expect two log lines, one for accept, one for exit. */ + for (i = 0; i < 2; i++) { + ssize_t output_len = (ssize_t)strcspn(output, "\n"); + ssize_t len = getdelim(&line, &linesize, '\n', fp); + if (len == -1) { + sudo_warn("getdelim"); + return false; + } + if (line[len - 1] == '\n') + len--; + + if (len != output_len || strncmp(line, output, (size_t)len) != 0) { + fprintf(stderr, "%s: %s mismatch\n", infile, i ? "exit" : "accept"); + fprintf(stderr, "expected: %.*s\n", (int)len, line); + fprintf(stderr, "got : %.*s\n", (int)output_len, output); + return false; + } + if (i == 0) { + /* Skip past newline in accept record output. */ + output += output_len; + if (output[0] != '\n' || output[1] == '\0') { + sudo_warnx("missing exit record"); + return false; + } + output++; + } + } + + return true; +} + +int +main(int argc, char *argv[]) +{ + int ch, i, ntests = 0, errors = 0; + struct sudo_lbuf lbuf; + bool cat = false; + + initprogname(argc > 0 ? argv[0] : "store_sudo_test"); + + while ((ch = getopt(argc, argv, "v")) != -1) { + switch (ch) { + case 'c': + cat = true; + break; + case 'v': + /* ignored */ + break; + default: + usage(); + /* NOTREACHED */ + } + } + argc -= optind; + argv += optind; + + if (argc < 1) + usage(); + + sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0); + for (i = 0; i < argc; i++) { + struct eventlog_json_object *root; + struct eventlog *evlog = NULL; + const char *infile = argv[i]; + const char *outfile = argv[i]; + char pathbuf[PATH_MAX]; + FILE *infp = NULL; + FILE *outfp = NULL; + size_t len; + + ntests++; + + /* Parse input file. */ + if ((infp = fopen(infile, "r")) == NULL) { + sudo_warn("%s", argv[i]); + errors++; + continue; + } + root = eventlog_json_read(infp, infile); + if (root == NULL) { + errors++; + goto next; + } + + /* Convert JSON to event log. */ + evlog = calloc(1, sizeof(*evlog)); + if (evlog == NULL) { + sudo_warnx("%s: %s", __func__, "unable to allocate memory"); + errors++; + goto next; + } + if (!eventlog_json_parse(root, evlog)) { + errors++; + goto next; + } + + /* Format event log in sudo log format. */ + if (!eventlog_store_sudo(EVLOG_ACCEPT, evlog, &lbuf)) { + errors++; + goto next; + } + sudo_lbuf_append(&lbuf, "\n"); + if (!eventlog_store_sudo(EVLOG_EXIT, evlog, &lbuf)) { + errors++; + goto next; + } + sudo_lbuf_append(&lbuf, "\n"); + + /* Write the formatted output to stdout for -c (cat) */ + if (cat) { + puts(lbuf.buf); + fflush(stdout); + } + + /* Check for a .out.ok file in the same location as the .in file. */ + len = strlen(infile); + if (len < sizeof(".json.in")) { + sudo_warnx("%s must end in .json.in", infile); + errors++; + goto next; + } + len -= sizeof(".json.in") - 1; + if (strcmp(&infile[len], ".json.in") != 0) { + sudo_warnx("%s must end in .json.in", infile); + errors++; + goto next; + } + snprintf(pathbuf, sizeof(pathbuf), "%.*s.sudo.out.ok", + (int)len, infile); + if ((outfp = fopen(pathbuf, "r")) == NULL) { + sudo_warn("%s", pathbuf); + errors++; + goto next; + } + + /* Compare output to expected output. */ + if (!compare(outfp, outfile, lbuf.buf)) + errors++; + +next: + lbuf.len = 0; + eventlog_json_free(root); + eventlog_free(evlog); + if (infp != NULL) + fclose(infp); + if (outfp != NULL && outfp != infp) + fclose(outfp); + } + sudo_lbuf_destroy(&lbuf); + + if (ntests != 0) { + printf("%s: %d test%s run, %d errors, %d%% success rate\n", + getprogname(), ntests, ntests == 1 ? "" : "s", errors, + (ntests - errors) * 100 / ntests); + } + + return errors; +} diff --git a/lib/eventlog/regress/eventlog_store/test1.json.in b/lib/eventlog/regress/eventlog_store/test1.json.in new file mode 100644 index 0000000..0e73df9 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test1.json.in @@ -0,0 +1,52 @@ +{ + "uuid": "94109a6eb8-9bed-41ba-0ff1-79926f3947", + "server_time": { + "seconds": 1677638673, + "nanoseconds": 98769807, + "iso8601": "20230301024433Z", + "localtime": "Tue Feb 28 19:44:33 MST 2023" + }, + "submit_time": { + "seconds": 1677638673, + "nanoseconds": 93789768, + "iso8601": "20230301024433Z", + "localtime": "Tue Feb 28 19:44:33 MST 2023" + }, + "peeraddr": "172.30.200.2", + "iolog_path": "/var/log/sudo-logsrvd/millert/00/03/FI", + "iolog_file": "00/03/FI", + "columns": 80, + "command": "/usr/bin/ci", + "lines": 24, + "runargv": [ + "ci", + "-u", + "aliases\n" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/ci -u aliases", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ], + "runenv_override": [ + "KRB5CCNAME=bogus", + "LD_LIBRARY_PATH=/opt/sudo/libexec" + ], + "runuid": 0, + "runuser": "root", + "source": "/etc/sudoers:89:24", + "submitcwd": "/etc/mail", + "submithost": "xerxes.sudo.ws", + "submituser": "millert", + "ttyname": "/dev/ttypb", + "exit_value": 1 +} diff --git a/lib/eventlog/regress/eventlog_store/test1.json.out.ok b/lib/eventlog/regress/eventlog_store/test1.json.out.ok new file mode 100644 index 0000000..2ddc8c5 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test1.json.out.ok @@ -0,0 +1,31 @@ +{ + "submituser": "millert", + "command": "/usr/bin/ci", + "runuser": "root", + "source": "/etc/sudoers:89:24", + "ttyname": "/dev/ttypb", + "submithost": "xerxes.sudo.ws", + "submitcwd": "/etc/mail", + "runuid": 0, + "columns": 80, + "lines": 24, + "runargv": [ + "ci", + "-u", + "aliases\n" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/ci -u aliases", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ] +} diff --git a/lib/eventlog/regress/eventlog_store/test1.sudo.out.ok b/lib/eventlog/regress/eventlog_store/test1.sudo.out.ok new file mode 100644 index 0000000..17c344e --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test1.sudo.out.ok @@ -0,0 +1,2 @@ +HOST=xerxes.sudo.ws ; TTY=ttypb ; CWD=/etc/mail ; USER=root ; TSID=0003FI ; ENV=KRB5CCNAME=bogus LD_LIBRARY_PATH=/opt/sudo/libexec ; COMMAND=/usr/bin/ci -u aliases#012 +HOST=xerxes.sudo.ws ; TTY=ttypb ; CWD=/etc/mail ; USER=root ; TSID=0003FI ; ENV=KRB5CCNAME=bogus LD_LIBRARY_PATH=/opt/sudo/libexec ; COMMAND=/usr/bin/ci -u aliases#012 ; EXIT=1 diff --git a/lib/eventlog/regress/eventlog_store/test2.json.in b/lib/eventlog/regress/eventlog_store/test2.json.in new file mode 100644 index 0000000..6af3a31 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test2.json.in @@ -0,0 +1,48 @@ +{ + "uuid": "a17521dd52-1b7f-4ca1-5086-6957336362", + "server_time": { + "seconds": 1671070212, + "nanoseconds": 246006550, + "iso8601": "20221215021012Z", + "localtime": "Wed Dec 14 19:10:12 MST 2022" + }, + "submit_time": { + "seconds": 1671070212, + "nanoseconds": 243017337, + "iso8601": "20221215021012Z", + "localtime": "Wed Dec 14 19:10:12 MST 2022" + }, + "peeraddr": "172.30.200.2", + "iolog_path": "/var/log/sudo-logsrvd/millert/00/03/5Q", + "iolog_file": "00/03/5Q", + "columns": 80, + "command": "/usr/bin/id", + "lines": 24, + "runargv": [ + "id" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/id", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ], + "runenv_override": [ + "KRB5CCNAME=bogus" + ], + "runuid": 0, + "runuser": "root", + "source": "sudoRole %wheel", + "submitcwd": "/usr/src/local/millert/sudo/trunk", + "submithost": "xerxes.sudo.ws", + "submituser": "millert", + "ttyname": "/dev/ttyp0" +} diff --git a/lib/eventlog/regress/eventlog_store/test2.json.out.ok b/lib/eventlog/regress/eventlog_store/test2.json.out.ok new file mode 100644 index 0000000..e26290c --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test2.json.out.ok @@ -0,0 +1,29 @@ +{ + "submituser": "millert", + "command": "/usr/bin/id", + "runuser": "root", + "source": "sudoRole %wheel", + "ttyname": "/dev/ttyp0", + "submithost": "xerxes.sudo.ws", + "submitcwd": "/usr/src/local/millert/sudo/trunk", + "runuid": 0, + "columns": 80, + "lines": 24, + "runargv": [ + "id" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/id", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ] +} diff --git a/lib/eventlog/regress/eventlog_store/test2.sudo.out.ok b/lib/eventlog/regress/eventlog_store/test2.sudo.out.ok new file mode 100644 index 0000000..51faf04 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test2.sudo.out.ok @@ -0,0 +1,2 @@ +HOST=xerxes.sudo.ws ; TTY=ttyp0 ; CWD=/usr/src/local/millert/sudo/trunk ; USER=root ; TSID=00035Q ; ENV=KRB5CCNAME=bogus ; COMMAND=/usr/bin/id +HOST=xerxes.sudo.ws ; TTY=ttyp0 ; CWD=/usr/src/local/millert/sudo/trunk ; USER=root ; TSID=00035Q ; ENV=KRB5CCNAME=bogus ; COMMAND=/usr/bin/id ; EXIT=0 diff --git a/lib/eventlog/regress/eventlog_store/test3.json.in b/lib/eventlog/regress/eventlog_store/test3.json.in new file mode 100644 index 0000000..184333f --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test3.json.in @@ -0,0 +1,49 @@ +{ + "uuid": "54e6806305-0f50-44bf-fe6a-c8fa7a65ac", + "server_time": { + "seconds": 1678475729, + "nanoseconds": 286796437, + "iso8601": "20230310191529Z", + "localtime": "Fri Mar 10 12:15:29 MST 2023" + }, + "submit_time": { + "seconds": 1633116433, + "nanoseconds": 682537651, + "iso8601": "20211001192713Z", + "localtime": "Fri Oct 1 13:27:13 MDT 2021" + }, + "peeraddr": "172.30.200.50", + "iolog_path": "/var/log/sudo-logsrvd/millert/00/00/5H", + "iolog_file": "00/00/5H", + "columns": 80, + "command": "/usr/bin/find", + "lines": 24, + "runargv": [ + "find", + "build/out/sudoers/" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/find build/out/sudoers/", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ], + "runuid": 0, + "runuser": "root", + "source": "/etc/sudoers:89:24", + "submitcwd": "/home/millert/sudo/oss-fuzz", + "submithost": "linux-build", + "submituser": "millert", + "ttyname": "/dev/pts/1", + "exit_value": 131, + "signal": "QUIT", + "dumped_core": true +} diff --git a/lib/eventlog/regress/eventlog_store/test3.json.out.ok b/lib/eventlog/regress/eventlog_store/test3.json.out.ok new file mode 100644 index 0000000..967a75c --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test3.json.out.ok @@ -0,0 +1,30 @@ +{ + "submituser": "millert", + "command": "/usr/bin/find", + "runuser": "root", + "source": "/etc/sudoers:89:24", + "ttyname": "/dev/pts/1", + "submithost": "linux-build", + "submitcwd": "/home/millert/sudo/oss-fuzz", + "runuid": 0, + "columns": 80, + "lines": 24, + "runargv": [ + "find", + "build/out/sudoers/" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/find build/out/sudoers/", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20" + ] +} diff --git a/lib/eventlog/regress/eventlog_store/test3.sudo.out.ok b/lib/eventlog/regress/eventlog_store/test3.sudo.out.ok new file mode 100644 index 0000000..5f7fee2 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test3.sudo.out.ok @@ -0,0 +1,2 @@ +HOST=linux-build ; TTY=pts/1 ; CWD=/home/millert/sudo/oss-fuzz ; USER=root ; TSID=00005H ; COMMAND=/usr/bin/find build/out/sudoers/ +HOST=linux-build ; TTY=pts/1 ; CWD=/home/millert/sudo/oss-fuzz ; USER=root ; TSID=00005H ; COMMAND=/usr/bin/find build/out/sudoers/ ; SIGNAL=QUIT ; EXIT=131 diff --git a/lib/eventlog/regress/eventlog_store/test4.json.in b/lib/eventlog/regress/eventlog_store/test4.json.in new file mode 100644 index 0000000..8836a44 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test4.json.in @@ -0,0 +1,47 @@ +{ + "uuid": "0bf9f26a7c-5e8b-4f82-f6c1-24a49a254c", + "server_time": { + "seconds": 1677638637, + "nanoseconds": 369091862, + "iso8601": "20230301024357Z", + "localtime": "Tue Feb 28 19:43:57 MST 2023" + }, + "submit_time": { + "seconds": 1677638637, + "nanoseconds": 364571747, + "iso8601": "20230301024357Z", + "localtime": "Tue Feb 28 19:43:57 MST 2023" + }, + "peeraddr": "172.30.200.2", + "iolog_path": "/var/log/sudo-logsrvd/millert/00/03/FG", + "iolog_file": "00/03/FG", + "columns": 80, + "command": "/usr/bin/vi", + "lines": 24, + "runargv": [ + "vi", + "aliases" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/vi aliases", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20", + "KRB5CCNAME=bogus" + ], + "runuid": 0, + "runuser": "root", + "source": "/etc/sudoers:89:24", + "submitcwd": "/etc/mail", + "submithost": "xerxes.sudo.ws", + "submituser": "millert", + "ttyname": "/dev/ttypb" +} diff --git a/lib/eventlog/regress/eventlog_store/test4.json.out.ok b/lib/eventlog/regress/eventlog_store/test4.json.out.ok new file mode 100644 index 0000000..2f15940 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test4.json.out.ok @@ -0,0 +1,31 @@ +{ + "submituser": "millert", + "command": "/usr/bin/vi", + "runuser": "root", + "source": "/etc/sudoers:89:24", + "ttyname": "/dev/ttypb", + "submithost": "xerxes.sudo.ws", + "submitcwd": "/etc/mail", + "runuid": 0, + "columns": 80, + "lines": 24, + "runargv": [ + "vi", + "aliases" + ], + "runenv": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=tmux", + "LANG=en_US.UTF-8", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/bash", + "SUDO_COMMAND=/usr/bin/vi aliases", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20", + "KRB5CCNAME=bogus" + ] +} diff --git a/lib/eventlog/regress/eventlog_store/test4.sudo.out.ok b/lib/eventlog/regress/eventlog_store/test4.sudo.out.ok new file mode 100644 index 0000000..c1589d0 --- /dev/null +++ b/lib/eventlog/regress/eventlog_store/test4.sudo.out.ok @@ -0,0 +1,2 @@ +HOST=xerxes.sudo.ws ; TTY=ttypb ; CWD=/etc/mail ; USER=root ; TSID=0003FG ; COMMAND=/usr/bin/vi aliases +HOST=xerxes.sudo.ws ; TTY=ttypb ; CWD=/etc/mail ; USER=root ; TSID=0003FG ; COMMAND=/usr/bin/vi aliases ; EXIT=0 diff --git a/lib/eventlog/regress/logwrap/check_wrap.c b/lib/eventlog/regress/logwrap/check_wrap.c new file mode 100644 index 0000000..15134f0 --- /dev/null +++ b/lib/eventlog/regress/logwrap/check_wrap.c @@ -0,0 +1,124 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2011-2013 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include <unistd.h> + +#define SUDO_ERROR_WRAP 0 + +#include <sudo_compat.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_plugin.h> +#include <sudo_util.h> + +sudo_dso_public int main(int argc, char *argv[]); + +sudo_noreturn static void +usage(void) +{ + fprintf(stderr, "usage: %s [-v] inputfile\n", getprogname()); + exit(EXIT_FAILURE); +} + +int +main(int argc, char *argv[]) +{ + int ch, lineno = 0, which = 0; + char *line, lines[2][2048]; + const char *infile; + unsigned int len; + FILE *fp; + + initprogname(argc > 0 ? argv[0] : "check_wrap"); + + while ((ch = getopt(argc, argv, "v")) != -1) { + switch (ch) { + case 'v': + /* ignored */ + break; + default: + usage(); + /* NOTREACHED */ + } + } + argc -= optind; + argv += optind; + + if (argc != 1) + usage(); + infile = argv[0]; + + fp = fopen(infile, "r"); + if (fp == NULL) + sudo_fatalx("unable to open %s", infile); + + /* + * Each test record consists of a log entry on one line and a list of + * line lengths to test it with on the next. E.g. + * + * Jun 30 14:49:51 : millert : TTY=ttypn ; PWD=/usr/src/local/millert/hg/sudo/trunk/plugins/sudoers ; USER=root ; TSID=0004LD ; COMMAND=/usr/local/sbin/visudo + * 60-80,40 + */ + while ((line = fgets(lines[which], sizeof(lines[which]), fp)) != NULL) { + char *cp, *last; + + line[strcspn(line, "\n")] = '\0'; + + /* If we read the 2nd line, parse list of line lengths and check. */ + if (which) { + lineno++; + for (cp = strtok_r(lines[1], ",", &last); cp != NULL; cp = strtok_r(NULL, ",", &last)) { + unsigned int maxlen; + const char *errstr; + char *dash; + + /* May be either a number or a range. */ + dash = strchr(cp, '-'); + if (dash != NULL) { + *dash = '\0'; + len = (unsigned int)sudo_strtonum(cp, 0, INT_MAX, &errstr); + if (errstr == NULL) + maxlen = (unsigned int)sudo_strtonum(dash + 1, 0, INT_MAX, &errstr); + } else { + len = maxlen = (unsigned int)sudo_strtonum(cp, 0, INT_MAX, &errstr); + } + if (errstr != NULL) { + sudo_fatalx("%s: invalid length on line %d", infile, lineno); + } + while (len <= maxlen) { + if (len == 0) { + puts("# word wrap disabled"); + } else { + printf("# word wrap at %u characters\n", len); + } + eventlog_writeln(stdout, lines[0], strlen(lines[0]), len); + len++; + } + } + } + which = !which; + } + + return EXIT_SUCCESS; +} diff --git a/lib/eventlog/regress/logwrap/check_wrap.in b/lib/eventlog/regress/logwrap/check_wrap.in new file mode 100644 index 0000000..e8e7081 --- /dev/null +++ b/lib/eventlog/regress/logwrap/check_wrap.in @@ -0,0 +1,4 @@ +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +0,60-80,120,140 +Jun 26 18:00:06 : millert : TTY=ttypm ; PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +0,60-80,120,140 diff --git a/lib/eventlog/regress/logwrap/check_wrap.out.ok b/lib/eventlog/regress/logwrap/check_wrap.out.ok new file mode 100644 index 0000000..55e9da8 --- /dev/null +++ b/lib/eventlog/regress/logwrap/check_wrap.out.ok @@ -0,0 +1,179 @@ +# word wrap disabled +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +# word wrap at 60 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 + ; PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 61 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 + ; PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 62 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 63 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 64 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 65 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 66 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 67 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool + list users +# word wrap at 68 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool + list users +# word wrap at 69 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool + list users +# word wrap at 70 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool + list users +# word wrap at 71 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool + list users +# word wrap at 72 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 73 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 74 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 75 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 76 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 77 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list + users +# word wrap at 78 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +# word wrap at 79 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +# word wrap at 80 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; + PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +# word wrap at 120 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; PWD=/home/tu2sp3-a ; USER=root ; + COMMAND=/opt/quest/bin/vastool list users +# word wrap at 140 characters +Jul 11 11:30:17 : tu2sp3-a : command not allowed ; TTY=pts/1 ; PWD=/home/tu2sp3-a ; USER=root ; COMMAND=/opt/quest/bin/vastool list users +# word wrap disabled +Jun 26 18:00:06 : millert : TTY=ttypm ; PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 60 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 61 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 62 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 63 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 64 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 65 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 66 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 67 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 68 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 69 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; + TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 70 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT + ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 71 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT + ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 72 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 73 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 74 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 75 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 76 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 77 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 78 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 79 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; + PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 80 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; PWD=/usr/src/local/millert/hg/sudo/build + ; USER=root ; TSID=0004KT ; COMMAND=/bin/rm /root/.bash_profile +# word wrap at 120 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; + COMMAND=/bin/rm /root/.bash_profile +# word wrap at 140 characters +Jun 26 18:00:06 : millert : TTY=ttypm ; PWD=/usr/src/local/millert/hg/sudo/build ; USER=root ; TSID=0004KT ; COMMAND=/bin/rm + /root/.bash_profile diff --git a/lib/eventlog/regress/parse_json/check_parse_json.c b/lib/eventlog/regress/parse_json/check_parse_json.c new file mode 100644 index 0000000..496fac9 --- /dev/null +++ b/lib/eventlog/regress/parse_json/check_parse_json.c @@ -0,0 +1,270 @@ +/* + * SPDX-License-Identifier: ISC + * + * Copyright (c) 2020 Todd C. Miller <Todd.Miller@sudo.ws> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <limits.h> +#include <unistd.h> + +#define SUDO_ERROR_WRAP 0 + +#include <sudo_compat.h> +#include <sudo_eventlog.h> +#include <sudo_fatal.h> +#include <sudo_util.h> + +#include <parse_json.h> + +sudo_dso_public int main(int argc, char *argv[]); + +static bool +json_print_object(struct json_container *jsonc, struct eventlog_json_object *object) +{ + struct json_item *item; + struct json_value json_value; + bool ret = false; + + TAILQ_FOREACH(item, &object->items, entries) { + switch (item->type) { + case JSON_STRING: + json_value.type = JSON_STRING; + json_value.u.string = item->u.string; + if (!sudo_json_add_value(jsonc, item->name, &json_value)) + goto oom; + break; + case JSON_NUMBER: + json_value.type = JSON_NUMBER; + json_value.u.number = item->u.number; + if (!sudo_json_add_value(jsonc, item->name, &json_value)) + goto oom; + break; + case JSON_OBJECT: + if (!sudo_json_open_object(jsonc, item->name)) + goto oom; + if (!json_print_object(jsonc, &item->u.child)) + goto done; + if (!sudo_json_close_object(jsonc)) + goto oom; + break; + case JSON_ARRAY: + if (!sudo_json_open_array(jsonc, item->name)) + goto oom; + if (!json_print_object(jsonc, &item->u.child)) + goto done; + if (!sudo_json_close_array(jsonc)) + goto oom; + break; + case JSON_BOOL: + json_value.type = JSON_BOOL; + json_value.u.boolean = item->u.boolean; + if (!sudo_json_add_value(jsonc, item->name, &json_value)) + goto oom; + break; + case JSON_NULL: + json_value.type = JSON_NULL; + if (!sudo_json_add_value(jsonc, item->name, &json_value)) + goto oom; + break; + default: + sudo_warnx("unsupported JSON type %d", item->type); + goto done; + } + } + + ret = true; + goto done; + +oom: + sudo_warnx("%s: %s", __func__, "unable to allocate memory"); +done: + return ret; +} + +static bool +json_format(struct json_container *jsonc, struct eventlog_json_object *object) +{ + struct json_item *item; + bool ret = false; + + /* First object holds all the actual data. */ + item = TAILQ_FIRST(&object->items); + if (item->type != JSON_OBJECT) { + sudo_warnx("expected JSON_OBJECT, got %d", item->type); + goto done; + } + object = &item->u.child; + + if (!json_print_object(jsonc, object)) + goto done; + + ret = true; + +done: + return ret; +} + +sudo_noreturn static void +usage(void) +{ + fprintf(stderr, "usage: %s [-cv] input_file ...\n", + getprogname()); + exit(EXIT_FAILURE); +} + +static bool +compare(FILE *fp, const char *infile, struct json_container *jsonc) +{ + const char *cp; + unsigned int lineno = 0; + size_t linesize = 0; + char *line = NULL; + ssize_t len; + + cp = sudo_json_get_buf(jsonc); + + while ((len = getdelim(&line, &linesize, '\n', fp)) != -1) { + lineno++; + + /* skip open/close brace, not present in formatted output */ + if (lineno == 1 && strcmp(line, "{\n") == 0) + continue; + if (*cp == '\0' && strcmp(line, "}\n") == 0) + continue; + + /* Ignore newlines in output to make comparison easier. */ + if (*cp == '\n') + cp++; + if (line[len - 1] == '\n') + len--; + + if (strncmp(line, cp, (size_t)len) != 0) { + fprintf(stderr, "%s: mismatch on line %u\n", infile, lineno); + fprintf(stderr, "expected: %s", line); + fprintf(stderr, "got : %.*s\n", (int)len, cp); + return false; + } + cp += len; + } + free(line); + + return true; +} + +int +main(int argc, char *argv[]) +{ + int ch, i, ntests = 0, errors = 0; + bool cat = false; + + initprogname(argc > 0 ? argv[0] : "check_parse_json"); + + while ((ch = getopt(argc, argv, "cv")) != -1) { + switch (ch) { + case 'c': + cat = true; + break; + case 'v': + /* ignored */ + break; + default: + usage(); + } + } + argc -= optind; + argv += optind; + + if (argc < 1) + usage(); + + for (i = 0; i < argc; i++) { + struct eventlog_json_object *root; + struct json_container jsonc; + const char *infile = argv[i]; + const char *outfile = argv[i]; + const char *cp; + char pathbuf[PATH_MAX]; + FILE *infp = NULL; + FILE *outfp = NULL; + + ntests++; + + if (!sudo_json_init(&jsonc, 4, false, true, true)) { + errors++; + continue; + } + + /* Parse input file. */ + if ((infp = fopen(infile, "r")) == NULL) { + sudo_warn("%s", argv[i]); + errors++; + continue; + } + root = eventlog_json_read(infp, infile); + if (root == NULL) { + errors++; + goto next; + } + + /* Format as pretty-printed JSON */ + if (!json_format(&jsonc, root)) { + errors++; + goto next; + } + + /* Check for a .out.ok file in the same location as the .in file. */ + cp = strrchr(infile, '.'); + if (cp != NULL && strcmp(cp, ".in") == 0) { + snprintf(pathbuf, sizeof(pathbuf), "%.*s.out.ok", + (int)(cp - infile), infile); + if ((outfp = fopen(pathbuf, "r")) != NULL) + outfile = pathbuf; + } + if (outfp == NULL) + outfp = infp; + + /* Compare output to expected output. */ + rewind(outfp); + if (!compare(outfp, outfile, &jsonc)) + errors++; + + /* Write the formatted output to stdout for -c (cat) */ + if (cat) { + fprintf(stdout, "{%s\n}\n", sudo_json_get_buf(&jsonc)); + fflush(stdout); + } + +next: + eventlog_json_free(root); + sudo_json_free(&jsonc); + if (infp != NULL) + fclose(infp); + if (outfp != NULL && outfp != infp) + fclose(outfp); + } + + if (ntests != 0) { + printf("%s: %d test%s run, %d errors, %d%% success rate\n", + getprogname(), ntests, ntests == 1 ? "" : "s", errors, + (ntests - errors) * 100 / ntests); + } + + return errors; +} diff --git a/lib/eventlog/regress/parse_json/test1.in b/lib/eventlog/regress/parse_json/test1.in new file mode 100644 index 0000000..8ad3689 --- /dev/null +++ b/lib/eventlog/regress/parse_json/test1.in @@ -0,0 +1,34 @@ +{ + "timestamp": { + "seconds": 1584993067, + "nanoseconds": 880288287 + }, + "columns": 80, + "command": "/usr/bin/make", + "lines": 24, + "runargv": [ + "make", + "test" + ], + "runenv": [ + "LANG=en_US.UTF-8", + "PATH=/bin:/sbin:/usr/games:/usr/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin", + "TERM=vt100", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/ksh", + "SUDO_COMMAND=/usr/bin/make test", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20", + "A__z=\"*SHLVL" + ], + "runuid": 0, + "runuser": "root", + "submitcwd": "/home/test", + "submithost": "sudo.ws", + "submituser": "millert", + "ttyname": "/dev/console" +} diff --git a/lib/eventlog/regress/parse_json/test2.in b/lib/eventlog/regress/parse_json/test2.in new file mode 100644 index 0000000..df7170f --- /dev/null +++ b/lib/eventlog/regress/parse_json/test2.in @@ -0,0 +1,28 @@ +{ + "timestamp": { "seconds": 1584993067, "nanoseconds": 880288287 }, + "columns": 80, + "command": "/usr/bin/make", + "lines": 24, + "runargv": [ "make", "test" ], + "runenv": [ + "LANG=en_US.UTF-8", + "PATH=/bin:/sbin:/usr/games:/usr/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin", + "TERM=vt100", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/ksh", + "SUDO_COMMAND=/usr/bin/make test", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20", + "A__z=\"*SHLVL" + ], + "runuid": 0, + "runuser": "root", + "submitcwd": "/home/test", + "submithost": "sudo.ws", + "submituser": "millert", + "ttyname": "/dev/console" +} diff --git a/lib/eventlog/regress/parse_json/test2.out.ok b/lib/eventlog/regress/parse_json/test2.out.ok new file mode 100644 index 0000000..8ad3689 --- /dev/null +++ b/lib/eventlog/regress/parse_json/test2.out.ok @@ -0,0 +1,34 @@ +{ + "timestamp": { + "seconds": 1584993067, + "nanoseconds": 880288287 + }, + "columns": 80, + "command": "/usr/bin/make", + "lines": 24, + "runargv": [ + "make", + "test" + ], + "runenv": [ + "LANG=en_US.UTF-8", + "PATH=/bin:/sbin:/usr/games:/usr/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin", + "TERM=vt100", + "MAIL=/var/mail/root", + "LOGNAME=root", + "USER=root", + "HOME=/root", + "SHELL=/bin/ksh", + "SUDO_COMMAND=/usr/bin/make test", + "SUDO_USER=millert", + "SUDO_UID=8036", + "SUDO_GID=20", + "A__z=\"*SHLVL" + ], + "runuid": 0, + "runuser": "root", + "submitcwd": "/home/test", + "submithost": "sudo.ws", + "submituser": "millert", + "ttyname": "/dev/console" +} diff --git a/lib/eventlog/regress/parse_json/test3.in b/lib/eventlog/regress/parse_json/test3.in new file mode 100644 index 0000000..6f243e3 --- /dev/null +++ b/lib/eventlog/regress/parse_json/test3.in @@ -0,0 +1,22 @@ +{ + "true": false, + "false": true, + "number": 1234567890, + "null": null, + "string": "non\u0073ense", + "scope": { + "a": "b", + "bah": null + }, + "array1": [ + "foo", + "bar", + [ + 123, + null, + false, + "fizz", + "buzz" + ] + ] +} diff --git a/lib/eventlog/regress/parse_json/test3.out.ok b/lib/eventlog/regress/parse_json/test3.out.ok new file mode 100644 index 0000000..ea2df89 --- /dev/null +++ b/lib/eventlog/regress/parse_json/test3.out.ok @@ -0,0 +1,22 @@ +{ + "true": false, + "false": true, + "number": 1234567890, + "null": null, + "string": "nonsense", + "scope": { + "a": "b", + "bah": null + }, + "array1": [ + "foo", + "bar", + [ + 123, + null, + false, + "fizz", + "buzz" + ] + ] +} |