OpenVPN
platform.c
Go to the documentation of this file.
1 /*
2  * OpenVPN -- An application to securely tunnel IP networks
3  * over a single TCP/UDP port, with support for SSL/TLS-based
4  * session authentication and key exchange,
5  * packet encryption, packet authentication, and
6  * packet compression.
7  *
8  * Copyright (C) 2002-2021 OpenVPN Inc <sales@openvpn.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2
12  * as published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #include "syshead.h"
31 
32 #include "buffer.h"
33 #include "crypto.h"
34 #include "error.h"
35 #include "misc.h"
36 #include "win32.h"
37 
38 #include "memdbg.h"
39 
40 #include "platform.h"
41 
42 #if _WIN32
43 #include <direct.h>
44 #endif
45 
46 /* Redefine the top level directory of the filesystem
47  * to restrict access to files for security */
48 void
49 platform_chroot(const char *path)
50 {
51  if (path)
52  {
53 #ifdef HAVE_CHROOT
54  const char *top = "/";
55  if (chroot(path))
56  {
57  msg(M_ERR, "chroot to '%s' failed", path);
58  }
59  if (platform_chdir(top))
60  {
61  msg(M_ERR, "cd to '%s' failed", top);
62  }
63  msg(M_INFO, "chroot to '%s' and cd to '%s' succeeded", path, top);
64 #else /* ifdef HAVE_CHROOT */
65  msg(M_FATAL, "Sorry but I can't chroot to '%s' because this operating system doesn't appear to support the chroot() system call", path);
66 #endif
67  }
68 }
69 
70 /* Get/Set UID of process */
71 
72 bool
73 platform_user_get(const char *username, struct platform_state_user *state)
74 {
75  bool ret = false;
76  CLEAR(*state);
77  if (username)
78  {
79 #if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID)
80  state->pw = getpwnam(username);
81  if (!state->pw)
82  {
83  msg(M_ERR, "failed to find UID for user %s", username);
84  }
85  state->username = username;
86  ret = true;
87 #else /* if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID) */
88  msg(M_FATAL, "cannot get UID for user %s -- platform lacks getpwname() or setuid() system calls", username);
89 #endif
90  }
91  return ret;
92 }
93 
94 void
96 {
97 #if defined(HAVE_GETPWNAM) && defined(HAVE_SETUID)
98  if (state->username && state->pw)
99  {
100  if (setuid(state->pw->pw_uid))
101  {
102  msg(M_ERR, "setuid('%s') failed", state->username);
103  }
104  msg(M_INFO, "UID set to %s", state->username);
105  }
106 #endif
107 }
108 
109 /* Get/Set GID of process */
110 
111 bool
112 platform_group_get(const char *groupname, struct platform_state_group *state)
113 {
114  bool ret = false;
115  CLEAR(*state);
116  if (groupname)
117  {
118 #if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID)
119  state->gr = getgrnam(groupname);
120  if (!state->gr)
121  {
122  msg(M_ERR, "failed to find GID for group %s", groupname);
123  }
124  state->groupname = groupname;
125  ret = true;
126 #else /* if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID) */
127  msg(M_FATAL, "cannot get GID for group %s -- platform lacks getgrnam() or setgid() system calls", groupname);
128 #endif
129  }
130  return ret;
131 }
132 
133 void
135 {
136 #if defined(HAVE_GETGRNAM) && defined(HAVE_SETGID)
137  if (state->groupname && state->gr)
138  {
139  if (setgid(state->gr->gr_gid))
140  {
141  msg(M_ERR, "setgid('%s') failed", state->groupname);
142  }
143  msg(M_INFO, "GID set to %s", state->groupname);
144 #ifdef HAVE_SETGROUPS
145  {
146  gid_t gr_list[1];
147  gr_list[0] = state->gr->gr_gid;
148  if (setgroups(1, gr_list))
149  {
150  msg(M_ERR, "setgroups('%s') failed", state->groupname);
151  }
152  }
153 #endif
154  }
155 #endif
156 }
157 
158 /* Change process priority */
159 void
160 platform_nice(int niceval)
161 {
162  if (niceval)
163  {
164 #ifdef HAVE_NICE
165  errno = 0;
166  if (nice(niceval) < 0 && errno != 0)
167  {
168  msg(M_WARN | M_ERRNO, "WARNING: nice %d failed", niceval);
169  }
170  else
171  {
172  msg(M_INFO, "nice %d succeeded", niceval);
173  }
174 #else /* ifdef HAVE_NICE */
175  msg(M_WARN, "WARNING: nice %d failed (function not implemented)", niceval);
176 #endif
177  }
178 }
179 
180 /* Get current PID */
181 unsigned int
183 {
184 #ifdef _WIN32
185  return (unsigned int) GetCurrentProcessId();
186 #else
187  return (unsigned int) getpid();
188 #endif
189 }
190 
191 /* Disable paging */
192 void
193 platform_mlockall(bool print_msg)
194 {
195 #ifdef HAVE_MLOCKALL
196 
197 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_MEMLOCK)
198 #define MIN_LOCKED_MEM_MB 100
199  struct rlimit rl;
200  if (getrlimit(RLIMIT_MEMLOCK, &rl) < 0)
201  {
202  msg(M_WARN | M_ERRNO, "WARNING: getrlimit(RLIMIT_MEMLOCK) failed");
203  }
204  else
205  {
206  msg(M_INFO, "mlock: MEMLOCK limit: soft=%ld KB, hard=%ld KB",
207  ((long int) rl.rlim_cur) / 1024, ((long int) rl.rlim_max) / 1024);
208  if (rl.rlim_cur < MIN_LOCKED_MEM_MB*1024*1024)
209  {
210  msg(M_INFO, "mlock: RLIMIT_MEMLOCK < %d MB, increase limit",
211  MIN_LOCKED_MEM_MB);
212  rl.rlim_cur = MIN_LOCKED_MEM_MB*1024*1024;
213  if (rl.rlim_max < rl.rlim_cur)
214  {
215  rl.rlim_max = rl.rlim_cur;
216  }
217  if (setrlimit(RLIMIT_MEMLOCK, &rl) < 0)
218  {
219  msg(M_FATAL | M_ERRNO, "ERROR: setrlimit() failed");
220  }
221  }
222  }
223 #endif
224 
225  if (mlockall(MCL_CURRENT | MCL_FUTURE))
226  {
227  msg(M_WARN | M_ERRNO, "WARNING: mlockall call failed");
228  }
229  else if (print_msg)
230  {
231  msg(M_INFO, "mlockall call succeeded");
232  }
233 #else /* ifdef HAVE_MLOCKALL */
234  msg(M_WARN, "WARNING: mlockall call failed (function not implemented)");
235 #endif
236 }
237 
238 /*
239  * Wrapper for chdir library function
240  */
241 int
242 platform_chdir(const char *dir)
243 {
244 #ifdef HAVE_CHDIR
245 #ifdef _WIN32
246  int res;
247  struct gc_arena gc = gc_new();
248  res = _wchdir(wide_string(dir, &gc));
249  gc_free(&gc);
250  return res;
251 #else /* ifdef _WIN32 */
252  return chdir(dir);
253 #endif
254 #else /* ifdef HAVE_CHDIR */
255  return -1;
256 #endif
257 }
258 
259 /*
260  * convert execve() return into a success/failure value
261  */
262 bool
264 {
265 #ifdef _WIN32
266  return stat == 0;
267 #else
268  return stat != -1 && WIFEXITED(stat) && WEXITSTATUS(stat) == 0;
269 #endif
270 }
271 
272 #ifdef _WIN32
273 int
275 {
276  if (stat >= 0 && stat < 255)
277  {
278  return stat;
279  }
280  else
281  {
282  return -1;
283  }
284 }
285 #else
286 int
287 platform_ret_code(int stat)
288 {
289  if (!WIFEXITED(stat) || stat == -1)
290  {
291  return -1;
292  }
293 
294  int status = WEXITSTATUS(stat);
295  if (status >= 0 && status < 255)
296  {
297  return status;
298  }
299  else
300  {
301  return -1;
302  }
303 }
304 #endif
305 
306 int
307 platform_access(const char *path, int mode)
308 {
309 #ifdef _WIN32
310  struct gc_arena gc = gc_new();
311  int ret = _waccess(wide_string(path, &gc), mode & ~X_OK);
312  gc_free(&gc);
313  return ret;
314 #else
315  return access(path, mode);
316 #endif
317 }
318 
319 /*
320  * Go to sleep for n milliseconds.
321  */
322 void
324 {
325 #ifdef _WIN32
326  Sleep(n);
327 #else
328  struct timeval tv;
329  tv.tv_sec = n / 1000;
330  tv.tv_usec = (n % 1000) * 1000;
331  select(0, NULL, NULL, NULL, &tv);
332 #endif
333 }
334 
335 /*
336  * Go to sleep indefinitely.
337  */
338 void
340 {
341 #ifdef _WIN32
342  ASSERT(0);
343 #else
344  select(0, NULL, NULL, NULL, NULL);
345 #endif
346 }
347 
348 /* delete a file, return true if succeeded */
349 bool
350 platform_unlink(const char *filename)
351 {
352 #if defined(_WIN32)
353  struct gc_arena gc = gc_new();
354  BOOL ret = DeleteFileW(wide_string(filename, &gc));
355  gc_free(&gc);
356  return (ret != 0);
357 #else
358  return (unlink(filename) == 0);
359 #endif
360 }
361 
362 FILE *
363 platform_fopen(const char *path, const char *mode)
364 {
365 #ifdef _WIN32
366  struct gc_arena gc = gc_new();
367  FILE *f = _wfopen(wide_string(path, &gc), wide_string(mode, &gc));
368  gc_free(&gc);
369  return f;
370 #else
371  return fopen(path, mode);
372 #endif
373 }
374 
375 int
376 platform_open(const char *path, int flags, int mode)
377 {
378 #ifdef _WIN32
379  struct gc_arena gc = gc_new();
380  int fd = _wopen(wide_string(path, &gc), flags, mode);
381  gc_free(&gc);
382  return fd;
383 #else
384  return open(path, flags, mode);
385 #endif
386 }
387 
388 int
389 platform_stat(const char *path, platform_stat_t *buf)
390 {
391 #ifdef _WIN32
392  struct gc_arena gc = gc_new();
393  int res = _wstat(wide_string(path, &gc), buf);
394  gc_free(&gc);
395  return res;
396 #else
397  return stat(path, buf);
398 #endif
399 }
400 
401 /* create a temporary filename in directory */
402 const char *
403 platform_create_temp_file(const char *directory, const char *prefix, struct gc_arena *gc)
404 {
405  int fd;
406  const char *retfname = NULL;
407  unsigned int attempts = 0;
408  char fname[256] = { 0 };
409  const char *fname_fmt = PACKAGE "_%.*s_%08lx%08lx.tmp";
410  const int max_prefix_len = sizeof(fname) - (sizeof(PACKAGE) + 7 + (2 * 8));
411 
412  while (attempts < 6)
413  {
414  ++attempts;
415 
416  if (!openvpn_snprintf(fname, sizeof(fname), fname_fmt, max_prefix_len,
417  prefix, (unsigned long) get_random(),
418  (unsigned long) get_random()))
419  {
420  msg(M_WARN, "ERROR: temporary filename too long");
421  return NULL;
422  }
423 
424  retfname = platform_gen_path(directory, fname, gc);
425  if (!retfname)
426  {
427  msg(M_WARN, "Failed to create temporary filename and path");
428  return NULL;
429  }
430 
431  /* Atomically create the file. Errors out if the file already
432  * exists. */
433  fd = platform_open(retfname, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR);
434  if (fd != -1)
435  {
436  close(fd);
437  return retfname;
438  }
439  else if (fd == -1 && errno != EEXIST)
440  {
441  /* Something else went wrong, no need to retry. */
442  msg(M_WARN | M_ERRNO, "Could not create temporary file '%s'",
443  retfname);
444  return NULL;
445  }
446  }
447 
448  msg(M_WARN, "Failed to create temporary file after %i attempts", attempts);
449  return NULL;
450 }
451 
452 /*
453  * Put a directory and filename together.
454  */
455 const char *
456 platform_gen_path(const char *directory, const char *filename,
457  struct gc_arena *gc)
458 {
459 #ifdef _WIN32
460  const int CC_PATH_RESERVED = CC_LESS_THAN|CC_GREATER_THAN|CC_COLON
462 #else
463  const int CC_PATH_RESERVED = CC_SLASH;
464 #endif
465 
466  if (!gc)
467  {
468  return NULL; /* Would leak memory otherwise */
469  }
470 
471  const char *safe_filename = string_mod_const(filename, CC_PRINT, CC_PATH_RESERVED, '_', gc);
472 
473  if (safe_filename
474  && strcmp(safe_filename, ".")
475  && strcmp(safe_filename, "..")
476 #ifdef _WIN32
477  && win_safe_filename(safe_filename)
478 #endif
479  )
480  {
481  const size_t outsize = strlen(safe_filename) + (directory ? strlen(directory) : 0) + 16;
482  struct buffer out = alloc_buf_gc(outsize, gc);
483  char dirsep[2];
484 
485  dirsep[0] = PATH_SEPARATOR;
486  dirsep[1] = '\0';
487 
488  if (directory)
489  {
490  buf_printf(&out, "%s%s", directory, dirsep);
491  }
492  buf_printf(&out, "%s", safe_filename);
493 
494  return BSTR(&out);
495  }
496  else
497  {
498  return NULL;
499  }
500 }
501 
502 bool
503 platform_absolute_pathname(const char *pathname)
504 {
505  if (pathname)
506  {
507  const int c = pathname[0];
508 #ifdef _WIN32
509  return c == '\\' || (isalpha(c) && pathname[1] == ':' && pathname[2] == '\\');
510 #else
511  return c == '/';
512 #endif
513  }
514  else
515  {
516  return false;
517  }
518 }
519 
520 /* return true if filename can be opened for read */
521 bool
522 platform_test_file(const char *filename)
523 {
524  bool ret = false;
525  if (filename)
526  {
527  FILE *fp = platform_fopen(filename, "r");
528  if (fp)
529  {
530  fclose(fp);
531  ret = true;
532  }
533  else
534  {
535  if (openvpn_errno() == EACCES)
536  {
537  msg( M_WARN | M_ERRNO, "Could not access file '%s'", filename);
538  }
539  }
540  }
541 
542  dmsg(D_TEST_FILE, "TEST FILE '%s' [%d]",
543  filename ? filename : "UNDEF",
544  ret);
545 
546  return ret;
547 }
unsigned int platform_getpid(void)
Definition: platform.c:182
void platform_group_set(const struct platform_state_group *state)
Definition: platform.c:134
bool platform_group_get(const char *groupname, struct platform_state_group *state)
Definition: platform.c:112
void platform_nice(int niceval)
Definition: platform.c:160
#define D_TEST_FILE
Definition: errlevel.h:133
#define openvpn_errno()
Definition: error.h:78
#define M_INFO
Definition: errlevel.h:55
void platform_sleep_until_signal(void)
Definition: platform.c:339
#define CC_LESS_THAN
Definition: buffer.h:936
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1023
bool platform_user_get(const char *username, struct platform_state_user *state)
Definition: platform.c:73
#define CC_PRINT
Definition: buffer.h:915
bool buf_printf(struct buffer *buf, const char *format,...)
Definition: buffer.c:242
#define dmsg(flags,...)
Definition: error.h:157
WCHAR * wide_string(const char *utf8, struct gc_arena *gc)
Definition: win32-util.c:43
#define X_OK
Definition: config-msvc.h:110
#define ASSERT(x)
Definition: error.h:204
#define CC_BACKSLASH
Definition: buffer.h:924
void platform_user_set(const struct platform_state_user *state)
Definition: platform.c:95
bool platform_unlink(const char *filename)
Definition: platform.c:350
#define S_IWUSR
Definition: config-msvc.h:107
void platform_mlockall(bool print_msg)
Definition: platform.c:193
list flags
bool platform_system_ok(int stat)
interpret the status code returned by execve()
Definition: platform.c:263
FILE * platform_fopen(const char *path, const char *mode)
Definition: platform.c:363
#define CLEAR(x)
Definition: basic.h:33
int platform_ret_code(int stat)
Return an exit code if valid and between 0 and 255, -1 otherwise.
Definition: platform.c:274
bool openvpn_snprintf(char *str, size_t size, const char *format,...)
Definition: buffer.c:296
#define PATH_SEPARATOR
Definition: config.h:745
#define CC_ASTERISK
Definition: buffer.h:940
int platform_open(const char *path, int flags, int mode)
Definition: platform.c:376
void platform_sleep_milliseconds(unsigned int n)
Definition: platform.c:323
string f
Definition: http-client.py:6
static struct gc_arena gc_new(void)
Definition: buffer.h:1015
bool platform_test_file(const char *filename)
Return true if filename can be opened for read.
Definition: platform.c:522
#define S_IRUSR
Definition: config-msvc.h:106
const char * platform_gen_path(const char *directory, const char *filename, struct gc_arena *gc)
Put a directory and filename together.
Definition: platform.c:456
bool win_safe_filename(const char *fn)
Definition: win32-util.c:105
#define M_ERRNO
Definition: error.h:103
int platform_stat(const char *path, platform_stat_t *buf)
Definition: platform.c:389
#define CC_QUESTION_MARK
Definition: buffer.h:939
const char * string_mod_const(const char *str, const unsigned int inclusive, const unsigned int exclusive, const char replace, struct gc_arena *gc)
Definition: buffer.c:1109
#define msg(flags,...)
Definition: error.h:153
#define M_ERR
Definition: error.h:114
#define CC_GREATER_THAN
Definition: buffer.h:937
#define CC_SLASH
Definition: buffer.h:930
#define CC_PIPE
Definition: buffer.h:938
int platform_chdir(const char *dir)
Definition: platform.c:242
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
#define M_FATAL
Definition: error.h:98
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition: buffer.c:90
#define M_WARN
Definition: error.h:100
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
const char * platform_create_temp_file(const char *directory, const char *prefix, struct gc_arena *gc)
Create a temporary file in directory, returns the filename of the created file.
Definition: platform.c:403
#define BSTR(buf)
Definition: buffer.h:129
#define PACKAGE
Definition: config.h:724
long int get_random(void)
Definition: crypto.c:1775
void platform_chroot(const char *path)
Definition: platform.c:49
#define CC_COLON
Definition: buffer.h:929
static SERVICE_STATUS status
Definition: interactive.c:56
bool platform_absolute_pathname(const char *pathname)
Return true if pathname is absolute.
Definition: platform.c:503
struct _stat platform_stat_t
Definition: platform.h:148
#define CC_DOUBLE_QUOTE
Definition: buffer.h:932
int platform_access(const char *path, int mode)
Definition: platform.c:307