forked from NorthernTechHQ/libntech
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_lib.c
More file actions
2209 lines (1947 loc) · 58.5 KB
/
file_lib.c
File metadata and controls
2209 lines (1947 loc) · 58.5 KB
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 Northern.tech AS
This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
To the extent this program is licensed as part of the Enterprise
versions of CFEngine, the applicable Commercial Open Source License
(COSL) may apply to this file if you as a licensee so wish it. See
included file COSL.txt.
*/
#include <platform.h>
#include <file_lib.h>
#include <misc_lib.h>
#include <dir.h>
#include <logging.h>
#include <alloc.h>
#include <definitions.h> /* CF_PERMS_DEFAULT */
#include <libgen.h>
#include <logging.h>
#include <string_lib.h> /* memcchr */
#include <path.h>
/* below are includes for the fancy efficient file/data copying on Linux */
#ifdef __linux__
#ifdef HAVE_LINUX_FS_H
#include <linux/fs.h> /* FICLONE */
#endif
#include <fcntl.h>
#include <sys/ioctl.h>
#ifdef HAVE_SYS_SENDFILE_H
#include <sys/sendfile.h>
#endif
#include <sys/stat.h>
#include <unistd.h> /* copy_file_range(), lseek() */
#endif /* __linux__ */
#ifdef __MINGW32__
#include <windows.h> /* LockFileEx and friends */
#endif
#define SYMLINK_MAX_DEPTH 32
bool FileCanOpen(const char *path, const char *modes)
{
FILE *test = NULL;
if ((test = fopen(path, modes)) != NULL)
{
fclose(test);
return true;
}
else
{
return false;
}
}
#define READ_BUFSIZE 4096
Writer *FileRead(const char *filename, size_t max_size, bool *truncated)
{
int fd = safe_open(filename, O_RDONLY);
if (fd == -1)
{
return NULL;
}
Writer *w = FileReadFromFd(fd, max_size, truncated);
close(fd);
return w;
}
ssize_t ReadFileStreamToBuffer(FILE *file, size_t max_bytes, char *buf)
{
size_t bytes_read = 0;
size_t n = 0;
while (bytes_read < max_bytes)
{
n = fread(buf + bytes_read, 1, max_bytes - bytes_read, file);
if (ferror(file) && !feof(file))
{
return FILE_ERROR_READ;
}
else if (n == 0)
{
break;
}
bytes_read += n;
}
if (ferror(file))
{
return FILE_ERROR_READ;
}
return bytes_read;
}
bool File_Copy(const char *src, const char *dst)
{
assert(src != NULL);
assert(dst != NULL);
Log(LOG_LEVEL_INFO, "Copying: '%s' -> '%s'", src, dst);
FILE *in = safe_fopen(src, "r");
if (in == NULL)
{
Log(LOG_LEVEL_ERR, "Could not open '%s' (%s)", src, strerror(errno));
return false;
}
FILE *out = safe_fopen_create_perms(dst, "w", CF_PERMS_DEFAULT);
if (out == NULL)
{
Log(LOG_LEVEL_ERR, "Could not open '%s' (%s)", dst, strerror(errno));
fclose(in);
return false;
}
size_t bytes_in = 0;
size_t bytes_out = 0;
bool ret = true;
do
{
#define BUFSIZE 1024
char buf[BUFSIZE] = {0};
bytes_in = fread(buf, sizeof(char), sizeof(buf), in);
bytes_out = fwrite(buf, sizeof(char), bytes_in, out);
while (bytes_out < bytes_in && !ferror(out))
{
bytes_out += fwrite(
buf + bytes_out, sizeof(char), bytes_in - bytes_out, out);
}
} while (!feof(in) && !ferror(in) && !ferror(out) &&
bytes_in == bytes_out);
if (ferror(in))
{
Log(LOG_LEVEL_ERR, "Error encountered while reading '%s'", src);
ret = false;
}
else if (ferror(out))
{
Log(LOG_LEVEL_ERR, "Error encountered while writing '%s'", dst);
ret = false;
}
else if (bytes_in != bytes_out)
{
Log(LOG_LEVEL_ERR, "Did not copy the whole file");
ret = false;
}
const int i = fclose(in);
if (i != 0)
{
Log(LOG_LEVEL_ERR,
"Error encountered while closing '%s' (%s)",
src,
strerror(errno));
ret = false;
}
const int o = fclose(out);
if (o != 0)
{
Log(LOG_LEVEL_ERR,
"Error encountered while closing '%s' (%s)",
dst,
strerror(errno));
ret = false;
}
return ret;
}
bool File_CopyToDir(const char *src, const char *dst_dir)
{
assert(src != NULL);
assert(dst_dir != NULL);
assert(StringEndsWith(dst_dir, FILE_SEPARATOR_STR));
const char *filename = Path_Basename(src);
if (filename == NULL)
{
Log(LOG_LEVEL_ERR, "Cannot find filename in '%s'", src);
return false;
}
char dst[PATH_MAX] = {0};
const int s = snprintf(dst, PATH_MAX, "%s%s", dst_dir, filename);
if (s >= PATH_MAX)
{
Log(LOG_LEVEL_ERR, "Copy destination path too long: '%s...'", dst);
return false;
}
if (!File_Copy(src, dst))
{
Log(LOG_LEVEL_ERR, "Copying '%s' failed", filename);
return false;
}
return true;
}
Writer *FileReadFromFd(int fd, size_t max_size, bool *truncated)
{
if (truncated)
{
*truncated = false;
}
Writer *w = StringWriter();
for (;;)
{
char buf[READ_BUFSIZE];
/* Reading more data than needed is deliberate. It is a truncation detection. */
ssize_t read_ = read(fd, buf, READ_BUFSIZE);
if (read_ == 0)
{
/* Done. */
return w;
}
else if (read_ < 0)
{
if (errno != EINTR)
{
/* Something went wrong. */
WriterClose(w);
return NULL;
}
/* Else: interrupted - try again. */
}
else if (read_ + StringWriterLength(w) > max_size)
{
WriterWriteLen(w, buf, max_size - StringWriterLength(w));
/* Reached limit - stop. */
if (truncated)
{
*truncated = true;
}
return w;
}
else /* Filled buffer; copy and ask for more. */
{
WriterWriteLen(w, buf, read_);
}
}
}
ssize_t FullWrite(int desc, const char *ptr, size_t len)
{
ssize_t total_written = 0;
while (len > 0)
{
int written = write(desc, ptr, len);
if (written < 0)
{
if (errno == EINTR)
{
continue;
}
return written;
}
total_written += written;
ptr += written;
len -= written;
}
return total_written;
}
ssize_t FullRead(int fd, char *ptr, size_t len)
{
ssize_t total_read = 0;
while (len > 0)
{
ssize_t bytes_read = read(fd, ptr, len);
if (bytes_read < 0)
{
if (errno == EINTR)
{
continue;
}
return -1;
}
if (bytes_read == 0)
{
return total_read;
}
total_read += bytes_read;
ptr += bytes_read;
len -= bytes_read;
}
return total_read;
}
/**
* @note difference with files_names.h:IsDir() is that this doesn't
* follow symlinks, so a symlink is never a directory...
*/
bool IsDirReal(const char *path)
{
struct stat s;
if (lstat(path, &s) == -1)
{
return false; // Error
}
return (S_ISDIR(s.st_mode) != 0);
}
#ifndef __MINGW32__
NewLineMode FileNewLineMode(ARG_UNUSED const char *file)
{
return NewLineMode_Unix;
}
#endif // !__MINGW32__
bool IsWindowsNetworkPath(const char *const path)
{
#ifdef _WIN32
int off = 0;
while (path[off] == '\"')
{
// Bypass quoted strings
off += 1;
}
if (IsFileSep(path[off]) && IsFileSep(path[off + 1]))
{
return true;
}
#else // _WIN32
UNUSED(path);
#endif // _WIN32
return false;
}
bool IsWindowsDiskPath(const char *const path)
{
#ifdef _WIN32
int off = 0;
while (path[off] == '\"')
{
// Bypass quoted strings
off += 1;
}
if (isalpha(path[off]) && path[off + 1] == ':' && IsFileSep(path[off + 2]))
{
return true;
}
#else // _WIN32
UNUSED(path);
#endif // _WIN32
return false;
}
bool IsAbsoluteFileName(const char *f)
{
int off = 0;
// Check for quoted strings
for (off = 0; f[off] == '\"'; off++)
{
}
if (IsWindowsNetworkPath(f))
{
return true;
}
if (IsWindowsDiskPath(f))
{
return true;
}
if (IsFileSep(f[off]))
{
return true;
}
return false;
}
/* We assume that s is at least MAX_FILENAME large.
* MapName() is thread-safe, but the argument is modified. */
#ifdef _WIN32
# if defined(__MINGW32__)
char *MapNameCopy(const char *s)
{
char *str = xstrdup(s);
char *c = str;
while ((c = strchr(c, '/')))
{
*c = '\\';
}
return str;
}
char *MapName(char *s)
{
char *c = s;
while ((c = strchr(c, '/')))
{
*c = '\\';
}
return s;
}
# elif defined(__CYGWIN__)
char *MapNameCopy(const char *s)
{
Writer *w = StringWriter();
/* c:\a\b -> /cygdrive/c\a\b */
if (s[0] && isalpha(s[0]) && s[1] == ':')
{
WriterWriteF(w, "/cygdrive/%c", s[0]);
s += 2;
}
for (; *s; s++)
{
/* a//b//c -> a/b/c */
/* a\\b\\c -> a\b\c */
if (IsFileSep(*s) && IsFileSep(*(s + 1)))
{
continue;
}
/* a\b\c -> a/b/c */
WriterWriteChar(w, *s == '\\' ? '/' : *s);
}
return StringWriterClose(w);
}
char *MapName(char *s)
{
char *ret = MapNameCopy(s);
if (strlcpy(s, ret, MAX_FILENAME) >= MAX_FILENAME)
{
FatalError(ctx, "Expanded path (%s) is longer than MAX_FILENAME ("
TO_STRING(MAX_FILENAME) ") characters",
ret);
}
free(ret);
return s;
}
# else/* !__MINGW32__ && !__CYGWIN__ */
# error Unknown NT-based compilation environment
# endif/* __MINGW32__ || __CYGWIN__ */
#else /* !_WIN32 */
char *MapName(char *s)
{
return s;
}
char *MapNameCopy(const char *s)
{
return xstrdup(s);
}
#endif /* !_WIN32 */
char *MapNameForward(char *s)
/* Like MapName(), but maps all slashes to forward */
{
while ((s = strchr(s, '\\')))
{
*s = '/';
}
return s;
}
#ifdef TEST_SYMLINK_ATOMICITY
void switch_symlink_hook();
#define TEST_SYMLINK_SWITCH_POINT switch_symlink_hook();
#else
#define TEST_SYMLINK_SWITCH_POINT
#endif
void PathWalk(
const char *const path,
PathWalkFn callback,
void *const data,
PathWalkCopyFn copy,
PathWalkDestroyFn destroy)
{
assert(path != NULL);
assert(callback != NULL);
Seq *const children = ListDir(path, NULL);
if (children == NULL) {
Log(
LOG_LEVEL_DEBUG,
"Failed to list directory '%s'. Subdirectories will not be "
"iterated.", path);
return;
}
const size_t n_children = SeqLength(children);
Seq *const dirnames = SeqNew(1, free);
Seq *const filenames = SeqNew(1, free);
for (size_t i = 0; i < n_children; i++)
{
char *const child = SeqAt(children, i);
/* The basename(3) function might potentially mutate the argument.
* Thus, we make a copy to pass instead. */
char buf[PATH_MAX];
const size_t ret = StringCopy(child, buf, PATH_MAX);
if (ret >= PATH_MAX) {
Log(LOG_LEVEL_ERR,
"Failed to copy path: Path too long (%zu >= %d)",
ret, PATH_MAX);
SeqDestroy(dirnames);
SeqDestroy(filenames);
return;
}
const char *const b_name = basename(buf);
/* We don't iterate the '.' and '..' directory entries as it would cause
* infinite recursion. */
if (StringEqual(b_name, ".") || StringEqual(b_name, ".."))
{
continue;
}
// Note that stat(2) follows symbolic links.
struct stat sb;
if (stat(child, &sb) == 0)
{
char *const dup = xstrdup(b_name);
if (sb.st_mode & S_IFDIR)
{
SeqAppend(dirnames, dup);
}
else
{
SeqAppend(filenames, dup);
}
}
else
{
Log(LOG_LEVEL_DEBUG,
"Failed to stat file '%s': %s",
child,
GetErrorStr());
}
}
SeqDestroy(children);
callback(path, dirnames, filenames, data);
SeqDestroy(filenames);
// Recursively walk through subdirectories.
const size_t n_dirs = SeqLength(dirnames);
for (size_t i = 0; i < n_dirs; i++)
{
const char *const dir = SeqAt(dirnames, i);
if (dir != NULL)
{
char *const duplicate = (copy != NULL) ? copy(data) : data;
if (StringEqual(path, "."))
{
PathWalk(dir, callback, duplicate, copy, destroy);
}
else
{
char *next = Path_JoinAlloc(path, dir);
PathWalk(next, callback, duplicate, copy, destroy);
free(next);
}
if (copy != NULL && destroy != NULL)
{
destroy(duplicate);
}
}
}
SeqDestroy(dirnames);
}
Seq *ListDir(const char *dir, const char *extension)
{
Dir *dirh = DirOpen(dir);
if (dirh == NULL)
{
return NULL;
}
Seq *contents = SeqNew(10, free);
const struct dirent *dirp;
while ((dirp = DirRead(dirh)) != NULL)
{
const char *name = dirp->d_name;
if (extension == NULL || StringEndsWithCase(name, extension, true))
{
SeqAppend(contents, Path_JoinAlloc(dir, name));
}
}
DirClose(dirh);
return contents;
}
mode_t SetUmask(mode_t new_mask)
{
const mode_t old_mask = umask(new_mask);
Log(LOG_LEVEL_DEBUG, "Set umask to %o, was %o", new_mask, old_mask);
return old_mask;
}
void RestoreUmask(mode_t old_mask)
{
umask(old_mask);
Log(LOG_LEVEL_DEBUG, "Restored umask to %o", old_mask);
}
/**
* Opens a file safely, with default (strict) permissions on creation.
* See safe_open_create_perms for more documentation.
*
* @param pathname The path to open.
* @param flags Same flags as for system open().
* @return Same errors as open().
*/
int safe_open(const char *pathname, int flags)
{
return safe_open_create_perms(pathname, flags, CF_PERMS_DEFAULT);
}
/**
* Opens a file safely. It will follow symlinks, but only if the symlink is
* trusted, that is, if the owner of the symlink and the owner of the target are
* the same, or if the owner of the symlink is either root or the user running
* the current process. All components are checked, even symlinks encountered in
* earlier parts of the path name.
*
* It should always be used when opening a file or directory that is not
* guaranteed to be owned by root.
*
* safe_open and safe_fopen both default to secure (0600) file creation perms.
* The _create_perms variants allow you to explicitly set different permissions.
*
* @param pathname The path to open
* @param flags Same flags as for system open()
* @param create_perms Permissions for file, only relevant on file creation
* @return Same errors as open()
* @see safe_fopen_create_perms()
* @see safe_open()
*/
int safe_open_create_perms(
const char *const pathname, int flags, const mode_t create_perms)
{
if (flags & O_TRUNC)
{
/* Undefined behaviour otherwise, according to the standard. */
assert((flags & O_RDWR) || (flags & O_WRONLY));
}
if (!pathname)
{
errno = EINVAL;
return -1;
}
if (*pathname == '\0')
{
errno = ENOENT;
return -1;
}
#ifdef __MINGW32__
// Windows gets off easy. No symlinks there.
return open(pathname, flags, create_perms);
#elif defined(__ANDROID__)
// if effective user is not root then don't try to open
// all paths from '/' up, might not have permissions.
uid_t p_euid = geteuid();
if (p_euid != 0)
{
return open(pathname, flags, create_perms);
}
#else // !__MINGW32__ and !__ANDROID__
const size_t path_bufsize = strlen(pathname) + 1;
char path[path_bufsize];
const size_t res_len = StringCopy(pathname, path, path_bufsize);
UNUSED(res_len);
assert(res_len == strlen(pathname));
int currentfd;
const char *first_dir;
bool trunc = false;
const int orig_flags = flags;
char *next_component = path;
bool p_uid;
if (*next_component == '/')
{
first_dir = "/";
// Eliminate double slashes.
while (*(++next_component) == '/') { /*noop*/ }
if (!*next_component)
{
next_component = NULL;
}
}
else
{
first_dir = ".";
}
currentfd = openat(AT_FDCWD, first_dir, O_RDONLY);
if (currentfd < 0)
{
return -1;
}
// current process user id
p_uid = geteuid();
size_t final_size = (size_t) -1;
while (next_component)
{
char *component = next_component;
next_component = strchr(component + 1, '/');
// Used to restore the slashes in the final path component.
char *restore_slash = NULL;
if (next_component)
{
restore_slash = next_component;
*next_component = '\0';
// Eliminate double slashes.
while (*(++next_component) == '/') { /*noop*/ }
if (!*next_component)
{
next_component = NULL;
}
else
{
restore_slash = NULL;
}
}
// In cases of a race condition when creating a file, our attempt to open it may fail
// (see O_EXCL and O_CREAT flags below). However, this can happen even under normal
// circumstances, if we are unlucky; it does not mean that someone is up to something bad.
// So retry it a few times before giving up.
int attempts = 3;
trunc = false;
while (true)
{
if (( (orig_flags & O_RDWR) || (orig_flags & O_WRONLY))
&& (orig_flags & O_TRUNC))
{
trunc = true;
/* We need to check after we have opened the file whether we
* opened the right one. But if we truncate it, the damage is
* already done, we have destroyed the contents, and that file
* might have been a symlink to /etc/shadow! So save that flag
* and apply the truncation afterwards instead. */
flags &= ~O_TRUNC;
}
if (restore_slash)
{
*restore_slash = '\0';
}
struct stat stat_before, stat_after;
int stat_before_result = fstatat(currentfd, component, &stat_before, AT_SYMLINK_NOFOLLOW);
if (stat_before_result < 0
&& (errno != ENOENT
|| next_component // Meaning "not a leaf".
|| !(flags & O_CREAT)))
{
close(currentfd);
return -1;
}
/*
* This testing entry point is about the following real-world
* scenario: There can be an attacker that at this point
* overwrites the existing file or writes a file, invalidating
* basically the previous fstatat().
*
* - We make sure that can't happen if the file did not exist, by
* creating with O_EXCL.
* - We make sure that can't happen if the file existed, by
* comparing with fstat() result after the open().
*
*/
TEST_SYMLINK_SWITCH_POINT
if (!next_component) /* last component */
{
if (stat_before_result < 0)
{
assert(flags & O_CREAT);
// Doesn't exist. Make sure *we* create it.
flags |= O_EXCL;
/* No need to ftruncate() the file at the end. */
trunc = false;
}
else
{
if ((flags & O_CREAT) && (flags & O_EXCL))
{
close(currentfd);
errno = EEXIST;
return -1;
}
// Already exists. Make sure we *don't* create it.
flags &= ~O_CREAT;
}
if (restore_slash)
{
*restore_slash = '/';
}
int filefd = openat(currentfd, component, flags, create_perms);
if (filefd < 0)
{
if ((stat_before_result < 0 && !(orig_flags & O_EXCL) && errno == EEXIST) ||
(stat_before_result >= 0 && (orig_flags & O_CREAT) && errno == ENOENT))
{
if (--attempts >= 0)
{
// Might be our fault. Try again.
flags = orig_flags;
continue;
}
else
{
// Too many attempts. Give up.
// Most likely a link that is in the way of file creation, but can also
// be a file that is constantly created and deleted (race condition).
// It is not possible to separate between the two, so return EACCES to
// signal that we denied access.
errno = EACCES;
}
}
close(currentfd);
return -1;
}
close(currentfd);
currentfd = filefd;
}
else
{
int new_currentfd = openat(currentfd, component, O_RDONLY);
close(currentfd);
if (new_currentfd < 0)
{
return -1;
}
currentfd = new_currentfd;
}
/* If file did exist, we fstat() again and compare with previous. */
if (stat_before_result == 0)
{
if (fstat(currentfd, &stat_after) < 0)
{
close(currentfd);
return -1;
}
// Some attacks may use symlinks to get higher privileges
// The safe cases are:
// * symlinks owned by root
// * symlinks owned by the user running the process
// * symlinks that have the same owner and group as the destination
if (stat_before.st_uid != 0 &&
stat_before.st_uid != p_uid &&
(stat_before.st_uid != stat_after.st_uid || stat_before.st_gid != stat_after.st_gid))
{
close(currentfd);
Log(LOG_LEVEL_ERR, "Cannot follow symlink '%s'; it is not "
"owned by root or the user running this process, and "
"the target owner and/or group differs from that of "
"the symlink itself.", pathname);
// Return ENOLINK to signal that the link cannot be followed
// ('Link has been severed').
errno = ENOLINK;
return -1;
}
final_size = (size_t) stat_after.st_size;
}
// If we got here, we've been successful, so don't try again.
break;
}
}
/* Truncate if O_CREAT and the file preexisted. */
if (trunc)
{
/* Do not truncate if the size is already zero, some
* filesystems don't support ftruncate() with offset>=size. */
assert(final_size != (size_t) -1);
if (final_size != 0)
{
int tr_ret = ftruncate(currentfd, 0);
if (tr_ret < 0)
{
Log(LOG_LEVEL_ERR,
"safe_open: unexpected failure (ftruncate: %s)",
GetErrorStr());
close(currentfd);
return -1;
}
}
}
return currentfd;
#endif // !__MINGW32__
}
FILE *safe_fopen(const char *const path, const char *const mode)
{
return safe_fopen_create_perms(path, mode, CF_PERMS_DEFAULT);
}
/**
* Opens a file safely. It will follow symlinks, but only if the symlink is trusted,
* that is, if the owner of the symlink and the owner of the target are the same,
* or if the owner of the symlink is either root or the user running the current process.
* All components are checked, even symlinks encountered in earlier parts of the
* path name.
*
* It should always be used when opening a directory that is not guaranteed to be
* owned by root.
*
* @param pathname The path to open.
* @param flags Same mode as for system fopen().
* @param create_perms Permissions for file, only relevant on file creation.
* @return Same errors as fopen().
*/
FILE *safe_fopen_create_perms(
const char *const path, const char *const mode, const mode_t create_perms)
{
if (!path || !mode)
{
errno = EINVAL;
return NULL;
}
char fdopen_mode_str[3] = {0};
int fdopen_mode_idx = 0;
int flags = 0;
for (int c = 0; mode[c]; c++)