summaryrefslogtreecommitdiffstats
path: root/libuser-dirtree-TOCTOU-fix.patch
blob: 11db6a7ff9b5cd9903d77806932631ebc801b343 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
diff --git a/Makefile.am b/Makefile.am
index 5376bb9..e993557 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -14,7 +14,8 @@ PYTHON_CPPFLAGS = -I/usr/include/python$(PYTHON_VERSION)
 
 ## Targets
 SUBDIRS = po docs
-TESTS = tests/config_test.sh tests/files_test tests/pwhash_test tests/utils_test
+TESTS = tests/config_test.sh tests/fs_test tests/files_test tests/pwhash_test \
+	tests/utils_test
 if LDAP
 TESTS += tests/default_pw_test tests/ldap_test
 endif
@@ -30,6 +31,7 @@ EXTRA_DIST = \
 	tests/config_test.sh \
 	tests/default_pw.conf.in tests/default_pw_test tests/default_pw_test.py \
 	tests/files.conf.in tests/files_test tests/files_test.py \
+	tests/fs.conf.in tests/fs_tests tests/fs_test.py \
 	tests/ldap.conf.in tests/ldaprc tests/ldap_skel.ldif tests/ldap_test \
 	tests/ldap_test.py \
 	tests/pwhash.conf.in tests/pwhash.py tests/pwhash_test \
diff --git a/apps/apputil.c b/apps/apputil.c
index 4a260be..1ee6500 100644
--- a/apps/apputil.c
+++ b/apps/apputil.c
@@ -95,348 +95,712 @@ current_umask(void)
 	return value;
 }
 
-/* Copy the "src" directory to "dest", setting all ownerships as given, and
-   setting the mode of the top-level directory as given.  The group ID of the
-   copied files is preserved if it is nonzero.  If keep_contexts, preserve
-   SELinux contexts in files under dest; use matchpathcon otherwise.  Assume
-   umask_value is the current value of umask.
-
-   Note that keep_contexts does NOT affect the context of dest; the caller must
-   perform an explicit setfscreatecon() before calling lu_homedir_copy() to set
-   the context of dest.  The SELinux fscreate context is on return from this
-   function is unspecified. */
+/* What should the ownership and permissions of the copied files be? */
+struct copy_access_options
+{
+	/* Preserve ownership and permissions of the original unmodified;
+	   otherwise, use matchpathcon() for SELinux contexts and apply
+	   the following fields.. */
+	gboolean preserve_source;
+	/* Ignore EEXIST errors.  This will go away in the future. */
+	gboolean ignore_eexist;
+	uid_t uid;	     /* UID to use for the copy if !preserve_source. */
+	/* GID to use for the copy if !preserve_source and original is owned by
+	   GID 0. */
+	gid_t gid;
+	mode_t umask;	      /* umask to apply to modes if !preserve_source */
+};
+
+/* Return an UID appropriate for a copy of ST given OPTIONS. */
+static uid_t
+uid_for_copy(const struct copy_access_options *options, const struct stat *st)
+{
+	if (options->preserve_source)
+		return st->st_uid;
+	return options->uid;
+}
+
+/* Return a GID appropriate for a copy of ST given OPTIONS. */
+static gid_t
+gid_for_copy(const struct copy_access_options *options, const struct stat *st)
+{
+	if (options->preserve_source)
+		return st->st_gid;
+	if (st->st_gid != 0) /* Skeleton wants us to us a different group */
+		return st->st_gid;
+	return options->gid;
+}
+
+/* Return a mode_t value appropriate for a copy of ST given OPTIONS. */
+static mode_t
+mode_for_copy(const struct copy_access_options *options, const struct stat *st)
+{
+	if (options->preserve_source)
+		return st->st_mode;
+	return st->st_mode & ~options->umask;
+}
+
+/* Copy symlink SYMLINK_NAME in SRC_DIR_FD, which corresponds to SRC_PATH, to
+   SYMLINK_NAME in DEST_DIR_FD, which corresponds to DEST_PATH.  Use
+   ACCESS_OPTIONS.  Use SRC_STAT for data about SRC_PATH.
+
+   On return from this function, SELinux fscreate context is unspecified.
+
+   Note that SRC_PATH should only be used for error messages, not to access the
+   files; if the user is still logged in, a directory in the path may be
+   replaced by a symbolic link, redirecting the access outside of
+   SRC_DIR_FD/SYMLINK_NAME.  Likewise for DEST_*. */
 static gboolean
-lu_homedir_copy(const char *src, const char *dest, uid_t owner, gid_t group,
-		mode_t mode, gboolean keep_contexts, mode_t umask_value,
-		struct lu_error **error)
+copy_symlink(int src_dir_fd, const char *src_path, int dest_dir_fd,
+	     const char *dest_path, const char *symlink_name,
+	     const struct stat *src_stat,
+	     const struct copy_access_options *access_options,
+	     struct lu_error **error)
 {
-	struct dirent *ent;
-	DIR *dir;
-	int ifd, ofd;
-	gboolean ret = FALSE;
+	char buf[PATH_MAX];
+	ssize_t len;
+	struct timespec timebuf[2];
 
 	LU_ERROR_CHECK(error);
 
-	if (*dest != '/') {
+	/* In the worst case here, we end up with a wrong SELinux context for a
+	   symbolic link due to a path name lookup race.  That's unfortunate,
+	   but symlink contents are more or less public anyway... (A possible
+	   improvement would be to use Linux-only O_PATH to open src_path
+	   first, then see if it is a symlink, and "upgrade" to an O_RDONLY if
+	   not.  But O_PATH is available only in Linux >= 2.6.39.)
+
+	   The symlinkat()/fchownat()/utimensat() calls are also not safe
+	   against an user meddling; we might be able to ensure the
+	   fchownat()/utimensat() are done on the same file using O_PATH again,
+	   but symlinkat()/the rest is definitely unatomic.  Rely on having an
+	   unwritable the parent directory, same as in the mkdirat()/openat()
+	   case of lu_homedir_copy_and_close(). */
+	if (access_options->preserve_source) {
+		if (!lu_util_fscreate_from_lfile(src_path, error))
+			return FALSE;
+	} else if (!lu_util_fscreate_for_path(dest_path,
+					      src_stat->st_mode & S_IFMT,
+					      error))
+		return FALSE;
+
+	len = readlinkat(src_dir_fd, symlink_name, buf, sizeof(buf) - 1);
+	if (len == -1) {
 		lu_error_new(error, lu_error_generic,
-			     _("Home directory path `%s' is not absolute"),
-			     dest);
-		goto err;
+			     _("Error reading `%s': %s"), src_path,
+			     strerror(errno));
+		return FALSE;
 	}
-
-	dir = opendir(src);
-	if (dir == NULL) {
+	buf[len] = '\0';
+	if (symlinkat(buf, dest_dir_fd, symlink_name) == -1) {
+		if (errno == EEXIST && access_options->ignore_eexist)
+			return TRUE;
 		lu_error_new(error, lu_error_generic,
-			     _("Error reading `%s': %s"), src,
+			     _("Error creating `%s': %s"), dest_path,
 			     strerror(errno));
-		goto err;
+		return FALSE;
 	}
-
-	/* Create the top-level directory. */
-	if (mkdir(dest, mode) == -1 && errno != EEXIST) {
+	if (fchownat(dest_dir_fd, symlink_name,
+		     uid_for_copy(access_options, src_stat),
+		     gid_for_copy(access_options, src_stat),
+		     AT_SYMLINK_NOFOLLOW) == -1
+	    && errno != EPERM && errno != EOPNOTSUPP) {
 		lu_error_new(error, lu_error_generic,
-			     _("Error creating `%s': %s"), dest,
+			     _("Error changing owner of `%s': %s"), dest_path,
 			     strerror(errno));
-		goto err_dir;
+		return FALSE;
 	}
+	timebuf[0] = src_stat->st_atim;
+	timebuf[1] = src_stat->st_mtim;
+	utimensat(dest_dir_fd, symlink_name, timebuf, AT_SYMLINK_NOFOLLOW);
+	return TRUE;
+}
+
+/* Copy SRC_FD, which corresponds to SRC_PATH, to DEST_NAME in DEST_DIR_FD,
+   which corresponds to DEST_PATH.  Use ACCESS_OPTIONS.  Use SRC_STAT for data
+   about SRC_PATH.
+
+   On return from this function, SELinux fscreate context is unspecified.
+
+   Note that SRC_PATH should only be used for error messages, not to access the
+   files; if the user is still logged in, a directory in the path may be
+   replaced by a symbolic link, redirecting the access outside of SRC_FD.
+   Likewise for DEST_*. */
+static gboolean
+copy_regular_file(int src_fd, const char *src_path, int dest_dir_fd,
+		  const char *dest_name, const char *dest_path,
+		  const struct stat *src_stat,
+		  const struct copy_access_options *access_options,
+		  struct lu_error **error)
+{
+	int dest_fd;
+	struct timespec timebuf[2];
+	gboolean ret = FALSE;
+
+	LU_ERROR_CHECK(error);
 
-	/* Set the ownership on the top-level directory. */
-	if (chown(dest, owner, group) == -1 && errno != EPERM) {
+	if (access_options->preserve_source) {
+		if (!lu_util_fscreate_from_fd(src_fd, src_path, error))
+			return FALSE;
+	} else if (!lu_util_fscreate_for_path(dest_path,
+					      src_stat->st_mode & S_IFMT,
+					      error))
+		return FALSE;
+	/* Start with absolutely restrictive permissions; the original file may
+	   be e.g. a hardlink to /etc/shadow. */
+	dest_fd = openat(dest_dir_fd, dest_name,
+			 O_EXCL | O_CREAT | O_WRONLY | O_NOFOLLOW, 0);
+	if (dest_fd == -1) {
+		if (errno == EEXIST && access_options->ignore_eexist)
+			return TRUE;
+		lu_error_new(error, lu_error_open, _("Error writing `%s': %s"),
+			     dest_path, strerror(errno));
+		return FALSE;
+	}
+
+	/* Now just copy the data. */
+	for (;;) {
+		unsigned char buf[BUFSIZ];
+		ssize_t left;
+		unsigned char *p;
+
+		left = read(src_fd, &buf, sizeof(buf));
+		if (left == -1) {
+			if (errno == EINTR)
+				continue;
+			lu_error_new(error, lu_error_read,
+				     _("Error reading `%s': %s"), src_path,
+				     strerror(errno));
+			goto err_dest_fd;
+		}
+		if (left == 0)
+			break;
+		p = buf;
+		while (left > 0) {
+			ssize_t out;
+
+			out = write(dest_fd, p, left);
+			if (out == -1) {
+				if (errno == EINTR)
+					continue;
+				lu_error_new(error, lu_error_write,
+					     _("Error writing `%s': %s"),
+					     dest_path, strerror(errno));
+				goto err_dest_fd;
+			}
+			p += out;
+			left -= out;
+		}
+	}
+
+	/* Set the ownership; permissions are still restrictive. */
+	if (fchown(dest_fd, uid_for_copy(access_options, src_stat),
+		   gid_for_copy(access_options, src_stat)) == -1
+	    && errno != EPERM) {
 		lu_error_new(error, lu_error_generic,
-			     _("Error changing owner of `%s': %s"), dest,
+			     _("Error changing owner of `%s': %s"), dest_path,
 			     strerror(errno));
-		goto err_dir;
+		goto err_dest_fd;
 	}
 
-	/* Set modes explicitly to preserve S_ISGID and other bits.  Do this
-	   after chown, because chown is permitted to reset these bits. */
-	if (chmod(dest, mode & ~umask_value) == -1) {
+	/* Set the desired mode.  Do this explicitly to preserve S_ISGID and
+	   other bits.  Do this after chown, because chown is permitted to
+	   reset these bits. */
+	if (fchmod(dest_fd, mode_for_copy(access_options, src_stat)) == -1) {
 		lu_error_new(error, lu_error_generic,
-			     _("Error setting mode of `%s': %s"), dest,
+			     _("Error setting mode of `%s': %s"), dest_path,
 			     strerror(errno));
-		goto err_dir;
+		goto err_dest_fd;
 	}
 
-	while ((ent = readdir(dir)) != NULL) {
-		char srcpath[PATH_MAX], path[PATH_MAX], buf[PATH_MAX];
-		struct stat st;
-		struct utimbuf timebuf;
+	timebuf[0] = src_stat->st_atim;
+	timebuf[1] = src_stat->st_mtim;
+	futimens(dest_fd, timebuf);
 
-		/* Iterate through each item in the directory. */
-		/* Skip over self and parent hard links. */
-		if (strcmp(ent->d_name, ".") == 0) {
-			continue;
-		}
-		if (strcmp(ent->d_name, "..") == 0) {
-			continue;
+	ret = TRUE;
+	/* Fall through */
+
+err_dest_fd:
+	close(dest_fd);
+	return ret;
+}
+
+/* Forward declaration. */
+static gboolean lu_copy_dir_and_close(int src_dir_fd, GString *src_path_buf,
+				      int dest_parent_fd,
+				      const char *dest_dir_name,
+				      GString *dest_path_buf,
+				      const struct stat *src_dir_stat,
+				      const struct copy_access_options
+				      *access_options, struct lu_error **error);
+
+/* Copy ENT_NAME in SRC_DIR_FD, which corresponds to SRC_PATH_BUF,
+   to DEST_DIR_FD, which corresponds to DEST_PATH_BUF.  Use ACCESS_OPTIONS.
+
+   On return from this function, SELinux fscreate context is unspecified.  This
+   function may temporarily modify SRC_PATH_BUF and DEST_PATH_BUF, but they
+   will be unchanged on return.
+
+   Note that SRC_PATH_BUF should only be used for error messages, not to access
+   the files; if the user is still logged in, a directory in the path may be
+   replaced by a symbolic link, redirecting the access outside of SRC_DIR_FD.
+   Likewise for DEST_*. */
+static gboolean
+copy_dir_entry(int src_dir_fd, GString *src_path_buf, int dest_dir_fd,
+	       GString *dest_path_buf, const char *ent_name,
+	       const struct copy_access_options *access_options,
+	       struct lu_error **error)
+{
+	struct stat st;
+	int ifd;
+	gboolean ret = FALSE;
+
+	LU_ERROR_CHECK(error);
+
+	/* Open the input entry first, then we can fstat() it and be certain
+	   that it is still the same file.  O_NONBLOCK protects us against
+	   FIFOs and perhaps side-effects of the open() of a device file if
+	   there ever was one here, and doesn't matter for regular files or
+	   directories. */
+	ifd = openat(src_dir_fd, ent_name,
+		     O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
+	if (ifd == -1) {
+		int saved_errno;
+
+		saved_errno = errno;
+		if (errno != ELOOP || fstatat(src_dir_fd, ent_name, &st,
+					      AT_SYMLINK_NOFOLLOW) != 0
+		    || !S_ISLNK(st.st_mode)) {
+			lu_error_new(error, lu_error_open,
+				     _("Error opening `%s': %s"),
+				     src_path_buf->str, strerror(saved_errno));
+			return FALSE;
 		}
 
-		/* Build the path of the source file or directory and its
-		   corresponding member in the new tree. */
-		snprintf(srcpath, sizeof(srcpath), "%s/%s", src, ent->d_name);
-		snprintf(path, sizeof(path), "%s/%s", dest, ent->d_name);
+		return copy_symlink(src_dir_fd, src_path_buf->str, dest_dir_fd,
+				    dest_path_buf->str, ent_name, &st,
+				    access_options, error);
+	}
 
-		/* What we do next depends on the type of entry we're
-		 * looking at. */
-		if (lstat(srcpath, &st) != 0)
-			continue;
+	if (fstat(ifd, &st) != 0) {
+		lu_error_new(error, lu_error_stat, _("couldn't stat `%s': %s"),
+			     src_path_buf->str, strerror(errno));
+		goto err_ifd;
+	}
+	g_assert(!S_ISLNK(st.st_mode));
+
+	if (S_ISDIR(st.st_mode)) {
+		ret = lu_copy_dir_and_close(ifd, src_path_buf, dest_dir_fd,
+					    ent_name, dest_path_buf, &st,
+					    access_options, error);
+		ifd = -1;
+	} else if (S_ISREG(st.st_mode))
+		ret = copy_regular_file(ifd, src_path_buf->str, dest_dir_fd,
+					ent_name, dest_path_buf->str, &st,
+					access_options, error);
+	else
+		/* Note that we don't copy device specials. */
+		ret = TRUE;
+	/* Fall through */
 
-		if (keep_contexts != 0) {
-			if (!lu_util_fscreate_from_file(srcpath, error))
-				goto err_dir;
-		} else if (!lu_util_fscreate_for_path(path, st.st_mode & S_IFMT,
-						      error))
-			goto err_dir;
+err_ifd:
+	if (ifd != -1)
+		close(ifd);
+	return ret;
+}
 
-		/* We always want to preserve atime/mtime. */
-		timebuf.actime = st.st_atime;
-		timebuf.modtime = st.st_mtime;
+/* Copy SRC_DIR_FD, which corresponds to SRC_PATH_BUF, to DEST_DIR_NAME under
+   DEST_PARENT_FD, which corresponds to DEST_PATH_BUF.  Use ACCESS_OPTIONS.  Use
+   SRC_DIR_STAT for data about SRC_PATH_BUF.
 
-		/* If it's a directory, descend into it. */
-		if (S_ISDIR(st.st_mode)) {
-			if (!lu_homedir_copy(srcpath, path, owner,
-					     st.st_gid ?: group, st.st_mode,
-					     keep_contexts, umask_value, error))
-				/* Aargh!  Fail up. */
-				goto err_dir;
-			/* Set the date on the directory. */
-			utime(path, &timebuf);
-			continue;
-		}
+   In every case, even on error, close SRC_DIR_FD.
 
-		/* If it's a symlink, duplicate it. */
-		if (S_ISLNK(st.st_mode)) {
-			ssize_t len;
+   DEST_PARENT_FD may be AT_FDCWD.  On return from this function, SELinux
+   fscreate context is unspecified.  This function may temporarily modify
+   SRC_PATH_BUF and DEST_PATH_BUF, but they will be unchanged on return.
 
-			len = readlink(srcpath, buf, sizeof(buf) - 1);
-			if (len == -1) {
-				lu_error_new(error, lu_error_generic,
-					     _("Error reading `%s': %s"),
-					     srcpath, strerror(errno));
-				goto err_dir;
-			}
-			buf[len] = '\0';
-			if (symlink(buf, path) == -1) {
-				if (errno == EEXIST)
-					continue;
-				lu_error_new(error, lu_error_generic,
-					     _("Error creating `%s': %s"),
-					     path, strerror(errno));
-				goto err_dir;
-			}
-			if (lchown(path, owner, st.st_gid ?: group) == -1
-			    && errno != EPERM && errno != EOPNOTSUPP) {
-				lu_error_new(error, lu_error_generic,
-					     _("Error changing owner of `%s': "
-					       "%s"), dest, strerror(errno));
-				goto err_dir;
-			}
-			utime(path, &timebuf);
-			continue;
-		}
+   Note that SRC_PATH_BUF should only be used for error messages, not to access
+   the files; if the user is still logged in, a directory in the path may be
+   replaced by a symbolic link, redirecting the access outside of
+   SRC_PARENT_FD/SRC_DIR_NAME.   Likewise for DEST_*. */
+static gboolean
+lu_copy_dir_and_close(int src_dir_fd, GString *src_path_buf, int dest_parent_fd,
+		      const char *dest_dir_name, GString *dest_path_buf,
+		      const struct stat *src_dir_stat,
+		      const struct copy_access_options *access_options,
+		      struct lu_error **error)
+{
+	size_t orig_src_path_buf_len, orig_dest_path_buf_len;
+	struct dirent *ent;
+	DIR *dir;
+	int dest_dir_fd;
+	struct timespec timebuf[2];
+	gboolean ret = FALSE;
 
-		/* If it's a regular file, copy it. */
-		if (S_ISREG(st.st_mode)) {
-			off_t offset;
-
-			/* Open both the input and output files.  If we fail to
-			   do either, we have to give up. */
-			ifd = open(srcpath, O_RDONLY);
-			if (ifd == -1) {
-				lu_error_new(error, lu_error_open,
-					     _("Error reading `%s': %s"),
-					     srcpath, strerror(errno));
-				goto err_dir;
-			}
-			ofd = open(path, O_EXCL | O_CREAT | O_WRONLY,
-				   st.st_mode);
-			if (ofd == -1) {
-				if (errno == EEXIST) {
-					close(ifd);
-					continue;
-				}
-				lu_error_new(error, lu_error_open,
-					     _("Error writing `%s': %s"),
-					     path, strerror(errno));
-				goto err_ifd;
-			}
+	LU_ERROR_CHECK(error);
+	orig_src_path_buf_len = src_path_buf->len;
+	orig_dest_path_buf_len = dest_path_buf->len;
 
-			/* Now just copy the data. */
-			for (;;) {
-				ssize_t left;
-				char *p;
-
-				left = read(ifd, &buf, sizeof(buf));
-				if (left == -1) {
-					if (errno == EINTR)
-						continue;
-					lu_error_new(error, lu_error_read,
-						     _("Error reading `%s': "
-						       "%s"), srcpath,
-						     strerror(errno));
-					goto err_ofd;
-				}
-				if (left == 0)
-					break;
-				p = buf;
-				while (left > 0) {
-					ssize_t out;
-
-					out = write(ofd, p, left);
-					if (out == -1) {
-						if (errno == EINTR)
-							continue;
-						lu_error_new(error,
-							     lu_error_write,
-							     _("Error writing "
-							       "`%s': %s"),
-							     path,
-							     strerror(errno));
-						goto err_ofd;
-					}
-					p += out;
-					left -= out;
-				}
-			}
+	if (*dest_path_buf->str != '/') {
+		lu_error_new(error, lu_error_generic,
+			     _("Home directory path `%s' is not absolute"),
+			     dest_path_buf->str);
+		goto err_src_dir_fd;
+	}
 
-			/* Close the files. */
-			offset = lseek(ofd, 0, SEEK_CUR);
-			if (offset != ((off_t) -1)) {
-				if (ftruncate(ofd, offset) == -1) {
-					lu_error_new(error, lu_error_generic,
-						     _("Error writing `%s': "
-						       "%s"), path,
-						     strerror(errno));
-					goto err_ofd;
-				}
-			}
-			close (ifd);
-			close (ofd);
+	dir = fdopendir(src_dir_fd);
+	if (dir == NULL) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error reading `%s': %s"), src_path_buf->str,
+			     strerror(errno));
+		goto err_src_dir_fd;
+	}
 
-			/* Set the ownership and timestamp on the new file. */
-			if (chown(path, owner, st.st_gid ?: group) == -1
-			    && errno != EPERM) {
-				lu_error_new(error, lu_error_generic,
-					     _("Error changing owner of `%s': "
-					       "%s"), dest, strerror(errno));
-				goto err_dir;
-			}
-			utime(path, &timebuf);
+	if (access_options->preserve_source) {
+		if (!lu_util_fscreate_from_fd(src_dir_fd, src_path_buf->str,
+					      error))
+			goto err_dir;
+	} else if (!lu_util_fscreate_for_path(dest_path_buf->str,
+					      src_dir_stat->st_mode & S_IFMT,
+					      error))
+		goto err_dir;
+
+	/* Create the directory.  It starts owned by us (presumbaly root), with
+	   fairly restrictive permissions that still allow us to use the
+	   directory. */
+	if (mkdirat(dest_parent_fd, dest_dir_name, S_IRWXU) == -1
+	    && (errno != EEXIST || !access_options->ignore_eexist)) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error creating `%s': %s"), dest_path_buf->str,
+			     strerror(errno));
+		goto err_dir;
+	}
+	/* FIXME: O_SEARCH would be ideal here, but Linux doesn't currently
+	   provide it. */
+	dest_dir_fd = openat(dest_parent_fd, dest_dir_name,
+			     O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
+	if (dest_dir_fd == -1) {
+		lu_error_new(error, lu_error_open, _("Error opening `%s': %s"),
+			     dest_path_buf->str, strerror(errno));
+		goto err_dir;
+	}
+	/* The openat() after mkdirat() is not 100% safe; we may be modifying
+	   ownership/permissions of another user's directory that was moved to
+	   dest_dir_name in the mean time!  (Although why there would exist an
+	   another user's directory, assuming lack hardlinks of directories, is
+	   not clear.)
+
+	   There's no way to do this completely atomically; so, rely on
+	   permissions of the parent directory (write access to parent is
+	   required to rename directories).  This holds for the top-level
+	   directory, and for the others we achieve this by creating them
+	   root-owned and S_IRWXU, and only applying the original ownership and
+	   permissions after finishing other work.  See also the comment in
+	   copy_symlink().
+
+	   Handling any preexisting directory structure complicates this -
+	   should we temporarily chown/chmod any existing directory to
+	   root:root/S_IRWXU?  That might be very disruptive, and such
+	   structures should not exist in the first place. */
+
+	while ((ent = readdir(dir)) != NULL) {
+		if (strcmp(ent->d_name, ".") == 0
+		    || strcmp(ent->d_name, "..") == 0)
 			continue;
-		}
-		/* Note that we don't copy device specials. */
+
+		/* Build the path of the source file or directory and its
+		   corresponding member in the new tree. */
+		g_string_append_c(src_path_buf, '/');
+		g_string_append(src_path_buf, ent->d_name);
+		g_string_append_c(dest_path_buf, '/');
+		g_string_append(dest_path_buf, ent->d_name);
+
+		if (!copy_dir_entry(src_dir_fd, src_path_buf, dest_dir_fd,
+				    dest_path_buf, ent->d_name, access_options,
+				    error))
+			goto err_dest_dir_fd;
+
+		g_string_truncate(src_path_buf, orig_src_path_buf_len);
+		g_string_truncate(dest_path_buf, orig_dest_path_buf_len);
+	}
+
+	/* Set the ownership on the directory.  Permissions are still
+	   fairly restrictive. */
+	if (fchown(dest_dir_fd, uid_for_copy(access_options, src_dir_stat),
+		   gid_for_copy(access_options, src_dir_stat)) == -1
+	    && errno != EPERM) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error changing owner of `%s': %s"),
+			     dest_path_buf->str, strerror(errno));
+		goto err_dest_dir_fd;
+	}
+
+	/* Set the desired mode.  Do this explicitly to preserve S_ISGID and
+	   other bits.  Do this after chown, because chown is permitted to
+	   reset these bits. */
+	if (fchmod(dest_dir_fd,
+		   mode_for_copy(access_options, src_dir_stat)) == -1) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error setting mode of `%s': %s"),
+			     dest_path_buf->str, strerror(errno));
+		goto err_dest_dir_fd;
 	}
+
+	timebuf[0] = src_dir_stat->st_atim;
+	timebuf[1] = src_dir_stat->st_mtim;
+	futimens(dest_dir_fd, timebuf);
+
 	ret = TRUE;
-	goto err_dir;
+	/* Fall through */
 
- err_ofd:
-	close(ofd);
- err_ifd:
-	close(ifd);
+ err_dest_dir_fd:
+	close(dest_dir_fd);
  err_dir:
 	closedir(dir);
- err:
+	src_dir_fd = -1;
+ err_src_dir_fd:
+	if (src_dir_fd != -1)
+		close(src_dir_fd);
+	g_string_truncate(src_path_buf, orig_src_path_buf_len);
+	g_string_truncate(dest_path_buf, orig_dest_path_buf_len);
 	return ret;
 }
 
-/* Populate a user's home directory, copying data from a named skeleton
-   directory (or default if skeleton is NULL), setting all ownerships as
-   given, and setting the mode of the top-level directory as given. */
-gboolean
-lu_homedir_populate(struct lu_context *ctx, const char *skeleton,
-		    const char *directory, uid_t owner, gid_t group,
-		    mode_t mode, struct lu_error **error)
+/* Copy SRC_DIR to DEST_DIR.  Use ACCESS_OPTIONS.
+
+   Return TRUE on error.
+
+   To be secure, neither SRC_DIR nor DEST_DIR should contain any
+   user-controlled parent directories in the path.  SRC_DIR may be an
+   user-owned directory, or even a symlink, but its parent should not be
+   user-writable (so that the user can't replace it with a symlink or change
+   the symlink). */
+static gboolean
+lu_homedir_copy(const char *src_dir, const char *dest_dir,
+		const struct copy_access_options *access_options,
+		struct lu_error **error)
 {
 	lu_security_context_t fscreate;
+	int fd;
+	struct stat st;
+	GString *src_path_buf, *dest_path_buf;
 	gboolean ret;
 
-	if (skeleton == NULL)
-		skeleton = lu_cfg_read_single(ctx, "defaults/skeleton",
-					      "/etc/skel");
+	LU_ERROR_CHECK(error);
+
 	ret = FALSE;
 	if (!lu_util_fscreate_save(&fscreate, error))
 		goto err;
-	if (!lu_util_fscreate_for_path(directory, S_IFDIR, error))
+
+	fd = open(src_dir, O_RDONLY | O_CLOEXEC | O_DIRECTORY);
+	if (fd == -1) {
+		lu_error_new(error, lu_error_open, _("Error opening `%s': %s"),
+			     src_dir, strerror(errno));
 		goto err_fscreate;
-	ret = lu_homedir_copy(skeleton, directory, owner, group, mode, 0,
-			      current_umask(), error);
+	}
+	if (fstat(fd, &st) == -1) {
+		lu_error_new(error, lu_error_stat, _("couldn't stat `%s': %s"),
+			     src_dir, strerror(errno));
+		goto err_fd;
+	}
+
+	src_path_buf = g_string_new(src_dir);
+	dest_path_buf = g_string_new(dest_dir);
+	ret = lu_copy_dir_and_close(fd, src_path_buf, AT_FDCWD, dest_dir,
+				    dest_path_buf, &st, access_options, error);
+	g_string_free(dest_path_buf, TRUE);
+	g_string_free(src_path_buf, TRUE);
+	goto err_fscreate;
+
+err_fd:
+	close(fd);
 err_fscreate:
 	lu_util_fscreate_restore(fscreate);
 err:
 	return ret;
 }
 
-/* Recursively remove a user's home (or really, any) directory. */
+/**
+ * lu_homedir_populate:
+ * @ctx: A context
+ * @skeleton: Path to a "skeleton" directory, or %NULL for the system default
+ * @directory: The home directory to populate
+ * @owner: UID to use for contents of the new home directory
+ * @group: GID to use for contents of the new home directory that have GID set
+ * to 0 in the skeleton director
+ * @mode: Mode to use for the top-level directory, also affected by umask
+ * @error: Filled with #lu_error if an error occurs
+ *
+ * Creates a new home directory for an user.
+ *
+ * If you want to use this in a hostile environment, ensure that no untrusted
+ * user has write permission to any parent of @skeleton or @directory.  Usually
+ * /home is only writable by root, which is safe.
+ *
+ * Returns: %TRUE on success
+ */
 gboolean
-lu_homedir_remove(const char *directory, struct lu_error ** error)
+lu_homedir_populate(struct lu_context *ctx, const char *skeleton,
+		    const char *directory, uid_t owner, gid_t group,
+		    mode_t mode, struct lu_error **error)
 {
+	struct copy_access_options access_options;
+
+	LU_ERROR_CHECK(error);
+	g_return_val_if_fail(ctx != NULL, FALSE);
+	g_return_val_if_fail(directory != NULL, FALSE);
+
+	if (skeleton == NULL)
+		skeleton = lu_cfg_read_single(ctx, "defaults/skeleton",
+					      "/etc/skel");
+	access_options.preserve_source = FALSE;
+	access_options.ignore_eexist = TRUE;
+	access_options.uid = owner;
+	access_options.gid = group;
+	access_options.umask = current_umask();
+	if (!lu_homedir_copy(skeleton, directory, &access_options, error))
+		return FALSE;
+
+	/* Now reconfigure the toplevel directory as desired.  The directory
+	   thus might have incorrect owner/permissions for a while; this is OK
+	   because the contents are public anyway (every users sees them on
+	   first access), and write access is not allowed because the skeleton
+	   is not writable. */
+
+	/* Set the ownership on the top-level directory manually again,
+	   lu_homedir_copy() would have preserved st.st_gid if it were not root
+	   for some reason; our API promises to use precisely "owner" and
+	   "group". */
+	if (chown(directory, owner, group) == -1 && errno != EPERM) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error changing owner of `%s': %s"), directory,
+			     strerror(errno));
+		return FALSE;
+	}
+	/* Set modes as required instead of preserving st.st_mode.  Do this
+	   after chown, because chown is permitted to reset these bits. */
+	if (chmod(directory, mode & ~access_options.umask) == -1) {
+		lu_error_new(error, lu_error_generic,
+			     _("Error setting mode of `%s': %s"), directory,
+			     strerror(errno));
+		return FALSE;
+	}
+
+	return TRUE;
+}
+
+/* Recursively remove a user's home (or really, any) directory. */
+static gboolean
+remove_subdirectory(int parent_fd, const char *dir_name, GString *path_buf,
+		    struct lu_error **error)
+{
+	size_t orig_path_buf_len;
+	int dir_fd;
 	struct dirent *ent;
 	DIR *dir;
 
 	LU_ERROR_CHECK(error);
+	orig_path_buf_len = path_buf->len;
 
-	/* Open the directory.  This catches the case that it's already gone. */
-	dir = opendir(directory);
+	dir_fd = openat(parent_fd, dir_name,
+			O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
+	if (dir_fd == -1) {
+		lu_error_new(error, lu_error_open,
+			     _("Error opening `%s': %s"), path_buf->str,
+			     strerror(errno));
+		return FALSE;
+	}
+	dir = fdopendir(dir_fd);
 	if (dir == NULL) {
-		lu_error_new(error, lu_error_generic,
-			     _("Error removing `%s': %s"), directory,
+		lu_error_new(error, lu_error_open,
+			     _("Error opening `%s': %s"), path_buf->str,
 			     strerror(errno));
+		close(dir_fd);
 		return FALSE;
 	}
 
 	/* Iterate over all of its contents. */
 	while ((ent = readdir(dir)) != NULL) {
 		struct stat st;
-		char path[PATH_MAX];
 
 		/* Skip over the self and parent hard links. */
-		if (strcmp(ent->d_name, ".") == 0) {
-			continue;
-		}
-		if (strcmp(ent->d_name, "..") == 0) {
+		if (strcmp(ent->d_name, ".") == 0
+		    || strcmp(ent->d_name, "..") == 0)
 			continue;
-		}
 
 		/* Generate the full path of the next victim. */
-		snprintf(path, sizeof(path), "%s/%s", directory, ent->d_name);
+		g_string_append_c(path_buf, '/');
+		g_string_append(path_buf, ent->d_name);
 
 		/* What we do next depends on whether or not the next item to
-		 * remove is a directory. */
-		if (lstat(path, &st) != -1) {
-			if (S_ISDIR(st.st_mode)) {
-				/* We decend into subdirectories... */
-				if (lu_homedir_remove(path, error) == FALSE) {
-					closedir(dir);
-					return FALSE;
-				}
-			} else {
-				/* ... and unlink everything else. */
-				if (unlink(path) == -1) {
-					lu_error_new(error,
-						     lu_error_generic,
-						     _("Error removing "
-						     "`%s': %s"),
-						     path,
-						     strerror
-						     (errno));
-					closedir(dir);
-					return FALSE;
-				}
+		   remove is a directory. */
+		if (fstatat(dir_fd, ent->d_name, &st,
+			    AT_SYMLINK_NOFOLLOW) == -1) {
+			lu_error_new(error, lu_error_stat,
+				     _("couldn't stat `%s': %s"), path_buf->str,
+				     strerror(errno));
+			goto err_dir;
+		}
+		if (S_ISDIR(st.st_mode)) {
+			/* We descend into subdirectories... */
+			if (remove_subdirectory(dir_fd, ent->d_name, path_buf,
+						error) == FALSE)
+				goto err_dir;
+		} else {
+			/* ... and unlink everything else. */
+			if (unlinkat(dir_fd, ent->d_name, 0) == -1) {
+				lu_error_new(error, lu_error_generic,
+					     _("Error removing `%s': %s"),
+					     path_buf->str, strerror(errno));
+				goto err_dir;
 			}
 		}
+
+		g_string_truncate(path_buf, orig_path_buf_len);
 	}
 
 	closedir(dir);
 
 	/* As a final step, remove the directory itself. */
-	if (rmdir(directory) == -1) {
+	if (unlinkat(parent_fd, dir_name, AT_REMOVEDIR) == -1) {
 		lu_error_new(error, lu_error_generic,
-			     _("Error removing `%s': %s"), directory,
+			     _("Error removing `%s': %s"), path_buf->str,
 			     strerror(errno));
 		return FALSE;
 	}
 
 	return TRUE;
+
+err_dir:
+	closedir(dir);
+	g_string_truncate(path_buf, orig_path_buf_len);
+	return FALSE;
+}
+
+/* Recursively remove directory DIR_NAME under PARENT_FD, which corresponds to
+   PATH_BUF.
+
+   Return TRUE on sucess.
+
+   PARENT_FD may be AT_FDCWD.  This function may temporarily modify PATH_BUF,
+   but it will be unchanged on return.
+
+   Note that PATH_BUF should only be used for error messages, not to access
+   the files; if the user is still logged in, a directory in the path may be
+   replaced by a symbolic link, redirecting the access outside of
+   PARENT_FD/DIR_NAME. */
+gboolean
+lu_homedir_remove(const char *directory, struct lu_error ** error)
+{
+	gboolean ret;
+	GString *path_buf;
+
+	LU_ERROR_CHECK(error);
+	g_return_val_if_fail(directory != NULL, FALSE);
+	path_buf = g_string_new(directory);
+	ret = remove_subdirectory(AT_FDCWD, directory, path_buf, error);
+	g_string_free(path_buf, TRUE);
+	return ret;
 }
 
 /* Move a directory from one place to another. */
@@ -444,31 +808,18 @@ gboolean
 lu_homedir_move(const char *oldhome, const char *newhome,
 		struct lu_error ** error)
 {
-	struct stat st;
-	lu_security_context_t fscreate;
+	struct copy_access_options access_options;
 
 	LU_ERROR_CHECK(error);
+	g_return_val_if_fail(oldhome != NULL, FALSE);
+	g_return_val_if_fail(newhome != NULL, FALSE);
 
-	/* If the directory exists... */
-	if (stat(oldhome, &st) != 0)
-		goto err;
+	access_options.preserve_source = TRUE;
+	access_options.ignore_eexist = FALSE;
+	if (!lu_homedir_copy(oldhome, newhome, &access_options, error))
+		return FALSE;
 
-	if (!lu_util_fscreate_save(&fscreate, error))
-		goto err;
-	if (!lu_util_fscreate_from_file(oldhome, error))
-		goto err_fscreate;
-	/* ... and we can copy it ... */
-	if (!lu_homedir_copy(oldhome, newhome, st.st_uid, st.st_gid,
-			     st.st_mode, 1, current_umask(), error))
-		goto err_fscreate;
-	lu_util_fscreate_restore(fscreate);
-	/* ... remove the old one. */
 	return lu_homedir_remove(oldhome, error);
-
-err_fscreate:
-	lu_util_fscreate_restore(fscreate);
-err:
-	return FALSE;
 }
 
 #if 0
diff --git a/apps/lnewusers.c b/apps/lnewusers.c
index a85b377..71d7f0f 100644
--- a/apps/lnewusers.c
+++ b/apps/lnewusers.c
@@ -283,16 +283,6 @@ main(int argc, const char **argv)
 				_("Refusing to use dangerous home directory `%s' "
 				  "for %s by default\n"), homedir, fields[0]);
 		else if (lu_user_add(ctx, ent, &error)) {
-			if (!lu_user_setpass(ctx, ent, fields[1], FALSE,
-					     &error)) {
-				fprintf(stderr,
-					_("Error setting initial password for "
-					  "%s: %s\n"), fields[0],
-					lu_strerror(error));
-				if (error) {
-					lu_error_free(&error);
-				}
-			}
 			lu_nscd_flush_cache("passwd");
 			/* Unless the nocreatehomedirs flag was given, attempt
 			 * to create the user's home directory. */
@@ -317,8 +307,22 @@ main(int argc, const char **argv)
 					fprintf(stderr,
 						_("Error creating mail spool "
 						  "for %s.\n"), fields[0]);
-
 			}
+			/* Set the password after creating the home directory
+			   to prevent the user from seeing an incomplete
+			   home, and to prevent the user from interfering with
+			   the creation of the home directory. */
+			if (!lu_user_setpass(ctx, ent, fields[1], FALSE,
+					     &error)) {
+				fprintf(stderr,
+					_("Error setting initial password for "
+					  "%s: %s\n"), fields[0],
+					lu_strerror(error));
+				if (error) {
+					lu_error_free(&error);
+				}
+			}
+			lu_nscd_flush_cache("passwd");
 		} else {
 			fprintf(stderr,
 				_("Error creating user account for %s: %s\n"),
diff --git a/apps/luseradd.c b/apps/luseradd.c
index 59dd1e2..cb88cee 100644
--- a/apps/luseradd.c
+++ b/apps/luseradd.c
@@ -279,26 +279,6 @@ main(int argc, const char **argv)
 		return 3;
 	}
 
-	if (userPassword != NULL) {
-		if (lu_user_setpass(ctx, ent, userPassword, FALSE, &error)
-		    == FALSE) {
-			fprintf(stderr, _("Error setting password for user "
-					  "%s: %s.\n"), name,
-				lu_strerror(error));
-			return 3;
-		}
-	}
-
-	if (cryptedUserPassword != NULL) {
-		if (lu_user_setpass(ctx, ent, cryptedUserPassword, TRUE,
-				    &error) == FALSE) {
-			fprintf(stderr, _("Error setting password for user "
-					  "%s: %s.\n"), name,
-				lu_strerror(error));
-			return 3;
-		}
-	}
-
         lu_nscd_flush_cache("passwd");
 
 	/* If we don't have the the don't-create-home flag, create the user's
@@ -336,6 +316,29 @@ main(int argc, const char **argv)
 		}
 	}
 
+	/* Set the password after creating the home directory to prevent the
+	   user from seeing an incomplete home, and to prevent the user from
+	   interfering with the creation of the home directory. */
+	if (userPassword != NULL) {
+		if (lu_user_setpass(ctx, ent, userPassword, FALSE, &error)
+		    == FALSE) {
+			fprintf(stderr, _("Error setting password for user "
+					  "%s: %s.\n"), name,
+				lu_strerror(error));
+			return 3;
+		}
+	}
+	if (cryptedUserPassword != NULL) {
+		if (lu_user_setpass(ctx, ent, cryptedUserPassword, TRUE,
+				    &error) == FALSE) {
+			fprintf(stderr, _("Error setting password for user "
+					  "%s: %s.\n"), name,
+				lu_strerror(error));
+			return 3;
+		}
+	}
+	lu_nscd_flush_cache("passwd");
+
 	lu_ent_free(ent);
 
 	lu_end(ctx);
diff --git a/lib/user_private.h b/lib/user_private.h
index 5c11912..be0498f 100644
--- a/lib/user_private.h
+++ b/lib/user_private.h
@@ -320,7 +320,10 @@ typedef security_context_t lu_security_context_t;
 gboolean lu_util_fscreate_save(security_context_t *ctx,
 				      struct lu_error **error);
 void lu_util_fscreate_restore(security_context_t ctx);
+gboolean lu_util_fscreate_from_fd(int fd, const char *path,
+				  struct lu_error **error);
 gboolean lu_util_fscreate_from_file(const char *file, struct lu_error **error);
+gboolean lu_util_fscreate_from_lfile(const char *file, struct lu_error **error);
 gboolean lu_util_fscreate_for_path(const char *path, mode_t mode,
 				   struct lu_error **error);
 
@@ -328,8 +331,12 @@ gboolean lu_util_fscreate_for_path(const char *path, mode_t mode,
 typedef char lu_security_context_t; /* "Something" */
 #define lu_util_fscreate_save(CTX, ERROR) ((void)(CTX), (void)(ERROR), TRUE)
 #define lu_util_fscreate_restore(CTX) ((void)(CTX))
+#define lu_util_fscreate_from_fd(FD, PATH, ERROR) \
+  ((void)(FILE), (void)(PATH), (void)(ERROR), TRUE)
 #define lu_util_fscreate_from_file(FILE, ERROR) \
   ((void)(FILE), (void)(ERROR), TRUE)
+#define lu_util_fscreate_from_lfile(FILE, ERROR) \
+  ((void)(FILE), (void)(ERROR), TRUE)
 #define lu_util_fscreate_for_path(PATH, MODE, ERROR) \
   ((void)(PATH), (void)(MODE), (void)(ERROR), TRUE)
 #endif
diff --git a/lib/util.c b/lib/util.c
index 8a87b55..f717bf8 100644
--- a/lib/util.c
+++ b/lib/util.c
@@ -711,6 +711,32 @@ lu_util_fscreate_restore(security_context_t ctx)
 	}
 }
 
+/* Set fscreate context from context of fd.  Use path only for diagnostics. */
+gboolean
+lu_util_fscreate_from_fd(int fd, const char *path, struct lu_error **error)
+{
+	if (is_selinux_enabled() > 0) {
+		security_context_t ctx;
+
+		if (fgetfilecon(fd, &ctx) < 0) {
+			lu_error_new(error, lu_error_stat,
+				     _("couldn't get security context of "
+				       "`%s': %s"), path, strerror(errno));
+			return FALSE;
+		}
+		if (setfscreatecon(ctx) < 0) {
+			lu_error_new(error, lu_error_generic,
+				     _("couldn't set default security context "
+				       "to `%s': %s"), ctx, strerror(errno));
+			freecon(ctx);
+			return FALSE;
+		}
+		freecon(ctx);
+	}
+	return TRUE;
+}
+
+
 /* Set fscreate context from context of file. */
 gboolean
 lu_util_fscreate_from_file(const char *file, struct lu_error **error)
@@ -736,6 +762,32 @@ lu_util_fscreate_from_file(const char *file, struct lu_error **error)
 	return TRUE;
 }
 
+/* Set fscreate context from context of file, not resolving it if it is a
+   symlink. */
+gboolean
+lu_util_fscreate_from_lfile(const char *file, struct lu_error **error)
+{
+	if (is_selinux_enabled() > 0) {
+		security_context_t ctx;
+
+		if (lgetfilecon(file, &ctx) < 0) {
+			lu_error_new(error, lu_error_stat,
+				     _("couldn't get security context of "
+				       "`%s': %s"), file, strerror(errno));
+			return FALSE;
+		}
+		if (setfscreatecon(ctx) < 0) {
+			lu_error_new(error, lu_error_generic,
+				     _("couldn't set default security context "
+				       "to `%s': %s"), ctx, strerror(errno));
+			freecon(ctx);
+			return FALSE;
+		}
+		freecon(ctx);
+	}
+	return TRUE;
+}
+
 /* Set fscreate context for creating a file at path, with file type specified
    by mode. */
 gboolean
diff --git a/tests/fs.conf.in b/tests/fs.conf.in
new file mode 100644
index 0000000..3991b93
--- /dev/null
+++ b/tests/fs.conf.in
@@ -0,0 +1,24 @@
+[defaults]
+# non-portable
+moduledir = @TOP_BUILDDIR@/modules/.libs
+skeleton = @WORKDIR@/skel
+modules = files shadow
+create_modules = files shadow
+crypt_style = md5
+
+[userdefaults]
+LU_USERNAME = %n
+LU_UIDNUMBER = 500
+LU_GIDNUMBER = %u
+
+[groupdefaults]
+LU_GROUPNAME = %n
+LU_GIDNUMBER = 500
+
+[files]
+directory = @WORKDIR@/files
+nonroot = yes
+
+[shadow]
+directory = @WORKDIR@/files
+nonroot = yes
diff --git a/tests/fs_test b/tests/fs_test
new file mode 100755
index 0000000..4179fc8
--- /dev/null
+++ b/tests/fs_test
@@ -0,0 +1,233 @@
+#! /bin/sh
+# Automated libuser fs function regression tester
+#
+# Copyright (c) 2012 Red Hat, Inc. All rights reserved.
+#
+# This is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Library General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any 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 GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Library 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.
+#
+# Author: Miloslav Trmač <mitr@redhat.com>
+
+srcdir=$srcdir/tests
+
+workdir=$(pwd)/test_fs
+
+umask 002
+
+trap 'status=$?; chmod -R u+rwx "$workdir"; rm -rf "$workdir"; exit $status' 0
+trap '(exit 1); exit 1' 1 2 13 15
+
+rm -rf "$workdir"
+mkdir "$workdir"
+
+# Set up an the environment
+mkdir "$workdir"/files
+> "$workdir"/files/passwd
+> "$workdir"/files/shadow
+> "$workdir"/files/group
+> "$workdir"/files/gshadow
+
+# Set up the client
+LIBUSER_CONF=$workdir/libuser.conf
+export LIBUSER_CONF
+sed "s|@WORKDIR@|$workdir|g; s|@TOP_BUILDDIR@|$(pwd)|g" \
+    < "$srcdir"/fs.conf.in > "$LIBUSER_CONF"
+# Ugly non-portable hacks
+LD_LIBRARY_PATH=$(pwd)/lib/.libs
+export LD_LIBRARY_PATH
+PYTHONPATH=$(pwd)/python/.libs
+export PYTHONPATH
+
+# Test lu_homedir_remove()
+fakeroot > rm_output <<EOF
+# User's "own" content
+mkdir -p "$workdir"/rm/root/{dir,unreadable}
+touch "$workdir"/rm/{kept,root/{dir,unreadable}/f}
+mkfifo "$workdir"/rm/root/fifo
+ln -s ../kept "$workdir"/rm/root/symlink
+chown -R 555:555 "$workdir"/rm/root
+chmod 701 "$workdir"/rm/root
+chmod 000 "$workdir"/rm/root/unreadable
+
+# Other content in the home directory
+mknod "$workdir"/rm/root/block b 1 1
+mknod "$workdir"/rm/root/char c 1 1
+echo 'foo' > "$workdir"/rm/secret
+chmod 000 "$workdir"/rm/secret
+ln "$workdir"/rm/{secret,root/hardlink}
+
+$VALGRIND python "$srcdir"/fs_test.py --remove "$workdir/rm/root"
+if [ \$? -ne 0 ]; then
+   exit 1
+fi
+
+LC_ALL=C ls -lnR "$workdir/rm" | tail -n +3 | \
+	awk '{ printf("%.10s %d %4d %4d %8d %s\n",
+		      \$1, \$2, \$3, \$4, \$5, \$9) ;}'
+
+EOF
+
+diff rm_output - <<EOF
+-rw-rw-r-- 1    0    0        0 kept
+---------- 1    0    0        4 secret
+EOF
+if [ $? -ne 0 ]; then
+    exit 1
+fi
+
+
+# Prepare an "interesting" home directory, to be used both directly and as
+# a skeleton
+fakeroot -s "$workdir"/save <<EOF
+mkdir -p "$workdir"/common/{dir,unreadable,group-owned}
+cd "$workdir"/common
+# User's "own" content
+for i in '.' dir group-owned; do
+    touch "\$i"/f "\$i"/setuid
+    chmod u+xs "\$i"/setuid
+    mkfifo "\$i"/fifo
+    ln -s ../outside "\$i"/symlink
+done
+mkdir setgid
+chmod g+s setgid
+echo 'content' > unreadable/f
+chmod 000 unreadable/f unreadable
+chown -R 555:555 .
+chgrp -R 444 group-owned
+
+# Other content in the home directory
+mknod block b 1 1
+mknod char c 1 1
+echo 'foo' > secret
+chmod 000 secret
+EOF
+
+
+# Test lu_homedir_move()
+fakeroot -i "$workdir"/save -s "$workdir"/save > mv_output <<EOF
+cp -a "$workdir"/common "$workdir"/home1
+# This seems to be a fakeroot bug
+# (https://bugzilla.redhat.com/show_bug.cgi?id=887001) - in the copy, mode-0
+# files are really unreadable in the underlying filesystem.  However, a chmod
+# resets the state.
+chmod 0 "$workdir"/home1/{unreadable,unreadable/f,secret}
+
+$VALGRIND python "$srcdir"/fs_test.py --move "$workdir"/{home1,home2}
+if [ \$? -ne 0 ]; then
+   exit 1
+fi
+
+cd "$workdir"/home2
+LC_ALL=C ls -lnR | \
+	awk 'NF > 3 { printf("%.10s %d %4d %4d %s\n",
+			     \$1, \$2, \$3, \$4, \$9); }
+             NF <= 3 && !/total/ { print }'
+EOF
+
+# Special files and fifos are not copied over.  Ownership and permissions are
+# preserved.
+diff mv_output - <<EOF
+.:
+drwx------ 2  555  555 dir
+-rw------- 1  555  555 f
+drwx------ 2  555  444 group-owned
+---------- 1    0    0 secret
+drwxrwsr-x 2  555  555 setgid
+-rwsrw-r-- 1  555  555 setuid
+lrwxrwxrwx 1  555  555 symlink
+d--------- 2  555  555 unreadable
+
+./dir:
+-rw------- 1  555  555 f
+-rwsrw-r-- 1  555  555 setuid
+lrwxrwxrwx 1  555  555 symlink
+
+./group-owned:
+-rw------- 1  555  444 f
+-rwsrw-r-- 1  555  444 setuid
+lrwxrwxrwx 1  555  444 symlink
+
+./setgid:
+
+./unreadable:
+---------- 1  555  555 f
+EOF
+
+# Moving onto an existing directory is prohibited
+fakeroot > mv2_output 2>&1 <<EOF
+mkdir "$workdir"/mv2home{1,2}
+
+$VALGRIND python "$srcdir"/fs_test.py --move "$workdir"/mv2home{1,2}
+echo \$?
+EOF
+diff mv2_output - <<EOF
+Error creating \`$workdir/mv2home2': File exists
+1
+EOF
+
+
+# Test lu_homedir_populate()
+fakeroot -i "$workdir"/save -s "$workdir"/save > pop_output <<EOF
+cp -a "$workdir"/common "$workdir"/skel
+# This seems to be a fakeroot bug
+# (https://bugzilla.redhat.com/show_bug.cgi?id=887001) - in the copy, mode-0
+# files are really unreadable in the underlying filesystem.  However, a chmod
+# resets the state.
+chmod 0 "$workdir"/skel/{unreadable,unreadable/f,secret}
+chown -R 0:0 "$workdir"/skel
+chgrp -R 444 "$workdir"/skel/group-owned
+
+$VALGRIND python "$srcdir"/fs_test.py --populate "$workdir"/newhome 556 557
+if [ \$? -ne 0 ]; then
+   exit 1
+fi
+
+cd "$workdir"/newhome
+LC_ALL=C ls -lnR | \
+	awk 'NF > 3 { printf("%.10s %d %4d %4d %s\n",
+			     \$1, \$2, \$3, \$4, \$9); }
+             NF <= 3 && !/total/ { print }'
+EOF
+
+# Special files and fifos are not copied over.  Permissions are preserved,
+# ownership is changed to the desired values except for non-root groups
+diff pop_output - <<EOF
+.:
+drwx------ 2  556  557 dir
+-rw------- 1  556  557 f
+drwx------ 2  556  444 group-owned
+---------- 1  556  557 secret
+drwxrwsr-x 2  556  557 setgid
+-rwsrw-r-- 1  556  557 setuid
+lrwxrwxrwx 1  556  557 symlink
+d--------- 2  556  557 unreadable
+
+./dir:
+-rw------- 1  556  557 f
+-rwsrw-r-- 1  556  557 setuid
+lrwxrwxrwx 1  556  557 symlink
+
+./group-owned:
+-rw------- 1  556  444 f
+-rwsrw-r-- 1  556  444 setuid
+lrwxrwxrwx 1  556  444 symlink
+
+./setgid:
+
+./unreadable:
+---------- 1  556  557 f
+EOF
+if [ $? -ne 0 ]; then
+    exit 1
+fi
diff --git a/tests/fs_test.py b/tests/fs_test.py
new file mode 100644
index 0000000..914bc17
--- /dev/null
+++ b/tests/fs_test.py
@@ -0,0 +1,53 @@
+# Helpers for fs_test.
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2012 Red Hat, Inc. All rights reserved.
+#
+# This is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Library General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any 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 GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU Library 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.
+#
+# Author: Miloslav Trmač <mitr@redhat.com>
+
+import libuser
+import sys
+
+def main():
+    if sys.argv[1] == '--remove':
+        a = libuser.admin()
+        u = a.initUser('fs_test_remove')
+        u[libuser.HOMEDIRECTORY] = sys.argv[2]
+        a.removeHome(u)
+    elif sys.argv[1] == '--move':
+        a = libuser.admin()
+        u = a.initUser('fs_test_move')
+        u[libuser.HOMEDIRECTORY] = sys.argv[2]
+        try:
+            a.moveHome(u, sys.argv[3])
+        except RuntimeError, e:
+            sys.exit(str(e))
+    elif sys.argv[1] == '--populate':
+        a = libuser.admin()
+        u = a.initUser('fs_test_populate')
+	u[libuser.HOMEDIRECTORY] = sys.argv[2]
+	u[libuser.UIDNUMBER] = int(sys.argv[3])
+	u[libuser.GIDNUMBER] = int(sys.argv[4])
+        try:
+            a.createHome(u)
+        except RuntimeError, e:
+            sys.exit(str(e))
+    else:
+	sys.exit('Unexpected mode')
+
+if __name__ == '__main__':
+    main()