Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/iolog/iolog_openat.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2009-2021 Todd C. Miller <[email protected]>
5
*
6
* Permission to use, copy, modify, and distribute this software for any
7
* purpose with or without fee is hereby granted, provided that the above
8
* copyright notice and this permission notice appear in all copies.
9
*
10
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
*/
18
19
#include <config.h>
20
21
#include <sys/stat.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#ifdef HAVE_STDBOOL_H
25
# include <stdbool.h>
26
#else
27
# include <compat/stdbool.h>
28
#endif
29
#include <errno.h>
30
#include <fcntl.h>
31
#include <unistd.h>
32
33
#include <sudo_compat.h>
34
#include <sudo_debug.h>
35
#include <sudo_fatal.h>
36
#include <sudo_gettext.h>
37
#include <sudo_iolog.h>
38
#include <sudo_util.h>
39
40
/*
41
* Wrapper for openat(2) that sets umask and retries as iolog_uid/iolog_gid
42
* if openat(2) returns EACCES.
43
*/
44
int
45
iolog_openat(int dfd, const char *path, int flags)
46
{
47
const mode_t iolog_filemode = iolog_get_file_mode();
48
const mode_t iolog_dirmode = iolog_get_dir_mode();
49
mode_t omask = S_IRWXG|S_IRWXO;
50
int fd;
51
debug_decl(iolog_openat, SUDO_DEBUG_UTIL);
52
53
if (ISSET(flags, O_CREAT)) {
54
/* umask must not be more restrictive than the file modes. */
55
omask = umask(ACCESSPERMS & ~(iolog_filemode|iolog_dirmode));
56
}
57
fd = openat(dfd, path, flags, iolog_filemode);
58
if (fd == -1 && errno == EACCES) {
59
/* Enable write bit if it is missing. */
60
struct stat sb;
61
if (fstatat(dfd, path, &sb, 0) == 0) {
62
mode_t write_bits = iolog_filemode & (S_IWUSR|S_IWGRP|S_IWOTH);
63
if ((sb.st_mode & write_bits) != write_bits) {
64
if (fchmodat(dfd, path, iolog_filemode, 0) == 0)
65
fd = openat(dfd, path, flags, iolog_filemode);
66
}
67
}
68
}
69
if (fd == -1 && errno == EACCES) {
70
/* Try again as the I/O log owner (for NFS). */
71
if (iolog_swapids(false)) {
72
fd = openat(dfd, path, flags, iolog_filemode);
73
if (!iolog_swapids(true)) {
74
/* iolog_swapids() warns on error. */
75
if (fd != -1) {
76
close(fd);
77
fd = -1;
78
}
79
}
80
}
81
}
82
if (ISSET(flags, O_CREAT))
83
umask(omask);
84
debug_return_int(fd);
85
}
86
87