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
|
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
avscan.c
Abstract:
This is the main module of the avscan mini-filter driver.
This filter demonstrates how to implement a transaction-aware
anti-virus filter.
Av prefix denotes "Anti-virus" module.
Environment:
Kernel mode
--*/
#include <initguid.h>
#include "avscan.h"
/*************************************************************************
Local Function Prototypes
*************************************************************************/
DRIVER_INITIALIZE DriverEntry;
NTSTATUS
DriverEntry (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
);
typedef
NTSTATUS
(*PFN_IoOpenDriverRegistryKey) (
PDRIVER_OBJECT DriverObject,
DRIVER_REGKEY_TYPE RegKeyType,
ACCESS_MASK DesiredAccess,
ULONG Flags,
PHANDLE DriverRegKey
);
PFN_IoOpenDriverRegistryKey
AvGetIoOpenDriverRegistryKey (
VOID
);
NTSTATUS
AvOpenServiceParametersKey (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING ServiceRegistryPath,
_Out_ PHANDLE ServiceParametersKey
);
NTSTATUS
AvSetConfiguration (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
);
NTSTATUS
AvInstanceSetup (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_SETUP_FLAGS Flags,
_In_ DEVICE_TYPE VolumeDeviceType,
_In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
);
VOID
AvInstanceTeardownStart (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Unreferenced_parameter_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
);
VOID
AvInstanceTeardownComplete (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
);
NTSTATUS
AvUnload (
_Unreferenced_parameter_ FLT_FILTER_UNLOAD_FLAGS Flags
);
NTSTATUS
AvInstanceQueryTeardown (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
);
FLT_PREOP_CALLBACK_STATUS
AvPreOperationCallback (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_PREOP_CALLBACK_STATUS
AvPreCreate (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_POSTOP_CALLBACK_STATUS
AvPostCreate (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_opt_ PVOID CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
);
FLT_PREOP_CALLBACK_STATUS
AvPreCleanup (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
FLT_PREOP_CALLBACK_STATUS
AvPreFsControl (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
);
NTSTATUS
AvKtmNotificationCallback (
_Unreferenced_parameter_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PFLT_CONTEXT TransactionContext,
_In_ ULONG TransactionNotification
);
NTSTATUS
AvScanAbortCallbackAsync (
_Unreferenced_parameter_ PFLT_INSTANCE Instance,
_In_ PFLT_CONTEXT Context,
_Unreferenced_parameter_ PFLT_CALLBACK_DATA Data
);
//
// Local routines
//
BOOLEAN
AvOperationsModifyingFile (
_In_ PFLT_CALLBACK_DATA Data
);
NTSTATUS
AvQueryTransactionOutcome(
_In_ PKTRANSACTION Transaction,
_Out_ PULONG TxOutcome
);
NTSTATUS
AvProcessPreviousTransaction (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Inout_ PAV_STREAM_CONTEXT StreamContext
);
NTSTATUS
AvProcessTransactionOutcome (
_Inout_ PAV_TRANSACTION_CONTEXT TransactionContext,
_In_ ULONG TransactionOutcome
);
NTSTATUS
AvLoadFileStateFromCache (
_In_ PFLT_INSTANCE Instance,
_In_ PAV_FILE_REFERENCE FileId,
_Out_ LONG volatile* State,
_Out_ PLONGLONG VolumeRevision,
_Out_ PLONGLONG CacheRevision,
_Out_ PLONGLONG FileRevision
);
NTSTATUS
AvSyncCache (
_In_ PFLT_INSTANCE Instance,
_In_ PAV_STREAM_CONTEXT StreamContext
);
BOOLEAN
AvIsPrefetchEcpPresent (
_In_ PFLT_FILTER Filter,
_In_ PFLT_CALLBACK_DATA Data
);
BOOLEAN
AvIsStreamAlternate (
_Inout_ PFLT_CALLBACK_DATA Data
);
NTSTATUS
AvScan (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ AV_SCAN_MODE ScanMode,
_In_ UCHAR IOMajorFunctionAtScan,
_In_ BOOLEAN IsInTxWriter,
_Inout_ PAV_STREAM_CONTEXT StreamContext
);
VOID
AvDoCancelScanAndRelease (
_In_ PAV_SCAN_CONTEXT ScanContext,
_In_ PAV_SECTION_CONTEXT SectionContext
);
NTSTATUS
AvSendUnloadingToUser (
VOID
);
//
// Assign text sections for each routine.
//
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DriverEntry)
#pragma alloc_text(INIT, AvGetIoOpenDriverRegistryKey)
#pragma alloc_text(INIT, AvOpenServiceParametersKey)
#pragma alloc_text(INIT, AvSetConfiguration)
#pragma alloc_text(PAGE, AvUnload)
#pragma alloc_text(PAGE, AvInstanceQueryTeardown)
#pragma alloc_text(PAGE, AvInstanceSetup)
#pragma alloc_text(PAGE, AvInstanceTeardownStart)
#pragma alloc_text(PAGE, AvInstanceTeardownComplete)
#pragma alloc_text(PAGE, AvPreCreate)
#pragma alloc_text(PAGE, AvPostCreate)
#pragma alloc_text(PAGE, AvPreFsControl)
#pragma alloc_text(PAGE, AvPreCleanup)
#pragma alloc_text(PAGE, AvKtmNotificationCallback)
#pragma alloc_text(PAGE, AvScanAbortCallbackAsync)
#pragma alloc_text(PAGE, AvOperationsModifyingFile)
#pragma alloc_text(PAGE, AvQueryTransactionOutcome)
#pragma alloc_text(PAGE, AvProcessPreviousTransaction)
#pragma alloc_text(PAGE, AvProcessTransactionOutcome)
#pragma alloc_text(PAGE, AvLoadFileStateFromCache)
#pragma alloc_text(PAGE, AvSyncCache)
#pragma alloc_text(PAGE, AvIsPrefetchEcpPresent)
#pragma alloc_text(PAGE, AvIsStreamAlternate)
#pragma alloc_text(PAGE, AvScan)
#pragma alloc_text(PAGE, AvDoCancelScanAndRelease)
#pragma alloc_text(PAGE, AvSendAbortToUser)
#pragma alloc_text(PAGE, AvSendUnloadingToUser)
#endif
//
// operation registration
//
CONST FLT_OPERATION_REGISTRATION Callbacks[] = {
{ IRP_MJ_CREATE,
0,
AvPreCreate,
AvPostCreate },
{ IRP_MJ_CLEANUP,
0,
AvPreCleanup,
NULL },
{ IRP_MJ_WRITE,
0,
AvPreOperationCallback,
NULL },
{ IRP_MJ_SET_INFORMATION,
0,
AvPreOperationCallback,
NULL },
{ IRP_MJ_FILE_SYSTEM_CONTROL,
0,
AvPreFsControl,
NULL },
{ IRP_MJ_OPERATION_END }
};
//
// Context registraction construct defined in context.c
//
extern const FLT_CONTEXT_REGISTRATION ContextRegistration[];
//
// This defines what we want to filter with FltMgr
//
CONST FLT_REGISTRATION FilterRegistration = {
sizeof( FLT_REGISTRATION ), // Size
FLT_REGISTRATION_VERSION, // Version
0, // Flags
ContextRegistration, // Context
Callbacks, // Operation callbacks
AvUnload, // MiniFilterUnload
AvInstanceSetup, // InstanceSetup
AvInstanceQueryTeardown, // InstanceQueryTeardown
AvInstanceTeardownStart, // InstanceTeardownStart
AvInstanceTeardownComplete, // InstanceTeardownComplete
NULL, // GenerateFileName
NULL, // NormalizeNameComponentCallback
NULL, // NormalizeContextCleanupCallback
AvKtmNotificationCallback, // TransactionNotificationCallback
NULL, // NormalizeNameComponentExCallback
AvScanAbortCallbackAsync // SectionNotificationCallback
};
NTSTATUS
AvInstanceSetup (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_SETUP_FLAGS Flags,
_In_ DEVICE_TYPE VolumeDeviceType,
_In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
)
/*++
Routine Description:
This routine is called whenever a new instance is created on a volume. This
gives us a chance to decide if we need to attach to this volume or not.
If this routine is not defined in the registration structure, automatic
instances are alwasys created.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance and its associated volume.
Flags - Flags describing the reason for this attach request.
Return Value:
STATUS_SUCCESS - attach
STATUS_FLT_DO_NOT_ATTACH - do not attach
--*/
{
NTSTATUS status;
PAV_INSTANCE_CONTEXT instanceContext = NULL;
BOOLEAN isOnCsv = FALSE;
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvInstanceSetup: Entered\n") );
//
// Don't attach to network volumes.
//
if (VolumeDeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) {
return STATUS_FLT_DO_NOT_ATTACH;
}
//
// Determine if the filter is attaching to the hidden NTFS volume
// that corresponds to a CSV volume. If so do not attach. Note
// that it would be feasible for the filter to attach to this
// volume as part of a distrubuted filter implementation but that
// is beyond the scope of this sample.
//
if (VolumeFilesystemType == FLT_FSTYPE_NTFS) {
isOnCsv = AvIsVolumeOnCsvDisk( FltObjects->Volume );
if (isOnCsv) {
return STATUS_FLT_DO_NOT_ATTACH;
}
}
status = FltAllocateContext( Globals.Filter,
FLT_INSTANCE_CONTEXT,
AV_INSTANCE_CONTEXT_SIZE,
NonPagedPoolNx,
&instanceContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvInstanceSetup: allocate instance context failed. status = 0x%x\n", status) );
return STATUS_FLT_DO_NOT_ATTACH;
}
//
// Setup instance context
//
RtlZeroMemory(instanceContext, AV_INSTANCE_CONTEXT_SIZE);
instanceContext->Volume = FltObjects->Volume;
instanceContext->Instance = FltObjects->Instance;
instanceContext->VolumeFSType = VolumeFilesystemType;
instanceContext->IsOnCsvMDS = isOnCsv;
//
// There will be a file state cache table for each NTFS volume instance.
// As for other file systems, file id is not unique, and thus we do
// not have cache for other kinds of file systems. Since the cache
// table is not mandatory to implement an anti-virus filter, we
// only have the volatile cache for NTFS, CSVFS and REFS.
//
// It is worth mentioning that the table is potentially very large.
// We use an AVL tree to improve insertion and query times. We do not
// set an upper bound for the size of the tree which is not optimal.
// Consider limiting the size of the tree for a production filter.
//
if (FS_SUPPORTS_FILE_STATE_CACHE( VolumeFilesystemType )) {
//
// Initialize file state cache in the instance context.
//
ExInitializeResourceLite( &instanceContext->Resource );
RtlInitializeGenericTable( &instanceContext->FileStateCacheTable,
AvCompareEntry,
AvAllocateGenericTableEntry,
AvFreeGenericTableEntry,
NULL );
}
status = FltSetInstanceContext( FltObjects->Instance,
FLT_SET_CONTEXT_KEEP_IF_EXISTS,
instanceContext,
NULL );
//
// In all cases, we need to release the instance context at this time.
// If we hit an error, it will get freed now.
//
FltReleaseContext( instanceContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvInstanceSetup: set instance context failed. status = 0x%x\n", status) );
return STATUS_FLT_DO_NOT_ATTACH;
}
//
// Register this instance as a datascan filter. If this call
// fails the underlying filesystem does not support using
// the filter manager datascan API. Currently only the
// the namedpipe and mailslot file systems are unsupported.
//
status = FltRegisterForDataScan( FltObjects->Instance );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvInstanceSetup: FltRegisterForDataScan failed. status = 0x%x\n", status) );
return STATUS_FLT_DO_NOT_ATTACH;
}
return STATUS_SUCCESS;
}
NTSTATUS
AvInstanceQueryTeardown (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
)
/*++
Routine Description:
This is called when an instance is being manually deleted by a
call to FltDetachVolume or FilterDetach thereby giving us a
chance to fail that detach request.
If this routine is not defined in the registration structure, explicit
detach requests via FltDetachVolume or FilterDetach will always be
failed.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance and its associated volume.
Flags - Indicating where this detach request came from.
Return Value:
Returns the status of this operation.
--*/
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvInstanceQueryTeardown: Entered\n") );
return STATUS_SUCCESS;
}
VOID
AvInstanceTeardownStart (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Unreferenced_parameter_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
)
/*++
Routine Description:
This routine is called at the start of instance teardown.
If we have cache table, we have to clean up the table at this point.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance and its associated volume.
Flags - Reason why this instance is been deleted.
Return Value:
None.
--*/
{
NTSTATUS status;
PLIST_ENTRY scan;
PLIST_ENTRY next;
PAV_SCAN_CONTEXT scanCtx = NULL;
PAV_INSTANCE_CONTEXT instanceContext = NULL;
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[AV] AvInstanceTeardownStart: Entered\n") );
status = FltGetInstanceContext( FltObjects->Instance,
&instanceContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvInstanceTeardownStart: FltGetInstanceContext failed. status = 0x%x\n", status) );
return;
}
//
// Search the scan context from the global list.
//
AvAcquireResourceExclusive( &Globals.ScanCtxListLock );
LIST_FOR_EACH_SAFE( scan, next, &Globals.ScanCtxListHead ) {
scanCtx = CONTAINING_RECORD( scan, AV_SCAN_CONTEXT, List );
if (scanCtx->FilterInstance != FltObjects->Instance) {
continue;
}
//
// Notify the user scan thread to abort the scan.
//
status = AvSendAbortToUser(scanCtx->ScanThreadId,
scanCtx->ScanId);
//
// If we fail to send message to the user, then we
// do the cancel and cleanup by ourself; otherwise,
// the listening thread will call back to cleanup and
// I/O request thred will tear down the scan context.
//
if (!NT_SUCCESS( status ) || status == STATUS_TIMEOUT) {
AvFinalizeScanAndSection(scanCtx);
}
}
AvReleaseResource( &Globals.ScanCtxListLock );
//
// Clean up the cache table if the volume supports one.
//
if (FS_SUPPORTS_FILE_STATE_CACHE( instanceContext->VolumeFSType )) {
PAV_GENERIC_TABLE_ENTRY entry = NULL;
AvAcquireResourceExclusive( &instanceContext->Resource );
while (!RtlIsGenericTableEmpty( &instanceContext->FileStateCacheTable ) ) {
entry = RtlGetElementGenericTable(&instanceContext->FileStateCacheTable, 0);
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvInstanceTeardownStart: %I64x,%I64x requesting deletion, state:%d\n",
entry->FileId.FileId64.UpperZeroes,
entry->FileId.FileId64.Value,
entry->InfectedState) );
RtlDeleteElementGenericTable(&instanceContext->FileStateCacheTable, entry);
}
AvReleaseResource( &instanceContext->Resource );
}
FltReleaseContext( instanceContext );
FltDeleteInstanceContext( FltObjects->Instance, NULL );
}
VOID
AvInstanceTeardownComplete (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
)
/*++
Routine Description:
This routine is called at the end of instance teardown.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance and its associated volume.
Flags - Reason why this instance is been deleted.
Return Value:
None.
--*/
{
UNREFERENCED_PARAMETER( FltObjects );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvInstanceTeardownComplete: Entered\n") );
}
/*************************************************************************
MiniFilter initialization and unload routines.
*************************************************************************/
NTSTATUS
DriverEntry (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
This is the initialization routine for this miniFilter driver. This
registers with FltMgr and initializes all global data structures.
Arguments:
DriverObject - Pointer to driver object created by the system to
represent this driver.
RegistryPath - Unicode string identifying where the parameters for this
driver are located in the registry.
Return Value:
Returns the final status of this operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PSECURITY_DESCRIPTOR sd = NULL;
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] DriverEntry: Entered\n") );
//
// Set default global configuration
//
RtlZeroMemory( &Globals, sizeof(Globals) );
InitializeListHead( &Globals.ScanCtxListHead );
ExInitializeResourceLite( &Globals.ScanCtxListLock );
Globals.ScanIdCounter = 0;
Globals.LocalScanTimeout = 30000;
Globals.NetworkScanTimeout = 60000;
#if DBG
Globals.DebugLevel = 0xffffffff; // AVDBG_TRACE_ERROR | AVDBG_TRACE_DEBUG;
#endif
try {
//
// Set the filter configuration based on registry keys
//
status = AvSetConfiguration( DriverObject, RegistryPath );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV]: DriverEntry: SetConfiguration FAILED. status = 0x%x\n", status) );
leave;
}
//
// Register with FltMgr to tell it our callback routines
//
status = FltRegisterFilter( DriverObject,
&FilterRegistration,
&Globals.Filter );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: FltRegisterFilter FAILED. status = 0x%x\n", status) );
leave;
}
//
// Builds a default security descriptor for use with FltCreateCommunicationPort.
//
status = FltBuildDefaultSecurityDescriptor( &sd,
FLT_PORT_ALL_ACCESS );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: FltBuildDefaultSecurityDescriptor FAILED. status = 0x%x\n", status) );
leave;
}
//
// Prepare ports between kernel and user.
//
status = AvPrepareServerPort( sd, AvConnectForScan );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: AvPrepareServerPort Scan Port FAILED. status = 0x%x\n", status) );
leave;
}
status = AvPrepareServerPort( sd, AvConnectForAbort );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: AvPrepareServerPort Abort Port FAILED. status = 0x%x\n", status) );
leave;
}
status = AvPrepareServerPort( sd, AvConnectForQuery );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: AvPrepareServerPort Query Port FAILED. status = 0x%x\n", status) );
leave;
}
//
// Start filtering i/o
//
status = FltStartFiltering( Globals.Filter );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] DriverEntry: FltStartFiltering FAILED. status = 0x%x\n", status) );
leave;
}
} finally {
if ( sd != NULL ) {
FltFreeSecurityDescriptor( sd );
}
if (!NT_SUCCESS( status ) ) {
if (NULL != Globals.ScanServerPort) {
FltCloseCommunicationPort( Globals.ScanServerPort );
}
if (NULL != Globals.AbortServerPort) {
FltCloseCommunicationPort( Globals.AbortServerPort );
}
if (NULL != Globals.QueryServerPort) {
FltCloseCommunicationPort( Globals.QueryServerPort );
}
if (NULL != Globals.Filter) {
FltUnregisterFilter( Globals.Filter );
Globals.Filter = NULL;
}
ExDeleteResourceLite( &Globals.ScanCtxListLock );
}
}
return status;
}
NTSTATUS
AvUnload (
_Unreferenced_parameter_ FLT_FILTER_UNLOAD_FLAGS Flags
)
/*++
Routine Description:
This is the unload routine for this miniFilter driver. This is called
when the minifilter is about to be unloaded. We can fail this unload
request if this is not a mandatory unloaded indicated by the Flags
parameter.
Arguments:
Flags - Indicating if this is a mandatory unload.
Return Value:
Returns the final status of this operation.
--*/
{
PAGED_CODE();
UNREFERENCED_PARAMETER( Flags );
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[AV] AvUnload: Entered\n") );
//
// Traverse the scan context list, and cancel the scan if it exists.
//
AvAcquireResourceExclusive( &Globals.ScanCtxListLock );
Globals.Unloading = TRUE;
AvReleaseResource( &Globals.ScanCtxListLock );
//
// This function will wait for the user to abort the outstanding scan and
// close the section
//
AvSendUnloadingToUser();
FltCloseCommunicationPort( Globals.ScanServerPort );
Globals.ScanServerPort = NULL;
FltCloseCommunicationPort( Globals.AbortServerPort );
Globals.AbortServerPort = NULL;
FltCloseCommunicationPort( Globals.QueryServerPort );
Globals.QueryServerPort = NULL;
FltUnregisterFilter( Globals.Filter ); // This will typically trigger instance tear down.
Globals.Filter = NULL;
ExDeleteResourceLite( &Globals.ScanCtxListLock );
return STATUS_SUCCESS;
}
/*************************************************************************
Local utility routines.
*************************************************************************/
BOOLEAN
AvOperationsModifyingFile (
_In_ PFLT_CALLBACK_DATA Data
)
/*++
Routine Description:
This identifies those operations we need to set the file to be modified.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
Return Value:
TRUE - If we want the file associated with the request to be modified.
FALSE - If we don't
--*/
{
PFLT_IO_PARAMETER_BLOCK iopb = Data->Iopb;
PAGED_CODE();
switch(iopb->MajorFunction) {
case IRP_MJ_WRITE:
return TRUE;
case IRP_MJ_FILE_SYSTEM_CONTROL:
switch ( iopb->Parameters.FileSystemControl.Common.FsControlCode ) {
case FSCTL_OFFLOAD_WRITE:
case FSCTL_WRITE_RAW_ENCRYPTED:
case FSCTL_SET_ZERO_DATA:
return TRUE;
default: break;
}
break;
case IRP_MJ_SET_INFORMATION:
switch ( iopb->Parameters.SetFileInformation.FileInformationClass ) {
case FileEndOfFileInformation:
case FileValidDataLengthInformation:
return TRUE;
default: break;
}
break;
default:
break;
}
return FALSE;
}
NTSTATUS
AvQueryTransactionOutcome(
_In_ PKTRANSACTION Transaction,
_Out_ PULONG TxOutcome
)
/*++
Routine Description:
This is a helper function that qeury the KTM that how trasnaction was ended.
Arguments:
Transaction - Pointer to transaction object.
TxOutcome - Output. Specifies the type of transaction outcome.
Return Value:
The status of the operation
--*/
{
HANDLE transactionHandle;
NTSTATUS status;
TRANSACTION_BASIC_INFORMATION txBasicInfo = {0};
PAGED_CODE();
status = ObOpenObjectByPointer( Transaction,
OBJ_KERNEL_HANDLE,
NULL,
GENERIC_READ,
*TmTransactionObjectType,
KernelMode,
&transactionHandle );
if (!NT_SUCCESS(status)) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvQueryTransactionOutcome: ObOpenObjectByPointer failed.\n") );
return status;
}
status = ZwQueryInformationTransaction( transactionHandle,
TransactionBasicInformation,
&txBasicInfo,
sizeof(TRANSACTION_BASIC_INFORMATION),
NULL );
if (!NT_SUCCESS(status)) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvQueryTransactionOutcome: ObOpenObjectByPointer failed.\n") );
goto Cleanup;
}
*TxOutcome = txBasicInfo.Outcome;
Cleanup:
ZwClose(transactionHandle);
return status;
}
FORCEINLINE
VOID
AvPropagateFileState(
_Inout_ PAV_STREAM_CONTEXT StreamContext,
_In_ ULONG TransactionOutcome
)
/*++
Routine Description:
An inline function that propagate the TxState to State in stream context.
Arguments:
StreamContext - The stream context to be propagated.
TransactionOutcome - TRANSACTION_OUTCOME enumeration indicating how transaction was ended.
Return Value:
None.
--*/
{
//
// Only when the transaction was committed will we propagate the state.
//
if (TransactionOutcome == TransactionOutcomeCommitted) {
AV_FILE_INFECTED_STATE oldTxState = InterlockedExchange( &StreamContext->TxState, AvFileModified );
switch (oldTxState) {
case AvFileModified:
case AvFileInfected:
case AvFileNotInfected:
//
// Propagate the file state from TxState to State.
//
InterlockedExchange( &StreamContext->State, oldTxState );
break;
case AvFileScanning:
//
// It is possible at KTM callback, file Tx state is still in scanning.
// All we can do here is to be conservative, that is to assume that
// this commit did involve the modification of the file.
//
InterlockedExchange( &StreamContext->State, AvFileModified );
break;
default:
FLT_ASSERTMSG("AvPropagateFileState does not handle the state", FALSE);
break;
}
}
//
// Either cleanup or commited, we need to reset TxState to be default state.
//
SET_FILE_TX_MODIFIED( StreamContext );
}
NTSTATUS
AvProcessTransactionOutcome (
_Inout_ PAV_TRANSACTION_CONTEXT TransactionContext,
_In_ ULONG TransactionOutcome
)
/*++
Routine Description:
This is a helper function that process transaction commitment or rollback
Arguments:
TransactionContext - Pointer to the minifilter driver's transaction context
set at PostCreate.
TransactionOutcome - Specifies the type of notifications. Should be either
TransactionOutcomeCommitted or TransactionOutcomeAborted
Return Value:
STATUS_SUCCESS - Returning this status value indicates that the minifilter
driver is finished with the transaction. This is a success code.
--*/
{
PLIST_ENTRY scan;
PLIST_ENTRY next;
PAV_STREAM_CONTEXT streamContext = NULL;
PAV_TRANSACTION_CONTEXT oldTxCtx = NULL;
PAGED_CODE();
//
// Tranversing the stream context list, and
// sync the TxState -> State.
//
// Either commit or rollback, we need to cleanup the list
// Tear down stream context list inside transactionContext
//
AvAcquireResourceExclusive( TransactionContext->Resource );
LIST_FOR_EACH_SAFE( scan, next, &TransactionContext->ScListHead ) {
streamContext = CONTAINING_RECORD( scan, AV_STREAM_CONTEXT, ListInTransaction );
oldTxCtx = InterlockedCompareExchangePointer( &streamContext->TxContext, NULL, TransactionContext );
if (oldTxCtx == TransactionContext) {
//
// The exchange pointer was successful
//
RemoveEntryList ( scan );
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[AV] AvProcessTransactionOutcome: Requesting deletion of entry in transaction context: %I64x,%I64x, modified: %d\n",
streamContext->FileId.FileId64.UpperZeroes,
streamContext->FileId.FileId64.Value,
IS_FILE_MODIFIED( streamContext ) ) );
AvPropagateFileState( streamContext, TransactionOutcome );
FltReleaseContext( oldTxCtx );
FltReleaseContext( streamContext );
}
}
SetFlag( TransactionContext->Flags, AV_TXCTX_LISTDRAINED );
AvReleaseResource( TransactionContext->Resource );
return STATUS_SUCCESS;
}
NTSTATUS
AvLoadFileStateFromCache (
_In_ PFLT_INSTANCE Instance,
_In_ PAV_FILE_REFERENCE FileId,
_Out_ LONG volatile *State,
_Out_ PLONGLONG VolumeRevision,
_Out_ PLONGLONG CacheRevision,
_Out_ PLONGLONG FileRevision
)
/*++
Routine Description:
This routine lookups the file state in the cache table.
Arguments:
Instance - Opaque filter pointer for the caller. This parameter is required and cannot be NULL.
FileID - The ID to lookup in the cache
State - The cached state for the file
Return Value:
Returns the final status of this operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PAV_INSTANCE_CONTEXT instanceContext = NULL;
AV_GENERIC_TABLE_ENTRY query = {0};
PAV_GENERIC_TABLE_ENTRY entry = NULL;
PAGED_CODE();
//
// We should never be trying to cache with an invalid fileID.
//
ASSERT( !AV_INVALID_FILE_REFERENCE(*FileId) );
status = FltGetInstanceContext( Instance,
&instanceContext );
if (!NT_SUCCESS( status )){
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvLoadFileStateFromCache: failed to get instance context.\n") );
return status;
}
if (! FS_SUPPORTS_FILE_STATE_CACHE( instanceContext->VolumeFSType )) {
status = STATUS_NOT_FOUND;
goto Cleanup;
}
RtlCopyMemory( &query.FileId, FileId, sizeof(query.FileId) );
AvAcquireResourceShared( &instanceContext->Resource );
entry = RtlLookupElementGenericTable( &instanceContext->FileStateCacheTable,
&query );
if (entry != NULL) {
*State = entry->InfectedState;
*VolumeRevision = entry->VolumeRevision;
*CacheRevision = entry->CacheRevision;
*FileRevision = entry->FileRevision;
} else {
status = STATUS_NOT_FOUND;
}
AvReleaseResource( &instanceContext->Resource );
Cleanup:
FltReleaseContext( instanceContext );
return status;
}
NTSTATUS
AvSyncCache (
_In_ PFLT_INSTANCE Instance,
_In_ PAV_STREAM_CONTEXT StreamContext
)
/*++
Routine Description:
This routine sync the file state from stream context to volatile cache table.
It is file system transparent.
Arguments:
Instance - Opaque filter pointer for the caller. This parameter is required and cannot be NULL.
StreamContext - The stream context of the target file.
Return Value:
Returns the final status of this operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
BOOLEAN inserted = FALSE;
AV_GENERIC_TABLE_ENTRY entry = {0};
PAV_GENERIC_TABLE_ENTRY pEntry = NULL;
PAV_INSTANCE_CONTEXT instanceContext = NULL;
PAGED_CODE();
if ((NULL == Instance) ||
(NULL == StreamContext)) {
return STATUS_INVALID_PARAMETER;
}
status = FltGetInstanceContext( Instance, &instanceContext );
if (!NT_SUCCESS( status )){
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvSyncCache: failed to get instance context.\n") );
return status;
}
//
// If the file system is not NTFS, CSVFS or REFS, do nothing
//
if (!FS_SUPPORTS_FILE_STATE_CACHE( instanceContext->VolumeFSType )) {
goto Cleanup;
}
//
// If originally, we failed to get the file id,
// then we do not cache it.
//
if (AV_INVALID_FILE_REFERENCE( StreamContext->FileId )) {
goto Cleanup;
}
//
// If the file system is NTFS, CSVFS or REFS, overwrite the entry in the
// cache table if exists
//
RtlCopyMemory( &entry.FileId, &StreamContext->FileId, sizeof(entry.FileId) );
AvAcquireResourceExclusive( &instanceContext->Resource );
pEntry = RtlInsertElementGenericTable( &instanceContext->FileStateCacheTable,
(PVOID) &entry,
AV_GENERIC_TABLE_ENTRY_SIZE,
&inserted);
if (pEntry) {
//
// Note the cache may become stale as files are modified.
//
//
// It is possible that after entering the following else-if
// branch, thread A modifies the file, and before thread A
// closes the handle, thread B opens the same file. This
// is fine because in such a case, the streamcontext exists
// AvLoadFileStateFromCache would return the state in stream
// context. Thus, thread B will need to scan the file.
//
pEntry->InfectedState = StreamContext->State;
pEntry->VolumeRevision = StreamContext->VolumeRevision;
pEntry->CacheRevision = StreamContext->CacheRevision;
pEntry->FileRevision = StreamContext->FileRevision;
}
AvReleaseResource( &instanceContext->Resource );
if (!pEntry) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvSyncCache: RtlInsertElementGenericTable failed.\n") );
}
Cleanup:
FltReleaseContext( instanceContext );
return status;
}
BOOLEAN
AvIsPrefetchEcpPresent (
_In_ PFLT_FILTER Filter,
_In_ PFLT_CALLBACK_DATA Data
)
/*++
Routine Description:
This local function will return if this data stream is alternate or not.
It by default returns FALSE if it fails to retrieve the name information
from the file system.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
Return Value:
TRUE - This data stream is alternate.
FALSE - This data stream is NOT alternate.
--*/
{
NTSTATUS status;
PECP_LIST ecpList;
PVOID ecpContext;
PAGED_CODE();
status = FltGetEcpListFromCallbackData( Filter, Data, &ecpList );
if (NT_SUCCESS(status) && (ecpList != NULL)) {
status = FltFindExtraCreateParameter( Filter,
ecpList,
&GUID_ECP_PREFETCH_OPEN,
&ecpContext,
NULL );
if (NT_SUCCESS(status)) {
if (!FltIsEcpFromUserMode( Filter, ecpContext )) {
return TRUE;
}
}
}
return FALSE;
}
BOOLEAN
AvIsStreamAlternate(
_Inout_ PFLT_CALLBACK_DATA Data
)
/*++
Routine Description:
This local function will return if this data stream is alternate or not.
It by default returns FALSE if it fails to retrieve the name information
from the file system.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
Return Value:
TRUE - This data stream is alternate.
FALSE - This data stream is NOT alternate.
--*/
{
NTSTATUS status;
BOOLEAN alternate = FALSE;
PFLT_FILE_NAME_INFORMATION nameInfo = NULL;
PAGED_CODE();
status = FltGetFileNameInformation( Data,
FLT_FILE_NAME_OPENED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP,
&nameInfo );
if (!NT_SUCCESS(status)) {
goto Cleanup;
}
status = FltParseFileNameInformation( nameInfo );
if (!NT_SUCCESS(status)) {
goto Cleanup;
}
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[Av]: Dir: %wZ, FinalComponent: %wZ, Stream: %wZ, sLen: %d\n",
nameInfo->ParentDir,
nameInfo->FinalComponent,
nameInfo->Stream,
nameInfo->Stream.Length) );
alternate = (nameInfo->Stream.Length > 0);
Cleanup:
if (nameInfo != NULL) {
FltReleaseFileNameInformation( nameInfo );
nameInfo = NULL;
}
return alternate;
}
NTSTATUS
AvScan (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ AV_SCAN_MODE ScanMode,
_In_ UCHAR IOMajorFunctionAtScan,
_In_ BOOLEAN IsInTxWriter,
_Inout_ PAV_STREAM_CONTEXT StreamContext
)
/*++
Routine Description:
This routine kicks of a scan.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
ScanMode - Can either be AvUserMode or AvKernelMode.
IOMajorFunctionAtScan - Major function of an IRP.
StreamContext - The stream context of the target file.
Return Value:
Returns the final status of this operation.
STATUS_TIMEOUT - if scan in user mode and the thread reference fails,
then it would wait for the scan finish event with a timeout.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
LONGLONG fileSize;
FLT_VOLUME_PROPERTIES volumeProperties;
ULONG volumePropertiesLength;
PAGED_CODE();
//
// Skip the empty file.
//
status = AvGetFileSize( FltObjects->Instance,
FltObjects->FileObject,
&fileSize );
if (NT_SUCCESS( status ) &&
(0 == fileSize)) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[Av]: AvScan: Skip the EMPTY file.\n") );
// As if we have 'scanned' this empty file.
SET_FILE_NOT_INFECTED( StreamContext );
return STATUS_SUCCESS;
}
//
// We could cause deadlocks if the thread were suspended once
// we have started scanning so enter a critical region.
//
FsRtlEnterFileSystem();
//
// Wait here for an existing scan on the stream to complete.
// We wait indefinitely since scans themselves will timeout.
//
status = FltCancellableWaitForSingleObject( StreamContext->ScanSynchronizationEvent,
NULL,
Data );
if (NT_SUCCESS(status)) {
//
// Check again in case the file was scanned during the wait
// and is already known to be clean
//
if (IS_FILE_NEED_SCAN( StreamContext )){
if (ScanMode == AvUserMode) {
status = FltGetVolumeProperties( FltObjects->Volume,
&volumeProperties,
sizeof(volumeProperties),
&volumePropertiesLength );
if (!NT_SUCCESS(status)) {
volumeProperties.DeviceType = FILE_DEVICE_NETWORK;
}
//
// If the scan mode is user mode, the section context will
// be created as needed (at MessageNotification callback).
//
// Setting the file state will be done at
// MessageNotification callback as well.
//
status = AvScanInUser( Data,
FltObjects,
IOMajorFunctionAtScan,
IsInTxWriter,
volumeProperties.DeviceType );
if (!NT_SUCCESS( status ) || status == STATUS_TIMEOUT) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvScan: failed to scan the file.\n") );
}
} else {
status = AvScanInKernel( FltObjects,
IOMajorFunctionAtScan,
IsInTxWriter,
StreamContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvScan: failed to scan the file.\n") );
}
}
}
//
// Signal ScanSynchronizationEvent to release any con-current scan of the stream,
//
KeSetEvent( StreamContext->ScanSynchronizationEvent, 0, FALSE );
} else if (IOMajorFunctionAtScan == IRP_MJ_CREATE) {
//
// I/O requesting thread if waiting on synchronization event is cancelled,
// we need to clean up the file object too.
//
AvCancelFileOpen(Data, FltObjects, status);
}
FsRtlExitFileSystem();
return status;
}
VOID
AvDoCancelScanAndRelease (
_In_ PAV_SCAN_CONTEXT ScanContext,
_In_ PAV_SECTION_CONTEXT SectionContext
)
/*++
Routine Description:
This routine closes the section object, and released all waiting threads.
Arguments:
ScanContext - The scan context.
SectionContext - The section context associated with the scan context.
Return Value:
None.
--*/
{
NTSTATUS status;
PAV_STREAM_CONTEXT streamContext = NULL;
PAGED_CODE();
AvFinalizeSectionContext( SectionContext );
status = FltGetStreamContext( ScanContext->FilterInstance,
ScanContext->FileObject,
&streamContext );
if (NT_SUCCESS( status )) {
KeSetEvent( streamContext->ScanSynchronizationEvent, 0, FALSE );
FltReleaseContext( streamContext );
}
//
// Release I/O request thread.
//
KeSetEvent( &ScanContext->ScanCompleteNotification, 0, FALSE );
return;
}
NTSTATUS
AvSendAbortToUser (
_In_ ULONG ScanThreadId,
_In_ LONGLONG ScanId
)
/*++
Routine Description:
This routine sends an abortion message to the user scan thread.
The cancel callback is asynchronous and thus we send which
scan id to abort; otherwise the worker thread in the user
may abort the 'next' scan task.
Arguments:
ScanThreadId - The thread identifier of whom to be aborted.
ScanId - Which scan task to be aborted.
Return Value:
The return value is the status of the operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
ULONG replyLength = 0;
LARGE_INTEGER timeout = {0};
AV_SCANNER_NOTIFICATION notification = {0};
PAGED_CODE();
notification.Message = AvMsgAbortScanning;
notification.ScanThreadId = ScanThreadId;
notification.ScanId = ScanId;
timeout.QuadPart = -((LONGLONG)10) * (LONGLONG)1000 * (LONGLONG)1000; // 1s
//
// Tell the user-scanner to abort the scan.
//
status = FltSendMessage( Globals.Filter,
&Globals.AbortClientPort,
¬ification,
sizeof(AV_SCANNER_NOTIFICATION),
NULL,
&replyLength,
&timeout );
if (!NT_SUCCESS( status ) ||
(status == STATUS_TIMEOUT)) {
if ((status != STATUS_PORT_DISCONNECTED) &&
(status != STATUS_TIMEOUT)) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: AvSendAbortToUser: Failed to FltSendMessage.\n, 0x%08x\n",
status) );
}
return status;
}
return status;
}
NTSTATUS
AvSendUnloadingToUser (
VOID
)
/*++
Routine Description:
This routine sends unloading message to the user program.
Arguments:
None.
Return Value:
The return value is the status of the operation.
--*/
{
ULONG abortThreadId;
NTSTATUS status = STATUS_SUCCESS;
ULONG replyLength = sizeof(ULONG);
AV_SCANNER_NOTIFICATION notification = {0};
PAGED_CODE();
notification.Message = AvMsgFilterUnloading;
//
// Tell the user-scanner that we are unloading the filter.
// and waits for its reply.
//
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[Av]: AvSendUnloadingToUser: BEFORE...\n") );
status = FltSendMessage( Globals.Filter,
&Globals.AbortClientPort,
¬ification,
sizeof(AV_SCANNER_NOTIFICATION),
&abortThreadId,
&replyLength,
NULL );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: AvSendUnloadingToUser: Failed to FltSendMessage.\n, 0x%08x\n",
status) );
}
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[Av]: AvSendUnloadingToUser: After...\n") );
return status;
}
/*************************************************************************
MiniFilter callback routines.
*************************************************************************/
FLT_PREOP_CALLBACK_STATUS
AvPreOperationCallback (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
This routine is the registered callback routine for filtering
the "write" operation, i.e. the operations that have potentials
to modify the file.
This is non-pageable because it could be called on the paging path
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - If this callback routine returns FLT_PREOP_SUCCESS_WITH_CALLBACK or
FLT_PREOP_SYNCHRONIZE, this parameter is an optional context pointer to be passed to
the corresponding post-operation callback routine. Otherwise, it must be NULL.
Return Value:
The return value is the status of the operation.
--*/
{
NTSTATUS status;
PAV_STREAM_CONTEXT streamContext = NULL;
PAV_STREAMHANDLE_CONTEXT streamHandleContext = NULL;
ULONG flags;
UNREFERENCED_PARAMETER( CompletionContext );
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPreOperationCallback: Entered\n") );
if (!AvOperationsModifyingFile(Data)) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Skip prefetcher handles to avoid deadlocks
//
status = FltGetStreamHandleContext( FltObjects->Instance,
FltObjects->FileObject,
&streamHandleContext );
if (NT_SUCCESS(status)) {
flags = streamHandleContext->Flags;
FltReleaseContext( streamHandleContext );
if (FlagOn( flags, AV_FLAG_PREFETCH )) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
}
status = FltGetStreamContext( FltObjects->Instance,
FltObjects->FileObject,
&streamContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPreOperationCallback: get stream context failed. rq: %d\n",
Data->Iopb->MajorFunction) );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// If this operation is performed in a transacted writer view.
//
if ((streamContext->TxContext != NULL) &&
(FltObjects->Transaction != NULL)) {
#if DBG
PAV_TRANSACTION_CONTEXT transactionContext = NULL;
NTSTATUS statusTx = FltGetTransactionContext( FltObjects->Instance,
FltObjects->Transaction,
&transactionContext );
FLT_ASSERTMSG( "Transaction context should not fail, because it is supposed to be created at post create.\n", NT_SUCCESS( statusTx ));
FLT_ASSERTMSG( "The file's TxCtx should be identical with the target TxCtx.\n",
streamContext->TxContext == transactionContext);
if (NT_SUCCESS( statusTx )) {
FltReleaseContext( transactionContext );
}
#endif // DBG
//
// Instead of updating State, we update TxState here,
// because the file is part of a transaction writer
//
SET_FILE_TX_MODIFIED( streamContext );
} else {
//
// Consider an optimization for the case where another thread
// is already scanning the file as it is being modified here.
//
SET_FILE_MODIFIED( streamContext );
}
FltReleaseContext( streamContext );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
FLT_PREOP_CALLBACK_STATUS
AvPreFsControl (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
Pre-file system control callback. This filter example does not support save point feature.
So, we explicitly fail the request here.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - If this callback routine returns FLT_PREOP_SUCCESS_WITH_CALLBACK or
FLT_PREOP_SYNCHRONIZE, this parameter is an optional context pointer to be passed to
the corresponding post-operation callback routine. Otherwise, it must be NULL.
Return Value:
The return value is the status of the operation.
--*/
{
PAGED_CODE();
if (Data->Iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_TXFS_SAVEPOINT_INFORMATION ) {
//
// We explicitly fail the request of save point here since we
// are deprecating savepoint support for the OS version targeted
// for this filter.
//
Data->IoStatus.Status = STATUS_NOT_SUPPORTED;
return FLT_PREOP_COMPLETE;
}
return AvPreOperationCallback(Data, FltObjects, CompletionContext);
}
FLT_PREOP_CALLBACK_STATUS
AvPreCreate (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
This routine is the pre-create completion routine.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - If this callback routine returns FLT_PREOP_SUCCESS_WITH_CALLBACK or
FLT_PREOP_SYNCHRONIZE, this parameter is an optional context pointer to be passed to
the corresponding post-operation callback routine. Otherwise, it must be NULL.
Return Value:
FLT_PREOP_SYNCHRONIZE - PostCreate needs to be called back synchronizedly.
FLT_PREOP_SUCCESS_NO_CALLBACK - PostCreate does not need to be called.
--*/
{
ULONG_PTR stackLow;
ULONG_PTR stackHigh;
PFILE_OBJECT FileObject = Data->Iopb->TargetFileObject;
AV_STREAMHANDLE_CONTEXT streamHandleContext;
PAGED_CODE();
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPreCreate: Entered\n") );
streamHandleContext.Flags = 0;
//
// Stack file objects are never scanned.
//
IoGetStackLimits( &stackLow, &stackHigh );
if (((ULONG_PTR)FileObject > stackLow) &&
((ULONG_PTR)FileObject < stackHigh)) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Directory opens don't need to be scanned.
//
if (FlagOn( Data->Iopb->Parameters.Create.Options, FILE_DIRECTORY_FILE )) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Skip pre-rename operations which always open a directory.
//
if ( FlagOn( Data->Iopb->OperationFlags, SL_OPEN_TARGET_DIRECTORY )) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Skip paging files.
//
if (FlagOn( Data->Iopb->OperationFlags, SL_OPEN_PAGING_FILE )) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Skip scanning DASD opens
//
if (FlagOn( FltObjects->FileObject->Flags, FO_VOLUME_OPEN )) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Skip scanning any files being opened by CSVFS for its downlevel
// processing. This includes filters on the hidden NTFS stack and
// for filters attached to MUP
//
if (AvIsCsvDlEcpPresent( FltObjects->Filter, Data ) ) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// Flag prefetch handles so they can be skipped. Performing IO
// using a prefetch fileobject could lead to a deadlock.
//
if (AvIsPrefetchEcpPresent( FltObjects->Filter, Data )) {
SetFlag( streamHandleContext.Flags, AV_FLAG_PREFETCH );
}
*CompletionContext = (PVOID)streamHandleContext.Flags;
//
// Perform any CSVFS pre create processing
//
AvPreCreateCsvfs( Data, FltObjects );
//
// return status can be safely ignored
//
//
// Return FLT_PREOP_SYNCHRONIZE at PreCreate to ensure PostCreate
// is in the same thread at passive level.
// EResource can't be acquired at DPC.
//
return FLT_PREOP_SYNCHRONIZE;
}
NTSTATUS
AvProcessPreviousTransaction (
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Inout_ PAV_STREAM_CONTEXT StreamContext
)
/*++
Routine Description:
This routine is transaction related implementation, and is expected to be
invoked at post-create. Note that this function will enlist the newly
allocated transaction context via FltEnlistInTransaction if it needs to.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
StreamContext - The stream context.
Return Value:
The return value is the status of the operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PAV_TRANSACTION_CONTEXT oldTxCtx = NULL;
PAV_TRANSACTION_CONTEXT transactionContext = NULL;
PAGED_CODE();
if (FltObjects->Transaction != NULL ) {
//
// Get transaction context
//
status = AvFindOrCreateTransactionContext( FltObjects,
&transactionContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvProcessPreviousTransaction: AvFindOrCreateTransactionContext FAILED\n") );
transactionContext = NULL;
goto Cleanup;
}
//
// Enlist it if haven't.
//
if (! FlagOn(transactionContext->Flags, AV_TXCTX_ENLISTED) ) {
//
// You can also consider to register TRANSACTION_NOTIFY_PREPARE,
// and scan the file at TRANSACTION_NOTIFY_PREPARE callback if it was modified.
//
status = FltEnlistInTransaction( FltObjects->Instance,
FltObjects->Transaction,
transactionContext,
TRANSACTION_NOTIFY_COMMIT_FINALIZE | TRANSACTION_NOTIFY_ROLLBACK );
if (!NT_SUCCESS( status ) &&
(status != STATUS_FLT_ALREADY_ENLISTED)) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvProcessPreviousTransaction: FltEnlistInTransaction FAILED!!!!\n") );
goto Cleanup;
}
status = STATUS_SUCCESS;
SetFlag( transactionContext->Flags, AV_TXCTX_ENLISTED );
}
}
//
// Here we have five cases:
//
// 1)
// oldTxCtx : NULL
// transCtx : B
// 2)
// oldTxCtx : A
// transCtx : NULL
// 3)
// oldTxCtx : A
// transCtx : B
// 4)
// oldTxCtx : A
// transCtx : A
// 5)
// oldTxCtx : NULL
// transCtx : NULL
//
//
// Synchronize the replacement of StreamContext->TxContext with KTM callback.
//
oldTxCtx = InterlockedExchangePointer( &StreamContext->TxContext, transactionContext );
if (oldTxCtx != transactionContext) { // case 1,2,3
//
// txOutcome is by default set as committed because we are conservative about
// propagating the file state if AvQueryTransactionOutcome failed, it may cause
// redundant scan but will not overlook infected file anyway.
//
ULONG txOutcome = TransactionOutcomeCommitted;
if ( oldTxCtx == NULL ) { // case 1
// This file was not linked in a transaction context yet, and is about to.
//
// Increment TxContext's reference count because stream context has a reference to it.
//
FltReferenceContext ( transactionContext );
//
// Before insertion into the FcList in transaction context, we increment stream context's ref count
//
AvAcquireResourceExclusive( transactionContext->Resource );
if (!FlagOn(transactionContext->Flags, AV_TXCTX_LISTDRAINED)) {
FltReferenceContext ( StreamContext ); // Q
InsertTailList( &transactionContext->ScListHead,
&StreamContext->ListInTransaction );
}
AvReleaseResource( transactionContext->Resource );
goto Cleanup;
}
// case 2,3
//
// We have to query transaction outcome in order to know how we
// can process the previously outstanding transaction context.
//
status = AvQueryTransactionOutcome( oldTxCtx->Transaction, &txOutcome );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvProcessPreviousTransaction: AvQueryTransactionOutcome FAILED!!!!\n") );
//
// We have exchanged the pointer anyway, if we cannot query its outcome,
// we have to go through.
//
}
AvAcquireResourceExclusive( oldTxCtx->Resource );
RemoveEntryList ( &StreamContext->ListInTransaction );
AvReleaseResource( oldTxCtx->Resource );
AvPropagateFileState ( StreamContext, txOutcome );
if ( transactionContext ) { // case 3
FltReferenceContext( StreamContext );
AvAcquireResourceExclusive( transactionContext->Resource );
if (!FlagOn(transactionContext->Flags, AV_TXCTX_LISTDRAINED)) {
InsertTailList( &transactionContext->ScListHead,
&StreamContext->ListInTransaction );
} else {
FltReleaseContext( StreamContext );
}
AvReleaseResource( transactionContext->Resource );
} else { // case 2
FltReleaseContext ( StreamContext ); // Release reference count at Q
}
// case 2,3
FltReleaseContext( oldTxCtx ); // Release reference count in stream context originally.
}
//
// We don't care about case 4, 5.
//
Cleanup:
if (transactionContext) {
FltReleaseContext( transactionContext ); // Release the ref count grabbed at AvFindOrCreateTransactionContext(...)
}
return status;
}
FLT_POSTOP_CALLBACK_STATUS
AvPostCreate (_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_In_opt_ PVOID CompletionContext,
_In_ FLT_POST_OPERATION_FLAGS Flags
)
/*++
Routine Description:
This routine is the post-create completion routine.
In this routine, stream context and/or transaction context shall be
created if not exits.
Note that we only allocate and set the stream context to filter manager
at post create.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - The completion context set in the pre-create routine.
Flags - Denotes whether the completion is successful or is being drained.
Return Value:
The return value is the status of the operation.
--*/
{
NTSTATUS status = Data->IoStatus.Status;
BOOLEAN isDir = FALSE;
BOOLEAN isTxWriter = FALSE;
PAV_STREAM_CONTEXT streamContext = NULL;
PAV_STREAM_CONTEXT oldStreamContext = NULL;
PAV_STREAMHANDLE_CONTEXT streamHandleContext = NULL;
ACCESS_MASK desiredAccess = Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess;
BOOLEAN updateRevisionNumbers;
LONGLONG VolumeRevision, CacheRevision, FileRevision;
UNREFERENCED_PARAMETER( CompletionContext );
UNREFERENCED_PARAMETER( Flags );
PAGED_CODE();
if (!NT_SUCCESS( status ) ||
(status == STATUS_REPARSE)) {
//
// File Creation may fail.
//
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPostCreate: file creation failed\n") );
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// After creation, skip it if it is directory.
//
status = FltIsDirectory( FltObjects->FileObject,
FltObjects->Instance,
&isDir );
//
// If FltIsDirectory failed, we do not know if it is a directoy,
// we let it go through because if it is a directory, it will fail
// at section creation anyway.
//
if ( NT_SUCCESS( status ) && isDir ) {
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// We skip the encrypted file open without FILE_WRITE_DATA and FILE_READ_DATA
// This is because if application calls OpenEncryptedFileRaw(...) for backup,
// it won't have to decrypt the file. In such case, if we scan it, we will hit
// an assertion error in NTFS because it does not have the encryption context.
// Thus, we have to skip the encrypted file not open for read/write.
//
if (!(FlagOn(desiredAccess, FILE_WRITE_DATA)) &&
!(FlagOn(desiredAccess, FILE_READ_DATA)) ) {
BOOLEAN encrypted = FALSE;
status = AvGetFileEncrypted( FltObjects->Instance,
FltObjects->FileObject,
&encrypted );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPostCreate: AvGetFileEncrypted FAILED!! \n0x%x\n", status) );
}
if (encrypted) {
return FLT_POSTOP_FINISHED_PROCESSING;
}
}
//
// In this sample, we skip the alternate data stream. However, you may decide
// to scan it and modify accordingly.
//
if (AvIsStreamAlternate( Data )) {
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// Skip a prefetch open and flag it so we skip subsequent
// IO operations on the handle.
//
if (FlagOn((ULONG_PTR)CompletionContext, AV_FLAG_PREFETCH)) {
if (!FltSupportsStreamHandleContexts( FltObjects->FileObject )) {
return FLT_POSTOP_FINISHED_PROCESSING;
}
status = AvCreateStreamHandleContext( FltObjects->Filter,
&streamHandleContext );
if (!NT_SUCCESS(status)) {
return FLT_POSTOP_FINISHED_PROCESSING;
}
SetFlag( streamHandleContext->Flags, AV_FLAG_PREFETCH );
status = FltSetStreamHandleContext( FltObjects->Instance,
FltObjects->FileObject,
FLT_SET_CONTEXT_KEEP_IF_EXISTS,
streamHandleContext,
NULL );
FltReleaseContext( streamHandleContext );
if (!NT_SUCCESS(status)) {
//
// Shouldn't find the handle already set
//
ASSERT( status != STATUS_FLT_CONTEXT_ALREADY_DEFINED );
}
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// Find or create a stream context
//
status = FltGetStreamContext( FltObjects->Instance,
FltObjects->FileObject,
&streamContext );
if (status == STATUS_NOT_FOUND) {
//
// Create a stream context
//
status = AvCreateStreamContext( FltObjects->Filter, &streamContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: Failed to create stream context with status 0x%x. (FileObject = %p, Instance = %p)\n",
status,
FltObjects->FileObject,
FltObjects->Instance) );
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// Attempt to get the stream infected state from our cache
//
status = AvGetFileId( FltObjects->Instance, FltObjects->FileObject, &streamContext->FileId );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[Av]: Failed to get file id with status 0x%x. (FileObject = %p, Instance = %p)\n",
status,
FltObjects->FileObject,
FltObjects->Instance) );
//
// File id is optional and therefore should not affect the scan logic.
//
AV_SET_INVALID_FILE_REFERENCE( streamContext->FileId )
} else {
//
// This function will load the file infected state from the
// cache if the fileID is valid. Even if this function fails,
// we still have to move on because the cache is optional.
//
AvLoadFileStateFromCache( FltObjects->Instance,
&streamContext->FileId,
&streamContext->State,
&streamContext->VolumeRevision,
&streamContext->CacheRevision,
&streamContext->FileRevision );
}
//
// Set the new context we just allocated on the file object
//
status = FltSetStreamContext( FltObjects->Instance,
FltObjects->FileObject,
FLT_SET_CONTEXT_KEEP_IF_EXISTS,
streamContext,
&oldStreamContext );
if (!NT_SUCCESS(status)) {
if (status == STATUS_FLT_CONTEXT_ALREADY_DEFINED) {
//
// Race condition. Someone has set a context after we queried it.
// Use the already set context instead
//
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: Race: Stream context already defined. Retaining old stream context %p (FileObject = %p, Instance = %p)\n",
oldStreamContext,
FltObjects->FileObject,
FltObjects->Instance) );
FltReleaseContext( streamContext );
streamContext = oldStreamContext;
} else {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: Failed to set stream context with status 0x%x. (FileObject = %p, Instance = %p)\n",
status,
FltObjects->FileObject,
FltObjects->Instance) );
goto Cleanup;
}
}
} else if (!NT_SUCCESS(status)) {
//
// We will get here if stream contexts are not supported
//
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[Av]: Failed to get stream context with status 0x%x. (FileObject = %p, Instance = %p)\n",
status,
FltObjects->FileObject,
FltObjects->Instance) );
return FLT_POSTOP_FINISHED_PROCESSING;
}
//
// If successfully opened a file with the desired access matching
// the "exclusive write" from a TxF point of view, we can guarantee that
// if previous transaction context exists, it must have been comitted
// or rollbacked.
//
if (FlagOn( Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess,
FILE_WRITE_DATA | FILE_APPEND_DATA |
DELETE | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA |
WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY ) ) {
//
// Either this file is opened in a transaction context or not,
// we need to process the previous transaction if it exists.
// AvProcessPreviousTransaction(...) handles these cases.
//
status = AvProcessPreviousTransaction ( FltObjects,
streamContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvPostCreate: AvProcessTransaction FAILED!! \n") );
goto Cleanup;
}
isTxWriter = (FltObjects->Transaction != NULL);
}
//
// Perform any CSVFS specific processing
//
AvPostCreateCsvfs( Data,
FltObjects,
streamContext,
&updateRevisionNumbers,
&VolumeRevision,
&CacheRevision,
&FileRevision );
//
// Ignore return status
//
if (IS_FILE_NEED_SCAN( streamContext )) {
status = AvScan( Data,
FltObjects,
AvUserMode,
Data->Iopb->MajorFunction,
isTxWriter,
streamContext );
if (!NT_SUCCESS( status ) ||
(STATUS_TIMEOUT == status)) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPostCreate: AvScan FAILED!! \n") );
goto Cleanup;
}
}
//
// If needed, update the stream context with the latest revision
// numbers that correspond to the verion just scanned
//
if (updateRevisionNumbers) {
streamContext->VolumeRevision = VolumeRevision;
streamContext->CacheRevision = CacheRevision;
streamContext->FileRevision = FileRevision;
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[Av]: AvPostCreate: RevisionNumbers updated to %I64x:%I64x:%I64x\n",
VolumeRevision,
CacheRevision,
FileRevision)
);
}
if (IS_FILE_INFECTED( streamContext )) {
//
// If the file is infected, deny the access.
//
AvCancelFileOpen(Data, FltObjects, STATUS_VIRUS_INFECTED);
//
// If the scan timed-out or scan was failed, we let the create succeed,
// and it may cause security hole;
//
// Alternatively, you can add a state called AvFileScanFailure or equivalent,
// add a condition here and fail the create. This option will have better
// protection from viruses, but the apps will see the failures due to a
// lengthy scan or scan failure. It's a trade-off.
//
goto Cleanup;
}
Cleanup:
FltReleaseContext( streamContext );
return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS
AvPreCleanup (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
/*++
Routine Description:
Pre-cleanup callback. Make the stream context persistent in the volatile cache.
If the file is transacted, it will be synced at KTM notification callback
if committed.
Arguments:
Data - Pointer to the filter callbackData that is passed to us.
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
CompletionContext - If this callback routine returns FLT_PREOP_SUCCESS_WITH_CALLBACK or
FLT_PREOP_SYNCHRONIZE, this parameter is an optional context pointer to be passed to
the corresponding post-operation callback routine. Otherwise, it must be NULL.
Return Value:
The return value is the status of the operation.
--*/
{
NTSTATUS status;
BOOLEAN encrypted = FALSE;
PAV_STREAM_CONTEXT streamContext = NULL;
PAV_STREAMHANDLE_CONTEXT streamHandleContext = NULL;
ULONG_PTR stackLow;
ULONG_PTR stackHigh;
BOOLEAN updateRevisionNumbers;
LONGLONG VolumeRevision, CacheRevision, FileRevision;
UNREFERENCED_PARAMETER( CompletionContext );
PAGED_CODE();
//
// Skip scan on prefetcher handles to avoid deadlocks
//
status = FltGetStreamHandleContext( FltObjects->Instance,
FltObjects->FileObject,
&streamHandleContext );
if (NT_SUCCESS(status)) {
if (FlagOn( streamHandleContext->Flags, AV_FLAG_PREFETCH )) {
//
// Because the Memory Manager can cache the file object
// and use it for other applications performing mapped I/O,
// whenever a Cleanup operation is seen on a prefetcher
// file object, that file object should no longer be
// considered prefetcher-opened.
//
RtlInterlockedClearBits( &streamHandleContext->Flags,
AV_FLAG_PREFETCH );
FltDeleteStreamHandleContext( FltObjects->Instance,
FltObjects->FileObject,
NULL );
FltReleaseContext( streamHandleContext );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
FltReleaseContext( streamHandleContext );
}
//
// Stack file objects are never scanned.
//
IoGetStackLimits( &stackLow, &stackHigh );
if (((ULONG_PTR)FltObjects->FileObject > stackLow) &&
((ULONG_PTR)FltObjects->FileObject < stackHigh)) {
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
status = FltGetStreamContext( FltObjects->Instance,
FltObjects->FileObject,
&streamContext );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPreCleanup: find stream context failed.\n") );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
//
// We skip encrypted files at cleanup time because we cannot be
// sure if the file is open raw for backup. It will get scanned
// on the next open anyway.
//
status = AvGetFileEncrypted( FltObjects->Instance,
FltObjects->FileObject,
&encrypted );
if (!NT_SUCCESS( status )) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvPreCleanup: AvGetFileEncrypted FAILED!! \n") );
goto Cleanup;
}
if (encrypted) {
goto Cleanup;
}
AvPreCleanupCsvfs( Data,
FltObjects,
streamContext,
&updateRevisionNumbers,
&VolumeRevision,
&CacheRevision,
&FileRevision );
//
// For applications, the typical calling sequence is, close the file handle
// and commit/rollback the changes. We skip the scan here for
// transacted writer because we do not know if the change will be
// rollbacked or not. If it eventually commits, it will be scanned
// at next create anyway. However, if it rollbacks, the scan here will
// be redundant.
//
if ((streamContext->TxContext == NULL) &&
IS_FILE_MODIFIED( streamContext )) {
status = AvScan( Data,
FltObjects,
AvUserMode,
Data->Iopb->MajorFunction,
FALSE,
streamContext );
if (!NT_SUCCESS( status ) || STATUS_TIMEOUT == status) {
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvPreCleanup: AvScan FAILED!! \n") );
goto Cleanup;
}
//
// If needed, update the stream context with the latest revision
// numbers that correspond to the verion just scanned
//
if (updateRevisionNumbers) {
streamContext->VolumeRevision = VolumeRevision;
streamContext->CacheRevision = CacheRevision;
streamContext->FileRevision = FileRevision;
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[Av]: AvPreCleanup: RevisionNumbers updated to %I64x:%I64x:%I64x\n",
VolumeRevision,
CacheRevision,
FileRevision)
);
}
}
Cleanup:
//
// We only insert the entry when the file is clean or infected.
//
if (!IS_FILE_MODIFIED( streamContext ) ||
IS_FILE_INFECTED( streamContext )) {
if (!NT_SUCCESS ( AvSyncCache( FltObjects->Instance, streamContext ))) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvPreCleanup: AvSyncCache FAILED!! \n") );
}
}
FltReleaseContext( streamContext );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
NTSTATUS
AvKtmNotificationCallback (
_Unreferenced_parameter_ PCFLT_RELATED_OBJECTS FltObjects,
_In_ PFLT_CONTEXT TransactionContext,
_In_ ULONG TransactionNotification
)
/*++
Routine Description:
The registered routine of type PFLT_TRANSACTION_NOTIFICATION_CALLBACK
in FLT_REGISTRATION structure.
Arguments:
FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
opaque handles to this filter, instance, its associated volume and
file object.
TransactionContext - Pointer to the minifilter driver's transaction context
set at PostCreate.
TransactionNotification - Specifies the type of notifications that the
filter manager is sending to the minifilter driver.
Return Value:
STATUS_SUCCESS - Returning this status value indicates that the minifilter
driver is finished with the transaction. This is a success code.
STATUS_PENDING - Returning this status value indicates that the minifilter
driver is not yet finished with the transaction. This is a success code.
--*/
{
PAV_TRANSACTION_CONTEXT transactionContext = (PAV_TRANSACTION_CONTEXT) TransactionContext;
PAGED_CODE();
UNREFERENCED_PARAMETER( FltObjects );
FLT_ASSERTMSG("[AV] AvKtmNotificationCallback: The expected type of notifications registered at FltEnlistInTransaction(...).\n",
FlagOn( TransactionNotification,
(TRANSACTION_NOTIFY_COMMIT_FINALIZE | TRANSACTION_NOTIFY_ROLLBACK) ) );
AV_DBG_PRINT( AVDBG_TRACE_ROUTINES,
("[AV] AvKtmNotificationCallback: Entered\n") );
if (NULL != transactionContext) {
if ( FlagOn( TransactionNotification, TRANSACTION_NOTIFY_COMMIT_FINALIZE ) ) {
return AvProcessTransactionOutcome( TransactionContext, TransactionOutcomeCommitted );
} else {
return AvProcessTransactionOutcome( TransactionContext, TransactionOutcomeAborted );
}
}
return STATUS_SUCCESS;
}
NTSTATUS
AvScanAbortCallbackAsync (
_Unreferenced_parameter_ PFLT_INSTANCE Instance,
_In_ PFLT_CONTEXT Context,
_Unreferenced_parameter_ PFLT_CALLBACK_DATA Data
)
/*++
Routine Description:
This routine is the registered cancel callback function in FLT_REGISTRATION.
It would be invoked by the file system if it decides to abort the scan.
As its name suggests, this function is asynchrounous, so the caller is not
blocked.
Note: This routine may be called before FltCreateSectionForDataScan returns.
This means the SectionHandle and SectionObject may not yet be set in the
SectionContext. We can't take a dependency on these being set before needing
to abort the scan.
Arguments:
Instance - Opaque filter pointer for the caller. This parameter is required and cannot be NULL.
Context - The section context.
Data - Pointer to the filter callbackData that is passed to us.
Return Value:
Returns the final status of this operation.
--*/
{
PAV_SECTION_CONTEXT sectionCtx = (PAV_SECTION_CONTEXT) Context;
PAV_SCAN_CONTEXT scanCtx = NULL;
PAGED_CODE();
UNREFERENCED_PARAMETER( Instance );
UNREFERENCED_PARAMETER( Data );
if (NULL == sectionCtx) {
AV_DBG_PRINT( AVDBG_TRACE_ERROR,
("[AV] AvScanAbortCallbackAsync: INVALID ARGUMENT.\n") );
return STATUS_INVALID_PARAMETER_2;
}
AV_DBG_PRINT( AVDBG_TRACE_DEBUG,
("[AV] AvScanAbortCallbackAsync: closesection handle=%p, object=%p, cancelable=%d\n",
sectionCtx->SectionHandle,
sectionCtx->SectionObject,
sectionCtx->CancelableOnConflictingIo) );
//
// Send abort signal only when the scanning
// happens in cancelable context (such as pre-cleanup).
//
if (sectionCtx->CancelableOnConflictingIo) {
//
// The only reason of scan context being NULL is that
// the section context is about to close anyway.
// Please see AvCloseSectionForDataScan(...)
//
scanCtx = InterlockedExchangePointer( §ionCtx->ScanContext, NULL );
if (scanCtx == NULL) {
return STATUS_SUCCESS;
}
sectionCtx->Aborted = TRUE;
AvSendAbortToUser( scanCtx->ScanThreadId, scanCtx->ScanId );
}
return STATUS_SUCCESS;
}
PFN_IoOpenDriverRegistryKey
AvGetIoOpenDriverRegistryKey (
VOID
)
{
static PFN_IoOpenDriverRegistryKey pIoOpenDriverRegistryKey = NULL;
UNICODE_STRING FunctionName = {0};
if (pIoOpenDriverRegistryKey == NULL) {
RtlInitUnicodeString(&FunctionName, L"IoOpenDriverRegistryKey");
pIoOpenDriverRegistryKey = (PFN_IoOpenDriverRegistryKey)MmGetSystemRoutineAddress(&FunctionName);
}
return pIoOpenDriverRegistryKey;
}
NTSTATUS
AvOpenServiceParametersKey (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING ServiceRegistryPath,
_Out_ PHANDLE ServiceParametersKey
)
/*++
Routine Description:
This routine opens the service parameters key, using the isolation-compliant
APIs when possible.
Arguments:
DriverObject - Pointer to driver object created by the system to
represent this driver.
RegistryPath - The path key passed to the driver during DriverEntry.
ServiceParametersKey - Returns a handle to the service parameters subkey.
Return Value:
STATUS_SUCCESS if the function completes successfully. Otherwise a valid
NTSTATUS code is returned.
--*/
{
NTSTATUS Status;
PFN_IoOpenDriverRegistryKey pIoOpenDriverRegistryKey;
UNICODE_STRING Subkey;
HANDLE ParametersKey = NULL;
HANDLE ServiceRegKey = NULL;
OBJECT_ATTRIBUTES Attributes;
//
// Open the parameters key to read values from the INF, using the API to
// open the key if possible
//
pIoOpenDriverRegistryKey = AvGetIoOpenDriverRegistryKey();
if (pIoOpenDriverRegistryKey != NULL) {
//
// Open the parameters key using the API
//
Status = pIoOpenDriverRegistryKey( DriverObject,
DriverRegKeyParameters,
KEY_READ,
0,
&ParametersKey );
if (!NT_SUCCESS( Status )) {
goto OpenServiceParametersKeyCleanup;
}
} else {
//
// Open specified service root key
//
InitializeObjectAttributes( &Attributes,
ServiceRegistryPath,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL );
Status = ZwOpenKey( &ServiceRegKey,
KEY_READ,
&Attributes );
if (!NT_SUCCESS( Status )) {
goto OpenServiceParametersKeyCleanup;
}
//
// Open the parameters key relative to service key path
//
RtlInitUnicodeString( &Subkey, L"Parameters" );
InitializeObjectAttributes( &Attributes,
&Subkey,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
ServiceRegKey,
NULL );
Status = ZwOpenKey( &ParametersKey,
KEY_READ,
&Attributes );
if (!NT_SUCCESS( Status )) {
goto OpenServiceParametersKeyCleanup;
}
}
//
// Return value to caller
//
*ServiceParametersKey = ParametersKey;
OpenServiceParametersKeyCleanup:
if (ServiceRegKey != NULL) {
ZwClose( ServiceRegKey );
}
return Status;
}
NTSTATUS
AvSetConfiguration (
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++
Routine Descrition:
This routine sets the filter configuration based on registry values.
Arguments:
DriverObject - Pointer to driver object created by the system to
represent this driver.
RegistryPath - The path key passed to the driver during DriverEntry.
Return Value:
Returns the status of this operation.
--*/
{
NTSTATUS status;
HANDLE settingsKey = NULL;
UNICODE_STRING valueName;
UCHAR buffer[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(ULONG)];
PKEY_VALUE_PARTIAL_INFORMATION value = (PKEY_VALUE_PARTIAL_INFORMATION)buffer;
ULONG valueLength = sizeof(buffer);
ULONG resultLength;
//
// Open service parameters key to query values from
//
status = AvOpenServiceParametersKey( DriverObject,
RegistryPath,
&settingsKey );
if (!NT_SUCCESS( status )) {
goto Cleanup;
}
#if DBG
//
// Query the debug level
//
RtlInitUnicodeString( &valueName, L"DebugLevel" );
status = ZwQueryValueKey( settingsKey,
&valueName,
KeyValuePartialInformation,
value,
valueLength,
&resultLength );
if (NT_SUCCESS( status )) {
Globals.DebugLevel = *(PULONG)value->Data;
}
#endif
//
// Query the local scan timeout
//
RtlInitUnicodeString( &valueName, L"LocalScanTimeout" );
status = ZwQueryValueKey( settingsKey,
&valueName,
KeyValuePartialInformation,
value,
valueLength,
&resultLength );
if (NT_SUCCESS( status )) {
Globals.LocalScanTimeout = (LONGLONG)(*(PULONG)value->Data);
}
//
// Query the network scan timeout
//
RtlInitUnicodeString( &valueName, L"NetworkScanTimeout" );
status = ZwQueryValueKey( settingsKey,
&valueName,
KeyValuePartialInformation,
value,
valueLength,
&resultLength );
if (NT_SUCCESS( status )) {
Globals.NetworkScanTimeout = (LONGLONG)(*(PULONG)value->Data);
}
status = STATUS_SUCCESS;
Cleanup:
if (settingsKey != NULL) {
ZwClose( settingsKey );
}
return status;
}
|