2 * Copyright (c) 2006-2007 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 // StaticCode - SecStaticCode API objects
31 #include "Requirements.h"
32 #include "requirement.h"
34 #include "codedirectory.h"
35 #include <Security/SecTrust.h>
36 #include <CoreFoundation/CFData.h>
39 namespace CodeSigning
{
46 // A SecStaticCode object represents the file system version of some code.
47 // There's a lot of pieces to this, and we'll bring them all into
48 // memory here (lazily) and let you fondle them with ease.
50 // Note that concrete knowledge of where stuff is stored resides in the DiskRep
51 // object we hold. DiskReps allocate, retrieve, and return data to us. We are
52 // responsible for interpreting, caching, and validating them. (In other words,
53 // DiskReps know where stuff is and how it is stored, but we know what it means.)
55 // Data accessors (returning CFDataRef, CFDictionaryRef, various pointers, etc.)
56 // cache those values internally and return unretained(!) references ("Get" style)
57 // that are valid as long as the SecStaticCode object's lifetime, or until
58 // resetValidity() is called, whichever is sooner. If you need to keep them,
59 // retain or copy them as needed.
61 class SecStaticCode
: public SecCFObject
{
66 // A context for resource validation operations, to tailor error response.
67 // The base class throws an exception immediately and ignores detail data.
69 class ValidationContext
{
71 virtual ~ValidationContext();
72 virtual void reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
);
76 // A CollectingContext collects all error details and throws an annotated final error.
78 class CollectingContext
: public ValidationContext
{
80 CollectingContext(SecStaticCode
&c
) : code(c
), mStatus(noErr
) { }
81 void reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
);
83 OSStatus
osStatus() { return mStatus
; }
84 operator OSStatus () const { return mStatus
; }
85 void throwMe() __attribute__((noreturn
));
90 CFRef
<CFMutableDictionaryRef
> mCollection
;
95 SECCFFUNCTIONS(SecStaticCode
, SecStaticCodeRef
,
96 errSecCSInvalidObjectRef
, gCFObjects().StaticCode
)
98 // implicitly convert SecCodeRefs to their SecStaticCodeRefs
99 static SecStaticCode
*requiredStatic(SecStaticCodeRef ref
); // convert SecCodeRef
100 static SecCode
*optionalDynamic(SecStaticCodeRef ref
); // extract SecCodeRef or NULL
102 SecStaticCode(DiskRep
*rep
);
103 virtual ~SecStaticCode() throw();
105 bool equal(SecCFObject
&other
);
108 void detachedSignature(CFDataRef sig
); // attach an explicitly given detached signature
109 void checkForSystemSignature(); // check for and attach system-supplied detached signature
111 const CodeDirectory
*codeDirectory(bool check
= true);
113 CFDataRef
signature();
114 CFAbsoluteTime
signingTime();
115 bool isSigned() { return codeDirectory(false) != NULL
; }
116 DiskRep
*diskRep() { return mRep
; }
117 std::string
mainExecutablePath() { return mRep
->mainExecutablePath(); }
118 CFURLRef
canonicalPath() const { return mRep
->canonicalPath(); }
119 std::string
identifier() { return codeDirectory()->identifier(); }
120 std::string
format() const { return mRep
->format(); }
121 std::string
signatureSource();
122 CFDataRef
component(CodeDirectory::SpecialSlot slot
, OSStatus fail
= errSecCSSignatureFailed
);
123 CFDictionaryRef
infoDictionary();
124 CFDictionaryRef
entitlements();
126 CFDictionaryRef
resourceDictionary();
127 CFURLRef
resourceBase();
128 CFDataRef
resource(std::string path
);
129 CFDataRef
resource(std::string path
, ValidationContext
&ctx
);
130 void validateResource(std::string path
, ValidationContext
&ctx
);
132 bool flag(uint32_t tested
);
134 void resetValidity(); // clear validation caches (if something may have changed)
136 bool validated() const { return mValidated
; }
138 { assert(validated()); return mValidated
&& (mValidationResult
== noErr
); }
139 bool validatedExecutable() const { return mExecutableValidated
; }
140 bool validatedResources() const { return mResourcesValidated
; }
143 void validateDirectory();
144 void validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
= errSecCSSignatureFailed
);
145 void validateNonResourceComponents();
146 void validateResources();
147 void validateExecutable();
149 const Requirements
*internalRequirements();
150 const Requirement
*internalRequirement(SecRequirementType type
);
151 const Requirement
*designatedRequirement();
152 const Requirement
*defaultDesignatedRequirement(); // newly allocated (caller owns)
154 void validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
155 OSStatus nullError
= noErr
); // target against my [type], throws
156 void validateRequirement(const Requirement
*req
, OSStatus failure
); // me against [req], throws
157 bool satisfiesRequirement(const Requirement
*req
, OSStatus failure
); // me against [req], returns on clean miss
159 // certificates are available after signature validation (they are stored in the CMS signature)
160 SecCertificateRef
cert(int ix
); // get a cert from the cert chain
161 CFArrayRef
certificates(); // get the entire certificate chain
163 CFDictionaryRef
signingInformation(SecCSFlags flags
); // omnibus information-gathering API (creates new dictionary)
166 class AllArchitectures
;
169 CFDictionaryRef
getDictionary(CodeDirectory::SpecialSlot slot
, OSStatus fail
); // component value as a dictionary
170 bool verifySignature();
171 CFTypeRef
verificationPolicy(SecCSFlags flags
);
173 void defaultDesignatedAppleAnchor(Requirement::Maker
&maker
);
174 void defaultDesignatedNonAppleAnchor(Requirement::Maker
&maker
);
175 bool isAppleSDKSignature();
176 bool isAppleCaspianSignature();
178 static void checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
);
181 RefPointer
<DiskRep
> mRep
; // on-disk representation
183 // master validation state
184 bool mValidated
; // core validation was attempted
185 OSStatus mValidationResult
; // outcome of core validation
186 bool mValidationExpired
; // outcome had expired certificates
188 // static executable validation state (nested within mValidated/mValid)
189 bool mExecutableValidated
; // tried to validate executable file
190 OSStatus mExecutableValidResult
; // outcome if mExecutableValidated
192 // static resource validation state (nested within mValidated/mValid)
193 bool mResourcesValidated
; // tried to validate resources
194 OSStatus mResourcesValidResult
; // outcome if mResourceValidated or..
195 CollectingContext
*mResourcesValidContext
; // other outcome
198 CFRef
<CFDataRef
> mDir
; // code directory data
199 CFRef
<CFDataRef
> mSignature
; // CMS signature data
200 CFAbsoluteTime mSigningTime
; // (signed) signing time
201 CFRef
<CFDataRef
> mCache
[cdSlotCount
]; // NULL => not tried, kCFNull => absent, other => present
203 // alternative cache forms (storage may depend on cached contents above)
204 CFRef
<CFDictionaryRef
> mInfoDict
; // derived from mCache slot
205 CFRef
<CFDictionaryRef
> mEntitlements
; // derived from mCache slot
206 CFRef
<CFDictionaryRef
> mResourceDict
; // derived from mCache slot
207 const Requirement
*mDesignatedReq
; // cached designated req if we made one up
208 CFRef
<CFDataRef
> mCDHash
; // hash of CodeDirectory
210 bool mGotResourceBase
; // asked mRep for resourceBasePath
211 CFRef
<CFURLRef
> mResourceBase
; // URL form of resource base directory
213 // signature verification outcome (mTrust == NULL => not done yet)
214 CFRef
<SecTrustRef
> mTrust
; // outcome of crypto validation (valid or not)
215 CFRef
<CFArrayRef
> mCertChain
;
216 CSSM_TP_APPLE_EVIDENCE_INFO
*mEvalDetails
;
221 // Given a SecStaticCode, create an iterator that produces SecStaticCodes
222 // for all architectures encompassed by this static code reference.
224 class SecStaticCode::AllArchitectures
: public SecPointer
<SecStaticCode
> {
226 AllArchitectures(SecStaticCode
*code
);
228 SecStaticCode
*operator () ();
231 SecPointer
<SecStaticCode
> mBase
;
232 enum { fatBinary
, firstNonFat
, atEnd
} mState
;
233 Universal::Architectures mArchitectures
;
234 Universal::Architectures::const_iterator mCurrent
;
238 } // end namespace CodeSigning
239 } // end namespace Security
241 #endif // !_H_STATICCODE