VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Common/BootEncryption.cpp
blob: 3b799d042d6c1a8fb5d3f96837c683b792cfcfce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
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
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file)
 and all other portions of this file are Copyright (c) 2013-2016 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#include "Tcdefs.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include <devguid.h>
#include <io.h>
#include <shlobj.h>
#include <atlbase.h>
#include "BootEncryption.h"
#include "Boot/Windows/BootCommon.h"
#include "Common/Resource.h"
#include "Crc.h"
#include "Crypto.h"
#include "Dlgcode.h"
#include "Endian.h"
#include "Language.h"
#include "Random.h"
#include "Registry.h"
#include "Volumes.h"
#include "Xml.h"
#include "XZip.h"
#include "XUnzip.h"

#ifdef VOLFORMAT
#include "Format/FormatCom.h"
#elif defined (TCMOUNT)
#include "Mount/MainCom.h"
#endif

#include <Strsafe.h>

namespace VeraCrypt
{
#if !defined (SETUP)

	class Elevator
	{
	public:
		
		static void AddReference ()
		{
			++ReferenceCount;
		}


		static void CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize)
		{
			Elevate();

			CComBSTR inputBstr;
			if (input && inputBstr.AppendBytes ((const char *) input, inputSize) != S_OK)
				throw ParameterIncorrect (SRC_POS);

			CComBSTR outputBstr;
			if (output && outputBstr.AppendBytes ((const char *) output, outputSize) != S_OK)
				throw ParameterIncorrect (SRC_POS);

			DWORD result = ElevatedComInstance->CallDriver (ioctl, inputBstr, &outputBstr);

			if (output)
				memcpy (output, *(void **) &outputBstr, outputSize);

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void CopyFile (const wstring &sourceFile, const wstring &destinationFile)
		{
			Elevate();
			DWORD result;
			CComBSTR sourceFileBstr, destinationFileBstr;
			BSTR bstr = W2BSTR(sourceFile.c_str());
			if (bstr)
			{
				sourceFileBstr.Attach (bstr);

				bstr = W2BSTR(destinationFile.c_str());
				if (bstr)
				{
					destinationFileBstr.Attach (bstr);
					result = ElevatedComInstance->CopyFile (sourceFileBstr, destinationFileBstr);
				}
				else
				{
					result = ERROR_OUTOFMEMORY;
				}
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void DeleteFile (const wstring &file)
		{
			Elevate();
			CComBSTR fileBstr;
			DWORD result;
			BSTR bstr = W2BSTR(file.c_str());
			if (bstr)
			{
				fileBstr.Attach (bstr);
				result = ElevatedComInstance->DeleteFile (fileBstr);
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void ReadWriteFile (BOOL write, BOOL device, const wstring &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone)
		{
			Elevate();

			DWORD result;
			CComBSTR bufferBstr, fileBstr;
			if (bufferBstr.AppendBytes ((const char *) buffer, size) != S_OK)
				throw ParameterIncorrect (SRC_POS);
			BSTR bstr = W2BSTR(filePath.c_str());
			if (bstr)
			{
				fileBstr.Attach (bstr);
				result = ElevatedComInstance->ReadWriteFile (write, device, fileBstr, &bufferBstr, offset, size, sizeDone);
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}

			if (!write)
				memcpy (buffer, (BYTE *) bufferBstr.m_str, size);
		}

		static void GetFileSize (const wstring &filePath, unsigned __int64* pSize)
		{
			Elevate();

			DWORD result;
			CComBSTR fileBstr;
			BSTR bstr = W2BSTR(filePath.c_str());
			if (bstr)
			{
				fileBstr.Attach (bstr);
				result = ElevatedComInstance->GetFileSize (fileBstr, pSize);
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static BOOL DeviceIoControl (BOOL readOnly, BOOL device, const wstring &filePath, DWORD dwIoControlCode, LPVOID input, DWORD inputSize, 
												LPVOID output, DWORD outputSize)
		{
			Elevate();

			DWORD result;

			BSTR bstr = W2BSTR(filePath.c_str());
			if (bstr)
			{
				CComBSTR inputBstr;
				if (input && inputBstr.AppendBytes ((const char *) input, inputSize) != S_OK)
				{
					SetLastError (ERROR_INVALID_PARAMETER);
					return FALSE;
				}

				CComBSTR outputBstr;
				if (output && outputBstr.AppendBytes ((const char *) output, outputSize) != S_OK)
				{
					SetLastError (ERROR_INVALID_PARAMETER);
					return FALSE;
				}

				CComBSTR fileBstr;
				fileBstr.Attach (bstr);
				result = ElevatedComInstance->DeviceIoControl (readOnly, device, fileBstr, dwIoControlCode, inputBstr, &outputBstr);

				if (output)
					memcpy (output, *(void **) &outputBstr, outputSize);
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				return FALSE;
			}
			else
				return TRUE;
		}

		static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly)
		{
			Elevate();

			return ElevatedComInstance->IsPagingFileActive (checkNonWindowsPartitionsOnly);
		}

		static void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value)
		{
			Elevate();
			DWORD result;
			CComBSTR keyPathBstr, valueNameBstr;
			BSTR bstr = W2BSTR(keyPath);
			if (bstr)
			{
				keyPathBstr.Attach (bstr);

				bstr = W2BSTR(valueName);
				if (bstr)
				{
					valueNameBstr.Attach (bstr);

					result = ElevatedComInstance->WriteLocalMachineRegistryDwordValue (keyPathBstr, valueNameBstr, value);
				}
				else
				{
					result = ERROR_OUTOFMEMORY;
				}
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void RegisterFilterDriver (bool registerDriver, BootEncryption::FilterType filterType)
		{
			Elevate();

			DWORD result = ElevatedComInstance->RegisterFilterDriver (registerDriver ? TRUE : FALSE, filterType);
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void RegisterSystemFavoritesService (BOOL registerService)
		{
			Elevate();

			DWORD result = ElevatedComInstance->RegisterSystemFavoritesService (registerService);
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void InstallEfiBootLoader (bool preserveUserConfig, bool hiddenOSCreation, int pim, int hashAlg)
		{
			Elevate();

			DWORD result = ElevatedComInstance->InstallEfiBootLoader (preserveUserConfig ? TRUE : FALSE, hiddenOSCreation ? TRUE : FALSE, pim, hashAlg);
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void BackupEfiSystemLoader ()
		{
			Elevate();

			DWORD result = ElevatedComInstance->BackupEfiSystemLoader ();
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void RestoreEfiSystemLoader ()
		{
			Elevate();

			DWORD result = ElevatedComInstance->RestoreEfiSystemLoader ();
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void GetEfiBootDeviceNumber (PSTORAGE_DEVICE_NUMBER pSdn)
		{
			Elevate();

			CComBSTR outputBstr;
			if (pSdn && outputBstr.AppendBytes ((const char *) pSdn, sizeof (STORAGE_DEVICE_NUMBER)) != S_OK)
			{
				SetLastError (ERROR_INVALID_PARAMETER);
				throw SystemException(SRC_POS);
			}

			DWORD result = ElevatedComInstance->GetEfiBootDeviceNumber (&outputBstr);

			if (pSdn)
				memcpy (pSdn, *(void **) &outputBstr, sizeof (STORAGE_DEVICE_NUMBER));

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void ReadEfiConfig (byte* confContent, DWORD maxSize, DWORD* pcbRead)
		{
			Elevate();

			CComBSTR outputBstr;
			if (confContent && outputBstr.AppendBytes ((const char *) confContent, maxSize) != S_OK)
			{
				SetLastError (ERROR_INVALID_PARAMETER);
				throw SystemException(SRC_POS);
			}

			DWORD result = ElevatedComInstance->ReadEfiConfig (&outputBstr, pcbRead);

			if (confContent)
				memcpy (confContent, *(void **) &outputBstr, maxSize);

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void WriteEfiBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg)
		{
			Elevate();

			DWORD result;
			CComBSTR customUserMessageBstr;
			BSTR bstr = A2BSTR(customUserMessage.c_str());
			if (bstr)
			{
				customUserMessageBstr.Attach (bstr);
				result = ElevatedComInstance->WriteEfiBootSectorUserConfig ((DWORD) userConfig, customUserMessageBstr, pim, hashAlg);
			}
			else
			{
				result = ERROR_OUTOFMEMORY;
			}

			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

		static void Release ()
		{
			if (--ReferenceCount == 0 && ElevatedComInstance)
			{
				ElevatedComInstance->Release();
				ElevatedComInstance = nullptr;
				CoUninitialize ();
			}
		}

		static void SetDriverServiceStartType (DWORD startType)
		{
			Elevate();

			DWORD result = ElevatedComInstance->SetDriverServiceStartType (startType);
			if (result != ERROR_SUCCESS)
			{
				SetLastError (result);
				throw SystemException(SRC_POS);
			}
		}

	protected:
		static void Elevate ()
		{
			if (IsAdmin())
			{
				SetLastError (ERROR_ACCESS_DENIED);
				throw SystemException(SRC_POS);
			}

			if (!ElevatedComInstance || ElevatedComInstanceThreadId != GetCurrentThreadId())
			{
				CoInitialize (NULL);
				ElevatedComInstance = GetElevatedInstance (GetActiveWindow() ? GetActiveWindow() : MainDlg);
				ElevatedComInstanceThreadId = GetCurrentThreadId();
			}
		}

#if defined (TCMOUNT)
		static ITrueCryptMainCom *ElevatedComInstance;
#elif defined (VOLFORMAT)
		static ITrueCryptFormatCom *ElevatedComInstance;
#endif
		static DWORD ElevatedComInstanceThreadId;
		static int ReferenceCount;
	};

#if defined (TCMOUNT)
	ITrueCryptMainCom *Elevator::ElevatedComInstance;
#elif defined (VOLFORMAT)
	ITrueCryptFormatCom *Elevator::ElevatedComInstance;
#endif
	DWORD Elevator::ElevatedComInstanceThreadId;
	int Elevator::ReferenceCount = 0;

#else // SETUP

	class Elevator
	{
	public:
		static void AddReference () { }
		static void CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize) { throw ParameterIncorrect (SRC_POS); }
		static void ReadWriteFile (BOOL write, BOOL device, const wstring &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone) { throw ParameterIncorrect (SRC_POS); }
		static void RegisterFilterDriver (bool registerDriver, BootEncryption::FilterType filterType) { throw ParameterIncorrect (SRC_POS); }
		static void Release () { }
		static void SetDriverServiceStartType (DWORD startType) { throw ParameterIncorrect (SRC_POS); }
		static void GetFileSize (const wstring &filePath, unsigned __int64 *pSize) { throw ParameterIncorrect (SRC_POS); }
		static BOOL DeviceIoControl (BOOL readOnly, BOOL device, const wstring &filePath, DWORD dwIoControlCode, LPVOID input, DWORD inputSize, LPVOID output, DWORD outputSize) { throw ParameterIncorrect (SRC_POS); }
		static void InstallEfiBootLoader (bool preserveUserConfig, bool hiddenOSCreation, int pim, int hashAlg) { throw ParameterIncorrect (SRC_POS); }
		static void BackupEfiSystemLoader () { throw ParameterIncorrect (SRC_POS); }
		static void RestoreEfiSystemLoader () { throw ParameterIncorrect (SRC_POS); }
		static void GetEfiBootDeviceNumber (PSTORAGE_DEVICE_NUMBER pSdn) { throw ParameterIncorrect (SRC_POS); }
		static void ReadEfiConfig (byte* confContent, DWORD maxSize, DWORD* pcbRead) { throw ParameterIncorrect (SRC_POS); }
		static void WriteEfiBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg) { throw ParameterIncorrect (SRC_POS); }
	};

#endif // SETUP

	File::File (wstring path, bool readOnly, bool create) : Elevated (false), FileOpen (false), ReadOnly (readOnly), LastError(0)
	{
		Handle = CreateFile (path.c_str(),
			readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, create ? CREATE_ALWAYS : OPEN_EXISTING,
			FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_WRITE_THROUGH, NULL);

		if (Handle != INVALID_HANDLE_VALUE)
		{
			FileOpen = true;
		}
		else
		{
			LastError = GetLastError();
			if (LastError == ERROR_ACCESS_DENIED && IsUacSupported())
			{
				Elevated = true;
				FileOpen = true;
			}
		}

		FilePointerPosition = 0;
		IsDevice = false;
		Path = path;
	}

	void File::Close ()
	{
		if (Handle != INVALID_HANDLE_VALUE)
		{
			CloseHandle (Handle);
			Handle = INVALID_HANDLE_VALUE;
		}

		FileOpen = false;
	}

	DWORD File::Read (byte *buffer, DWORD size)
	{
		DWORD bytesRead;

		if (!FileOpen)
		{
			SetLastError (LastError);
			throw SystemException (SRC_POS);
		}

		if (Elevated)
		{
			DWORD bytesRead;

			Elevator::ReadWriteFile (false, IsDevice, Path, buffer, FilePointerPosition, size, &bytesRead);
			FilePointerPosition += bytesRead;
			return bytesRead;
		}

		throw_sys_if (!ReadFile (Handle, buffer, size, &bytesRead, NULL));
		return bytesRead;
	}

	void File::SeekAt (int64 position)
	{
		if (!FileOpen)
		{
			SetLastError (LastError);
			throw SystemException (SRC_POS);
		}

		FilePointerPosition = position;

		if (!Elevated)
		{
			LARGE_INTEGER pos;
			pos.QuadPart = position;
			throw_sys_if (!SetFilePointerEx (Handle, pos, NULL, FILE_BEGIN));
		}
	}

	void File::GetFileSize (unsigned __int64& size)
	{
		if (!FileOpen)
		{
			SetLastError (LastError);
			throw SystemException (SRC_POS);
		}

		if (Elevated)
		{
			Elevator::GetFileSize (Path, &size);
		}
		else
		{
			LARGE_INTEGER lSize;
			lSize.QuadPart = 0;
			throw_sys_if (!GetFileSizeEx (Handle, &lSize));
			size = (unsigned __int64) lSize.QuadPart;
		}
	}

	void File::GetFileSize (DWORD& dwSize)
	{
		unsigned __int64 size64;
		GetFileSize (size64);
		dwSize = (DWORD) size64;
	}

	void File::Write (byte *buffer, DWORD size)
	{
		DWORD bytesWritten;

		if (!FileOpen)
		{
			SetLastError (LastError);
			throw SystemException (SRC_POS);
		}

		try
		{
			if (Elevated)
			{
				Elevator::ReadWriteFile (true, IsDevice, Path, buffer, FilePointerPosition, size, &bytesWritten);
				FilePointerPosition += bytesWritten;
				throw_sys_if (bytesWritten != size);
			}
			else
			{
				throw_sys_if (!WriteFile (Handle, buffer, size, &bytesWritten, NULL) || bytesWritten != size);
			}
		}
		catch (SystemException &e)
		{
			if (!IsDevice || e.ErrorCode != ERROR_WRITE_PROTECT)
				throw;

			BootEncryption bootEnc (NULL);

			while (size >= TC_SECTOR_SIZE_BIOS)
			{
				bootEnc.WriteBootDriveSector (FilePointerPosition, buffer);

				FilePointerPosition += TC_SECTOR_SIZE_BIOS;
				buffer += TC_SECTOR_SIZE_BIOS;
				size -= TC_SECTOR_SIZE_BIOS;
			}
		}
	}

	bool File::IoCtl(DWORD code, void* inBuf, DWORD inBufSize, void* outBuf, DWORD outBufSize)
	{
		if (!FileOpen)
		{
			SetLastError (LastError);
			throw SystemException (SRC_POS);
		}

		if (Elevated)
		{
			return TRUE == Elevator::DeviceIoControl (ReadOnly, IsDevice, Path, code, inBuf, inBufSize, outBuf, outBufSize);
		}
		else
		{
			DWORD bytesReturned = 0;
			return TRUE == DeviceIoControl(Handle, code, inBuf, inBufSize, outBuf, outBufSize, &bytesReturned, NULL);
		}
	}

	void Show (HWND parent, const wstring &str)
	{
		MessageBox (parent, str.c_str(), NULL, 0);
	}


	Device::Device (wstring path, bool readOnly)
	{
		 FileOpen = false;
		 Elevated = false;

		Handle = CreateFile ((wstring (L"\\\\.\\") + path).c_str(),
			readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
			FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_WRITE_THROUGH, NULL);

		if (Handle != INVALID_HANDLE_VALUE)
		{
			FileOpen = true;
		}
		else
		{
			LastError = GetLastError ();
			if (LastError == ERROR_ACCESS_DENIED && IsUacSupported())
			{
				Elevated = true;
				FileOpen = true;
			}
		}

		FilePointerPosition = 0;
		IsDevice = true;
		Path = path;
		ReadOnly = readOnly;
	}

	static EfiBoot EfiBootInst;

	BootEncryption::BootEncryption (HWND parent)
		: DriveConfigValid (false),
		ParentWindow (parent),
		RealSystemDriveSizeValid (false),
		RescueIsoImage (nullptr),
		RescueZipData (nullptr),
		RescueZipSize (0),
		RescueVolumeHeaderValid (false),
		SelectedEncryptionAlgorithmId (0),
		SelectedPrfAlgorithmId (0),
		VolumeHeaderValid (false)
	{
      HiddenOSCandidatePartition.IsGPT = FALSE;
      HiddenOSCandidatePartition.Number = (size_t) -1;
      DriveConfig.DriveNumber = -1;
      DriveConfig.ExtraBootPartitionPresent = false;
      DriveConfig.SystemLoaderPresent = false;
      DriveConfig.InitialUnallocatedSpace = 0;
      DriveConfig.TotalUnallocatedSpace = 0;
		Elevator::AddReference();
	}


	BootEncryption::~BootEncryption ()
	{
		if (RescueIsoImage)
		{
			burn (RescueIsoImage, RescueIsoImageSize);
			delete[] RescueIsoImage;
		}
		if (RescueZipData)
		{
			burn (RescueZipData, RescueZipSize);
			delete [] RescueZipData;
		}

		Elevator::Release();
	}


	void BootEncryption::CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize)
	{
		try
		{
			DWORD bytesReturned;
			throw_sys_if (!DeviceIoControl (hDriver, ioctl, input, inputSize, output, outputSize, &bytesReturned, NULL));
		}
		catch (SystemException &)
		{
			if (GetLastError() == ERROR_ACCESS_DENIED && IsUacSupported())
				Elevator::CallDriver (ioctl, input, inputSize, output, outputSize);
			else
				throw;
		}
	}


	// Finds the first partition physically located behind the active one and returns its properties
	Partition BootEncryption::GetPartitionForHiddenOS ()
	{
		Partition candidatePartition;

		memset (&candidatePartition, 0, sizeof(candidatePartition));

		// The user may have modified/added/deleted partitions since the time the partition table was last scanned
		InvalidateCachedSysDriveProperties();

		SystemDriveConfiguration config = GetSystemDriveConfiguration ();
		bool activePartitionFound = false;
		bool candidateForHiddenOSFound = false;

 		if (!config.SystemPartition.IsGPT)
		{
//				throw ParameterIncorrect (SRC_POS);	// It is assumed that CheckRequirements() had been called

			// Find the first active partition on the system drive
			foreach (const Partition &partition, config.Partitions)
			{
				if (partition.Info.BootIndicator)
				{
					if (partition.Info.PartitionNumber != config.SystemPartition.Number)
					{
						// If there is an extra boot partition, the system partition must be located right behind it
						if (IsOSAtLeast (WIN_7) && config.ExtraBootPartitionPresent)
						{
							int64 minOffsetFound = config.DrivePartition.Info.PartitionLength.QuadPart;
							Partition bootPartition = partition;
							Partition partitionBehindBoot;

							foreach (const Partition &partition, config.Partitions)
							{
								if (partition.Info.StartingOffset.QuadPart > bootPartition.Info.StartingOffset.QuadPart
									&& partition.Info.StartingOffset.QuadPart < minOffsetFound)
								{
									minOffsetFound = partition.Info.StartingOffset.QuadPart;
									partitionBehindBoot = partition;
								}
							}

							if (minOffsetFound != config.DrivePartition.Info.PartitionLength.QuadPart
								&& partitionBehindBoot.Number == config.SystemPartition.Number)
							{
								activePartitionFound = true;
								break;
							}
						}

						throw ErrorException (wstring (GetString ("SYSTEM_PARTITION_NOT_ACTIVE"))
							+ GetRemarksOnHiddenOS(), SRC_POS);
					}

					activePartitionFound = true;
					break;
				}
			}
		} else {
			// For GPT
			activePartitionFound = true;
		}
		/* WARNING: Note that the partition number at the end of a device path (\Device\HarddiskY\PartitionX) must
		NOT be used to find the first partition physically located behind the active one. The reason is that the
		user may have deleted and created partitions during this session and e.g. the second partition could have
		a higer number than the third one. */


		// Find the first partition physically located behind the active partition
		if (activePartitionFound)
		{
			int64 minOffsetFound = config.DrivePartition.Info.PartitionLength.QuadPart;

			foreach (const Partition &partition, config.Partitions)
			{
				if (partition.Info.StartingOffset.QuadPart > config.SystemPartition.Info.StartingOffset.QuadPart
					&& partition.Info.StartingOffset.QuadPart < minOffsetFound)
				{
					minOffsetFound = partition.Info.StartingOffset.QuadPart;

					candidatePartition = partition;

					candidateForHiddenOSFound = true;
				}
			}

			if (!candidateForHiddenOSFound)
			{
				throw ErrorException (wstring (GetString ("NO_PARTITION_FOLLOWS_BOOT_PARTITION"))
					+ GetRemarksOnHiddenOS(), SRC_POS);
			}

			if (config.SystemPartition.Info.PartitionLength.QuadPart > TC_MAX_FAT_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
			{
				if ((double) candidatePartition.Info.PartitionLength.QuadPart / config.SystemPartition.Info.PartitionLength.QuadPart < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS)
				{
					throw ErrorException (wstring (GetString ("PARTITION_TOO_SMALL_FOR_HIDDEN_OS_NTFS"))
						+ GetRemarksOnHiddenOS(), SRC_POS);
				}
			}
			else if ((double) candidatePartition.Info.PartitionLength.QuadPart / config.SystemPartition.Info.PartitionLength.QuadPart < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_FAT)
			{
				throw ErrorException (wstring (GetString ("PARTITION_TOO_SMALL_FOR_HIDDEN_OS"))
					+ GetRemarksOnHiddenOS(), SRC_POS);
			}
		}
		else
		{
			// No active partition on the system drive
			throw ErrorException ("SYSTEM_PARTITION_NOT_ACTIVE", SRC_POS);
		}

		HiddenOSCandidatePartition = candidatePartition;
		return candidatePartition;
	}


	DWORD BootEncryption::GetDriverServiceStartType ()
	{
		DWORD startType;
		throw_sys_if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", &startType));
		return startType;
	}


	wstring BootEncryption::GetRemarksOnHiddenOS ()
	{
		return (wstring (L"\n\n")
				+ GetString ("TWO_SYSTEMS_IN_ONE_PARTITION_REMARK")
				+ L"\n\n"
				+ GetString ("FOR_MORE_INFO_ON_PARTITIONS"));
	}


	void BootEncryption::SetDriverServiceStartType (DWORD startType)
	{
		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::SetDriverServiceStartType (startType);
			return;
		}

		BOOL startOnBoot = (startType == SERVICE_BOOT_START);

		SC_HANDLE serviceManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
		throw_sys_if (!serviceManager);

		finally_do_arg (SC_HANDLE, serviceManager, { CloseServiceHandle (finally_arg); });

		SC_HANDLE service = OpenService (serviceManager, L"veracrypt", SERVICE_CHANGE_CONFIG);
		throw_sys_if (!service);

		finally_do_arg (SC_HANDLE, service, { CloseServiceHandle (finally_arg); });

		// Windows versions preceding Vista can be installed on FAT filesystem which does not
		// support long filenames during boot. Convert the driver path to short form if required.
		wstring driverPath;
		if (startOnBoot && !IsOSAtLeast (WIN_VISTA))
		{
			wchar_t pathBuf[MAX_PATH];
			wchar_t filesystem[128];

			wstring path (GetWindowsDirectory());
			path += L"\\drivers\\veracrypt.sys";

			if (GetVolumePathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf))
				&& GetVolumeInformation (pathBuf, NULL, 0, NULL, NULL, NULL, filesystem, ARRAYSIZE(filesystem))
				&& wmemcmp (filesystem, L"FAT", 3) == 0)
			{
				throw_sys_if (GetShortPathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf)) == 0);

				// Convert absolute path to relative to the Windows directory
				driverPath = pathBuf;
				driverPath = driverPath.substr (driverPath.rfind (L"\\", driverPath.rfind (L"\\", driverPath.rfind (L"\\") - 1) - 1) + 1);
			}
		}

		throw_sys_if (!ChangeServiceConfig (service, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
			startOnBoot ? SERVICE_ERROR_SEVERE : SERVICE_ERROR_NORMAL,
			driverPath.empty() ? NULL : driverPath.c_str(),
			startOnBoot ? L"Filter" : NULL,
			NULL, NULL, NULL, NULL, NULL));

		// ChangeServiceConfig() rejects SERVICE_BOOT_START with ERROR_INVALID_PARAMETER
		throw_sys_if (!WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", startType));
	}


	void BootEncryption::ProbeRealSystemDriveSize ()
	{
		if (RealSystemDriveSizeValid)
			return;

		GetSystemDriveConfiguration();

		ProbeRealDriveSizeRequest request;
		StringCchCopyW (request.DeviceName, ARRAYSIZE (request.DeviceName), DriveConfig.DrivePartition.DevicePath.c_str());

		CallDriver (TC_IOCTL_PROBE_REAL_DRIVE_SIZE, &request, sizeof (request), &request, sizeof (request));
		DriveConfig.DrivePartition.Info.PartitionLength = request.RealDriveSize;

		RealSystemDriveSizeValid = true;

		if (request.TimeOut)
			throw TimeOut (SRC_POS);
	}


	void BootEncryption::InvalidateCachedSysDriveProperties ()
	{
		DriveConfigValid = false;
		RealSystemDriveSizeValid = false;
	}


	PartitionList BootEncryption::GetDrivePartitions (int driveNumber)
	{
		PartitionList partList;

		for (int partNumber = 0; partNumber < 64; ++partNumber)
		{
			wstringstream partPath;
			partPath << L"\\Device\\Harddisk" << driveNumber << L"\\Partition" << partNumber;

			DISK_PARTITION_INFO_STRUCT diskPartInfo = {0};
			StringCchCopyW (diskPartInfo.deviceName, ARRAYSIZE (diskPartInfo.deviceName), partPath.str().c_str());

			try
			{
				CallDriver (TC_IOCTL_GET_DRIVE_PARTITION_INFO, &diskPartInfo, sizeof (diskPartInfo), &diskPartInfo, sizeof (diskPartInfo));
			}
			catch (...)
			{
				continue;
			}

			if (	(diskPartInfo.IsGPT == TRUE || diskPartInfo.IsGPT == FALSE)
				&&	(diskPartInfo.IsDynamic == TRUE || diskPartInfo.IsDynamic == FALSE)
				&&	(diskPartInfo.partInfo.BootIndicator == TRUE || diskPartInfo.partInfo.BootIndicator == FALSE)
				&&	(diskPartInfo.partInfo.RecognizedPartition == TRUE || diskPartInfo.partInfo.RecognizedPartition == FALSE)
				&&	(diskPartInfo.partInfo.RewritePartition == TRUE || diskPartInfo.partInfo.RewritePartition == FALSE)
				&&	(diskPartInfo.partInfo.StartingOffset.QuadPart >= 0)
				&&	(diskPartInfo.partInfo.PartitionLength.QuadPart >= 0)
				)
			{
				Partition part;
				part.DevicePath = partPath.str();
				part.Number = partNumber;
				part.Info = diskPartInfo.partInfo;
				part.IsGPT = diskPartInfo.IsGPT;

				// Mount point
				int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) partPath.str().c_str());

				if (driveNumber >= 0)
				{
					part.MountPoint += (wchar_t) (driveNumber + L'A');
					part.MountPoint += L":";
				}

				// Volume ID
				wchar_t volumePath[TC_MAX_PATH];
				if (ResolveSymbolicLink ((wchar_t *) partPath.str().c_str(), volumePath, sizeof(volumePath)))
				{
					wchar_t volumeName[TC_MAX_PATH];
					HANDLE fh = FindFirstVolumeW (volumeName, array_capacity (volumeName));
					if (fh != INVALID_HANDLE_VALUE)
					{
						do
						{
							wstring volumeNameStr = volumeName;
							wchar_t devicePath[TC_MAX_PATH];

							if (QueryDosDeviceW (volumeNameStr.substr (4, volumeNameStr.size() - 1 - 4).c_str(), devicePath, array_capacity (devicePath)) != 0
								&& wcscmp (volumePath, devicePath) == 0)
							{
								part.VolumeNameId = volumeName;
								break;
							}

						} while (FindNextVolumeW (fh, volumeName, array_capacity (volumeName)));

						FindVolumeClose (fh);
					}
				}

				partList.push_back (part);
			}
		}

		return partList;
	}


	DISK_GEOMETRY BootEncryption::GetDriveGeometry (int driveNumber)
	{
		wstringstream devName;
		devName << L"\\Device\\Harddisk" << driveNumber << L"\\Partition0";

		DISK_GEOMETRY geometry;
		throw_sys_if (!::GetDriveGeometry (devName.str().c_str(), &geometry));
		return geometry;
	}


	wstring BootEncryption::GetWindowsDirectory ()
	{
		wchar_t buf[MAX_PATH];
		throw_sys_if (GetSystemDirectory (buf, ARRAYSIZE (buf)) == 0);

		return wstring (buf);
	}



	uint16 BootEncryption::GetInstalledBootLoaderVersion ()
	{
		uint16 version;
		CallDriver (TC_IOCTL_GET_BOOT_LOADER_VERSION, NULL, 0, &version, sizeof (version));
		return version;
	}

	void BootEncryption::GetInstalledBootLoaderFingerprint (byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE])
	{
		BootLoaderFingerprintRequest request;
		CallDriver (VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT, NULL, 0, &request, sizeof (request));
		memcpy (fingerprint, request.Fingerprint, sizeof (request.Fingerprint));
	}

	// Note that this does not require admin rights (it just requires the driver to be running)
	bool BootEncryption::IsBootLoaderOnDrive (wchar_t *devicePath)
	{
		try
		{
			OPEN_TEST_STRUCT openTestStruct;
			memset (&openTestStruct, 0, sizeof (openTestStruct));
			DWORD dwResult;

			StringCchCopyW (&openTestStruct.wszFileName[0], ARRAYSIZE(openTestStruct.wszFileName),devicePath);

			openTestStruct.bDetectTCBootLoader = TRUE;

			return (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST,
				   &openTestStruct, sizeof (OPEN_TEST_STRUCT),
				   &openTestStruct, sizeof (OPEN_TEST_STRUCT),
				   &dwResult, NULL) && openTestStruct.TCBootLoaderDetected);
		}
		catch (...)
		{
			return false;
		}
	}


	BootEncryptionStatus BootEncryption::GetStatus ()
	{
		/* IMPORTANT: Do NOT add any potentially time-consuming operations to this function. */

		BootEncryptionStatus status;
		CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS, NULL, 0, &status, sizeof (status));
		return status;
	}


	void BootEncryption::GetVolumeProperties (VOLUME_PROPERTIES_STRUCT *properties)
	{
		if (properties == NULL)
			throw ParameterIncorrect (SRC_POS);

		CallDriver (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES, NULL, 0, properties, sizeof (*properties));
	}


	bool BootEncryption::IsHiddenSystemRunning ()
	{
		int hiddenSystemStatus;

		CallDriver (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING, nullptr, 0, &hiddenSystemStatus, sizeof (hiddenSystemStatus));
		return hiddenSystemStatus != 0;
	}


	bool BootEncryption::SystemDriveContainsPartitionType (byte type)
	{
		Device device (GetSystemDriveConfiguration().DevicePath, true);
		device.CheckOpened (SRC_POS);

		byte mbrBuf[TC_SECTOR_SIZE_BIOS];
		device.SeekAt (0);
		device.Read (mbrBuf, sizeof (mbrBuf));

		MBR *mbr = reinterpret_cast <MBR *> (mbrBuf);
		if (mbr->Signature != 0xaa55)
			throw ParameterIncorrect (SRC_POS);

		for (size_t i = 0; i < array_capacity (mbr->Partitions); ++i)
		{
			if (mbr->Partitions[i].Type == type)
				return true;
		}

		return false;
	}


	bool BootEncryption::SystemDriveContainsExtendedPartition ()
	{
		return SystemDriveContainsPartitionType (PARTITION_EXTENDED) || SystemDriveContainsPartitionType (PARTITION_XINT13_EXTENDED);
	}


	bool BootEncryption::SystemDriveContainsNonStandardPartitions ()
	{
		for (int partitionType = 1; partitionType <= 0xff; ++partitionType)
		{
			switch (partitionType)
			{
			case PARTITION_FAT_12:
			case PARTITION_FAT_16:
			case PARTITION_EXTENDED:
			case PARTITION_HUGE:
			case PARTITION_IFS:
			case PARTITION_FAT32:
			case PARTITION_FAT32_XINT13:
			case PARTITION_XINT13:
			case PARTITION_XINT13_EXTENDED:
				continue;
			}

			if (SystemDriveContainsPartitionType ((byte) partitionType))
				return true;
		}

		return false;
	}


	bool BootEncryption::SystemDriveIsDynamic ()
	{
		GetSystemDriveConfigurationRequest request;
		StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), GetSystemDriveConfiguration().DeviceKernelPath.c_str());

		CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request));
		return request.DriveIsDynamic ? true : false;
	}


	SystemDriveConfiguration BootEncryption::GetSystemDriveConfiguration ()
	{
		if (DriveConfigValid)
			return DriveConfig;

		SystemDriveConfiguration config;

		wstring winDir = GetWindowsDirectory();

		// Scan all drives
		for (int driveNumber = 0; driveNumber < 32; ++driveNumber)
		{
			bool windowsFound = false;
			bool activePartitionFound = false;
			config.ExtraBootPartitionPresent = false;
			config.SystemLoaderPresent = false;

			PartitionList partitions = GetDrivePartitions (driveNumber);
			foreach (const Partition &part, partitions)
			{
				if (!part.MountPoint.empty()
					&& (_waccess ((part.MountPoint + L"\\bootmgr").c_str(), 0) == 0 || _waccess ((part.MountPoint + L"\\ntldr").c_str(), 0) == 0))
				{
					config.SystemLoaderPresent = true;
				}
				else if (!part.VolumeNameId.empty()
					&& (_waccess ((part.VolumeNameId + L"\\bootmgr").c_str(), 0) == 0 || _waccess ((part.VolumeNameId + L"\\ntldr").c_str(), 0) == 0))
				{
					config.SystemLoaderPresent = true;
				}

				if (!windowsFound && !part.MountPoint.empty() && ToUpperCase (winDir).find (ToUpperCase (part.MountPoint)) == 0)
				{
					config.SystemPartition = part;
					windowsFound = true;
				}

				if (!activePartitionFound && part.Info.BootIndicator)
				{
					activePartitionFound = true;

					if (part.Info.PartitionLength.QuadPart > 0 && part.Info.PartitionLength.QuadPart <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE)
						config.ExtraBootPartitionPresent = true;
				}
			}

			if (windowsFound)
			{
				config.DriveNumber = driveNumber;

				wstringstream ss;
				ss << L"PhysicalDrive" << driveNumber;
				config.DevicePath = ss.str();

				wstringstream kernelPath;
				kernelPath << L"\\Device\\Harddisk" << driveNumber << L"\\Partition0";
				config.DeviceKernelPath = kernelPath.str();

				config.DrivePartition = partitions.front();
				partitions.pop_front();
				config.Partitions = partitions;

				config.InitialUnallocatedSpace = 0x7fffFFFFffffFFFFull;
				config.TotalUnallocatedSpace = config.DrivePartition.Info.PartitionLength.QuadPart;

				foreach (const Partition &part, config.Partitions)
				{
					if (part.Info.StartingOffset.QuadPart < config.InitialUnallocatedSpace)
						config.InitialUnallocatedSpace = part.Info.StartingOffset.QuadPart;

					config.TotalUnallocatedSpace -= part.Info.PartitionLength.QuadPart;
				}

				DriveConfig = config;
				DriveConfigValid = true;
				return DriveConfig;
			}
		}

		throw ParameterIncorrect (SRC_POS);
	}


	bool BootEncryption::SystemPartitionCoversWholeDrive ()
	{
		SystemDriveConfiguration config = GetSystemDriveConfiguration();

		if (IsOSAtLeast (WIN_7)
			&& config.Partitions.size() == 2
			&& config.ExtraBootPartitionPresent
			&& config.DrivePartition.Info.PartitionLength.QuadPart - config.SystemPartition.Info.PartitionLength.QuadPart < 164 * BYTES_PER_MB)
		{
			return true;
		}

		return config.Partitions.size() == 1
			&& config.DrivePartition.Info.PartitionLength.QuadPart - config.SystemPartition.Info.PartitionLength.QuadPart < 64 * BYTES_PER_MB;
	}


	uint32 BootEncryption::GetChecksum (byte *data, size_t size)
	{
		uint32 sum = 0;

		while (size-- > 0)
		{
			sum += *data++;
			sum = _rotl (sum, 1);
		}

		return sum;
	}


	void BootEncryption::CreateBootLoaderInMemory (byte *buffer, size_t bufferSize, bool rescueDisk, bool hiddenOSCreation)
	{
		if (bufferSize < TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE)
			throw ParameterIncorrect (SRC_POS);

		ZeroMemory (buffer, bufferSize);

		int ea = 0;
		int pkcs5_prf = 0;
		BOOL bIsGPT = GetSystemDriveConfiguration().SystemPartition.IsGPT;
		if (GetStatus().DriveMounted)
		{
			try
			{
				GetBootEncryptionAlgorithmNameRequest request;
				// since we added new field to GetBootEncryptionAlgorithmNameRequest since version 1.0f
				// we zero all the structure so that if we are talking to an older driver, the field
				// BootPrfAlgorithmName will be an empty string
				ZeroMemory(&request, sizeof(request));
				CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME, NULL, 0, &request, sizeof (request));

				if (_stricmp (request.BootEncryptionAlgorithmName, "AES") == 0)
					ea = AES;
				else if (_stricmp (request.BootEncryptionAlgorithmName, "Serpent") == 0)
					ea = SERPENT;
				else if (_stricmp (request.BootEncryptionAlgorithmName, "Twofish") == 0)
					ea = TWOFISH;
				else if (_stricmp (request.BootEncryptionAlgorithmName, "Camellia") == 0)
					ea = CAMELLIA;
#if defined(CIPHER_GOST89)
				else if (_stricmp (request.BootEncryptionAlgorithmName, "GOST89") == 0)
					ea = GOST89;
#endif

				if (_stricmp(request.BootPrfAlgorithmName, "SHA-256") == 0)
					pkcs5_prf = SHA256;
				else if (_stricmp(request.BootPrfAlgorithmName, "RIPEMD-160") == 0)
					pkcs5_prf = RIPEMD160;
				else if (_stricmp(request.BootPrfAlgorithmName, "SHA-512") == 0)
					pkcs5_prf = SHA512;
				else if (_stricmp(request.BootPrfAlgorithmName, "Whirlpool") == 0)
					pkcs5_prf = WHIRLPOOL;
				else if (_stricmp(request.BootPrfAlgorithmName, "Streebog") == 0)
					pkcs5_prf = STREEBOG;
				else if (strlen(request.BootPrfAlgorithmName) == 0) // case of version < 1.0f
					pkcs5_prf = RIPEMD160;
			}
			catch (...)
			{
				try
				{
					VOLUME_PROPERTIES_STRUCT properties;
					GetVolumeProperties (&properties);
					ea = properties.ea;
					pkcs5_prf = properties.pkcs5;
				}
				catch (...) { }
			}

			if (pkcs5_prf == 0)
				throw ParameterIncorrect (SRC_POS);
		}
		else
		{
			if (SelectedEncryptionAlgorithmId == 0 || SelectedPrfAlgorithmId == 0)
				throw ParameterIncorrect (SRC_POS);

			ea = SelectedEncryptionAlgorithmId;
			pkcs5_prf = SelectedPrfAlgorithmId;
		}

		// Only RIPEMD160 and SHA-256 are supported for MBR boot loader		
		if (!bIsGPT && pkcs5_prf != RIPEMD160 && pkcs5_prf != SHA256)
			throw ParameterIncorrect (SRC_POS);

		int bootSectorId = 0;
		int bootLoaderId = 0;

		if (pkcs5_prf == SHA256)
		{
			bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SHA2 : IDR_BOOT_SECTOR_SHA2;
			bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SHA2 : IDR_BOOT_LOADER_SHA2;
		}
		else
		{
			bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR : IDR_BOOT_SECTOR;
			bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER : IDR_BOOT_LOADER;
		}

		switch (ea)
		{
		case AES:
			if (pkcs5_prf == SHA256)
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES_SHA2 : IDR_BOOT_SECTOR_AES_SHA2;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES_SHA2 : IDR_BOOT_LOADER_AES_SHA2;
			}
			else
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES : IDR_BOOT_SECTOR_AES;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES : IDR_BOOT_LOADER_AES;
			}
			break;

		case SERPENT:
			if (pkcs5_prf == SHA256)
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 : IDR_BOOT_SECTOR_SERPENT_SHA2;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT_SHA2 : IDR_BOOT_LOADER_SERPENT_SHA2;
			}
			else
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT : IDR_BOOT_SECTOR_SERPENT;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT : IDR_BOOT_LOADER_SERPENT;
			}
			break;

		case TWOFISH:
			if (pkcs5_prf == SHA256)
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 : IDR_BOOT_SECTOR_TWOFISH_SHA2;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH_SHA2 : IDR_BOOT_LOADER_TWOFISH_SHA2;
			}
			else
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH : IDR_BOOT_SECTOR_TWOFISH;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH : IDR_BOOT_LOADER_TWOFISH;
			}
			break;
			
		case CAMELLIA:
			if (pkcs5_prf == SHA256)
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_CAMELLIA_SHA2 : IDR_BOOT_SECTOR_CAMELLIA_SHA2;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_CAMELLIA_SHA2 : IDR_BOOT_LOADER_CAMELLIA_SHA2;
			}
			else
			{
				bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_CAMELLIA : IDR_BOOT_SECTOR_CAMELLIA;
				bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_CAMELLIA : IDR_BOOT_LOADER_CAMELLIA;
			}
			break;
		}

		// Boot sector
		DWORD size;
		byte *bootSecResourceImg = MapResource (L"BIN", bootSectorId, &size);
		if (!bootSecResourceImg || size != TC_SECTOR_SIZE_BIOS)
			throw ParameterIncorrect (SRC_POS);

		memcpy (buffer, bootSecResourceImg, size);

		*(uint16 *) (buffer + TC_BOOT_SECTOR_VERSION_OFFSET) = BE16 (VERSION_NUM);

		if (IsOSAtLeast (WIN_VISTA))
			buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER;

		if (rescueDisk && (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION))
			buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION;

		// Checksum of the backup header of the outer volume for the hidden system
		if (hiddenOSCreation)
		{
			Device device (GetSystemDriveConfiguration().DevicePath);
			device.CheckOpened (SRC_POS);
			byte headerSector[TC_SECTOR_SIZE_BIOS];

			device.SeekAt (HiddenOSCandidatePartition.Info.StartingOffset.QuadPart + HiddenOSCandidatePartition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE + TC_VOLUME_HEADER_EFFECTIVE_SIZE);
			device.Read (headerSector, sizeof (headerSector));

			*(uint32 *) (buffer + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET) = GetCrc32 (headerSector, sizeof (headerSector));
		}

		// Decompressor
		byte *decompressor = MapResource (L"BIN", IDR_BOOT_LOADER_DECOMPRESSOR, &size);
		if (!decompressor || size > TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
			throw ParameterIncorrect (SRC_POS);

		memcpy (buffer + TC_SECTOR_SIZE_BIOS, decompressor, size);

		// Compressed boot loader
		byte *bootLoader = MapResource (L"BIN", bootLoaderId, &size);
		if (!bootLoader || size > TC_MAX_BOOT_LOADER_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
			throw ParameterIncorrect (SRC_POS);

		memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS, bootLoader, size);

		// Boot loader and decompressor checksum
		*(uint16 *) (buffer + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET) = static_cast <uint16> (size);
		*(uint32 *) (buffer + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET) = GetChecksum (buffer + TC_SECTOR_SIZE_BIOS,
			TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS + size);

		// Backup of decompressor and boot loader
		if (size + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS <= TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
		{
			memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS,
				buffer + TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS);

			buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE;
		}
		else if (!rescueDisk && bootLoaderId != IDR_BOOT_LOADER && bootLoaderId != IDR_BOOT_LOADER_SHA2)
		{
			throw ParameterIncorrect (SRC_POS);
		}
	}

	void BootEncryption::ReadEfiConfig (byte* confContent, DWORD maxSize, DWORD* pcbRead)
	{
		if (!pcbRead)
			throw ParameterIncorrect (SRC_POS);

		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::ReadEfiConfig (confContent, maxSize, pcbRead);
		}
		else
		{
			unsigned __int64 ui64Size = 0;

			finally_do ({ EfiBootInst.DismountBootPartition(); });
			EfiBootInst.MountBootPartition(0);		

			EfiBootInst.GetFileSize(L"\\EFI\\VeraCrypt\\DcsProp", ui64Size);

			*pcbRead = (DWORD) ui64Size;

			if (*pcbRead > maxSize)
				throw ParameterIncorrect (SRC_POS);

			EfiBootInst.ReadFile (L"\\EFI\\VeraCrypt\\DcsProp", confContent, *pcbRead);		
		}
	}

	// return false when the user cancel an elevation request
	bool BootEncryption::ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig, string *customUserMessage, uint16 *bootLoaderVersion)
	{
		bool bCanceled = false, bExceptionOccured = false;
		try
		{
			if (GetSystemDriveConfiguration().SystemPartition.IsGPT)
			{
				byte confContent[4096];
				DWORD dwSize;

				// for now, we don't support any boot config flags, like hidden OS one
				if (config)
					memset (config, 0, bufLength);

				// call ReadEfiConfig only when needed since it requires elevation
				if (userConfig || customUserMessage || bootLoaderVersion)
				{
					ReadEfiConfig (confContent, sizeof (confContent) - 1, &dwSize);
					
					confContent[dwSize] = 0;

					EfiBootConf conf;
					conf.Load ((char*) confContent);

					if (userConfig)
					{
						*userConfig = 0;
						if (!conf.requestPim)
							*userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_PIM;
						if (!conf.requestHash)
							*userConfig |= TC_BOOT_USER_CFG_FLAG_STORE_HASH;

					}

					if (customUserMessage)
						customUserMessage->clear();

					if (bootLoaderVersion)
					{
						*bootLoaderVersion = GetStatus().BootLoaderVersion;
					}
				}
			}
			else
			{
				if (config && bufLength < TC_BOOT_CFG_FLAG_AREA_SIZE)
					throw ParameterIncorrect (SRC_POS);

				GetSystemDriveConfigurationRequest request;
				StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), GetSystemDriveConfiguration().DeviceKernelPath.c_str());

				CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request));
				if (config)
					*config = request.Configuration;

				if (userConfig)
					*userConfig = request.UserConfiguration;
				
				if (customUserMessage)
				{
					request.CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0;
					*customUserMessage = request.CustomUserMessage;
				}

				if (bootLoaderVersion)
					*bootLoaderVersion = request.BootLoaderVersion;
			}
		}
		catch (UserAbort&)
		{
			bCanceled = true;
			bExceptionOccured= true;
		}
		catch (...)
		{
			bExceptionOccured = true;
		}

		if (bExceptionOccured)
		{
			if (config)
				*config = 0;

			if (userConfig)
				*userConfig = 0;
			
			if (customUserMessage)
				customUserMessage->clear();

			if (bootLoaderVersion)
				*bootLoaderVersion = 0;
		}

		return !bCanceled;
	}


	void BootEncryption::WriteBootSectorConfig (const byte newConfig[])
	{
		Device device (GetSystemDriveConfiguration().DevicePath);
		device.CheckOpened (SRC_POS);
		byte mbr[TC_SECTOR_SIZE_BIOS];

		device.SeekAt (0);
		device.Read (mbr, sizeof (mbr));

		memcpy (mbr + TC_BOOT_SECTOR_CONFIG_OFFSET, newConfig, TC_BOOT_CFG_FLAG_AREA_SIZE);

		device.SeekAt (0);
		device.Write (mbr, sizeof (mbr));

		byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS];
		device.SeekAt (0);
		device.Read (mbrVerificationBuf, sizeof (mbr));

		if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0)
			throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS);
	}

	void BootEncryption::WriteEfiBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg)
	{
		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::WriteEfiBootSectorUserConfig (userConfig, customUserMessage, pim, hashAlg);
		}
		else
		{
			finally_do ({ EfiBootInst.DismountBootPartition(); });
			EfiBootInst.MountBootPartition(0);

			if (! (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM))
				pim = -1;
			if (! (userConfig & TC_BOOT_USER_CFG_FLAG_STORE_HASH))
				hashAlg = -1;				

			EfiBootInst.UpdateConfig (L"\\EFI\\VeraCrypt\\DcsProp", pim, hashAlg, ParentWindow);
		}
	}

	void BootEncryption::WriteBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg)
	{
		if (GetSystemDriveConfiguration().SystemPartition.IsGPT)
		{
			WriteEfiBootSectorUserConfig (userConfig, customUserMessage, pim, hashAlg);
		}
		else
		{
			Device device (GetSystemDriveConfiguration().DevicePath);
			device.CheckOpened (SRC_POS);
			byte mbr[TC_SECTOR_SIZE_BIOS];

			device.SeekAt (0);
			device.Read (mbr, sizeof (mbr));

			if (!BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME)
				|| BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET)) != VERSION_NUM)
			{
				return;
			}

			mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = userConfig;

			memset (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, 0, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH);

			if (!customUserMessage.empty())
			{
				if (customUserMessage.size() > TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)
					throw ParameterIncorrect (SRC_POS);

				memcpy (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, customUserMessage.c_str(), customUserMessage.size());
			}
			
			if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM)
			{
				// PIM for pre-boot authentication can be encoded on two bytes since its maximum
				// value is 65535 (0xFFFF)
				memcpy (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE);
			}
			else
				memset (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, 0, TC_BOOT_SECTOR_PIM_VALUE_SIZE);

			device.SeekAt (0);
			device.Write (mbr, sizeof (mbr));

			byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS];
			device.SeekAt (0);
			device.Read (mbrVerificationBuf, sizeof (mbr));

			if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0)
				throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS);
		}
	}


	unsigned int BootEncryption::GetHiddenOSCreationPhase ()
	{
		byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE];

		ReadBootSectorConfig (configFlags, sizeof(configFlags));

		return (configFlags[0] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE);
	}


	void BootEncryption::SetHiddenOSCreationPhase (unsigned int newPhase)
	{
#if TC_BOOT_CFG_FLAG_AREA_SIZE != 1
#	error TC_BOOT_CFG_FLAG_AREA_SIZE != 1; revise GetHiddenOSCreationPhase() and SetHiddenOSCreationPhase()
#endif
		byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE];

		ReadBootSectorConfig (configFlags, sizeof(configFlags));

		configFlags[0] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE;

		configFlags[0] |= newPhase;

		WriteBootSectorConfig (configFlags);
	}


#ifndef SETUP

	void BootEncryption::StartDecoyOSWipe (WipeAlgorithmId wipeAlgorithm)
	{
		if (!IsHiddenOSRunning())
			throw ParameterIncorrect (SRC_POS);

		WipeDecoySystemRequest request;
		ZeroMemory (&request, sizeof (request));

		request.WipeAlgorithm = wipeAlgorithm;
		
		if (Randinit() != ERR_SUCCESS)
		{
			if (CryptoAPILastError == ERROR_SUCCESS)
				throw RandInitFailed (SRC_POS, GetLastError ());
			else
				throw CryptoApiFailed (SRC_POS, CryptoAPILastError);
		}

		/* force the display of the random enriching dialog */
		SetRandomPoolEnrichedByUserStatus (FALSE);

		UserEnrichRandomPool (ParentWindow);

		if (!RandgetBytes (ParentWindow, request.WipeKey, sizeof (request.WipeKey), TRUE))
			throw ParameterIncorrect (SRC_POS);

		CallDriver (TC_IOCTL_START_DECOY_SYSTEM_WIPE, &request, sizeof (request), NULL, 0);

		burn (&request, sizeof (request));
	}


	void BootEncryption::AbortDecoyOSWipe ()
	{
		CallDriver (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE);
	}

	
	DecoySystemWipeStatus BootEncryption::GetDecoyOSWipeStatus ()
	{
		DecoySystemWipeStatus status;
		CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS, NULL, 0, &status, sizeof (status));
		return status;
	}


	void BootEncryption::CheckDecoyOSWipeResult ()
	{
		CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT);
	}


	void BootEncryption::WipeHiddenOSCreationConfig ()
	{
		if (IsHiddenOSRunning())
			throw ParameterIncorrect (SRC_POS);

		if (Randinit() != ERR_SUCCESS)
		{
			if (CryptoAPILastError == ERROR_SUCCESS)
				throw RandInitFailed (SRC_POS, GetLastError ());
			else
				throw CryptoApiFailed (SRC_POS, CryptoAPILastError);
		}

		Device device (GetSystemDriveConfiguration().DevicePath);
		device.CheckOpened(SRC_POS);
		byte mbr[TC_SECTOR_SIZE_BIOS];

		device.SeekAt (0);
		device.Read (mbr, sizeof (mbr));
		
		finally_do_arg (BootEncryption *, this,
		{
			try
			{
				finally_arg->SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE);
			} catch (...) { }
		});

#if PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE
#	error PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE
#endif

		byte randData[PRAND_DISK_WIPE_PASSES];
		if (!RandgetBytes (ParentWindow, randData, sizeof (randData), FALSE))
			throw ParameterIncorrect (SRC_POS);

		for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES; wipePass++)
		{
			for (int i = 0; i < TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE; ++i)
			{
				mbr[TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + i] = randData[wipePass];
			}

			mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE;
			mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] |= randData[wipePass] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE;

			if (wipePass == PRAND_DISK_WIPE_PASSES - 1)
				memset (mbr + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET, 0, TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE);

			device.SeekAt (0);
			device.Write (mbr, sizeof (mbr));
		}

		for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES/4 + 1; wipePass++)
		{
			SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE);
			SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_CLONING);
			SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPING);
			SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPED);
		}
		SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE);
	}

#endif // !SETUP

	NtQuerySystemInformationFn NtQuerySystemInformationPtr = NULL;

	EfiBootConf::EfiBootConf() : passwordType (0),
		passwordMsg ("Enter Password: "),
		passwordPicture ("login.bmp"),
		hashMsg ("(0) TEST ALL (1) SHA512 (2) WHIRLPOOL (3) SHA256 (4) RIPEMD160 (5) STREEBOG\nHash: "),
		hashAlgo (0),
		requestHash (0),
		pimMsg ("PIM (Leave empty for default): "),
		pim (0),
		requestPim (1),
		authorizeVisible (0),
		authorizeRetry (10)
	{

	}

	BOOL EfiBootConf::ReadConfigValue (char* configContent, const char *configKey, char *configValue, int maxValueSize)
	{
		char *xml;

		xml = configContent;
		if (xml != NULL)
		{
			xml = XmlFindElementByAttributeValue (xml, "config", "key", configKey);
			if (xml != NULL)
			{
				XmlGetNodeText (xml, configValue, maxValueSize);
				return TRUE;
			}
		}

		return FALSE;
	}


	int EfiBootConf::ReadConfigInteger (char* configContent, const char *configKey, int defaultValue)
	{
		char s[32];
		int iRet;
		if (ReadConfigValue (configContent, configKey, s, sizeof (s)))
			iRet = atoi (s);
		else
			iRet = defaultValue;
		burn (s, sizeof (s));
		return iRet;
	}


	char* EfiBootConf::ReadConfigString (char* configContent, const char *configKey, char *defaultValue, char *str, int maxLen)
	{
		if (ReadConfigValue (configContent, configKey, str, maxLen))
			return str;
		else
		{
			StringCbCopyA (str, maxLen, defaultValue);
			return defaultValue;
		}
	}

	BOOL EfiBootConf::WriteConfigString (FILE* configFile, char* configContent, const char *configKey, const char *configValue)
	{
		
		BOOL bRet = FALSE;
		if (configFile)
		{
			char *c;
			// Mark previous config value as updated
			if (configContent != NULL)
			{
				c = XmlFindElementByAttributeValue (configContent, "config", "key", configKey);
				if (c != NULL)
					c[1] = '!';
			}

			if ( 0 != fwprintf (
					configFile, L"\n\t\t<config key=\"%hs\">%hs</config>",
					configKey, configValue))
			{
				bRet = TRUE;
			}
		}
		return bRet;
	}

	BOOL EfiBootConf::WriteConfigInteger (FILE* configFile, char* configContent, const char *configKey, int configValue)
	{
		BOOL bRet = FALSE;
		if (configFile)
		{
			char val[32];
			StringCbPrintfA (val, sizeof(val), "%d", configValue);
			bRet = WriteConfigString (configFile, configContent, configKey, val);
			burn (val, sizeof (val));
		}
		return bRet;
	}

	BOOL EfiBootConf::Load (const wchar_t* fileName)
	{
		DWORD size = 0;
		char* configContent = LoadFile (fileName, &size);
		if (configContent)
		{
			Load (configContent);
			burn (configContent, size);
			free (configContent);
			return TRUE;
		}
		else
			return FALSE;
	}

	void EfiBootConf::Load (char* configContent)
	{
		char buffer[1024];

		passwordType = ReadConfigInteger (configContent, "PasswordType", 0);
		passwordMsg = ReadConfigString (configContent, "PasswordMsg", "Enter password: ", buffer, sizeof (buffer));
		passwordPicture = ReadConfigString (configContent, "PasswordPicture", "\\EFI\\VeraCrypt\\login.bmp", buffer, sizeof (buffer));
		//hashMsg = ReadConfigString (configContent, "HashMsg", "(0) TEST ALL (1) SHA512 (2) WHIRLPOOL (3) SHA256 (4) RIPEMD160 (5) STREEBOG\nHash: ", buffer, sizeof (buffer));
		hashAlgo = ReadConfigInteger (configContent, "Hash", 0);
		requestHash = ReadConfigInteger (configContent, "HashRqt", 1);
		pimMsg = ReadConfigString (configContent, "PimMsg", "PIM: ", buffer, sizeof (buffer));
		pim = ReadConfigInteger (configContent, "Pim", 0);
		requestPim = ReadConfigInteger (configContent, "PimRqt", 1);
		authorizeVisible = ReadConfigInteger (configContent, "AuthorizeVisible", 0);
		authorizeRetry = ReadConfigInteger (configContent, "AuthorizeRetry", 0);

		burn (buffer, sizeof (buffer));
	}

	BOOL EfiBootConf::Save (const wchar_t* fileName, HWND hwnd)
	{
		FILE *configFile = _wfopen (fileName, L"w,ccs=UTF-8");
		if (configFile == NULL)
			return FALSE;

		BOOL bRet = FALSE;
		DWORD size = 0;
		char* configContent = LoadFile (fileName, &size);
		

		XmlWriteHeader (configFile);
		fputws (L"\n\t<configuration>", configFile);

		WriteConfigInteger (configFile, configContent, "PasswordType", passwordType);
		WriteConfigString (configFile, configContent, "PasswordMsg", passwordMsg.c_str());
		WriteConfigString (configFile, configContent, "PasswordPicture", passwordPicture.c_str());
		WriteConfigString (configFile, configContent, "HashMsg", hashMsg.c_str());
		WriteConfigInteger (configFile, configContent, "Hash", hashAlgo);
		WriteConfigInteger (configFile, configContent, "HashRqt", requestHash);
		WriteConfigString (configFile, configContent, "PimMsg", pimMsg.c_str());
		WriteConfigInteger (configFile, configContent, "Pim", pim);
		WriteConfigInteger (configFile, configContent, "PimRqt", requestPim);
		WriteConfigInteger (configFile, configContent, "AuthorizeVisible", authorizeVisible);
		WriteConfigInteger (configFile, configContent, "AuthorizeRetry", authorizeRetry);

		// Write unmodified values
		char* xml = configContent;
		char key[128], value[2048];
		while (xml && (xml = XmlFindElement (xml, "config")))
		{
			XmlGetAttributeText (xml, "key", key, sizeof (key));
			XmlGetNodeText (xml, value, sizeof (value));

			fwprintf (configFile, L"\n\t\t<config key=\"%hs\">%hs</config>", key, value);
			xml++;
		}

		fputws (L"\n\t</configuration>", configFile);
		XmlWriteFooter (configFile);

		TCFlushFile (configFile);

		bRet = CheckFileStreamWriteErrors (hwnd, configFile, fileName);

		fclose (configFile);

		if (configContent != NULL)
		{
			burn (configContent, size);
			free (configContent);
		}

		return bRet;
	}

	static const wchar_t*	EfiVarGuid = L"{8BE4DF61-93CA-11D2-AA0D-00E098032B8C}";

	EfiBoot::EfiBoot() {
		ZeroMemory(EfiBootPartPath, sizeof(EfiBootPartPath));		
		ZeroMemory (systemPartitionPath, sizeof (systemPartitionPath));
		m_bMounted = false;
	}

	void EfiBoot::MountBootPartition(WCHAR letter) {
		NTSTATUS res;
		ULONG    len;
		memset(tempBuf, 0, sizeof(tempBuf));

		// Load NtQuerySystemInformation function point
		if (!NtQuerySystemInformationPtr)
		{
			NtQuerySystemInformationPtr = (NtQuerySystemInformationFn) GetProcAddress (GetModuleHandle (L"ntdll.dll"), "NtQuerySystemInformation");
			if (!NtQuerySystemInformationPtr)
				throw SystemException (SRC_POS);
		}

		res = NtQuerySystemInformationPtr((SYSTEM_INFORMATION_CLASS)SYSPARTITIONINFORMATION, tempBuf, sizeof(tempBuf), &len);
		if (res != S_OK)
		{
			SetLastError (res);
			throw SystemException (SRC_POS);
		}		

		PUNICODE_STRING pStr = (PUNICODE_STRING) tempBuf;
		memcpy (systemPartitionPath, pStr->Buffer, min (pStr->Length, (sizeof (systemPartitionPath) - 2)));	

		if (!letter) {
			if (!GetFreeDriveLetter(&EfiBootPartPath[0])) {
				throw ErrorException(L"No free letter to mount EFI boot partition", SRC_POS);
			}
		} else {
			EfiBootPartPath[0] = letter;
		}
		EfiBootPartPath[1] = ':';
		EfiBootPartPath[2] = 0;
		throw_sys_if(!DefineDosDevice(DDD_RAW_TARGET_PATH, EfiBootPartPath, systemPartitionPath));		

		Device  dev(EfiBootPartPath, TRUE);

		try
		{
			dev.CheckOpened(SRC_POS);
		}
		catch (...)
		{
			DefineDosDevice(DDD_REMOVE_DEFINITION, EfiBootPartPath, NULL);
			throw;
		}
		
		bool bSuccess = dev.IoCtl(IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn))
							&& dev.IoCtl(IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &partInfo, sizeof(partInfo));
		DWORD dwLastError = GetLastError ();
		dev.Close();
		if (!bSuccess)
		{
			DefineDosDevice(DDD_REMOVE_DEFINITION, EfiBootPartPath, NULL);
			SetLastError (dwLastError);
			throw SystemException(SRC_POS);
		}

		m_bMounted = true;
	}

	void EfiBoot::DismountBootPartition() {
		if (m_bMounted)
		{
			DefineDosDevice(DDD_REMOVE_DEFINITION, EfiBootPartPath, NULL);
			m_bMounted = false;
		}
	}

	bool EfiBoot::IsEfiBoot() {
		DWORD BootOrderLen;
		BootOrderLen = GetFirmwareEnvironmentVariable(L"BootOrder", EfiVarGuid, tempBuf, sizeof(tempBuf));
		return BootOrderLen != 0;
	}

	void EfiBoot::DeleteStartExec(uint16 statrtOrderNum, wchar_t* type) {
		RaisePrivileges();
		// Check EFI
		if (!IsEfiBoot()) {
			throw ErrorException(L"can not detect EFI environment", SRC_POS);
		}
		wchar_t	varName[256];
		StringCchPrintfW(varName, ARRAYSIZE (varName), L"%s%04X", type == NULL ? L"Boot" : type, statrtOrderNum);
		SetFirmwareEnvironmentVariable(varName, EfiVarGuid, NULL, 0);

		wstring order = L"Order";
		order.insert(0, type == NULL ? L"Boot" : type);
		uint32 startOrderLen = GetFirmwareEnvironmentVariable(order.c_str(), EfiVarGuid, tempBuf, sizeof(tempBuf));
		uint32 startOrderNumPos = UINT_MAX;
		bool	startOrderUpdate = false;
		uint16*	startOrder = (uint16*)tempBuf;
		for (uint32 i = 0; i < startOrderLen / 2; i++) {
			if (startOrder[i] == statrtOrderNum) {
				startOrderNumPos = i;
				break;
			}
		}

		// delete entry if present
		if (startOrderNumPos != UINT_MAX) {
			for (uint32 i = startOrderNumPos; i < ((startOrderLen / 2) - 1); ++i) {
				startOrder[i] = startOrder[i + 1];
			}
			startOrderLen -= 2;
			startOrderUpdate = true;
		}

		if (startOrderUpdate) {
			SetFirmwareEnvironmentVariable(order.c_str(), EfiVarGuid, startOrder, startOrderLen);

			// remove ourselves from BootNext value
			uint16 bootNextValue = 0;
			wstring next = L"Next";
			next.insert(0, type == NULL ? L"Boot" : type);

			if (	(GetFirmwareEnvironmentVariable(next.c_str(), EfiVarGuid, &bootNextValue, 2) == 2)
				&&	(bootNextValue == statrtOrderNum)
				)
			{
				SetFirmwareEnvironmentVariable(next.c_str(), EfiVarGuid, startOrder, 0);
			}
		}
	}

	void EfiBoot::SetStartExec(wstring description, wstring execPath, uint16 statrtOrderNum , wchar_t* type, uint32 attr) {
		RaisePrivileges();
		// Check EFI
		if (!IsEfiBoot()) {
			throw ErrorException(L"can not detect EFI environment", SRC_POS);
		}
		
		uint32 varSize = 56;
		varSize += ((uint32) description.length()) * 2 + 2;
		varSize += ((uint32) execPath.length()) * 2 + 2;
		byte *startVar = new byte[varSize];
		byte *pVar = startVar;

		// Attributes (1b Active, 1000b - Hidden)
		*(uint32 *)pVar = attr;
		pVar += sizeof(uint32);

		// Size Of device path + file path
		*(uint16 *)pVar = (uint16)(50 + execPath.length() * 2 + 2);
		pVar += sizeof(uint16);

		// description
		for (uint32 i = 0; i < description.length(); i++) {
			*(uint16 *)pVar = description[i];
			pVar += sizeof(uint16);
		}
		*(uint16 *)pVar = 0;
		pVar += sizeof(uint16);

		/* EFI_DEVICE_PATH_PROTOCOL (HARDDRIVE_DEVICE_PATH \ FILE_PATH \ END) */

		// Type
		*(byte *)pVar = 0x04;
		pVar += sizeof(byte);

		// SubType
		*(byte *)pVar = 0x01;
		pVar += sizeof(byte);

		// HDD dev path length
		*(uint16 *)pVar = 0x2A; // 42
		pVar += sizeof(uint16);
		
		// PartitionNumber
		*(uint32 *)pVar = (uint32)partInfo.PartitionNumber;
		pVar += sizeof(uint32);

		// PartitionStart
		*(uint64 *)pVar = partInfo.StartingOffset.QuadPart >> 9;
		pVar += sizeof(uint64);

		// PartitiontSize
		*(uint64 *)pVar = partInfo.PartitionLength.QuadPart >> 9;
		pVar += sizeof(uint64);

		// GptGuid
		memcpy(pVar, &partInfo.Gpt.PartitionId, 16);
		pVar += 16;

		// MbrType
		*(byte *)pVar = 0x02;
		pVar += sizeof(byte);

		// SigType
		*(byte *)pVar = 0x02;
		pVar += sizeof(byte);

		// Type and sub type 04 04 (file path)
		*(uint16 *)pVar = 0x0404;
		pVar += sizeof(uint16);

		// SizeOfFilePath ((CHAR16)FullPath.length + sizeof(EndOfrecord marker) )
		*(uint16 *)pVar = (uint16)(execPath.length() * 2 + 2 + sizeof(uint32));
		pVar += sizeof(uint16);

		// FilePath
		for (uint32 i = 0; i < execPath.length(); i++) {
			*(uint16 *)pVar = execPath[i];
			pVar += sizeof(uint16);
		}
		*(uint16 *)pVar = 0;
		pVar += sizeof(uint16);

		// EndOfrecord
		*(uint32 *)pVar = 0x04ff7f;
		pVar += sizeof(uint32);

		// Set variable
		wchar_t	varName[256];
		StringCchPrintfW(varName, ARRAYSIZE (varName), L"%s%04X", type == NULL ? L"Boot" : type, statrtOrderNum);
		SetFirmwareEnvironmentVariable(varName, EfiVarGuid, startVar, varSize);
		delete startVar;

		// Update order
		wstring order = L"Order";
		order.insert(0, type == NULL ? L"Boot" : type);

		uint32 startOrderLen = GetFirmwareEnvironmentVariable(order.c_str(), EfiVarGuid, tempBuf, sizeof(tempBuf));
		uint32 startOrderNumPos = UINT_MAX;
		bool	startOrderUpdate = false;
		uint16*	startOrder = (uint16*)tempBuf;
		for (uint32 i = 0; i < startOrderLen / 2; i++) {
			if (startOrder[i] == statrtOrderNum) {
				startOrderNumPos = i;
				break;
			}
		}

		// Create new entry if absent
		if (startOrderNumPos == UINT_MAX) {
			for (uint32 i = startOrderLen / 2; i > 0; --i) {
				startOrder[i] = startOrder[i - 1];
			}
			startOrder[0] = statrtOrderNum;
			startOrderLen += 2;
			startOrderUpdate = true;
		} else if (startOrderNumPos > 0) {
			for (uint32 i = startOrderNumPos; i > 0; --i) {
				startOrder[i] = startOrder[i - 1];
			}
			startOrder[0] = statrtOrderNum;
			startOrderUpdate = true;
		}

		if (startOrderUpdate) {
			SetFirmwareEnvironmentVariable(order.c_str(), EfiVarGuid, startOrder, startOrderLen);
		}

		// set BootNext value
		wstring next = L"Next";
		next.insert(0, type == NULL ? L"Boot" : type);

		SetFirmwareEnvironmentVariable(next.c_str(), EfiVarGuid, &statrtOrderNum, 2);

	}

	void EfiBoot::SaveFile(wchar_t* name, byte* data, DWORD size) {
		wstring path = EfiBootPartPath;
		path += name;
		File f(path, false, true);
		f.Write(data, size);
		f.Close();
	}

	void EfiBoot::GetFileSize(const wchar_t* name, unsigned __int64& size) {
		wstring path = EfiBootPartPath;
		path += name;
		File f(path, true);
		f.GetFileSize(size);
		f.Close();
	}

	void EfiBoot::ReadFile(const wchar_t* name, byte* data, DWORD size) {
		wstring path = EfiBootPartPath;
		path += name;
		File f(path, true);
		f.Read(data, size);
		f.Close();
	}

	void EfiBoot::CopyFile(const wchar_t* name, const wchar_t* targetName) {
		wstring path = EfiBootPartPath;
		path += name;
		wstring targetPath;
		if (targetName[0] == L'\\')
		{
			targetPath = EfiBootPartPath;
			targetPath += targetName;
		}
		else
			targetPath = targetName;
		throw_sys_if (!::CopyFileW (path.c_str(), targetPath.c_str(), FALSE));
	}

	BOOL EfiBoot::RenameFile(wchar_t* name, wchar_t* nameNew, BOOL bForce) {
		wstring path = EfiBootPartPath;
		path += name;
		wstring pathNew = EfiBootPartPath;
		pathNew += nameNew;
		return MoveFileExW(path.c_str(), pathNew.c_str(), bForce? MOVEFILE_REPLACE_EXISTING : 0);
	}

	BOOL EfiBoot::DelFile(wchar_t* name) {
		wstring path = EfiBootPartPath;
		path += name;
		return DeleteFile(path.c_str());
	}

	BOOL EfiBoot::MkDir(wchar_t* name, bool& bAlreadyExists) {
		wstring path = EfiBootPartPath;
		path += name;
		bAlreadyExists = false;
		BOOL bRet = CreateDirectory(path.c_str(), NULL);
		if (!bRet && (GetLastError () == ERROR_ALREADY_EXISTS))
		{
			bRet = TRUE;
			bAlreadyExists = true;
		}
		return bRet;
	}

	BOOL EfiBoot::ReadConfig (wchar_t* name, EfiBootConf& conf)
	{
		wstring path = EfiBootPartPath;
		path += name;

		return conf.Load (path.c_str());
	}

	BOOL EfiBoot::UpdateConfig (wchar_t* name, int pim, int hashAlgo, HWND hwndDlg)
	{
		BOOL bRet = FALSE;
		EfiBootConf conf;
		wstring path = EfiBootPartPath;
		path += name;

		if (conf.Load (path.c_str()))
		{
			if (pim >= 0)
			{
				conf.pim = pim;
				conf.requestPim = 0;
			}
			else
			{
				conf.pim = 0;
				conf.requestPim = 1;
			}

			if (hashAlgo >= 0)
			{
				conf.hashAlgo = hashAlgo;
				conf.requestHash = 0;
			}
			else
			{
				conf.hashAlgo = 0;
				conf.requestHash = 1;
			}

			return conf.Save (path.c_str(), hwndDlg);
		}

		return bRet;
	}

	BOOL EfiBoot::WriteConfig (wchar_t* name, bool preserveUserConfig, int pim, int hashAlgo, const char* passPromptMsg, HWND hwndDlg)
	{
		EfiBootConf conf;
		wstring path = EfiBootPartPath;
		path += name;

		if (preserveUserConfig)
		{
			conf.Load (path.c_str());
			if (pim >= 0 && (conf.requestPim == 0))
			{
				conf.pim = pim;
			}
			if (hashAlgo >= 0 && (conf.requestHash == 0))
			{
				conf.hashAlgo = hashAlgo;
			}
		}
		else
		{
			if (pim >= 0)
			{
				conf.pim = pim;
				conf.requestPim = 0;
			}
			else
			{
				conf.pim = 0;
				conf.requestPim = 1;
			}

			if (hashAlgo >= 0)
			{
				conf.hashAlgo = hashAlgo;
				conf.requestHash = 0;
			}
			else
			{
				conf.hashAlgo = 0;
				conf.requestHash = 1;
			}
		}

		if (passPromptMsg && strlen (passPromptMsg))
		{
			conf.passwordMsg = passPromptMsg;
		}

		return conf.Save (path.c_str(), hwndDlg);
	}

	void BootEncryption::InstallBootLoader (bool preserveUserConfig, bool hiddenOSCreation, int pim, int hashAlg)
	{
		Device device (GetSystemDriveConfiguration().DevicePath);
		device.CheckOpened (SRC_POS);

		InstallBootLoader (device, preserveUserConfig, hiddenOSCreation, pim, hashAlg);
	}

	void BootEncryption::InstallBootLoader (Device& device, bool preserveUserConfig, bool hiddenOSCreation, int pim, int hashAlg)
	{
		SystemDriveConfiguration config = GetSystemDriveConfiguration();

		if (config.SystemPartition.IsGPT) {
			if (!IsAdmin()) {
				if (IsUacSupported())
				{
					Elevator::InstallEfiBootLoader (preserveUserConfig, hiddenOSCreation, pim, hashAlg);
					return;
				}
				else
				{
					Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", ParentWindow);
				}
			}
			DWORD sizeDcsBoot;
			byte *dcsBootImg = MapResource(L"BIN", IDR_EFI_DCSBOOT, &sizeDcsBoot);
			if (!dcsBootImg)
				throw ErrorException(L"Out of resource DcsBoot", SRC_POS);
			DWORD sizeDcsInt;
			byte *dcsIntImg = MapResource(L"BIN", IDR_EFI_DCSINT, &sizeDcsInt);
			if (!dcsIntImg)
				throw ErrorException(L"Out of resource DcsInt", SRC_POS);
			DWORD sizeDcsCfg;
			byte *dcsCfgImg = MapResource(L"BIN", IDR_EFI_DCSCFG, &sizeDcsCfg);
			if (!dcsCfgImg)
				throw ErrorException(L"Out of resource DcsCfg", SRC_POS);
			DWORD sizeLegacySpeaker;
			byte *LegacySpeakerImg = MapResource(L"BIN", IDR_EFI_LEGACYSPEAKER, &sizeLegacySpeaker);
			if (!LegacySpeakerImg)
				throw ErrorException(L"Out of resource LegacySpeaker", SRC_POS);
			DWORD sizeBootMenuLocker;
			byte *BootMenuLockerImg = MapResource(L"BIN", IDR_EFI_DCSBML, &sizeBootMenuLocker);
			if (!BootMenuLockerImg)
				throw ErrorException(L"Out of resource DcsBml", SRC_POS);

			finally_do ({ EfiBootInst.DismountBootPartition(); });
			EfiBootInst.MountBootPartition(0);			

			try
			{
				// Save modules
				bool bAlreadyExist;

				EfiBootInst.MkDir(L"\\EFI\\VeraCrypt", bAlreadyExist);
				EfiBootInst.SaveFile(L"\\EFI\\VeraCrypt\\DcsBoot.efi", dcsBootImg, sizeDcsBoot);
				EfiBootInst.SaveFile(L"\\EFI\\Boot\\bootx64.efi", dcsBootImg, sizeDcsBoot);
				EfiBootInst.SaveFile(L"\\EFI\\VeraCrypt\\DcsInt.dcs", dcsIntImg, sizeDcsInt);
				EfiBootInst.SaveFile(L"\\EFI\\VeraCrypt\\DcsCfg.dcs", dcsCfgImg, sizeDcsCfg);
				EfiBootInst.SaveFile(L"\\EFI\\VeraCrypt\\LegacySpeaker.dcs", LegacySpeakerImg, sizeLegacySpeaker);
				EfiBootInst.SaveFile(L"\\EFI\\VeraCrypt\\DcsBml.dcs", BootMenuLockerImg, sizeBootMenuLocker);
				EfiBootInst.SetStartExec(L"VeraCrypt BootLoader (DcsBoot)", L"\\EFI\\VeraCrypt\\DcsBoot.efi");

				// move configuration file from old location (if it exists) to new location
				// we don't force the move operation if the new location already exists
				EfiBootInst.RenameFile (L"\\DcsProp", L"\\EFI\\VeraCrypt\\DcsProp", FALSE);
				EfiBootInst.RenameFile (L"\\DcsBoot", L"\\EFI\\VeraCrypt\\DcsBoot", FALSE);

				// move the original bootloader backup from old location (if it exists) to new location
				// we don't force the move operation if the new location already exists
				EfiBootInst.RenameFile (L"\\EFI\\Boot\\original_bootx64_vc_backup.efi", L"\\EFI\\Boot\\original_bootx64.vc_backup", FALSE);

				// Clean beta9
				EfiBootInst.DelFile(L"\\DcsBoot.efi");
				EfiBootInst.DelFile(L"\\DcsInt.efi");
				EfiBootInst.DelFile(L"\\DcsCfg.efi");
				EfiBootInst.DelFile(L"\\LegacySpeaker.efi");
				EfiBootInst.DelFile(L"\\DcsBoot");
				EfiBootInst.DelFile(L"\\DcsProp");
			}
			catch (...)
			{
				throw;
			}

			EfiBootInst.WriteConfig (L"\\EFI\\VeraCrypt\\DcsProp", preserveUserConfig, pim, hashAlg, NULL, ParentWindow);
		}
		else
		{
			byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0};
			CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, hiddenOSCreation);

			// Write MBR
			byte mbr[TC_SECTOR_SIZE_BIOS];

			device.SeekAt (0);
			device.Read (mbr, sizeof (mbr));

			if (preserveUserConfig && BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME))
			{
				uint16 version = BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET));
				if (version != 0)
				{
					bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET];
					memcpy (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH);

					if (bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM)
					{
						if (pim >= 0)
						{
							memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE);
						}
						else
							memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, TC_BOOT_SECTOR_PIM_VALUE_SIZE);
					}
				}
			}

			memcpy (mbr, bootLoaderBuf, TC_MAX_MBR_BOOT_CODE_SIZE);

			device.SeekAt (0);
			device.Write (mbr, sizeof (mbr));

			byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS];
			device.SeekAt (0);
			device.Read (mbrVerificationBuf, sizeof (mbr));

			if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0)
				throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS);

			// Write boot loader
			device.SeekAt (TC_SECTOR_SIZE_BIOS);
			device.Write (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, sizeof (bootLoaderBuf) - TC_SECTOR_SIZE_BIOS);
		}
	}

#ifndef SETUP
	bool BootEncryption::CheckBootloaderFingerprint (bool bSilent)
	{
		SystemDriveConfiguration config = GetSystemDriveConfiguration();

		// return true for now when EFI system encryption is used until we implement
		// a dedicated EFI fingerprinting mechanism in VeraCrypt driver
		if (config.SystemPartition.IsGPT)
			return true;

		byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0};
		byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE];
		byte expectedFingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE];
		bool bRet = false;

		try
		{
			// read bootloader fingerprint
			GetInstalledBootLoaderFingerprint (fingerprint);

			// compute expected fingerprint
			CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, false);
			::ComputeBootloaderFingerprint (bootLoaderBuf, sizeof (bootLoaderBuf), expectedFingerprint);

			// compare values
			if (0 == memcmp (fingerprint, expectedFingerprint, sizeof (expectedFingerprint)))
			{
				bRet = true;
			}
		}
		catch (SystemException &e)
		{
			if (!bSilent && (GetLastError () != ERROR_INVALID_IMAGE_HASH))
				e.Show (ParentWindow);
		}
		catch (Exception& e)
		{
			if (!bSilent)
				e.Show (ParentWindow);
		}

		return bRet;
	}
#endif

	wstring BootEncryption::GetSystemLoaderBackupPath ()
	{
		WCHAR pathBuf[MAX_PATH];

		throw_sys_if (!SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, pathBuf)));
		
		wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME);
		CreateDirectory (path.c_str(), NULL);

		return path + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME;
	}


	void BootEncryption::RenameDeprecatedSystemLoaderBackup ()
	{
		WCHAR pathBuf[MAX_PATH];

		if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA, NULL, 0, pathBuf)))
		{
			wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME) + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME_LEGACY;

			if (FileExists (path.c_str()) && !FileExists (GetSystemLoaderBackupPath().c_str()))
				throw_sys_if (_wrename (path.c_str(), GetSystemLoaderBackupPath().c_str()) != 0);
		}
	}


#ifndef SETUP
	void BootEncryption::CreateRescueIsoImage (bool initialSetup, const wstring &isoImagePath)
	{
		BootEncryptionStatus encStatus = GetStatus();
		if (encStatus.SetupInProgress)
			throw ParameterIncorrect (SRC_POS);
		BOOL bIsGPT = GetSystemDriveConfiguration().SystemPartition.IsGPT;
		if (bIsGPT)
		{
			// create EFI disk structure
			DWORD sizeDcsBoot;
			byte *dcsBootImg = MapResource(L"BIN", IDR_EFI_DCSBOOT, &sizeDcsBoot);
			if (!dcsBootImg)
				throw ParameterIncorrect (SRC_POS);
			DWORD sizeDcsInt;
			byte *dcsIntImg = MapResource(L"BIN", IDR_EFI_DCSINT, &sizeDcsInt);
			if (!dcsIntImg)
				throw ParameterIncorrect (SRC_POS);
			DWORD sizeDcsCfg;
			byte *dcsCfgImg = MapResource(L"BIN", IDR_EFI_DCSCFG, &sizeDcsCfg);
			if (!dcsCfgImg)
				throw ParameterIncorrect (SRC_POS);
			DWORD sizeLegacySpeaker;
			byte *LegacySpeakerImg = MapResource(L"BIN", IDR_EFI_LEGACYSPEAKER, &sizeLegacySpeaker);
			if (!LegacySpeakerImg)
				throw ParameterIncorrect (SRC_POS);
			DWORD sizeBootMenuLocker;
			byte *BootMenuLockerImg = MapResource(L"BIN", IDR_EFI_DCSBML, &sizeBootMenuLocker);
			if (!BootMenuLockerImg)
				throw ParameterIncorrect (SRC_POS);
			DWORD sizeDcsRescue;
			byte *DcsRescueImg = MapResource(L"BIN", IDR_EFI_DCSRE, &sizeDcsRescue);
			if (!DcsRescueImg)
				throw ParameterIncorrect (SRC_POS);

			unsigned int maxRescueZipSize = 4 * 1024 * 1024;
			ZRESULT res;
			HZIP hz = CreateZip (0, maxRescueZipSize, ZIP_MEMORY);
			if (!hz)
				throw ParameterIncorrect (SRC_POS);

			finally_do_arg (HZIP, hz, { CloseZip (finally_arg); });

			if (ZR_OK != ZipAdd (hz, L"EFI/Boot/bootx64.efi", DcsRescueImg, sizeDcsRescue, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);
			if (ZR_OK !=ZipAdd (hz, L"EFI/VeraCrypt/DcsBml.dcs", BootMenuLockerImg, sizeBootMenuLocker, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);
			if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/DcsBoot.efi", dcsBootImg, sizeDcsBoot, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);
			if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/DcsCfg.dcs", dcsCfgImg, sizeDcsCfg, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);
			if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/DcsInt.dcs", dcsIntImg, sizeDcsInt, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);
			if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/LegacySpeaker.dcs", LegacySpeakerImg, sizeLegacySpeaker, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);

			Buffer volHeader(TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);

			// Volume header
			if (initialSetup)
			{
				if (!RescueVolumeHeaderValid)
					throw ParameterIncorrect (SRC_POS);

				memcpy (volHeader.Ptr (), RescueVolumeHeader, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
			}
			else
			{
				Device bootDevice (GetSystemDriveConfiguration().DevicePath, true);
				bootDevice.CheckOpened (SRC_POS);
				bootDevice.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
				bootDevice.Read (volHeader.Ptr (), TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
			}

			if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/svh_bak", volHeader.Ptr (), TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE, ZIP_MEMORY))
				throw ParameterIncorrect (SRC_POS);

			// Original system loader
			res = ZR_WRITE;
			try
			{
				DWORD fileSize = 0;
				File sysBakFile (GetSystemLoaderBackupPath(), true);
				sysBakFile.CheckOpened (SRC_POS);
				sysBakFile.GetFileSize(fileSize);
				Buffer fileBuf ((DWORD) fileSize);
				DWORD sizeLoader = sysBakFile.Read (fileBuf.Ptr (), fileSize);
				res = ZipAdd (hz, L"EFI/Boot/original_bootx64.vc_backup", fileBuf.Ptr (), sizeLoader, ZIP_MEMORY);				
			}
			catch (Exception &e)
			{
				e.Show (ParentWindow);
				Warning ("SYS_LOADER_UNAVAILABLE_FOR_RESCUE_DISK", ParentWindow);
			}

			if (res != ZR_OK)
				throw ParameterIncorrect (SRC_POS);			

			EfiBootConf conf;
			wstring dcsPropFileName = GetTempPathString() + L"_dcsproprescue";
			finally_do_arg (wstring, dcsPropFileName, { DeleteFileW (finally_arg.c_str()); });
			if (conf.Save(dcsPropFileName.c_str(), ParentWindow))
			{
				DWORD fileSize = 0;
				File propFile (dcsPropFileName, true, false);
				propFile.CheckOpened (SRC_POS);
				propFile.GetFileSize(fileSize);
				Buffer propBuf (fileSize);
				DWORD sizeDcsProp = propFile.Read (propBuf.Ptr (), fileSize);

				if (ZR_OK != ZipAdd (hz, L"EFI/VeraCrypt/DcsProp", propBuf.Ptr (), sizeDcsProp, ZIP_MEMORY))
					throw ParameterIncorrect (SRC_POS);
			}
			else
				throw ParameterIncorrect (SRC_POS);

			void* pZipContent = NULL;
			unsigned long ulZipSize = 0;
			if (ZR_OK != ZipGetMemory (hz, &pZipContent, &ulZipSize))
				throw ParameterIncorrect (SRC_POS);
			
			RescueZipData = new byte[ulZipSize];
			if (!RescueZipData)
				throw bad_alloc();
			memcpy (RescueZipData, pZipContent, ulZipSize);
			RescueZipSize = ulZipSize;

			if (!isoImagePath.empty())
			{
				File isoFile (isoImagePath, false, true);
				isoFile.Write (RescueZipData, RescueZipSize);
			}
		}
		else
		{
			Buffer imageBuf (RescueIsoImageSize);
		
			byte *image = imageBuf.Ptr();
			memset (image, 0, RescueIsoImageSize);

			// Primary volume descriptor
			const char* szPrimVolDesc = "\001CD001\001";
			const char* szPrimVolLabel = "VeraCrypt Rescue Disk           ";
			memcpy (image + 0x8000, szPrimVolDesc, strlen(szPrimVolDesc) + 1);
			memcpy (image + 0x7fff + 41, szPrimVolLabel, strlen(szPrimVolLabel) + 1);
			*(uint32 *) (image + 0x7fff + 81) = RescueIsoImageSize / 2048;
			*(uint32 *) (image + 0x7fff + 85) = BE32 (RescueIsoImageSize / 2048);
			image[0x7fff + 121] = 1;
			image[0x7fff + 124] = 1;
			image[0x7fff + 125] = 1;
			image[0x7fff + 128] = 1;
			image[0x7fff + 130] = 8;
			image[0x7fff + 131] = 8;

			image[0x7fff + 133] = 10;
			image[0x7fff + 140] = 10;
			image[0x7fff + 141] = 0x14;
			image[0x7fff + 157] = 0x22;
			image[0x7fff + 159] = 0x18;

			// Boot record volume descriptor
			const char* szBootRecDesc = "CD001\001EL TORITO SPECIFICATION";
			memcpy (image + 0x8801, szBootRecDesc, strlen(szBootRecDesc) + 1);
			image[0x8800 + 0x47] = 0x19;

			// Volume descriptor set terminator
			const char* szVolDescTerm = "\377CD001\001";
			memcpy (image + 0x9000, szVolDescTerm, strlen(szVolDescTerm) + 1);

			// Path table
			image[0xA000 + 0] = 1;
			image[0xA000 + 2] = 0x18;
			image[0xA000 + 6] = 1;

			// Root directory
			image[0xc000 + 0] = 0x22;
			image[0xc000 + 2] = 0x18;
			image[0xc000 + 9] = 0x18;
			image[0xc000 + 11] = 0x08;
			image[0xc000 + 16] = 0x08;
			image[0xc000 + 25] = 0x02;
			image[0xc000 + 28] = 0x01;
			image[0xc000 + 31] = 0x01;
			image[0xc000 + 32] = 0x01;
			image[0xc000 + 34] = 0x22;
			image[0xc000 + 36] = 0x18;
			image[0xc000 + 43] = 0x18;
			image[0xc000 + 45] = 0x08;
			image[0xc000 + 50] = 0x08;
			image[0xc000 + 59] = 0x02;
			image[0xc000 + 62] = 0x01;
			*(uint32 *) (image + 0xc000 + 65) = 0x010101;

			// Validation entry
			image[0xc800] = 1;
			int offset = 0xc800 + 0x1c;
			image[offset++] = 0xaa;
			image[offset++] = 0x55;
			image[offset++] = 0x55;
			image[offset] = 0xaa;

			// Initial entry
			offset = 0xc820;
			image[offset++] = 0x88;
			image[offset++] = 2;
			image[0xc820 + 6] = 1;
			image[0xc820 + 8] = TC_CD_BOOT_LOADER_SECTOR;

			// TrueCrypt Boot Loader
			CreateBootLoaderInMemory (image + TC_CD_BOOTSECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE, true);

			// Volume header
			if (initialSetup)
			{
				if (!RescueVolumeHeaderValid)
					throw ParameterIncorrect (SRC_POS);

				memcpy (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, RescueVolumeHeader, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
			}
			else
			{
				Device bootDevice (GetSystemDriveConfiguration().DevicePath, true);
				bootDevice.CheckOpened (SRC_POS);
				bootDevice.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
				bootDevice.Read (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
			}

			// Original system loader
			try
			{
				File sysBakFile (GetSystemLoaderBackupPath(), true);
				sysBakFile.CheckOpened (SRC_POS);
				sysBakFile.Read (image + TC_CD_BOOTSECTOR_OFFSET + TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE);
			
				image[TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER;
			}
			catch (Exception &e)
			{
				e.Show (ParentWindow);
				Warning ("SYS_LOADER_UNAVAILABLE_FOR_RESCUE_DISK", ParentWindow);
			}
		
			// Boot loader backup
			CreateBootLoaderInMemory (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE, false);

			RescueIsoImage = new byte[RescueIsoImageSize];
			if (!RescueIsoImage)
				throw bad_alloc();
			memcpy (RescueIsoImage, image, RescueIsoImageSize);

			if (!isoImagePath.empty())
			{
				File isoFile (isoImagePath, false, true);
				isoFile.Write (image, RescueIsoImageSize);
			}
		}
	}
#endif


	bool BootEncryption::IsCDRecorderPresent ()
	{
		ICDBurn* pICDBurn;
		BOOL bHasRecorder = FALSE;

		if (SUCCEEDED( CoCreateInstance (CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn)))
		{
			if (pICDBurn->HasRecordableDrive (&bHasRecorder) != S_OK)
			{
				bHasRecorder = FALSE;
			}
			pICDBurn->Release();
		}
		return bHasRecorder? true : false;
	}


	bool BootEncryption::VerifyRescueDisk ()
	{
		BOOL bIsGPT = GetSystemDriveConfiguration().SystemPartition.IsGPT;
		if ((bIsGPT && !RescueZipData) || (!bIsGPT && !RescueIsoImage))
			throw ParameterIncorrect (SRC_POS);

		if (bIsGPT)
		{
			const wchar_t* efiFiles[] = {
				L"EFI/Boot/bootx64.efi",
				L"EFI/VeraCrypt/DcsBml.dcs",
				L"EFI/VeraCrypt/DcsBoot.efi",
				L"EFI/VeraCrypt/DcsCfg.dcs",
				L"EFI/VeraCrypt/DcsInt.dcs",
				L"EFI/VeraCrypt/LegacySpeaker.dcs",
				L"EFI/VeraCrypt/svh_bak",
				L"EFI/Boot/original_bootx64.vc_backup"
			};

			ZRESULT res;
			HZIP hz = OpenZip(RescueZipData, RescueZipSize, ZIP_MEMORY);
			if (!hz)
				throw ParameterIncorrect (SRC_POS);
			finally_do_arg (HZIP, hz, { CloseZip (finally_arg); });

			for (WCHAR drive = L'Z'; drive >= L'C'; --drive)
			{
				try
				{
					WCHAR rootPath[4] = { drive, L':', L'\\', 0};
					UINT driveType = GetDriveType (rootPath);
					if (DRIVE_REMOVABLE == driveType)
					{
						// check if it is FAT/FAT32
						WCHAR szNameBuffer[TC_MAX_PATH];
						if (GetVolumeInformationW (rootPath, NULL, 0, NULL, NULL, NULL, szNameBuffer, ARRAYSIZE(szNameBuffer))
								&& !wcsncmp (szNameBuffer, L"FAT", 3))
						{
							int index, i;
							ZIPENTRYW ze;							
							for (i = 0; i < ARRAYSIZE(efiFiles); i++)
							{
								bool bMatch = false;
								res = FindZipItemW (hz, efiFiles[i], true, &index, &ze);
								if ((res == ZR_OK) && (index >= 0))
								{
									// check that the file exists on the disk and that it has the same content
									StringCbCopyW (szNameBuffer, sizeof (szNameBuffer), rootPath);
									StringCbCatW (szNameBuffer, sizeof (szNameBuffer), efiFiles[i]);

									try
									{
										DWORD dwSize = 0;
										File diskFile (szNameBuffer, true);
										diskFile.CheckOpened (SRC_POS);
										diskFile.GetFileSize (dwSize);
										if (dwSize == (DWORD) ze.unc_size)
										{
											Buffer fileBuf (dwSize);
											if (dwSize == diskFile.Read (fileBuf.Ptr (), dwSize))
											{
												Buffer efiBuf (dwSize);
												res = UnzipItem (hz, ze.index, efiBuf.Ptr (), dwSize, ZIP_MEMORY);
												if (res == ZR_OK)
												{
													bMatch = (memcmp (efiBuf.Ptr(), fileBuf.Ptr(), dwSize) == 0);
												}
											}
										}										
									}
									catch (...)
									{
									}

								}
								else
								{
									// entry not found in our Rescue ZIP image. Skip it.
									bMatch = true;
								}

								if (!bMatch)
									break;
							}

							if (i == ARRAYSIZE(efiFiles))
							{
								// All entries processed
								return true;
							}
						}
					}
				}
				catch (...) { }
			}
		}
		else
		{
			size_t verifiedSectorCount = (TC_CD_BOOTSECTOR_OFFSET + TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET + TC_BOOT_LOADER_AREA_SIZE) / 2048;
			Buffer buffer ((verifiedSectorCount + 1) * 2048);
			for (WCHAR drive = L'Z'; drive >= L'C'; --drive)
			{
				try
				{
					WCHAR rootPath[4] = { drive, L':', L'\\', 0};
					UINT driveType = GetDriveType (rootPath);
					// check that it is a CD/DVD drive or a removable media in case a bootable
					// USB key was created from the rescue disk ISO file
					if ((DRIVE_CDROM == driveType) || (DRIVE_REMOVABLE == driveType)) 
					{
						rootPath[2] = 0; // remove trailing backslash

						Device driveDevice (rootPath, true);
						driveDevice.CheckOpened (SRC_POS);

						DWORD bytesRead = driveDevice.Read (buffer.Ptr(), (DWORD) buffer.Size());
						if (bytesRead != buffer.Size())
							continue;

						if (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0)
							return true;
					}
				}
				catch (...) { }
			}
		}

		return false;
	}

	bool BootEncryption::VerifyRescueDiskImage (const wchar_t* imageFile)
	{
		BOOL bIsGPT = GetSystemDriveConfiguration().SystemPartition.IsGPT;
		if ((bIsGPT && !RescueZipData) || (!bIsGPT && !RescueIsoImage))
			throw ParameterIncorrect (SRC_POS);

		if (bIsGPT)
		{
			try
			{
				DWORD dwSize = 0;
				File rescueFile (imageFile, true);
				rescueFile.CheckOpened (SRC_POS);
				rescueFile.GetFileSize (dwSize);
				Buffer rescueData (dwSize);

				if (dwSize == rescueFile.Read (rescueData.Ptr (), dwSize))
				{
					ZRESULT res;
					HZIP hzFile = OpenZip(rescueData.Ptr (), dwSize, ZIP_MEMORY);
					if (hzFile)
					{
						finally_do_arg (HZIP, hzFile, { CloseZip (finally_arg); });
						HZIP hzMem = OpenZip(RescueZipData, RescueZipSize, ZIP_MEMORY);
						if (hzMem)
						{
							finally_do_arg (HZIP, hzMem, { CloseZip (finally_arg); });
							const wchar_t* efiFiles[] = {
								L"EFI/Boot/bootx64.efi",
								L"EFI/VeraCrypt/DcsBml.dcs",
								L"EFI/VeraCrypt/DcsBoot.efi",
								L"EFI/VeraCrypt/DcsCfg.dcs",
								L"EFI/VeraCrypt/DcsInt.dcs",
								L"EFI/VeraCrypt/LegacySpeaker.dcs",
								L"EFI/VeraCrypt/svh_bak",
								L"EFI/Boot/original_bootx64.vc_backup"
							};

							int index, i;
							ZIPENTRYW zeFile, zeMem;							
							for (i = 0; i < ARRAYSIZE(efiFiles); i++)
							{
								bool bMatch = false;
								res = FindZipItemW (hzMem, efiFiles[i], true, &index, &zeMem);
								if ((res == ZR_OK) && (index >= 0))
								{
									res = FindZipItemW (hzFile, efiFiles[i], true, &index, &zeFile);
									if ((res == ZR_OK) && (index >= 0) && (zeMem.unc_size == zeFile.unc_size))
									{
										Buffer fileBuf (zeFile.unc_size);
										Buffer memBuf (zeFile.unc_size);

										res = UnzipItem (hzMem, zeMem.index, memBuf.Ptr (), zeMem.unc_size, ZIP_MEMORY);
										if (res == ZR_OK)
										{
											res = UnzipItem (hzFile, zeFile.index, fileBuf.Ptr (), zeFile.unc_size, ZIP_MEMORY);
											if (res == ZR_OK)
											{
												bMatch = (memcmp (memBuf.Ptr (), fileBuf.Ptr (), zeMem.unc_size) == 0);
											}
										}
									}

								}
								else
								{
									// entry not found in our internal Rescue ZIP image. Skip it.
									bMatch = true;
								}

								if (!bMatch)
									break;
							}

							if (i == ARRAYSIZE(efiFiles))
							{
								// All entries processed
								return true;
							}


						}
					}
				}
			}
			catch (...) { }
		}
		else
		{
			try
			{
				File rescueFile (imageFile, true);
				rescueFile.CheckOpened (SRC_POS);
				size_t verifiedSectorCount = (TC_CD_BOOTSECTOR_OFFSET + TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET + TC_BOOT_LOADER_AREA_SIZE) / 2048;
				Buffer buffer ((verifiedSectorCount + 1) * 2048);

				DWORD bytesRead = rescueFile.Read (buffer.Ptr(), (DWORD) buffer.Size());
				if (	(bytesRead == buffer.Size()) 
					&& (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0)
					)
				{
					return true;
				}
			}
			catch (...) { }
		}

		return false;
	}


#ifndef SETUP

	void BootEncryption::CreateVolumeHeader (uint64 volumeSize, uint64 encryptedAreaStart, Password *password, int ea, int mode, int pkcs5, int pim)
	{
		PCRYPTO_INFO cryptoInfo = NULL;

		if (!IsRandomNumberGeneratorStarted())
			throw ParameterIncorrect (SRC_POS);

		throw_sys_if (CreateVolumeHeaderInMemory (ParentWindow, TRUE, (char *) VolumeHeader, ea, mode, password, pkcs5, pim, NULL, &cryptoInfo,
			volumeSize, 0, encryptedAreaStart, 0, TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION, TC_HEADER_FLAG_ENCRYPTED_SYSTEM, TC_SECTOR_SIZE_BIOS, FALSE) != 0);

		finally_do_arg (PCRYPTO_INFO*, &cryptoInfo, { crypto_close (*finally_arg); });

		// Initial rescue disk assumes encryption of the drive has been completed (EncryptedAreaLength == volumeSize)
		memcpy (RescueVolumeHeader, VolumeHeader, sizeof (RescueVolumeHeader));
		if (0 != ReadVolumeHeader (TRUE, (char *) RescueVolumeHeader, password, pkcs5, pim, FALSE, NULL, cryptoInfo))
			throw ParameterIncorrect (SRC_POS);

		DecryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo);

		if (GetHeaderField32 (RescueVolumeHeader, TC_HEADER_OFFSET_MAGIC) != 0x56455241)
			throw ParameterIncorrect (SRC_POS);

		byte *fieldPos = RescueVolumeHeader + TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH;
		mputInt64 (fieldPos, volumeSize);

		// CRC of the header fields
		uint32 crc = GetCrc32 (RescueVolumeHeader + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
		fieldPos = RescueVolumeHeader + TC_HEADER_OFFSET_HEADER_CRC;
		mputLong (fieldPos, crc);

		EncryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo);

		VolumeHeaderValid = true;
		RescueVolumeHeaderValid = true;
	}


	void BootEncryption::InstallVolumeHeader ()
	{
		if (!VolumeHeaderValid)
			throw ParameterIncorrect (SRC_POS);

		Device device (GetSystemDriveConfiguration().DevicePath);
		device.CheckOpened (SRC_POS);

		device.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
		device.Write ((byte *) VolumeHeader, sizeof (VolumeHeader));
	}


	// For synchronous operations use AbortSetupWait()
	void BootEncryption::AbortSetup ()
	{
		CallDriver (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP);
	}


	// For asynchronous operations use AbortSetup()
	void BootEncryption::AbortSetupWait ()
	{
		CallDriver (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP);

		BootEncryptionStatus encStatus = GetStatus();

		while (encStatus.SetupInProgress)
		{
			Sleep (TC_ABORT_TRANSFORM_WAIT_INTERVAL);
			encStatus = GetStatus();
		}
	}


#define VC_EFI_BOOTLOADER_NAME	L"DcsBoot"

	void BootEncryption::BackupSystemLoader ()
	{
		if (GetSystemDriveConfiguration().SystemPartition.IsGPT)
		{
			if (!IsAdmin()) {
				if (IsUacSupported())
				{
					Elevator::BackupEfiSystemLoader ();
					return;
				}
				else
				{
					Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", ParentWindow);
				}
			}
			unsigned __int64 loaderSize = 0;

			finally_do ({ EfiBootInst.DismountBootPartition(); });

			EfiBootInst.MountBootPartition(0);			

			EfiBootInst.GetFileSize(L"\\EFI\\Boot\\bootx64.efi", loaderSize);

			std::vector<byte> bootLoaderBuf ((size_t) loaderSize);

			EfiBootInst.ReadFile(L"\\EFI\\Boot\\bootx64.efi", &bootLoaderBuf[0], (DWORD) loaderSize);

			// Prevent VeraCrypt EFI loader from being backed up
			for (size_t i = 0; i < (size_t) loaderSize - (wcslen (VC_EFI_BOOTLOADER_NAME) * 2); ++i)
			{
				if (memcmp (&bootLoaderBuf[i], VC_EFI_BOOTLOADER_NAME, wcslen (VC_EFI_BOOTLOADER_NAME) * 2) == 0)
				{
					if (AskWarnNoYes ("TC_BOOT_LOADER_ALREADY_INSTALLED", ParentWindow) == IDNO)
						throw UserAbort (SRC_POS);
					return;
				}
			}

			EfiBootInst.CopyFile(L"\\EFI\\Boot\\bootx64.efi", GetSystemLoaderBackupPath().c_str());
			EfiBootInst.CopyFile(L"\\EFI\\Boot\\bootx64.efi", L"\\EFI\\Boot\\original_bootx64.vc_backup");
		}
		else
		{
			Device device (GetSystemDriveConfiguration().DevicePath, true);
			device.CheckOpened (SRC_POS);
			byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS];

			device.SeekAt (0);
			device.Read (bootLoaderBuf, sizeof (bootLoaderBuf));

			// Prevent TrueCrypt loader from being backed up
			for (size_t i = 0; i < sizeof (bootLoaderBuf) - strlen (TC_APP_NAME); ++i)
			{
				if (memcmp (bootLoaderBuf + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
				{
					if (AskWarnNoYes ("TC_BOOT_LOADER_ALREADY_INSTALLED", ParentWindow) == IDNO)
						throw UserAbort (SRC_POS);
					return;
				}
			}

			File backupFile (GetSystemLoaderBackupPath(), false, true);
			backupFile.Write (bootLoaderBuf, sizeof (bootLoaderBuf));
		}
	}


	void BootEncryption::RestoreSystemLoader ()
	{
		SystemDriveConfiguration config = GetSystemDriveConfiguration();
		if (config.SystemPartition.IsGPT) {
			if (!IsAdmin()) {
				if (IsUacSupported())
				{
					Elevator::RestoreEfiSystemLoader ();
					return;
				}
				else
				{
					Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", ParentWindow);
				}
			}

			finally_do ({ EfiBootInst.DismountBootPartition(); });

			EfiBootInst.MountBootPartition(0);			

			EfiBootInst.DeleteStartExec();
			EfiBootInst.RenameFile(L"\\EFI\\Boot\\original_bootx64.vc_backup", L"\\EFI\\Boot\\bootx64.efi", TRUE);

			EfiBootInst.DelFile(L"\\DcsBoot.efi");
			EfiBootInst.DelFile(L"\\DcsInt.efi");
			EfiBootInst.DelFile(L"\\DcsCfg.efi");
			EfiBootInst.DelFile(L"\\LegacySpeaker.efi");
			EfiBootInst.DelFile(L"\\DcsBoot");
			EfiBootInst.DelFile(L"\\DcsProp");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsBoot.efi");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsInt.dcs");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsCfg.dcs");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\LegacySpeaker.dcs");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsBml.dcs");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsBoot");
			EfiBootInst.DelFile(L"\\EFI\\VeraCrypt\\DcsProp");
		}
		else
		{
			byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS];

			File backupFile (GetSystemLoaderBackupPath(), true);
			backupFile.CheckOpened(SRC_POS);
			if (backupFile.Read (bootLoaderBuf, sizeof (bootLoaderBuf)) != sizeof (bootLoaderBuf))
				throw ParameterIncorrect (SRC_POS);

			Device device (GetSystemDriveConfiguration().DevicePath);
			device.CheckOpened (SRC_POS);

			// Preserve current partition table
			byte mbr[TC_SECTOR_SIZE_BIOS];
			device.SeekAt (0);
			device.Read (mbr, sizeof (mbr));
			memcpy (bootLoaderBuf + TC_MAX_MBR_BOOT_CODE_SIZE, mbr + TC_MAX_MBR_BOOT_CODE_SIZE, sizeof (mbr) - TC_MAX_MBR_BOOT_CODE_SIZE);

			device.SeekAt (0);
			device.Write (bootLoaderBuf, sizeof (bootLoaderBuf));
		}
	}

#endif // SETUP

	static bool CompareMultiString (const char* str1, const char* str2)
	{
		size_t l1, l2;
		if (!str1 || !str2)
			return false;
		while (true)
		{
			l1 = strlen (str1);
			l2 = strlen (str2);
			if (l1 == l2)
			{
				if (l1 == 0)
					break; // we reached the end
				if (_stricmp (str1, str2) == 0)
				{
					str1 += l1 + 1;
					str2 += l2 + 1;
				}
				else
					return false;
			}
			else
				return false;

		}

		return true;
	}

	static void AppendToMultiString (char* mszDest, DWORD dwMaxDesSize, DWORD& dwDestSize, const char* input)
	{
		// find the index of the end of the last string
		DWORD dwInputSize = (DWORD) strlen (input) + 1;
		DWORD index = dwDestSize;
		while (index > 0 && mszDest[index - 1] == 0)
			index--;

		if (dwMaxDesSize > (index + 1 + dwInputSize + 1))
		{
			if (index == 0)
			{
				StringCchCopyA ((char *) mszDest, dwMaxDesSize, input);
				mszDest [dwInputSize] = 0;
				dwDestSize = dwInputSize + 1;
			}
			else
			{
				mszDest[index] = 0;
				StringCchCopyA ((char *) &mszDest[index + 1], dwMaxDesSize - index - 1, input);
				mszDest [index + 1 + dwInputSize] = 0;
				dwDestSize = index + 1 + dwInputSize + 1;
			}
		}
	}

	// mszDest is guaranteed to be double zero terminated
	static bool RemoveFromMultiString (char* mszDest, DWORD& dwDestSize, const char* input)
	{
		bool bRet = false;
		if (mszDest && input)
		{
			DWORD offset, remainingSize = dwDestSize;
			while (*mszDest)
			{
				if (_stricmp (mszDest, input) == 0)
				{
					offset = (DWORD) strlen (input) + 1;
					memmove (mszDest, mszDest + offset, remainingSize - offset);
					dwDestSize -= offset;
					bRet = true;
					break;
				}
				offset = (DWORD) strlen (mszDest) + 1;
				mszDest += offset;
				remainingSize -= offset;
			}
		}

		return bRet;
	}

	void BootEncryption::RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid)
	{
		string filter;
		string filterReg;
		HKEY regKey;

		switch (filterType)
		{
		case DriveFilter:
		case VolumeFilter:
			filter = "veracrypt";
			filterReg = "UpperFilters";
			regKey = OpenDeviceClassRegKey (deviceClassGuid);
			throw_sys_if (regKey == INVALID_HANDLE_VALUE);

			break;

		case DumpFilter:
			if (!IsOSAtLeast (WIN_VISTA))
				return;

			filter = "veracrypt.sys";
			filterReg = "DumpFilters";
			SetLastError (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\CrashControl", 0, KEY_READ | KEY_WRITE, &regKey));
			throw_sys_if (GetLastError() != ERROR_SUCCESS);

			break;

		default:
			throw ParameterIncorrect (SRC_POS);
		}

		finally_do_arg (HKEY, regKey, { RegCloseKey (finally_arg); });

		if (registerFilter)
		{
			if (filterType != DumpFilter)
			{
				// Register class filter below all other filters in the stack

				size_t strSize = filter.size() + 1;
				byte regKeyBuf[65536];
				DWORD size = (DWORD) (sizeof (regKeyBuf) - strSize);

				// SetupInstallFromInfSection() does not support prepending of values so we have to modify the registry directly
				StringCchCopyA ((char *) regKeyBuf, ARRAYSIZE(regKeyBuf), filter.c_str());

				if (RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, regKeyBuf + strSize, &size) != ERROR_SUCCESS)
					size = 1;

				SetLastError (RegSetValueExA (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, regKeyBuf, (DWORD) strSize + size));
				throw_sys_if (GetLastError() != ERROR_SUCCESS);
			}
			else
			{
				// workaround rare SetupInstallFromInfSection which overwrite value instead of appending new value
				// read initial value
				DWORD strSize = (DWORD) filter.size() + 1, expectedSize;
				Buffer expectedRegKeyBuf(65536), outputRegKeyBuf(65536);
				byte* pbExpectedRegKeyBuf = expectedRegKeyBuf.Ptr ();
				byte* pbOutputRegKeyBuf = outputRegKeyBuf.Ptr ();
				DWORD initialSize = (DWORD) (expectedRegKeyBuf.Size() - strSize - 2);				

				if (RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, pbExpectedRegKeyBuf, &initialSize) != ERROR_SUCCESS)
				{
					StringCchCopyA ((char *) pbExpectedRegKeyBuf, expectedRegKeyBuf.Size(), filter.c_str());
					pbExpectedRegKeyBuf [strSize] = 0;
					expectedSize = strSize + 1;
				}
				else
				{
					expectedSize = initialSize;
					AppendToMultiString ((char *) pbExpectedRegKeyBuf, (DWORD) expectedRegKeyBuf.Size(), expectedSize, filter.c_str());
				}

				RegisterDriverInf (registerFilter, filter, filterReg, ParentWindow, regKey);

				// check if operation successful
				initialSize = (DWORD) outputRegKeyBuf.Size() - 2;
				if (RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, pbOutputRegKeyBuf, &initialSize) != ERROR_SUCCESS)
				{
					pbOutputRegKeyBuf [0] = 0;
					pbOutputRegKeyBuf [1] = 0;
				}
				else
				{
					// append two \0 at the end if they are missing
					if (pbOutputRegKeyBuf [initialSize - 1] != 0)
					{
						pbOutputRegKeyBuf [initialSize] = 0;
						pbOutputRegKeyBuf [initialSize + 1] = 0;
					}
					else if (pbOutputRegKeyBuf [initialSize - 2] != 0)
					{
						pbOutputRegKeyBuf [initialSize] = 0;
					}
				}

				if (!CompareMultiString ((char *) pbExpectedRegKeyBuf, (char *) pbOutputRegKeyBuf))
				{
					// Set value manually
					SetLastError (RegSetValueExA (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, pbExpectedRegKeyBuf, expectedSize));
					throw_sys_if (GetLastError() != ERROR_SUCCESS);
				}
			}
		}
		else
		{
			RegisterDriverInf (registerFilter, filter, filterReg, ParentWindow, regKey);

			// remove value in case it was not done properly
			Buffer regKeyBuf(65536);
			byte* pbRegKeyBuf = regKeyBuf.Ptr ();

			DWORD initialSize = (DWORD) regKeyBuf.Size() - 2;				

			if (		(RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, pbRegKeyBuf, &initialSize) == ERROR_SUCCESS)
					&& (initialSize >= ((DWORD) filter.size()))
				)
			{
				// append two \0 at the end if they are missing
				if (pbRegKeyBuf [initialSize - 1] != 0)
				{
					pbRegKeyBuf [initialSize] = 0;
					pbRegKeyBuf [initialSize + 1] = 0;
					initialSize += 2;
				}
				else if (pbRegKeyBuf [initialSize - 2] != 0)
				{
					pbRegKeyBuf [initialSize] = 0;
					initialSize ++;
				}

				if (RemoveFromMultiString ((char*) pbRegKeyBuf, initialSize, filter.c_str()))
				{
					// Set value manually
					SetLastError (RegSetValueExA (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, pbRegKeyBuf, initialSize));
					throw_sys_if (GetLastError() != ERROR_SUCCESS);
				}
			}
		}
	}

	void BootEncryption::RegisterFilterDriver (bool registerDriver, FilterType filterType)
	{
		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::RegisterFilterDriver (registerDriver, filterType);
			return;
		}

		switch (filterType)
		{
		case DriveFilter:
			RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_DISKDRIVE);
			break;

		case VolumeFilter:
			RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_VOLUME);
			RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_FLOPPYDISK);
			break;

		case DumpFilter:
			RegisterFilter (registerDriver, filterType);
			break;

		default:
			throw ParameterIncorrect (SRC_POS);
		}
	}

	void BootEncryption::RegisterSystemFavoritesService (BOOL registerService, BOOL noFileHandling)
	{
		SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
		throw_sys_if (!scm);
		finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); });

		wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false);
		wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true);

		if (registerService)
		{
			try
			{
				RegisterSystemFavoritesService (FALSE, noFileHandling);
			}
			catch (...) { }

			if (!noFileHandling)
			{
				wchar_t appPath[TC_MAX_PATH];
				throw_sys_if (!GetModuleFileName (NULL, appPath, ARRAYSIZE (appPath)));

				throw_sys_if (!CopyFile (appPath, servicePath.c_str(), FALSE));
			}

			SC_HANDLE service = CreateService (scm,
				TC_SYSTEM_FAVORITES_SERVICE_NAME,
				_T(TC_APP_NAME) L" System Favorites",
				SERVICE_ALL_ACCESS,
				SERVICE_WIN32_OWN_PROCESS,
				SERVICE_AUTO_START,
				SERVICE_ERROR_NORMAL,
				(wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(),
				TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP,
				NULL,
				NULL,
				NULL,
				NULL);

			throw_sys_if (!service);

			SERVICE_DESCRIPTION description;
			description.lpDescription = L"Mounts VeraCrypt system favorite volumes.";
			ChangeServiceConfig2 (service, SERVICE_CONFIG_DESCRIPTION, &description);

			CloseServiceHandle (service);

			try
			{
				WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE);
				WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE);

				SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, true);
			}
			catch (...)
			{
				try
				{
					RegisterSystemFavoritesService (FALSE, noFileHandling);
				}
				catch (...) { }

				throw;
			}
		}
		else
		{
			SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, false);

			DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal", TC_SYSTEM_FAVORITES_SERVICE_NAME);
			DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network", TC_SYSTEM_FAVORITES_SERVICE_NAME);

			SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS);
			throw_sys_if (!service);

			throw_sys_if (!DeleteService (service));
			CloseServiceHandle (service);

			if (!noFileHandling)
			{
				DeleteFile (servicePath.c_str());
				if (serviceLegacyPath != servicePath)
					DeleteFile (serviceLegacyPath.c_str());
			}
		}
	}

	void BootEncryption::UpdateSystemFavoritesService ()
	{
		SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
		throw_sys_if (!scm);

		finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); });

		wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false);

		// check if service exists
		SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS);
		if (service)
		{
			finally_do_arg (SC_HANDLE, service, { CloseServiceHandle (finally_arg); });
			// ensure that its parameters are correct
			throw_sys_if (!ChangeServiceConfig (service,
				SERVICE_WIN32_OWN_PROCESS,
				SERVICE_AUTO_START,
				SERVICE_ERROR_NORMAL,
				(wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(),
				TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP,
				NULL,
				NULL,
				NULL,
				NULL,
				_T(TC_APP_NAME) L" System Favorites"));

		}
		else
		{
			RegisterSystemFavoritesService (TRUE, TRUE);
		}
	}

	void BootEncryption::SetDriverConfigurationFlag (uint32 flag, bool state)
	{
		DWORD configMap = ReadDriverConfigurationFlags();

		if (state)
			configMap |= flag;
		else
			configMap &= ~flag;
#ifdef SETUP
		WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap);
#else
		WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap);
#endif
	}

#ifndef SETUP

	void BootEncryption::RegisterSystemFavoritesService (BOOL registerService)
	{
		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::RegisterSystemFavoritesService (registerService);
			return;
		}

		RegisterSystemFavoritesService (registerService, FALSE);
	}

	void BootEncryption::GetEfiBootDeviceNumber (PSTORAGE_DEVICE_NUMBER pSdn)
	{
		SystemDriveConfiguration config = GetSystemDriveConfiguration ();
		if (config.SystemPartition.IsGPT && pSdn)
		{
			if (!IsAdmin() && IsUacSupported())
			{
				Elevator::GetEfiBootDeviceNumber (pSdn);
			}
			else
			{
				finally_do ({ EfiBootInst.DismountBootPartition(); });
				EfiBootInst.MountBootPartition(0);		
				memcpy (pSdn, EfiBootInst.GetStorageDeviceNumber(), sizeof (STORAGE_DEVICE_NUMBER));
			}
		}
		else
		{
			SetLastError (ERROR_INVALID_PARAMETER);
			throw SystemException (SRC_POS);
		}
	}

	void BootEncryption::CheckRequirements ()
	{
		if (nCurrentOS == WIN_2000)
			throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_CURRENT_OS", SRC_POS);
 
		if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1)
			throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_VISTA_SP0", SRC_POS);

		if (IsNonInstallMode())
			throw ErrorException ("FEATURE_REQUIRES_INSTALLATION", SRC_POS);

		SystemDriveConfiguration config = GetSystemDriveConfiguration ();

		if (config.SystemPartition.IsGPT && !Is64BitOs())
			throw ErrorException ("GPT_BOOT_DRIVE_UNSUPPORTED", SRC_POS);

		if (SystemDriveIsDynamic())
			throw ErrorException ("SYSENC_UNSUPPORTED_FOR_DYNAMIC_DISK", SRC_POS);

		if (config.InitialUnallocatedSpace < TC_BOOT_LOADER_AREA_SIZE)
			throw ErrorException ("NO_SPACE_FOR_BOOT_LOADER", SRC_POS);

		DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber);

		if (geometry.BytesPerSector != TC_SECTOR_SIZE_BIOS)
			throw ErrorException ("SYSENC_UNSUPPORTED_SECTOR_SIZE_BIOS", SRC_POS);

		bool activePartitionFound = false;
		if (config.SystemPartition.IsGPT)
		{
			STORAGE_DEVICE_NUMBER sdn;
			GetEfiBootDeviceNumber (&sdn);
			activePartitionFound = (config.DriveNumber == (int) sdn.DeviceNumber);				
		}
		else
		{
			// Determine whether there is an Active partition on the system drive
			foreach (const Partition &partition, config.Partitions)
			{
				if (partition.Info.BootIndicator)
				{
					activePartitionFound = true;
					break;
				}
			}
		}

		if (!config.SystemLoaderPresent || !activePartitionFound)
		{
			static bool confirmed = false;

			if (!confirmed && AskWarnNoYes ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR", ParentWindow) == IDNO)
				throw UserAbort (SRC_POS);

			confirmed = true;
		}
	}


	void BootEncryption::CheckRequirementsHiddenOS ()
	{
		// It is assumed that CheckRequirements() had been called (so we don't check e.g. whether it's GPT).

		// The user may have modified/added/deleted partitions since the partition table was last scanned.
		InvalidateCachedSysDriveProperties ();

		GetPartitionForHiddenOS ();
	}


	void BootEncryption::InitialSecurityChecksForHiddenOS ()
	{
		wchar_t windowsDrive = (wchar_t) towupper (GetWindowsDirectory()[0]);

		// Paging files
		bool pagingFilesOk = !IsPagingFileActive (TRUE);

		wchar_t pagingFileRegData[65536];
		DWORD pagingFileRegDataSize = sizeof (pagingFileRegData);

		if (ReadLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFileRegData, &pagingFileRegDataSize)
			&& pagingFileRegDataSize > 8)
		{
			for (size_t i = 1; i < pagingFileRegDataSize/2 - 2; ++i)
			{
				if (wmemcmp (pagingFileRegData + i, L":\\", 2) == 0 && towupper (pagingFileRegData[i - 1]) != windowsDrive)
				{
					pagingFilesOk = false;
					break;
				}
			}
		}

		if (!pagingFilesOk)
		{
			if (AskWarnYesNoString ((wchar_t *) (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) 
				+ GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION")
				+ L"\n\n\n"
				+ GetString ("RESTRICT_PAGING_FILES_TO_SYS_PARTITION")
				).c_str(), ParentWindow) == IDYES)
			{
				RestrictPagingFilesToSystemPartition();
				RestartComputer();
				AbortProcessSilent();
			}

			throw ErrorException (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) 
				+ GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS);
		}

		// User profile
		wchar_t *configPath = GetConfigPath (L"dummy");
		if (configPath && towupper (configPath[0]) != windowsDrive)
		{
			throw ErrorException (wstring (GetString ("USER_PROFILE_NOT_ON_SYS_PARTITION")) 
				+ GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS);
		}

		// Temporary files
		if (towupper (GetTempPathString()[0]) != windowsDrive)
		{
			throw ErrorException (wstring (GetString ("TEMP_NOT_ON_SYS_PARTITION")) 
				+ GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS);
		}
	}


	// This operation may take a long time when an antivirus is installed and its real-time protection enabled.
	// Therefore, if calling it without the wizard displayed, it should be called with displayWaitDialog set to true.
	void BootEncryption::Deinstall (bool displayWaitDialog)
	{
		BootEncryptionStatus encStatus = GetStatus();

		if (encStatus.DriveEncrypted || encStatus.DriveMounted)
			throw ParameterIncorrect (SRC_POS);

		SystemDriveConfiguration config = GetSystemDriveConfiguration ();

      if (!config.SystemPartition.IsGPT) {
         if (encStatus.VolumeHeaderPresent)
         {
            // Verify CRC of header salt
            Device device(config.DevicePath, true);
            device.CheckOpened(SRC_POS);
            byte header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE];

            device.SeekAt(TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
            device.Read(header, sizeof(header));

            if (encStatus.VolumeHeaderSaltCrc32 != GetCrc32((byte *)header, PKCS5_SALT_SIZE))
               throw ParameterIncorrect(SRC_POS);
         }
      }

		try
		{
			RegisterFilterDriver (false, DriveFilter);
			RegisterFilterDriver (false, VolumeFilter);
			RegisterFilterDriver (false, DumpFilter);
			SetDriverServiceStartType (SERVICE_SYSTEM_START);
		}
		catch (...)
		{
			try
			{
				RegisterBootDriver (IsHiddenSystemRunning());
			}
			catch (...) { }

			throw;
		}

		SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE);	// In case RestoreSystemLoader() fails

		try
		{
			RegisterSystemFavoritesService (false);
		}
		catch (...) { }

		try
		{
			if (displayWaitDialog)
				DisplayStaticModelessWaitDlg (ParentWindow);

			finally_do_arg (bool, displayWaitDialog, { if (finally_arg) CloseStaticModelessWaitDlg(); });

			RestoreSystemLoader ();
		}
		catch (Exception &e)
		{
			e.Show (ParentWindow);
			throw ErrorException ("SYS_LOADER_RESTORE_FAILED", SRC_POS);
		}
	}


	int BootEncryption::ChangePassword (Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg)
	{
		BootEncryptionStatus encStatus = GetStatus();

		if (encStatus.SetupInProgress || (wipePassCount <= 0))
			throw ParameterIncorrect (SRC_POS);

		SystemDriveConfiguration config = GetSystemDriveConfiguration ();

		char header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE];
		Device device (config.DevicePath);
		device.CheckOpened (SRC_POS);

		// Only one algorithm is currently supported
		if (pkcs5 != 0)
			throw ParameterIncorrect (SRC_POS);

		int64 headerOffset = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET;
		int64 backupHeaderOffset = -1;

		if (encStatus.HiddenSystem)
		{
			headerOffset = encStatus.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET;

			// Find hidden system partition
			foreach (const Partition &partition, config.Partitions)
			{
				if (partition.Info.StartingOffset.QuadPart == encStatus.HiddenSystemPartitionStart)
				{
					backupHeaderOffset = partition.Info.StartingOffset.QuadPart + partition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_SIZE;
					break;
				}
			}

			if (backupHeaderOffset == -1)
				throw ParameterIncorrect (SRC_POS);
		}

		device.SeekAt (headerOffset);
		device.Read ((byte *) header, sizeof (header));

		PCRYPTO_INFO cryptoInfo = NULL;
		
		int status = ReadVolumeHeader (!encStatus.HiddenSystem, header, oldPassword, old_pkcs5, old_pim, FALSE, &cryptoInfo, NULL);
		finally_do_arg (PCRYPTO_INFO, cryptoInfo, { if (finally_arg) crypto_close (finally_arg); });

		if (status != 0)
		{
			handleError (hwndDlg, status, SRC_POS);
			return status;
		}

		// Change the PKCS-5 PRF if requested by user
		if (pkcs5 != 0)
		{
			cryptoInfo->pkcs5 = pkcs5;
			RandSetHashFunction (pkcs5);
		}

		if (Randinit() != 0)
		{
			if (CryptoAPILastError == ERROR_SUCCESS)
				throw RandInitFailed (SRC_POS, GetLastError ());
			else
				throw CryptoApiFailed (SRC_POS, CryptoAPILastError);
		}
		finally_do ({ RandStop (FALSE); });

		/* force the display of the random enriching dialog */
		SetRandomPoolEnrichedByUserStatus (FALSE);

		NormalCursor();
		UserEnrichRandomPool (hwndDlg);
		WaitCursor();

		/* The header will be re-encrypted wipePassCount times to prevent adversaries from using 
		techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy
		to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22
		times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might
		impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the
		valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman
		recommends. During each pass we will write a valid working header. Each pass will use the same master
		key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only
		item that will be different for each pass will be the salt. This is sufficient to cause each "version"
		of the header to differ substantially and in a random manner from the versions written during the
		other passes. */

		bool headerUpdated = false;
		int result = ERR_SUCCESS;

		try
		{
			BOOL backupHeader = FALSE;
			while (TRUE)
			{
				for (int wipePass = 0; wipePass < wipePassCount; wipePass++)
				{
					PCRYPTO_INFO tmpCryptoInfo = NULL;

					status = CreateVolumeHeaderInMemory (hwndDlg, !encStatus.HiddenSystem,
						header,
						cryptoInfo->ea,
						cryptoInfo->mode,
						newPassword,
						cryptoInfo->pkcs5,
						pim,
						(char *) cryptoInfo->master_keydata,
						&tmpCryptoInfo,
						cryptoInfo->VolumeSize.Value,
						cryptoInfo->hiddenVolumeSize,
						cryptoInfo->EncryptedAreaStart.Value,
						cryptoInfo->EncryptedAreaLength.Value,
						cryptoInfo->RequiredProgramVersion,
						cryptoInfo->HeaderFlags | TC_HEADER_FLAG_ENCRYPTED_SYSTEM,
						cryptoInfo->SectorSize,
						wipePass < wipePassCount - 1);

					if (tmpCryptoInfo)
						crypto_close (tmpCryptoInfo);

					if (status != 0)
					{
						handleError (hwndDlg, status, SRC_POS);
						return status;
					}

					device.SeekAt (headerOffset);
					device.Write ((byte *) header, sizeof (header));
					headerUpdated = true;
				}

				if (!encStatus.HiddenSystem || backupHeader)
					break;

				backupHeader = TRUE;
				headerOffset = backupHeaderOffset;
			}
		}
		catch (Exception &e)
		{
			e.Show (hwndDlg);
			result = ERR_OS_ERROR;
		}

		if (headerUpdated)
		{
			bool storedPimUpdateNeeded = false;
			ReopenBootVolumeHeaderRequest reopenRequest;
			reopenRequest.VolumePassword = *newPassword;
			reopenRequest.pkcs5_prf = cryptoInfo->pkcs5;
			reopenRequest.pim = pim;
			finally_do_arg (ReopenBootVolumeHeaderRequest*, &reopenRequest, { burn (finally_arg, sizeof (*finally_arg)); });

			if (old_pim != pim)
			{
				try
				{
					// check if PIM is stored in MBR
					byte userConfig = 0;
					if (	ReadBootSectorConfig (nullptr, 0, &userConfig)
						&& (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM)
						)
					{
						storedPimUpdateNeeded = true;
					}
				}
				catch (...)
				{
				}
			}

			try
			{
				// force update of bootloader if fingerprint doesn't match or if the stored PIM changed
				if (storedPimUpdateNeeded || !CheckBootloaderFingerprint (true))
					InstallBootLoader (device, true, false, pim, cryptoInfo->pkcs5);
			}
			catch (...)
			{}

			CallDriver (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER, &reopenRequest, sizeof (reopenRequest));
		}

		return result;
	}


	void BootEncryption::CheckEncryptionSetupResult ()
	{
		CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT);
	}


	void BootEncryption::Install (bool hiddenSystem, int hashAlgo)
	{
		BootEncryptionStatus encStatus = GetStatus();
		if (encStatus.DriveMounted)
			throw ParameterIncorrect (SRC_POS);

		try
		{
			InstallBootLoader (false, hiddenSystem, -1, hashAlgo);

			if (!hiddenSystem)
				InstallVolumeHeader ();

			RegisterBootDriver (hiddenSystem);
		}
		catch (Exception &)
		{
			try
			{
				RestoreSystemLoader ();
			}
			catch (Exception &e)
			{
				e.Show (ParentWindow);
			}

			throw;
		}
	}


	void BootEncryption::PrepareHiddenOSCreation (int ea, int mode, int pkcs5)
	{
		BootEncryptionStatus encStatus = GetStatus();
		if (encStatus.DriveMounted)
			throw ParameterIncorrect (SRC_POS);

		CheckRequirements();
		BackupSystemLoader();

		SelectedEncryptionAlgorithmId = ea;
		SelectedPrfAlgorithmId = pkcs5;
	}


	void BootEncryption::PrepareInstallation (bool systemPartitionOnly, Password &password, int ea, int mode, int pkcs5, int pim, const wstring &rescueIsoImagePath)
	{
		BootEncryptionStatus encStatus = GetStatus();
		if (encStatus.DriveMounted)
			throw ParameterIncorrect (SRC_POS);

		CheckRequirements ();

		SystemDriveConfiguration config = GetSystemDriveConfiguration();

		// Some chipset drivers may prevent access to the last sector of the drive
		if (!systemPartitionOnly)
		{
			DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber);
			if ((geometry.BytesPerSector > 0) && (geometry.BytesPerSector < TC_MAX_VOLUME_SECTOR_SIZE))
			{
				Buffer sector (geometry.BytesPerSector);

				Device device (config.DevicePath);
				device.CheckOpened (SRC_POS);

				try
				{
					device.SeekAt (config.DrivePartition.Info.PartitionLength.QuadPart - geometry.BytesPerSector);
					device.Read (sector.Ptr(), (DWORD) sector.Size());
				}
				catch (SystemException &e)
				{
					if (e.ErrorCode != ERROR_CRC)
					{
						e.Show (ParentWindow);
						Error ("WHOLE_DRIVE_ENCRYPTION_PREVENTED_BY_DRIVERS", ParentWindow);
						throw UserAbort (SRC_POS);
					}
				}
			}
		}

		BackupSystemLoader ();

		uint64 volumeSize;
		uint64 encryptedAreaStart;

		if (systemPartitionOnly)
		{
			volumeSize = config.SystemPartition.Info.PartitionLength.QuadPart;
			encryptedAreaStart = config.SystemPartition.Info.StartingOffset.QuadPart;
		}
		else
		{
			volumeSize = config.DrivePartition.Info.PartitionLength.QuadPart - TC_BOOT_LOADER_AREA_SIZE;
			encryptedAreaStart = config.DrivePartition.Info.StartingOffset.QuadPart + TC_BOOT_LOADER_AREA_SIZE;
		}

		SelectedEncryptionAlgorithmId = ea;
		SelectedPrfAlgorithmId = pkcs5;
		CreateVolumeHeader (volumeSize, encryptedAreaStart, &password, ea, mode, pkcs5, pim);
		
		if (!rescueIsoImagePath.empty())
			CreateRescueIsoImage (true, rescueIsoImagePath);
	}

	bool BootEncryption::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly)
	{
		if (!IsAdmin() && IsUacSupported())
			return Elevator::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false;

		return ::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false;
	}

	void BootEncryption::RestrictPagingFilesToSystemPartition ()
	{
		wchar_t pagingFiles[128] = {0};
		StringCchCopyW (pagingFiles, ARRAYSIZE(pagingFiles), L"X:\\pagefile.sys 0 0");
		pagingFiles[0] = GetWindowsDirectory()[0];

		throw_sys_if (!WriteLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFiles, (DWORD) (wcslen (pagingFiles) + 2) * sizeof (wchar_t)));
	}

	void BootEncryption::WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value)
	{
		if (!IsAdmin() && IsUacSupported())
		{
			Elevator::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value);
			return;
		}

		throw_sys_if (!WriteLocalMachineRegistryDword (keyPath, valueName, value));
	}

	void BootEncryption::StartDecryption (BOOL discardUnreadableEncryptedSectors)
	{
		BootEncryptionStatus encStatus = GetStatus();

		if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress)
			throw ParameterIncorrect (SRC_POS);

		BootEncryptionSetupRequest request;
		ZeroMemory (&request, sizeof (request));
		
		request.SetupMode = SetupDecryption;
		request.DiscardUnreadableEncryptedSectors = discardUnreadableEncryptedSectors;

		CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0);
	}

	void BootEncryption::StartEncryption (WipeAlgorithmId wipeAlgorithm, bool zeroUnreadableSectors)
	{
		BootEncryptionStatus encStatus = GetStatus();

		if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress)
			throw ParameterIncorrect (SRC_POS);

		BootEncryptionSetupRequest request;
		ZeroMemory (&request, sizeof (request));
		
		request.SetupMode = SetupEncryption;
		request.WipeAlgorithm = wipeAlgorithm;
		request.ZeroUnreadableSectors = zeroUnreadableSectors;

		CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0);
	}

	void BootEncryption::CopyFileAdmin (const wstring &sourceFile, const wstring &destinationFile)
	{
		if (!IsAdmin())
		{
			if (!IsUacSupported())
			{
				SetLastError (ERROR_ACCESS_DENIED);
				throw SystemException(SRC_POS);
			}
			else
				Elevator::CopyFile (sourceFile, destinationFile);
		}
		else
			throw_sys_if (!::CopyFile (sourceFile.c_str(), destinationFile.c_str(), FALSE));
	}

	void BootEncryption::DeleteFileAdmin (const wstring &file)
	{
		if (!IsAdmin() && IsUacSupported())
			Elevator::DeleteFile (file);
		else
			throw_sys_if (!::DeleteFile (file.c_str()));
	}

#endif // !SETUP

	uint32 BootEncryption::ReadDriverConfigurationFlags ()
	{
		DWORD configMap;

		if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap))
			configMap = 0;

		return configMap;
	}

	void BootEncryption::WriteBootDriveSector (uint64 offset, byte *data)
	{
		WriteBootDriveSectorRequest request;
		request.Offset.QuadPart = offset;
		memcpy (request.Data, data, sizeof (request.Data));

		CallDriver (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR, &request, sizeof (request), NULL, 0);
	}

	void BootEncryption::RegisterBootDriver (bool hiddenSystem)
	{
		SetDriverServiceStartType (SERVICE_BOOT_START);

		try
		{
			RegisterFilterDriver (false, DriveFilter);
			RegisterFilterDriver (false, VolumeFilter);
			RegisterFilterDriver (false, DumpFilter);
		}
		catch (...) { }

		try
		{
			RegisterFilterDriver (true, DriveFilter);

			if (hiddenSystem)
				RegisterFilterDriver (true, VolumeFilter);

			RegisterFilterDriver (true, DumpFilter);
		}
		catch (...)
		{
			try { RegisterFilterDriver (false, DriveFilter); } catch (...) { }
			try { RegisterFilterDriver (false, VolumeFilter); } catch (...) { }
			try { RegisterFilterDriver (false, DumpFilter); } catch (...) { }
			try { SetDriverServiceStartType (SERVICE_SYSTEM_START); } catch (...) { }

			throw;
		}
	}

	bool BootEncryption::RestartComputer (void)
	{
		return (::RestartComputer() != FALSE);
	}
}