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_BUNDLE 0x8
249 #define MH_DYLIB_STUB 0x9
251 struct load_command
{
256 #define LC_REQ_DYLD uint32_t(0x80000000)
258 #define LC_SEGMENT uint32_t(0x01)
259 #define LC_SYMTAB uint32_t(0x02)
260 #define LC_DYSYMTAB uint32_t(0x0b)
261 #define LC_LOAD_DYLIB uint32_t(0x0c)
262 #define LC_ID_DYLIB uint32_t(0x0d)
263 #define LC_SEGMENT_64 uint32_t(0x19)
264 #define LC_UUID uint32_t(0x1b)
265 #define LC_CODE_SIGNATURE uint32_t(0x1d)
266 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
267 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
268 #define LC_ENCRYPTION_INFO uint32_t(0x21)
269 #define LC_DYLD_INFO uint32_t(0x22)
270 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
271 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
286 uint32_t current_version
;
287 uint32_t compatibility_version
;
290 struct dylib_command
{
296 struct uuid_command
{
302 struct symtab_command
{
311 struct dyld_info_command
{
315 uint32_t rebase_size
;
318 uint32_t weak_bind_off
;
319 uint32_t weak_bind_size
;
320 uint32_t lazy_bind_off
;
321 uint32_t lazy_bind_size
;
323 uint32_t export_size
;
326 struct dysymtab_command
{
339 uint32_t extrefsymoff
;
340 uint32_t nextrefsyms
;
341 uint32_t indirectsymoff
;
342 uint32_t nindirectsyms
;
349 struct dylib_table_of_contents
{
350 uint32_t symbol_index
;
351 uint32_t module_index
;
354 struct dylib_module
{
355 uint32_t module_name
;
364 uint32_t iinit_iterm
;
365 uint32_t ninit_nterm
;
366 uint32_t objc_module_info_addr
;
367 uint32_t objc_module_info_size
;
370 struct dylib_reference
{
375 struct relocation_info
{
377 uint32_t r_symbolnum
:24;
396 struct segment_command
{
410 struct segment_command_64
{
453 struct linkedit_data_command
{
460 struct encryption_info_command
{
468 #define BIND_OPCODE_MASK 0xf0
469 #define BIND_IMMEDIATE_MASK 0x0f
470 #define BIND_OPCODE_DONE 0x00
471 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
472 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
473 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
474 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
475 #define BIND_OPCODE_SET_TYPE_IMM 0x50
476 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
477 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
478 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
479 #define BIND_OPCODE_DO_BIND 0x90
480 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
481 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
482 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
484 struct : ldid::Progress
{
485 virtual void operator()(const std::string
&value
) const {
488 virtual void operator()(double value
) const {
492 struct Progression
: ldid::Progress
{
493 const ldid::Progress
&progress_
;
496 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
502 virtual void operator()(const std::string
&value
) const {
503 return progress_(name_
+ " (" + value
+ ")");
506 virtual void operator()(double value
) const {
507 return progress_(value
);
511 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
512 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
517 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
518 _assert(read(stream
, data
, size
) == size
);
521 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
522 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
525 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
527 for (size_t total(0); total
!= size
;) {
528 auto writ(std::min(size
- total
, size_t(4096 * 4)));
529 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
531 progress(double(total
) / size
);
535 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
538 if (auto writ
= read(stream
, data
, size
))
544 static inline void pad(std::streambuf
&stream
, size_t size
) {
546 memset(padding
, 0, size
);
547 put(stream
, padding
, size
);
550 template <typename Type_
>
551 Type_
Align(Type_ value
, size_t align
) {
558 static const uint8_t PageShift_(0x0c);
559 static const uint32_t PageSize_(1 << PageShift_
);
561 static inline uint16_t Swap_(uint16_t value
) {
563 ((value
>> 8) & 0x00ff) |
564 ((value
<< 8) & 0xff00);
567 static inline uint32_t Swap_(uint32_t value
) {
568 value
= ((value
>> 8) & 0x00ff00ff) |
569 ((value
<< 8) & 0xff00ff00);
570 value
= ((value
>> 16) & 0x0000ffff) |
571 ((value
<< 16) & 0xffff0000);
575 static inline uint64_t Swap_(uint64_t value
) {
576 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
577 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
578 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
582 static inline int16_t Swap_(int16_t value
) {
583 return Swap_(static_cast<uint16_t>(value
));
586 static inline int32_t Swap_(int32_t value
) {
587 return Swap_(static_cast<uint32_t>(value
));
590 static inline int64_t Swap_(int64_t value
) {
591 return Swap_(static_cast<uint64_t>(value
));
594 static bool little_(true);
596 static inline uint16_t Swap(uint16_t value
) {
597 return little_
? Swap_(value
) : value
;
600 static inline uint32_t Swap(uint32_t value
) {
601 return little_
? Swap_(value
) : value
;
604 static inline uint64_t Swap(uint64_t value
) {
605 return little_
? Swap_(value
) : value
;
608 static inline int16_t Swap(int16_t value
) {
609 return Swap(static_cast<uint16_t>(value
));
612 static inline int32_t Swap(int32_t value
) {
613 return Swap(static_cast<uint32_t>(value
));
616 static inline int64_t Swap(int64_t value
) {
617 return Swap(static_cast<uint64_t>(value
));
630 Swapped(bool swapped
) :
635 template <typename Type_
>
636 Type_
Swap(Type_ value
) const {
637 return swapped_
? Swap_(value
) : value
;
649 Data(void *base
, size_t size
) :
655 void *GetBase() const {
659 size_t GetSize() const {
670 struct mach_header
*mach_header_
;
671 struct load_command
*load_command_
;
674 MachHeader(void *base
, size_t size
) :
677 mach_header_
= (mach_header
*) base
;
679 switch (Swap(mach_header_
->magic
)) {
681 swapped_
= !swapped_
;
687 swapped_
= !swapped_
;
696 void *post
= mach_header_
+ 1;
698 post
= (uint32_t *) post
+ 1;
699 load_command_
= (struct load_command
*) post
;
702 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
703 Swap(mach_header_
->filetype
) == MH_DYLIB
||
704 Swap(mach_header_
->filetype
) == MH_BUNDLE
708 bool Bits64() const {
712 struct mach_header
*operator ->() const {
716 operator struct mach_header
*() const {
720 uint32_t GetCPUType() const {
721 return Swap(mach_header_
->cputype
);
724 uint32_t GetCPUSubtype() const {
725 return Swap(mach_header_
->cpusubtype
) & 0xff;
728 struct load_command
*GetLoadCommand() const {
729 return load_command_
;
732 std::vector
<struct load_command
*> GetLoadCommands() const {
733 std::vector
<struct load_command
*> load_commands
;
735 struct load_command
*load_command
= load_command_
;
736 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
737 load_commands
.push_back(load_command
);
738 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
741 return load_commands
;
744 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
745 _foreach (load_command
, GetLoadCommands())
746 switch (Swap(load_command
->cmd
)) {
748 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
749 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
750 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
751 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
752 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
755 case LC_SEGMENT_64
: {
756 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
757 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
758 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
759 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
760 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
765 template <typename Target_
>
766 Target_
*GetOffset(uint32_t offset
) const {
767 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
771 class FatMachHeader
:
778 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
779 MachHeader(base
, size
),
784 fat_arch
*GetFatArch() const {
793 fat_header
*fat_header_
;
794 std::vector
<FatMachHeader
> mach_headers_
;
797 FatHeader(void *base
, size_t size
) :
800 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
802 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
803 swapped_
= !swapped_
;
805 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
807 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
809 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
810 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
812 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
813 uint32_t arch_offset
= Swap(fat_arch
->offset
);
814 uint32_t arch_size
= Swap(fat_arch
->size
);
815 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
821 std::vector
<FatMachHeader
> &GetMachHeaders() {
822 return mach_headers_
;
826 return fat_header_
!= NULL
;
829 struct fat_header
*operator ->() const {
833 operator struct fat_header
*() const {
838 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
839 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
840 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
841 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
842 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
843 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
844 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
845 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
847 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
848 #define CSSLOT_INFOSLOT uint32_t(0x00001)
849 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
850 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
851 #define CSSLOT_APPLICATION uint32_t(0x00004)
852 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
853 #define CSSLOT_ALTERNATE uint32_t(0x01000)
855 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
857 #define CS_HASHTYPE_SHA160_160 1
858 #define CS_HASHTYPE_SHA256_256 2
859 #define CS_HASHTYPE_SHA256_160 3
860 #define CS_HASHTYPE_SHA386_386 4
875 struct BlobIndex index
[];
878 struct CodeDirectory
{
882 uint32_t identOffset
;
883 uint32_t nSpecialSlots
;
891 uint32_t scatterOffset
;
892 uint32_t teamIDOffset
;
894 //uint64_t codeLimit64;
897 enum CodeSignatureFlags
{
898 kSecCodeSignatureHost
= 0x0001,
899 kSecCodeSignatureAdhoc
= 0x0002,
900 kSecCodeSignatureForceHard
= 0x0100,
901 kSecCodeSignatureForceKill
= 0x0200,
902 kSecCodeSignatureForceExpiration
= 0x0400,
903 kSecCodeSignatureRestrict
= 0x0800,
904 kSecCodeSignatureEnforcement
= 0x1000,
905 kSecCodeSignatureLibraryValidation
= 0x2000,
908 enum Kind
: uint32_t {
909 exprForm
= 1, // prefix expr form
912 enum ExprOp
: uint32_t {
913 opFalse
, // unconditionally false
914 opTrue
, // unconditionally true
915 opIdent
, // match canonical code [string]
916 opAppleAnchor
, // signed by Apple as Apple's product
917 opAnchorHash
, // match anchor [cert hash]
918 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
919 opAnd
, // binary prefix expr AND expr [expr; expr]
920 opOr
, // binary prefix expr OR expr [expr; expr]
921 opCDHash
, // match hash of CodeDirectory directly [cd hash]
922 opNot
, // logical inverse [expr]
923 opInfoKeyField
, // Info.plist key field [string; match suffix]
924 opCertField
, // Certificate field [cert index; field name; match suffix]
925 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
926 opTrustedCerts
, // require trust settings to approve the cert chain
927 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
928 opAppleGenericAnchor
, // signed by Apple in any capacity
929 opEntitlementField
, // entitlement dictionary field [string; match suffix]
930 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
931 opNamedAnchor
, // named anchor type
932 opNamedCode
, // named subroutine
933 opPlatform
, // platform constraint [integer]
934 exprOpCount
// (total opcode count in use)
937 enum MatchOperation
{
938 matchExists
, // anything but explicit "false" - no value stored
939 matchEqual
, // equal (CFEqual)
940 matchContains
, // partial match (substring)
941 matchBeginsWith
, // partial match (initial substring)
942 matchEndsWith
, // partial match (terminal substring)
943 matchLessThan
, // less than (string with numeric comparison)
944 matchGreaterThan
, // greater than (string with numeric comparison)
945 matchLessEqual
, // less or equal (string with numeric comparison)
946 matchGreaterEqual
, // greater or equal (string with numeric comparison)
949 #define OID_ISO_MEMBER 42
950 #define OID_US OID_ISO_MEMBER, 134, 72
951 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
952 #define APPLE_ADS_OID APPLE_OID, 0x64
953 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
956 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
963 Algorithm(size_t size
, uint8_t type
) :
969 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
971 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
972 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
973 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
975 virtual const char *name() = 0;
978 struct AlgorithmSHA1
:
982 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
986 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
990 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
991 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
994 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
995 return operator()(hash
.sha1_
, data
, size
);
998 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
999 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1000 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1003 virtual const char *name() {
1008 struct AlgorithmSHA256
:
1012 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1016 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1017 return hash
.sha256_
;
1020 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1021 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1024 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1025 return operator()(hash
.sha256_
, data
, size
);
1028 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1029 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1030 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1033 virtual const char *name() {
1038 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1039 static AlgorithmSHA1 sha1
;
1040 static AlgorithmSHA256 sha256
;
1042 static Algorithm
*array
[] = {
1047 static std::vector
<Algorithm
*> algorithms(array
, array
+ sizeof(array
) / sizeof(array
[0]));
1051 struct CodesignAllocation
{
1052 FatMachHeader mach_header_
;
1060 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
, const char *arch
) :
1061 mach_header_(mach_header
),
1072 #ifndef LDID_NOTOOLS
1085 _syscall(close(file_
));
1088 void open(const char *path
, int flags
) {
1089 _assert(file_
== -1);
1090 file_
= _syscall(::open(path
, flags
));
1107 _syscall(munmap(data_
, size_
));
1119 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1122 open(path
, oflag
, pflag
, mflag
);
1125 Map(const std::string
&path
, bool edit
) :
1135 bool empty() const {
1136 return data_
== NULL
;
1139 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1142 file_
.open(path
.c_str(), oflag
);
1143 int file(file_
.file());
1146 _syscall(fstat(file
, &stat
));
1147 size_
= stat
.st_size
;
1149 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1152 void open(const std::string
&path
, bool edit
) {
1154 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1156 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1159 void *data() const {
1163 size_t size() const {
1167 operator std::string() const {
1168 return std::string(static_cast<char *>(data_
), size_
);
1175 std::string
Analyze(const void *data
, size_t size
) {
1176 std::string entitlements
;
1178 FatHeader
fat_header(const_cast<void *>(data
), size
);
1179 _foreach (mach_header
, fat_header
.GetMachHeaders())
1180 _foreach (load_command
, mach_header
.GetLoadCommands())
1181 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1182 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1183 auto offset(mach_header
.Swap(signature
->dataoff
));
1184 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1185 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1187 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1188 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1189 auto begin(Swap(super
->index
[index
].offset
));
1190 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1191 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1193 if (entitlements
.empty())
1194 entitlements
.assign(reinterpret_cast<char *>(blob
+ 1), writ
);
1196 _assert(entitlements
.compare(0, entitlements
.size(), reinterpret_cast<char *>(blob
+ 1), writ
) == 0);
1200 return entitlements
;
1203 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, std::streambuf
&output
, size_t, const std::string
&, const char *, const Progress
&)> &save
, const Progress
&progress
) {
1204 FatHeader
source(const_cast<void *>(idata
), isize
);
1208 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1210 std::vector
<CodesignAllocation
> allocations
;
1211 _foreach (mach_header
, source
.GetMachHeaders()) {
1212 struct linkedit_data_command
*signature(NULL
);
1213 struct symtab_command
*symtab(NULL
);
1215 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1216 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1218 else if (cmd
== LC_CODE_SIGNATURE
)
1219 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1220 else if (cmd
== LC_SYMTAB
)
1221 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1225 if (signature
== NULL
)
1226 size
= mach_header
.GetSize();
1228 size
= mach_header
.Swap(signature
->dataoff
);
1229 _assert(size
<= mach_header
.GetSize());
1232 if (symtab
!= NULL
) {
1233 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1234 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1235 _assert(end
<= size
);
1236 _assert(end
>= size
- 0x10);
1241 size_t alloc(allocate(mach_header
, size
));
1243 auto *fat_arch(mach_header
.GetFatArch());
1246 if (fat_arch
!= NULL
)
1247 align
= source
.Swap(fat_arch
->align
);
1248 else switch (mach_header
.GetCPUType()) {
1249 case CPU_TYPE_POWERPC
:
1250 case CPU_TYPE_POWERPC64
:
1252 case CPU_TYPE_X86_64
:
1256 case CPU_TYPE_ARM64
:
1264 const char *arch(NULL
);
1265 switch (mach_header
.GetCPUType()) {
1266 case CPU_TYPE_POWERPC
:
1269 case CPU_TYPE_POWERPC64
:
1275 case CPU_TYPE_X86_64
:
1281 case CPU_TYPE_ARM64
:
1286 offset
= Align(offset
, 1 << align
);
1288 uint32_t limit(size
);
1290 limit
= Align(limit
, 0x10);
1292 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
));
1293 offset
+= size
+ alloc
;
1294 offset
= Align(offset
, 0x10);
1299 if (source
.IsFat()) {
1300 fat_header fat_header
;
1301 fat_header
.magic
= Swap(FAT_MAGIC
);
1302 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1303 put(output
, &fat_header
, sizeof(fat_header
));
1304 position
+= sizeof(fat_header
);
1306 _foreach (allocation
, allocations
) {
1307 auto &mach_header(allocation
.mach_header_
);
1310 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1311 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1312 fat_arch
.offset
= Swap(allocation
.offset_
);
1313 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1314 fat_arch
.align
= Swap(allocation
.align_
);
1315 put(output
, &fat_arch
, sizeof(fat_arch
));
1316 position
+= sizeof(fat_arch
);
1320 _foreach (allocation
, allocations
) {
1321 progress(allocation
.arch_
);
1322 auto &mach_header(allocation
.mach_header_
);
1324 pad(output
, allocation
.offset_
- position
);
1325 position
= allocation
.offset_
;
1327 std::vector
<std::string
> commands
;
1329 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1330 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1332 switch (mach_header
.Swap(load_command
->cmd
)) {
1333 case LC_CODE_SIGNATURE
:
1338 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1339 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1341 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1342 segment_command
->filesize
= size
;
1343 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1346 case LC_SEGMENT_64
: {
1347 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1348 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1350 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1351 segment_command
->filesize
= size
;
1352 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1356 commands
.push_back(copy
);
1359 if (allocation
.alloc_
!= 0) {
1360 linkedit_data_command signature
;
1361 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1362 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1363 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1364 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1365 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1368 size_t begin(position
);
1371 _foreach(command
, commands
)
1372 after
+= command
.size();
1374 std::stringbuf altern
;
1376 struct mach_header
header(*mach_header
);
1377 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1378 header
.sizeofcmds
= mach_header
.Swap(after
);
1379 put(output
, &header
, sizeof(header
));
1380 put(altern
, &header
, sizeof(header
));
1381 position
+= sizeof(header
);
1383 if (mach_header
.Bits64()) {
1384 auto pad(mach_header
.Swap(uint32_t(0)));
1385 put(output
, &pad
, sizeof(pad
));
1386 put(altern
, &pad
, sizeof(pad
));
1387 position
+= sizeof(pad
);
1390 _foreach(command
, commands
) {
1391 put(output
, command
.data(), command
.size());
1392 put(altern
, command
.data(), command
.size());
1393 position
+= command
.size();
1396 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1397 if (before
> after
) {
1398 pad(output
, before
- after
);
1399 pad(altern
, before
- after
);
1400 position
+= before
- after
;
1403 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1405 std::string
overlap(altern
.str());
1406 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1408 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1409 position
= begin
+ allocation
.size_
;
1411 pad(output
, allocation
.limit_
- allocation
.size_
);
1412 position
+= allocation
.limit_
- allocation
.size_
;
1414 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
, progress
));
1415 if (allocation
.alloc_
> saved
)
1416 pad(output
, allocation
.alloc_
- saved
);
1418 _assert(allocation
.alloc_
== saved
);
1419 position
+= allocation
.alloc_
;
1425 typedef std::map
<uint32_t, std::string
> Blobs
;
1427 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1428 auto value(buffer
.str());
1429 std::swap(blobs
[slot
], value
);
1432 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1433 auto value(buffer
.str());
1435 blob
.magic
= Swap(magic
);
1436 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1437 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1438 auto &save(blobs
[slot
]);
1439 std::swap(save
, value
);
1443 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1445 _foreach (blob
, blobs
)
1446 total
+= blob
.second
.size();
1448 struct SuperBlob super
;
1449 super
.blob
.magic
= Swap(magic
);
1450 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1451 super
.count
= Swap(uint32_t(blobs
.size()));
1452 put(output
, &super
, sizeof(super
));
1454 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1456 _foreach (blob
, blobs
) {
1458 index
.type
= Swap(blob
.first
);
1459 index
.offset
= Swap(uint32_t(offset
));
1460 put(output
, &index
, sizeof(index
));
1461 offset
+= blob
.second
.size();
1464 _foreach (blob
, blobs
)
1465 put(output
, blob
.second
.data(), blob
.second
.size());
1470 #ifndef LDID_NOSMIME
1479 _assert(bio_
!= NULL
);
1483 bio_(BIO_new(BIO_s_mem()))
1487 Buffer(const char *data
, size_t size
) :
1488 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1492 Buffer(const std::string
&data
) :
1493 Buffer(data
.data(), data
.size())
1497 Buffer(PKCS7
*pkcs
) :
1500 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1507 operator BIO
*() const {
1511 explicit operator std::string() const {
1513 auto size(BIO_get_mem_data(bio_
, &data
));
1514 return std::string(data
, size
);
1523 STACK_OF(X509
) *ca_
;
1527 value_(d2i_PKCS12_bio(bio
, NULL
)),
1530 _assert(value_
!= NULL
);
1531 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1533 _assert(key_
!= NULL
);
1534 _assert(cert_
!= NULL
);
1537 ca_
= sk_X509_new_null();
1538 _assert(ca_
!= NULL
);
1541 Stuff(const std::string
&data
) :
1547 sk_X509_pop_free(ca_
, X509_free
);
1549 EVP_PKEY_free(key_
);
1550 PKCS12_free(value_
);
1553 operator PKCS12
*() const {
1557 operator EVP_PKEY
*() const {
1561 operator X509
*() const {
1565 operator STACK_OF(X509
) *() const {
1575 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1576 value_
= PKCS7_new();
1577 _assert(value_
!= NULL
);
1579 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1580 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1582 STACK_OF(X509
) *certs(stuff
);
1583 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1584 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1586 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1587 _assert(X509_check_private_key(stuff
, stuff
));
1588 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1589 _assert(info
!= NULL
);
1590 _assert(PKCS7_add_certificate(value_
, stuff
));
1591 _assert(PKCS7_add_signed_attribute(info
, NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1593 PKCS7_set_detached(value_
, 1);
1595 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1596 _assert(string
!= NULL
);
1598 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1600 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1601 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1603 ASN1_OCTET_STRING_free(string
);
1607 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1608 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1609 _assert(bio
!= NULL
);
1610 _scope({ BIO_free_all(bio
); });
1611 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1613 _assert(PKCS7_dataFinal(value_
, bio
));
1620 operator PKCS7
*() const {
1627 public std::streambuf
1630 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1634 virtual int_type
overflow(int_type next
) {
1641 uint8_t sha1_
[LDID_SHA1_DIGEST_LENGTH
];
1645 public std::streambuf
1650 LDID_SHA1_CTX sha1_
;
1651 LDID_SHA256_CTX sha256_
;
1654 HashBuffer(ldid::Hash
&hash
) :
1657 LDID_SHA1_Init(&sha1_
);
1658 LDID_SHA256_Init(&sha256_
);
1662 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1663 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1666 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1667 LDID_SHA1_Update(&sha1_
, data
, size
);
1668 LDID_SHA256_Update(&sha256_
, data
, size
);
1672 virtual int_type
overflow(int_type next
) {
1673 if (next
== traits_type::eof())
1685 std::streambuf
&buffer_
;
1688 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1694 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1695 _assert(HashBuffer::xsputn(data
, size
) == size
);
1696 return buffer_
.sputn(data
, size
);
1700 #ifndef LDID_NOTOOLS
1701 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1702 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1710 Split(const std::string
&path
) {
1711 size_t slash(path
.rfind('/'));
1712 if (slash
== std::string::npos
)
1715 dir
= path
.substr(0, slash
+ 1);
1716 base
= path
.substr(slash
+ 1);
1721 static void mkdir_p(const std::string
&path
) {
1725 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1728 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1731 auto slash(path
.rfind('/', path
.size() - 1));
1732 if (slash
== std::string::npos
)
1734 mkdir_p(path
.substr(0, slash
));
1737 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1738 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1740 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1744 static void Commit(const std::string
&path
, const std::string
&temp
) {
1746 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1748 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1750 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1753 _syscall(rename(temp
.c_str(), path
.c_str()));
1759 #ifndef LDID_NOSMIME
1760 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
1761 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
1762 _assert(index
>= 0);
1763 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
1764 _assert(next
== -1);
1765 auto entry(X509_NAME_get_entry(name
, index
));
1766 _assert(entry
!= NULL
);
1767 auto asn(X509_NAME_ENTRY_get_data(entry
));
1768 _assert(asn
!= NULL
);
1769 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1773 static void req(std::streambuf
&buffer
, uint32_t value
) {
1774 value
= Swap(value
);
1775 put(buffer
, &value
, sizeof(value
));
1778 static void req(std::streambuf
&buffer
, const std::string
&value
) {
1779 req(buffer
, value
.size());
1780 put(buffer
, value
.data(), value
.size());
1781 static uint8_t zeros
[] = {0,0,0,0};
1782 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
1785 template <size_t Size_
>
1786 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
1788 put(buffer
, data
, Size_
);
1789 static uint8_t zeros
[] = {0,0,0,0};
1790 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
1793 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, uint32_t flags
, bool platform
, const Progress
&progress
) {
1800 #ifndef LDID_NOSMIME
1803 auto name(X509_get_subject_name(stuff
));
1804 _assert(name
!= NULL
);
1805 get(team
, name
, NID_organizationalUnitName
);
1806 get(common
, name
, NID_commonName
);
1811 std::stringbuf backing
;
1813 if (!requirements
.empty()) {
1814 put(backing
, requirements
.data(), requirements
.size());
1818 std::stringbuf requirement
;
1819 req(requirement
, exprForm
);
1820 req(requirement
, opAnd
);
1821 req(requirement
, opIdent
);
1822 req(requirement
, identifier
);
1823 req(requirement
, opAnd
);
1824 req(requirement
, opAppleGenericAnchor
);
1825 req(requirement
, opAnd
);
1826 req(requirement
, opCertField
);
1827 req(requirement
, 0);
1828 req(requirement
, "subject.CN");
1829 req(requirement
, matchEqual
);
1830 req(requirement
, common
);
1831 req(requirement
, opCertGeneric
);
1832 req(requirement
, 1);
1833 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
1834 req(requirement
, matchExists
);
1835 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
1837 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
1841 // XXX: this is just a "sufficiently large number"
1842 size_t certificate(0x3000);
1844 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1845 size_t alloc(sizeof(struct SuperBlob
));
1847 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1849 uint32_t special(0);
1851 _foreach (slot
, slots
)
1852 special
= std::max(special
, slot
.first
);
1854 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1855 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1856 special
= std::max(special
, CSSLOT_INFOSLOT
);
1859 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1860 alloc
+= sizeof(struct BlobIndex
);
1861 alloc
+= backing
.str().size();
1863 if (!entitlements
.empty()) {
1864 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1865 alloc
+= sizeof(struct BlobIndex
);
1866 alloc
+= sizeof(struct Blob
);
1867 alloc
+= entitlements
.size();
1870 size_t directory(0);
1872 directory
+= sizeof(struct BlobIndex
);
1873 directory
+= sizeof(struct Blob
);
1874 directory
+= sizeof(struct CodeDirectory
);
1875 directory
+= identifier
.size() + 1;
1878 directory
+= team
.size() + 1;
1880 for (Algorithm
*algorithm
: GetAlgorithms())
1881 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
1883 #ifndef LDID_NOSMIME
1885 alloc
+= sizeof(struct BlobIndex
);
1886 alloc
+= sizeof(struct Blob
);
1887 alloc
+= certificate
;
1892 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
1896 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
1899 if (!entitlements
.empty()) {
1900 std::stringbuf data
;
1901 put(data
, entitlements
.data(), entitlements
.size());
1902 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1907 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1908 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
1909 auto &slot(posts
[CSSLOT_INFOSLOT
]);
1910 for (Algorithm
*algorithm
: GetAlgorithms())
1911 (*algorithm
)(slot
, data
, size
);
1916 for (Algorithm
*pointer
: GetAlgorithms()) {
1917 Algorithm
&algorithm(*pointer
);
1919 std::stringbuf data
;
1921 uint32_t special(0);
1922 _foreach (blob
, blobs
)
1923 special
= std::max(special
, blob
.first
);
1924 _foreach (slot
, posts
)
1925 special
= std::max(special
, slot
.first
);
1926 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1928 CodeDirectory directory
;
1929 directory
.version
= Swap(uint32_t(0x00020200));
1930 directory
.flags
= Swap(uint32_t(flags
));
1931 directory
.nSpecialSlots
= Swap(special
);
1932 directory
.codeLimit
= Swap(uint32_t(limit
));
1933 directory
.nCodeSlots
= Swap(normal
);
1934 directory
.hashSize
= algorithm
.size_
;
1935 directory
.hashType
= algorithm
.type_
;
1936 directory
.platform
= platform
? 0x01 : 0x00;
1937 directory
.pageSize
= PageShift_
;
1938 directory
.spare2
= Swap(uint32_t(0));
1939 directory
.scatterOffset
= Swap(uint32_t(0));
1940 //directory.spare3 = Swap(uint32_t(0));
1941 //directory.codeLimit64 = Swap(uint64_t(0));
1943 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1945 directory
.identOffset
= Swap(uint32_t(offset
));
1946 offset
+= identifier
.size() + 1;
1949 directory
.teamIDOffset
= Swap(uint32_t(0));
1951 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1952 offset
+= team
.size() + 1;
1955 offset
+= special
* algorithm
.size_
;
1956 directory
.hashOffset
= Swap(uint32_t(offset
));
1957 offset
+= normal
* algorithm
.size_
;
1959 put(data
, &directory
, sizeof(directory
));
1961 put(data
, identifier
.c_str(), identifier
.size() + 1);
1963 put(data
, team
.c_str(), team
.size() + 1);
1965 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
1966 auto *hashes(&storage
[special
* algorithm
.size_
]);
1968 memset(storage
.data(), 0, special
* algorithm
.size_
);
1970 _foreach (blob
, blobs
) {
1971 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1972 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
1975 _foreach (slot
, posts
)
1976 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
1980 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
1981 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1982 progress(double(i
) / normal
);
1985 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1988 put(data
, storage
.data(), storage
.size());
1990 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
1991 algorithm(hash
, save
.data(), save
.size());
1996 #ifndef LDID_NOSMIME
1999 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2000 _scope({ CFRelease(plist
); });
2002 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2003 _scope({ CFRelease(cdhashes
); });
2005 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2007 auto plist(plist_new_dict());
2008 _scope({ plist_free(plist
); });
2010 auto cdhashes(plist_new_array());
2011 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2015 for (Algorithm
*pointer
: GetAlgorithms()) {
2016 Algorithm
&algorithm(*pointer
);
2019 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2022 std::vector
<char> hash
;
2023 algorithm(hash
, blob
.data(), blob
.size());
2027 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2028 _scope({ CFRelease(value
); });
2029 CFArrayAppendValue(cdhashes
, value
);
2031 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2036 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2037 _scope({ CFRelease(created
); });
2038 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2039 auto size(CFDataGetLength(created
));
2043 plist_to_xml(plist
, &xml
, &size
);
2044 _scope({ free(xml
); });
2047 std::stringbuf data
;
2048 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2053 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2054 Buffer
result(signature
);
2055 std::string
value(result
);
2056 put(data
, value
.data(), value
.size());
2058 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2059 _assert(save
.size() <= certificate
);
2063 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2069 #ifndef LDID_NOTOOLS
2070 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2071 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
2073 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2078 std::string
DiskFolder::Path(const std::string
&path
) const {
2079 return path_
+ "/" + path
;
2082 DiskFolder::DiskFolder(const std::string
&path
) :
2087 DiskFolder::~DiskFolder() {
2088 if (!std::uncaught_exception())
2089 for (const auto &commit
: commit_
)
2090 Commit(commit
.first
, commit
.second
);
2094 std::string
readlink(const std::string
&path
) {
2095 for (size_t size(1024); ; size
*= 2) {
2099 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2100 if (size_t(writ
) >= size
)
2109 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 {
2110 std::string
path(Path(root
) + base
);
2112 DIR *dir(opendir(path
.c_str()));
2113 _assert(dir
!= NULL
);
2114 _scope({ _syscall(closedir(dir
)); });
2116 while (auto child
= readdir(dir
)) {
2117 std::string
name(child
->d_name
);
2118 if (name
== "." || name
== "..")
2120 if (Starts(name
, ".ldid."))
2127 _syscall(stat((path
+ name
).c_str(), &info
));
2129 else if (S_ISDIR(info
.st_mode
))
2131 else if (S_ISREG(info
.st_mode
))
2134 _assert_(false, "st_mode=%x", info
.st_mode
);
2136 switch (child
->d_type
) {
2144 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2147 _assert_(false, "d_type=%u", child
->d_type
);
2152 Find(root
, base
+ name
+ "/", code
, link
);
2158 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2161 std::stringbuf save
;
2165 auto from(Path(path
));
2166 commit_
[from
] = Temporary(save
, from
);
2171 bool DiskFolder::Look(const std::string
&path
) const {
2172 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2175 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2177 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2178 _assert_(result
== &data
, "DiskFolder::Open(%s)", path
.c_str());
2180 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2181 data
.pubseekpos(0, std::ios::in
);
2182 code(data
, length
, NULL
);
2185 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 {
2186 Find(path
, "", code
, link
);
2190 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2196 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2197 return parent_
.Save(path_
+ path
, edit
, flag
, code
);
2200 bool SubFolder::Look(const std::string
&path
) const {
2201 return parent_
.Look(path_
+ path
);
2204 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2205 return parent_
.Open(path_
+ path
, code
);
2208 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 {
2209 return parent_
.Find(path_
+ path
, code
, link
);
2212 std::string
UnionFolder::Map(const std::string
&path
) const {
2213 auto remap(remaps_
.find(path
));
2214 if (remap
== remaps_
.end())
2216 return remap
->second
;
2219 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 {
2220 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2221 code(file
.substr(path
.size()));
2224 UnionFolder::UnionFolder(Folder
&parent
) :
2229 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2230 return parent_
.Save(Map(path
), edit
, flag
, code
);
2233 bool UnionFolder::Look(const std::string
&path
) const {
2234 auto file(resets_
.find(path
));
2235 if (file
!= resets_
.end())
2237 return parent_
.Look(Map(path
));
2240 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2241 auto file(resets_
.find(path
));
2242 if (file
== resets_
.end())
2243 return parent_
.Open(Map(path
), code
);
2244 auto &entry(file
->second
);
2246 auto &data(*entry
.data_
);
2247 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2248 data
.pubseekpos(0, std::ios::in
);
2249 code(data
, length
, entry
.flag_
);
2252 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 {
2253 for (auto &reset
: resets_
)
2254 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2255 auto &entry(reset
.second
);
2256 auto &data(*entry
.data_
);
2257 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2258 data
.pubseekpos(0, std::ios::in
);
2259 code(data
, length
, entry
.flag_
);
2262 for (auto &remap
: remaps_
)
2263 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2264 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2265 code(data
, length
, flag
);
2269 parent_
.Find(path
, fun([&](const std::string
&name
) {
2270 if (deletes_
.find(path
+ name
) == deletes_
.end())
2272 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2273 if (deletes_
.find(path
+ name
) == deletes_
.end())
2278 #ifndef LDID_NOTOOLS
2279 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2283 char data
[4096 * 4];
2284 size_t writ(source
.sgetn(data
, sizeof(data
)));
2287 _assert(target
.sputn(data
, writ
) == writ
);
2289 progress(double(total
) / length
);
2293 #ifndef LDID_NOPLIST
2294 static plist_t
plist(const std::string
&data
) {
2295 plist_t
plist(NULL
);
2296 if (Starts(data
, "bplist00"))
2297 plist_from_bin(data
.data(), data
.size(), &plist
);
2299 plist_from_xml(data
.data(), data
.size(), &plist
);
2300 _assert(plist
!= NULL
);
2304 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2305 std::stringbuf data
;
2306 copy(buffer
, data
, length
, dummy_
);
2307 auto node(plist(data
.str()));
2308 _scope({ plist_free(node
); });
2309 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2313 static std::string
plist_s(plist_t node
) {
2314 _assert(node
!= NULL
);
2315 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2317 plist_get_string_val(node
, &data
);
2318 _scope({ free(data
); });
2334 std::vector
<std::string
> matches_
;
2337 Expression(const std::string
&code
) {
2338 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2339 matches_
.resize(regex_
.re_nsub
+ 1);
2346 bool operator ()(const std::string
&data
) {
2347 regmatch_t matches
[matches_
.size()];
2348 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2349 if (value
== REG_NOMATCH
)
2351 _assert_(value
== 0, "regexec()");
2352 for (size_t i(0); i
!= matches_
.size(); ++i
)
2353 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2357 const std::string
&operator [](size_t index
) const {
2358 return matches_
[index
];
2367 mutable std::auto_ptr
<Expression
> regex_
;
2369 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2376 Rule(const Rule
&rhs
) :
2377 weight_(rhs
.weight_
),
2383 void Compile() const {
2384 regex_
.reset(new Expression(code_
));
2387 bool operator ()(const std::string
&data
) const {
2388 _assert(regex_
.get() != NULL
);
2389 return (*regex_
)(data
);
2392 bool operator <(const Rule
&rhs
) const {
2393 if (weight_
> rhs
.weight_
)
2395 if (weight_
< rhs
.weight_
)
2397 return mode_
> rhs
.mode_
;
2402 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2403 return lhs
->code_
< rhs
->code_
;
2407 #ifndef LDID_NOPLIST
2408 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
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2409 // XXX: this is a miserable fail
2410 std::stringbuf temp
;
2411 put(temp
, prefix
, size
);
2412 copy(buffer
, temp
, length
- size
, progress
);
2413 // XXX: this is a stupid hack
2414 pad(temp
, 0x10 - (length
& 0xf));
2415 auto data(temp
.str());
2417 HashProxy
proxy(hash
, save
);
2418 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, requirements
, key
, slots
, flags
, platform
, progress
);
2421 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, Hash
> &remote
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2422 std::string executable
;
2423 std::string identifier
;
2427 std::string
info("Info.plist");
2428 if (!folder
.Look(info
) && folder
.Look("Resources/" + info
)) {
2430 info
= "Resources/" + info
;
2433 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2434 plist_d(buffer
, length
, fun([&](plist_t node
) {
2435 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2436 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2440 if (!mac
&& folder
.Look("MacOS/" + executable
)) {
2441 executable
= "MacOS/" + executable
;
2445 progress(root
+ "*");
2447 std::string entitlements
;
2448 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2449 // XXX: this is a miserable fail
2450 std::stringbuf temp
;
2451 copy(buffer
, temp
, length
, progress
);
2452 // XXX: this is a stupid hack
2453 pad(temp
, 0x10 - (length
& 0xf));
2454 auto data(temp
.str());
2455 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2458 static const std::string
directory("_CodeSignature/");
2459 static const std::string
signature(directory
+ "CodeResources");
2461 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2463 auto &rules1(versions
[""]);
2464 auto &rules2(versions
["2"]);
2466 const std::string
resources(mac
? "Resources/" : "");
2469 rules1
.insert(Rule
{1, NoMode
, "^" + resources
});
2470 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2471 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2472 rules1
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2473 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2477 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2478 rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2479 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2480 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2481 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2482 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2483 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2484 rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2485 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2486 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2487 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2488 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2489 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2492 std::map
<std::string
, Hash
> local
;
2494 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2495 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2496 std::map
<std::string
, Bundle
> bundles
;
2498 folder
.Find("", fun([&](const std::string
&name
) {
2501 auto bundle(root
+ Split(name
).dir
);
2502 bundle
.resize(bundle
.size() - resources
.size());
2503 SubFolder
subfolder(folder
, bundle
);
2505 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2506 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2508 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2511 std::set
<std::string
> excludes
;
2513 auto exclude([&](const std::string
&name
) {
2514 // BundleDiskRep::adjustResources -> builder.addExclusion
2515 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2518 for (const auto &bundle
: bundles
)
2519 if (Starts(name
, bundle
.first
+ "/")) {
2520 excludes
.insert(name
);
2527 std::map
<std::string
, std::string
> links
;
2529 folder
.Find("", fun([&](const std::string
&name
) {
2533 if (local
.find(name
) != local
.end())
2535 auto &hash(local
[name
]);
2537 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2538 progress(root
+ name
);
2549 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2551 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2552 switch (Swap(header
.magic
)) {
2554 // Java class file format
2555 if (Swap(header
.count
) >= 40)
2558 case MH_MAGIC
: case MH_MAGIC_64
:
2559 case MH_CIGAM
: case MH_CIGAM_64
:
2560 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2562 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2567 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2568 HashProxy
proxy(hash
, save
);
2569 put(proxy
, header
.bytes
, size
);
2570 copy(data
, proxy
, length
- size
, progress
);
2573 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2577 links
[name
] = read();
2580 auto plist(plist_new_dict());
2581 _scope({ plist_free(plist
); });
2583 for (const auto &version
: versions
) {
2584 auto files(plist_new_dict());
2585 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2587 for (const auto &rule
: version
.second
)
2590 bool old(&version
.second
== &rules1
);
2592 for (const auto &hash
: local
)
2593 for (const auto &rule
: version
.second
)
2594 if (rule(hash
.first
)) {
2595 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2596 else if (old
&& rule
.mode_
== NoMode
)
2597 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2598 else if (rule
.mode_
!= OmitMode
) {
2599 auto entry(plist_new_dict());
2600 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2602 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2603 if (rule
.mode_
== OptionalMode
)
2604 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2605 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2611 for (const auto &link
: links
)
2612 for (const auto &rule
: version
.second
)
2613 if (rule(link
.first
)) {
2614 if (rule
.mode_
!= OmitMode
) {
2615 auto entry(plist_new_dict());
2616 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2617 if (rule
.mode_
== OptionalMode
)
2618 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2619 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2626 for (const auto &bundle
: bundles
) {
2627 auto entry(plist_new_dict());
2628 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2629 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2630 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2634 for (const auto &version
: versions
) {
2635 auto rules(plist_new_dict());
2636 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2638 std::multiset
<const Rule
*, RuleCode
> ordered
;
2639 for (const auto &rule
: version
.second
)
2640 ordered
.insert(&rule
);
2642 for (const auto &rule
: ordered
)
2643 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2644 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2646 auto entry(plist_new_dict());
2647 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2649 switch (rule
->mode_
) {
2653 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2656 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2659 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2662 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2666 if (rule
->weight_
>= 10000)
2667 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2668 else if (rule
->weight_
!= 1)
2669 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2673 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2674 HashProxy
proxy(local
[signature
], save
);
2677 plist_to_xml(plist
, &xml
, &size
);
2678 _scope({ free(xml
); });
2679 put(proxy
, xml
, size
);
2683 bundle
.path
= executable
;
2685 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2686 progress(root
+ executable
);
2687 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2689 slots
[1] = local
.at(info
);
2690 slots
[3] = local
.at(signature
);
2691 bundle
.hash
= Sign(NULL
, 0, buffer
, local
[executable
], save
, identifier
, entitlements
, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
2695 for (const auto &entry
: local
)
2696 remote
[root
+ entry
.first
] = entry
.second
;
2701 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
) {
2702 std::map
<std::string
, Hash
> local
;
2703 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
2710 #ifndef LDID_NOTOOLS
2711 int main(int argc
, char *argv
[]) {
2712 #ifndef LDID_NOSMIME
2713 OpenSSL_add_all_algorithms();
2721 little_
= endian
.byte
[0];
2727 #ifndef LDID_NOFLAGT
2742 bool platform(false);
2744 uint32_t flag_CPUType(_not(uint32_t));
2745 uint32_t flag_CPUSubtype(_not(uint32_t));
2747 const char *flag_I(NULL
);
2749 #ifndef LDID_NOFLAGT
2759 std::vector
<std::string
> files
;
2762 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2763 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2764 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2765 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2769 for (int argi(1); argi
!= argc
; ++argi
)
2770 if (argv
[argi
][0] != '-')
2771 files
.push_back(argv
[argi
]);
2772 else switch (argv
[argi
][1]) {
2779 case 'e': flag_e
= true; break;
2782 const char *string
= argv
[argi
] + 2;
2783 const char *colon
= strchr(string
, ':');
2784 _assert(colon
!= NULL
);
2785 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2787 unsigned number(strtoul(string
, &arge
, 0));
2788 _assert(arge
== colon
);
2789 auto &slot(slots
[number
]);
2790 for (Algorithm
*algorithm
: GetAlgorithms())
2791 (*algorithm
)(slot
, file
.data(), file
.size());
2794 case 'q': flag_q
= true; break;
2797 const char *xml
= argv
[argi
] + 2;
2798 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2801 case 'D': flag_D
= true; break;
2803 case 'a': flag_a
= true; break;
2808 if (argv
[argi
][2] != '\0') {
2809 const char *cpu
= argv
[argi
] + 2;
2810 const char *colon
= strchr(cpu
, ':');
2811 _assert(colon
!= NULL
);
2813 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2814 _assert(arge
== colon
);
2815 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2816 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2821 const char *name
= argv
[argi
] + 2;
2823 else if (strcmp(name
, "host") == 0)
2824 flags
|= kSecCodeSignatureHost
;
2825 else if (strcmp(name
, "adhoc") == 0)
2826 flags
|= kSecCodeSignatureAdhoc
;
2827 else if (strcmp(name
, "hard") == 0)
2828 flags
|= kSecCodeSignatureForceHard
;
2829 else if (strcmp(name
, "kill") == 0)
2830 flags
|= kSecCodeSignatureForceKill
;
2831 else if (strcmp(name
, "expires") == 0)
2832 flags
|= kSecCodeSignatureForceExpiration
;
2833 else if (strcmp(name
, "restrict") == 0)
2834 flags
|= kSecCodeSignatureRestrict
;
2835 else if (strcmp(name
, "enforcement") == 0)
2836 flags
|= kSecCodeSignatureEnforcement
;
2837 else if (strcmp(name
, "library-validation") == 0)
2838 flags
|= kSecCodeSignatureLibraryValidation
;
2839 else _assert(false);
2856 if (argv
[argi
][2] != '\0') {
2857 const char *xml
= argv
[argi
] + 2;
2858 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2863 if (argv
[argi
][2] != '\0')
2864 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2867 #ifndef LDID_NOFLAGT
2870 if (argv
[argi
][2] == '-')
2874 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2875 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2885 flag_I
= argv
[argi
] + 2;
2893 _assert(flag_S
|| key
.empty());
2894 _assert(flag_S
|| flag_I
== NULL
);
2896 if (files
.empty()) usage
: {
2900 size_t filei(0), filee(0);
2901 _foreach (file
, files
) try {
2902 std::string
path(file
);
2905 _syscall(stat(path
.c_str(), &info
));
2907 if (S_ISDIR(info
.st_mode
)) {
2908 #ifndef LDID_NOPLIST
2910 ldid::DiskFolder
folder(path
);
2911 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
2915 } else if (flag_S
|| flag_r
) {
2916 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2918 std::filebuf output
;
2920 auto temp(Temporary(output
, split
));
2923 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
2925 std::string
identifier(flag_I
?: split
.base
.c_str());
2926 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, requirements
, key
, slots
, flags
, platform
, dummy_
);
2933 #ifndef LDID_NOFLAGT
2940 Map
mapping(path
, modify
);
2941 FatHeader
fat_header(mapping
.data(), mapping
.size());
2943 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2944 struct linkedit_data_command
*signature(NULL
);
2945 struct encryption_info_command
*encryption(NULL
);
2948 if (mach_header
.GetCPUType() != flag_CPUType
)
2950 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2955 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2957 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2958 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2961 else if (cmd
== LC_CODE_SIGNATURE
)
2962 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2963 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2964 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2965 else if (cmd
== LC_LOAD_DYLIB
) {
2966 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2967 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2969 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2972 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2973 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2977 #ifndef LDID_NOFLAGT
2978 else if (cmd
== LC_ID_DYLIB
) {
2979 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2987 dylib_command
->dylib
.timestamp
= 0;
2988 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2991 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2998 _assert(encryption
!= NULL
);
2999 encryption
->cryptid
= mach_header
.Swap(0);
3003 _assert(signature
!= NULL
);
3005 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3007 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3008 uint8_t *blob
= top
+ data
;
3009 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3011 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3012 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3013 uint32_t begin
= Swap(super
->index
[index
].offset
);
3014 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3015 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3020 _assert(signature
!= NULL
);
3022 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3024 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3025 uint8_t *blob
= top
+ data
;
3026 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3028 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3029 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3030 uint32_t begin
= Swap(super
->index
[index
].offset
);
3031 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3032 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3037 _assert(signature
!= NULL
);
3039 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3041 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3042 uint8_t *blob
= top
+ data
;
3043 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3045 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3046 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3047 uint32_t begin
= Swap(super
->index
[index
].offset
);
3048 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3050 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3051 uint32_t pages
= Swap(directory
->nCodeSlots
);
3054 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3055 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3057 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3063 } catch (const char *) {