Skip to content

Commit a2f589b

Browse files
committed
Make use of realpath() safer
1 parent 7622cba commit a2f589b

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

linux-launcher.c

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@
2424
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
2525
#define MAX_ARGC 1024
2626

27+
static inline bool
28+
safe_realpath(const char* src, char *buf, size_t buf_sz) {
29+
char* ans = realpath(src, NULL);
30+
if (ans == NULL) return false;
31+
snprintf(buf, buf_sz, "%s", ans);
32+
free(ans);
33+
return true;
34+
}
35+
36+
2737
#ifdef FOR_BUNDLE
2838
static int run_embedded(const char* exe_dir_, int argc, wchar_t **argv) {
2939
int num;
@@ -80,6 +90,7 @@ static int run_embedded(const char* exe_dir_, int argc, wchar_t **argv) {
8090

8191
#else
8292
static int run_embedded(const char* exe_dir, int argc, wchar_t **argv) {
93+
(void)exe_dir;
8394
return Py_Main(argc, argv);
8495
}
8596

@@ -92,7 +103,7 @@ read_exe_path(char *exe, size_t buf_sz) {
92103
uint32_t size = PATH_MAX;
93104
char apple[PATH_MAX+1] = {0};
94105
if (_NSGetExecutablePath(apple, &size) != 0) { fprintf(stderr, "Failed to get path to executable\n"); return false; }
95-
if (realpath(apple, exe) == NULL) { fprintf(stderr, "realpath() failed on the executable's path\n"); return false; }
106+
if (!safe_realpath(apple, exe, buf_sz)) { fprintf(stderr, "realpath() failed on the executable's path\n"); return false; }
96107
return true;
97108
}
98109
#elif defined(__FreeBSD__)
@@ -114,15 +125,15 @@ read_exe_path(char *exe, size_t buf_sz) {
114125

115126
static inline bool
116127
read_exe_path(char *exe, size_t buf_sz) {
117-
if (realpath("/proc/curproc/exe", exe) == NULL) { fprintf(stderr, "Failed to read /proc/self/exe\n"); return false; }
128+
if (!safe_realpath("/proc/curproc/exe", exe, buf_sz)) { fprintf(stderr, "Failed to read /proc/self/exe\n"); return false; }
118129
return true;
119130
}
120131

121132
#else
122133

123134
static inline bool
124135
read_exe_path(char *exe, size_t buf_sz) {
125-
if (realpath("/proc/self/exe", exe) == NULL) { fprintf(stderr, "Failed to read /proc/self/exe\n"); return false; }
136+
if (!safe_realpath("/proc/self/exe", exe, buf_sz)) { fprintf(stderr, "Failed to read /proc/self/exe\n"); return false; }
126137
return true;
127138
}
128139
#endif

0 commit comments

Comments
 (0)