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
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
|
/*++
Copyright (c) 1991 Microsoft Corporation
Module Name:
SecurSup.c
Abstract:
This module implements the Ntfs Security Support routines
Author:
Gary Kimura [GaryKi] 27-Dec-1991
Revision History:
--*/
#include "NtfsProc.h"
#define Dbg (DEBUG_TRACE_SECURSUP)
#define DbgAcl (DEBUG_TRACE_SECURSUP | DEBUG_TRACE_ACLINDEX)
//
// Define a tag for general pool allocations from this module
//
#undef MODULE_POOL_TAG
#define MODULE_POOL_TAG ('SFtN')
UNICODE_STRING FileString = CONSTANT_UNICODE_STRING( L"File" );
//
// Local procedure prototypes
//
VOID
NtfsLoadSecurityDescriptor (
PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PFCB ParentFcb OPTIONAL
);
VOID
NtfsStoreSecurityDescriptor (
PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN BOOLEAN LogIt
);
#ifdef _CAIRO_
PSHARED_SECURITY
NtOfsFindCachedSharedSecurityBySecurityId (
IN PVCB Vcb,
IN SECURITY_ID SecurityId
);
PSHARED_SECURITY
NtOfsFindCachedSharedSecurityByHash (
IN PVCB Vcb,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG SecurityDescriptorLength,
IN ULONG Hash
);
VOID
NtOfsAddCachedSharedSecurity (
IN PVCB Vcb,
PSHARED_SECURITY SharedSecurity
);
VOID
NtOfsMapSecurityIdToSecurityDescriptor (
IN PIRP_CONTEXT IrpContext,
IN PVCB Vcb,
IN SECURITY_ID SecurityId,
OUT PSECURITY_DESCRIPTOR *SecurityDescriptor,
OUT PULONG SecurityDescriptorLength,
OUT PBCB *Bcb
);
NTSTATUS
NtOfsMatchSecurityHash (
IN PINDEX_ROW IndexRow,
IN OUT PVOID MatchData
);
VOID
NtOfsLookupSecurityDescriptorInIndex (
PIRP_CONTEXT IrpContext,
IN OUT PSHARED_SECURITY SharedSecurity
);
SECURITY_ID
NtOfsGetSecurityIdFromSecurityDescriptor (
PIRP_CONTEXT IrpContext,
IN OUT PSHARED_SECURITY SharedSecurity
);
#endif // _CAIRO_
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, NtfsAccessCheck)
#pragma alloc_text(PAGE, NtfsAssignSecurity)
#pragma alloc_text(PAGE, NtfsCheckFileForDelete)
#pragma alloc_text(PAGE, NtfsCheckIndexForAddOrDelete)
#pragma alloc_text(PAGE, NtfsDereferenceSharedSecurity)
#pragma alloc_text(PAGE, NtfsLoadSecurityDescriptor)
#pragma alloc_text(PAGE, NtfsModifySecurity)
#pragma alloc_text(PAGE, NtfsNotifyTraverseCheck)
#pragma alloc_text(PAGE, NtfsQuerySecurity)
#pragma alloc_text(PAGE, NtfsStoreSecurityDescriptor)
#ifdef _CAIRO_
#pragma alloc_text(PAGE, NtfsInitializeSecurity)
#pragma alloc_text(PAGE, NtfsLoadSecurityDescriptorById)
#pragma alloc_text(PAGE, NtOfsFindCachedSharedSecurityBySecurityId)
#pragma alloc_text(PAGE, NtOfsFindCachedSharedSecurityByHash)
#pragma alloc_text(PAGE, NtOfsAddCachedSharedSecurity)
#pragma alloc_text(PAGE, NtOfsPurgeSecurityCache)
#pragma alloc_text(PAGE, NtOfsMapSecurityIdToSecurityDescriptor)
#pragma alloc_text(PAGE, NtOfsMatchSecurityHash)
#pragma alloc_text(PAGE, NtOfsLookupSecurityDescriptorInIndex)
#pragma alloc_text(PAGE, NtOfsGetSecurityIdFromSecurityDescriptor)
#pragma alloc_text(PAGE, NtOfsCollateSecurityHash)
#endif // _CAIRO_
#endif
VOID
NtfsAssignSecurity (
IN PIRP_CONTEXT IrpContext,
IN PFCB ParentFcb,
IN PIRP Irp,
IN PFCB NewFcb,
IN PFILE_RECORD_SEGMENT_HEADER FileRecord, // BUGBUG delete
IN PBCB FileRecordBcb, // BUGBUG delete
IN LONGLONG FileOffset, // BUGBUG delete
IN OUT PBOOLEAN LogIt // BUGBUG delete
)
/*++
Routine Description:
This routine constructs and assigns a new security descriptor to the
specified file/directory. The new security descriptor is placed both
on the fcb and on the disk.
This will only be called in the context of an open/create operation.
It currently MUST NOT be called to store a security descriptor for
an existing file, because it instructs NtfsStoreSecurityDescriptor
to not log the change.
If this is a large security descriptor then it is possible that
AllocateClusters may be called twice within the call to AddAllocation
when the attribute is created. If so then the second call will always
log the changes. In that case we need to log all of the operations to
create this security attribute and also we must log the current state
of the file record.
It is possible that our caller has already started logging operations against
this log record. In that case we always log the security changes.
Arguments:
ParentFcb - Supplies the directory under which the new fcb exists
Irp - Supplies the Irp being processed
NewFcb - Supplies the fcb that is being assigned a new security descriptor
FileRecord - Supplies the file record for this operation. Used if we
have to log against the file record.
FileRecordBcb - Bcb for the file record above.
FileOffset - File offset in the Mft for this file record.
LogIt - On entry this indicates whether our caller wants this operation
logged. On exit we return TRUE if we logged the security change.
Return Value:
None.
--*/
{
PSECURITY_DESCRIPTOR SecurityDescriptor;
NTSTATUS Status;
BOOLEAN IsDirectory;
PACCESS_STATE AccessState;
PIO_STACK_LOCATION IrpSp;
ULONG SecurityDescLength;
ASSERT_IRP_CONTEXT( IrpContext );
ASSERT_FCB( ParentFcb );
ASSERT_IRP( Irp );
ASSERT_FCB( NewFcb );
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsAssignSecurity...\n") );
//
// First decide if we are creating a file or a directory
//
IrpSp = IoGetCurrentIrpStackLocation(Irp);
if (FlagOn(IrpSp->Parameters.Create.Options, FILE_DIRECTORY_FILE)) {
IsDirectory = TRUE;
} else {
IsDirectory = FALSE;
}
//
// Extract the parts of the Irp that we need to do our assignment
//
AccessState = IrpSp->Parameters.Create.SecurityContext->AccessState;
//
// Check if we need to load the security descriptor for the parent.
//
if (ParentFcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, ParentFcb, NULL );
}
ASSERT( ParentFcb->SharedSecurity != NULL );
//
// Create a new security descriptor for the file and raise if there is
// an error
//
if (!NT_SUCCESS( Status = SeAssignSecurity( &ParentFcb->SharedSecurity->SecurityDescriptor,
AccessState->SecurityDescriptor,
&SecurityDescriptor,
IsDirectory,
&AccessState->SubjectSecurityContext,
IoGetFileObjectGenericMapping(),
PagedPool ))) {
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
//
// Load the security descriptor into the Fcb
//
SecurityDescLength = RtlLengthSecurityDescriptor( SecurityDescriptor );
//
// Make sure the length is non-zero.
//
if (SecurityDescLength == 0) {
SeDeassignSecurity( &SecurityDescriptor );
NtfsRaiseStatus( IrpContext, STATUS_INVALID_PARAMETER, NULL, NULL );
}
ASSERT( SeValidSecurityDescriptor( SecurityDescLength, SecurityDescriptor ));
NtfsUpdateFcbSecurity( IrpContext,
NewFcb,
ParentFcb,
#ifdef _CAIRO_
SECURITY_ID_INVALID,
#endif // _CAIRO_
SecurityDescriptor,
SecurityDescLength );
//
// Free the security descriptor created by Se
//
if (!NT_SUCCESS( Status = SeDeassignSecurity( &SecurityDescriptor ))) {
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
//
// BUGBUG begin section to delete when all volumes are cairo
//
#ifdef _CAIRO_
if (NewFcb->Vcb->SecurityDescriptorStream == NULL) {
#endif
//
// If the security descriptor is large enough that it may cause us to
// start logging in the StoreSecurity call below then make sure everything
// is logged.
//
if (!(LogIt) &&
(SecurityDescLength > BytesFromClusters( NewFcb->Vcb, MAXIMUM_RUNS_AT_ONCE ))) {
//
// Log the current state of the file record.
//
FileRecord->Lsn = NtfsWriteLog( IrpContext,
NewFcb->Vcb->MftScb,
FileRecordBcb,
InitializeFileRecordSegment,
FileRecord,
FileRecord->FirstFreeByte,
Noop,
NULL,
0,
FileOffset,
0,
0,
NewFcb->Vcb->BytesPerFileRecordSegment );
*LogIt = TRUE;
}
#ifdef _CAIRO_
}
#endif // _CAIRO_
//
// BUGBUG end section to delete when all volumes are cairo
//
//
// Write out the new security descriptor
//
NtfsStoreSecurityDescriptor( IrpContext, NewFcb, *LogIt );
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsAssignSecurity -> VOID\n") );
return;
}
NTSTATUS
NtfsModifySecurity (
IN PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PSECURITY_INFORMATION SecurityInformation,
OUT PSECURITY_DESCRIPTOR SecurityDescriptor
)
/*++
Routine Description:
This routine modifies an existing security descriptor for a file/directory.
Arguments:
Fcb - Supplies the Fcb whose security is being modified
SecurityInformation - Supplies the security information structure passed to
the file system by the I/O system.
SecurityDescriptor - Supplies the security information structure passed to
the file system by the I/O system.
Return Value:
NTSTATUS - Returns an appropriate status value for the function results
--*/
{
NTSTATUS Status;
PSECURITY_DESCRIPTOR DescriptorPtr;
ULONG DescriptorLength;
ASSERT_IRP_CONTEXT( IrpContext );
ASSERT_FCB( Fcb );
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsModifySecurity...\n") );
//
// First check if we need to load the security descriptor for the file
//
if (Fcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, Fcb, NULL );
}
ASSERT( Fcb->SharedSecurity != NULL);
DescriptorPtr = &Fcb->SharedSecurity->SecurityDescriptor;
//
// Do the modify operation. SeSetSecurityDescriptorInfo no longer
// frees the passed security descriptor.
//
if (!NT_SUCCESS( Status = SeSetSecurityDescriptorInfo( NULL,
SecurityInformation,
SecurityDescriptor,
&DescriptorPtr,
PagedPool,
IoGetFileObjectGenericMapping() ))) {
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
DescriptorLength = RtlLengthSecurityDescriptor( DescriptorPtr );
//
// Check for a zero length.
//
if (DescriptorLength == 0) {
SeDeassignSecurity( &DescriptorPtr );
NtfsRaiseStatus( IrpContext, STATUS_INVALID_PARAMETER, NULL, NULL );
}
//
// Update the move the quota to the new owner if necessary.
//
NtfsMoveQuotaOwner( IrpContext, Fcb, DescriptorPtr );
NtfsAcquireFcbSecurity( Fcb->Vcb );
NtfsDereferenceSharedSecurity( Fcb );
NtfsReleaseFcbSecurity( Fcb->Vcb );
//
// Load the security descriptor into the Fcb
//
NtfsUpdateFcbSecurity( IrpContext,
Fcb,
NULL,
#ifdef _CAIRO_
SECURITY_ID_INVALID,
#endif // _CAIRO_
DescriptorPtr,
DescriptorLength );
//
// Free the security descriptor created by Se
//
if (!NT_SUCCESS( Status = SeDeassignSecurity( &DescriptorPtr ))) {
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
//
// Now we need to store the new security descriptor on disk
//
NtfsStoreSecurityDescriptor( IrpContext, Fcb, TRUE );
//
// Remember that we modified the security on the file.
//
SetFlag( Fcb->InfoFlags, FCB_INFO_MODIFIED_SECURITY );
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsModifySecurity -> %08lx\n", Status) );
return Status;
}
NTSTATUS
NtfsQuerySecurity (
IN PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PSECURITY_INFORMATION SecurityInformation,
OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OUT PULONG SecurityDescriptorLength
)
/*++
Routine Description:
This routine is used to query the contents of an existing security descriptor for
a file/directory.
Arguments:
Fcb - Supplies the file/directory being queried
SecurityInformation - Supplies the security information structure passed to
the file system by the I/O system.
SecurityDescriptor - Supplies the security information structure passed to
the file system by the I/O system.
SecurityDescriptorLength - Supplies the length of the input security descriptor
buffer in bytes.
Return Value:
NTSTATUS - Returns an appropriate status value for the function results
--*/
{
NTSTATUS Status;
PSECURITY_DESCRIPTOR LocalPointer;
ASSERT_IRP_CONTEXT( IrpContext );
ASSERT_FCB( Fcb );
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsQuerySecurity...\n") );
//
// First check if we need to load the security descriptor for the file
//
if (Fcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, Fcb, NULL );
}
LocalPointer = &Fcb->SharedSecurity->SecurityDescriptor;
//
// Now with the security descriptor loaded do the query operation but
// protect ourselves with a exception handler just in case the caller's
// buffer isn't valid
//
try {
Status = SeQuerySecurityDescriptorInfo( SecurityInformation,
SecurityDescriptor,
SecurityDescriptorLength,
&LocalPointer );
} except(EXCEPTION_EXECUTE_HANDLER) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsQuerySecurity -> %08lx\n", Status) );
return Status;
}
#define NTFS_SE_CONTROL (((SE_DACL_PRESENT | SE_SELF_RELATIVE) << 16) | SECURITY_DESCRIPTOR_REVISION1)
#define NTFS_DEFAULT_ACCESS_MASK 0x001f01ff
ULONG NtfsWorldAclFile[] = {
0x00000000, // Null Sacl
0x00000014, // Dacl
0x001c0002, // Acl header
0x00000001, // One ACE
0x00140000, // ACE Header
NTFS_DEFAULT_ACCESS_MASK,
0x00000101, // World Sid
0x01000000,
0x00000000
};
ULONG NtfsWorldAclDir[] = {
0x00000000, // Null Sacl
0x00000014, // Dacl
0x00300002, // Acl header
0x00000002, // Two ACEs
0x00140000, // ACE Header
NTFS_DEFAULT_ACCESS_MASK,
0x00000101, // World Sid
0x01000000,
0x00000000,
0x00140b00, // ACE Header
NTFS_DEFAULT_ACCESS_MASK,
0x00000101, // World Sid
0x01000000,
0x00000000
};
VOID
NtfsAccessCheck (
PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PFCB ParentFcb OPTIONAL,
IN PIRP Irp,
IN ACCESS_MASK DesiredAccess,
IN BOOLEAN CheckOnly
)
/*++
Routine Description:
This routine does a general access check for the indicated desired access.
This will only be called in the context of an open/create operation.
If access is granted then control is returned to the caller
otherwise this function will do the proper Nt security calls to log
the attempt and then raise an access denied status.
Arguments:
Fcb - Supplies the file/directory being examined
ParentFcb - Optionally supplies the parent of the Fcb being examined
Irp - Supplies the Irp being processed
DesiredAccess - Supplies a mask of the access being requested
CheckOnly - Indicates if this operation is to check the desired access
only and not accumulate the access granted here. In this case we
are guaranteed that we have passed in a hard-wired desired access
and MAXIMUM_ALLOWED will not be one of them.
Return Value:
None.
--*/
{
NTSTATUS Status;
NTSTATUS AccessStatus;
NTSTATUS AccessStatusError;
PACCESS_STATE AccessState;
PIO_STACK_LOCATION IrpSp;
BOOLEAN AccessGranted;
ACCESS_MASK GrantedAccess;
PISECURITY_DESCRIPTOR SecurityDescriptor;
PPRIVILEGE_SET Privileges;
PUNICODE_STRING FileName;
PUNICODE_STRING RelatedFileName;
PUNICODE_STRING PartialFileName;
UNICODE_STRING FullFileName;
PUNICODE_STRING DeviceObjectName;
USHORT DeviceObjectNameLength;
BOOLEAN LeadingSlash;
BOOLEAN RelatedFileNamePresent;
BOOLEAN PartialFileNamePresent;
BOOLEAN MaximumRequested;
BOOLEAN MaximumDeleteAcquired;
BOOLEAN MaximumReadAttrAcquired;
BOOLEAN PerformAccessValidation;
BOOLEAN PerformDeleteAudit;
ASSERT_IRP_CONTEXT( IrpContext );
ASSERT_FCB( Fcb );
ASSERT_IRP( Irp );
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsAccessCheck...\n") );
//
// First extract the parts of the Irp that we need to do our checking
//
IrpSp = IoGetCurrentIrpStackLocation(Irp);
AccessState = IrpSp->Parameters.Create.SecurityContext->AccessState;
//
// Check if we need to load the security descriptor for the file
//
if (Fcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, Fcb, ParentFcb );
}
ASSERT( Fcb->SharedSecurity != NULL );
SecurityDescriptor = (PISECURITY_DESCRIPTOR) Fcb->SharedSecurity->SecurityDescriptor;
//
// Check to see if auditing is enabled and if this is the default world ACL.
//
if (*((PULONG) SecurityDescriptor) == NTFS_SE_CONTROL &&
!SeAuditingFileEvents( TRUE, SecurityDescriptor )) {
// Directories and files have different default ACLs.
if (((Fcb->Info.FileAttributes & DUP_FILE_NAME_INDEX_PRESENT) &&
RtlEqualMemory(
&SecurityDescriptor->Sacl,
NtfsWorldAclDir,
sizeof(NtfsWorldAclDir))) ||
RtlEqualMemory(
&SecurityDescriptor->Sacl,
NtfsWorldAclFile,
sizeof(NtfsWorldAclFile))) {
if (FlagOn( DesiredAccess, MAXIMUM_ALLOWED )) {
GrantedAccess = NTFS_DEFAULT_ACCESS_MASK;
} else {
GrantedAccess = DesiredAccess & NTFS_DEFAULT_ACCESS_MASK;
}
if (!CheckOnly) {
SetFlag( AccessState->PreviouslyGrantedAccess, GrantedAccess );
ClearFlag( AccessState->RemainingDesiredAccess, (GrantedAccess | MAXIMUM_ALLOWED) );
}
return;
}
}
Privileges = NULL;
FileName = NULL;
RelatedFileName = NULL;
PartialFileName = NULL;
DeviceObjectName = NULL;
MaximumRequested = FALSE;
MaximumDeleteAcquired = FALSE;
MaximumReadAttrAcquired = FALSE;
PerformAccessValidation = TRUE;
PerformDeleteAudit = FALSE;
//
// Check to see if we need to perform access validation
//
ClearFlag( DesiredAccess, AccessState->PreviouslyGrantedAccess );
if (DesiredAccess == 0) {
//
// Nothing to check, skip AVR and go straight to auditing
//
PerformAccessValidation = FALSE;
AccessGranted = TRUE;
}
//
// Remember the case where MAXIMUM_ALLOWED was requested.
//
if (FlagOn( DesiredAccess, MAXIMUM_ALLOWED )) {
MaximumRequested = TRUE;
}
if (FlagOn(IrpSp->Parameters.Create.SecurityContext->FullCreateOptions,FILE_DELETE_ON_CLOSE)) {
PerformDeleteAudit = TRUE;
}
//
// Lock the user context, do the access check and then unlock the context
//
SeLockSubjectContext( &AccessState->SubjectSecurityContext );
if (PerformAccessValidation) {
AccessGranted = SeAccessCheck( &Fcb->SharedSecurity->SecurityDescriptor,
&AccessState->SubjectSecurityContext,
TRUE, // Tokens are locked
DesiredAccess,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&GrantedAccess,
&AccessStatus );
if (Privileges != NULL) {
Status = SeAppendPrivileges( AccessState, Privileges );
SeFreePrivileges( Privileges );
}
if (AccessGranted) {
ClearFlag( DesiredAccess, GrantedAccess | MAXIMUM_ALLOWED );
if (!CheckOnly) {
SetFlag( AccessState->PreviouslyGrantedAccess, GrantedAccess );
//
// Remember the case where MAXIMUM_ALLOWED was requested and we
// got everything requested from the file.
//
if (MaximumRequested) {
//
// Check whether we got DELETE and READ_ATTRIBUTES. Otherwise
// we will query the parent.
//
if (FlagOn( AccessState->PreviouslyGrantedAccess, DELETE )) {
MaximumDeleteAcquired = TRUE;
}
if (FlagOn( AccessState->PreviouslyGrantedAccess, FILE_READ_ATTRIBUTES )) {
MaximumReadAttrAcquired = TRUE;
}
}
ClearFlag( AccessState->RemainingDesiredAccess, (GrantedAccess | MAXIMUM_ALLOWED) );
}
} else {
AccessStatusError = AccessStatus;
}
//
// Check if the access is not granted and if we were given a parent fcb, and
// if the desired access was asking for delete or file read attributes. If so
// then we need to do some extra work to decide if the caller does get access
// based on the parent directories security descriptor. We also do the same
// work if MAXIMUM_ALLOWED was requested and we didn't get DELETE or
// FILE_READ_ATTRIBUTES.
//
if ((ParentFcb != NULL)
&& ((!AccessGranted && FlagOn( DesiredAccess, DELETE | FILE_READ_ATTRIBUTES ))
|| (MaximumRequested
&& (!MaximumDeleteAcquired || !MaximumReadAttrAcquired)))) {
BOOLEAN DeleteAccessGranted = TRUE;
BOOLEAN ReadAttributesAccessGranted = TRUE;
ACCESS_MASK DeleteChildGrantedAccess = 0;
ACCESS_MASK ListDirectoryGrantedAccess = 0;
//
// Before we proceed load in the parent security descriptor
//
if (ParentFcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, ParentFcb, NULL );
}
ASSERT( ParentFcb->SharedSecurity != NULL);
//
// Now if the user is asking for delete access then check if the parent
// will granted delete access to the child, and if so then we munge the
// desired access
//
if (FlagOn( DesiredAccess, DELETE )
|| (MaximumRequested && !MaximumDeleteAcquired)) {
DeleteAccessGranted = SeAccessCheck( &ParentFcb->SharedSecurity->SecurityDescriptor,
&AccessState->SubjectSecurityContext,
TRUE, // Tokens are locked
FILE_DELETE_CHILD,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&DeleteChildGrantedAccess,
&AccessStatus );
if (Privileges != NULL) { SeFreePrivileges( Privileges ); }
if (DeleteAccessGranted) {
SetFlag( DeleteChildGrantedAccess, DELETE );
ClearFlag( DeleteChildGrantedAccess, FILE_DELETE_CHILD );
ClearFlag( DesiredAccess, DELETE );
} else {
AccessStatusError = AccessStatus;
}
}
//
// Do the same test for read attributes and munge the desired access
// as appropriate
//
if (FlagOn(DesiredAccess, FILE_READ_ATTRIBUTES)
|| (MaximumRequested && !MaximumReadAttrAcquired)) {
ReadAttributesAccessGranted = SeAccessCheck( &ParentFcb->SharedSecurity->SecurityDescriptor,
&AccessState->SubjectSecurityContext,
TRUE, // Tokens are locked
FILE_LIST_DIRECTORY,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&ListDirectoryGrantedAccess,
&AccessStatus );
if (Privileges != NULL) { SeFreePrivileges( Privileges ); }
if (ReadAttributesAccessGranted) {
SetFlag( ListDirectoryGrantedAccess, FILE_READ_ATTRIBUTES );
ClearFlag( ListDirectoryGrantedAccess, FILE_LIST_DIRECTORY );
ClearFlag( DesiredAccess, FILE_READ_ATTRIBUTES );
} else {
AccessStatusError = AccessStatus;
}
}
if (DesiredAccess == 0) {
//
// If we got either the delete or list directory access then
// grant access.
//
if (ListDirectoryGrantedAccess != 0 ||
DeleteChildGrantedAccess != 0) {
AccessGranted = TRUE;
}
} else {
//
// Now the desired access has been munged by removing everything the parent
// has granted so now do the check on the child again
//
AccessGranted = SeAccessCheck( &Fcb->SharedSecurity->SecurityDescriptor,
&AccessState->SubjectSecurityContext,
TRUE, // Tokens are locked
DesiredAccess,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&GrantedAccess,
&AccessStatus );
if (Privileges != NULL) {
Status = SeAppendPrivileges( AccessState, Privileges );
SeFreePrivileges( Privileges );
}
//
// Suppose that we asked for MAXIMUM_ALLOWED and no access was allowed
// on the file. In that case the call above would fail. It's possible
// that we were given DELETE or READ_ATTR permission from the
// parent directory. If we have granted any access and the only remaining
// desired access is MAXIMUM_ALLOWED then grant this access.
//
if (!AccessGranted) {
AccessStatusError = AccessStatus;
if (DesiredAccess == MAXIMUM_ALLOWED &&
(ListDirectoryGrantedAccess != 0 ||
DeleteChildGrantedAccess != 0)) {
GrantedAccess = 0;
AccessGranted = TRUE;
}
}
}
//
// If we are given access this time then by definition one of the earlier
// parent checks had to have succeeded, otherwise we would have failed again
// and we can update the access state
//
if (!CheckOnly && AccessGranted) {
SetFlag( AccessState->PreviouslyGrantedAccess,
(GrantedAccess | DeleteChildGrantedAccess | ListDirectoryGrantedAccess) );
ClearFlag( AccessState->RemainingDesiredAccess,
(GrantedAccess | MAXIMUM_ALLOWED | DeleteChildGrantedAccess | ListDirectoryGrantedAccess) );
}
}
}
//
// Now call a routine that will do the proper open audit/alarm work
//
// **** We need to expand the audit alarm code to deal with
// create and traverse alarms.
//
//
// First we take a shortcut and see if we should bother setting up
// and making the audit call.
//
//
// NOTE: Calling SeAuditingFileEvents below disables per-user auditing functionality.
// To make per-user auditing work again, it is necessary to change the call below to
// be SeAuditingFileOrGlobalEvents, which also takes the subject context.
//
// The reason for calling SeAuditingFileEvents here is because per-user auditing is
// not currently exposed to users, and this routine imposes less of a performance
// penalty than does calling SeAuditingFileOrGlobalEvents.
//
if (SeAuditingFileEvents( AccessGranted, &Fcb->SharedSecurity->SecurityDescriptor )) {
BOOLEAN Found;
ATTRIBUTE_ENUMERATION_CONTEXT Context;
PFILE_NAME FileNameAttr;
UNICODE_STRING FileRecordName;
NtfsInitializeAttributeContext( &Context );
try {
//
// Construct the file name. The file name
// consists of:
//
// The device name out of the Vcb +
//
// The contents of the filename in the File Object +
//
// The contents of the Related File Object if it
// is present and the name in the File Object
// does not start with a '\'
//
//
// Obtain the file name.
//
PartialFileName = &IrpSp->FileObject->FileName;
PartialFileNamePresent = (PartialFileName->Length != 0);
if (!PartialFileNamePresent &&
FlagOn(IrpSp->Parameters.Create.Options, FILE_OPEN_BY_FILE_ID) ||
(IrpSp->FileObject->RelatedFileObject != NULL &&
IrpSp->FileObject->RelatedFileObject->FsContext2 != NULL &&
FlagOn(((PCCB) IrpSp->FileObject->RelatedFileObject->FsContext2)->Flags,
CCB_FLAG_OPEN_BY_FILE_ID))) {
//
// If this file is open by id or the relative file object is
// then get the first file name out of the file record.
//
Found = NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$FILE_NAME,
&Context );
while (Found) {
FileNameAttr = (PFILE_NAME) NtfsAttributeValue(
NtfsFoundAttribute( &Context ));
if (FileNameAttr->Flags != FILE_NAME_DOS) {
FileRecordName.Length = FileNameAttr->FileNameLength *
sizeof(WCHAR);
FileRecordName.MaximumLength = FileRecordName.Length;
FileRecordName.Buffer = FileNameAttr->FileName;
PartialFileNamePresent = TRUE;
PartialFileName = &FileRecordName;
break;
}
Found = NtfsLookupNextAttributeByCode( IrpContext,
Fcb,
$FILE_NAME,
&Context );
}
}
//
// Obtain the device name.
//
DeviceObjectName = &Fcb->Vcb->DeviceName;
DeviceObjectNameLength = DeviceObjectName->Length;
//
// Compute how much space we need for the final name string
//
FullFileName.MaximumLength = DeviceObjectNameLength +
PartialFileName->Length +
sizeof( UNICODE_NULL ) +
sizeof((WCHAR)'\\');
//
// If the partial file name starts with a '\', then don't use
// whatever may be in the related file name.
//
if (PartialFileNamePresent &&
((WCHAR)(PartialFileName->Buffer[0]) == L'\\' ||
PartialFileName == &FileRecordName)) {
LeadingSlash = TRUE;
} else {
//
// Since PartialFileName either doesn't exist or doesn't
// start with a '\', examine the RelatedFileName to see
// if it exists.
//
LeadingSlash = FALSE;
if (IrpSp->FileObject->RelatedFileObject != NULL) {
RelatedFileName = &IrpSp->FileObject->RelatedFileObject->FileName;
}
if (RelatedFileNamePresent = ((RelatedFileName != NULL) && (RelatedFileName->Length != 0))) {
FullFileName.MaximumLength += RelatedFileName->Length;
}
}
FullFileName.Buffer = NtfsAllocatePool(PagedPool, FullFileName.MaximumLength );
} finally {
NtfsCleanupAttributeContext( &Context );
if (AbnormalTermination()) {
SeUnlockSubjectContext( &AccessState->SubjectSecurityContext );
}
}
RtlCopyUnicodeString( &FullFileName, DeviceObjectName );
//
// RelatedFileNamePresent is not initialized if LeadingSlash == TRUE,
// but in that case we won't even examine it.
//
if (!LeadingSlash && RelatedFileNamePresent) {
Status = RtlAppendUnicodeStringToString( &FullFileName, RelatedFileName );
ASSERTMSG("RtlAppendUnicodeStringToString of RelatedFileName", NT_SUCCESS( Status ));
//
// RelatedFileName may simply be '\'. Don't append another
// '\' in this case.
//
if (RelatedFileName->Length != sizeof( WCHAR )) {
FullFileName.Buffer[ (FullFileName.Length / sizeof( WCHAR )) ] = L'\\';
FullFileName.Length += sizeof(WCHAR);
}
}
if (PartialFileNamePresent) {
Status = RtlAppendUnicodeStringToString( &FullFileName, PartialFileName );
//
// This should not fail
//
ASSERTMSG("RtlAppendUnicodeStringToString of PartialFileName failed", NT_SUCCESS( Status ));
}
if (PerformDeleteAudit) {
SeOpenObjectForDeleteAuditAlarm( &FileString,
NULL,
&FullFileName,
&Fcb->SharedSecurity->SecurityDescriptor,
AccessState,
FALSE,
AccessGranted,
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&AccessState->GenerateOnClose );
} else {
SeOpenObjectAuditAlarm( &FileString,
NULL,
&FullFileName,
&Fcb->SharedSecurity->SecurityDescriptor,
AccessState,
FALSE,
AccessGranted,
(KPROCESSOR_MODE)(FlagOn(IrpSp->Flags, SL_FORCE_ACCESS_CHECK) ?
UserMode : Irp->RequestorMode),
&AccessState->GenerateOnClose );
}
NtfsFreePool( FullFileName.Buffer );
}
SeUnlockSubjectContext( &AccessState->SubjectSecurityContext );
//
// If access is not granted then we will raise
//
if (!AccessGranted) {
DebugTrace( 0, Dbg, ("Access Denied\n") );
NtfsRaiseStatus( IrpContext, AccessStatusError, NULL, NULL );
}
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsAccessCheck -> VOID\n") );
return;
}
NTSTATUS
NtfsCheckFileForDelete (
IN PIRP_CONTEXT IrpContext,
IN PSCB ParentScb,
IN PFCB ThisFcb,
IN BOOLEAN FcbExisted,
IN PINDEX_ENTRY IndexEntry
)
/*++
Routine Description:
This routine checks that the caller has permission to delete the target
file of a rename or set link operation.
Arguments:
ParentScb - This is the parent directory for this file.
ThisFcb - This is the Fcb for the link being removed.
FcbExisted - Indicates if this Fcb was just created.
IndexEntry - This is the index entry on the disk for this file.
Return Value:
NTSTATUS - Indicating whether access was granted or the reason access
was denied.
--*/
{
UNICODE_STRING LastComponentFileName;
PFILE_NAME IndexFileName;
PLCB ThisLcb;
PFCB ParentFcb = ParentScb->Fcb;
PSCB NextScb = NULL;
BOOLEAN LcbExisted;
BOOLEAN AccessGranted;
ACCESS_MASK GrantedAccess;
NTSTATUS Status = STATUS_SUCCESS;
BOOLEAN UnlockSubjectContext = FALSE;
PPRIVILEGE_SET Privileges = NULL;
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsCheckFileForDelete: Entered\n") );
ThisLcb = NULL;
IndexFileName = (PFILE_NAME) NtfsFoundIndexEntry( IndexEntry );
//
// If the unclean count is non-zero, we exit with an error.
//
if (ThisFcb->CleanupCount != 0) {
DebugTrace( 0, Dbg, ("Unclean count of target is non-zero\n") );
return STATUS_ACCESS_DENIED;
}
//
// We look at the index entry to see if the file is either a directory
// or a read-only file. We can't delete this for a target directory open.
//
if (IsDirectory( &ThisFcb->Info )
|| IsReadOnly( &ThisFcb->Info )) {
DebugTrace( -1, Dbg, ("NtfsCheckFileForDelete: Read only or directory\n") );
return STATUS_ACCESS_DENIED;
}
//
// We want to scan through all of the Scb for data streams on this file
// and look for image sections. We must be able to remove the image section
// in order to delete the file. Otherwise we can get the case where an
// active image (with no handle) could be deleted and subsequent faults
// through the image section will return zeroes.
//
if (ThisFcb->LinkCount == 1) {
BOOLEAN DecrementScb = FALSE;
//
// We will increment the Scb count to prevent this Scb from going away
// if the flush call below generates a close. Use a try-finally to
// restore the count.
//
try {
while ((NextScb = NtfsGetNextChildScb( ThisFcb, NextScb )) != NULL) {
InterlockedIncrement( &NextScb->CloseCount );
DecrementScb = TRUE;
if (NtfsIsTypeCodeUserData( NextScb->AttributeTypeCode ) &&
!FlagOn( NextScb->ScbState, SCB_STATE_ATTRIBUTE_DELETED ) &&
(NextScb->NonpagedScb->SegmentObject.ImageSectionObject != NULL)) {
if (!MmFlushImageSection( &NextScb->NonpagedScb->SegmentObject,
MmFlushForDelete )) {
Status = STATUS_ACCESS_DENIED;
leave;
}
}
InterlockedDecrement( &NextScb->CloseCount );
DecrementScb = FALSE;
}
} finally {
if (DecrementScb) {
InterlockedDecrement( &NextScb->CloseCount );
}
}
if (Status != STATUS_SUCCESS) {
return Status;
}
}
//
// We need to check if the link to this file has been deleted. We
// first check if we definitely know if the link is deleted by
// looking at the file name flags and the Fcb flags.
// If that result is uncertain, we need to create an Lcb and
// check the Lcb flags.
//
if (FcbExisted) {
if (FlagOn( IndexFileName->Flags, FILE_NAME_NTFS | FILE_NAME_DOS )) {
if (FlagOn( ThisFcb->FcbState, FCB_STATE_PRIMARY_LINK_DELETED )) {
DebugTrace( -1, Dbg, ("NtfsCheckFileForDelete: Link is going away\n") );
return STATUS_DELETE_PENDING;
}
//
// This is a Posix link. We need to create the link to test it
// for deletion.
//
} else {
LastComponentFileName.MaximumLength
= LastComponentFileName.Length = IndexFileName->FileNameLength * sizeof( WCHAR );
LastComponentFileName.Buffer = (PWCHAR) IndexFileName->FileName;
ThisLcb = NtfsCreateLcb( IrpContext,
ParentScb,
ThisFcb,
LastComponentFileName,
IndexFileName->Flags,
&LcbExisted );
if (FlagOn( ThisLcb->LcbState, LCB_STATE_DELETE_ON_CLOSE )) {
DebugTrace( -1, Dbg, ("NtfsCheckFileForDelete: Link is going away\n") );
return STATUS_DELETE_PENDING;
}
}
}
//
// Finally call the security package to check for delete access.
// We check for delete access on the target Fcb. If this succeeds, we
// are done. Otherwise we will check for delete child access on the
// the parent. Either is sufficient to perform the delete.
//
//
// Check if we need to load the security descriptor for the file
//
if (ThisFcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, ThisFcb, ParentFcb );
}
ASSERT( ThisFcb->SharedSecurity != NULL );
//
// Use a try-finally to facilitate cleanup.
//
try {
//
// Lock the user context, do the access check and then unlock the context
//
SeLockSubjectContext( IrpContext->Union.SubjectContext );
UnlockSubjectContext = TRUE;
AccessGranted = SeAccessCheck( &ThisFcb->SharedSecurity->SecurityDescriptor,
IrpContext->Union.SubjectContext,
TRUE, // Tokens are locked
DELETE,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
UserMode,
&GrantedAccess,
&Status );
//
// Check if the access is not granted and if we were given a parent fcb, and
// if the desired access was asking for delete or file read attributes. If so
// then we need to do some extra work to decide if the caller does get access
// based on the parent directories security descriptor
//
if (!AccessGranted) {
//
// Before we proceed load in the parent security descriptor
//
if (ParentFcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, ParentFcb, NULL );
}
ASSERT( ParentFcb->SharedSecurity != NULL);
//
// Now if the user is asking for delete access then check if the parent
// will granted delete access to the child, and if so then we munge the
// desired access
//
AccessGranted = SeAccessCheck( &ParentFcb->SharedSecurity->SecurityDescriptor,
IrpContext->Union.SubjectContext,
TRUE, // Tokens are locked
FILE_DELETE_CHILD,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
UserMode,
&GrantedAccess,
&Status );
}
} finally {
DebugUnwind( NtfsCheckFileForDelete );
if (UnlockSubjectContext) {
SeUnlockSubjectContext( IrpContext->Union.SubjectContext );
}
DebugTrace( +1, Dbg, ("NtfsCheckFileForDelete: Exit\n") );
}
return Status;
}
VOID
NtfsCheckIndexForAddOrDelete (
IN PIRP_CONTEXT IrpContext,
IN PFCB ParentFcb,
IN ACCESS_MASK DesiredAccess
)
/*++
Routine Description:
This routine checks if a caller has permission to remove or add a link
within a directory.
Arguments:
ParentFcb - This is the parent directory for the add or delete operation.
DesiredAccess - Indicates the type of operation. We could be adding or
removing and entry in the index.
Return Value:
None - This routine raises on error.
--*/
{
BOOLEAN AccessGranted;
ACCESS_MASK GrantedAccess;
NTSTATUS Status;
BOOLEAN UnlockSubjectContext = FALSE;
PPRIVILEGE_SET Privileges = NULL;
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsCheckIndexForAddOrDelete: Entered\n") );
//
// Use a try-finally to facilitate cleanup.
//
try {
//
// Finally call the security package to check for delete access.
// We check for delete access on the target Fcb. If this succeeds, we
// are done. Otherwise we will check for delete child access on the
// the parent. Either is sufficient to perform the delete.
//
//
// Check if we need to load the security descriptor for the file
//
if (ParentFcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, ParentFcb, NULL );
}
ASSERT( ParentFcb->SharedSecurity != NULL );
//
// Capture and lock the user context, do the access check and then unlock the context
//
SeLockSubjectContext( IrpContext->Union.SubjectContext );
UnlockSubjectContext = TRUE;
AccessGranted = SeAccessCheck( &ParentFcb->SharedSecurity->SecurityDescriptor,
IrpContext->Union.SubjectContext,
TRUE, // Tokens are locked
DesiredAccess,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
UserMode,
&GrantedAccess,
&Status );
//
// If access is not granted then we will raise
//
if (!AccessGranted) {
DebugTrace( 0, Dbg, ("Access Denied\n") );
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
} finally {
DebugUnwind( NtfsCheckIndexForAddOrDelete );
if (UnlockSubjectContext) {
SeUnlockSubjectContext( IrpContext->Union.SubjectContext );
}
DebugTrace( +1, Dbg, ("NtfsCheckIndexForAddOrDelete: Exit\n") );
}
return;
}
VOID
NtfsUpdateFcbSecurity (
IN PIRP_CONTEXT IrpContext,
IN OUT PFCB Fcb,
IN PFCB ParentFcb OPTIONAL,
#ifdef _CAIRO_
IN SECURITY_ID SecurityId,
#endif // _CAIRO_
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG SecurityDescriptorLength
)
/*++
Routine Description:
This routine is called to fill in the shared security structure in
an Fcb. We check the parent if present to determine if we have
a matching security descriptor and reference the existing one if
so. This routine must be called while holding the Vcb so we can
safely access the parent structure.
Arguments:
Fcb - Supplies the fcb for the file being operated on
ParentFcb - Optionally supplies a parent Fcb to examine for a
match. If not present, we will follow the Lcb chain in the target
Fcb.
SecurityDescriptor - Security Descriptor for this file.
SecurityDescriptorLength - Length of security descriptor for this file
Return Value:
None.
--*/
{
PSHARED_SECURITY SharedSecurity = NULL;
PLCB ParentLcb;
PFCB LastParent = NULL;
#ifdef _CAIRO_
ULONG Hash = 0;
#endif // _CAIRO_
PAGED_CODE();
//
// Only continue with the load if the length is greater than zero
//
if (SecurityDescriptorLength == 0) {
return;
}
//
// Make sure the security descriptor we just read in is valid
//
if (!SeValidSecurityDescriptor( SecurityDescriptorLength, SecurityDescriptor )) {
SecurityDescriptor = NtfsData.DefaultDescriptor;
SecurityDescriptorLength = NtfsData.DefaultDescriptorLength;
if (!SeValidSecurityDescriptor( SecurityDescriptorLength, SecurityDescriptor )) {
NtfsRaiseStatus( IrpContext, STATUS_FILE_CORRUPT_ERROR, NULL, Fcb );
}
}
#ifdef _CAIRO_
//
// Hash security descriptor. This hash must be position independent to
// allow for multiple instances of the same descriptor. It is assumed
// that the bits within the security descriptor are all position
// independent, i.e, no pointers, all offsets.
//
// For speed in the hash, we consider the security descriptor as an array
// of ULONGs. The fragment at the end that is ignored should not affect
// the collision nature of this hash.
//
{
PULONG Rover = (PULONG)SecurityDescriptor;
ULONG Count = SecurityDescriptorLength / 4;
while (Count--)
{
Hash = ((Hash << 3) | (Hash >> (32-3))) + *Rover++;
}
DebugTrace( 0, Dbg, ("Hash is %08x\n", Hash) );
}
#endif // _CAIRO_
//
// Acquire the security event and use a try-finally to insure we release it.
//
NtfsAcquireFcbSecurity( Fcb->Vcb );
try {
//
// BUGBUG - since we have a cache based on a hash of security ID's, can
// we just skip this walk altogether?
//
//
// If we have a parent then check if this is a matching descriptor.
//
if (!ARGUMENT_PRESENT( ParentFcb )
&& !IsListEmpty( &Fcb->LcbQueue )) {
ParentLcb = CONTAINING_RECORD( Fcb->LcbQueue.Flink,
LCB,
FcbLinks );
if (ParentLcb != Fcb->Vcb->RootLcb) {
ParentFcb = ParentLcb->Scb->Fcb;
}
}
if (ParentFcb != NULL) {
while (TRUE) {
PSHARED_SECURITY NextSharedSecurity;
//
// If the target Fcb is an Index then use the security descriptor for
// our parent. Otherwise use the descriptor for a file on the drive.
//
if (FlagOn( Fcb->Info.FileAttributes, DUP_FILE_NAME_INDEX_PRESENT )) {
NextSharedSecurity = ParentFcb->SharedSecurity;
} else {
NextSharedSecurity = ParentFcb->ChildSharedSecurity;
}
if (NextSharedSecurity != NULL) {
if (GetSharedSecurityLength(NextSharedSecurity) == SecurityDescriptorLength
#ifdef _CAIRO_
&& NextSharedSecurity->Header.HashKey.Hash == Hash
#endif // _CAIRO_
&& RtlEqualMemory( &NextSharedSecurity->SecurityDescriptor,
SecurityDescriptor,
SecurityDescriptorLength )) {
SharedSecurity = NextSharedSecurity;
}
break;
}
LastParent = ParentFcb;
if (!IsListEmpty( &ParentFcb->LcbQueue )) {
ParentLcb = CONTAINING_RECORD( ParentFcb->LcbQueue.Flink,
LCB,
FcbLinks );
if (ParentLcb != Fcb->Vcb->RootLcb) {
ParentFcb = ParentLcb->Scb->Fcb;
} else {
break;
}
} else {
break;
}
}
}
#ifdef _CAIRO_
//
// If we havent't found the security descriptor by walking up the tree then
// try to find it by hash
//
SharedSecurity =
NtOfsFindCachedSharedSecurityByHash( Fcb->Vcb,
SecurityDescriptor,
SecurityDescriptorLength,
Hash );
#endif
//
// If we can't find an existing descriptor allocate new pool and copy
// security descriptor into it.
//
if (SharedSecurity == NULL) {
SharedSecurity = NtfsAllocatePool(PagedPool, FIELD_OFFSET( SHARED_SECURITY,
SecurityDescriptor )
+ SecurityDescriptorLength );
//
// If this is a file and we have a Parent Fcb without a child
// descriptor we will store this one with that directory.
//
if (!FlagOn( Fcb->Info.FileAttributes, DUP_FILE_NAME_INDEX_PRESENT )
&& LastParent != NULL) {
SharedSecurity->ParentFcb = LastParent;
ASSERT( LastParent->ChildSharedSecurity == NULL );
LastParent->ChildSharedSecurity = SharedSecurity;
LastParent->ChildSharedSecurity->ReferenceCount = 1;
} else {
SharedSecurity->ParentFcb = NULL;
SharedSecurity->ReferenceCount = 0;
}
#ifdef _CAIRO_
//
// Initialize security index data in shared security
//
//
// Set the security id in the shared structure. If it is not
// invalid, also cache this shared security structure
//
SharedSecurity->Header.HashKey.SecurityId = SecurityId;
SharedSecurity->Header.HashKey.Hash = Hash;
if (SecurityId != SECURITY_ID_INVALID) {
NtOfsAddCachedSharedSecurity( Fcb->Vcb, SharedSecurity );
}
SetSharedSecurityLength(SharedSecurity, SecurityDescriptorLength);
SharedSecurity->Header.Offset = (ULONGLONG) 0xFFFFFFFFFFFFFFFFi64;
#else // _CAIRO_
SetSharedSecurityLength(SharedSecurity, SecurityDescriptorLength);
#endif // _CAIRO_
RtlCopyMemory( &SharedSecurity->SecurityDescriptor,
SecurityDescriptor,
SecurityDescriptorLength );
}
Fcb->SharedSecurity = SharedSecurity;
Fcb->SharedSecurity->ReferenceCount++;
Fcb->CreateSecurityCount++;
} finally {
DebugUnwind( NtfsUpdateFcbSecurity );
NtfsReleaseFcbSecurity( Fcb->Vcb );
}
return;
}
_inline
VOID
NtfsRemoveReferenceSharedSecurity (
IN OUT PSHARED_SECURITY SharedSecurity
)
/*++
Routine Description:
This routine is called to manage the reference count on a shared security
descriptor. If the reference count goes to zero, the shared security is
freed.
Arguments:
SharedSecurity - security that is being dereferenced.
Return Value:
None.
--*/
{
//
// Note that there will be one less reference shortly
//
SharedSecurity->ReferenceCount--;
//
// If there is another reference to this shared security *AND* this
// shared security is being shared as a parent's child FCB then
// decouple it from the parent.
//
if (SharedSecurity->ReferenceCount == 1 && SharedSecurity->ParentFcb != NULL) {
//
// Verify that the parent's child matches this shared security
//
ASSERT( SharedSecurity->ParentFcb->ChildSharedSecurity == SharedSecurity );
//
// Remove reference from parent fcb
//
SharedSecurity->ParentFcb->ChildSharedSecurity = NULL;
SharedSecurity->ReferenceCount--;
SharedSecurity->ParentFcb = NULL;
}
if (SharedSecurity->ReferenceCount == 0) {
NtfsFreePool( SharedSecurity );
}
}
VOID
NtfsDereferenceSharedSecurity (
IN OUT PFCB Fcb
)
/*++
Routine Description:
This routine is called to dereference the shared security structure in
an Fcb and deallocate it if possible.
Arguments:
Fcb - Supplies the fcb for the file being operated on.
Return Value:
None.
--*/
{
PSHARED_SECURITY SharedSecurity;
PAGED_CODE();
//
// Remove the reference and capture the shared security if we are to free it.
//
SharedSecurity = Fcb->SharedSecurity;
Fcb->SharedSecurity = NULL;
NtfsRemoveReferenceSharedSecurity( SharedSecurity );
}
BOOLEAN
NtfsNotifyTraverseCheck (
IN PCCB Ccb,
IN PFCB Fcb,
IN PSECURITY_SUBJECT_CONTEXT SubjectContext
)
/*++
Routine Description:
This routine is the callback routine provided to the dir notify package
to check that a caller who is watching a tree has traverse access to
the directory which has the change. This routine is only called
when traverse access checking was turned on for the open used to
perform the watch.
Arguments:
Ccb - This is the Ccb associated with the directory which is being
watched.
Fcb - This is the Fcb for the directory which contains the file being
modified. We want to walk up the tree from this point and check
that the caller has traverse access across that directory.
If not specified then there is no work to do.
SubjectContext - This is the subject context captured at the time the
dir notify call was made.
Return Value:
BOOLEAN - TRUE if the caller has traverse access to the file which was
changed. FALSE otherwise.
--*/
{
TOP_LEVEL_CONTEXT TopLevelContext;
PTOP_LEVEL_CONTEXT ThreadTopLevelContext;
PFCB TopFcb;
IRP_CONTEXT LocalIrpContext;
IRP LocalIrp;
PIRP_CONTEXT IrpContext;
BOOLEAN AccessGranted;
ACCESS_MASK GrantedAccess;
NTSTATUS Status = STATUS_SUCCESS;
PPRIVILEGE_SET Privileges = NULL;
PAGED_CODE();
//
// If we have no Fcb then we can return immediately.
//
if (Fcb == NULL) {
return TRUE;
}
RtlZeroMemory( &LocalIrpContext, sizeof(LocalIrpContext) );
RtlZeroMemory( &LocalIrp, sizeof(LocalIrp) );
IrpContext = &LocalIrpContext;
IrpContext->NodeTypeCode = NTFS_NTC_IRP_CONTEXT;
IrpContext->NodeByteSize = sizeof(IRP_CONTEXT);
IrpContext->OriginatingIrp = &LocalIrp;
SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT);
InitializeListHead( &IrpContext->ExclusiveFcbList );
IrpContext->Vcb = Fcb->Vcb;
//
// Make sure we don't get any pop-ups
//
ThreadTopLevelContext = NtfsSetTopLevelIrp( &TopLevelContext, TRUE, FALSE );
ASSERT( ThreadTopLevelContext == &TopLevelContext );
NtfsUpdateIrpContextWithTopLevel( IrpContext, &TopLevelContext );
TopFcb = Ccb->Lcb->Fcb;
//
// Use a try-except to catch all of the errors.
//
try {
//
// Always lock the subject context.
//
SeLockSubjectContext( SubjectContext );
//
// Use a try-finally to perform local cleanup.
//
try {
//
// We look while walking up the tree.
//
do {
PLCB ParentLcb;
//
// Since this is a directory it can have only one parent. So
// we can use any Lcb to walk upwards.
//
ParentLcb = CONTAINING_RECORD( Fcb->LcbQueue.Flink,
LCB,
FcbLinks );
Fcb = ParentLcb->Scb->Fcb;
//
// Check if we need to load the security descriptor for the file
//
if (Fcb->SharedSecurity == NULL) {
NtfsLoadSecurityDescriptor( IrpContext, Fcb, NULL );
}
AccessGranted = SeAccessCheck( &Fcb->SharedSecurity->SecurityDescriptor,
SubjectContext,
TRUE, // Tokens are locked
FILE_TRAVERSE,
0,
&Privileges,
IoGetFileObjectGenericMapping(),
UserMode,
&GrantedAccess,
&Status );
} while ( AccessGranted && Fcb != TopFcb );
} finally {
SeUnlockSubjectContext( SubjectContext );
}
} except (NtfsExceptionFilter( IrpContext, GetExceptionInformation() )) {
NOTHING;
}
NtfsRestoreTopLevelIrp( &TopLevelContext );
return AccessGranted;
}
#ifdef _CAIRO_
VOID
NtfsInitializeSecurity (
IN PIRP_CONTEXT IrpContext,
IN PVCB Vcb,
IN PFCB Fcb
)
/*++
Routine Description:
This routine is called to initialize the security indexes and descriptor
stream.
Arguments:
IrpContext - context of call
Vcb - Supplies the volume being initialized
Fcb - Supplies the file containing the seurity indexes and descriptor
stream.
Return Value:
None.
--*/
{
UNICODE_STRING SecurityIdIndexName =
CONSTANT_UNICODE_STRING( L"$SecurityIdIndex" );
UNICODE_STRING SecurityDescriptorHashIndexName =
CONSTANT_UNICODE_STRING( L"$SecurityDescriptorHashIndex" );
UNICODE_STRING SecurityDescriptorStreamName =
CONSTANT_UNICODE_STRING( L"$SecurityDescriptorStream" );
MAP_HANDLE Map;
NTSTATUS Status;
PAGED_CODE( );
//
// Open/Create the security descriptor stream
//
NtOfsCreateAttribute( IrpContext,
Fcb,
SecurityDescriptorStreamName,
CREATE_OR_OPEN,
TRUE,
&Vcb->SecurityDescriptorStream );
NtfsAcquireSharedScb( IrpContext, Vcb->SecurityDescriptorStream );
//
// Load the run information for the Security data stream.
// Note this call must be done after the stream is nonresident.
//
if (!FlagOn( Vcb->SecurityDescriptorStream->ScbState, SCB_STATE_ATTRIBUTE_RESIDENT )) {
NtfsPreloadAllocation( IrpContext,
Vcb->SecurityDescriptorStream,
0,
MAXLONGLONG );
}
//
// Open the Security descriptor indexes and storage.
// BUGBUG: At present, these attributes are stored as part of the
// QuotaTable file record.
//
NtOfsCreateIndex( IrpContext,
Fcb,
SecurityIdIndexName,
CREATE_OR_OPEN,
0,
NtOfsCollateUlong,
NULL,
&Vcb->SecurityIdIndex );
NtOfsCreateIndex( IrpContext,
Fcb,
SecurityDescriptorHashIndexName,
CREATE_OR_OPEN,
0,
NtOfsCollateSecurityHash,
NULL,
&Vcb->SecurityDescriptorHashIndex );
//
// Retrieve the next security Id to allocate
//
try {
SECURITY_ID LastSecurityId = 0xFFFFFFFF;
INDEX_KEY LastKey;
INDEX_ROW LastRow;
LastKey.KeyLength = sizeof( SECURITY_ID );
LastKey.Key = &LastSecurityId;
Map.Bcb = NULL;
Status = NtOfsFindLastRecord( IrpContext,
Vcb->SecurityIdIndex,
&LastKey,
&LastRow,
&Map );
//
// If we've found the last key, set the next Id to allocate to be
// one greater than this last key.
//
if (Status == STATUS_SUCCESS) {
ASSERT( LastRow.KeyPart.KeyLength == sizeof( SECURITY_ID ) );
if (LastRow.KeyPart.KeyLength != sizeof( SECURITY_ID )) {
NtfsRaiseStatus( IrpContext, STATUS_DISK_CORRUPT_ERROR, NULL, NULL );
}
DebugTrace( 0, Dbg, ("Found last security Id in index\n") );
Vcb->NextSecurityId = *(SECURITY_ID *)LastRow.KeyPart.Key + 1;
//
// If the index is empty, then set the next Id to be the beginning of the
// user range.
//
} else if (Status == STATUS_NO_MATCH) {
DebugTrace( 0, Dbg, ("Security Id index is empty\n") );
Vcb->NextSecurityId = SECURITY_ID_FIRST;
} else {
NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
}
DebugTrace( 0, Dbg, ("NextSecurityId is %x\n", Vcb->NextSecurityId) );
} finally {
NtOfsReleaseMap( IrpContext, &Map );
}
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
PSHARED_SECURITY
NtOfsFindCachedSharedSecurityBySecurityId (
IN PVCB Vcb,
IN SECURITY_ID SecurityId
)
/*++
Routine Description:
This routine maps looks up a shared security structure given the security Id by
looking in the per-Vcb cache. This routine assumes exclusive access to the
security cache.
Arguments:
Vcb - Volume where security Id is cached
SecurityId - security Id for descriptor that is being retrieved
Return Value:
PSHARED_SECURITY of found descriptor. Otherwise, NULL is returned.
--*/
{
PSHARED_SECURITY SharedSecurity;
PAGED_CODE( );
SharedSecurity = Vcb->SecurityCacheById[SecurityId % VCB_SECURITY_CACHE_BY_ID_SIZE];
//
// If there is no security descriptor there then no match was found
//
if (SharedSecurity == NULL) {
return NULL;
}
//
// If the security Id's don't match then no descriptor was found
//
if (SharedSecurity->Header.HashKey.SecurityId != SecurityId) {
return NULL;
}
//
// The shared security was found
//
return SharedSecurity;
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
PSHARED_SECURITY
NtOfsFindCachedSharedSecurityByHash (
IN PVCB Vcb,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG SecurityDescriptorLength,
IN ULONG Hash
)
/*++
Routine Description:
This routine maps looks up a shared security structure given the Hash by
looking in the per-Vcb cache. This routine assumes exclusive access to the
security cache.
Arguments:
Vcb - Volume where security Id is cached
SecurityDescriptor - Security descriptor being retrieved
SecurityDescriptorLength - length of descriptor.
Hash - Hash for descriptor that is being retrieved
Return Value:
PSHARED_SECURITY of found shared descriptor. Otherwise, NULL is returned.
--*/
{
PSHARED_SECURITY *SharedSecurity;
PAGED_CODE( );
//
// Hash the hash into the per-volume table
SharedSecurity = Vcb->SecurityCacheByHash[Hash % VCB_SECURITY_CACHE_BY_HASH_SIZE];
//
// If there is no shared descriptor there, then no match
//
if (SharedSecurity == NULL || *SharedSecurity == NULL) {
return NULL;
}
//
// if the hash doesn't match then no descriptor found
//
if ((*SharedSecurity)->Header.HashKey.Hash != Hash) {
return NULL;
}
//
// If the lengths don't match then no descriptor found
//
if (GetSharedSecurityLength( *SharedSecurity ) != SecurityDescriptorLength) {
return NULL;
}
//
// If the security descriptor bits don't compare then no match
//
if (!RtlEqualMemory( (*SharedSecurity)->SecurityDescriptor,
SecurityDescriptor,
SecurityDescriptorLength) ) {
return NULL;
}
//
// The shared security was found
//
return *SharedSecurity;
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
void
NtOfsAddCachedSharedSecurity (
IN PVCB Vcb,
PSHARED_SECURITY SharedSecurity
)
/*++
Routine Description:
This routine adds shared security to the Vcb Cache. This routine assumes
exclusive access to the security cache. The shared security being added
may have a ref count of one and may already be in the table.
Arguments:
Vcb - Volume where security Id is cached
SharedSecurity - descriptor to be added to the cache
Return Value:
None.
--*/
{
PSHARED_SECURITY *Bucket;
PSHARED_SECURITY Old;
PAGED_CODE( );
//
// Is there an item already in the hash bucket?
//
Bucket = &Vcb->SecurityCacheById[SharedSecurity->Header.HashKey.SecurityId % VCB_SECURITY_CACHE_BY_ID_SIZE];
Old = *Bucket;
//
// Place it into the bucket and reference it
//
*Bucket = SharedSecurity;
SharedSecurity->ReferenceCount ++;
//
// Set up hash to point to bucket
//
Vcb->SecurityCacheByHash[SharedSecurity->Header.HashKey.Hash % VCB_SECURITY_CACHE_BY_HASH_SIZE] =
Bucket;
//
// Handle removing the old value from the bucket. We do this after advancing
// the ReferenceCount above in the case where the item is already in the bucket.
//
if (Old != NULL) {
//
// Remove and dereference the item in the bucket
//
// *Bucket = NULL;
NtfsRemoveReferenceSharedSecurity( Old );
}
}
#endif // _CAIRO_
#ifdef _CAIRO_
VOID
NtOfsPurgeSecurityCache (
IN PVCB Vcb
)
/*++
Routine Description:
This routine removes all shared security from the per-Vcb cache.
Arguments:
Vcb - Volume where descriptors are cached
Return Value:
None.
--*/
{
ULONG i;
PAGED_CODE( );
//
// Serialize access to the security cache
//
NtfsAcquireFcbSecurity( Vcb );
//
// Walk through the cache looking for cached security
//
for (i = 0; i < VCB_SECURITY_CACHE_BY_ID_SIZE; i++)
{
if (Vcb->SecurityCacheById[i] != NULL) {
//
// Remove the reference to the security
//
PSHARED_SECURITY SharedSecurity = Vcb->SecurityCacheById[i];
Vcb->SecurityCacheById[i] = NULL;
NtfsRemoveReferenceSharedSecurity( SharedSecurity );
}
}
//
// Release access to the cache
//
NtfsReleaseFcbSecurity( Vcb );
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
VOID
NtOfsMapSecurityIdToSecurityDescriptor (
IN PIRP_CONTEXT IrpContext,
IN PVCB Vcb,
IN SECURITY_ID SecurityId,
OUT PSECURITY_DESCRIPTOR *SecurityDescriptor,
OUT PULONG SecurityDescriptorLength,
OUT PBCB *Bcb
)
/*++
Routine Description:
This routine maps from a security Id to the descriptor bits stored in the
security descriptor stream using the security Id index
Arguments:
IrpContext - Context of the call
Vcb - Volume where descriptor is stored
SecurityId - security Id for descriptor that is being retrieved
SecurityDescriptor - returned security descriptor pointer
SecurityDescriptorLength - returned length of security descriptor
Bcb - returned mapping control structure
Return Value:
None.
--*/
{
SECURITY_DESCRIPTOR_HEADER Header;
NTSTATUS Status;
MAP_HANDLE Map;
INDEX_ROW Row;
INDEX_KEY Key;
PAGED_CODE( );
DebugTrace( 0, Dbg, ("Mapping security ID %08x\n", SecurityId) );
//
// Lookup descriptor stream position information.
// The format of the key is simply the ULONG SecurityId
//
Key.KeyLength = sizeof( SecurityId );
Key.Key = &SecurityId;
Status = NtOfsFindRecord( IrpContext,
Vcb->SecurityIdIndex,
&Key,
&Row,
&Map,
NULL );
DebugTrace( 0, Dbg, ("Security Id lookup status = %08x\n", Status) );
//
// If the security Id is not found, then this volume is corrupt.
// We raise the error which will force CHKDSK to be run to rebuild
// the mapping index.
//
if (Status == STATUS_NO_MATCH) {
DebugTrace( 0, Dbg, ("SecurityId is not found in index\n") );
NtfsRaiseStatus( IrpContext, STATUS_DISK_CORRUPT_ERROR, NULL, NULL );
}
//
// Save security descriptor offset and length information
//
Header = *(PSECURITY_DESCRIPTOR_HEADER)Row.DataPart.Data;
ASSERT( Header.HashKey.SecurityId == SecurityId );
//
// Release mapping information
//
NtOfsReleaseMap( IrpContext, &Map );
//
// Make sure that the data is the correct size
//
ASSERT( Row.DataPart.DataLength == sizeof( SECURITY_DESCRIPTOR_HEADER ) );
if (Row.DataPart.DataLength != sizeof( SECURITY_DESCRIPTOR_HEADER )) {
DebugTrace( 0, Dbg, ("SecurityId data doesn't have the correct length\n") );
NtfsRaiseStatus( IrpContext, STATUS_DISK_CORRUPT_ERROR, NULL, NULL );
}
//
// Map security descriptor
//
DebugTrace( 0, Dbg, ("Mapping security descriptor stream at %I64x, len %x\n",
Header.Offset, Header.Length) );
NtfsMapStream(
IrpContext,
Vcb->SecurityDescriptorStream,
Header.Offset,
Header.Length,
Bcb,
SecurityDescriptor );
//
// Set return values
//
*SecurityDescriptor =
(PSECURITY_DESCRIPTOR) Add2Ptr( *SecurityDescriptor,
sizeof( SECURITY_DESCRIPTOR_HEADER ) );
*SecurityDescriptorLength =
GETSECURITYDESCRIPTORLENGTH( &Header );
}
VOID
NtfsLoadSecurityDescriptorById (
IN PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PFCB ParentFcb OPTIONAL
)
/*++
Routine Description:
This routine finds or creates the shared security for the specified
Fcb by looking in the volume cache or index
Arguments:
IrpContext - Context of call
Fcb - File whose security is to be loaded
ParentFcb - FCB of parent when searching upward to find already-cached
descriptor
Return Value:
None.
--*/
{
PSHARED_SECURITY SharedSecurity;
PAGED_CODE( );
//
// Serialize access to the security cache
//
NtfsAcquireFcbSecurity( Fcb->Vcb );
//
// First, consult the Vcb cache of security Ids
//
SharedSecurity = NtOfsFindCachedSharedSecurityBySecurityId( Fcb->Vcb, Fcb->SecurityId );
//
// If we found one, store it in the Fcb and we're done
//
if (SharedSecurity != NULL) {
Fcb->SharedSecurity = SharedSecurity;
Fcb->SharedSecurity->ReferenceCount++;
Fcb->CreateSecurityCount += 1;
DebugTrace( 0, DbgAcl, ("Found cached security descriptor %x %x\n",
SharedSecurity, SharedSecurity->Header.HashKey.SecurityId) );
//
// Release access to security cache
//
NtfsReleaseFcbSecurity( Fcb->Vcb );
} else {
PBCB Bcb = NULL;
PSECURITY_DESCRIPTOR SecurityDescriptor;
ULONG SecurityDescriptorLength;
//
// Release access to security cache
//
NtfsReleaseFcbSecurity( Fcb->Vcb );
DebugTrace( 0, Dbg, ("Looking up security descriptor %x\n", Fcb->SecurityId) );
//
// Lock down the security stream
//
NtfsAcquireSharedScb( IrpContext, Fcb->Vcb->SecurityDescriptorStream );
try {
//
// Consult the Vcb index to map to the security descriptor
//
NtOfsMapSecurityIdToSecurityDescriptor( IrpContext,
Fcb->Vcb,
Fcb->SecurityId,
&SecurityDescriptor,
&SecurityDescriptorLength,
&Bcb );
//
// Generate the shared security from the security Id and descriptor
//
NtfsUpdateFcbSecurity( IrpContext,
Fcb,
ParentFcb,
Fcb->SecurityId,
SecurityDescriptor,
SecurityDescriptorLength );
} finally {
NtfsUnpinBcb( &Bcb );
NtfsReleaseScb( IrpContext, Fcb->Vcb->SecurityDescriptorStream );
}
}
}
#endif // _CAIRO_
//
// Local Support routine
//
VOID
NtfsLoadSecurityDescriptor (
IN PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN PFCB ParentFcb OPTIONAL
)
/*++
Routine Description:
This routine loads the shared security descriptor into the fcb for the
file from disk using either the SecurityId or the $Security_Descriptor
Arguments:
Fcb - Supplies the fcb for the file being operated on
Return Value:
None.
--*/
{
PAGED_CODE();
ASSERTMSG("Must only be called with a null value here", Fcb->SharedSecurity == NULL);
DebugTrace( +1, Dbg, ("NtfsLoadSecurityDescriptor...\n") );
#ifdef _CAIRO_
//
// If the file has a valid SecurityId then retrieve the security descriptor
// from the security descriptor index
//
if (Fcb->SecurityId != SECURITY_ID_INVALID) {
NtfsLoadSecurityDescriptorById( IrpContext, Fcb, ParentFcb );
} else
#endif // _CAIRO_
{
PBCB Bcb = NULL;
PSHARED_SECURITY SharedSecurity;
PSECURITY_DESCRIPTOR SecurityDescriptor;
ULONG SecurityDescriptorLength;
ATTRIBUTE_ENUMERATION_CONTEXT AttributeContext;
PATTRIBUTE_RECORD_HEADER Attribute;
try {
//
// Read in the security descriptor attribute, and it is is not present
// then there then the file is not protected. In that case we will
// use the default descriptor.
//
NtfsInitializeAttributeContext( &AttributeContext );
if (!NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$SECURITY_DESCRIPTOR,
&AttributeContext )) {
DebugTrace( 0, Dbg, ("Security Descriptor attribute does not exist\n") );
SecurityDescriptor = NtfsData.DefaultDescriptor;
SecurityDescriptorLength = NtfsData.DefaultDescriptorLength;
} else {
//
// There must be a security descriptor with a non-zero length; only
// applies for non-resident descriptors with valid data length.
//
Attribute = NtfsFoundAttribute( &AttributeContext );
if (NtfsIsAttributeResident( Attribute ) ?
(Attribute->Form.Resident.ValueLength == 0) :
(Attribute->Form.Nonresident.ValidDataLength == 0)) {
SecurityDescriptor = NtfsData.DefaultDescriptor;
SecurityDescriptorLength = NtfsData.DefaultDescriptorLength;
} else {
NtfsMapAttributeValue( IrpContext,
Fcb,
(PVOID *)&SecurityDescriptor,
&SecurityDescriptorLength,
&Bcb,
&AttributeContext );
}
}
NtfsUpdateFcbSecurity( IrpContext,
Fcb,
ParentFcb,
#ifdef _CAIRO_
SECURITY_ID_INVALID,
#endif // _CAIRO_
SecurityDescriptor,
SecurityDescriptorLength );
} finally {
DebugUnwind( NtfsLoadSecurityDescriptor );
//
// Cleanup our attribute enumeration context and the Bcb
//
NtfsCleanupAttributeContext( &AttributeContext );
NtfsUnpinBcb( &Bcb );
}
}
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsLoadSecurityDescriptor -> VOID\n") );
return;
}
//
// Local Support routine
//
#ifdef _CAIRO_
NTSTATUS
NtOfsMatchSecurityHash (
IN PINDEX_ROW IndexRow,
IN OUT PVOID MatchData
)
/*++
Routine Description:
Test whether an index row is worthy of returning based on its contents as
a row in the SecurityDescriptorHashIndex.
Arguments:
IndexRow - row that is being tested
MatchData - a PVOID that is the hash function we look for.
Returns:
STATUS_SUCCESS if the IndexRow matches
STATUS_NO_MATCH if the IndexRow does not match, but the enumeration should
continue
STATUS_NO_MORE_MATCHES if the IndexRow does not match, and the enumeration
should terminate
--*/
{
ASSERT(IndexRow->KeyPart.KeyLength == sizeof( SECURITY_HASH_KEY ) );
PAGED_CODE( );
if (((PSECURITY_HASH_KEY)IndexRow->KeyPart.Key)->Hash == (ULONG) MatchData) {
return STATUS_SUCCESS;
} else {
return STATUS_NO_MORE_MATCHES;
}
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
VOID
NtOfsLookupSecurityDescriptorInIndex (
PIRP_CONTEXT IrpContext,
IN OUT PSHARED_SECURITY SharedSecurity
)
/*++
Routine Description:
Look up the security descriptor in the index. If found, return the
security ID.
Arguments:
IrpContext - context of the call
SharedSecurity - shared security for a file
Return Value:
None.
--*/
{
PAGED_CODE( );
DebugTrace( +1, Dbg, ("NtOfsLookupSecurityDescriptorInIndex...\n") );
//
// For each matching hash record in the index, see if the actual security
// security descriptor matches.
//
{
INDEX_KEY IndexKey;
INDEX_ROW FoundRow;
PSECURITY_DESCRIPTOR_HEADER Header;
UCHAR HashDescriptorHeader[2 * (sizeof( SECURITY_DESCRIPTOR_HEADER ) + sizeof( ULONG ))];
PINDEX_KEY Key = &IndexKey;
PREAD_CONTEXT ReadContext = NULL;
ULONG FoundCount = 0;
PBCB Bcb = NULL;
IndexKey.KeyLength = sizeof( SharedSecurity->Header.HashKey );
IndexKey.Key = &SharedSecurity->Header.HashKey.Hash;
try {
//
// We keep reading hash records until we find a hash.
//
while (SharedSecurity->Header.HashKey.SecurityId == SECURITY_ID_INVALID)
{
//
// Read next matching SecurityHashIndex record
//
FoundCount = 1;
NtOfsReadRecords(
IrpContext,
IrpContext->Vcb->SecurityDescriptorHashIndex,
&ReadContext,
Key,
NtOfsMatchSecurityHash,
(PVOID)SharedSecurity->Header.HashKey.Hash,
&FoundCount,
&FoundRow,
sizeof( HashDescriptorHeader ),
&HashDescriptorHeader[0]);
//
// Set next read to read sequentially rather than explicitly
// seek.
//
Key = NULL;
//
// If there were no more records found, then go and establish a
// a new security Id.
//
if (FoundCount == 0) {
break;
}
//
// Examine the row to see if the descriptors are
// the same. Verify the cache contents.
//
ASSERT( FoundRow.DataPart.DataLength == sizeof( SECURITY_DESCRIPTOR_HEADER ) );
if (FoundRow.DataPart.DataLength != sizeof( SECURITY_DESCRIPTOR_HEADER )) {
DebugTrace( 0, Dbg, ("Found row has a bad size\n") );
NtfsRaiseStatus( IrpContext,
STATUS_DISK_CORRUPT_ERROR,
NULL, NULL );
}
Header = (PSECURITY_DESCRIPTOR_HEADER)FoundRow.DataPart.Data;
//
// If the length of the security descriptor in the stream is NOT
// the same as the current security descriptor, then a match is
// not possible
//
if (SharedSecurity->Header.Length != Header->Length) {
continue;
}
//
// Map security descriptor given descriptor stream position.
//
try {
PSECURITY_DESCRIPTOR_HEADER TestHeader;
NtfsMapStream(
IrpContext,
IrpContext->Vcb->SecurityDescriptorStream,
Header->Offset,
Header->Length,
&Bcb,
&TestHeader);
//
// Make sure index data matches stream data
//
ASSERT( TestHeader->HashKey.Hash == Header->HashKey.Hash &&
TestHeader->HashKey.SecurityId == Header->HashKey.SecurityId &&
TestHeader->Length == Header->Length );
//
// Compare byte-for-byte the security descriptors. We do not
// perform any rearranging of descriptors into canonical forms.
//
if (RtlEqualMemory( SharedSecurity->SecurityDescriptor,
TestHeader + 1,
GetSharedSecurityLength( SharedSecurity )) ) {
//
// We have a match. Save the found header
//
SharedSecurity->Header = *TestHeader;
DebugTrace( 0, DbgAcl, ("Reusing indexed security Id %x\n",
TestHeader->HashKey.SecurityId) );
}
} finally {
NtfsUnpinBcb( &Bcb );
}
}
} finally {
if (ReadContext != NULL) {
NtOfsFreeReadContext( ReadContext );
}
}
}
}
#endif // _CAIRO_
//
// Local Support routine
//
#ifdef _CAIRO_
SECURITY_ID
NtOfsGetSecurityIdFromSecurityDescriptor (
PIRP_CONTEXT IrpContext,
IN OUT PSHARED_SECURITY SharedSecurity
)
/*++
Routine Description:
Return the security Id associated with a given security descriptor. If
there is an existing Id, return it. If no Id exists, create one.
Arguments:
IrpContext - context of the call
SharedSecurity - Shared security used by file
Return Value:
SECURITY_ID corresponding to the unique instantiation of the security
descriptor on the volume.
--*/
{
SECURITY_ID SavedSecurityId;
PAGED_CODE( );
DebugTrace( +1, Dbg, ("NtOfsGetSecurityIdFromSecurityDescriptor...\n") );
//
// Make sure the data structures don't change underneath us
//
NtfsAcquireSharedScb( IrpContext, IrpContext->Vcb->SecurityDescriptorStream );
//
// Save next Security Id. This is used if we fail to find the security
// descriptor in the descriptor stream.
//
SavedSecurityId = IrpContext->Vcb->NextSecurityId;
//
// Find descriptor in indexes/stream
//
try {
NtOfsLookupSecurityDescriptorInIndex( IrpContext, SharedSecurity );
//
// If we've found the security descriptor in the stream we're done.
//
if (SharedSecurity->Header.HashKey.SecurityId != SECURITY_ID_INVALID) {
leave;
}
//
// The security descriptor is not found. Reacquire the security
// stream exclusive since we are about to modify it.
//
NtfsReleaseScb( IrpContext, IrpContext->Vcb->SecurityDescriptorStream );
NtfsAcquireExclusiveScb( IrpContext, IrpContext->Vcb->SecurityDescriptorStream );
//
// During the short interval above, we did not own the security stream.
// It is possible that another thread has gotten in and created this
// descriptor. Therefore, we must probe the indexes again.
//
// Rather than perform this expensive test *always*, we saved the next
// security id to be allocated above. Now that we've obtained the stream
// exclusive we can check to see if the saved one is the same as the next
// one. If so, then we need to probe the indexes. Otherwise
// we know that no modifications have taken place.
//
if (SavedSecurityId != IrpContext->Vcb->NextSecurityId) {
DebugTrace( 0, DbgAcl, ("SecurityId changed, rescanning\n") );
//
// The descriptor cache has been edited. We must search again
//
NtOfsLookupSecurityDescriptorInIndex( IrpContext, SharedSecurity );
//
// If the Id was found this time, simply return it
//
if (SharedSecurity->Header.HashKey.SecurityId != SECURITY_ID_INVALID) {
leave;
}
}
//
// allocate security id. This does not need to be logged since we only
// increment this and initialize this from the max key in the index at
// mount time.
//
SharedSecurity->Header.HashKey.SecurityId =
IrpContext->Vcb->NextSecurityId++;
//
// Determine allocation location in descriptor stream. The alignment
// requirements for security descriptors within the stream are:
//
// DWORD alignment
// Not spanning a VACB_MAPPING_GRANULARITY boundary
//
//
// Get current EOF for descriptor stream
//
SharedSecurity->Header.Offset =
IrpContext->Vcb->SecurityDescriptorStream->Header.FileSize.QuadPart;
//
// Align to big boundary
//
SharedSecurity->Header.Offset =
(SharedSecurity->Header.Offset + 0xF) & 0xFFFFFFFFFFFFFFF0i64;
DebugTrace( 0, DbgAcl, ("Allocating SecurityId %x at %016I64x\n",
SharedSecurity->Header.HashKey.SecurityId,
SharedSecurity->Header.Offset) );
//
// Make sure we don't span a VACB_MAPPING_GRANULARITY boundary
//
if ((SharedSecurity->Header.Offset & (VACB_MAPPING_GRANULARITY - 1)) +
SharedSecurity->Header.Length >= VACB_MAPPING_GRANULARITY) {
SharedSecurity->Header.Offset =
(SharedSecurity->Header.Offset + VACB_MAPPING_GRANULARITY - 1) &
~(VACB_MAPPING_GRANULARITY - 1);
}
//
// Grow security stream to make room for new descriptor and header
//
NtOfsSetLength( IrpContext, IrpContext->Vcb->SecurityDescriptorStream,
SharedSecurity->Header.Offset +
SharedSecurity->Header.Length);
//
// Put the new descriptor into the stream
//
NtOfsPutData( IrpContext, IrpContext->Vcb->SecurityDescriptorStream,
SharedSecurity->Header.Offset,
SharedSecurity->Header.Length,
&SharedSecurity->Header );
//
// add id->data map
//
{
INDEX_ROW Row;
Row.KeyPart.KeyLength =
sizeof( SharedSecurity->Header.HashKey.SecurityId );
Row.KeyPart.Key = &SharedSecurity->Header.HashKey.SecurityId;
Row.DataPart.DataLength = sizeof( SharedSecurity->Header );
Row.DataPart.Data = &SharedSecurity->Header;
NtOfsAddRecords(
IrpContext,
IrpContext->Vcb->SecurityIdIndex,
1,
&Row,
FALSE );
}
//
// add hash|id->data map
//
{
INDEX_ROW Row;
Row.KeyPart.KeyLength =
sizeof( SharedSecurity->Header.HashKey );
Row.KeyPart.Key = &SharedSecurity->Header.HashKey;
Row.DataPart.DataLength = sizeof( SharedSecurity->Header );
Row.DataPart.Data = &SharedSecurity->Header;
NtOfsAddRecords(
IrpContext,
IrpContext->Vcb->SecurityDescriptorHashIndex,
1,
&Row,
FALSE );
}
} finally {
NtfsReleaseScb( IrpContext, IrpContext->Vcb->SecurityDescriptorStream );
}
DebugTrace(-1, Dbg, ("NtOfsGetSecurityIdFromSecurityDescriptor returns %08x\n",
SharedSecurity->Header.HashKey.SecurityId));
return SharedSecurity->Header.HashKey.SecurityId;
}
#endif // _CAIRO_
//
// Local Support routine
//
VOID
NtfsStoreSecurityDescriptor (
PIRP_CONTEXT IrpContext,
IN PFCB Fcb,
IN BOOLEAN LogIt
)
/*++
Routine Description:
This routine stores a new security descriptor already stored in the fcb
from memory onto the disk.
Arguments:
Fcb - Supplies the fcb for the file being operated on
LogIt - Supplies whether or not the creation of a new security descriptor
should/ be logged or not. Modifications are always logged. This
parameter must only be specified as FALSE for a file which is currently
being created.
Return Value:
None.
--*/
{
ATTRIBUTE_ENUMERATION_CONTEXT AttributeContext;
ATTRIBUTE_ENUMERATION_CONTEXT StdInfoContext;
BOOLEAN CleanupStdInfoContext = FALSE;
PAGED_CODE();
DebugTrace( +1, Dbg, ("NtfsStoreSecurityDescriptor...\n") );
//
// Initialize the attribute and find the security attribute
//
NtfsInitializeAttributeContext( &AttributeContext );
try {
#ifdef _CAIRO_
//
// BUGBUG - remove the following IF statement when all volumes get security
// descriptor streams.
//
if (Fcb->Vcb->SecurityDescriptorStream != NULL) {
//
// If the shared security pointer is null, then we are deleting the
// security descriptor altogether. If so, and we have a security
// attribute, indicated by NOT having large standard info, then we
// must delete the security attribute.
//
if (Fcb->SharedSecurity == NULL) {
if (!FlagOn( Fcb->FcbState, FCB_STATE_LARGE_STD_INFO )) {
DebugTrace( 0, Dbg, ("Security Descriptor is null\n") );
//
// Read in the security descriptor attribute if it already
// doesn't exist then we're done, otherwise simply delete
// the attribute
//
if (NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$SECURITY_DESCRIPTOR,
&AttributeContext )) {
DebugTrace( 0, Dbg, ("Delete existing Security Descriptor\n") );
NtfsDeleteAttributeRecord( IrpContext,
Fcb,
TRUE,
FALSE,
&AttributeContext );
}
}
leave;
}
//
// We are called to replace an existing security descriptor. In the
// event that we have a downlevel $STANDARD_INFORMATION attribute, we
// must convert it to large form before we store the ACL efficiently.
//
if (!FlagOn( Fcb->FcbState, FCB_STATE_LARGE_STD_INFO) ) {
DebugTrace( 0, Dbg, ("Growing standard information\n") );
NtfsGrowStandardInformation( IrpContext, Fcb );
DebugTrace( 0, Dbg, ("Security Descriptor is null\n") );
//
// Read in the security descriptor attribute if it already
// doesn't exist then we're done, otherwise simply delete the
// attribute
//
if (NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$SECURITY_DESCRIPTOR,
&AttributeContext )) {
DebugTrace( 0, Dbg, ("Delete existing Security Descriptor\n") );
NtfsDeleteAttributeRecord( IrpContext,
Fcb,
TRUE,
FALSE,
&AttributeContext );
}
}
//
// If the shared security descriptor already has an ID assigned, then
// use it
//
if (Fcb->SharedSecurity->Header.HashKey.SecurityId != SECURITY_ID_INVALID) {
Fcb->SecurityId = Fcb->SharedSecurity->Header.HashKey.SecurityId;
DebugTrace( 0, DbgAcl, ("Reusing cached security Id %x\n", Fcb->SecurityId) );
} else {
//
// Find unique SecurityId for descriptor and set SecurityId in Fcb.
//
Fcb->SecurityId = NtOfsGetSecurityIdFromSecurityDescriptor( IrpContext,
Fcb->SharedSecurity );
//
// By serializing allocation of Id's, we have a tiny race in here
// where two threads could be setting the same security Id into
// the shared security.
//
ASSERT( Fcb->SharedSecurity->Header.HashKey.SecurityId == SECURITY_ID_INVALID ||
Fcb->SharedSecurity->Header.HashKey.SecurityId == Fcb->SecurityId );
Fcb->SharedSecurity->Header.HashKey.SecurityId = Fcb->SecurityId;
//
// Serialize access to the security cache
//
NtfsAcquireFcbSecurity( Fcb->Vcb );
//
// Cache this shared security for faster access
//
NtOfsAddCachedSharedSecurity( Fcb->Vcb, Fcb->SharedSecurity );
//
// Release access to security cache
//
NtfsReleaseFcbSecurity( Fcb->Vcb );
}
//
// We've changed the standard information for this file. We now must
// update the disk to make sure things are consistent.
//
leave;
}
#endif // _CAIRO_
//
// Check if the attribute is first being modified or deleted, a null
// value means that we are deleting the security descriptor
//
if (Fcb->SharedSecurity == NULL) {
DebugTrace( 0, Dbg, ("Security Descriptor is null\n") );
//
// If it already doesn't exist then we're done, otherwise simply
// delete the attribute
//
if (NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$SECURITY_DESCRIPTOR,
&AttributeContext )) {
DebugTrace( 0, Dbg, ("Delete existing Security Descriptor\n") );
NtfsDeleteAttributeRecord( IrpContext,
Fcb,
TRUE,
FALSE,
&AttributeContext );
}
leave;
}
//
// At this point we are modifying the security descriptor so read in the
// security descriptor, if it does not exist then we will need to create
// one.
//
if (!NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$SECURITY_DESCRIPTOR,
&AttributeContext )) {
DebugTrace( 0, Dbg, ("Create a new Security Descriptor\n") );
NtfsCleanupAttributeContext( &AttributeContext );
NtfsInitializeAttributeContext( &AttributeContext );
NtfsCreateAttributeWithValue( IrpContext,
Fcb,
$SECURITY_DESCRIPTOR,
NULL, // attribute name
&Fcb->SharedSecurity->SecurityDescriptor,
GetSharedSecurityLength(Fcb->SharedSecurity),
0, // attribute flags
NULL, // where indexed
LogIt, // logit
&AttributeContext );
//
// We may be modifying the security descriptor of an NT 5.0 volume.
// We want to store a SecurityID in the standard information field so
// that if we reboot on 5.0 NTFS will know where to find the most
// recent security descriptor.
//
if (FlagOn( Fcb->FcbState, FCB_STATE_LARGE_STD_INFO )) {
LARGE_STANDARD_INFORMATION StandardInformation;
//
// Initialize the context structure.
//
NtfsInitializeAttributeContext( &StdInfoContext );
CleanupStdInfoContext = TRUE;
//
// Locate the standard information, it must be there.
//
if (!NtfsLookupAttributeByCode( IrpContext,
Fcb,
&Fcb->FileReference,
$STANDARD_INFORMATION,
&StdInfoContext )) {
DebugTrace( 0, Dbg, ("Can't find standard information\n") );
NtfsRaiseStatus( IrpContext, STATUS_FILE_CORRUPT_ERROR, NULL, Fcb );
}
ASSERT( NtfsFoundAttribute( &StdInfoContext )->Form.Resident.ValueLength >= sizeof( LARGE_STANDARD_INFORMATION ));
//
// Copy the existing standard information to our buffer.
//
RtlCopyMemory( &StandardInformation,
NtfsAttributeValue( NtfsFoundAttribute( &StdInfoContext )),
sizeof( LARGE_STANDARD_INFORMATION ));
StandardInformation.SecurityId = SECURITY_ID_INVALID;
StandardInformation.OwnerId = 0;
//
// Call to change the attribute value.
//
NtfsChangeAttributeValue( IrpContext,
Fcb,
0,
&StandardInformation,
sizeof( LARGE_STANDARD_INFORMATION ),
FALSE,
FALSE,
FALSE,
FALSE,
&StdInfoContext );
}
} else {
DebugTrace( 0, Dbg, ("Change an existing Security Descriptor\n") );
NtfsChangeAttributeValue( IrpContext,
Fcb,
0, // Value offset
&Fcb->SharedSecurity->SecurityDescriptor,
GetSharedSecurityLength( Fcb->SharedSecurity ),
TRUE, // logit
TRUE,
FALSE,
FALSE,
&AttributeContext );
}
} finally {
DebugUnwind( NtfsStoreSecurityDescriptor );
//
// Cleanup our attribute enumeration context
//
NtfsCleanupAttributeContext( &AttributeContext );
if (CleanupStdInfoContext) {
NtfsCleanupAttributeContext( &StdInfoContext );
}
}
//
// And return to our caller
//
DebugTrace( -1, Dbg, ("NtfsStoreSecurityDescriptor -> VOID\n") );
return;
}
/*++
Routine Descriptions:
Collation routines for security hash index. Collation occurs by Hash first,
then security Id
Arguments:
Key1 - First key to compare.
Key2 - Second key to compare.
CollationData - Optional data to support the collation.
Return Value:
LessThan, EqualTo, or Greater than, for how Key1 compares
with Key2.
--*/
#ifdef _CAIRO_
FSRTL_COMPARISON_RESULT
NtOfsCollateSecurityHash (
IN PINDEX_KEY Key1,
IN PINDEX_KEY Key2,
IN PVOID CollationData
)
{
PSECURITY_HASH_KEY HashKey1 = (PSECURITY_HASH_KEY) Key1->Key;
PSECURITY_HASH_KEY HashKey2 = (PSECURITY_HASH_KEY) Key2->Key;
UNREFERENCED_PARAMETER(CollationData);
PAGED_CODE( );
ASSERT( Key1->KeyLength == sizeof( SECURITY_HASH_KEY ) );
ASSERT( Key2->KeyLength == sizeof( SECURITY_HASH_KEY ) );
if (HashKey1->Hash < HashKey2->Hash) {
return LessThan;
} else if (HashKey1->Hash > HashKey2->Hash) {
return GreaterThan;
} else if (HashKey1->SecurityId < HashKey2->SecurityId) {
return LessThan;
} else if (HashKey1->SecurityId > HashKey2->SecurityId) {
return GreaterThan;
} else {
return EqualTo;
}
}
#endif // _CAIRO_
|