summaryrefslogtreecommitdiff
path: root/open-vm-tools/lib/file/fileTempPosix.c
blob: e5e8921919a9339d4d63c83493f378f3ad3b2e3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*********************************************************
 * Copyright (C) 2004-2011 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

#include <string.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <ctype.h>

#if !defined(__FreeBSD__) && !defined(sun)
#   include <pwd.h>
#endif

#if defined(sun)
#   include <procfs.h>
#endif

#include "vmware.h"
#include "file.h"
#include "fileInt.h"
#include "util.h"
#include "su.h"
#include "vm_atomic.h"
#include "str.h"
#include "vm_product.h"
#include "random.h"
#include "userlock.h"
#include "unicodeOperations.h"
#include "err.h"
#include "posix.h"
#include "mutexRankLib.h"
#include "hostType.h"
#include "localconfig.h"

#define LOGLEVEL_MODULE util
#include "loglevel_user.h"


/*
 *----------------------------------------------------------------------
 *
 * FileTryDir --
 *
 *	Check to see if the given directory is actually a directory
 *      and is writable by us.
 *
 * Results:
 *	The expanded directory name on success, NULL on failure.
 *
 * Side effects:
 *	The result is allocated.
 *
 *----------------------------------------------------------------------
 */

static char *
FileTryDir(const char *dirName)  // IN: Is this a writable directory?
{
   char *edirName;

   if (dirName != NULL) {
      edirName = Util_ExpandString(dirName);

      if ((edirName != NULL) && FileIsWritableDir(edirName)) {
         return edirName;
      }

      free(edirName);
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------
 *
 * FileGetTmpDir --
 *
 *	Determine the best temporary directory. Unsafe since the
 *	returned directory is generally going to be 0777, thus all sorts
 *	of denial of service or symlink attacks are possible.
 *
 * Results:
 *	NULL if error (reported to the user).
 *
 * Side effects:
 *	The result is allocated.
 *
 *----------------------------------------------------------------------
 */

static char *
FileGetTmpDir(Bool useConf)  // IN: Use the config file?
{
   char *dirName;
   char *edirName;

   /* Make several attempts to find a good temporary directory candidate */

   if (useConf) {
      dirName = (char *)LocalConfig_GetString(NULL, "tmpDirectory");
      edirName = FileTryDir(dirName);
      free(dirName);
      if (edirName != NULL) {
         return edirName;
      }
   }

   /* Posix_Getenv string must _not_ be freed */
   edirName = FileTryDir(Posix_Getenv("TMPDIR"));
   if (edirName != NULL) {
      return edirName;
   }

   /* P_tmpdir is usually defined in <stdio.h> */
   edirName = FileTryDir(P_tmpdir);
   if (edirName != NULL) {
      return edirName;
   }

   edirName = FileTryDir("/tmp");
   if (edirName != NULL) {
      return edirName;
   }

   edirName = FileTryDir("~");
   if (edirName != NULL) {
      return edirName;
   }

   dirName = File_Cwd(NULL);

   if (dirName != NULL) {
      edirName = FileTryDir(dirName);
      free(dirName);
      if (edirName != NULL) {
         return edirName;
      }
   }

   edirName = FileTryDir("/");
   if (edirName != NULL) {
      return edirName;
   }

   Warning("%s: Couldn't get a temporary directory\n", __FUNCTION__);
   return NULL;
}

#undef HOSTINFO_TRYDIR


#if !defined(__FreeBSD__) && !defined(sun)
/*
 *-----------------------------------------------------------------------------
 *
 * FileGetUserName --
 *
 *      Retrieve the name associated with a user ID. Thread-safe
 *      version. --hpreg
 *
 * Results:
 *      The allocated name on success
 *      NULL on failure
 *
 * Side effects:
 *      None
 *
 *-----------------------------------------------------------------------------
 */

static char *
FileGetUserName(uid_t uid)  // IN:
{
   char *memPool;
   char *userName;
   struct passwd pw;
   struct passwd *pw_p;
   long memPoolSize;

#if defined(__APPLE__)
   memPoolSize = _PASSWORD_LEN;
#else
   memPoolSize = sysconf(_SC_GETPW_R_SIZE_MAX);

   if (memPoolSize <= 0) {
      Warning("%s: sysconf(_SC_GETPW_R_SIZE_MAX) failed.\n", __FUNCTION__);

      return NULL;
   }
#endif

   memPool = malloc(memPoolSize);
   if (memPool == NULL) {
      Warning("%s: Not enough memory.\n", __FUNCTION__);

      return NULL;
   }

   if ((Posix_Getpwuid_r(uid, &pw, memPool, memPoolSize, &pw_p) != 0) ||
       pw_p == NULL) {
      free(memPool);
      Warning("%s: Unable to retrieve the username associated with "
              "user ID %u.\n", __FUNCTION__, uid);

      return NULL;
   }

   userName = strdup(pw_p->pw_name);
   free(memPool);
   if (userName == NULL) {
      Warning("%s: Not enough memory.\n", __FUNCTION__);

      return NULL;
   }

   return userName;
}


/*
 *-----------------------------------------------------------------------------
 *
 * FileAcceptableSafeTmpDir --
 *
 *      Determines if the specified path is acceptable as the safe
 *      temp directory.  The directory must either be creatable
 *      with the appropriate permissions and userId or it must
 *      already exist with those settings.
 *
 * Results:
 *      TRUE if path is acceptible, FALSE otherwise
 *
 * Side effects:
 *      Directory may be created
 *
 *-----------------------------------------------------------------------------
 */

static Bool
FileAcceptableSafeTmpDir(const char *dirname,  // IN:
                         int userId)           // IN:
{
   Bool result;
   static const mode_t mode = 0700;

   result = (Posix_Mkdir(dirname, mode) == 0);
   if (!result) {
      int error = errno;

      if (EEXIST == error) {
         struct stat st;

         /*
          * The name already exists. Check that it is what we want: a
          * directory owned by the current effective user with permissions
          * 'mode'. It is crucial to use lstat() instead of stat() here,
          * because we do not want the name to be a symlink (created by
          * another user) pointing to a directory owned by the current
          * effective user with permissions 'mode'.
          */

         if (0 == Posix_Lstat(dirname, &st)) {
            /*
             * Our directory inherited S_ISGID if its parent had it. So it
             * is important to ignore that bit, and it is safe to do so
             * because that bit does not affect the owner's permissions.
             */

            if (S_ISDIR(st.st_mode) &&
                (st.st_uid == userId) &&
                ((st.st_mode & 05777) == mode)) {
               result = TRUE;
            }
         }
      }
   }

   return result;
}


/*
 *-----------------------------------------------------------------------------
 *
 * FileFindExistingSafeTmpDir --
 *
 *      Searches the directory baseTmpDir to see if any subdirectories
 *      are suitable to use as the safe temp directory.  The safe temp
 *      directory must have the correct permissions and userId.
 *
 * Results:
 *      Path to discovered safe temp directory (must be freed).
 *      NULL returned if no suitable directory is found.
 *
 * Side effects:
 *      None
 *
 *-----------------------------------------------------------------------------
 */

static Unicode
FileFindExistingSafeTmpDir(uid_t userId,            // IN:
                           const char *userName,    // IN:
                           const char *baseTmpDir)  // IN:
{
   int i;
   int numFiles;
   Unicode pattern;
   Unicode tmpDir = NULL;
   Unicode *fileList = NULL;

   /*
    * We always use the pattern PRODUCT-USER-xxxx when creating
    * alternative safe temp directories, so check for ones with
    * those names and the appropriate permissions.
    */

   pattern = Unicode_Format("%s-%s-", PRODUCT_GENERIC_NAME_LOWER, userName);
   if (pattern == NULL) {
      return NULL;
   }

   numFiles = File_ListDirectory(baseTmpDir, &fileList);

   if (numFiles == -1) {
      Unicode_Free(pattern);

      return NULL;
   }

   for (i = 0; i < numFiles; i++) {
       if (Unicode_StartsWith(fileList[i], pattern)) {
          Unicode path = Unicode_Join(baseTmpDir, DIRSEPS, fileList[i],
                                      NULL);

          if (File_IsDirectory(path) &&
              FileAcceptableSafeTmpDir(path, userId)) {
             tmpDir = path;
             break;
          }

          Unicode_Free(path);
       }
   }

   Unicode_FreeList(fileList, numFiles);
   Unicode_Free(pattern);

   return tmpDir;
}


/*
 *-----------------------------------------------------------------------------
 *
 * FileCreateSafeTmpDir --
 *
 *      Creates a new directory within baseTmpDir with the correct permissions
 *      and userId to ensure it is safe from symlink attacks.
 *
 * Results:
 *      Path to created safe temp directory (must be freed).
 *      NULL returned if no suitable directory could be created.
 *
 * Side effects:
 *      Directory may be created.
 *
 *-----------------------------------------------------------------------------
 */

static char *
FileCreateSafeTmpDir(uid_t userId,            // IN:
                     const char *userName,    // IN:
                     const char *baseTmpDir)  // IN:
{
   static const int MAX_DIR_ITERS = 250;
   int curDirIter = 0;
   char *tmpDir = NULL;

   while (TRUE) {
      /*
       * We use a random number that makes it more likely that we will create
       * an unused name than if we had simply tried suffixes in numeric order.
       */

      tmpDir = Str_Asprintf(NULL, "%s%s%s-%s-%u", baseTmpDir, DIRSEPS,
                            PRODUCT_GENERIC_NAME_LOWER, userName,
                            FileSimpleRandom());

      if (!tmpDir) {
         Warning("%s: Out of memory error.\n", __FUNCTION__);
         break;
      }

      if (FileAcceptableSafeTmpDir(tmpDir, userId)) {
         break;
      }

      if (++curDirIter > MAX_DIR_ITERS) {
         Warning("%s: Failed to create a safe temporary directory, path "
                 "\"%s\". The maximum number of attempts was exceeded.\n",
                 __FUNCTION__, tmpDir);
         free(tmpDir);
         tmpDir = NULL;
         break;
      }

      free(tmpDir);
      tmpDir = NULL;
   }

   return tmpDir;
}
#endif // __linux__


/*
 *-----------------------------------------------------------------------------
 *
 * File_GetSafeTmpDir --
 *
 *      Return a safe temporary directory (i.e. a temporary directory which
 *      is not prone to symlink attacks, because it is only writable by the
 *      current effective user).
 *
 *      Guaranteed to return the same directory every time it is
 *      called during the lifetime of the current process, for the
 *      current effective user ID. (Barring the user manually deleting
 *      or renaming the directory.)
 *
 * Results:
 *      The allocated directory path on success.
 *      NULL on failure.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

char *
File_GetSafeTmpDir(Bool useConf)  // IN:
{
   char *tmpDir;

#if defined(__FreeBSD__) || defined(sun)
   tmpDir = FileGetTmpDir(useConf);
#else
   static Atomic_Ptr lckStorage;
   static char *safeDir;
   char *baseTmpDir = NULL;
   char *userName = NULL;
   uid_t userId;
   MXUserExclLock *lck;

   userId = geteuid();

   /* Get and take lock for our safe dir. */
   lck = MXUser_CreateSingletonExclLock(&lckStorage, "getSafeTmpDirLock",
                                        RANK_getSafeTmpDirLock);
   ASSERT_NOT_IMPLEMENTED(lck != NULL);

   MXUser_AcquireExclLock(lck);

   /*
    * Check if we've created a temporary dir already and if it is still usable.
    */

   tmpDir = NULL;

   if (safeDir && FileAcceptableSafeTmpDir(safeDir, userId)) {
      tmpDir = Util_SafeStrdup(safeDir);
      goto exit;
   }

   /* We don't have a useable temporary dir, create one. */
   baseTmpDir = FileGetTmpDir(useConf);

   if (!baseTmpDir) {
      Warning("%s: FileGetTmpDir failed.\n", __FUNCTION__);
      goto exit;
   }

   userName = FileGetUserName(userId);

   if (!userName) {
      Warning("%s: FileGetUserName failed, using numeric ID "
              "as username instead.\n", __FUNCTION__);

      /* Fallback on just using the userId as the username. */
      userName = Str_Asprintf(NULL, "uid-%d", userId);

      if (!userName) {
         Warning("%s: Str_Asprintf error.\n", __FUNCTION__);
         goto exit;
      }
   }

   tmpDir = Str_Asprintf(NULL, "%s%s%s-%s", baseTmpDir, DIRSEPS,
                         PRODUCT_GENERIC_NAME_LOWER, userName);

   if (!tmpDir) {
      Warning("%s: Out of memory error.\n", __FUNCTION__);
      goto exit;
   }

   if (!FileAcceptableSafeTmpDir(tmpDir, userId)) {
      /*
       * We didn't get our first choice for the safe temp directory.
       * Search through the unsafe tmp directory to see if there is
       * an acceptable one to use.
       */

      free(tmpDir);

      tmpDir = FileFindExistingSafeTmpDir(userId, userName, baseTmpDir);

      if (!tmpDir) {
         /*
          * We didn't find any usable directories, so try to create one now.
          */

         tmpDir = FileCreateSafeTmpDir(userId, userName, baseTmpDir);
      }
   }

   if (tmpDir) {
      /*
       * We have successfully created a temporary directory, remember it for
       * future calls.
       */

      free(safeDir);
      safeDir = Util_SafeStrdup(tmpDir);
   }

  exit:
   MXUser_ReleaseExclLock(lck);
   free(baseTmpDir);
   free(userName);
#endif

   return tmpDir;
}