]> git.saurik.com Git - apple/security.git/blob - libsecurity_codesigning/lib/signer.cpp
9b676c339b9d9b5c26c65ae0b0a06f34695d4807
[apple/security.git] / libsecurity_codesigning / lib / signer.cpp
1 /*
2 * Copyright (c) 2006-2010 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // signer - Signing operation supervisor and controller
26 //
27 #include "signer.h"
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"
37 #include "machorep.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>
44
45 namespace Security {
46 namespace CodeSigning {
47
48
49 //
50 // Sign some code.
51 //
52 void SecCodeSigner::Signer::sign(SecCSFlags flags)
53 {
54 rep = code->diskRep()->base();
55 this->prepare(flags);
56
57 PreSigningContext context(*this);
58
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);
62
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);
68 } else {
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;
76 } else {
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);
80 }
81 }
82
83 if (Universal *fat = state.mNoMachO ? NULL : rep->mainExecutableImage()) {
84 signMachO(fat, context);
85 } else {
86 signArchitectureAgnostic(context);
87 }
88 }
89
90
91 //
92 // Remove any existing code signature from code
93 //
94 void SecCodeSigner::Signer::remove(SecCSFlags flags)
95 {
96 // can't remove a detached signature
97 if (state.mDetached)
98 MacOSError::throwMe(errSecCSNotSupported);
99
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
106 } else {
107 // architecture-agnostic removal
108 RefPointer<DiskRep::Writer> writer = rep->writer();
109 writer->remove();
110 writer->flush();
111 }
112 }
113
114
115 //
116 // Contemplate the object-to-be-signed and set up the Signer state accordingly.
117 //
118 void SecCodeSigner::Signer::prepare(SecCSFlags flags)
119 {
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));
124
125 uint32_t inherit = code->isSigned() ? state.mPreserveMetadata : 0;
126
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());
138 } else
139 secdebug("signer", "using explicit identifier=%s", identifier.c_str());
140
141 teamID = state.mTeamID;
142 if (teamID.empty() && (inherit & kSecCodeSignerPreserveTeamIdentifier)) {
143 const char *c_id = code->teamID();
144 if (c_id)
145 teamID = c_id;
146 }
147
148 entitlements = state.mEntitlementData;
149 if (!entitlements && (inherit & kSecCodeSignerPreserveEntitlements))
150 entitlements = code->component(cdEntitlementSlot);
151
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);
157 haveCdFlags = true;
158 }
159 if (!haveCdFlags) {
160 cdFlags = 0;
161 if (infoDict)
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);
169 } else
170 MacOSError::throwMe(errSecCSBadDictionaryFormat);
171 haveCdFlags = true;
172 }
173 }
174 if (!haveCdFlags && (inherit & kSecCodeSignerPreserveFlags)) {
175 cdFlags = code->codeDirectory(false)->flags & ~kSecCodeSignatureAdhoc;
176 secdebug("signer", "using inherited cdFlags=0x%x", cdFlags);
177 haveCdFlags = true;
178 }
179 if (!haveCdFlags)
180 cdFlags = 0;
181 if (state.mSigner == SecIdentityRef(kCFNull)) // ad-hoc signing requested...
182 cdFlags |= kSecCodeSignatureAdhoc; // ... so note that
183
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));
197 } else
198 MacOSError::throwMe(errSecCSInvalidObjectRef);
199 } else if (inherit & kSecCodeSignerPreserveRequirements)
200 if (const Requirements *rp = code->internalRequirements())
201 requirements = rp->clone();
202
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;
208
209 // inherited rules come next (overriding embedded ones!)
210 if (!resourceRules && (inherit & kSecCodeSignerPreserveResourceRules))
211 if (CFDictionaryRef oldRules = code->resourceDictionary(false))
212 resourceRules = oldRules;
213
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);
223 }
224
225 // if we got one from anywhere (but the defaults), sanity-check it
226 if (resourceRules) {
227 CFTypeRef rules = CFDictionaryGetValue(resourceRules, CFSTR("rules"));
228 if (!rules || CFGetTypeID(rules) != CFDictionaryGetTypeID())
229 MacOSError::throwMe(errSecCSResourceRulesInvalid);
230 }
231
232 // finally, ask the DiskRep for its default
233 if (!resourceRules)
234 resourceRules.take(rep->defaultResourceRules(state));
235
236 // build the resource directory
237 buildResources(rpath, resourceRules);
238 }
239
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
246 } else {
247 CFAbsoluteTime time = CFDateGetAbsoluteTime(state.mSigningTime);
248 if (time > now) // not allowed to post-date a signature
249 MacOSError::throwMe(errSecCSBadDictionaryFormat);
250 signingTime = time;
251 }
252
253 pagesize = state.mPageSize ? cfNumber<size_t>(state.mPageSize) : rep->pageSize(state);
254
255 // Timestamping setup
256 CFRef<SecIdentityRef> mTSAuth; // identity for client-side authentication to the Timestamp server
257 }
258
259
260 //
261 // Collect the resource seal for a program.
262 // This includes both sealed resources and information about nested code.
263 //
264 void SecCodeSigner::Signer::buildResources(std::string root, CFDictionaryRef rulesDict)
265 {
266 typedef ResourceBuilder::Rule Rule;
267
268 secdebug("codesign", "start building resource directory");
269 __block CFRef<CFMutableDictionaryRef> result = makeCFMutableDictionary();
270
271 CFDictionaryRef rules = cfget<CFDictionaryRef>(rulesDict, "rules");
272 assert(rules);
273
274 CFDictionaryRef files2 = NULL;
275 if (!(state.signingFlags() & kSecCSSignV1)) {
276 CFCopyRef<CFDictionaryRef> rules2 = cfget<CFDictionaryRef>(rulesDict, "rules2");
277 if (!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
283 "}", rules);
284 }
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);
297 if (len < 0)
298 UnixError::check(-1);
299 target[len] = '\0';
300 seal.take(cfmake<CFMutableDictionaryRef>("{symlink=%s}", target));
301 } else {
302 seal.take(cfmake<CFMutableDictionaryRef>("{hash=%O}",
303 CFRef<CFDataRef>(resources.hashFile(ent->fts_accpath)).get()));
304 }
305 if (ruleFlags & ResourceBuilder::optional)
306 CFDictionaryAddValue(seal, CFSTR("optional"), kCFBooleanTrue);
307 CFTypeRef hash;
308 if ((hash = CFDictionaryGetValue(seal, CFSTR("hash"))) && CFDictionaryGetCount(seal) == 1) // simple form
309 CFDictionaryAddValue(files, CFTempString(relpath).get(), hash);
310 else
311 CFDictionaryAddValue(files, CFTempString(relpath).get(), seal.get());
312 });
313 CFDictionaryAddValue(result, CFSTR("rules2"), resourceBuilder.rules());
314 files2 = files;
315 CFDictionaryAddValue(result, CFSTR("files2"), files2);
316 }
317
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);
332 else
333 hash = CFDataRef(CFDictionaryGetValue(CFDictionaryRef(seal), CFSTR("hash")));
334 }
335 if (!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);
344 }
345 }
346 });
347 CFDictionaryAddValue(result, CFSTR("files"), files.get());
348 }
349
350 resourceDirectory = result.get();
351 resourceDictData.take(makeCFData(resourceDirectory.get()));
352 }
353
354
355 //
356 // Deal with one piece of nested code
357 //
358 CFMutableDictionaryRef SecCodeSigner::Signer::signNested(FTSENT *ent, const char *relpath)
359 {
360 // sign nested code and collect nesting information
361 try {
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(),
368 code->cdHash());
369 } catch (const CommonError &err) {
370 CSError::throwMe(err.osStatus(), kSecCFErrorPath, CFTempURL(relpath, false, this->code->resourceBase()));
371 }
372 }
373
374
375 //
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.
380 //
381 void SecCodeSigner::Signer::signMachO(Universal *fat, const Requirement::Context &context)
382 {
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
389 populate(*editor);
390
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
397 populate(arch);
398 populate(arch.cdbuilder, arch, arch.ireqs,
399 arch.source->offset(), arch.source->signingExtent());
400
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)));
406 }
407
408 // prepare SuperBlob size estimate
409 size_t cdSize = arch.cdbuilder.size(CodeDirectory::currentVersion);
410 arch.blobSize = arch.size(cdSize, state.mCMSSize, 0);
411 }
412
413 editor->allocate();
414
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;
418 editor->reset(arch);
419
420 // finish CodeDirectory (off new binary) and sign it
421 CodeDirectory *cd = arch.cdbuilder.build();
422 CFRef<CFDataRef> signature = signCodeDirectory(cd);
423
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
431 }
432 }
433
434 // done: write edit copy back over the original
435 if (!state.mDryRun)
436 editor->commit();
437 }
438
439
440 //
441 // Sign a binary that has no notion of architecture.
442 // That currently means anything that isn't Mach-O format.
443 //
444 void SecCodeSigner::Signer::signArchitectureAgnostic(const Requirement::Context &context)
445 {
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);
452 populate(*writer);
453 populate(builder, *writer, ireqs, rep->signingBase(), rep->signingLimit());
454
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);
459 }
460
461 CodeDirectory *cd = builder.build();
462 CFRef<CFDataRef> signature = signCodeDirectory(cd);
463 if (!state.mDryRun) {
464 writer->codeDirectory(cd);
465 writer->signature(signature);
466 writer->flush();
467 }
468 ::free(cd);
469 }
470
471
472 //
473 // Global populate - send components to destination buffers ONCE
474 //
475 void SecCodeSigner::Signer::populate(DiskRep::Writer &writer)
476 {
477 if (resourceDirectory && !state.mDryRun)
478 writer.component(cdResourceDirSlot, resourceDictData);
479 }
480
481
482 //
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.
487 //
488 void SecCodeSigner::Signer::populate(CodeDirectory::Builder &builder, DiskRep::Writer &writer,
489 InternalRequirements &ireqs, size_t offset /* = 0 */, size_t length /* = 0 */)
490 {
491 // fill the CodeDirectory
492 builder.executable(rep->mainExecutablePath(), pagesize, offset, length);
493 builder.flags(cdFlags);
494 builder.identifier(identifier);
495 builder.teamID(teamID);
496
497 if (CFRef<CFDataRef> data = rep->component(cdInfoSlot))
498 builder.specialSlot(cdInfoSlot, data);
499 if (ireqs) {
500 CFRef<CFDataRef> data = makeCFData(*ireqs);
501 writer.component(cdRequirementsSlot, data);
502 builder.specialSlot(cdRequirementsSlot, data);
503 }
504 if (resourceDirectory)
505 builder.specialSlot(cdResourceDirSlot, resourceDictData);
506 #if NOT_YET
507 if (state.mApplicationData)
508 builder.specialSlot(cdApplicationSlot, state.mApplicationData);
509 #endif
510 if (entitlements) {
511 writer.component(cdEntitlementSlot, entitlements);
512 builder.specialSlot(cdEntitlementSlot, entitlements);
513 }
514
515 writer.addDiscretionary(builder);
516 }
517
518 #include <security_smime/tsaSupport.h>
519
520 //
521 // Generate the CMS signature for a (finished) CodeDirectory.
522 //
523 CFDataRef SecCodeSigner::Signer::signCodeDirectory(const CodeDirectory *cd)
524 {
525 assert(state.mSigner);
526 CFRef<CFMutableDictionaryRef> defaultTSContext = NULL;
527
528 // a null signer generates a null signature blob
529 if (state.mSigner == SecIdentityRef(kCFNull))
530 return CFDataCreate(NULL, NULL, 0);
531
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));
538
539 if (signingTime) {
540 MacOSError::check(CMSEncoderAddSignedAttributes(cms, kCMSAttrSigningTime));
541 MacOSError::check(CMSEncoderSetSigningTime(cms, signingTime));
542 }
543
544 MacOSError::check(CMSEncoderUpdateContent(cms, cd, cd->length()));
545
546 // Set up to call Timestamp server if requested
547
548 if (state.mWantTimeStamp)
549 {
550 CFRef<CFErrorRef> error = NULL;
551 defaultTSContext = SecCmsTSAGetDefaultContext(&error.aref());
552 if (error)
553 MacOSError::throwMe(errSecDataNotAvailable);
554
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);
560 }
561
562 CmsMessageSetTSAContext(cms, defaultTSContext);
563 }
564
565 CFDataRef signature;
566 MacOSError::check(CMSEncoderCopyEncodedContent(cms, &signature));
567
568 return signature;
569 }
570
571
572 //
573 // Parse a text of the form
574 // flag,...,flag
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.
577 //
578 uint32_t SecCodeSigner::Signer::cdTextFlags(std::string text)
579 {
580 uint32_t flags = 0;
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;
587 break;
588 }
589 if (!item->name) // not found
590 MacOSError::throwMe(errSecCSInvalidFlags);
591 if (comma == string::npos) // last word
592 break;
593 }
594 return flags;
595 }
596
597
598 //
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.
607 //
608 std::string SecCodeSigner::Signer::uniqueName() const
609 {
610 CFRef<CFDataRef> identification = rep->identification();
611 const UInt8 *ident = CFDataGetBytePtr(identification);
612 const CFIndex length = CFDataGetLength(identification);
613 string result;
614 for (CFIndex n = 0; n < length; n++) {
615 char hex[3];
616 snprintf(hex, sizeof(hex), "%02x", ident[n]);
617 result += hex;
618 }
619 return result;
620 }
621
622
623 } // end namespace CodeSigning
624 } // end namespace Security