1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include <sys/types.h>
46 #include <openssl/err.h>
47 #include <openssl/pem.h>
48 #include <openssl/pkcs7.h>
49 #include <openssl/pkcs12.h>
53 #include <CommonCrypto/CommonDigest.h>
55 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56 #define LDID_SHA1 CC_SHA1
57 #define LDID_SHA1_CTX CC_SHA1_CTX
58 #define LDID_SHA1_Init CC_SHA1_Init
59 #define LDID_SHA1_Update CC_SHA1_Update
60 #define LDID_SHA1_Final CC_SHA1_Final
62 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63 #define LDID_SHA256 CC_SHA256
64 #define LDID_SHA256_CTX CC_SHA256_CTX
65 #define LDID_SHA256_Init CC_SHA256_Init
66 #define LDID_SHA256_Update CC_SHA256_Update
67 #define LDID_SHA256_Final CC_SHA256_Final
69 #include <openssl/sha.h>
71 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72 #define LDID_SHA1 SHA1
73 #define LDID_SHA1_CTX SHA_CTX
74 #define LDID_SHA1_Init SHA1_Init
75 #define LDID_SHA1_Update SHA1_Update
76 #define LDID_SHA1_Final SHA1_Final
78 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79 #define LDID_SHA256 SHA256
80 #define LDID_SHA256_CTX SHA256_CTX
81 #define LDID_SHA256_Init SHA256_Init
82 #define LDID_SHA256_Update SHA256_Update
83 #define LDID_SHA256_Final SHA256_Final
87 #include <plist/plist.h>
89 #include <CoreFoundation/CoreFoundation.h>
94 #define _assert___(line) \
96 #define _assert__(line) \
100 #define $(value) value
104 #define _assert_(expr, format, ...) \
106 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
107 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
110 // XXX: this is not acceptable
111 #define _assert_(expr, format, ...) \
113 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
118 #define _assert(expr) \
119 _assert_(expr, "%s", $(#expr))
121 #define _syscall(expr, ...) [&] { for (;;) { \
123 if ((long) _value != -1) \
126 if (error == EINTR) \
128 /* XXX: EINTR is included in this list to fix g++ */ \
129 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
130 if (error == success) \
131 return (decltype(expr)) -success; \
132 _assert_(false, "errno=%u", error); \
136 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
142 __attribute__((packed))
144 template <typename Type_
>
146 typedef typename
Type_::const_iterator Result
;
149 #define _foreach(item, list) \
150 for (bool _stop(true); _stop; ) \
151 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
152 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
153 for (bool _suck(true); _suck; _suck = false) \
154 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
159 template <typename Function_
>
167 Scope(const Function_
&function
) :
177 template <typename Function_
>
178 Scope
<Function_
> _scope(const Function_
&function
) {
179 return Scope
<Function_
>(function
);
182 #define _scope__(counter, function) \
183 __attribute__((__unused__)) \
184 const _Scope &_scope ## counter(_scope([&]function))
185 #define _scope_(counter, function) \
186 _scope__(counter, function)
187 #define _scope(function) \
188 _scope_(__COUNTER__, function)
190 #define CPU_ARCH_MASK uint32_t(0xff000000)
191 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
193 #define CPU_TYPE_ANY uint32_t(-1)
194 #define CPU_TYPE_VAX uint32_t( 1)
195 #define CPU_TYPE_MC680x0 uint32_t( 6)
196 #define CPU_TYPE_X86 uint32_t( 7)
197 #define CPU_TYPE_MC98000 uint32_t(10)
198 #define CPU_TYPE_HPPA uint32_t(11)
199 #define CPU_TYPE_ARM uint32_t(12)
200 #define CPU_TYPE_MC88000 uint32_t(13)
201 #define CPU_TYPE_SPARC uint32_t(14)
202 #define CPU_TYPE_I860 uint32_t(15)
203 #define CPU_TYPE_POWERPC uint32_t(18)
205 #define CPU_TYPE_I386 CPU_TYPE_X86
207 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
208 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
209 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
216 #define FAT_MAGIC 0xcafebabe
217 #define FAT_CIGAM 0xbebafeca
237 #define MH_MAGIC 0xfeedface
238 #define MH_CIGAM 0xcefaedfe
240 #define MH_MAGIC_64 0xfeedfacf
241 #define MH_CIGAM_64 0xcffaedfe
243 #define MH_DYLDLINK 0x4
245 #define MH_OBJECT 0x1
246 #define MH_EXECUTE 0x2
248 #define MH_DYLINKER 0x7
249 #define MH_BUNDLE 0x8
250 #define MH_DYLIB_STUB 0x9
252 struct load_command
{
257 #define LC_REQ_DYLD uint32_t(0x80000000)
259 #define LC_SEGMENT uint32_t(0x01)
260 #define LC_SYMTAB uint32_t(0x02)
261 #define LC_DYSYMTAB uint32_t(0x0b)
262 #define LC_LOAD_DYLIB uint32_t(0x0c)
263 #define LC_ID_DYLIB uint32_t(0x0d)
264 #define LC_SEGMENT_64 uint32_t(0x19)
265 #define LC_UUID uint32_t(0x1b)
266 #define LC_CODE_SIGNATURE uint32_t(0x1d)
267 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
268 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
269 #define LC_ENCRYPTION_INFO uint32_t(0x21)
270 #define LC_DYLD_INFO uint32_t(0x22)
271 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
272 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
287 uint32_t current_version
;
288 uint32_t compatibility_version
;
291 struct dylib_command
{
297 struct uuid_command
{
303 struct symtab_command
{
312 struct dyld_info_command
{
316 uint32_t rebase_size
;
319 uint32_t weak_bind_off
;
320 uint32_t weak_bind_size
;
321 uint32_t lazy_bind_off
;
322 uint32_t lazy_bind_size
;
324 uint32_t export_size
;
327 struct dysymtab_command
{
340 uint32_t extrefsymoff
;
341 uint32_t nextrefsyms
;
342 uint32_t indirectsymoff
;
343 uint32_t nindirectsyms
;
350 struct dylib_table_of_contents
{
351 uint32_t symbol_index
;
352 uint32_t module_index
;
355 struct dylib_module
{
356 uint32_t module_name
;
365 uint32_t iinit_iterm
;
366 uint32_t ninit_nterm
;
367 uint32_t objc_module_info_addr
;
368 uint32_t objc_module_info_size
;
371 struct dylib_reference
{
376 struct relocation_info
{
378 uint32_t r_symbolnum
:24;
397 struct segment_command
{
411 struct segment_command_64
{
454 struct linkedit_data_command
{
461 struct encryption_info_command
{
469 #define BIND_OPCODE_MASK 0xf0
470 #define BIND_IMMEDIATE_MASK 0x0f
471 #define BIND_OPCODE_DONE 0x00
472 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
473 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
474 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
475 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
476 #define BIND_OPCODE_SET_TYPE_IMM 0x50
477 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
478 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
479 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
480 #define BIND_OPCODE_DO_BIND 0x90
481 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
482 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
483 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
485 struct : ldid::Progress
{
486 virtual void operator()(const std::string
&value
) const {
489 virtual void operator()(double value
) const {
493 struct Progression
: ldid::Progress
{
494 const ldid::Progress
&progress_
;
497 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
503 virtual void operator()(const std::string
&value
) const {
504 return progress_(name_
+ " (" + value
+ ")");
507 virtual void operator()(double value
) const {
508 return progress_(value
);
512 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
513 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
518 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
519 _assert(read(stream
, data
, size
) == size
);
522 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
523 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
526 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
528 for (size_t total(0); total
!= size
;) {
529 auto writ(std::min(size
- total
, size_t(4096 * 4)));
530 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
532 progress(double(total
) / size
);
536 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
539 if (auto writ
= read(stream
, data
, size
))
545 static inline void pad(std::streambuf
&stream
, size_t size
) {
547 memset(padding
, 0, size
);
548 put(stream
, padding
, size
);
551 template <typename Type_
>
552 Type_
Align(Type_ value
, size_t align
) {
559 static const uint8_t PageShift_(0x0c);
560 static const uint32_t PageSize_(1 << PageShift_
);
562 static inline uint16_t Swap_(uint16_t value
) {
564 ((value
>> 8) & 0x00ff) |
565 ((value
<< 8) & 0xff00);
568 static inline uint32_t Swap_(uint32_t value
) {
569 value
= ((value
>> 8) & 0x00ff00ff) |
570 ((value
<< 8) & 0xff00ff00);
571 value
= ((value
>> 16) & 0x0000ffff) |
572 ((value
<< 16) & 0xffff0000);
576 static inline uint64_t Swap_(uint64_t value
) {
577 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
578 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
579 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
583 static inline int16_t Swap_(int16_t value
) {
584 return Swap_(static_cast<uint16_t>(value
));
587 static inline int32_t Swap_(int32_t value
) {
588 return Swap_(static_cast<uint32_t>(value
));
591 static inline int64_t Swap_(int64_t value
) {
592 return Swap_(static_cast<uint64_t>(value
));
595 static bool little_(true);
597 static inline uint16_t Swap(uint16_t value
) {
598 return little_
? Swap_(value
) : value
;
601 static inline uint32_t Swap(uint32_t value
) {
602 return little_
? Swap_(value
) : value
;
605 static inline uint64_t Swap(uint64_t value
) {
606 return little_
? Swap_(value
) : value
;
609 static inline int16_t Swap(int16_t value
) {
610 return Swap(static_cast<uint16_t>(value
));
613 static inline int32_t Swap(int32_t value
) {
614 return Swap(static_cast<uint32_t>(value
));
617 static inline int64_t Swap(int64_t value
) {
618 return Swap(static_cast<uint64_t>(value
));
631 Swapped(bool swapped
) :
636 template <typename Type_
>
637 Type_
Swap(Type_ value
) const {
638 return swapped_
? Swap_(value
) : value
;
650 Data(void *base
, size_t size
) :
656 void *GetBase() const {
660 size_t GetSize() const {
671 struct mach_header
*mach_header_
;
672 struct load_command
*load_command_
;
675 MachHeader(void *base
, size_t size
) :
678 mach_header_
= (mach_header
*) base
;
680 switch (Swap(mach_header_
->magic
)) {
682 swapped_
= !swapped_
;
688 swapped_
= !swapped_
;
697 void *post
= mach_header_
+ 1;
699 post
= (uint32_t *) post
+ 1;
700 load_command_
= (struct load_command
*) post
;
703 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
704 Swap(mach_header_
->filetype
) == MH_DYLIB
||
705 Swap(mach_header_
->filetype
) == MH_DYLINKER
||
706 Swap(mach_header_
->filetype
) == MH_BUNDLE
710 bool Bits64() const {
714 struct mach_header
*operator ->() const {
718 operator struct mach_header
*() const {
722 uint32_t GetCPUType() const {
723 return Swap(mach_header_
->cputype
);
726 uint32_t GetCPUSubtype() const {
727 return Swap(mach_header_
->cpusubtype
) & 0xff;
730 struct load_command
*GetLoadCommand() const {
731 return load_command_
;
734 std::vector
<struct load_command
*> GetLoadCommands() const {
735 std::vector
<struct load_command
*> load_commands
;
737 struct load_command
*load_command
= load_command_
;
738 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
739 load_commands
.push_back(load_command
);
740 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
743 return load_commands
;
746 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
747 _foreach (load_command
, GetLoadCommands())
748 switch (Swap(load_command
->cmd
)) {
750 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
751 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
752 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
753 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
754 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
757 case LC_SEGMENT_64
: {
758 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
759 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
760 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
761 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
762 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
767 template <typename Target_
>
768 Target_
*GetOffset(uint32_t offset
) const {
769 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
773 class FatMachHeader
:
780 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
781 MachHeader(base
, size
),
786 fat_arch
*GetFatArch() const {
795 fat_header
*fat_header_
;
796 std::vector
<FatMachHeader
> mach_headers_
;
799 FatHeader(void *base
, size_t size
) :
802 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
804 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
805 swapped_
= !swapped_
;
807 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
809 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
811 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
812 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
814 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
815 uint32_t arch_offset
= Swap(fat_arch
->offset
);
816 uint32_t arch_size
= Swap(fat_arch
->size
);
817 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
823 std::vector
<FatMachHeader
> &GetMachHeaders() {
824 return mach_headers_
;
828 return fat_header_
!= NULL
;
831 struct fat_header
*operator ->() const {
835 operator struct fat_header
*() const {
840 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
841 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
842 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
843 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
844 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
845 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
846 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
847 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
849 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
850 #define CSSLOT_INFOSLOT uint32_t(0x00001)
851 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
852 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
853 #define CSSLOT_APPLICATION uint32_t(0x00004)
854 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
855 #define CSSLOT_ALTERNATE uint32_t(0x01000)
857 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
859 #define CS_HASHTYPE_SHA160_160 1
860 #define CS_HASHTYPE_SHA256_256 2
861 #define CS_HASHTYPE_SHA256_160 3
862 #define CS_HASHTYPE_SHA386_386 4
877 struct BlobIndex index
[];
880 struct CodeDirectory
{
884 uint32_t identOffset
;
885 uint32_t nSpecialSlots
;
893 uint32_t scatterOffset
;
894 uint32_t teamIDOffset
;
896 //uint64_t codeLimit64;
899 enum CodeSignatureFlags
{
900 kSecCodeSignatureHost
= 0x0001,
901 kSecCodeSignatureAdhoc
= 0x0002,
902 kSecCodeSignatureForceHard
= 0x0100,
903 kSecCodeSignatureForceKill
= 0x0200,
904 kSecCodeSignatureForceExpiration
= 0x0400,
905 kSecCodeSignatureRestrict
= 0x0800,
906 kSecCodeSignatureEnforcement
= 0x1000,
907 kSecCodeSignatureLibraryValidation
= 0x2000,
910 enum Kind
: uint32_t {
911 exprForm
= 1, // prefix expr form
914 enum ExprOp
: uint32_t {
915 opFalse
, // unconditionally false
916 opTrue
, // unconditionally true
917 opIdent
, // match canonical code [string]
918 opAppleAnchor
, // signed by Apple as Apple's product
919 opAnchorHash
, // match anchor [cert hash]
920 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
921 opAnd
, // binary prefix expr AND expr [expr; expr]
922 opOr
, // binary prefix expr OR expr [expr; expr]
923 opCDHash
, // match hash of CodeDirectory directly [cd hash]
924 opNot
, // logical inverse [expr]
925 opInfoKeyField
, // Info.plist key field [string; match suffix]
926 opCertField
, // Certificate field [cert index; field name; match suffix]
927 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
928 opTrustedCerts
, // require trust settings to approve the cert chain
929 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
930 opAppleGenericAnchor
, // signed by Apple in any capacity
931 opEntitlementField
, // entitlement dictionary field [string; match suffix]
932 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
933 opNamedAnchor
, // named anchor type
934 opNamedCode
, // named subroutine
935 opPlatform
, // platform constraint [integer]
936 exprOpCount
// (total opcode count in use)
939 enum MatchOperation
{
940 matchExists
, // anything but explicit "false" - no value stored
941 matchEqual
, // equal (CFEqual)
942 matchContains
, // partial match (substring)
943 matchBeginsWith
, // partial match (initial substring)
944 matchEndsWith
, // partial match (terminal substring)
945 matchLessThan
, // less than (string with numeric comparison)
946 matchGreaterThan
, // greater than (string with numeric comparison)
947 matchLessEqual
, // less or equal (string with numeric comparison)
948 matchGreaterEqual
, // greater or equal (string with numeric comparison)
951 #define OID_ISO_MEMBER 42
952 #define OID_US OID_ISO_MEMBER, 134, 72
953 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
954 #define APPLE_ADS_OID APPLE_OID, 0x64
955 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
958 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
965 Algorithm(size_t size
, uint8_t type
) :
971 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
973 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
974 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
975 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
977 virtual const char *name() = 0;
980 struct AlgorithmSHA1
:
984 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
988 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
992 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
993 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
996 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
997 return operator()(hash
.sha1_
, data
, size
);
1000 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1001 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1002 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1005 virtual const char *name() {
1010 struct AlgorithmSHA256
:
1014 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1018 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1019 return hash
.sha256_
;
1022 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1023 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1026 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1027 return operator()(hash
.sha256_
, data
, size
);
1030 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1031 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1032 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1035 virtual const char *name() {
1040 static bool do_sha1(true);
1041 static bool do_sha256(true);
1043 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1044 static AlgorithmSHA1 sha1
;
1045 static AlgorithmSHA256 sha256
;
1047 static std::vector
<Algorithm
*> algorithms
;
1048 if (algorithms
.empty()) {
1050 algorithms
.push_back(&sha1
);
1052 algorithms
.push_back(&sha256
);
1059 std::string entitlements_
;
1062 struct CodesignAllocation
{
1063 FatMachHeader mach_header_
;
1072 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
, const char *arch
, const Baton
&baton
) :
1073 mach_header_(mach_header
),
1085 #ifndef LDID_NOTOOLS
1098 _syscall(close(file_
));
1101 void open(const char *path
, int flags
) {
1102 _assert(file_
== -1);
1103 file_
= _syscall(::open(path
, flags
));
1120 _syscall(munmap(data_
, size_
));
1132 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1135 open(path
, oflag
, pflag
, mflag
);
1138 Map(const std::string
&path
, bool edit
) :
1148 bool empty() const {
1149 return data_
== NULL
;
1152 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1155 file_
.open(path
.c_str(), oflag
);
1156 int file(file_
.file());
1159 _syscall(fstat(file
, &stat
));
1160 size_
= stat
.st_size
;
1162 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1165 void open(const std::string
&path
, bool edit
) {
1167 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1169 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1172 void *data() const {
1176 size_t size() const {
1180 operator std::string() const {
1181 return std::string(static_cast<char *>(data_
), size_
);
1188 #ifndef LDID_NOPLIST
1189 static plist_t
plist(const std::string
&data
);
1192 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1193 _foreach (load_command
, mach_header
.GetLoadCommands())
1194 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1195 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1196 auto offset(mach_header
.Swap(signature
->dataoff
));
1197 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1198 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1200 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1201 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1202 auto begin(Swap(super
->index
[index
].offset
));
1203 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1204 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1205 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1210 std::string
Analyze(const void *data
, size_t size
) {
1211 std::string entitlements
;
1213 FatHeader
fat_header(const_cast<void *>(data
), size
);
1214 _foreach (mach_header
, fat_header
.GetMachHeaders())
1215 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1216 if (entitlements
.empty())
1217 entitlements
.assign(data
, size
);
1219 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1222 return entitlements
;
1225 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, Baton
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, const Baton
&, std::streambuf
&output
, size_t, const std::string
&, const char *, const Progress
&)> &save
, const Progress
&progress
) {
1226 FatHeader
source(const_cast<void *>(idata
), isize
);
1230 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1232 std::vector
<CodesignAllocation
> allocations
;
1233 _foreach (mach_header
, source
.GetMachHeaders()) {
1234 struct linkedit_data_command
*signature(NULL
);
1235 struct symtab_command
*symtab(NULL
);
1237 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1238 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1240 else if (cmd
== LC_CODE_SIGNATURE
)
1241 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1242 else if (cmd
== LC_SYMTAB
)
1243 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1247 if (signature
== NULL
)
1248 size
= mach_header
.GetSize();
1250 size
= mach_header
.Swap(signature
->dataoff
);
1251 _assert(size
<= mach_header
.GetSize());
1254 if (symtab
!= NULL
) {
1255 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1256 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1257 _assert(end
<= size
);
1258 _assert(end
>= size
- 0x10);
1264 size_t alloc(allocate(mach_header
, baton
, size
));
1266 auto *fat_arch(mach_header
.GetFatArch());
1269 if (fat_arch
!= NULL
)
1270 align
= source
.Swap(fat_arch
->align
);
1271 else switch (mach_header
.GetCPUType()) {
1272 case CPU_TYPE_POWERPC
:
1273 case CPU_TYPE_POWERPC64
:
1275 case CPU_TYPE_X86_64
:
1279 case CPU_TYPE_ARM64
:
1287 const char *arch(NULL
);
1288 switch (mach_header
.GetCPUType()) {
1289 case CPU_TYPE_POWERPC
:
1292 case CPU_TYPE_POWERPC64
:
1298 case CPU_TYPE_X86_64
:
1304 case CPU_TYPE_ARM64
:
1309 offset
= Align(offset
, 1 << align
);
1311 uint32_t limit(size
);
1313 limit
= Align(limit
, 0x10);
1315 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1316 offset
+= size
+ alloc
;
1317 offset
= Align(offset
, 0x10);
1322 if (source
.IsFat()) {
1323 fat_header fat_header
;
1324 fat_header
.magic
= Swap(FAT_MAGIC
);
1325 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1326 put(output
, &fat_header
, sizeof(fat_header
));
1327 position
+= sizeof(fat_header
);
1329 _foreach (allocation
, allocations
) {
1330 auto &mach_header(allocation
.mach_header_
);
1333 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1334 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1335 fat_arch
.offset
= Swap(allocation
.offset_
);
1336 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1337 fat_arch
.align
= Swap(allocation
.align_
);
1338 put(output
, &fat_arch
, sizeof(fat_arch
));
1339 position
+= sizeof(fat_arch
);
1343 _foreach (allocation
, allocations
) {
1344 progress(allocation
.arch_
);
1345 auto &mach_header(allocation
.mach_header_
);
1347 pad(output
, allocation
.offset_
- position
);
1348 position
= allocation
.offset_
;
1350 std::vector
<std::string
> commands
;
1352 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1353 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1355 switch (mach_header
.Swap(load_command
->cmd
)) {
1356 case LC_CODE_SIGNATURE
:
1361 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1362 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1364 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1365 segment_command
->filesize
= size
;
1366 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1369 case LC_SEGMENT_64
: {
1370 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1371 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1373 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1374 segment_command
->filesize
= size
;
1375 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1379 commands
.push_back(copy
);
1382 if (allocation
.alloc_
!= 0) {
1383 linkedit_data_command signature
;
1384 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1385 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1386 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1387 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1388 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1391 size_t begin(position
);
1394 _foreach(command
, commands
)
1395 after
+= command
.size();
1397 std::stringbuf altern
;
1399 struct mach_header
header(*mach_header
);
1400 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1401 header
.sizeofcmds
= mach_header
.Swap(after
);
1402 put(output
, &header
, sizeof(header
));
1403 put(altern
, &header
, sizeof(header
));
1404 position
+= sizeof(header
);
1406 if (mach_header
.Bits64()) {
1407 auto pad(mach_header
.Swap(uint32_t(0)));
1408 put(output
, &pad
, sizeof(pad
));
1409 put(altern
, &pad
, sizeof(pad
));
1410 position
+= sizeof(pad
);
1413 _foreach(command
, commands
) {
1414 put(output
, command
.data(), command
.size());
1415 put(altern
, command
.data(), command
.size());
1416 position
+= command
.size();
1419 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1420 if (before
> after
) {
1421 pad(output
, before
- after
);
1422 pad(altern
, before
- after
);
1423 position
+= before
- after
;
1426 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1428 std::string
overlap(altern
.str());
1429 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1431 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1432 position
= begin
+ allocation
.size_
;
1434 pad(output
, allocation
.limit_
- allocation
.size_
);
1435 position
+= allocation
.limit_
- allocation
.size_
;
1437 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, overlap
, top
, progress
));
1438 if (allocation
.alloc_
> saved
)
1439 pad(output
, allocation
.alloc_
- saved
);
1441 _assert(allocation
.alloc_
== saved
);
1442 position
+= allocation
.alloc_
;
1448 typedef std::map
<uint32_t, std::string
> Blobs
;
1450 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1451 auto value(buffer
.str());
1452 std::swap(blobs
[slot
], value
);
1455 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1456 auto value(buffer
.str());
1458 blob
.magic
= Swap(magic
);
1459 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1460 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1461 auto &save(blobs
[slot
]);
1462 std::swap(save
, value
);
1466 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1468 _foreach (blob
, blobs
)
1469 total
+= blob
.second
.size();
1471 struct SuperBlob super
;
1472 super
.blob
.magic
= Swap(magic
);
1473 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1474 super
.count
= Swap(uint32_t(blobs
.size()));
1475 put(output
, &super
, sizeof(super
));
1477 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1479 _foreach (blob
, blobs
) {
1481 index
.type
= Swap(blob
.first
);
1482 index
.offset
= Swap(uint32_t(offset
));
1483 put(output
, &index
, sizeof(index
));
1484 offset
+= blob
.second
.size();
1487 _foreach (blob
, blobs
)
1488 put(output
, blob
.second
.data(), blob
.second
.size());
1493 #ifndef LDID_NOSMIME
1502 _assert(bio_
!= NULL
);
1506 bio_(BIO_new(BIO_s_mem()))
1510 Buffer(const char *data
, size_t size
) :
1511 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1515 Buffer(const std::string
&data
) :
1516 Buffer(data
.data(), data
.size())
1520 Buffer(PKCS7
*pkcs
) :
1523 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1530 operator BIO
*() const {
1534 explicit operator std::string() const {
1536 auto size(BIO_get_mem_data(bio_
, &data
));
1537 return std::string(data
, size
);
1546 STACK_OF(X509
) *ca_
;
1550 value_(d2i_PKCS12_bio(bio
, NULL
)),
1553 _assert(value_
!= NULL
);
1554 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1556 _assert(key_
!= NULL
);
1557 _assert(cert_
!= NULL
);
1560 ca_
= sk_X509_new_null();
1561 _assert(ca_
!= NULL
);
1564 Stuff(const std::string
&data
) :
1570 sk_X509_pop_free(ca_
, X509_free
);
1572 EVP_PKEY_free(key_
);
1573 PKCS12_free(value_
);
1576 operator PKCS12
*() const {
1580 operator EVP_PKEY
*() const {
1584 operator X509
*() const {
1588 operator STACK_OF(X509
) *() const {
1598 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1599 value_
= PKCS7_new();
1600 _assert(value_
!= NULL
);
1602 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1603 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1605 STACK_OF(X509
) *certs(stuff
);
1606 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1607 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1609 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1610 _assert(X509_check_private_key(stuff
, stuff
));
1611 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1612 _assert(info
!= NULL
);
1613 _assert(PKCS7_add_certificate(value_
, stuff
));
1614 _assert(PKCS7_add_signed_attribute(info
, NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1616 PKCS7_set_detached(value_
, 1);
1618 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1619 _assert(string
!= NULL
);
1621 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1623 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1624 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1626 ASN1_OCTET_STRING_free(string
);
1630 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1631 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1632 _assert(bio
!= NULL
);
1633 _scope({ BIO_free_all(bio
); });
1634 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1636 _assert(PKCS7_dataFinal(value_
, bio
));
1643 operator PKCS7
*() const {
1650 public std::streambuf
1653 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1657 virtual int_type
overflow(int_type next
) {
1663 public std::streambuf
1668 LDID_SHA1_CTX sha1_
;
1669 LDID_SHA256_CTX sha256_
;
1672 HashBuffer(ldid::Hash
&hash
) :
1675 LDID_SHA1_Init(&sha1_
);
1676 LDID_SHA256_Init(&sha256_
);
1680 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1681 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1684 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1685 LDID_SHA1_Update(&sha1_
, data
, size
);
1686 LDID_SHA256_Update(&sha256_
, data
, size
);
1690 virtual int_type
overflow(int_type next
) {
1691 if (next
== traits_type::eof())
1703 std::streambuf
&buffer_
;
1706 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1712 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1713 _assert(HashBuffer::xsputn(data
, size
) == size
);
1714 return buffer_
.sputn(data
, size
);
1718 #ifndef LDID_NOTOOLS
1719 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1720 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1728 Split(const std::string
&path
) {
1729 size_t slash(path
.rfind('/'));
1730 if (slash
== std::string::npos
)
1733 dir
= path
.substr(0, slash
+ 1);
1734 base
= path
.substr(slash
+ 1);
1739 static void mkdir_p(const std::string
&path
) {
1743 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1746 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1749 auto slash(path
.rfind('/', path
.size() - 1));
1750 if (slash
== std::string::npos
)
1752 mkdir_p(path
.substr(0, slash
));
1755 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1756 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1758 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1762 static void Commit(const std::string
&path
, const std::string
&temp
) {
1764 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1766 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1768 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1771 _syscall(rename(temp
.c_str(), path
.c_str()));
1777 #ifndef LDID_NOSMIME
1778 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
1779 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
1780 _assert(index
>= 0);
1781 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
1782 _assert(next
== -1);
1783 auto entry(X509_NAME_get_entry(name
, index
));
1784 _assert(entry
!= NULL
);
1785 auto asn(X509_NAME_ENTRY_get_data(entry
));
1786 _assert(asn
!= NULL
);
1787 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1791 static void req(std::streambuf
&buffer
, uint32_t value
) {
1792 value
= Swap(value
);
1793 put(buffer
, &value
, sizeof(value
));
1796 static void req(std::streambuf
&buffer
, const std::string
&value
) {
1797 req(buffer
, value
.size());
1798 put(buffer
, value
.data(), value
.size());
1799 static uint8_t zeros
[] = {0,0,0,0};
1800 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
1803 template <size_t Size_
>
1804 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
1806 put(buffer
, data
, Size_
);
1807 static uint8_t zeros
[] = {0,0,0,0};
1808 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
1811 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, uint32_t flags
, bool platform
, const Progress
&progress
) {
1818 #ifndef LDID_NOSMIME
1821 auto name(X509_get_subject_name(stuff
));
1822 _assert(name
!= NULL
);
1823 get(team
, name
, NID_organizationalUnitName
);
1824 get(common
, name
, NID_commonName
);
1829 std::stringbuf backing
;
1831 if (!requirements
.empty()) {
1832 put(backing
, requirements
.data(), requirements
.size());
1836 std::stringbuf requirement
;
1837 req(requirement
, exprForm
);
1838 req(requirement
, opAnd
);
1839 req(requirement
, opIdent
);
1840 req(requirement
, identifier
);
1841 req(requirement
, opAnd
);
1842 req(requirement
, opAppleGenericAnchor
);
1843 req(requirement
, opAnd
);
1844 req(requirement
, opCertField
);
1845 req(requirement
, 0);
1846 req(requirement
, "subject.CN");
1847 req(requirement
, matchEqual
);
1848 req(requirement
, common
);
1849 req(requirement
, opCertGeneric
);
1850 req(requirement
, 1);
1851 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
1852 req(requirement
, matchExists
);
1853 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
1855 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
1859 // XXX: this is just a "sufficiently large number"
1860 size_t certificate(0x3000);
1862 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
1863 size_t alloc(sizeof(struct SuperBlob
));
1865 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1867 uint32_t special(0);
1869 _foreach (slot
, slots
)
1870 special
= std::max(special
, slot
.first
);
1872 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1873 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1874 special
= std::max(special
, CSSLOT_INFOSLOT
);
1877 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1878 alloc
+= sizeof(struct BlobIndex
);
1879 alloc
+= backing
.str().size();
1882 baton
.entitlements_
= entitlements
;
1884 #ifndef LDID_NOPLIST
1885 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1886 baton
.entitlements_
.assign(data
, size
);
1889 if (baton
.entitlements_
.empty())
1890 baton
.entitlements_
= entitlements
;
1891 else if (!entitlements
.empty()) {
1892 auto combined(plist(baton
.entitlements_
));
1893 _scope({ plist_free(combined
); });
1894 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
1896 auto merging(plist(entitlements
));
1897 _scope({ plist_free(merging
); });
1898 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
1900 plist_dict_iter
iterator(NULL
);
1901 plist_dict_new_iter(merging
, &iterator
);
1902 _scope({ free(iterator
); });
1906 plist_t
value(NULL
);
1907 plist_dict_next_item(merging
, iterator
, &key
, &value
);
1910 _scope({ free(key
); });
1911 plist_dict_set_item(combined
, key
, plist_copy(value
));
1916 plist_to_xml(combined
, &xml
, &size
);
1917 _scope({ free(xml
); });
1919 baton
.entitlements_
.assign(xml
, size
);
1926 if (!baton
.entitlements_
.empty()) {
1927 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1928 alloc
+= sizeof(struct BlobIndex
);
1929 alloc
+= sizeof(struct Blob
);
1930 alloc
+= baton
.entitlements_
.size();
1933 size_t directory(0);
1935 directory
+= sizeof(struct BlobIndex
);
1936 directory
+= sizeof(struct Blob
);
1937 directory
+= sizeof(struct CodeDirectory
);
1938 directory
+= identifier
.size() + 1;
1941 directory
+= team
.size() + 1;
1943 for (Algorithm
*algorithm
: GetAlgorithms())
1944 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
1946 #ifndef LDID_NOSMIME
1948 alloc
+= sizeof(struct BlobIndex
);
1949 alloc
+= sizeof(struct Blob
);
1950 alloc
+= certificate
;
1955 }), fun([&](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
1959 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
1962 if (!baton
.entitlements_
.empty()) {
1963 std::stringbuf data
;
1964 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
1965 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1970 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1971 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
1972 auto &slot(posts
[CSSLOT_INFOSLOT
]);
1973 for (Algorithm
*algorithm
: GetAlgorithms())
1974 (*algorithm
)(slot
, data
, size
);
1979 for (Algorithm
*pointer
: GetAlgorithms()) {
1980 Algorithm
&algorithm(*pointer
);
1982 std::stringbuf data
;
1984 uint32_t special(0);
1985 _foreach (blob
, blobs
)
1986 special
= std::max(special
, blob
.first
);
1987 _foreach (slot
, posts
)
1988 special
= std::max(special
, slot
.first
);
1989 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1991 CodeDirectory directory
;
1992 directory
.version
= Swap(uint32_t(0x00020200));
1993 directory
.flags
= Swap(uint32_t(flags
));
1994 directory
.nSpecialSlots
= Swap(special
);
1995 directory
.codeLimit
= Swap(uint32_t(limit
));
1996 directory
.nCodeSlots
= Swap(normal
);
1997 directory
.hashSize
= algorithm
.size_
;
1998 directory
.hashType
= algorithm
.type_
;
1999 directory
.platform
= platform
? 0x01 : 0x00;
2000 directory
.pageSize
= PageShift_
;
2001 directory
.spare2
= Swap(uint32_t(0));
2002 directory
.scatterOffset
= Swap(uint32_t(0));
2003 //directory.spare3 = Swap(uint32_t(0));
2004 //directory.codeLimit64 = Swap(uint64_t(0));
2006 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2008 directory
.identOffset
= Swap(uint32_t(offset
));
2009 offset
+= identifier
.size() + 1;
2012 directory
.teamIDOffset
= Swap(uint32_t(0));
2014 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2015 offset
+= team
.size() + 1;
2018 offset
+= special
* algorithm
.size_
;
2019 directory
.hashOffset
= Swap(uint32_t(offset
));
2020 offset
+= normal
* algorithm
.size_
;
2022 put(data
, &directory
, sizeof(directory
));
2024 put(data
, identifier
.c_str(), identifier
.size() + 1);
2026 put(data
, team
.c_str(), team
.size() + 1);
2028 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2029 auto *hashes(&storage
[special
* algorithm
.size_
]);
2031 memset(storage
.data(), 0, special
* algorithm
.size_
);
2033 _foreach (blob
, blobs
) {
2034 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2035 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2038 _foreach (slot
, posts
)
2039 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2043 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2044 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2045 progress(double(i
) / normal
);
2048 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2051 put(data
, storage
.data(), storage
.size());
2053 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2054 algorithm(hash
, save
.data(), save
.size());
2059 #ifndef LDID_NOSMIME
2062 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2063 _scope({ CFRelease(plist
); });
2065 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2066 _scope({ CFRelease(cdhashes
); });
2068 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2070 auto plist(plist_new_dict());
2071 _scope({ plist_free(plist
); });
2073 auto cdhashes(plist_new_array());
2074 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2078 for (Algorithm
*pointer
: GetAlgorithms()) {
2079 Algorithm
&algorithm(*pointer
);
2082 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2085 std::vector
<char> hash
;
2086 algorithm(hash
, blob
.data(), blob
.size());
2090 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2091 _scope({ CFRelease(value
); });
2092 CFArrayAppendValue(cdhashes
, value
);
2094 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2099 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2100 _scope({ CFRelease(created
); });
2101 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2102 auto size(CFDataGetLength(created
));
2106 plist_to_xml(plist
, &xml
, &size
);
2107 _scope({ free(xml
); });
2110 std::stringbuf data
;
2111 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2116 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2117 Buffer
result(signature
);
2118 std::string
value(result
);
2119 put(data
, value
.data(), value
.size());
2121 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2122 _assert(save
.size() <= certificate
);
2126 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2132 #ifndef LDID_NOTOOLS
2133 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2134 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2136 }), fun([](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2141 std::string
DiskFolder::Path(const std::string
&path
) const {
2142 return path_
+ path
;
2145 DiskFolder::DiskFolder(const std::string
&path
) :
2148 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2151 DiskFolder::~DiskFolder() {
2152 if (!std::uncaught_exception())
2153 for (const auto &commit
: commit_
)
2154 Commit(commit
.first
, commit
.second
);
2158 std::string
readlink(const std::string
&path
) {
2159 for (size_t size(1024); ; size
*= 2) {
2163 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2164 if (size_t(writ
) >= size
)
2173 void DiskFolder::Find(const std::string
&root
, const std::string
&base
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2174 std::string
path(Path(root
) + base
);
2176 DIR *dir(opendir(path
.c_str()));
2177 _assert(dir
!= NULL
);
2178 _scope({ _syscall(closedir(dir
)); });
2180 while (auto child
= readdir(dir
)) {
2181 std::string
name(child
->d_name
);
2182 if (name
== "." || name
== "..")
2184 if (Starts(name
, ".ldid."))
2191 _syscall(stat((path
+ name
).c_str(), &info
));
2193 else if (S_ISDIR(info
.st_mode
))
2195 else if (S_ISREG(info
.st_mode
))
2198 _assert_(false, "st_mode=%x", info
.st_mode
);
2200 switch (child
->d_type
) {
2208 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2211 _assert_(false, "d_type=%u", child
->d_type
);
2216 Find(root
, base
+ name
+ "/", code
, link
);
2222 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2225 std::stringbuf save
;
2229 auto from(Path(path
));
2230 commit_
[from
] = Temporary(save
, from
);
2235 bool DiskFolder::Look(const std::string
&path
) const {
2236 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2239 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2241 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2242 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2244 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2245 data
.pubseekpos(0, std::ios::in
);
2246 code(data
, length
, NULL
);
2249 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2250 Find(path
, "", code
, link
);
2254 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2258 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2261 std::string
SubFolder::Path(const std::string
&path
) const {
2262 return path_
+ path
;
2265 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2266 return parent_
.Save(Path(path
), edit
, flag
, code
);
2269 bool SubFolder::Look(const std::string
&path
) const {
2270 return parent_
.Look(Path(path
));
2273 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2274 return parent_
.Open(Path(path
), code
);
2277 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2278 return parent_
.Find(Path(path
), code
, link
);
2281 std::string
UnionFolder::Map(const std::string
&path
) const {
2282 auto remap(remaps_
.find(path
));
2283 if (remap
== remaps_
.end())
2285 return remap
->second
;
2288 void UnionFolder::Map(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const std::string
&file
, const Functor
<void (const Functor
<void (std::streambuf
&, size_t, const void *)> &)> &save
) const {
2289 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2290 code(file
.substr(path
.size()));
2293 UnionFolder::UnionFolder(Folder
&parent
) :
2298 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2299 return parent_
.Save(Map(path
), edit
, flag
, code
);
2302 bool UnionFolder::Look(const std::string
&path
) const {
2303 auto file(resets_
.find(path
));
2304 if (file
!= resets_
.end())
2306 return parent_
.Look(Map(path
));
2309 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2310 auto file(resets_
.find(path
));
2311 if (file
== resets_
.end())
2312 return parent_
.Open(Map(path
), code
);
2313 auto &entry(file
->second
);
2315 auto &data(*entry
.data_
);
2316 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2317 data
.pubseekpos(0, std::ios::in
);
2318 code(data
, length
, entry
.flag_
);
2321 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2322 for (auto &reset
: resets_
)
2323 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2324 auto &entry(reset
.second
);
2325 auto &data(*entry
.data_
);
2326 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2327 data
.pubseekpos(0, std::ios::in
);
2328 code(data
, length
, entry
.flag_
);
2331 for (auto &remap
: remaps_
)
2332 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2333 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2334 code(data
, length
, flag
);
2338 parent_
.Find(path
, fun([&](const std::string
&name
) {
2339 if (deletes_
.find(path
+ name
) == deletes_
.end())
2341 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2342 if (deletes_
.find(path
+ name
) == deletes_
.end())
2347 #ifndef LDID_NOTOOLS
2348 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2352 char data
[4096 * 4];
2353 size_t writ(source
.sgetn(data
, sizeof(data
)));
2356 _assert(target
.sputn(data
, writ
) == writ
);
2358 progress(double(total
) / length
);
2362 #ifndef LDID_NOPLIST
2363 static plist_t
plist(const std::string
&data
) {
2364 plist_t
plist(NULL
);
2365 if (Starts(data
, "bplist00"))
2366 plist_from_bin(data
.data(), data
.size(), &plist
);
2368 plist_from_xml(data
.data(), data
.size(), &plist
);
2369 _assert(plist
!= NULL
);
2373 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2374 std::stringbuf data
;
2375 copy(buffer
, data
, length
, dummy_
);
2376 auto node(plist(data
.str()));
2377 _scope({ plist_free(node
); });
2378 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2382 static std::string
plist_s(plist_t node
) {
2383 _assert(node
!= NULL
);
2384 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2386 plist_get_string_val(node
, &data
);
2387 _scope({ free(data
); });
2403 std::vector
<std::string
> matches_
;
2406 Expression(const std::string
&code
) {
2407 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2408 matches_
.resize(regex_
.re_nsub
+ 1);
2415 bool operator ()(const std::string
&data
) {
2416 regmatch_t matches
[matches_
.size()];
2417 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2418 if (value
== REG_NOMATCH
)
2420 _assert_(value
== 0, "regexec()");
2421 for (size_t i(0); i
!= matches_
.size(); ++i
)
2422 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2426 const std::string
&operator [](size_t index
) const {
2427 return matches_
[index
];
2436 mutable std::auto_ptr
<Expression
> regex_
;
2438 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2445 Rule(const Rule
&rhs
) :
2446 weight_(rhs
.weight_
),
2452 void Compile() const {
2453 regex_
.reset(new Expression(code_
));
2456 bool operator ()(const std::string
&data
) const {
2457 _assert(regex_
.get() != NULL
);
2458 return (*regex_
)(data
);
2461 bool operator <(const Rule
&rhs
) const {
2462 if (weight_
> rhs
.weight_
)
2464 if (weight_
< rhs
.weight_
)
2466 return mode_
> rhs
.mode_
;
2471 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2472 return lhs
->code_
< rhs
->code_
;
2476 #ifndef LDID_NOPLIST
2477 static Hash
Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, Hash
&hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2478 // XXX: this is a miserable fail
2479 std::stringbuf temp
;
2480 put(temp
, prefix
, size
);
2481 copy(buffer
, temp
, length
- size
, progress
);
2482 // XXX: this is a stupid hack
2483 pad(temp
, 0x10 - (length
& 0xf));
2484 auto data(temp
.str());
2486 HashProxy
proxy(hash
, save
);
2487 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2491 std::map
<std::string
, Hash
> files
;
2492 std::map
<std::string
, std::string
> links
;
2494 void Merge(const std::string
&root
, const State
&state
) {
2495 for (const auto &entry
: state
.files
)
2496 files
[root
+ entry
.first
] = entry
.second
;
2497 for (const auto &entry
: state
.links
)
2498 links
[root
+ entry
.first
] = entry
.second
;
2502 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&remote
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2503 std::string executable
;
2504 std::string identifier
;
2508 std::string
info("Info.plist");
2510 SubFolder
folder(parent
, [&]() {
2511 if (parent
.Look(info
))
2515 else if (parent
.Look("Contents/" + info
))
2517 else if (parent
.Look("Resources/" + info
)) {
2518 info
= "Resources/" + info
;
2520 } else _assert_(false, "cannot find Info.plist");
2523 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2524 plist_d(buffer
, length
, fun([&](plist_t node
) {
2525 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2526 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2530 if (mac
&& info
== "Info.plist")
2531 executable
= "MacOS/" + executable
;
2533 progress(root
+ "*");
2535 std::string entitlements
;
2536 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2537 // XXX: this is a miserable fail
2538 std::stringbuf temp
;
2539 copy(buffer
, temp
, length
, progress
);
2540 // XXX: this is a stupid hack
2541 pad(temp
, 0x10 - (length
& 0xf));
2542 auto data(temp
.str());
2543 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2546 static const std::string
directory("_CodeSignature/");
2547 static const std::string
signature(directory
+ "CodeResources");
2549 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2551 auto &rules1(versions
[""]);
2552 auto &rules2(versions
["2"]);
2554 const std::string
resources(mac
? "Resources/" : "");
2557 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2558 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2559 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2560 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2561 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2565 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2566 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2567 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2568 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2569 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2570 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2571 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2572 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2573 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2574 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2575 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2576 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2577 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2578 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2583 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2584 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2585 std::map
<std::string
, Bundle
> bundles
;
2587 folder
.Find("", fun([&](const std::string
&name
) {
2590 auto bundle(root
+ Split(name
).dir
);
2592 _assert(!bundle
.empty());
2593 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2595 SubFolder
subfolder(folder
, bundle
);
2597 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2598 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2600 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2603 std::set
<std::string
> excludes
;
2605 auto exclude([&](const std::string
&name
) {
2606 // BundleDiskRep::adjustResources -> builder.addExclusion
2607 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2610 for (const auto &bundle
: bundles
)
2611 if (Starts(name
, bundle
.first
+ "/")) {
2612 excludes
.insert(name
);
2619 folder
.Find("", fun([&](const std::string
&name
) {
2623 if (local
.files
.find(name
) != local
.files
.end())
2625 auto &hash(local
.files
[name
]);
2627 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2628 progress(root
+ name
);
2639 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2641 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2642 switch (Swap(header
.magic
)) {
2644 // Java class file format
2645 if (Swap(header
.count
) >= 40)
2648 case MH_MAGIC
: case MH_MAGIC_64
:
2649 case MH_CIGAM
: case MH_CIGAM_64
:
2650 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2652 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2657 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2658 HashProxy
proxy(hash
, save
);
2659 put(proxy
, header
.bytes
, size
);
2660 copy(data
, proxy
, length
- size
, progress
);
2663 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2667 local
.links
[name
] = read();
2670 auto plist(plist_new_dict());
2671 _scope({ plist_free(plist
); });
2673 for (const auto &version
: versions
) {
2674 auto files(plist_new_dict());
2675 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2677 for (const auto &rule
: version
.second
)
2680 bool old(&version
.second
== &rules1
);
2682 for (const auto &hash
: local
.files
)
2683 for (const auto &rule
: version
.second
)
2684 if (rule(hash
.first
)) {
2685 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2686 else if (old
&& rule
.mode_
== NoMode
)
2687 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2688 else if (rule
.mode_
!= OmitMode
) {
2689 auto entry(plist_new_dict());
2690 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2692 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2693 if (rule
.mode_
== OptionalMode
)
2694 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2695 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2702 for (const auto &link
: local
.links
)
2703 for (const auto &rule
: version
.second
)
2704 if (rule(link
.first
)) {
2705 if (rule
.mode_
!= OmitMode
) {
2706 auto entry(plist_new_dict());
2707 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2708 if (rule
.mode_
== OptionalMode
)
2709 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2710 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2717 for (const auto &bundle
: bundles
) {
2718 auto entry(plist_new_dict());
2719 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2720 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2721 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2725 for (const auto &version
: versions
) {
2726 auto rules(plist_new_dict());
2727 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2729 std::multiset
<const Rule
*, RuleCode
> ordered
;
2730 for (const auto &rule
: version
.second
)
2731 ordered
.insert(&rule
);
2733 for (const auto &rule
: ordered
)
2734 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2735 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2737 auto entry(plist_new_dict());
2738 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2740 switch (rule
->mode_
) {
2744 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2747 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2750 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2753 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2757 if (rule
->weight_
>= 10000)
2758 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2759 else if (rule
->weight_
!= 1)
2760 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2764 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2765 HashProxy
proxy(local
.files
[signature
], save
);
2768 plist_to_xml(plist
, &xml
, &size
);
2769 _scope({ free(xml
); });
2770 put(proxy
, xml
, size
);
2774 bundle
.path
= folder
.Path(executable
);
2776 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2777 progress(root
+ executable
);
2778 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2780 slots
[1] = local
.files
.at(info
);
2781 slots
[3] = local
.files
.at(signature
);
2782 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
2786 remote
.Merge(root
, local
);
2790 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2792 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
2799 static void usage(const char *argv0
) {
2800 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv0
);
2801 fprintf(stderr
, " %s -e MobileSafari\n", argv0
);
2802 fprintf(stderr
, " %s -S cat\n", argv0
);
2803 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv0
);
2806 #ifndef LDID_NOTOOLS
2807 int main(int argc
, char *argv
[]) {
2808 #ifndef LDID_NOSMIME
2809 OpenSSL_add_all_algorithms();
2817 little_
= endian
.byte
[0];
2825 #ifndef LDID_NOFLAGT
2842 bool platform(false);
2844 uint32_t flag_CPUType(_not(uint32_t));
2845 uint32_t flag_CPUSubtype(_not(uint32_t));
2847 const char *flag_I(NULL
);
2849 #ifndef LDID_NOFLAGT
2859 std::vector
<std::string
> files
;
2866 for (int argi(1); argi
!= argc
; ++argi
)
2867 if (argv
[argi
][0] != '-')
2868 files
.push_back(argv
[argi
]);
2869 else switch (argv
[argi
][1]) {
2876 case 'e': flag_e
= true; break;
2879 const char *string
= argv
[argi
] + 2;
2880 const char *colon
= strchr(string
, ':');
2881 _assert(colon
!= NULL
);
2882 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2884 unsigned number(strtoul(string
, &arge
, 0));
2885 _assert(arge
== colon
);
2886 auto &slot(slots
[number
]);
2887 for (Algorithm
*algorithm
: GetAlgorithms())
2888 (*algorithm
)(slot
, file
.data(), file
.size());
2891 case 'q': flag_q
= true; break;
2894 const char *hash
= argv
[argi
] + 2;
2902 fprintf(stderr
, "WARNING: -H is only present for compatibility with a fork of ldid\n");
2903 fprintf(stderr
, " you should NOT be manually specifying the hash algorithm\n");
2907 else if (strcmp(hash
, "sha1") == 0)
2909 else if (strcmp(hash
, "sha256") == 0)
2911 else _assert(false);
2915 const char *xml
= argv
[argi
] + 2;
2916 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2919 case 'D': flag_D
= true; break;
2921 case 'a': flag_a
= true; break;
2926 if (argv
[argi
][2] != '\0') {
2927 const char *cpu
= argv
[argi
] + 2;
2928 const char *colon
= strchr(cpu
, ':');
2929 _assert(colon
!= NULL
);
2931 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2932 _assert(arge
== colon
);
2933 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2934 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2939 const char *name
= argv
[argi
] + 2;
2941 else if (strcmp(name
, "host") == 0)
2942 flags
|= kSecCodeSignatureHost
;
2943 else if (strcmp(name
, "adhoc") == 0)
2944 flags
|= kSecCodeSignatureAdhoc
;
2945 else if (strcmp(name
, "hard") == 0)
2946 flags
|= kSecCodeSignatureForceHard
;
2947 else if (strcmp(name
, "kill") == 0)
2948 flags
|= kSecCodeSignatureForceKill
;
2949 else if (strcmp(name
, "expires") == 0)
2950 flags
|= kSecCodeSignatureForceExpiration
;
2951 else if (strcmp(name
, "restrict") == 0)
2952 flags
|= kSecCodeSignatureRestrict
;
2953 else if (strcmp(name
, "enforcement") == 0)
2954 flags
|= kSecCodeSignatureEnforcement
;
2955 else if (strcmp(name
, "library-validation") == 0)
2956 flags
|= kSecCodeSignatureLibraryValidation
;
2957 else _assert(false);
2974 if (argv
[argi
][2] != '\0') {
2975 const char *xml
= argv
[argi
] + 2;
2976 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2985 if (argv
[argi
][2] != '\0')
2986 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2989 #ifndef LDID_NOFLAGT
2992 if (argv
[argi
][2] == '-')
2996 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2997 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3007 flag_I
= argv
[argi
] + 2;
3016 _assert(flag_S
|| key
.empty());
3017 _assert(flag_S
|| flag_I
== NULL
);
3022 size_t filei(0), filee(0);
3023 _foreach (file
, files
) try {
3024 std::string
path(file
);
3027 _syscall(stat(path
.c_str(), &info
));
3029 if (flag_S
&& S_ISDIR(info
.st_mode
)) {
3030 #ifndef LDID_NOPLIST
3032 ldid::DiskFolder
folder(path
+ "/");
3033 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3037 } else if (flag_S
|| flag_r
) {
3038 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3040 std::filebuf output
;
3042 auto temp(Temporary(output
, split
));
3045 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3047 std::string
identifier(flag_I
?: split
.base
.c_str());
3048 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3055 #ifndef LDID_NOFLAGT
3062 Map
mapping(path
, modify
);
3063 FatHeader
fat_header(mapping
.data(), mapping
.size());
3065 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3066 struct linkedit_data_command
*signature(NULL
);
3067 struct encryption_info_command
*encryption(NULL
);
3070 if (mach_header
.GetCPUType() != flag_CPUType
)
3072 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3077 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3079 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3080 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3083 else if (cmd
== LC_CODE_SIGNATURE
)
3084 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3085 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3086 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3087 else if (cmd
== LC_LOAD_DYLIB
) {
3088 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3089 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3091 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3094 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3095 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3099 #ifndef LDID_NOFLAGT
3100 else if (cmd
== LC_ID_DYLIB
) {
3101 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3109 dylib_command
->dylib
.timestamp
= 0;
3110 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3113 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3120 _assert(encryption
!= NULL
);
3121 encryption
->cryptid
= mach_header
.Swap(0);
3125 _assert(signature
!= NULL
);
3127 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3129 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3130 uint8_t *blob
= top
+ data
;
3131 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3133 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3134 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3135 uint32_t begin
= Swap(super
->index
[index
].offset
);
3136 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3137 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3142 _assert(signature
!= NULL
);
3144 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3146 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3147 uint8_t *blob
= top
+ data
;
3148 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3150 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3151 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3152 uint32_t begin
= Swap(super
->index
[index
].offset
);
3153 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3154 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3159 _assert(signature
!= NULL
);
3161 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3163 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3164 uint8_t *blob
= top
+ data
;
3165 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3167 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3168 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3169 uint32_t begin
= Swap(super
->index
[index
].offset
);
3170 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3172 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3173 uint32_t pages
= Swap(directory
->nCodeSlots
);
3176 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3177 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3179 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3185 } catch (const char *) {