/*1* SPDX-License-Identifier: ISC2*3* Copyright (c) 2009-2021 Todd C. Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <config.h>1920#include <sys/stat.h>21#include <stdio.h>22#include <stdlib.h>23#ifdef HAVE_STDBOOL_H24# include <stdbool.h>25#else26# include <compat/stdbool.h>27#endif28#include <errno.h>29#include <fcntl.h>30#include <unistd.h>3132#include <sudo_compat.h>33#include <sudo_debug.h>34#include <sudo_fatal.h>35#include <sudo_gettext.h>36#include <sudo_iolog.h>37#include <sudo_util.h>3839/*40* Wrapper for openat(2) that sets umask and retries as iolog_uid/iolog_gid41* if openat(2) returns EACCES.42*/43int44iolog_openat(int dfd, const char *path, int flags)45{46const mode_t iolog_filemode = iolog_get_file_mode();47const mode_t iolog_dirmode = iolog_get_dir_mode();48mode_t omask = S_IRWXG|S_IRWXO;49int fd;50debug_decl(iolog_openat, SUDO_DEBUG_UTIL);5152if (ISSET(flags, O_CREAT)) {53/* umask must not be more restrictive than the file modes. */54omask = umask(ACCESSPERMS & ~(iolog_filemode|iolog_dirmode));55}56fd = openat(dfd, path, flags, iolog_filemode);57if (fd == -1 && errno == EACCES) {58/* Enable write bit if it is missing. */59struct stat sb;60if (fstatat(dfd, path, &sb, 0) == 0) {61mode_t write_bits = iolog_filemode & (S_IWUSR|S_IWGRP|S_IWOTH);62if ((sb.st_mode & write_bits) != write_bits) {63if (fchmodat(dfd, path, iolog_filemode, 0) == 0)64fd = openat(dfd, path, flags, iolog_filemode);65}66}67}68if (fd == -1 && errno == EACCES) {69/* Try again as the I/O log owner (for NFS). */70if (iolog_swapids(false)) {71fd = openat(dfd, path, flags, iolog_filemode);72if (!iolog_swapids(true)) {73/* iolog_swapids() warns on error. */74if (fd != -1) {75close(fd);76fd = -1;77}78}79}80}81if (ISSET(flags, O_CREAT))82umask(omask);83debug_return_int(fd);84}858687