OpenVPN 3 Core Library
Loading...
Searching...
No Matches
peercred.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#ifndef OPENVPN_COMMON_PEERCRED_H
13#define OPENVPN_COMMON_PEERCRED_H
14
15#include <unistd.h>
16#include <sys/types.h>
17#include <sys/socket.h>
18
21
22#if defined(__APPLE__) || defined(__FreeBSD__)
23#include <sys/ucred.h>
24#endif
25
27
28struct Creds
29{
30 Creds(const int uid_arg = -1, const int gid_arg = -1, const int pid_arg = -1)
31 : uid(uid_arg),
32 gid(gid_arg),
33 pid(pid_arg)
34 {
35 }
36
37 bool root_or_self_uid() const
38 {
39 return !uid || uid == ::getuid();
40 }
41
42 bool root_uid() const
43 {
44 return !uid;
45 }
46
47 bool match_uid(const uid_t other_uid) const
48 {
49 return uid >= 0 && uid == other_uid;
50 }
51
52 uid_t uid;
53 uid_t gid;
54 pid_t pid;
55};
56
57// get credentials of process on other side of unix socket
58inline bool peercreds(const int fd, Creds &cr)
59{
60#if defined(__APPLE__) || defined(__FreeBSD__)
61 xucred cred;
62 socklen_t credLen = sizeof(cred);
63 if (::getsockopt(fd, SOL_LOCAL, LOCAL_PEERCRED, &cred, &credLen) != 0)
64 return false;
65 cr = Creds(cred.cr_uid, cred.cr_gid);
66 return true;
67#elif defined(OPENVPN_PLATFORM_LINUX)
68 struct ucred uc;
69 socklen_t uc_len = sizeof(uc);
70 if (::getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &uc, &uc_len) != 0)
71 return false;
72 cr = Creds(uc.uid, uc.gid, uc.pid);
73 return true;
74#else
75#error no implementation for peercreds()
76#endif
77}
78
79} // namespace openvpn::SockOpt
80
81#endif
bool peercreds(const int fd, Creds &cr)
Definition peercred.hpp:58
bool root_or_self_uid() const
Definition peercred.hpp:37
Creds(const int uid_arg=-1, const int gid_arg=-1, const int pid_arg=-1)
Definition peercred.hpp:30
bool root_uid() const
Definition peercred.hpp:42
bool match_uid(const uid_t other_uid) const
Definition peercred.hpp:47