2 * Copyright (c) 2006-2010 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 // signer - Signing operation supervisor and controller
28 #include "resources.h"
29 #include "signerutils.h"
30 #include "SecCodeSigner.h"
31 #include <Security/SecIdentity.h>
32 #include <Security/CMSEncoder.h>
33 #include <Security/CMSPrivate.h>
34 #include <Security/CSCommonPriv.h>
35 #include <CoreFoundation/CFBundlePriv.h>
36 #include "resources.h"
38 #include "reqparser.h"
39 #include "reqdumper.h"
40 #include "csutilities.h"
41 #include <security_utilities/unix++.h>
42 #include <security_utilities/unixchild.h>
43 #include <security_utilities/cfmunge.h>
46 namespace CodeSigning
{
52 void SecCodeSigner::Signer::sign(SecCSFlags flags
)
54 rep
= code
->diskRep()->base();
57 PreSigningContext
context(*this);
59 /* If an explicit teamID was passed in it must be
60 the same as what came from the cert */
61 std::string teamIDFromCert
= state
.getTeamIDFromSigner(context
.certs
);
63 if (state
.mPreserveMetadata
& kSecCodeSignerPreserveTeamIdentifier
) {
64 /* If preserving the team identifier, teamID is set previously when the
65 code object is still available */
66 if (!teamIDFromCert
.empty() && teamID
!= teamIDFromCert
)
67 MacOSError::throwMe(errSecCSInvalidFlags
);
69 if (teamIDFromCert
.empty()) {
70 /* state.mTeamID is an explicitly passed teamID */
71 teamID
= state
.mTeamID
;
72 } else if (state
.mTeamID
.empty() || (state
.mTeamID
== teamIDFromCert
)) {
73 /* If there was no explicit team ID set, or the explicit team ID matches
74 what is in the cert, use the team ID from the certificate */
75 teamID
= teamIDFromCert
;
77 /* The caller passed in an explicit team ID that does not match what is
78 in the signing cert, which is an invalid usage */
79 MacOSError::throwMe(errSecCSInvalidFlags
);
83 if (Universal
*fat
= state
.mNoMachO
? NULL
: rep
->mainExecutableImage()) {
84 signMachO(fat
, context
);
86 signArchitectureAgnostic(context
);
92 // Remove any existing code signature from code
94 void SecCodeSigner::Signer::remove(SecCSFlags flags
)
96 // can't remove a detached signature
98 MacOSError::throwMe(errSecCSNotSupported
);
100 rep
= code
->diskRep();
101 if (Universal
*fat
= state
.mNoMachO
? NULL
: rep
->mainExecutableImage()) {
102 // architecture-sensitive removal
103 MachOEditor
editor(rep
->writer(), *fat
, kSecCodeSignatureNoHash
, rep
->mainExecutablePath());
104 editor
.allocate(); // create copy
105 editor
.commit(); // commit change
107 // architecture-agnostic removal
108 RefPointer
<DiskRep::Writer
> writer
= rep
->writer();
116 // Contemplate the object-to-be-signed and set up the Signer state accordingly.
118 void SecCodeSigner::Signer::prepare(SecCSFlags flags
)
120 // get the Info.plist out of the rep for some creative defaulting
121 CFRef
<CFDictionaryRef
> infoDict
;
122 if (CFRef
<CFDataRef
> infoData
= rep
->component(cdInfoSlot
))
123 infoDict
.take(makeCFDictionaryFrom(infoData
));
125 uint32_t inherit
= code
->isSigned() ? state
.mPreserveMetadata
: 0;
127 // work out the canonical identifier
128 identifier
= state
.mIdentifier
;
129 if (identifier
.empty() && (inherit
& kSecCodeSignerPreserveIdentifier
))
130 identifier
= code
->identifier();
131 if (identifier
.empty()) {
132 identifier
= rep
->recommendedIdentifier(state
);
133 if (identifier
.find('.') == string::npos
)
134 identifier
= state
.mIdentifierPrefix
+ identifier
;
135 if (identifier
.find('.') == string::npos
&& state
.isAdhoc())
136 identifier
= identifier
+ "-" + uniqueName();
137 secdebug("signer", "using default identifier=%s", identifier
.c_str());
139 secdebug("signer", "using explicit identifier=%s", identifier
.c_str());
141 teamID
= state
.mTeamID
;
142 if (teamID
.empty() && (inherit
& kSecCodeSignerPreserveTeamIdentifier
)) {
143 const char *c_id
= code
->teamID();
148 entitlements
= state
.mEntitlementData
;
149 if (!entitlements
&& (inherit
& kSecCodeSignerPreserveEntitlements
))
150 entitlements
= code
->component(cdEntitlementSlot
);
152 // work out the CodeDirectory flags word
153 bool haveCdFlags
= false;
154 if (!haveCdFlags
&& state
.mCdFlagsGiven
) {
155 cdFlags
= state
.mCdFlags
;
156 secdebug("signer", "using explicit cdFlags=0x%x", cdFlags
);
162 if (CFTypeRef csflags
= CFDictionaryGetValue(infoDict
, CFSTR("CSFlags"))) {
163 if (CFGetTypeID(csflags
) == CFNumberGetTypeID()) {
164 cdFlags
= cfNumber
<uint32_t>(CFNumberRef(csflags
));
165 secdebug("signer", "using numeric cdFlags=0x%x from Info.plist", cdFlags
);
166 } else if (CFGetTypeID(csflags
) == CFStringGetTypeID()) {
167 cdFlags
= cdTextFlags(cfString(CFStringRef(csflags
)));
168 secdebug("signer", "using text cdFlags=0x%x from Info.plist", cdFlags
);
170 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
174 if (!haveCdFlags
&& (inherit
& kSecCodeSignerPreserveFlags
)) {
175 cdFlags
= code
->codeDirectory(false)->flags
& ~kSecCodeSignatureAdhoc
;
176 secdebug("signer", "using inherited cdFlags=0x%x", cdFlags
);
181 if (state
.mSigner
== SecIdentityRef(kCFNull
)) // ad-hoc signing requested...
182 cdFlags
|= kSecCodeSignatureAdhoc
; // ... so note that
184 // prepare the internal requirements input
185 if (state
.mRequirements
) {
186 if (CFGetTypeID(state
.mRequirements
) == CFDataGetTypeID()) { // binary form
187 const Requirements
*rp
= (const Requirements
*)CFDataGetBytePtr(state
.mRequirements
.as
<CFDataRef
>());
188 if (!rp
->validateBlob())
189 MacOSError::throwMe(errSecCSReqInvalid
);
190 requirements
= rp
->clone();
191 } else if (CFGetTypeID(state
.mRequirements
) == CFStringGetTypeID()) { // text form
192 CFRef
<CFMutableStringRef
> reqText
= CFStringCreateMutableCopy(NULL
, 0, state
.mRequirements
.as
<CFStringRef
>());
193 // substitute $ variable tokens
194 CFRange range
= { 0, CFStringGetLength(reqText
) };
195 CFStringFindAndReplace(reqText
, CFSTR("$self.identifier"), CFTempString(identifier
), range
, 0);
196 requirements
= parseRequirements(cfString(reqText
));
198 MacOSError::throwMe(errSecCSInvalidObjectRef
);
199 } else if (inherit
& kSecCodeSignerPreserveRequirements
)
200 if (const Requirements
*rp
= code
->internalRequirements())
201 requirements
= rp
->clone();
203 // prepare the resource directory, if any
204 string rpath
= rep
->resourcesRootPath();
205 if (!rpath
.empty()) {
206 // explicitly given resource rules always win
207 CFCopyRef
<CFDictionaryRef
> resourceRules
= state
.mResourceRules
;
209 // inherited rules come next (overriding embedded ones!)
210 if (!resourceRules
&& (inherit
& kSecCodeSignerPreserveResourceRules
))
211 if (CFDictionaryRef oldRules
= code
->resourceDictionary(false))
212 resourceRules
= oldRules
;
214 // embedded resource rules come next
215 if (!resourceRules
&& infoDict
)
216 if (CFTypeRef spec
= CFDictionaryGetValue(infoDict
, _kCFBundleResourceSpecificationKey
)) {
217 if (CFGetTypeID(spec
) == CFStringGetTypeID())
218 if (CFRef
<CFDataRef
> data
= cfLoadFile(rpath
+ "/" + cfString(CFStringRef(spec
))))
219 if (CFDictionaryRef dict
= makeCFDictionaryFrom(data
))
220 resourceRules
.take(dict
);
221 if (!resourceRules
) // embedded rules present but unacceptable
222 MacOSError::throwMe(errSecCSResourceRulesInvalid
);
225 // if we got one from anywhere (but the defaults), sanity-check it
227 CFTypeRef rules
= CFDictionaryGetValue(resourceRules
, CFSTR("rules"));
228 if (!rules
|| CFGetTypeID(rules
) != CFDictionaryGetTypeID())
229 MacOSError::throwMe(errSecCSResourceRulesInvalid
);
232 // finally, ask the DiskRep for its default
234 resourceRules
.take(rep
->defaultResourceRules(state
));
236 // build the resource directory
237 buildResources(rpath
, resourceRules
);
240 // screen and set the signing time
241 CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
242 if (state
.mSigningTime
== CFDateRef(kCFNull
)) {
243 signingTime
= 0; // no time at all
244 } else if (!state
.mSigningTime
) {
245 signingTime
= now
; // default
247 CFAbsoluteTime time
= CFDateGetAbsoluteTime(state
.mSigningTime
);
248 if (time
> now
) // not allowed to post-date a signature
249 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
253 pagesize
= state
.mPageSize
? cfNumber
<size_t>(state
.mPageSize
) : rep
->pageSize(state
);
255 // Timestamping setup
256 CFRef
<SecIdentityRef
> mTSAuth
; // identity for client-side authentication to the Timestamp server
261 // Collect the resource seal for a program.
262 // This includes both sealed resources and information about nested code.
264 void SecCodeSigner::Signer::buildResources(std::string root
, CFDictionaryRef rulesDict
)
266 typedef ResourceBuilder::Rule Rule
;
268 secdebug("codesign", "start building resource directory");
269 __block CFRef
<CFMutableDictionaryRef
> result
= makeCFMutableDictionary();
271 CFDictionaryRef rules
= cfget
<CFDictionaryRef
>(rulesDict
, "rules");
274 CFDictionaryRef files2
= NULL
;
275 if (!(state
.signingFlags() & kSecCSSignV1
)) {
276 CFCopyRef
<CFDictionaryRef
> rules2
= cfget
<CFDictionaryRef
>(rulesDict
, "rules2");
278 // Clone V1 rules and add default nesting rules at weight 0 (overridden by anything in rules).
279 // V1 rules typically do not cover these places so we'll prevail, but if they do, we defer to them.
280 rules2
= cfmake
<CFDictionaryRef
>("{+%O"
281 "'^[^/]+$' = {top=#T, weight=0}" // files directly in Contents
282 "'^(Frameworks|SharedFrameworks|Plugins|Plug-ins|XPCServices|Helpers|MacOS)/' = {nested=#T, weight=0}" // exclude dynamic repositories
285 // build the modern (V2) resource seal
286 __block CFRef
<CFMutableDictionaryRef
> files
= makeCFMutableDictionary();
287 ResourceBuilder
resourceBuilder(root
, rules2
, digestAlgorithm());
288 ResourceBuilder
&resources
= resourceBuilder
; // (into block)
289 rep
->adjustResources(resources
);
290 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const char *relpath
, Rule
*rule
) {
291 CFRef
<CFMutableDictionaryRef
> seal
;
292 if (ruleFlags
& ResourceBuilder::nested
) {
293 seal
.take(signNested(ent
, relpath
));
294 } else if (ent
->fts_info
== FTS_SL
) {
295 char target
[PATH_MAX
];
296 ssize_t len
= ::readlink(ent
->fts_accpath
, target
, sizeof(target
)-1);
298 UnixError::check(-1);
300 seal
.take(cfmake
<CFMutableDictionaryRef
>("{symlink=%s}", target
));
302 seal
.take(cfmake
<CFMutableDictionaryRef
>("{hash=%O}",
303 CFRef
<CFDataRef
>(resources
.hashFile(ent
->fts_accpath
)).get()));
305 if (ruleFlags
& ResourceBuilder::optional
)
306 CFDictionaryAddValue(seal
, CFSTR("optional"), kCFBooleanTrue
);
308 if ((hash
= CFDictionaryGetValue(seal
, CFSTR("hash"))) && CFDictionaryGetCount(seal
) == 1) // simple form
309 CFDictionaryAddValue(files
, CFTempString(relpath
).get(), hash
);
311 CFDictionaryAddValue(files
, CFTempString(relpath
).get(), seal
.get());
313 CFDictionaryAddValue(result
, CFSTR("rules2"), resourceBuilder
.rules());
315 CFDictionaryAddValue(result
, CFSTR("files2"), files2
);
318 CFDictionaryAddValue(result
, CFSTR("rules"), rules
); // preserve V1 rules in any case
319 if (!(state
.signingFlags() & kSecCSSignNoV1
)) {
320 // build the legacy (V1) resource seal
321 __block CFRef
<CFMutableDictionaryRef
> files
= makeCFMutableDictionary();
322 ResourceBuilder
resourceBuilder(root
, rules
, digestAlgorithm());
323 ResourceBuilder
&resources
= resourceBuilder
;
324 rep
->adjustResources(resources
); // DiskRep-specific adjustments
325 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const char *relpath
, Rule
*rule
) {
326 if (ent
->fts_info
== FTS_F
) {
327 CFRef
<CFDataRef
> hash
;
328 if (files2
) // try to get the hash from a previously-made version
329 if (CFTypeRef seal
= CFDictionaryGetValue(files2
, CFTempString(relpath
))) {
330 if (CFGetTypeID(seal
) == CFDataGetTypeID())
331 hash
= CFDataRef(seal
);
333 hash
= CFDataRef(CFDictionaryGetValue(CFDictionaryRef(seal
), CFSTR("hash")));
336 hash
.take(resources
.hashFile(ent
->fts_accpath
));
337 if (ruleFlags
== 0) { // default case - plain hash
338 cfadd(files
, "{%s=%O}", relpath
, hash
.get());
339 secdebug("csresource", "%s added simple (rule %p)", relpath
, rule
);
340 } else { // more complicated - use a sub-dictionary
341 cfadd(files
, "{%s={hash=%O,optional=%B}}",
342 relpath
, hash
.get(), ruleFlags
& ResourceBuilder::optional
);
343 secdebug("csresource", "%s added complex (rule %p)", relpath
, rule
);
347 CFDictionaryAddValue(result
, CFSTR("files"), files
.get());
350 resourceDirectory
= result
.get();
351 resourceDictData
.take(makeCFData(resourceDirectory
.get()));
356 // Deal with one piece of nested code
358 CFMutableDictionaryRef
SecCodeSigner::Signer::signNested(FTSENT
*ent
, const char *relpath
)
360 // sign nested code and collect nesting information
362 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(ent
->fts_path
));
363 if (state
.signingFlags() & kSecCSSignNestedCode
)
364 this->state
.sign(code
, state
.signingFlags());
365 std::string dr
= Dumper::dump(code
->designatedRequirement());
366 return cfmake
<CFMutableDictionaryRef
>("{requirement=%s,cdhash=%O}",
367 Dumper::dump(code
->designatedRequirement()).c_str(),
369 } catch (const CommonError
&err
) {
370 CSError::throwMe(err
.osStatus(), kSecCFErrorPath
, CFTempURL(relpath
, false, this->code
->resourceBase()));
376 // Sign a Mach-O binary, using liberal dollops of that special Mach-O magic sauce.
377 // Note that this will deal just fine with non-fat Mach-O binaries, but it will
378 // treat them as architectural binaries containing (only) one architecture - that
379 // interpretation is courtesy of the Universal/MachO support classes.
381 void SecCodeSigner::Signer::signMachO(Universal
*fat
, const Requirement::Context
&context
)
383 // Mach-O executable at the core - perform multi-architecture signing
384 auto_ptr
<ArchEditor
> editor(state
.mDetached
385 ? static_cast<ArchEditor
*>(new BlobEditor(*fat
, *this))
386 : new MachOEditor(rep
->writer(), *fat
, this->digestAlgorithm(), rep
->mainExecutablePath()));
387 assert(editor
->count() > 0);
388 if (!editor
->attribute(writerNoGlobal
)) // can store architecture-common components
391 // pass 1: prepare signature blobs and calculate sizes
392 for (MachOEditor::Iterator it
= editor
->begin(); it
!= editor
->end(); ++it
) {
393 MachOEditor::Arch
&arch
= *it
->second
;
394 arch
.source
.reset(fat
->architecture(it
->first
));
395 arch
.ireqs(requirements
, rep
->defaultRequirements(&arch
.architecture
, state
), context
);
396 if (editor
->attribute(writerNoGlobal
)) // can't store globally, add per-arch
398 populate(arch
.cdbuilder
, arch
, arch
.ireqs
,
399 arch
.source
->offset(), arch
.source
->signingExtent());
401 // add identification blob (made from this architecture) only if we're making a detached signature
402 if (state
.mDetached
) {
403 CFRef
<CFDataRef
> identification
= MachORep::identificationFor(arch
.source
.get());
404 arch
.add(cdIdentificationSlot
, BlobWrapper::alloc(
405 CFDataGetBytePtr(identification
), CFDataGetLength(identification
)));
408 // prepare SuperBlob size estimate
409 size_t cdSize
= arch
.cdbuilder
.size(CodeDirectory::currentVersion
);
410 arch
.blobSize
= arch
.size(cdSize
, state
.mCMSSize
, 0);
415 // pass 2: Finish and generate signatures, and write them
416 for (MachOEditor::Iterator it
= editor
->begin(); it
!= editor
->end(); ++it
) {
417 MachOEditor::Arch
&arch
= *it
->second
;
420 // finish CodeDirectory (off new binary) and sign it
421 CodeDirectory
*cd
= arch
.cdbuilder
.build();
422 CFRef
<CFDataRef
> signature
= signCodeDirectory(cd
);
424 // complete the SuperBlob
425 arch
.add(cdCodeDirectorySlot
, cd
); // takes ownership
426 arch
.add(cdSignatureSlot
, BlobWrapper::alloc(
427 CFDataGetBytePtr(signature
), CFDataGetLength(signature
)));
428 if (!state
.mDryRun
) {
429 EmbeddedSignatureBlob
*blob
= arch
.make();
430 editor
->write(arch
, blob
); // takes ownership of blob
434 // done: write edit copy back over the original
441 // Sign a binary that has no notion of architecture.
442 // That currently means anything that isn't Mach-O format.
444 void SecCodeSigner::Signer::signArchitectureAgnostic(const Requirement::Context
&context
)
446 // non-Mach-O executable - single-instance signing
447 RefPointer
<DiskRep::Writer
> writer
= state
.mDetached
?
448 (new DetachedBlobWriter(*this)) : rep
->writer();
449 CodeDirectory::Builder
builder(state
.mDigestAlgorithm
);
450 InternalRequirements ireqs
;
451 ireqs(requirements
, rep
->defaultRequirements(NULL
, state
), context
);
453 populate(builder
, *writer
, ireqs
, rep
->signingBase(), rep
->signingLimit());
455 // add identification blob (made from this architecture) only if we're making a detached signature
456 if (state
.mDetached
) {
457 CFRef
<CFDataRef
> identification
= rep
->identification();
458 writer
->component(cdIdentificationSlot
, identification
);
461 CodeDirectory
*cd
= builder
.build();
462 CFRef
<CFDataRef
> signature
= signCodeDirectory(cd
);
463 if (!state
.mDryRun
) {
464 writer
->codeDirectory(cd
);
465 writer
->signature(signature
);
473 // Global populate - send components to destination buffers ONCE
475 void SecCodeSigner::Signer::populate(DiskRep::Writer
&writer
)
477 if (resourceDirectory
&& !state
.mDryRun
)
478 writer
.component(cdResourceDirSlot
, resourceDictData
);
483 // Per-architecture populate - send components to per-architecture buffers
484 // and populate the CodeDirectory for an architecture. In architecture-agnostic
485 // signing operations, the non-architectural binary is considered one (arbitrary) architecture
486 // for the purposes of this call.
488 void SecCodeSigner::Signer::populate(CodeDirectory::Builder
&builder
, DiskRep::Writer
&writer
,
489 InternalRequirements
&ireqs
, size_t offset
/* = 0 */, size_t length
/* = 0 */)
491 // fill the CodeDirectory
492 builder
.executable(rep
->mainExecutablePath(), pagesize
, offset
, length
);
493 builder
.flags(cdFlags
);
494 builder
.identifier(identifier
);
495 builder
.teamID(teamID
);
497 if (CFRef
<CFDataRef
> data
= rep
->component(cdInfoSlot
))
498 builder
.specialSlot(cdInfoSlot
, data
);
500 CFRef
<CFDataRef
> data
= makeCFData(*ireqs
);
501 writer
.component(cdRequirementsSlot
, data
);
502 builder
.specialSlot(cdRequirementsSlot
, data
);
504 if (resourceDirectory
)
505 builder
.specialSlot(cdResourceDirSlot
, resourceDictData
);
507 if (state
.mApplicationData
)
508 builder
.specialSlot(cdApplicationSlot
, state
.mApplicationData
);
511 writer
.component(cdEntitlementSlot
, entitlements
);
512 builder
.specialSlot(cdEntitlementSlot
, entitlements
);
515 writer
.addDiscretionary(builder
);
518 #include <security_smime/tsaSupport.h>
521 // Generate the CMS signature for a (finished) CodeDirectory.
523 CFDataRef
SecCodeSigner::Signer::signCodeDirectory(const CodeDirectory
*cd
)
525 assert(state
.mSigner
);
526 CFRef
<CFMutableDictionaryRef
> defaultTSContext
= NULL
;
528 // a null signer generates a null signature blob
529 if (state
.mSigner
== SecIdentityRef(kCFNull
))
530 return CFDataCreate(NULL
, NULL
, 0);
532 // generate CMS signature
533 CFRef
<CMSEncoderRef
> cms
;
534 MacOSError::check(CMSEncoderCreate(&cms
.aref()));
535 MacOSError::check(CMSEncoderSetCertificateChainMode(cms
, kCMSCertificateChainWithRoot
));
536 CMSEncoderAddSigners(cms
, state
.mSigner
);
537 MacOSError::check(CMSEncoderSetHasDetachedContent(cms
, true));
540 MacOSError::check(CMSEncoderAddSignedAttributes(cms
, kCMSAttrSigningTime
));
541 MacOSError::check(CMSEncoderSetSigningTime(cms
, signingTime
));
544 MacOSError::check(CMSEncoderUpdateContent(cms
, cd
, cd
->length()));
546 // Set up to call Timestamp server if requested
548 if (state
.mWantTimeStamp
)
550 CFRef
<CFErrorRef
> error
= NULL
;
551 defaultTSContext
= SecCmsTSAGetDefaultContext(&error
.aref());
553 MacOSError::throwMe(errSecDataNotAvailable
);
555 if (state
.mNoTimeStampCerts
|| state
.mTimestampService
) {
556 if (state
.mTimestampService
)
557 CFDictionarySetValue(defaultTSContext
, kTSAContextKeyURL
, state
.mTimestampService
);
558 if (state
.mNoTimeStampCerts
)
559 CFDictionarySetValue(defaultTSContext
, kTSAContextKeyNoCerts
, kCFBooleanTrue
);
562 CmsMessageSetTSAContext(cms
, defaultTSContext
);
566 MacOSError::check(CMSEncoderCopyEncodedContent(cms
, &signature
));
573 // Parse a text of the form
575 // where each flag is the canonical name of a signable CodeDirectory flag.
576 // No abbreviations are allowed, and internally set flags are not accepted.
578 uint32_t SecCodeSigner::Signer::cdTextFlags(std::string text
)
581 for (string::size_type comma
= text
.find(','); ; text
= text
.substr(comma
+1), comma
= text
.find(',')) {
582 string word
= (comma
== string::npos
) ? text
: text
.substr(0, comma
);
583 const SecCodeDirectoryFlagTable
*item
;
584 for (item
= kSecCodeDirectoryFlagTable
; item
->name
; item
++)
585 if (item
->signable
&& word
== item
->name
) {
586 flags
|= item
->value
;
589 if (!item
->name
) // not found
590 MacOSError::throwMe(errSecCSInvalidFlags
);
591 if (comma
== string::npos
) // last word
599 // Generate a unique string from our underlying DiskRep.
600 // We could get 90%+ of the uniquing benefit by just generating
601 // a random string here. Instead, we pick the (hex string encoding of)
602 // the source rep's unique identifier blob. For universal binaries,
603 // this is the canonical local architecture, which is a bit arbitrary.
604 // This provides us with a consistent unique string for all architectures
605 // of a fat binary, *and* (unlike a random string) is reproducible
606 // for identical inputs, even upon resigning.
608 std::string
SecCodeSigner::Signer::uniqueName() const
610 CFRef
<CFDataRef
> identification
= rep
->identification();
611 const UInt8
*ident
= CFDataGetBytePtr(identification
);
612 const CFIndex length
= CFDataGetLength(identification
);
614 for (CFIndex n
= 0; n
< length
; n
++) {
616 snprintf(hex
, sizeof(hex
), "%02x", ident
[n
]);
623 } // end namespace CodeSigning
624 } // end namespace Security