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>
92 #define _assert___(line) \
94 #define _assert__(line) \
98 #define $(value) value
102 #define _assert_(expr, format, ...) \
104 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
105 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
108 // XXX: this is not acceptable
109 #define _assert_(expr, format, ...) \
111 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
116 #define _assert(expr) \
117 _assert_(expr, "%s", $(#expr))
119 #define _syscall(expr, ...) [&] { for (;;) { \
121 if ((long) _value != -1) \
124 if (error == EINTR) \
126 /* XXX: EINTR is included in this list to fix g++ */ \
127 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
128 if (error == success) \
129 return (decltype(expr)) -success; \
130 _assert_(false, "errno=%u", error); \
134 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
140 __attribute__((packed))
142 template <typename Type_
>
144 typedef typename
Type_::const_iterator Result
;
147 #define _foreach(item, list) \
148 for (bool _stop(true); _stop; ) \
149 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
150 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
151 for (bool _suck(true); _suck; _suck = false) \
152 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
157 template <typename Function_
>
165 Scope(const Function_
&function
) :
175 template <typename Function_
>
176 Scope
<Function_
> _scope(const Function_
&function
) {
177 return Scope
<Function_
>(function
);
180 #define _scope__(counter, function) \
181 __attribute__((__unused__)) \
182 const _Scope &_scope ## counter(_scope([&]function))
183 #define _scope_(counter, function) \
184 _scope__(counter, function)
185 #define _scope(function) \
186 _scope_(__COUNTER__, function)
188 #define CPU_ARCH_MASK uint32_t(0xff000000)
189 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
191 #define CPU_TYPE_ANY uint32_t(-1)
192 #define CPU_TYPE_VAX uint32_t( 1)
193 #define CPU_TYPE_MC680x0 uint32_t( 6)
194 #define CPU_TYPE_X86 uint32_t( 7)
195 #define CPU_TYPE_MC98000 uint32_t(10)
196 #define CPU_TYPE_HPPA uint32_t(11)
197 #define CPU_TYPE_ARM uint32_t(12)
198 #define CPU_TYPE_MC88000 uint32_t(13)
199 #define CPU_TYPE_SPARC uint32_t(14)
200 #define CPU_TYPE_I860 uint32_t(15)
201 #define CPU_TYPE_POWERPC uint32_t(18)
203 #define CPU_TYPE_I386 CPU_TYPE_X86
205 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
206 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
207 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
214 #define FAT_MAGIC 0xcafebabe
215 #define FAT_CIGAM 0xbebafeca
235 #define MH_MAGIC 0xfeedface
236 #define MH_CIGAM 0xcefaedfe
238 #define MH_MAGIC_64 0xfeedfacf
239 #define MH_CIGAM_64 0xcffaedfe
241 #define MH_DYLDLINK 0x4
243 #define MH_OBJECT 0x1
244 #define MH_EXECUTE 0x2
246 #define MH_BUNDLE 0x8
247 #define MH_DYLIB_STUB 0x9
249 struct load_command
{
254 #define LC_REQ_DYLD uint32_t(0x80000000)
256 #define LC_SEGMENT uint32_t(0x01)
257 #define LC_SYMTAB uint32_t(0x02)
258 #define LC_DYSYMTAB uint32_t(0x0b)
259 #define LC_LOAD_DYLIB uint32_t(0x0c)
260 #define LC_ID_DYLIB uint32_t(0x0d)
261 #define LC_SEGMENT_64 uint32_t(0x19)
262 #define LC_UUID uint32_t(0x1b)
263 #define LC_CODE_SIGNATURE uint32_t(0x1d)
264 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
265 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
266 #define LC_ENCRYPTION_INFO uint32_t(0x21)
267 #define LC_DYLD_INFO uint32_t(0x22)
268 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
269 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
284 uint32_t current_version
;
285 uint32_t compatibility_version
;
288 struct dylib_command
{
294 struct uuid_command
{
300 struct symtab_command
{
309 struct dyld_info_command
{
313 uint32_t rebase_size
;
316 uint32_t weak_bind_off
;
317 uint32_t weak_bind_size
;
318 uint32_t lazy_bind_off
;
319 uint32_t lazy_bind_size
;
321 uint32_t export_size
;
324 struct dysymtab_command
{
337 uint32_t extrefsymoff
;
338 uint32_t nextrefsyms
;
339 uint32_t indirectsymoff
;
340 uint32_t nindirectsyms
;
347 struct dylib_table_of_contents
{
348 uint32_t symbol_index
;
349 uint32_t module_index
;
352 struct dylib_module
{
353 uint32_t module_name
;
362 uint32_t iinit_iterm
;
363 uint32_t ninit_nterm
;
364 uint32_t objc_module_info_addr
;
365 uint32_t objc_module_info_size
;
368 struct dylib_reference
{
373 struct relocation_info
{
375 uint32_t r_symbolnum
:24;
394 struct segment_command
{
408 struct segment_command_64
{
451 struct linkedit_data_command
{
458 struct encryption_info_command
{
466 #define BIND_OPCODE_MASK 0xf0
467 #define BIND_IMMEDIATE_MASK 0x0f
468 #define BIND_OPCODE_DONE 0x00
469 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
470 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
471 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
472 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
473 #define BIND_OPCODE_SET_TYPE_IMM 0x50
474 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
475 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
476 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
477 #define BIND_OPCODE_DO_BIND 0x90
478 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
479 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
480 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
482 static auto dummy([](double) {});
484 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
485 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
490 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
491 _assert(read(stream
, data
, size
) == size
);
494 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
495 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
498 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Functor
<void (double)> &percent
) {
500 for (size_t total(0); total
!= size
;) {
501 auto writ(std::min(size
- total
, size_t(4096 * 4)));
502 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
504 percent(double(total
) / size
);
508 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
511 if (auto writ
= read(stream
, data
, size
))
517 static inline void pad(std::streambuf
&stream
, size_t size
) {
519 memset(padding
, 0, size
);
520 put(stream
, padding
, size
);
523 template <typename Type_
>
524 Type_
Align(Type_ value
, size_t align
) {
531 static const uint8_t PageShift_(0x0c);
532 static const uint32_t PageSize_(1 << PageShift_
);
534 static inline uint16_t Swap_(uint16_t value
) {
536 ((value
>> 8) & 0x00ff) |
537 ((value
<< 8) & 0xff00);
540 static inline uint32_t Swap_(uint32_t value
) {
541 value
= ((value
>> 8) & 0x00ff00ff) |
542 ((value
<< 8) & 0xff00ff00);
543 value
= ((value
>> 16) & 0x0000ffff) |
544 ((value
<< 16) & 0xffff0000);
548 static inline uint64_t Swap_(uint64_t value
) {
549 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
550 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
551 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
555 static inline int16_t Swap_(int16_t value
) {
556 return Swap_(static_cast<uint16_t>(value
));
559 static inline int32_t Swap_(int32_t value
) {
560 return Swap_(static_cast<uint32_t>(value
));
563 static inline int64_t Swap_(int64_t value
) {
564 return Swap_(static_cast<uint64_t>(value
));
567 static bool little_(true);
569 static inline uint16_t Swap(uint16_t value
) {
570 return little_
? Swap_(value
) : value
;
573 static inline uint32_t Swap(uint32_t value
) {
574 return little_
? Swap_(value
) : value
;
577 static inline uint64_t Swap(uint64_t value
) {
578 return little_
? Swap_(value
) : value
;
581 static inline int16_t Swap(int16_t value
) {
582 return Swap(static_cast<uint16_t>(value
));
585 static inline int32_t Swap(int32_t value
) {
586 return Swap(static_cast<uint32_t>(value
));
589 static inline int64_t Swap(int64_t value
) {
590 return Swap(static_cast<uint64_t>(value
));
603 Swapped(bool swapped
) :
608 template <typename Type_
>
609 Type_
Swap(Type_ value
) const {
610 return swapped_
? Swap_(value
) : value
;
622 Data(void *base
, size_t size
) :
628 void *GetBase() const {
632 size_t GetSize() const {
643 struct mach_header
*mach_header_
;
644 struct load_command
*load_command_
;
647 MachHeader(void *base
, size_t size
) :
650 mach_header_
= (mach_header
*) base
;
652 switch (Swap(mach_header_
->magic
)) {
654 swapped_
= !swapped_
;
660 swapped_
= !swapped_
;
669 void *post
= mach_header_
+ 1;
671 post
= (uint32_t *) post
+ 1;
672 load_command_
= (struct load_command
*) post
;
675 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
676 Swap(mach_header_
->filetype
) == MH_DYLIB
||
677 Swap(mach_header_
->filetype
) == MH_BUNDLE
681 bool Bits64() const {
685 struct mach_header
*operator ->() const {
689 operator struct mach_header
*() const {
693 uint32_t GetCPUType() const {
694 return Swap(mach_header_
->cputype
);
697 uint32_t GetCPUSubtype() const {
698 return Swap(mach_header_
->cpusubtype
) & 0xff;
701 struct load_command
*GetLoadCommand() const {
702 return load_command_
;
705 std::vector
<struct load_command
*> GetLoadCommands() const {
706 std::vector
<struct load_command
*> load_commands
;
708 struct load_command
*load_command
= load_command_
;
709 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
710 load_commands
.push_back(load_command
);
711 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
714 return load_commands
;
717 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
718 _foreach (load_command
, GetLoadCommands())
719 switch (Swap(load_command
->cmd
)) {
721 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
722 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
723 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
724 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
725 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
728 case LC_SEGMENT_64
: {
729 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
730 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
731 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
732 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
733 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
738 template <typename Target_
>
739 Target_
*GetOffset(uint32_t offset
) const {
740 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
744 class FatMachHeader
:
751 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
752 MachHeader(base
, size
),
757 fat_arch
*GetFatArch() const {
766 fat_header
*fat_header_
;
767 std::vector
<FatMachHeader
> mach_headers_
;
770 FatHeader(void *base
, size_t size
) :
773 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
775 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
776 swapped_
= !swapped_
;
778 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
780 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
782 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
783 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
785 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
786 uint32_t arch_offset
= Swap(fat_arch
->offset
);
787 uint32_t arch_size
= Swap(fat_arch
->size
);
788 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
794 std::vector
<FatMachHeader
> &GetMachHeaders() {
795 return mach_headers_
;
799 return fat_header_
!= NULL
;
802 struct fat_header
*operator ->() const {
806 operator struct fat_header
*() const {
811 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
812 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
813 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
814 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
815 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
816 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
817 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
818 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
820 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
821 #define CSSLOT_INFOSLOT uint32_t(0x00001)
822 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
823 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
824 #define CSSLOT_APPLICATION uint32_t(0x00004)
825 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
826 #define CSSLOT_ALTERNATE uint32_t(0x01000)
828 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
830 #define CS_HASHTYPE_SHA160_160 1
831 #define CS_HASHTYPE_SHA256_256 2
832 #define CS_HASHTYPE_SHA256_160 3
833 #define CS_HASHTYPE_SHA386_386 4
848 struct BlobIndex index
[];
851 struct CodeDirectory
{
855 uint32_t identOffset
;
856 uint32_t nSpecialSlots
;
864 uint32_t scatterOffset
;
865 uint32_t teamIDOffset
;
867 //uint64_t codeLimit64;
870 enum Kind
: uint32_t {
871 exprForm
= 1, // prefix expr form
874 enum ExprOp
: uint32_t {
875 opFalse
, // unconditionally false
876 opTrue
, // unconditionally true
877 opIdent
, // match canonical code [string]
878 opAppleAnchor
, // signed by Apple as Apple's product
879 opAnchorHash
, // match anchor [cert hash]
880 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
881 opAnd
, // binary prefix expr AND expr [expr; expr]
882 opOr
, // binary prefix expr OR expr [expr; expr]
883 opCDHash
, // match hash of CodeDirectory directly [cd hash]
884 opNot
, // logical inverse [expr]
885 opInfoKeyField
, // Info.plist key field [string; match suffix]
886 opCertField
, // Certificate field [cert index; field name; match suffix]
887 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
888 opTrustedCerts
, // require trust settings to approve the cert chain
889 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
890 opAppleGenericAnchor
, // signed by Apple in any capacity
891 opEntitlementField
, // entitlement dictionary field [string; match suffix]
892 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
893 opNamedAnchor
, // named anchor type
894 opNamedCode
, // named subroutine
895 opPlatform
, // platform constraint [integer]
896 exprOpCount
// (total opcode count in use)
899 enum MatchOperation
{
900 matchExists
, // anything but explicit "false" - no value stored
901 matchEqual
, // equal (CFEqual)
902 matchContains
, // partial match (substring)
903 matchBeginsWith
, // partial match (initial substring)
904 matchEndsWith
, // partial match (terminal substring)
905 matchLessThan
, // less than (string with numeric comparison)
906 matchGreaterThan
, // greater than (string with numeric comparison)
907 matchLessEqual
, // less or equal (string with numeric comparison)
908 matchGreaterEqual
, // greater or equal (string with numeric comparison)
911 #define OID_ISO_MEMBER 42
912 #define OID_US OID_ISO_MEMBER, 134, 72
913 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
914 #define APPLE_ADS_OID APPLE_OID, 0x64
915 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
918 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
925 Algorithm(size_t size
, uint8_t type
) :
931 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
933 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
934 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
935 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
938 struct AlgorithmSHA1
:
942 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
946 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
950 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
951 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
954 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
955 return operator()(hash
.sha1_
, data
, size
);
958 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
959 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
960 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
964 struct AlgorithmSHA256
:
968 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
972 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
976 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
977 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
980 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
981 return operator()(hash
.sha256_
, data
, size
);
984 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
985 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
986 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
990 static const std::vector
<Algorithm
*> &GetAlgorithms() {
991 static AlgorithmSHA1 sha1
;
992 static AlgorithmSHA256 sha256
;
994 static Algorithm
*array
[] = {
999 static std::vector
<Algorithm
*> algorithms(array
, array
+ sizeof(array
) / sizeof(array
[0]));
1003 struct CodesignAllocation
{
1004 FatMachHeader mach_header_
;
1011 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
1012 mach_header_(mach_header
),
1022 #ifndef LDID_NOTOOLS
1035 _syscall(close(file_
));
1038 void open(const char *path
, int flags
) {
1039 _assert(file_
== -1);
1040 file_
= _syscall(::open(path
, flags
));
1057 _syscall(munmap(data_
, size_
));
1069 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1072 open(path
, oflag
, pflag
, mflag
);
1075 Map(const std::string
&path
, bool edit
) :
1085 bool empty() const {
1086 return data_
== NULL
;
1089 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1092 file_
.open(path
.c_str(), oflag
);
1093 int file(file_
.file());
1096 _syscall(fstat(file
, &stat
));
1097 size_
= stat
.st_size
;
1099 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1102 void open(const std::string
&path
, bool edit
) {
1104 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1106 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1109 void *data() const {
1113 size_t size() const {
1117 operator std::string() const {
1118 return std::string(static_cast<char *>(data_
), size_
);
1125 std::string
Analyze(const void *data
, size_t size
) {
1126 std::string entitlements
;
1128 FatHeader
fat_header(const_cast<void *>(data
), size
);
1129 _foreach (mach_header
, fat_header
.GetMachHeaders())
1130 _foreach (load_command
, mach_header
.GetLoadCommands())
1131 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1132 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1133 auto offset(mach_header
.Swap(signature
->dataoff
));
1134 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1135 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1137 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1138 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1139 auto begin(Swap(super
->index
[index
].offset
));
1140 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1141 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1143 if (entitlements
.empty())
1144 entitlements
.assign(reinterpret_cast<char *>(blob
+ 1), writ
);
1146 _assert(entitlements
.compare(0, entitlements
.size(), reinterpret_cast<char *>(blob
+ 1), writ
) == 0);
1150 return entitlements
;
1153 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 Functor
<void (double)> &)> &save
, const Functor
<void (double)> &percent
) {
1154 FatHeader
source(const_cast<void *>(idata
), isize
);
1158 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1160 std::vector
<CodesignAllocation
> allocations
;
1161 _foreach (mach_header
, source
.GetMachHeaders()) {
1162 struct linkedit_data_command
*signature(NULL
);
1163 struct symtab_command
*symtab(NULL
);
1165 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1166 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1168 else if (cmd
== LC_CODE_SIGNATURE
)
1169 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1170 else if (cmd
== LC_SYMTAB
)
1171 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1175 if (signature
== NULL
)
1176 size
= mach_header
.GetSize();
1178 size
= mach_header
.Swap(signature
->dataoff
);
1179 _assert(size
<= mach_header
.GetSize());
1182 if (symtab
!= NULL
) {
1183 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1184 _assert(end
<= size
);
1185 _assert(end
>= size
- 0x10);
1189 size_t alloc(allocate(mach_header
, size
));
1191 auto *fat_arch(mach_header
.GetFatArch());
1194 if (fat_arch
!= NULL
)
1195 align
= source
.Swap(fat_arch
->align
);
1196 else switch (mach_header
.GetCPUType()) {
1197 case CPU_TYPE_POWERPC
:
1198 case CPU_TYPE_POWERPC64
:
1200 case CPU_TYPE_X86_64
:
1204 case CPU_TYPE_ARM64
:
1212 offset
= Align(offset
, 1 << align
);
1214 uint32_t limit(size
);
1216 limit
= Align(limit
, 0x10);
1218 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1219 offset
+= size
+ alloc
;
1220 offset
= Align(offset
, 0x10);
1225 if (source
.IsFat()) {
1226 fat_header fat_header
;
1227 fat_header
.magic
= Swap(FAT_MAGIC
);
1228 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1229 put(output
, &fat_header
, sizeof(fat_header
));
1230 position
+= sizeof(fat_header
);
1232 _foreach (allocation
, allocations
) {
1233 auto &mach_header(allocation
.mach_header_
);
1236 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1237 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1238 fat_arch
.offset
= Swap(allocation
.offset_
);
1239 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1240 fat_arch
.align
= Swap(allocation
.align_
);
1241 put(output
, &fat_arch
, sizeof(fat_arch
));
1242 position
+= sizeof(fat_arch
);
1246 _foreach (allocation
, allocations
) {
1247 auto &mach_header(allocation
.mach_header_
);
1249 pad(output
, allocation
.offset_
- position
);
1250 position
= allocation
.offset_
;
1252 std::vector
<std::string
> commands
;
1254 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1255 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1257 switch (mach_header
.Swap(load_command
->cmd
)) {
1258 case LC_CODE_SIGNATURE
:
1263 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1264 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1266 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1267 segment_command
->filesize
= size
;
1268 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1271 case LC_SEGMENT_64
: {
1272 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1273 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1275 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1276 segment_command
->filesize
= size
;
1277 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1281 commands
.push_back(copy
);
1284 if (allocation
.alloc_
!= 0) {
1285 linkedit_data_command signature
;
1286 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1287 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1288 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1289 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1290 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1293 size_t begin(position
);
1296 _foreach(command
, commands
)
1297 after
+= command
.size();
1299 std::stringbuf altern
;
1301 struct mach_header
header(*mach_header
);
1302 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1303 header
.sizeofcmds
= mach_header
.Swap(after
);
1304 put(output
, &header
, sizeof(header
));
1305 put(altern
, &header
, sizeof(header
));
1306 position
+= sizeof(header
);
1308 if (mach_header
.Bits64()) {
1309 auto pad(mach_header
.Swap(uint32_t(0)));
1310 put(output
, &pad
, sizeof(pad
));
1311 put(altern
, &pad
, sizeof(pad
));
1312 position
+= sizeof(pad
);
1315 _foreach(command
, commands
) {
1316 put(output
, command
.data(), command
.size());
1317 put(altern
, command
.data(), command
.size());
1318 position
+= command
.size();
1321 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1322 if (before
> after
) {
1323 pad(output
, before
- after
);
1324 pad(altern
, before
- after
);
1325 position
+= before
- after
;
1328 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1330 std::string
overlap(altern
.str());
1331 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1333 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), percent
);
1334 position
= begin
+ allocation
.size_
;
1336 pad(output
, allocation
.limit_
- allocation
.size_
);
1337 position
+= allocation
.limit_
- allocation
.size_
;
1339 size_t saved(save(mach_header
, output
, allocation
.limit_
, overlap
, top
, percent
));
1340 if (allocation
.alloc_
> saved
)
1341 pad(output
, allocation
.alloc_
- saved
);
1343 _assert(allocation
.alloc_
== saved
);
1344 position
+= allocation
.alloc_
;
1350 typedef std::map
<uint32_t, std::string
> Blobs
;
1352 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1353 auto value(buffer
.str());
1354 std::swap(blobs
[slot
], value
);
1357 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1358 auto value(buffer
.str());
1360 blob
.magic
= Swap(magic
);
1361 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1362 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1363 auto &save(blobs
[slot
]);
1364 std::swap(save
, value
);
1368 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1370 _foreach (blob
, blobs
)
1371 total
+= blob
.second
.size();
1373 struct SuperBlob super
;
1374 super
.blob
.magic
= Swap(magic
);
1375 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1376 super
.count
= Swap(uint32_t(blobs
.size()));
1377 put(output
, &super
, sizeof(super
));
1379 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1381 _foreach (blob
, blobs
) {
1383 index
.type
= Swap(blob
.first
);
1384 index
.offset
= Swap(uint32_t(offset
));
1385 put(output
, &index
, sizeof(index
));
1386 offset
+= blob
.second
.size();
1389 _foreach (blob
, blobs
)
1390 put(output
, blob
.second
.data(), blob
.second
.size());
1395 #ifndef LDID_NOSMIME
1404 _assert(bio_
!= NULL
);
1408 bio_(BIO_new(BIO_s_mem()))
1412 Buffer(const char *data
, size_t size
) :
1413 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1417 Buffer(const std::string
&data
) :
1418 Buffer(data
.data(), data
.size())
1422 Buffer(PKCS7
*pkcs
) :
1425 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1432 operator BIO
*() const {
1436 explicit operator std::string() const {
1438 auto size(BIO_get_mem_data(bio_
, &data
));
1439 return std::string(data
, size
);
1448 STACK_OF(X509
) *ca_
;
1452 value_(d2i_PKCS12_bio(bio
, NULL
)),
1455 _assert(value_
!= NULL
);
1456 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1457 _assert(key_
!= NULL
);
1458 _assert(cert_
!= NULL
);
1461 Stuff(const std::string
&data
) :
1467 sk_X509_pop_free(ca_
, X509_free
);
1469 EVP_PKEY_free(key_
);
1470 PKCS12_free(value_
);
1473 operator PKCS12
*() const {
1477 operator EVP_PKEY
*() const {
1481 operator X509
*() const {
1485 operator STACK_OF(X509
) *() const {
1495 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1496 value_
= PKCS7_new();
1497 _assert(value_
!= NULL
);
1499 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1500 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1502 STACK_OF(X509
) *certs(stuff
);
1503 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1504 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1506 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1507 _assert(info
!= NULL
);
1509 PKCS7_set_detached(value_
, 1);
1511 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1512 _assert(string
!= NULL
);
1514 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1516 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1517 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1519 ASN1_OCTET_STRING_free(string
);
1523 _assert(PKCS7_final(value_
, data
, PKCS7_BINARY
));
1530 operator PKCS7
*() const {
1537 public std::streambuf
1540 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1544 virtual int_type
overflow(int_type next
) {
1551 uint8_t sha1_
[LDID_SHA1_DIGEST_LENGTH
];
1555 public std::streambuf
1560 LDID_SHA1_CTX sha1_
;
1561 LDID_SHA256_CTX sha256_
;
1564 HashBuffer(ldid::Hash
&hash
) :
1567 LDID_SHA1_Init(&sha1_
);
1568 LDID_SHA256_Init(&sha256_
);
1572 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1573 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1576 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1577 LDID_SHA1_Update(&sha1_
, data
, size
);
1578 LDID_SHA256_Update(&sha256_
, data
, size
);
1582 virtual int_type
overflow(int_type next
) {
1583 if (next
== traits_type::eof())
1595 std::streambuf
&buffer_
;
1598 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1604 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1605 _assert(HashBuffer::xsputn(data
, size
) == size
);
1606 return buffer_
.sputn(data
, size
);
1610 #ifndef LDID_NOTOOLS
1611 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1612 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1620 Split(const std::string
&path
) {
1621 size_t slash(path
.rfind('/'));
1622 if (slash
== std::string::npos
)
1625 dir
= path
.substr(0, slash
+ 1);
1626 base
= path
.substr(slash
+ 1);
1631 static void mkdir_p(const std::string
&path
) {
1635 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1638 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1641 auto slash(path
.rfind('/', path
.size() - 1));
1642 if (slash
== std::string::npos
)
1644 mkdir_p(path
.substr(0, slash
));
1647 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1648 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1650 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1654 static void Commit(const std::string
&path
, const std::string
&temp
) {
1656 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1658 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1660 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1663 _syscall(rename(temp
.c_str(), path
.c_str()));
1669 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
1670 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
1671 _assert(index
>= 0);
1672 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
1673 _assert(next
== -1);
1674 auto entry(X509_NAME_get_entry(name
, index
));
1675 _assert(entry
!= NULL
);
1676 auto asn(X509_NAME_ENTRY_get_data(entry
));
1677 _assert(asn
!= NULL
);
1678 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1681 static void req(std::streambuf
&buffer
, uint32_t value
) {
1682 value
= Swap(value
);
1683 put(buffer
, &value
, sizeof(value
));
1686 static void req(std::streambuf
&buffer
, const std::string
&value
) {
1687 req(buffer
, value
.size());
1688 put(buffer
, value
.data(), value
.size());
1689 static uint8_t zeros
[] = {0,0,0,0};
1690 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
1693 template <size_t Size_
>
1694 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
1696 put(buffer
, data
, Size_
);
1697 static uint8_t zeros
[] = {0,0,0,0};
1698 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
1701 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
, const Functor
<void (double)> &percent
) {
1708 #ifndef LDID_NOSMIME
1711 auto name(X509_get_subject_name(stuff
));
1712 _assert(name
!= NULL
);
1713 get(team
, name
, NID_organizationalUnitName
);
1714 get(common
, name
, NID_commonName
);
1719 std::stringbuf backing
;
1721 if (!requirements
.empty()) {
1722 put(backing
, requirements
.data(), requirements
.size());
1726 std::stringbuf requirement
;
1727 req(requirement
, exprForm
);
1728 req(requirement
, opAnd
);
1729 req(requirement
, opIdent
);
1730 req(requirement
, identifier
);
1731 req(requirement
, opAnd
);
1732 req(requirement
, opAppleGenericAnchor
);
1733 req(requirement
, opAnd
);
1734 req(requirement
, opCertField
);
1735 req(requirement
, 0);
1736 req(requirement
, "subject.CN");
1737 req(requirement
, matchEqual
);
1738 req(requirement
, common
);
1739 req(requirement
, opCertGeneric
);
1740 req(requirement
, 1);
1741 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
1742 req(requirement
, matchExists
);
1743 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
1745 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
1749 // XXX: this is just a "sufficiently large number"
1750 size_t certificate(0x3000);
1752 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, size_t size
) -> size_t {
1753 size_t alloc(sizeof(struct SuperBlob
));
1755 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1757 uint32_t special(0);
1759 _foreach (slot
, slots
)
1760 special
= std::max(special
, slot
.first
);
1762 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1763 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1764 special
= std::max(special
, CSSLOT_INFOSLOT
);
1767 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1768 alloc
+= sizeof(struct BlobIndex
);
1769 alloc
+= backing
.str().size();
1771 if (!entitlements
.empty()) {
1772 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1773 alloc
+= sizeof(struct BlobIndex
);
1774 alloc
+= sizeof(struct Blob
);
1775 alloc
+= entitlements
.size();
1778 size_t directory(0);
1780 directory
+= sizeof(struct BlobIndex
);
1781 directory
+= sizeof(struct Blob
);
1782 directory
+= sizeof(struct CodeDirectory
);
1783 directory
+= identifier
.size() + 1;
1786 directory
+= team
.size() + 1;
1788 for (Algorithm
*algorithm
: GetAlgorithms())
1789 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
1791 #ifndef LDID_NOSMIME
1793 alloc
+= sizeof(struct BlobIndex
);
1794 alloc
+= sizeof(struct Blob
);
1795 alloc
+= certificate
;
1800 }), fun([&](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1804 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
1807 if (!entitlements
.empty()) {
1808 std::stringbuf data
;
1809 put(data
, entitlements
.data(), entitlements
.size());
1810 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1815 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1816 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
1817 auto &slot(posts
[CSSLOT_INFOSLOT
]);
1818 for (Algorithm
*algorithm
: GetAlgorithms())
1819 (*algorithm
)(slot
, data
, size
);
1824 for (Algorithm
*pointer
: GetAlgorithms()) {
1825 Algorithm
&algorithm(*pointer
);
1827 std::stringbuf data
;
1829 uint32_t special(0);
1830 _foreach (blob
, blobs
)
1831 special
= std::max(special
, blob
.first
);
1832 _foreach (slot
, posts
)
1833 special
= std::max(special
, slot
.first
);
1834 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1836 CodeDirectory directory
;
1837 directory
.version
= Swap(uint32_t(0x00020200));
1838 directory
.flags
= Swap(uint32_t(0));
1839 directory
.nSpecialSlots
= Swap(special
);
1840 directory
.codeLimit
= Swap(uint32_t(limit
));
1841 directory
.nCodeSlots
= Swap(normal
);
1842 directory
.hashSize
= algorithm
.size_
;
1843 directory
.hashType
= algorithm
.type_
;
1844 directory
.spare1
= 0x00;
1845 directory
.pageSize
= PageShift_
;
1846 directory
.spare2
= Swap(uint32_t(0));
1847 directory
.scatterOffset
= Swap(uint32_t(0));
1848 //directory.spare3 = Swap(uint32_t(0));
1849 //directory.codeLimit64 = Swap(uint64_t(0));
1851 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
1853 directory
.identOffset
= Swap(uint32_t(offset
));
1854 offset
+= identifier
.size() + 1;
1857 directory
.teamIDOffset
= Swap(uint32_t(0));
1859 directory
.teamIDOffset
= Swap(uint32_t(offset
));
1860 offset
+= team
.size() + 1;
1863 offset
+= special
* algorithm
.size_
;
1864 directory
.hashOffset
= Swap(uint32_t(offset
));
1865 offset
+= normal
* algorithm
.size_
;
1867 put(data
, &directory
, sizeof(directory
));
1869 put(data
, identifier
.c_str(), identifier
.size() + 1);
1871 put(data
, team
.c_str(), team
.size() + 1);
1873 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
1874 auto *hashes(&storage
[special
* algorithm
.size_
]);
1876 memset(storage
.data(), 0, special
* algorithm
.size_
);
1878 _foreach (blob
, blobs
) {
1879 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1880 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
1883 _foreach (slot
, posts
)
1884 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
1888 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
1889 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1890 percent(double(i
) / normal
);
1893 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1896 put(data
, storage
.data(), storage
.size());
1898 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
1899 algorithm(hash
, save
.data(), save
.size());
1904 #ifndef LDID_NOSMIME
1906 auto plist(plist_new_dict());
1907 _scope({ plist_free(plist
); });
1909 auto cdhashes(plist_new_array());
1910 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
1913 for (Algorithm
*pointer
: GetAlgorithms()) {
1914 Algorithm
&algorithm(*pointer
);
1917 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
1920 std::vector
<char> hash
;
1921 algorithm(hash
, blob
.data(), blob
.size());
1924 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
1929 plist_to_xml(plist
, &xml
, &size
);
1930 _scope({ free(xml
); });
1932 std::stringbuf data
;
1933 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1938 Signature
signature(stuff
, sign
, std::string(xml
, size
));
1939 Buffer
result(signature
);
1940 std::string
value(result
);
1941 put(data
, value
.data(), value
.size());
1943 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
1944 _assert(save
.size() <= certificate
);
1948 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1954 #ifndef LDID_NOTOOLS
1955 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<void (double)> &percent
) {
1956 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, size_t size
) -> size_t {
1958 }), fun([](const MachHeader
&mach_header
, std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
, const Functor
<void (double)> &percent
) -> size_t {
1963 std::string
DiskFolder::Path(const std::string
&path
) const {
1964 return path_
+ "/" + path
;
1967 DiskFolder::DiskFolder(const std::string
&path
) :
1972 DiskFolder::~DiskFolder() {
1973 if (!std::uncaught_exception())
1974 for (const auto &commit
: commit_
)
1975 Commit(commit
.first
, commit
.second
);
1979 std::string
readlink(const std::string
&path
) {
1980 for (size_t size(1024); ; size
*= 2) {
1984 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
1985 if (size_t(writ
) >= size
)
1994 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 {
1995 std::string
path(Path(root
) + base
);
1997 DIR *dir(opendir(path
.c_str()));
1998 _assert(dir
!= NULL
);
1999 _scope({ _syscall(closedir(dir
)); });
2001 while (auto child
= readdir(dir
)) {
2002 std::string
name(child
->d_name
);
2003 if (name
== "." || name
== "..")
2005 if (Starts(name
, ".ldid."))
2012 _syscall(stat((path
+ name
).c_str(), &info
));
2014 else if (S_ISDIR(info
.st_mode
))
2016 else if (S_ISREG(info
.st_mode
))
2019 _assert_(false, "st_mode=%x", info
.st_mode
);
2021 switch (child
->d_type
) {
2029 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2032 _assert_(false, "d_type=%u", child
->d_type
);
2037 Find(root
, base
+ name
+ "/", code
, link
);
2043 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2046 std::stringbuf save
;
2050 auto from(Path(path
));
2051 commit_
[from
] = Temporary(save
, from
);
2056 bool DiskFolder::Look(const std::string
&path
) const {
2057 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2060 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2062 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2063 _assert_(result
== &data
, "DiskFolder::Open(%s)", path
.c_str());
2065 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2066 data
.pubseekpos(0, std::ios::in
);
2067 code(data
, length
, NULL
);
2070 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 {
2071 Find(path
, "", code
, link
);
2075 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2081 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2082 return parent_
.Save(path_
+ path
, edit
, flag
, code
);
2085 bool SubFolder::Look(const std::string
&path
) const {
2086 return parent_
.Look(path_
+ path
);
2089 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2090 return parent_
.Open(path_
+ path
, code
);
2093 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 {
2094 return parent_
.Find(path_
+ path
, code
, link
);
2097 std::string
UnionFolder::Map(const std::string
&path
) const {
2098 auto remap(remaps_
.find(path
));
2099 if (remap
== remaps_
.end())
2101 return remap
->second
;
2104 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 {
2105 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2106 code(file
.substr(path
.size()));
2109 UnionFolder::UnionFolder(Folder
&parent
) :
2114 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2115 return parent_
.Save(Map(path
), edit
, flag
, code
);
2118 bool UnionFolder::Look(const std::string
&path
) const {
2119 auto file(resets_
.find(path
));
2120 if (file
!= resets_
.end())
2122 return parent_
.Look(Map(path
));
2125 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2126 auto file(resets_
.find(path
));
2127 if (file
== resets_
.end())
2128 return parent_
.Open(Map(path
), code
);
2129 auto &entry(file
->second
);
2131 auto &data(*entry
.data_
);
2132 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2133 data
.pubseekpos(0, std::ios::in
);
2134 code(data
, length
, entry
.flag_
);
2137 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 {
2138 for (auto &reset
: resets_
)
2139 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2140 auto &entry(reset
.second
);
2141 auto &data(*entry
.data_
);
2142 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2143 data
.pubseekpos(0, std::ios::in
);
2144 code(data
, length
, entry
.flag_
);
2147 for (auto &remap
: remaps_
)
2148 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2149 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2150 code(data
, length
, flag
);
2154 parent_
.Find(path
, fun([&](const std::string
&name
) {
2155 if (deletes_
.find(path
+ name
) == deletes_
.end())
2157 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2158 if (deletes_
.find(path
+ name
) == deletes_
.end())
2163 #ifndef LDID_NOTOOLS
2164 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const ldid::Functor
<void (double)> &percent
) {
2168 char data
[4096 * 4];
2169 size_t writ(source
.sgetn(data
, sizeof(data
)));
2172 _assert(target
.sputn(data
, writ
) == writ
);
2174 percent(double(total
) / length
);
2178 #ifndef LDID_NOPLIST
2179 static plist_t
plist(const std::string
&data
) {
2180 plist_t
plist(NULL
);
2181 if (Starts(data
, "bplist00"))
2182 plist_from_bin(data
.data(), data
.size(), &plist
);
2184 plist_from_xml(data
.data(), data
.size(), &plist
);
2185 _assert(plist
!= NULL
);
2189 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2190 std::stringbuf data
;
2191 copy(buffer
, data
, length
, ldid::fun(dummy
));
2192 auto node(plist(data
.str()));
2193 _scope({ plist_free(node
); });
2194 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2198 static std::string
plist_s(plist_t node
) {
2199 _assert(node
!= NULL
);
2200 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2202 plist_get_string_val(node
, &data
);
2203 _scope({ free(data
); });
2219 std::vector
<std::string
> matches_
;
2222 Expression(const std::string
&code
) {
2223 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2224 matches_
.resize(regex_
.re_nsub
+ 1);
2231 bool operator ()(const std::string
&data
) {
2232 regmatch_t matches
[matches_
.size()];
2233 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2234 if (value
== REG_NOMATCH
)
2236 _assert_(value
== 0, "regexec()");
2237 for (size_t i(0); i
!= matches_
.size(); ++i
)
2238 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2242 const std::string
&operator [](size_t index
) const {
2243 return matches_
[index
];
2252 mutable std::auto_ptr
<Expression
> regex_
;
2254 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2261 Rule(const Rule
&rhs
) :
2262 weight_(rhs
.weight_
),
2268 void Compile() const {
2269 regex_
.reset(new Expression(code_
));
2272 bool operator ()(const std::string
&data
) const {
2273 _assert(regex_
.get() != NULL
);
2274 return (*regex_
)(data
);
2277 bool operator <(const Rule
&rhs
) const {
2278 if (weight_
> rhs
.weight_
)
2280 if (weight_
< rhs
.weight_
)
2282 return mode_
> rhs
.mode_
;
2287 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2288 return lhs
->code_
< rhs
->code_
;
2292 #ifndef LDID_NOPLIST
2293 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
, const Functor
<void (double)> &percent
) {
2294 // XXX: this is a miserable fail
2295 std::stringbuf temp
;
2296 put(temp
, prefix
, size
);
2297 copy(buffer
, temp
, length
- size
, percent
);
2298 // XXX: this is a stupid hack
2299 pad(temp
, 0x10 - (length
& 0xf));
2300 auto data(temp
.str());
2302 HashProxy
proxy(hash
, save
);
2303 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, requirements
, key
, slots
, percent
);
2306 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 Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2307 std::string executable
;
2308 std::string identifier
;
2312 std::string
info("Info.plist");
2313 if (!folder
.Look(info
) && folder
.Look("Resources/" + info
)) {
2315 info
= "Resources/" + info
;
2318 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2319 plist_d(buffer
, length
, fun([&](plist_t node
) {
2320 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2321 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2325 if (!mac
&& folder
.Look("MacOS/" + executable
)) {
2326 executable
= "MacOS/" + executable
;
2330 std::string entitlements
;
2331 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2332 // XXX: this is a miserable fail
2333 std::stringbuf temp
;
2334 copy(buffer
, temp
, length
, percent
);
2335 // XXX: this is a stupid hack
2336 pad(temp
, 0x10 - (length
& 0xf));
2337 auto data(temp
.str());
2338 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2341 static const std::string
directory("_CodeSignature/");
2342 static const std::string
signature(directory
+ "CodeResources");
2344 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2346 auto &rules1(versions
[""]);
2347 auto &rules2(versions
["2"]);
2349 const std::string
resources(mac
? "Resources/" : "");
2352 rules1
.insert(Rule
{1, NoMode
, "^" + resources
});
2353 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2354 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2355 rules1
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2356 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2360 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2361 rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2362 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2363 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2364 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2365 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2366 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2367 rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2368 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2369 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2370 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2371 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2372 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2375 std::map
<std::string
, Hash
> local
;
2377 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2378 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2379 std::map
<std::string
, Bundle
> bundles
;
2381 folder
.Find("", fun([&](const std::string
&name
) {
2384 auto bundle(root
+ Split(name
).dir
);
2385 bundle
.resize(bundle
.size() - resources
.size());
2386 SubFolder
subfolder(folder
, bundle
);
2388 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2389 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&entitlements
) -> std::string
{ return entitlements
; }))
2390 , progress
, percent
);
2391 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2394 std::set
<std::string
> excludes
;
2396 auto exclude([&](const std::string
&name
) {
2397 // BundleDiskRep::adjustResources -> builder.addExclusion
2398 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2401 for (const auto &bundle
: bundles
)
2402 if (Starts(name
, bundle
.first
+ "/")) {
2403 excludes
.insert(name
);
2410 std::map
<std::string
, std::string
> links
;
2412 folder
.Find("", fun([&](const std::string
&name
) {
2416 if (local
.find(name
) != local
.end())
2418 auto &hash(local
[name
]);
2420 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2421 progress(root
+ name
);
2432 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2434 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2435 switch (Swap(header
.magic
)) {
2437 // Java class file format
2438 if (Swap(header
.count
) >= 40)
2441 case MH_MAGIC
: case MH_MAGIC_64
:
2442 case MH_CIGAM
: case MH_CIGAM_64
:
2443 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2445 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", "", key
, slots
, length
, percent
);
2450 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2451 HashProxy
proxy(hash
, save
);
2452 put(proxy
, header
.bytes
, size
);
2453 copy(data
, proxy
, length
- size
, percent
);
2456 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2460 links
[name
] = read();
2463 auto plist(plist_new_dict());
2464 _scope({ plist_free(plist
); });
2466 for (const auto &version
: versions
) {
2467 auto files(plist_new_dict());
2468 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2470 for (const auto &rule
: version
.second
)
2473 bool old(&version
.second
== &rules1
);
2475 for (const auto &hash
: local
)
2476 for (const auto &rule
: version
.second
)
2477 if (rule(hash
.first
)) {
2478 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2479 else if (old
&& rule
.mode_
== NoMode
)
2480 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2481 else if (rule
.mode_
!= OmitMode
) {
2482 auto entry(plist_new_dict());
2483 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2485 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2486 if (rule
.mode_
== OptionalMode
)
2487 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2488 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2494 for (const auto &link
: links
)
2495 for (const auto &rule
: version
.second
)
2496 if (rule(link
.first
)) {
2497 if (rule
.mode_
!= OmitMode
) {
2498 auto entry(plist_new_dict());
2499 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2500 if (rule
.mode_
== OptionalMode
)
2501 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2502 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2509 for (const auto &bundle
: bundles
) {
2510 auto entry(plist_new_dict());
2511 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2512 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2513 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2517 for (const auto &version
: versions
) {
2518 auto rules(plist_new_dict());
2519 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2521 std::multiset
<const Rule
*, RuleCode
> ordered
;
2522 for (const auto &rule
: version
.second
)
2523 ordered
.insert(&rule
);
2525 for (const auto &rule
: ordered
)
2526 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2527 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2529 auto entry(plist_new_dict());
2530 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2532 switch (rule
->mode_
) {
2536 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2539 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2542 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2545 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2549 if (rule
->weight_
>= 10000)
2550 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2551 else if (rule
->weight_
!= 1)
2552 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2556 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2557 HashProxy
proxy(local
[signature
], save
);
2560 plist_to_xml(plist
, &xml
, &size
);
2561 _scope({ free(xml
); });
2562 put(proxy
, xml
, size
);
2566 bundle
.path
= executable
;
2568 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2569 progress(root
+ executable
);
2570 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2572 slots
[1] = local
.at(info
);
2573 slots
[3] = local
.at(signature
);
2574 bundle
.hash
= Sign(NULL
, 0, buffer
, local
[executable
], save
, identifier
, entitlements
, requirements
, key
, slots
, length
, percent
);
2578 for (const auto &entry
: local
)
2579 remote
[root
+ entry
.first
] = entry
.second
;
2584 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 Functor
<void (const std::string
&)> &progress
, const Functor
<void (double)> &percent
) {
2585 std::map
<std::string
, Hash
> local
;
2586 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
, percent
);
2593 #ifndef LDID_NOTOOLS
2594 int main(int argc
, char *argv
[]) {
2595 #ifndef LDID_NOSMIME
2596 OpenSSL_add_all_algorithms();
2604 little_
= endian
.byte
[0];
2610 #ifndef LDID_NOFLAGT
2624 uint32_t flag_CPUType(_not(uint32_t));
2625 uint32_t flag_CPUSubtype(_not(uint32_t));
2627 const char *flag_I(NULL
);
2629 #ifndef LDID_NOFLAGT
2639 std::vector
<std::string
> files
;
2642 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
2643 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
2644 fprintf(stderr
, " %s -S cat\n", argv
[0]);
2645 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
2649 for (int argi(1); argi
!= argc
; ++argi
)
2650 if (argv
[argi
][0] != '-')
2651 files
.push_back(argv
[argi
]);
2652 else switch (argv
[argi
][1]) {
2659 case 'e': flag_e
= true; break;
2662 const char *string
= argv
[argi
] + 2;
2663 const char *colon
= strchr(string
, ':');
2664 _assert(colon
!= NULL
);
2665 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2667 unsigned number(strtoul(string
, &arge
, 0));
2668 _assert(arge
== colon
);
2669 auto &slot(slots
[number
]);
2670 for (Algorithm
*algorithm
: GetAlgorithms())
2671 (*algorithm
)(slot
, file
.data(), file
.size());
2674 case 'q': flag_q
= true; break;
2677 const char *xml
= argv
[argi
] + 2;
2678 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2681 case 'D': flag_D
= true; break;
2683 case 'a': flag_a
= true; break;
2688 if (argv
[argi
][2] != '\0') {
2689 const char *cpu
= argv
[argi
] + 2;
2690 const char *colon
= strchr(cpu
, ':');
2691 _assert(colon
!= NULL
);
2693 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2694 _assert(arge
== colon
);
2695 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2696 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2710 if (argv
[argi
][2] != '\0') {
2711 const char *xml
= argv
[argi
] + 2;
2712 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2717 if (argv
[argi
][2] != '\0')
2718 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2721 #ifndef LDID_NOFLAGT
2724 if (argv
[argi
][2] == '-')
2728 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2729 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2739 flag_I
= argv
[argi
] + 2;
2747 _assert(flag_S
|| key
.empty());
2748 _assert(flag_S
|| flag_I
== NULL
);
2750 if (files
.empty()) usage
: {
2754 size_t filei(0), filee(0);
2755 _foreach (file
, files
) try {
2756 std::string
path(file
);
2759 _syscall(stat(path
.c_str(), &info
));
2761 if (S_ISDIR(info
.st_mode
)) {
2762 #ifndef LDID_NOPLIST
2764 ldid::DiskFolder
folder(path
);
2765 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; })
2766 , ldid::fun([&](const std::string
&) {}), ldid::fun(dummy
)
2771 } else if (flag_S
|| flag_r
) {
2772 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2774 std::filebuf output
;
2776 auto temp(Temporary(output
, split
));
2779 ldid::Unsign(input
.data(), input
.size(), output
, ldid::fun(dummy
));
2781 std::string
identifier(flag_I
?: split
.base
.c_str());
2782 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, requirements
, key
, slots
, ldid::fun(dummy
));
2789 #ifndef LDID_NOFLAGT
2796 Map
mapping(path
, modify
);
2797 FatHeader
fat_header(mapping
.data(), mapping
.size());
2799 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2800 struct linkedit_data_command
*signature(NULL
);
2801 struct encryption_info_command
*encryption(NULL
);
2804 if (mach_header
.GetCPUType() != flag_CPUType
)
2806 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2811 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2813 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2814 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2817 else if (cmd
== LC_CODE_SIGNATURE
)
2818 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2819 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2820 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2821 else if (cmd
== LC_LOAD_DYLIB
) {
2822 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2823 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
2825 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2828 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
2829 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
2833 #ifndef LDID_NOFLAGT
2834 else if (cmd
== LC_ID_DYLIB
) {
2835 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2843 dylib_command
->dylib
.timestamp
= 0;
2844 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2847 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2854 _assert(encryption
!= NULL
);
2855 encryption
->cryptid
= mach_header
.Swap(0);
2859 _assert(signature
!= NULL
);
2861 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2863 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2864 uint8_t *blob
= top
+ data
;
2865 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2867 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2868 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2869 uint32_t begin
= Swap(super
->index
[index
].offset
);
2870 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2871 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2876 _assert(signature
!= NULL
);
2878 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2880 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2881 uint8_t *blob
= top
+ data
;
2882 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2884 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2885 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
2886 uint32_t begin
= Swap(super
->index
[index
].offset
);
2887 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2888 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
2893 _assert(signature
!= NULL
);
2895 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2897 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2898 uint8_t *blob
= top
+ data
;
2899 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2901 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2902 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2903 uint32_t begin
= Swap(super
->index
[index
].offset
);
2904 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
2906 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2907 uint32_t pages
= Swap(directory
->nCodeSlots
);
2910 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2911 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
2913 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
2919 } catch (const char *) {