unix-socket: disallow chdir() when creating unix domain sockets
Calls to `chdir()` are dangerous in a multi-threaded context. If `unix_stream_listen()` or `unix_stream_connect()` is given a socket pathname that is too long to fit in a `sockaddr_un` structure, it will `chdir()` to the parent directory of the requested socket pathname, create the socket using a relative pathname, and then `chdir()` back. This is not thread-safe. Teach `unix_sockaddr_init()` to not allow calls to `chdir()` when this flag is set. Signed-off-by: Jeff Hostetler <jeffhost@microsoft.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Jeff Hostetler committed
Mar 15, 2021 at 21:08 UTC
77e522caaeebe8c6378dcf7045b19cbd22c8b2fb
3 files changed
+15
-7
builtin/credential-cache.c
+1
-1
@@ -14,7 +14,7 @@
14
static int send_request(const char *socket, const struct strbuf *out)
15
{
16
int got_data = 0;
17
- int fd = unix_stream_connect(socket);
17
+ int fd = unix_stream_connect(socket, 0);
18
19
if (fd < 0)
20
return -1;
unix-socket.c
+12
-5
@@ -30,16 +30,23 @@ static void unix_sockaddr_cleanup(struct unix_sockaddr_context *ctx)
30
}
31
32
static int unix_sockaddr_init(struct sockaddr_un *sa, const char *path,
33
- struct unix_sockaddr_context *ctx)
33
+ struct unix_sockaddr_context *ctx,
34
+ int disallow_chdir)
35
{
36
int size = strlen(path) + 1;
37
38
ctx->orig_dir = NULL;
39
if (size > sizeof(sa->sun_path)) {
39
- const char *slash = find_last_dir_sep(path);
40
+ const char *slash;
41
const char *dir;
42
struct strbuf cwd = STRBUF_INIT;
43
44
+ if (disallow_chdir) {
45
+ errno = ENAMETOOLONG;
46
+ return -1;
47
+ }
48
+
49
+ slash = find_last_dir_sep(path);
50
if (!slash) {
51
errno = ENAMETOOLONG;
52
return -1;
@@ -65,13 +72,13 @@ static int unix_sockaddr_init(struct sockaddr_un *sa, const char *path,
72
return 0;
73
}
74
68
-int unix_stream_connect(const char *path)
75
+int unix_stream_connect(const char *path, int disallow_chdir)
76
{
77
int fd = -1, saved_errno;
78
struct sockaddr_un sa;
79
struct unix_sockaddr_context ctx;
80
74
- if (unix_sockaddr_init(&sa, path, &ctx) < 0)
81
+ if (unix_sockaddr_init(&sa, path, &ctx, disallow_chdir) < 0)
82
return -1;
83
fd = socket(AF_UNIX, SOCK_STREAM, 0);
84
if (fd < 0)
@@ -101,7 +108,7 @@ int unix_stream_listen(const char *path,
108
109
unlink(path);
110
104
- if (unix_sockaddr_init(&sa, path, &ctx) < 0)
111
+ if (unix_sockaddr_init(&sa, path, &ctx, opts->disallow_chdir) < 0)
112
return -1;
113
fd = socket(AF_UNIX, SOCK_STREAM, 0);
114
if (fd < 0)
unix-socket.h
+2
-1
@@ -3,11 +3,12 @@
3
4
struct unix_stream_listen_opts {
5
int listen_backlog_size;
6
+ unsigned int disallow_chdir:1;
7
};
8
9
#define UNIX_STREAM_LISTEN_OPTS_INIT { 0 }
10
10
-int unix_stream_connect(const char *path);
11
+int unix_stream_connect(const char *path, int disallow_chdir);
12
int unix_stream_listen(const char *path,
13
const struct unix_stream_listen_opts *opts);
14