summaryrefslogtreecommitdiff
path: root/src/vm/aptca.cpp
blob: 65c334a422c98dcb44de9b4795f2fd26856f4e1a (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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//--------------------------------------------------------------------------
// aptca.h
//
// Functions for handling allow partially trusted callers assemblies
//

// 
//--------------------------------------------------------------------------


#include "common.h"
#include "aptca.h"

//
// Conditional APTCA cache implementation
//

ConditionalAptcaCache::ConditionalAptcaCache(AppDomain *pAppDomain) 
    : m_pAppDomain(pAppDomain),
      m_canonicalListIsNull(false),
      m_domainState(kDomainStateUnknown)
{
    WRAPPER_NO_CONTRACT;

    _ASSERTE(pAppDomain != NULL);
}

ConditionalAptcaCache::~ConditionalAptcaCache()
{
    WRAPPER_NO_CONTRACT;
}

void ConditionalAptcaCache::SetCachedState(PTR_PEImage pImage, ConditionalAptcaCache::State state)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pImage));
        PRECONDITION(state != kUnknown);
    }
    CONTRACTL_END;

    if (state == kNotCAptca)
    {
        pImage->SetIsNotConditionalAptca();
    }
}

ConditionalAptcaCache::State ConditionalAptcaCache::GetCachedState(PTR_PEImage pImage)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pImage));
    }
    CONTRACTL_END;

    if (!pImage->MayBeConditionalAptca())
    {
        return kNotCAptca;
    }

    return kUnknown;
}

void ConditionalAptcaCache::SetCanonicalConditionalAptcaList(LPCWSTR wszCanonicalConditionalAptcaList)
{
    WRAPPER_NO_CONTRACT;
    m_canonicalListIsNull = (wszCanonicalConditionalAptcaList == NULL);
    m_canonicalList.Set(wszCanonicalConditionalAptcaList);
}

#ifndef CROSSGEN_COMPILE
ConditionalAptcaCache::DomainState ConditionalAptcaCache::GetConditionalAptcaDomainState()
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_domainState == kDomainStateUnknown)
    {
        IApplicationSecurityDescriptor *pASD = m_pAppDomain->GetSecurityDescriptor();
        DomainState domainState = kDomainStateUnknown;

        // In the full trust case we only need to look at the conditional APTCA list in the case that the host
        // has configured one on the default domain (for instance WPF).  Otherwise, all full trust domains have
        // all conditional APTCA assemblies enabled.
        bool processFullTrustAptcaList = false;
        if (m_pAppDomain->IsCompilationDomain())
        {
            processFullTrustAptcaList = false;
        }
        else if (m_pAppDomain->IsDefaultDomain())
        {
            processFullTrustAptcaList = !m_canonicalListIsNull;
        }
        else
        {
            processFullTrustAptcaList = ConsiderFullTrustConditionalAptcaLists();
        }

        // Consider the domain to be fully trusted if it really is fully trusted, or if we're currently
        // setting the domain up, it looks like it will be fully trusted, and the AppDomainManager has
        // promised that won't change.
        bool isFullTrustDomain = !m_pAppDomain->GetSecurityDescriptor()->DomainMayContainPartialTrustCode();
        if (pASD->IsInitializationInProgress() && (m_pAppDomain->GetAppDomainManagerInitializeNewDomainFlags() & eInitializeNewDomainFlags_NoSecurityChanges))
        {
            BOOL preResolveFullTrust;
            BOOL preResolveHomogenous;
            pASD->PreResolve(&preResolveFullTrust, &preResolveHomogenous);

            isFullTrustDomain = preResolveFullTrust && preResolveHomogenous;
        }

        if (m_pAppDomain->IsCompilationDomain())
        {
            // NGEN always enables all conditional APTCA assemblies
            domainState = kAllEnabled;
        }
        else if (!isFullTrustDomain || processFullTrustAptcaList)
        {
            if (m_canonicalList.GetCount() == 0)
            {
                // A null or empty conditional APTCA list means that no assemblies are enabled in this domain
                domainState = kAllDisabled;
            }
            else
            {
                // We're in a domain that supports conditional APTCA and an interesting list is supplied.  In
                // this domain, some assemblies are enabled.
                domainState = kSomeEnabled;
            }
        }
        else
        {
            domainState = kAllEnabled;
        }

        _ASSERTE(domainState != kDomainStateUnknown);
        InterlockedCompareExchange(reinterpret_cast<volatile LONG *>(&m_domainState), domainState, kDomainStateUnknown);
    }

    return m_domainState;
}

// static
bool ConditionalAptcaCache::ConsiderFullTrustConditionalAptcaLists()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (GetAppDomain()->IsCompilationDomain())
    {
        return false;
    }

    IApplicationSecurityDescriptor *pASD = SystemDomain::System()->DefaultDomain()->GetSecurityDescriptor();
    ConditionalAptcaCache *pDefaultDomainCaptca = pASD->GetConditionalAptcaCache();

    // The only way that we use CAPTCA lists is if the host has configured the default domain to not be all
    // enabled (that is, the host has setup a CAPTCA list of any sort for the default domain)
    return pDefaultDomainCaptca->GetConditionalAptcaDomainState() != kAllEnabled;
}

// APTCA killbit list helper functions
namespace
{
    static const LPCWSTR wszAptcaRootKey = W("SOFTWARE\\Microsoft\\.NETFramework\\Policy\\APTCA");

    //--------------------------------------------------------------------------------------------------------
    //
    // The AptcaKillBitList class is responsible for holding the machine wide list of assembly name / file
    // versions which have been disabled for APTCA on the machine.
    //

    class AptcaKillBitList
    {
    private:
        ArrayList m_killBitList;

    public:
        ~AptcaKillBitList();

        bool AreAnyAssembliesKillBitted();
        bool IsAssemblyKillBitted(PEAssembly *pAssembly);
        bool IsAssemblyKillBitted(IAssemblyName *pAssemblyName, ULARGE_INTEGER fileVersion);

        static AptcaKillBitList *ReadMachineKillBitList();

    private:
        AptcaKillBitList();
        AptcaKillBitList(const AptcaKillBitList &other); // not implemented

    private:
        static const LPCWSTR wszKillBitValue;

    private:
        static bool FileVersionsAreEqual(ULARGE_INTEGER targetVersion, IAssemblyName *pKillBitAssemblyName);
    };
    const LPCWSTR AptcaKillBitList::wszKillBitValue = W("APTCA_FLAG");
    
    AptcaKillBitList::AptcaKillBitList()
    {
        LIMITED_METHOD_CONTRACT;
    }

    AptcaKillBitList::~AptcaKillBitList()
    {
        WRAPPER_NO_CONTRACT;

        // Release all of the IAssemblyName objects stored in this list
        for (DWORD i = 0; i < m_killBitList.GetCount(); ++i)
        {
            IAssemblyName *pKillBitAssemblyName = reinterpret_cast<IAssemblyName *>(m_killBitList.Get(i));
            if (pKillBitAssemblyName != NULL)
            {
                pKillBitAssemblyName->Release();
            }
        }
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine if any assemblies are on the APTCA killbit list
    //

    bool AptcaKillBitList::AreAnyAssembliesKillBitted()
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
        }
        CONTRACTL_END;

        // We don't consider the killbit for NGEN, as ngened code always assumes that APTCA is enabled.
        if (GetAppDomain()->IsCompilationDomain())
        {
            return false;
        }

        return m_killBitList.GetCount() > 0;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Compare the file versions of an assembly with the verison that is being killbitted to see if they
    // match.  For compatibility with v3.5, we assume any failure means that the versions do not match.
    //

    // static
    bool AptcaKillBitList::FileVersionsAreEqual(ULARGE_INTEGER targetVersion, IAssemblyName *pKillBitAssemblyName)
    {
        DWORD dwKillBitMajorVersion = 0;
        DWORD dwVersionSize = sizeof(dwKillBitMajorVersion);
        if (FAILED(pKillBitAssemblyName->GetProperty(ASM_NAME_FILE_MAJOR_VERSION, &dwKillBitMajorVersion, &dwVersionSize)) ||
            dwVersionSize == 0)
        {
            return false;
        }

        DWORD dwKillBitMinorVersion = 0;
        dwVersionSize = sizeof(dwKillBitMinorVersion);
        if (FAILED(pKillBitAssemblyName->GetProperty(ASM_NAME_FILE_MINOR_VERSION, &dwKillBitMinorVersion, &dwVersionSize)) ||
            dwVersionSize == 0)
        {
            return false;
        }

        DWORD dwKillBitBuildVersion = 0;
        dwVersionSize = sizeof(dwKillBitBuildVersion);
        if (FAILED(pKillBitAssemblyName->GetProperty(ASM_NAME_FILE_BUILD_NUMBER, &dwKillBitBuildVersion, &dwVersionSize)) ||
            dwVersionSize == 0)
        {
            return false;
        }

        DWORD dwKillBitRevisionVersion = 0;
        dwVersionSize = sizeof(dwKillBitRevisionVersion);
        if (FAILED(pKillBitAssemblyName->GetProperty(ASM_NAME_FILE_REVISION_NUMBER, &dwKillBitRevisionVersion, &dwVersionSize)) ||
            dwVersionSize == 0)
        {
            return false;
        }

        DWORD dwTargetMajorVersion = (targetVersion.HighPart & 0xFFFF0000) >> 16;
        DWORD dwTargetMinorVersion = targetVersion.HighPart & 0x0000FFFF;
        DWORD dwTargetBuildVersion = (targetVersion.LowPart & 0xFFFF0000) >> 16;
        DWORD dwTargetRevisionVersion = targetVersion.LowPart & 0x0000FFFF;

        return dwTargetMajorVersion == dwKillBitMajorVersion &&
               dwTargetMinorVersion == dwKillBitMinorVersion &&
               dwTargetBuildVersion == dwKillBitBuildVersion &&
               dwTargetRevisionVersion == dwKillBitRevisionVersion;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine if a specific assembly is on the killbit list
    //

    bool AptcaKillBitList::IsAssemblyKillBitted(PEAssembly *pAssembly)
    {
        STANDARD_VM_CONTRACT;

        IAssemblyName *pTargetAssemblyName = pAssembly->GetFusionAssemblyName();

        // For compat with v3.5, we use hte Win32 file version here rather than the Fusion version
        LPCWSTR pwszPath = pAssembly->GetPath().GetUnicode();
        if (pwszPath != NULL)
        {
            ULARGE_INTEGER fileVersion = { 0, 0 };
            HRESULT hr = GetFileVersion(pwszPath, &fileVersion);
            if (SUCCEEDED(hr))
            {
                return IsAssemblyKillBitted(pTargetAssemblyName, fileVersion);
            }
        }

        return false;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine if a specific assembly is on the killbit list
    //

    bool AptcaKillBitList::IsAssemblyKillBitted(IAssemblyName *pTargetAssemblyName, ULARGE_INTEGER fileVersion)
    {
        STANDARD_VM_CONTRACT;

        // If nothing is killbitted, then this assembly cannot be killbitted
        if (!AreAnyAssembliesKillBitted())
        {
            return false;
        }

        for (DWORD i = 0; i < m_killBitList.GetCount(); ++i)
        {
            IAssemblyName *pKillBitAssemblyName = reinterpret_cast<IAssemblyName *>(m_killBitList.Get(i));

            // By default, we compare all fields of the assembly's name, however if the culture was neutral,
            // we strip that out.
            DWORD dwCmpFlags = ASM_CMPF_IL_ALL;

            DWORD cbCultureSize = 0;
            SString strCulture;
            HRESULT hrCulture = pKillBitAssemblyName->GetProperty(ASM_NAME_CULTURE, NULL, &cbCultureSize);
            if (hrCulture == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
            {
                DWORD cchCulture = (cbCultureSize / sizeof(WCHAR)) - 1;
                WCHAR *wszCultureBuffer = strCulture.OpenUnicodeBuffer(cchCulture);
                hrCulture = pKillBitAssemblyName->GetProperty(ASM_NAME_CULTURE, wszCultureBuffer, &cbCultureSize);
                strCulture.CloseBuffer();
            }

            if (SUCCEEDED(hrCulture))
            {
                if (cbCultureSize == 0 || strCulture.EqualsCaseInsensitive(W("")) || strCulture.EqualsCaseInsensitive(W("neutral")))
                {
                    dwCmpFlags &= ~ASM_CMPF_CULTURE;
                }
            }

            // If the input assembly matches the kill bit assembly's name and file version, then we need to
            // kill it.
            if (pTargetAssemblyName->IsEqual(pKillBitAssemblyName, dwCmpFlags) == S_OK &&
                FileVersionsAreEqual(fileVersion, pKillBitAssemblyName))
            {
                return true;
            }
        }

        return false;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Read the machine-wide APTCA kill bit list into a kill bit list object.  For compatibility with v3.5,
    // errors during this initialization are ignored - leading to APTCA entries that may not be considered
    // for kill bitting.
    //

    // static
    AptcaKillBitList *AptcaKillBitList::ReadMachineKillBitList()
    {
        CONTRACT(AptcaKillBitList *)
        {
            STANDARD_VM_CHECK;
            POSTCONDITION(CheckPointer(RETVAL));
        }
        CONTRACT_END;

        NewHolder<AptcaKillBitList> pKillBitList(new AptcaKillBitList);

        HKEYHolder hKeyAptca;

        // Open the APTCA subkey in the registry.
        if (WszRegOpenKeyEx(HKEY_LOCAL_MACHINE, wszAptcaRootKey, 0, KEY_READ, &hKeyAptca) == ERROR_SUCCESS)
        {

            DWORD cchSubKeySize = 0;
            if (WszRegQueryInfoKey(hKeyAptca, NULL, NULL, NULL, NULL, &cchSubKeySize, NULL, NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
            {
                cchSubKeySize = MAX_PATH_FNAME;
            }
            ++cchSubKeySize;

            NewArrayHolder<WCHAR> wszSubKey(new WCHAR[cchSubKeySize]);

            DWORD dwKey = 0;
            DWORD cchWszSubKey = cchSubKeySize;
            // Assembly specific records are represented as subkeys of the key we've just opened with names
            // equal to the strong name of the assembly being kill bitted, and a value of APTCA_FLAG = 1.
            while (WszRegEnumKeyEx(hKeyAptca, dwKey, wszSubKey, &cchWszSubKey, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
            {
                ++dwKey;
                cchWszSubKey = cchSubKeySize;

                // Open the subkey: the key name is the full name of the assembly to potentially kill-bit
                HKEYHolder hSubKey;
                if (WszRegOpenKeyEx(hKeyAptca, wszSubKey, 0, KEY_READ, &hSubKey) != ERROR_SUCCESS)
                {
                    continue;
                }

                DWORD dwKillbit = 0;
                DWORD dwType = REG_DWORD;
                DWORD dwSize = sizeof(dwKillbit);

                // look for the APTCA flag
                LONG queryValue =  WszRegQueryValueEx(hSubKey,
                                                      wszKillBitValue,
                                                      NULL,
                                                      &dwType,
                                                      reinterpret_cast<LPBYTE>(&dwKillbit),
                                                      &dwSize);
                if (queryValue == ERROR_SUCCESS && dwKillbit == 1)
                {
                    // We have a strong named assembly with an APTCA killbit value set - parse the key into
                    // an assembly name, and add it to our list
                    ReleaseHolder<IAssemblyName> pKillBitAssemblyName;
                    HRESULT hrAssemblyName = CreateAssemblyNameObject(&pKillBitAssemblyName, wszSubKey, CANOF_PARSE_DISPLAY_NAME, NULL);
                    if (FAILED(hrAssemblyName))
                    {
                        continue;
                    }

                    //
                    // For compatibility with v3.5, we only accept kill bit entries which have four part
                    // assembly versions, names, and public key tokens.
                    //

                    // Verify the version first
                    bool validVersion = true;
                    for (DWORD dwVersionPartId = ASM_NAME_MAJOR_VERSION; dwVersionPartId <= ASM_NAME_REVISION_NUMBER; ++dwVersionPartId)
                    {
                        DWORD dwVersionPart;
                        DWORD cbVersionPart = sizeof(dwVersionPart);
                        HRESULT hrVersion = pKillBitAssemblyName->GetProperty(dwVersionPartId, &dwVersionPart, &cbVersionPart);
                        if (FAILED(hrVersion) || cbVersionPart == 0)
                        {
                            validVersion = false;
                        }
                    }
                    if (!validVersion)
                    {
                        continue;
                    }

                    // Make sure there is a simple name
                    DWORD cbNameSize = 0;
                    HRESULT hrName = pKillBitAssemblyName->GetProperty(ASM_NAME_NAME, NULL, &cbNameSize);
                    if (hrName != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
                    {
                        continue;
                    }

                    // Verify the killbit assembly has a public key token
                    DWORD cbPublicKeyTokenSize = 0;
                    HRESULT hrPublicKey = pKillBitAssemblyName->GetProperty(ASM_NAME_PUBLIC_KEY_TOKEN, NULL, &cbPublicKeyTokenSize);
                    if (hrPublicKey != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
                    {
                        continue;
                    }

                    // Verify the killbit assembly has either no culture or a valid culture token
                    DWORD cbCultureSize = 0;
                    HRESULT hrCulture = pKillBitAssemblyName->GetProperty(ASM_NAME_CULTURE, NULL, &cbCultureSize);
                    if (FAILED(hrCulture) && hrCulture != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
                    {
                        continue;
                    }

                    // The name checks out, so add the kill bit entry
                    LOG((LF_SECURITY,
                         LL_INFO10,
                         "APTCA killbit added for assembly '%S'.\n",
                         wszSubKey));
                    pKillBitList->m_killBitList.Append(pKillBitAssemblyName.Extract());
                }
            }
        }

        RETURN(pKillBitList.Extract());
    }

    VolatilePtr<AptcaKillBitList> g_pAptcaKillBitList(NULL);

    //--------------------------------------------------------------------------------------------------------
    //
    // Get the APTCA killbit list
    //

    AptcaKillBitList *GetKillBitList()
    {
        STANDARD_VM_CONTRACT;

        if (g_pAptcaKillBitList.Load() == NULL)
        {
            NewHolder<AptcaKillBitList> pAptcaKillBitList(AptcaKillBitList::ReadMachineKillBitList());

            LPVOID pvOldValue = InterlockedCompareExchangeT(g_pAptcaKillBitList.GetPointer(),
                                                            pAptcaKillBitList.GetValue(),
                                                            NULL);
            if (pvOldValue == NULL)
            {
                pAptcaKillBitList.SuppressRelease();
            }
        }

        _ASSERTE(g_pAptcaKillBitList.Load() != NULL);
        return g_pAptcaKillBitList.Load();
    }
}

// APTCA helper functions
namespace
{
    enum ConditionalAptcaSharingMode
    {
        kShareUnknown,
        kShareIfEnabled,        // Share an assembly only if all conditional APTCA assemblies in its closure are enabled
        kShareIfDisabled,       // Share an assembly only if all conditional APTCA assemblies in its closure are disabled
    };

    //--------------------------------------------------------------------------------------------------------
    //
    // Get the name of an assembly as it would appear in the APTCA enabled list of an AppDomain
    //

    void GetAssemblyNameForConditionalAptca(Assembly *pAssembly, SString *pAssemblyName)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
            PRECONDITION(CheckPointer(pAssembly));
            PRECONDITION(CheckPointer(pAssemblyName));
        }
        CONTRACTL_END;

        GCX_COOP();

        // Call assembly.GetName().GetNameWithPublicKey() to get the name the user would have to add to the 
        // whitelist to enable this assembly
        struct
        {
            OBJECTREF orAssembly;
            STRINGREF orAssemblyName;
        }
        gc;
        ZeroMemory(&gc, sizeof(gc));

        GCPROTECT_BEGIN(gc);

        gc.orAssembly = pAssembly->GetExposedObject();
        MethodDescCallSite getAssemblyName(METHOD__ASSEMBLY__GET_NAME_FOR_CONDITIONAL_APTCA, &gc.orAssembly);
        ARG_SLOT args[1] =
        { 
            ObjToArgSlot(gc.orAssembly)
        };
        gc.orAssemblyName = getAssemblyName.Call_RetSTRINGREF(args);
            
        // Copy to assemblyName
        pAssemblyName->Set(gc.orAssemblyName->GetBuffer());

        GCPROTECT_END();
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine which types of conditional APTCA assemblies may be shared
    //

    ConditionalAptcaSharingMode GetConditionalAptcaSharingMode()
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
        }
        CONTRACTL_END;

        static ConditionalAptcaSharingMode sharingMode = kShareUnknown;

        if (sharingMode == kShareUnknown)
        {
            // If the default domain has any conditional APTCA assemblies enabled in it, then we share in the
            // enabled direction.  Otherwise, the default domain has all conditional APTCA assemblies disabled
            // so we need to share in the disabled direction
            ConditionalAptcaCache *pDefaultDomainCache = SystemDomain::System()->DefaultDomain()->GetSecurityDescriptor()->GetConditionalAptcaCache();
            ConditionalAptcaCache::DomainState domainState = pDefaultDomainCache->GetConditionalAptcaDomainState();
            
            if (domainState == ConditionalAptcaCache::kAllDisabled)
            {
                sharingMode = kShareIfDisabled;
            }
            else
            {
                sharingMode = kShareIfEnabled;
            }
        }

        return sharingMode;
    }

    /* XXX Fri 7/17/2009
     * I can't call DomainAssembly::IsConditionalAPTCAVisible() here.  That requires an Assembly which means
     * we have to be at FILE_LOAD_ALLOCATE.  There are two problems:
     * 1) We don't want to load dependencies here if we can avoid it
     * 2) We can't load them anyway (hard bound dependencies can't get past
     *      FILE_LOAD_VERIFY_NATIVE_IMAGE_DEPENDENCIES.
     *
     * We're going to do a relaxed check here.  Instead of checking the public key, we're
     * only going to check the public key token.  See
     * code:AppDomain::IsAssemblyOnAptcaVisibleListRaw for more information.
     *
     * pAsmName - The name of the assembly to check.
     * pDomainAssembly - The Domain Assembly used for logging.
     */
    bool IsAssemblyOnAptcaVisibleList(IAssemblyName * pAsmName, DomainAssembly *pDomainAssembly)
    {
        CONTRACTL
        {
            STANDARD_VM_CHECK;
            PRECONDITION(CheckPointer(pAsmName));
        }
        CONTRACTL_END;

        ConditionalAptcaCache *pDomainCache = pDomainAssembly->GetAppDomain()->GetSecurityDescriptor()->GetConditionalAptcaCache();
        if (pDomainCache->GetConditionalAptcaDomainState() == ConditionalAptcaCache::kAllEnabled)
        {
            return true;
        }

        CQuickBytes qbName;
        LPWSTR pszName;
        DWORD cbName = 0;
        HRESULT hr = pAsmName->GetProperty(ASM_NAME_NAME, NULL, &cbName);
        if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
        {
            pszName = (LPWSTR)qbName.AllocThrows(cbName);
        }
        else
        {
            pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting native image / code sharing because there was an ")
                                         W("error checking for conditional APTCA: 0x%x"), hr);
            return false;
        }
        hr = pAsmName->GetProperty(ASM_NAME_NAME, (void *)pszName, &cbName);
        if (FAILED(hr))
        {
            pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting native image / code sharing because there was an ")
                                         W("error checking for conditional APTCA: 0x%x"), hr);
            return false;
        }
        BYTE rgPublicKeyToken[8];
        DWORD cbPkt = _countof(rgPublicKeyToken);
        hr = pAsmName->GetProperty(ASM_NAME_PUBLIC_KEY_TOKEN,
                                                  (void*)rgPublicKeyToken, &cbPkt);
        if (FAILED(hr))
        {
            pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting native image / code sharing because there was an ")
                                         W("error obtaining the public key token for %s: 0x%x"),
                                         pszName, hr);
            return false;
        }

        GCX_COOP();

        CLR_BOOL isVisible = FALSE;

        struct
        {
            OBJECTREF orThis;
        }
        gc;
        ZeroMemory(&gc, sizeof(gc));
        GCPROTECT_BEGIN(gc);
        gc.orThis = pDomainAssembly->GetAppDomain()->GetExposedObject();

        MethodDescCallSite assemblyVisible(METHOD__APP_DOMAIN__IS_ASSEMBLY_ON_APTCA_VISIBLE_LIST_RAW,
                                           &gc.orThis);
        ARG_SLOT args[] = {
            ObjToArgSlot(gc.orThis),
            (ARG_SLOT)pszName,
            (ARG_SLOT)wcslen(pszName),
            (ARG_SLOT)rgPublicKeyToken,
            (ARG_SLOT)cbPkt
        };
        isVisible = assemblyVisible.Call_RetBool(args);
        GCPROTECT_END();

        return isVisible;
    }

    bool IsAssemblyOnAptcaVisibleList(DomainAssembly *pAssembly)
    {
        CONTRACTL
        {
            STANDARD_VM_CHECK;
            PRECONDITION(CheckPointer(pAssembly));
            PRECONDITION(GetAppDomain() == pAssembly->GetAppDomain());
        }
        CONTRACTL_END;

        ConditionalAptcaCache *pDomainCache = pAssembly->GetAppDomain()->GetSecurityDescriptor()->GetConditionalAptcaCache();
        if (pDomainCache->GetConditionalAptcaDomainState() == ConditionalAptcaCache::kAllEnabled)
        {
            return true;
        }

        GCX_COOP();

        bool foundInList = false;

        // Otherwise, we need to transition into the BCL code to find out if the assembly is on the list
        struct
        {
            OBJECTREF orAppDomain;
            OBJECTREF orAssembly;
        }
        gc;
        ZeroMemory(&gc, sizeof(gc));

        GCPROTECT_BEGIN(gc);

        MethodDescCallSite isAssemblyOnAptcaVisibleList(METHOD__APP_DOMAIN__IS_ASSEMBLY_ON_APTCA_VISIBLE_LIST);
        gc.orAppDomain = GetAppDomain()->GetExposedObject();
        gc.orAssembly = pAssembly->GetAssembly()->GetExposedObject();

        ARG_SLOT args[] =
        { 
            ObjToArgSlot(gc.orAppDomain),
            ObjToArgSlot(gc.orAssembly)
        };

        foundInList = isAssemblyOnAptcaVisibleList.Call_RetBool(args);

        GCPROTECT_END();

        return foundInList;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine if an assembly is APTCA in the current domain or not
    //
    // Arguments:
    //    pDomainAssembly - Assembly to check for APTCA-ness
    //    tokenFlags      - raw metadata security bits from the assembly
    //
    // Return Value:
    //    true if the assembly is APTCA, false if it is not
    //

    bool IsAssemblyAptcaEnabled(DomainAssembly *pDomainAssembly, TokenSecurityDescriptorFlags tokenFlags)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
            PRECONDITION(CheckPointer(pDomainAssembly));
        }
        CONTRACTL_END;

#ifdef _DEBUG
        SString strAptcaAssemblyBreak(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_Security_AptcaAssemblyBreak));
        SString strAssemblySimpleName(SString::Utf8, pDomainAssembly->GetSimpleName());
        if (strAptcaAssemblyBreak.EqualsCaseInsensitive(strAssemblySimpleName))
        {
            _ASSERTE(!"Checking APTCA-ness of an APTCA break assembly");
        }
#endif // _DEBUG

        // If the assembly is not marked APTCA, then it cannot possibly be APTCA enabled
        if ((tokenFlags & TokenSecurityDescriptorFlags_APTCA) == TokenSecurityDescriptorFlags_None)
        {
            return false;
        }

        GCX_PREEMP();

        // Additionally, if the assembly is on the APTCA kill list, then no matter what it says in its metadata,
        // it should not be considered APTCA
        if (GetKillBitList()->IsAssemblyKillBitted(pDomainAssembly->GetFile()))
        {
            return false;
        }

        // If the assembly is conditionally APTCA, then we need to check the current AppDomain's APTCA enabled
        // list to figure out if it is APTCA in this domain.
        if (tokenFlags & TokenSecurityDescriptorFlags_ConditionalAPTCA)
        {
            return IsAssemblyOnAptcaVisibleList(pDomainAssembly);
        }

        // Otherwise, the assembly is APTCA
        return true;
    }

    //--------------------------------------------------------------------------------------------------------
    //
    // Determine if the assembly matches the conditional APTCA sharing mode.  That is, if we are sharing
    // enabled conditional APTCA assemblies check that this assembly is enabled.  Similarly, if we are
    // sharing disabled conditional APTCA assemblies check that this assembly is disabled.
    // 
    // This method assumes that the assembly is conditionally APTCA
    //

    bool AssemblyMatchesShareMode(IAssemblyName *pAsmName, DomainAssembly *pDomainAssembly)
    {
        CONTRACTL
        {
            STANDARD_VM_CHECK;
            PRECONDITION(CheckPointer(pAsmName));
            PRECONDITION(GetConditionalAptcaSharingMode() != kShareUnknown);
        }
        CONTRACTL_END;

        if (IsAssemblyOnAptcaVisibleList(pAsmName, pDomainAssembly))
        {
            return GetConditionalAptcaSharingMode() == kShareIfEnabled;
        }
        else
        {
            return GetConditionalAptcaSharingMode() == kShareIfDisabled;
        }
    }

    bool AssemblyMatchesShareMode(ConditionalAptcaCache::State state)
    {
        STANDARD_VM_CONTRACT;

        _ASSERTE(state == ConditionalAptcaCache::kEnabled || state == ConditionalAptcaCache::kDisabled);

        if (state == ConditionalAptcaCache::kEnabled)
        {
            return GetConditionalAptcaSharingMode() == kShareIfEnabled;
        }
        else
        {
            return GetConditionalAptcaSharingMode() == kShareIfDisabled;
        }
    }
}

//------------------------------------------------------------------------------------------------------------
//
// Determine if the AppDomain can share an assembly or if APTCA restrictions prevent sharing
// 

bool DomainCanShareAptcaAssembly(DomainAssembly *pDomainAssembly)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pDomainAssembly));
    }
    CONTRACTL_END;

#ifdef _DEBUG
    DWORD dwAptcaAssemblyDomainBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_Security_AptcaAssemblySharingDomainBreak);
    if (dwAptcaAssemblyDomainBreak == 0 || ADID(dwAptcaAssemblyDomainBreak) == pDomainAssembly->GetAppDomain()->GetId())
    {
        SString strAptcaAssemblySharingBreak(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_Security_AptcaAssemblySharingBreak));
        SString strAssemblySimpleName(SString::Utf8, pDomainAssembly->GetSimpleName());

        if (strAptcaAssemblySharingBreak.EqualsCaseInsensitive(strAssemblySimpleName))
        {
            _ASSERTE(!"Checking code sharing for APTCA break assembly");
        }
    }
#endif // _DEBUG

    //
    // We can only share an assembly if all conditional APTCA assemblies in its full closure of dependencies
    // are enabled.
    //

    // We always allow sharing of mscorlib
    if (pDomainAssembly->IsSystem())
    {
        return true;
    }

    IApplicationSecurityDescriptor *pDomainSecDesc = pDomainAssembly->GetAppDomain()->GetSecurityDescriptor();
    ConditionalAptcaCache *pConditionalAptcaCache = pDomainSecDesc->GetConditionalAptcaCache();

    // If all assemblies in the domain match the sharing mode, then we can share the assembly
    ConditionalAptcaCache::DomainState domainState = pConditionalAptcaCache->GetConditionalAptcaDomainState();
    if (GetConditionalAptcaSharingMode() == kShareIfEnabled)
    {
        if (domainState == ConditionalAptcaCache::kAllEnabled)
        {
            return true;
        }
    }
    else
    {
        if (domainState == ConditionalAptcaCache::kAllDisabled)
        {
            return true;
        }
    }

    // If the root assembly is conditionally APTCA, then it needs to be enabled
    ReleaseHolder<IMDInternalImport> pRootImport(pDomainAssembly->GetFile()->GetMDImportWithRef());
    TokenSecurityDescriptorFlags rootSecurityAttributes =
        TokenSecurityDescriptor::ReadSecurityAttributes(pRootImport, TokenFromRid(1, mdtAssembly));
    if (rootSecurityAttributes & TokenSecurityDescriptorFlags_ConditionalAPTCA)
    {
        if (!AssemblyMatchesShareMode(pDomainAssembly->GetFile()->GetFusionAssemblyName(), pDomainAssembly))
        {
            return false;
        }
    }

    // Now we need to get the full closure of assemblies that this assembly depends upon and ensure that each
    // one of those is either not conditional APTCA or is enabled in the domain.  We get a new assembly
    // closure object here rather than using DomainAssembly::GetAssemblyBindingClosure because we don't want
    // to force that closure to walk the full dependency graph (and therefore not be considered equal to
    // closures which weren't fully walked).
    IUnknown *pFusionAssembly;
    if (pDomainAssembly->GetFile()->IsIStream())
    {
        pFusionAssembly = pDomainAssembly->GetFile()->GetIHostAssembly();
    }
    else
    {
        pFusionAssembly = pDomainAssembly->GetFile()->GetFusionAssembly();
    }

    // Get the closure and force it to do a full dependency walk, not stopping at framework assemblies
    SafeComHolder<IAssemblyBindingClosure> pClosure;


    LPCWSTR pNIPath = NULL;
    PEAssembly *pPEAsm = pDomainAssembly->GetFile();
    if (pPEAsm->HasNativeImage())
    {
        ReleaseHolder<PEImage> pNIImage = pPEAsm->GetNativeImageWithRef();
        pNIPath = pNIImage->GetPath().GetUnicode();
    }

    IfFailThrow(pDomainAssembly->GetAppDomain()->GetFusionContext()->GetAssemblyBindingClosure(pFusionAssembly, pNIPath, &pClosure));
    IfFailThrow(pClosure->EnsureWalked(pFusionAssembly, pDomainAssembly->GetAppDomain()->GetFusionContext(), LEVEL_FXPROBED));

    // Now iterate the closure looking for conditional APTCA assemblies
    SafeComHolder<IAssemblyBindingClosureEnumerator> pClosureEnumerator;
    IfFailThrow(pClosure->EnumerateAssemblies(&pClosureEnumerator));
    LPCOLESTR szDependentAssemblyPath = NULL;
    LPCOLESTR szDependentNIAssemblyPath = NULL;

    for (HRESULT hr = pClosureEnumerator->GetNextAssemblyPath(&szDependentAssemblyPath, &szDependentNIAssemblyPath);
         SUCCEEDED(hr);
         hr = pClosureEnumerator->GetNextAssemblyPath(&szDependentAssemblyPath, &szDependentNIAssemblyPath))
    {
        // Make sure we've succesfully enumerated an item
        if (hr != S_OK && hr != HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS))
        {
            pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting code sharing because of an error enumerating dependent assemblies: 0x%x"), hr);
            return false;
        }
        else if (szDependentAssemblyPath == NULL)
        {
            // This means we have an assembly but no way to verify the image at this point -- should we get
            // into this state, we'll be conservative and fail the share
            pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting code sharing because an assembly in the closure does not have a path"));
            return false;
        }
        else
        {
            // We have succesfully found a new item in the closure of assemblies - now check to ensure that
            // it is either not conditionally APTCA or is enabled in tihs domain.
            PEImageHolder pDependentImage;

            // Use the native image if it is loaded. 
            if (szDependentNIAssemblyPath != NULL)
            {
                SString strNIAssemblyPath(szDependentNIAssemblyPath);
                pDependentImage = PEImage::OpenImage(strNIAssemblyPath, MDInternalImport_OnlyLookInCache);
                if (pDependentImage != NULL && !pDependentImage->HasLoadedLayout())
                {
                    pDependentImage = NULL;
                }
                else
                {
#if FEATURE_CORECLR
#error Coreclr needs to check native image version here.
#endif
                }
            }

            if (pDependentImage == NULL)
            {
                SString strAssemblyPath(szDependentAssemblyPath);
                pDependentImage = PEImage::OpenImage(strAssemblyPath);
            }

            // See if we already know if this image is enabled in the current domain or not
            ConditionalAptcaCache::State dependentState = pConditionalAptcaCache->GetCachedState(pDependentImage);

            // We don't know this assembly's conditional APTCA state in this domain, so we need to figure it
            // out now.
            if (dependentState == ConditionalAptcaCache::kUnknown)
            {
                // First figure out if the assembly is even conditionally APTCA to begin with
                IMDInternalImport *pDependentImport = pDependentImage->GetMDImport();
                TokenSecurityDescriptorFlags dependentSecurityAttributes =
                    TokenSecurityDescriptor::ReadSecurityAttributes(pDependentImport, TokenFromRid(1, mdtAssembly));

                if (dependentSecurityAttributes & TokenSecurityDescriptorFlags_ConditionalAPTCA)
                {
                    // The the assembly name of the dependent assembly so we can check it to the domain
                    // enabled list
                    ReleaseHolder<IAssemblyName> pDependentAssemblyName;
                    AssemblySpec dependentAssemblySpec(pDomainAssembly->GetAppDomain());
                    dependentAssemblySpec.InitializeSpec(TokenFromRid(1, mdtAssembly), pDependentImport);
                    IfFailThrow(dependentAssemblySpec.CreateFusionName(&pDependentAssemblyName, FALSE));

                    // Check the domain list to see if the assembly is on it
                    if (IsAssemblyOnAptcaVisibleList(pDependentAssemblyName, pDomainAssembly))
                    {
                        dependentState = ConditionalAptcaCache::kEnabled;
                    }
                    else
                    {
                        dependentState = ConditionalAptcaCache::kDisabled;
                    }
                }
                else
                {
                    // The dependent assembly doesn't have the conditional APTCA bit set on it, so we don't
                    // need to do any checking to see if it's enabled
                    dependentState = ConditionalAptcaCache::kNotCAptca;
                }

                // Cache the result of evaluating conditional APTCA on this assembly in the domain
                pConditionalAptcaCache->SetCachedState(pDependentImage, dependentState);
            }

            // If the dependent assembly does not match the sharing mode, then we cannot share the
            // dependency. We can always share dependencies which are not conditionally APTCA, so don't
            // bother checking the share mode for them.
            if (dependentState != ConditionalAptcaCache::kNotCAptca)
            {
                if (!AssemblyMatchesShareMode(dependentState))
                {
                    pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting code sharing because a dependent assembly did not match the conditional APTCA share mode"));
                    return false;
                }
            }
        }
    }

    // The root assembly and all of its dependents were either on the conditional APTCA list or are not
    // conditional APTCA, so we can share this assembly
    return true;   
}

//------------------------------------------------------------------------------------------------------------
//
// Get an exception string indicating how to enable a conditional APTCA assembly if it was disabled and
// caused an exception
// 

SString GetConditionalAptcaAccessExceptionContext(Assembly *pTargetAssembly)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pTargetAssembly));
    }
    CONTRACTL_END;

    SString exceptionContext;

    ModuleSecurityDescriptor *pMSD = ModuleSecurityDescriptor::GetModuleSecurityDescriptor(pTargetAssembly);

    if (pMSD->GetTokenFlags() & TokenSecurityDescriptorFlags_ConditionalAPTCA)
    {
        GCX_PREEMP();

        if (!IsAssemblyOnAptcaVisibleList(pTargetAssembly->GetDomainAssembly()))
        {
            // We have a conditional APTCA assembly which is not on the visible list for the current
            // AppDomain, provide information on how to enable it.
            SString assemblyDisplayName;
            pTargetAssembly->GetDisplayName(assemblyDisplayName);

            SString assemblyConditionalAptcaName;
            GetAssemblyNameForConditionalAptca(pTargetAssembly, &assemblyConditionalAptcaName);

            EEException::GetResourceMessage(IDS_ACCESS_EXCEPTION_CONTEXT_CONDITIONAL_APTCA,
                                            exceptionContext,
                                            assemblyDisplayName,
                                            assemblyConditionalAptcaName);
        }
    }

    return exceptionContext;
}

//------------------------------------------------------------------------------------------------------------
//
// Get an exception string indicating that an assembly was on the kill bit list if it caused an exception
//

SString GetAptcaKillBitAccessExceptionContext(Assembly *pTargetAssembly)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pTargetAssembly));
    }
    CONTRACTL_END;

    GCX_PREEMP();

    SString exceptionContext;

    if (GetKillBitList()->IsAssemblyKillBitted(pTargetAssembly->GetDomainAssembly()->GetFile()))
    {
        SString assemblyDisplayName;
        pTargetAssembly->GetDisplayName(assemblyDisplayName);

        EEException::GetResourceMessage(IDS_ACCESS_EXCEPTION_CONTEXT_APTCA_KILLBIT,
                                        exceptionContext,
                                        assemblyDisplayName);
    }

    return exceptionContext;
}

//------------------------------------------------------------------------------------------------------------
//
// Determine if a native image is valid to use from the perspective of APTCA.  This means that the image
// itself and all of its dependencies must:
//   1. Not be killbitted
//   2. Be enabled if they are conditionally APTCA
//
// Arguments:
//    pNativeImage    -  native image to accept or reject
//    pDomainAssembly -  assembly that is being loaded
//
// Return Value:
//    true if the native image can be accepted due to APTCA-ness, false if we need to reject it
//

bool NativeImageHasValidAptcaDependencies(PEImage *pNativeImage, DomainAssembly *pDomainAssembly)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pNativeImage));
        PRECONDITION(CheckPointer(pDomainAssembly));
    }
    CONTRACTL_END;

    AptcaKillBitList *pKillBitList = GetKillBitList();

    ConditionalAptcaCache *pDomainCache = pDomainAssembly->GetAppDomain()->GetSecurityDescriptor()->GetConditionalAptcaCache();
    // If we have any killbitted assemblies, then we need to make sure that the current assembly and its dependencies
    BOOL aptcaChecks = pKillBitList->AreAnyAssembliesKillBitted();
    BOOL conditionalAptcaChecks = pDomainCache->GetConditionalAptcaDomainState() != ConditionalAptcaCache::kAllEnabled;
    if (!aptcaChecks && !conditionalAptcaChecks)
        return true;

    //
    // Check to see if the NGEN image itself is APTCA and killbitted
    //

    ReleaseHolder<IMDInternalImport> pAssemblyMD(pDomainAssembly->GetFile()->GetMDImportWithRef());
    TokenSecurityDescriptorFlags assemblySecurityAttributes =
        TokenSecurityDescriptor::ReadSecurityAttributes(pAssemblyMD, TokenFromRid(1, mdtAssembly));

    if (aptcaChecks)
    {
        if ((assemblySecurityAttributes & TokenSecurityDescriptorFlags_APTCA) &&
            pKillBitList->IsAssemblyKillBitted(pDomainAssembly->GetFile()))
        {
            return false;
        }
    }
    if (conditionalAptcaChecks
        && (assemblySecurityAttributes & TokenSecurityDescriptorFlags_ConditionalAPTCA))
    {
        //
        // First check to see if we're disabled.
        //

        AssemblySpec spec;
        spec.InitializeSpec(pDomainAssembly->GetFile());
        ReleaseHolder<IAssemblyName> pAsmName;
        IfFailThrow(spec.CreateFusionName(&pAsmName, FALSE));

        if (!IsAssemblyOnAptcaVisibleList(pAsmName, pDomainAssembly))
        {
            //IsAssemblyOnAptcaVisibleList has already logged an error.
            return false;
        }
    }

    if (aptcaChecks || conditionalAptcaChecks)
    {
        //
        // Also check its dependencies
        //

        COUNT_T dependencyCount;
        PEImageLayout *pNativeLayout = pNativeImage->GetLoadedLayout();
        CORCOMPILE_DEPENDENCY *pDependencies = pNativeLayout->GetNativeDependencies(&dependencyCount);

        for (COUNT_T i = 0; i < dependencyCount; ++i)
        {
            CORCOMPILE_DEPENDENCY* pDependency = &(pDependencies[i]);
            // Look for any dependency which is APTCA
            if (pDependencies[i].dwAssemblyDef != mdAssemblyRefNil)
            {
                AssemblySpec name;
                name.InitializeSpec(pDependency->dwAssemblyRef,
                                    pNativeImage->GetNativeMDImport(),
                                    NULL,
                                    pDomainAssembly->GetFile()->IsIntrospectionOnly());

                ReleaseHolder<IAssemblyName> pDependencyAssemblyName;
                HRESULT hr = name.CreateFusionName(&pDependencyAssemblyName, FALSE);

                // If we couldn't build the assemlby name up conservatively discard the image
                if (FAILED(hr))
                {
                    pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting native image because could not get ")
                                                 W("name for assemblyref 0x%x for native image dependency: ")
                                                 W("hr=0x%x"), pDependency->dwAssemblyRef, hr);
                    return false;
                }

                if (pDependencies[i].dependencyInfo & (CORCOMPILE_DEPENDENCY_IS_APTCA))
                {
                    ULARGE_INTEGER fileVersion;

                    //This is a workaround for Dev10# 743602
                    fileVersion.QuadPart = GET_UNALIGNED_VAL64(&(pDependencies[i].uliFileVersion));
                    // If the dependency really is killbitted, then discard the image
                    if (pKillBitList->IsAssemblyKillBitted(pDependencyAssemblyName, fileVersion))
                    {
                        pDomainAssembly->ExternalLog(LL_ERROR, W("Rejecting native image because dependency ")
                                                     W("assemblyref 0x%x is killbitted."),
                                                     pDependency->dwAssemblyRef);
                        return false;
                    }
                }
                if (pDependencies[i].dependencyInfo & (CORCOMPILE_DEPENDENCY_IS_CAPTCA))
                {
                    if (!IsAssemblyOnAptcaVisibleList(pDependencyAssemblyName, pDomainAssembly))
                    {
                        //IsAssemblyOnAptcaVisibleList has already logged an error.
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
#else // CROSSGEN_COMPILE
namespace
{
    bool IsAssemblyAptcaEnabled(DomainAssembly *pDomainAssembly, TokenSecurityDescriptorFlags tokenFlags)
    {
        // No killbits or conditional APTCA for crossgen. Just check whether the assembly is marked APTCA.
        return ((tokenFlags & TokenSecurityDescriptorFlags_APTCA) != TokenSecurityDescriptorFlags_None);
    }
}
#endif // CROSSGEN_COMPILE

//------------------------------------------------------------------------------------------------------------
//
// Process an assembly's real APTCA flags to determine if the assembly should be considered
// APTCA or not
//
// Arguments:
//    pDomainAssembly - Assembly to check for APTCA-ness
//    tokenFlags      - raw metadata security bits from the assembly
//
// Return Value:
//    updated token security descriptor flags which indicate the assembly's true APTCA state
//

TokenSecurityDescriptorFlags ProcessAssemblyAptcaFlags(DomainAssembly *pDomainAssembly,
                                                       TokenSecurityDescriptorFlags tokenFlags)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pDomainAssembly));
    }
    CONTRACTL_END;

    const TokenSecurityDescriptorFlags aptcaFlags = TokenSecurityDescriptorFlags_APTCA |
                                                    TokenSecurityDescriptorFlags_ConditionalAPTCA;

    if (IsAssemblyAptcaEnabled(pDomainAssembly, tokenFlags))
    {
        // The assembly is APTCA - temporarially remove all of its APTCA bits, and then add back the
        // unconditionally APTCA bit
        tokenFlags = tokenFlags & ~aptcaFlags;
        return tokenFlags | TokenSecurityDescriptorFlags_APTCA;
    }
    else
    {
        // The assembly is not APTCA, so remove all of its APTCA bits from the token security descriptor
        return tokenFlags & ~aptcaFlags;
    }
}