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/opensslv.h>
47 # if OPENSSL_VERSION_MAJOR >= 3
48 # include <openssl/provider.h>
50 #include <openssl/err.h>
51 #include <openssl/pem.h>
52 #include <openssl/pkcs7.h>
53 #include <openssl/pkcs12.h>
54 #include <openssl/ui.h>
58 #include <CommonCrypto/CommonDigest.h>
60 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
61 #define LDID_SHA1 CC_SHA1
62 #define LDID_SHA1_CTX CC_SHA1_CTX
63 #define LDID_SHA1_Init CC_SHA1_Init
64 #define LDID_SHA1_Update CC_SHA1_Update
65 #define LDID_SHA1_Final CC_SHA1_Final
67 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
68 #define LDID_SHA256 CC_SHA256
69 #define LDID_SHA256_CTX CC_SHA256_CTX
70 #define LDID_SHA256_Init CC_SHA256_Init
71 #define LDID_SHA256_Update CC_SHA256_Update
72 #define LDID_SHA256_Final CC_SHA256_Final
74 #include <openssl/sha.h>
76 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
77 #define LDID_SHA1 SHA1
78 #define LDID_SHA1_CTX SHA_CTX
79 #define LDID_SHA1_Init SHA1_Init
80 #define LDID_SHA1_Update SHA1_Update
81 #define LDID_SHA1_Final SHA1_Final
83 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
84 #define LDID_SHA256 SHA256
85 #define LDID_SHA256_CTX SHA256_CTX
86 #define LDID_SHA256_Init SHA256_Init
87 #define LDID_SHA256_Update SHA256_Update
88 #define LDID_SHA256_Final SHA256_Final
92 #include <plist/plist.h>
94 #include <CoreFoundation/CoreFoundation.h>
101 #define _assert___(line) \
103 #define _assert__(line) \
107 #define $(value) value
111 #define _assert_(expr, format, ...) \
113 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
114 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
117 // XXX: this is not acceptable
118 #define _assert_(expr, format, ...) \
120 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
125 #define _assert(expr) \
126 _assert_(expr, "%s", $(#expr))
128 #define _syscall(expr, ...) [&] { for (;;) { \
130 if ((long) _value != -1) \
133 if (error == EINTR) \
135 /* XXX: EINTR is included in this list to fix g++ */ \
136 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
137 if (error == success) \
138 return (decltype(expr)) -success; \
139 fprintf(stderr, "ldid: %s: %s\n", __func__, strerror(error)); \
144 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
150 __attribute__((packed))
153 std::string password
;
156 template <typename Type_
>
158 typedef typename
Type_::const_iterator Result
;
161 #define _foreach(item, list) \
162 for (bool _stop(true); _stop; ) \
163 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
164 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
165 for (bool _suck(true); _suck; _suck = false) \
166 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
171 template <typename Function_
>
179 Scope(const Function_
&function
) :
189 template <typename Function_
>
190 Scope
<Function_
> _scope(const Function_
&function
) {
191 return Scope
<Function_
>(function
);
194 #define _scope__(counter, function) \
195 __attribute__((__unused__)) \
196 const _Scope &_scope ## counter(_scope([&]function))
197 #define _scope_(counter, function) \
198 _scope__(counter, function)
199 #define _scope(function) \
200 _scope_(__COUNTER__, function)
207 #define FAT_MAGIC 0xcafebabe
208 #define FAT_CIGAM 0xbebafeca
228 #define MH_MAGIC 0xfeedface
229 #define MH_CIGAM 0xcefaedfe
231 #define MH_MAGIC_64 0xfeedfacf
232 #define MH_CIGAM_64 0xcffaedfe
234 #define MH_DYLDLINK 0x4
236 #define MH_OBJECT 0x1
237 #define MH_EXECUTE 0x2
239 #define MH_DYLINKER 0x7
240 #define MH_BUNDLE 0x8
241 #define MH_DYLIB_STUB 0x9
243 struct load_command
{
248 #define LC_REQ_DYLD uint32_t(0x80000000)
250 #define LC_SEGMENT uint32_t(0x01)
251 #define LC_SYMTAB uint32_t(0x02)
252 #define LC_DYSYMTAB uint32_t(0x0b)
253 #define LC_LOAD_DYLIB uint32_t(0x0c)
254 #define LC_ID_DYLIB uint32_t(0x0d)
255 #define LC_SEGMENT_64 uint32_t(0x19)
256 #define LC_UUID uint32_t(0x1b)
257 #define LC_CODE_SIGNATURE uint32_t(0x1d)
258 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
259 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
260 #define LC_ENCRYPTION_INFO uint32_t(0x21)
261 #define LC_DYLD_INFO uint32_t(0x22)
262 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
263 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
278 uint32_t current_version
;
279 uint32_t compatibility_version
;
282 struct dylib_command
{
288 struct uuid_command
{
294 struct symtab_command
{
303 struct dyld_info_command
{
307 uint32_t rebase_size
;
310 uint32_t weak_bind_off
;
311 uint32_t weak_bind_size
;
312 uint32_t lazy_bind_off
;
313 uint32_t lazy_bind_size
;
315 uint32_t export_size
;
318 struct dysymtab_command
{
331 uint32_t extrefsymoff
;
332 uint32_t nextrefsyms
;
333 uint32_t indirectsymoff
;
334 uint32_t nindirectsyms
;
341 struct dylib_table_of_contents
{
342 uint32_t symbol_index
;
343 uint32_t module_index
;
346 struct dylib_module
{
347 uint32_t module_name
;
356 uint32_t iinit_iterm
;
357 uint32_t ninit_nterm
;
358 uint32_t objc_module_info_addr
;
359 uint32_t objc_module_info_size
;
362 struct dylib_reference
{
367 struct relocation_info
{
369 uint32_t r_symbolnum
:24;
388 struct segment_command
{
402 struct segment_command_64
{
445 struct linkedit_data_command
{
452 struct encryption_info_command
{
460 #define BIND_OPCODE_MASK 0xf0
461 #define BIND_IMMEDIATE_MASK 0x0f
462 #define BIND_OPCODE_DONE 0x00
463 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
464 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
465 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
466 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
467 #define BIND_OPCODE_SET_TYPE_IMM 0x50
468 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
469 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
470 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
471 #define BIND_OPCODE_DO_BIND 0x90
472 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
473 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
474 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
476 struct : ldid::Progress
{
477 virtual void operator()(const std::string
&value
) const {
480 virtual void operator()(double value
) const {
484 struct Progression
: ldid::Progress
{
485 const ldid::Progress
&progress_
;
488 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
494 virtual void operator()(const std::string
&value
) const {
495 return progress_(name_
+ " (" + value
+ ")");
498 virtual void operator()(double value
) const {
499 return progress_(value
);
503 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
504 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
509 static inline void put(std::streambuf
&stream
, uint8_t value
) {
510 _assert(stream
.sputc(value
) != EOF
);
513 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
514 _assert(read(stream
, data
, size
) == size
);
517 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
518 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
521 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
523 for (size_t total(0); total
!= size
;) {
524 auto writ(std::min(size
- total
, size_t(4096 * 4)));
525 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
527 progress(double(total
) / size
);
531 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
532 return put(stream
, data
.data(), data
.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 unsigned bytes(uint64_t value
) {
562 return (64 - __builtin_clzll(value
) + 7) / 8;
565 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
567 do put(stream
, uint8_t(value
>> (length
-= 8)));
571 static void der(std::streambuf
&stream
, uint64_t value
) {
575 unsigned length(bytes(value
));
576 put(stream
, 0x80 | length
);
577 put(stream
, value
, length
);
581 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
585 put(data
, value
, length
);
589 static std::string
der(uint8_t tag
, const char *value
) {
590 return der(tag
, value
, strlen(value
)); }
591 static std::string
der(uint8_t tag
, const std::string
&value
) {
592 return der(tag
, value
.data(), value
.size()); }
594 template <typename Type_
>
595 static void der_(std::stringbuf
&data
, const Type_
&values
) {
597 for (const auto &value
: values
)
598 size
+= value
.size();
600 for (const auto &value
: values
)
604 static std::string
der(const std::vector
<std::string
> &values
) {
611 static std::string
der(const std::multiset
<std::string
> &values
) {
618 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
619 const auto key(der(0x0c, value
.first
));
622 der(data
, key
.size() + value
.second
.size());
624 put(data
, value
.second
);
629 static std::string
der(plist_t data
) {
630 switch (const auto type
= plist_get_node_type(data
)) {
631 case PLIST_BOOLEAN
: {
633 plist_get_bool_val(data
, &value
);
638 put(data
, value
!= 0 ? 1 : 0);
644 plist_get_uint_val(data
, &value
);
645 const auto length(bytes(value
));
650 put(data
, value
, length
);
655 fprintf(stderr
, "ldid: Invalid plist entry type\n");
660 fprintf(stderr
, "ldid: Invalid plist entry type\n");
667 plist_get_data_val(data
, &value
, &length
);
668 _scope({ free(value
); });
669 return der(0x04, value
, length
);
674 plist_get_string_val(data
, &value
);
675 _scope({ free(value
); });
676 return der(0x0c, value
);
680 std::vector
<std::string
> values
;
681 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
682 values
.push_back(der(plist_array_get_item(data
, i
)));
687 std::multiset
<std::string
> values
;
689 plist_dict_iter
iterator(NULL
);
690 plist_dict_new_iter(data
, &iterator
);
691 _scope({ free(iterator
); });
696 plist_dict_next_item(data
, iterator
, &key
, &value
);
699 _scope({ free(key
); });
700 values
.insert(der(std::make_pair(key
, der(value
))));
707 fprintf(stderr
, "ldid: Unsupported plist type %d", type
);
714 static inline uint16_t Swap_(uint16_t value
) {
716 ((value
>> 8) & 0x00ff) |
717 ((value
<< 8) & 0xff00);
720 static inline uint32_t Swap_(uint32_t value
) {
721 value
= ((value
>> 8) & 0x00ff00ff) |
722 ((value
<< 8) & 0xff00ff00);
723 value
= ((value
>> 16) & 0x0000ffff) |
724 ((value
<< 16) & 0xffff0000);
728 static inline uint64_t Swap_(uint64_t value
) {
729 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
730 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
731 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
735 static inline int16_t Swap_(int16_t value
) {
736 return Swap_(static_cast<uint16_t>(value
));
739 static inline int32_t Swap_(int32_t value
) {
740 return Swap_(static_cast<uint32_t>(value
));
743 static inline int64_t Swap_(int64_t value
) {
744 return Swap_(static_cast<uint64_t>(value
));
747 static bool little_(true);
749 static inline uint16_t Swap(uint16_t value
) {
750 return little_
? Swap_(value
) : value
;
753 static inline uint32_t Swap(uint32_t value
) {
754 return little_
? Swap_(value
) : value
;
757 static inline uint64_t Swap(uint64_t value
) {
758 return little_
? Swap_(value
) : value
;
761 static inline int16_t Swap(int16_t value
) {
762 return Swap(static_cast<uint16_t>(value
));
765 static inline int32_t Swap(int32_t value
) {
766 return Swap(static_cast<uint32_t>(value
));
769 static inline int64_t Swap(int64_t value
) {
770 return Swap(static_cast<uint64_t>(value
));
783 Swapped(bool swapped
) :
788 template <typename Type_
>
789 Type_
Swap(Type_ value
) const {
790 return swapped_
? Swap_(value
) : value
;
802 Data(void *base
, size_t size
) :
808 void *GetBase() const {
812 size_t GetSize() const {
823 struct mach_header
*mach_header_
;
824 struct load_command
*load_command_
;
827 MachHeader(void *base
, size_t size
) :
830 mach_header_
= (mach_header
*) base
;
832 switch (Swap(mach_header_
->magic
)) {
834 swapped_
= !swapped_
;
840 swapped_
= !swapped_
;
846 fprintf(stderr
, "ldid: Unknown header magic\nAre you sure that is a Mach-O?\n");
850 void *post
= mach_header_
+ 1;
852 post
= (uint32_t *) post
+ 1;
853 load_command_
= (struct load_command
*) post
;
855 if (Swap(mach_header_
->filetype
) != MH_EXECUTE
&&
856 Swap(mach_header_
->filetype
) != MH_DYLIB
&&
857 Swap(mach_header_
->filetype
) != MH_DYLINKER
&&
858 Swap(mach_header_
->filetype
) != MH_BUNDLE
) {
859 fprintf(stderr
, "ldid: Unsupported Mach-O type\n");
864 bool Bits64() const {
868 struct mach_header
*operator ->() const {
872 operator struct mach_header
*() const {
876 uint32_t GetCPUType() const {
877 return Swap(mach_header_
->cputype
);
880 uint32_t GetCPUSubtype() const {
881 return Swap(mach_header_
->cpusubtype
) & 0xff;
884 struct load_command
*GetLoadCommand() const {
885 return load_command_
;
888 std::vector
<struct load_command
*> GetLoadCommands() const {
889 std::vector
<struct load_command
*> load_commands
;
891 struct load_command
*load_command
= load_command_
;
892 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
893 load_commands
.push_back(load_command
);
894 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
897 return load_commands
;
900 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
901 _foreach (load_command
, GetLoadCommands())
902 switch (Swap(load_command
->cmd
)) {
904 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
905 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
906 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
907 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
908 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
911 case LC_SEGMENT_64
: {
912 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
913 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
914 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
915 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
916 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
921 template <typename Target_
>
922 Target_
*GetOffset(uint32_t offset
) const {
923 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
927 class FatMachHeader
:
934 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
935 MachHeader(base
, size
),
940 fat_arch
*GetFatArch() const {
949 fat_header
*fat_header_
;
950 std::vector
<FatMachHeader
> mach_headers_
;
953 FatHeader(void *base
, size_t size
) :
956 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
958 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
959 swapped_
= !swapped_
;
961 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
963 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
965 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
966 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
968 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
969 uint32_t arch_offset
= Swap(fat_arch
->offset
);
970 uint32_t arch_size
= Swap(fat_arch
->size
);
971 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
977 std::vector
<FatMachHeader
> &GetMachHeaders() {
978 return mach_headers_
;
982 return fat_header_
!= NULL
;
985 struct fat_header
*operator ->() const {
989 operator struct fat_header
*() const {
994 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
995 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
996 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
997 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
998 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
999 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
1000 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
1001 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
1002 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
1004 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
1005 #define CSSLOT_INFOSLOT uint32_t(0x00001)
1006 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
1007 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
1008 #define CSSLOT_APPLICATION uint32_t(0x00004)
1009 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
1010 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
1011 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
1012 #define CSSLOT_ALTERNATE uint32_t(0x01000)
1014 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
1016 #define CS_HASHTYPE_SHA160_160 1
1017 #define CS_HASHTYPE_SHA256_256 2
1018 #define CS_HASHTYPE_SHA256_160 3
1019 #define CS_HASHTYPE_SHA386_386 4
1022 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
1023 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
1024 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
1025 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1026 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1027 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1028 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1030 enum SecCodeExecSegFlags
{
1031 kSecCodeExecSegMainBinary
= 0x001,
1032 kSecCodeExecSegAllowUnsigned
= 0x010,
1033 kSecCodeExecSegDebugger
= 0x020,
1034 kSecCodeExecSegJit
= 0x040,
1035 kSecCodeExecSegSkipLibraryVal
= 0x080,
1036 kSecCodeExecSegCanLoadCdHash
= 0x100,
1037 kSecCodeExecSegCanExecCdHash
= 0x100,
1054 struct BlobIndex index
[];
1057 struct CodeDirectory
{
1060 uint32_t hashOffset
;
1061 uint32_t identOffset
;
1062 uint32_t nSpecialSlots
;
1063 uint32_t nCodeSlots
;
1070 uint32_t scatterOffset
;
1071 uint32_t teamIDOffset
;
1073 uint64_t codeLimit64
;
1074 uint64_t execSegBase
;
1075 uint64_t execSegLimit
;
1076 uint64_t execSegFlags
;
1077 #if 0 // version = 0x20500
1079 uint32_t preEncryptOffset
;
1081 #if 0 // version = 0x20600
1082 uint8_t linkageHashType
;
1083 uint8_t linkageTruncated
;
1085 uint32_t linkageOffset
;
1086 uint32_t linkageSize
;
1090 enum CodeSignatureFlags
{
1091 kSecCodeSignatureHost
= 0x0001,
1092 kSecCodeSignatureAdhoc
= 0x0002,
1093 kSecCodeSignatureForceHard
= 0x0100,
1094 kSecCodeSignatureForceKill
= 0x0200,
1095 kSecCodeSignatureForceExpiration
= 0x0400,
1096 kSecCodeSignatureRestrict
= 0x0800,
1097 kSecCodeSignatureEnforcement
= 0x1000,
1098 kSecCodeSignatureLibraryValidation
= 0x2000,
1099 kSecCodeSignatureRuntime
= 0x10000,
1102 enum Kind
: uint32_t {
1103 exprForm
= 1, // prefix expr form
1106 enum ExprOp
: uint32_t {
1107 opFalse
, // unconditionally false
1108 opTrue
, // unconditionally true
1109 opIdent
, // match canonical code [string]
1110 opAppleAnchor
, // signed by Apple as Apple's product
1111 opAnchorHash
, // match anchor [cert hash]
1112 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1113 opAnd
, // binary prefix expr AND expr [expr; expr]
1114 opOr
, // binary prefix expr OR expr [expr; expr]
1115 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1116 opNot
, // logical inverse [expr]
1117 opInfoKeyField
, // Info.plist key field [string; match suffix]
1118 opCertField
, // Certificate field [cert index; field name; match suffix]
1119 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1120 opTrustedCerts
, // require trust settings to approve the cert chain
1121 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1122 opAppleGenericAnchor
, // signed by Apple in any capacity
1123 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1124 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1125 opNamedAnchor
, // named anchor type
1126 opNamedCode
, // named subroutine
1127 opPlatform
, // platform constraint [integer]
1128 exprOpCount
// (total opcode count in use)
1131 enum MatchOperation
{
1132 matchExists
, // anything but explicit "false" - no value stored
1133 matchEqual
, // equal (CFEqual)
1134 matchContains
, // partial match (substring)
1135 matchBeginsWith
, // partial match (initial substring)
1136 matchEndsWith
, // partial match (terminal substring)
1137 matchLessThan
, // less than (string with numeric comparison)
1138 matchGreaterThan
, // greater than (string with numeric comparison)
1139 matchLessEqual
, // less or equal (string with numeric comparison)
1140 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1143 #define OID_ISO_MEMBER 42
1144 #define OID_US OID_ISO_MEMBER, 134, 72
1145 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1146 #define APPLE_ADS_OID APPLE_OID, 0x64
1147 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1149 #ifndef LDID_NOFLAGT
1150 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
1157 Algorithm(size_t size
, uint8_t type
) :
1163 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1165 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1166 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1167 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1169 virtual const char *name() = 0;
1172 struct AlgorithmSHA1
:
1176 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1180 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1184 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1185 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1188 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1189 return operator()(hash
.sha1_
, data
, size
);
1192 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1193 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1194 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1197 virtual const char *name() {
1202 struct AlgorithmSHA256
:
1206 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1210 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1211 return hash
.sha256_
;
1214 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1215 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1218 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1219 return operator()(hash
.sha256_
, data
, size
);
1222 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1223 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1224 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1227 virtual const char *name() {
1232 static bool do_sha1(true);
1233 static bool do_sha256(true);
1235 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1236 static AlgorithmSHA1 sha1
;
1237 static AlgorithmSHA256 sha256
;
1239 static std::vector
<Algorithm
*> algorithms
;
1240 if (algorithms
.empty()) {
1242 algorithms
.push_back(&sha1
);
1244 algorithms
.push_back(&sha256
);
1251 std::string entitlements_
;
1252 std::string derformat_
;
1255 struct CodesignAllocation
{
1256 FatMachHeader mach_header_
;
1265 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
, const char *arch
, const Baton
&baton
) :
1266 mach_header_(mach_header
),
1278 #ifndef LDID_NOTOOLS
1291 _syscall(close(file_
));
1294 void open(const char *path
, int flags
) {
1295 file_
= ::open(path
, flags
);
1297 fprintf(stderr
, "ldid: %s: %s\n", path
, strerror(errno
));
1316 _syscall(munmap(data_
, size_
));
1328 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1331 open(path
, oflag
, pflag
, mflag
);
1334 Map(const std::string
&path
, bool edit
) :
1344 bool empty() const {
1345 return data_
== NULL
;
1348 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1351 file_
.open(path
.c_str(), oflag
);
1352 int file(file_
.file());
1355 _syscall(fstat(file
, &stat
));
1356 size_
= stat
.st_size
;
1358 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1361 void open(const std::string
&path
, bool edit
) {
1363 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1365 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1368 void *data() const {
1372 size_t size() const {
1376 operator std::string() const {
1377 return std::string(static_cast<char *>(data_
), size_
);
1384 #ifndef LDID_NOPLIST
1385 static plist_t
plist(const std::string
&data
);
1388 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1389 _foreach (load_command
, mach_header
.GetLoadCommands())
1390 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1391 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1392 auto offset(mach_header
.Swap(signature
->dataoff
));
1393 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1394 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1396 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1397 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1398 auto begin(Swap(super
->index
[index
].offset
));
1399 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1400 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1401 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1406 std::string
Analyze(const void *data
, size_t size
) {
1407 std::string entitlements
;
1409 FatHeader
fat_header(const_cast<void *>(data
), size
);
1410 _foreach (mach_header
, fat_header
.GetMachHeaders())
1411 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1412 if (entitlements
.empty())
1413 entitlements
.assign(data
, size
);
1415 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1418 return entitlements
;
1421 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, Baton
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, const Baton
&, std::streambuf
&output
, size_t, size_t, size_t, const std::string
&, const char *, const Progress
&)> &save
, const Progress
&progress
) {
1422 FatHeader
source(const_cast<void *>(idata
), isize
);
1426 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1428 std::vector
<CodesignAllocation
> allocations
;
1429 _foreach (mach_header
, source
.GetMachHeaders()) {
1430 struct linkedit_data_command
*signature(NULL
);
1431 struct symtab_command
*symtab(NULL
);
1433 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1434 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1436 else if (cmd
== LC_CODE_SIGNATURE
)
1437 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1438 else if (cmd
== LC_SYMTAB
)
1439 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1443 if (signature
== NULL
)
1444 size
= mach_header
.GetSize();
1446 size
= mach_header
.Swap(signature
->dataoff
);
1447 _assert(size
<= mach_header
.GetSize());
1450 if (symtab
!= NULL
) {
1451 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1452 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1453 _assert(end
<= size
);
1454 _assert(end
>= size
- 0x10);
1460 size_t alloc(allocate(mach_header
, baton
, size
));
1462 auto *fat_arch(mach_header
.GetFatArch());
1465 if (fat_arch
!= NULL
)
1466 align
= source
.Swap(fat_arch
->align
);
1467 else switch (mach_header
.GetCPUType()) {
1468 case CPU_TYPE_POWERPC
:
1469 case CPU_TYPE_POWERPC64
:
1471 case CPU_TYPE_X86_64
:
1475 case CPU_TYPE_ARM64
:
1476 case CPU_TYPE_ARM64_32
:
1484 const char *arch(NULL
);
1485 switch (mach_header
.GetCPUType()) {
1486 case CPU_TYPE_POWERPC
:
1489 case CPU_TYPE_POWERPC64
:
1495 case CPU_TYPE_X86_64
:
1501 case CPU_TYPE_ARM64
:
1504 case CPU_TYPE_ARM64_32
:
1509 offset
= Align(offset
, 1 << align
);
1511 uint32_t limit(size
);
1513 limit
= Align(limit
, 0x10);
1515 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1516 offset
+= size
+ alloc
;
1517 offset
= Align(offset
, 0x10);
1522 if (source
.IsFat()) {
1523 fat_header fat_header
;
1524 fat_header
.magic
= Swap(FAT_MAGIC
);
1525 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1526 put(output
, &fat_header
, sizeof(fat_header
));
1527 position
+= sizeof(fat_header
);
1529 // XXX: support fat_arch_64 (not in my toolchain)
1530 // probably use C++14 generic lambda (not in my toolchain)
1533 _foreach (allocation
, allocations
) {
1534 const auto offset(allocation
.offset_
);
1535 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1536 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1540 }(), "FAT slice >=4GiB not currently supported");
1542 _foreach (allocation
, allocations
) {
1543 auto &mach_header(allocation
.mach_header_
);
1546 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1547 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1548 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1549 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1550 fat_arch
.align
= Swap(allocation
.align_
);
1551 put(output
, &fat_arch
, sizeof(fat_arch
));
1552 position
+= sizeof(fat_arch
);
1556 _foreach (allocation
, allocations
) {
1557 progress(allocation
.arch_
);
1558 auto &mach_header(allocation
.mach_header_
);
1560 pad(output
, allocation
.offset_
- position
);
1561 position
= allocation
.offset_
;
1566 std::vector
<std::string
> commands
;
1568 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1569 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1571 switch (mach_header
.Swap(load_command
->cmd
)) {
1572 case LC_CODE_SIGNATURE
:
1576 // XXX: this is getting ridiculous: provide a better abstraction
1579 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1581 if ((segment_command
->initprot
& 04) != 0) {
1582 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1583 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1590 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1591 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1592 segment_command
->filesize
= size
;
1593 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1597 case LC_SEGMENT_64
: {
1598 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1600 if ((segment_command
->initprot
& 04) != 0) {
1601 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1602 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1609 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1610 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1611 segment_command
->filesize
= size
;
1612 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1617 commands
.push_back(copy
);
1620 if (allocation
.alloc_
!= 0) {
1621 linkedit_data_command signature
;
1622 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1623 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1624 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1625 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1626 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1629 size_t begin(position
);
1632 _foreach(command
, commands
)
1633 after
+= command
.size();
1635 std::stringbuf altern
;
1637 struct mach_header
header(*mach_header
);
1638 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1639 header
.sizeofcmds
= mach_header
.Swap(after
);
1640 put(output
, &header
, sizeof(header
));
1641 put(altern
, &header
, sizeof(header
));
1642 position
+= sizeof(header
);
1644 if (mach_header
.Bits64()) {
1645 auto pad(mach_header
.Swap(uint32_t(0)));
1646 put(output
, &pad
, sizeof(pad
));
1647 put(altern
, &pad
, sizeof(pad
));
1648 position
+= sizeof(pad
);
1651 _foreach(command
, commands
) {
1652 put(output
, command
.data(), command
.size());
1653 put(altern
, command
.data(), command
.size());
1654 position
+= command
.size();
1657 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1658 if (before
> after
) {
1659 pad(output
, before
- after
);
1660 pad(altern
, before
- after
);
1661 position
+= before
- after
;
1664 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1666 std::string
overlap(altern
.str());
1667 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1669 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1670 position
= begin
+ allocation
.size_
;
1672 pad(output
, allocation
.limit_
- allocation
.size_
);
1673 position
+= allocation
.limit_
- allocation
.size_
;
1675 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1676 if (allocation
.alloc_
> saved
)
1677 pad(output
, allocation
.alloc_
- saved
);
1679 _assert(allocation
.alloc_
== saved
);
1680 position
+= allocation
.alloc_
;
1686 typedef std::map
<uint32_t, std::string
> Blobs
;
1688 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1689 auto value(buffer
.str());
1690 std::swap(blobs
[slot
], value
);
1693 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1694 auto value(buffer
.str());
1696 blob
.magic
= Swap(magic
);
1697 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1698 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1699 auto &save(blobs
[slot
]);
1700 std::swap(save
, value
);
1704 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1706 _foreach (blob
, blobs
)
1707 total
+= blob
.second
.size();
1709 struct SuperBlob super
;
1710 super
.blob
.magic
= Swap(magic
);
1711 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1712 super
.count
= Swap(uint32_t(blobs
.size()));
1713 put(output
, &super
, sizeof(super
));
1715 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1717 _foreach (blob
, blobs
) {
1719 index
.type
= Swap(blob
.first
);
1720 index
.offset
= Swap(uint32_t(offset
));
1721 put(output
, &index
, sizeof(index
));
1722 offset
+= blob
.second
.size();
1725 _foreach (blob
, blobs
)
1726 put(output
, blob
.second
.data(), blob
.second
.size());
1731 #ifndef LDID_NOSMIME
1740 _assert(bio_
!= NULL
);
1744 bio_(BIO_new(BIO_s_mem()))
1748 Buffer(const char *data
, size_t size
) :
1749 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1753 Buffer(const std::string
&data
) :
1754 Buffer(data
.data(), data
.size())
1758 Buffer(PKCS7
*pkcs
) :
1761 if(i2d_PKCS7_bio(bio_
, pkcs
) == 0){
1762 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1771 operator BIO
*() const {
1775 explicit operator std::string() const {
1777 auto size(BIO_get_mem_data(bio_
, &data
));
1778 return std::string(data
, size
);
1787 STACK_OF(X509
) *ca_
;
1791 value_(d2i_PKCS12_bio(bio
, NULL
)),
1795 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1799 if (!PKCS12_verify_mac(value_
, "", 0) && password
.empty()) {
1801 UI_UTIL_read_pw_string(passbuf
, 2048, "Enter password: ", 0);
1805 if(PKCS12_parse(value_
, password
.c_str(), &key_
, &cert_
, &ca_
) <= 0){
1806 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1809 if(key_
== NULL
|| cert_
== NULL
){
1810 fprintf(stderr
, "ldid: An error occured while parsing: %s\nYour p12 cert might not be valid\n", ERR_error_string(ERR_get_error(), NULL
));
1815 ca_
= sk_X509_new_null();
1817 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1822 Stuff(const std::string
&data
) :
1828 sk_X509_pop_free(ca_
, X509_free
);
1830 EVP_PKEY_free(key_
);
1831 PKCS12_free(value_
);
1834 operator PKCS12
*() const {
1838 operator EVP_PKEY
*() const {
1842 operator X509
*() const {
1846 operator STACK_OF(X509
) *() const {
1856 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1857 value_
= PKCS7_new();
1859 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1863 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1864 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1866 STACK_OF(X509
) *certs(stuff
);
1867 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1868 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1870 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1872 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1875 PKCS7_set_detached(value_
, 1);
1877 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1878 _assert(string
!= NULL
);
1880 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1882 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1883 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1885 ASN1_OCTET_STRING_free(string
);
1889 _assert(PKCS7_final(value_
, data
, PKCS7_BINARY
));
1896 operator PKCS7
*() const {
1903 public std::streambuf
1906 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1910 virtual int_type
overflow(int_type next
) {
1916 public std::streambuf
1921 LDID_SHA1_CTX sha1_
;
1922 LDID_SHA256_CTX sha256_
;
1925 HashBuffer(ldid::Hash
&hash
) :
1928 LDID_SHA1_Init(&sha1_
);
1929 LDID_SHA256_Init(&sha256_
);
1933 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1934 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1937 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1938 LDID_SHA1_Update(&sha1_
, data
, size
);
1939 LDID_SHA256_Update(&sha256_
, data
, size
);
1943 virtual int_type
overflow(int_type next
) {
1944 if (next
== traits_type::eof())
1956 std::streambuf
&buffer_
;
1959 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1965 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1966 _assert(HashBuffer::xsputn(data
, size
) == size
);
1967 return buffer_
.sputn(data
, size
);
1971 #ifndef LDID_NOTOOLS
1972 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1973 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1981 Split(const std::string
&path
) {
1982 size_t slash(path
.rfind('/'));
1983 if (slash
== std::string::npos
)
1986 dir
= path
.substr(0, slash
+ 1);
1987 base
= path
.substr(slash
+ 1);
1992 static void mkdir_p(const std::string
&path
) {
1996 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1999 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2002 auto slash(path
.rfind('/', path
.size() - 1));
2003 if (slash
== std::string::npos
)
2005 mkdir_p(path
.substr(0, slash
));
2008 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2009 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2011 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2015 static void Commit(const std::string
&path
, const std::string
&temp
) {
2017 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2019 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2021 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2024 _syscall(rename(temp
.c_str(), path
.c_str()));
2030 #ifndef LDID_NOSMIME
2031 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2032 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2033 _assert(index
>= 0);
2034 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2035 _assert(next
== -1);
2036 auto entry(X509_NAME_get_entry(name
, index
));
2037 _assert(entry
!= NULL
);
2038 auto asn(X509_NAME_ENTRY_get_data(entry
));
2039 _assert(asn
!= NULL
);
2040 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2044 static void req(std::streambuf
&buffer
, uint32_t value
) {
2045 value
= Swap(value
);
2046 put(buffer
, &value
, sizeof(value
));
2049 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2050 req(buffer
, value
.size());
2051 put(buffer
, value
.data(), value
.size());
2052 static uint8_t zeros
[] = {0,0,0,0};
2053 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2056 template <size_t Size_
>
2057 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2059 put(buffer
, data
, Size_
);
2060 static uint8_t zeros
[] = {0,0,0,0};
2061 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2064 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2071 #ifndef LDID_NOSMIME
2074 auto name(X509_get_subject_name(stuff
));
2076 fprintf(stderr
, "ldid: Your certificate might not be valid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2079 get(team
, name
, NID_organizationalUnitName
);
2080 get(common
, name
, NID_commonName
);
2085 std::stringbuf backing
;
2087 if (!requirements
.empty()) {
2088 put(backing
, requirements
.data(), requirements
.size());
2092 std::stringbuf requirement
;
2093 req(requirement
, exprForm
);
2094 req(requirement
, opAnd
);
2095 req(requirement
, opIdent
);
2096 req(requirement
, identifier
);
2097 req(requirement
, opAnd
);
2098 req(requirement
, opAppleGenericAnchor
);
2099 req(requirement
, opAnd
);
2100 req(requirement
, opCertField
);
2101 req(requirement
, 0);
2102 req(requirement
, "subject.CN");
2103 req(requirement
, matchEqual
);
2104 req(requirement
, common
);
2105 req(requirement
, opCertGeneric
);
2106 req(requirement
, 1);
2107 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2108 req(requirement
, matchExists
);
2109 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2111 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2115 // XXX: this is just a "sufficiently large number"
2116 size_t certificate(0x3000);
2118 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2119 size_t alloc(sizeof(struct SuperBlob
));
2121 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2123 uint32_t special(0);
2125 _foreach (slot
, slots
)
2126 special
= std::max(special
, slot
.first
);
2128 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2129 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2130 special
= std::max(special
, CSSLOT_INFOSLOT
);
2133 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2134 alloc
+= sizeof(struct BlobIndex
);
2135 alloc
+= backing
.str().size();
2138 baton
.entitlements_
= entitlements
;
2141 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2142 baton
.entitlements_
.assign(data
, size
);
2145 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2146 auto combined(plist(baton
.entitlements_
));
2147 _scope({ plist_free(combined
); });
2148 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
2150 auto merging(plist(entitlements
));
2151 _scope({ plist_free(merging
); });
2152 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
2154 plist_dict_iter
iterator(NULL
);
2155 plist_dict_new_iter(merging
, &iterator
);
2156 _scope({ free(iterator
); });
2160 plist_t
value(NULL
);
2161 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2164 _scope({ free(key
); });
2165 plist_dict_set_item(combined
, key
, plist_copy(value
));
2168 baton
.derformat_
= der(combined
);
2172 plist_to_xml(combined
, &xml
, &size
);
2173 _scope({ free(xml
); });
2175 baton
.entitlements_
.assign(xml
, size
);
2179 if (!baton
.entitlements_
.empty()) {
2180 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2181 alloc
+= sizeof(struct BlobIndex
);
2182 alloc
+= sizeof(struct Blob
);
2183 alloc
+= baton
.entitlements_
.size();
2186 if (!baton
.derformat_
.empty()) {
2187 special
= std::max(special
, CSSLOT_DERFORMAT
);
2188 alloc
+= sizeof(struct BlobIndex
);
2189 alloc
+= sizeof(struct Blob
);
2190 alloc
+= baton
.derformat_
.size();
2193 size_t directory(0);
2195 directory
+= sizeof(struct BlobIndex
);
2196 directory
+= sizeof(struct Blob
);
2197 directory
+= sizeof(struct CodeDirectory
);
2198 directory
+= identifier
.size() + 1;
2201 directory
+= team
.size() + 1;
2203 for (Algorithm
*algorithm
: GetAlgorithms())
2204 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2206 #ifndef LDID_NOSMIME
2208 alloc
+= sizeof(struct BlobIndex
);
2209 alloc
+= sizeof(struct Blob
);
2210 alloc
+= certificate
;
2215 }), fun([&](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2219 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2223 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2224 execs
|= kSecCodeExecSegMainBinary
;
2226 if (!baton
.entitlements_
.empty()) {
2227 std::stringbuf data
;
2228 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2229 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2231 #ifndef LDID_NOPLIST
2232 auto entitlements(plist(baton
.entitlements_
));
2233 _scope({ plist_free(entitlements
); });
2234 if (plist_get_node_type(entitlements
) != PLIST_DICT
) {
2235 fprintf(stderr
, "ldid: Entitlements should be a plist dicionary\n");
2239 const auto entitled([&](const char *key
) {
2240 auto item(plist_dict_get_item(entitlements
, key
));
2241 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2244 plist_get_bool_val(item
, &value
);
2248 if (entitled("get-task-allow"))
2249 execs
|= kSecCodeExecSegAllowUnsigned
;
2250 if (entitled("run-unsigned-code"))
2251 execs
|= kSecCodeExecSegAllowUnsigned
;
2252 if (entitled("com.apple.private.cs.debugger"))
2253 execs
|= kSecCodeExecSegDebugger
;
2254 if (entitled("dynamic-codesigning"))
2255 execs
|= kSecCodeExecSegJit
;
2256 if (entitled("com.apple.private.skip-library-validation"))
2257 execs
|= kSecCodeExecSegSkipLibraryVal
;
2258 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2259 execs
|= kSecCodeExecSegCanLoadCdHash
;
2260 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2261 execs
|= kSecCodeExecSegCanExecCdHash
;
2265 if (!baton
.derformat_
.empty()) {
2266 std::stringbuf data
;
2267 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2268 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2273 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2274 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2275 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2276 for (Algorithm
*algorithm
: GetAlgorithms())
2277 (*algorithm
)(slot
, data
, size
);
2282 for (Algorithm
*pointer
: GetAlgorithms()) {
2283 Algorithm
&algorithm(*pointer
);
2285 std::stringbuf data
;
2287 uint32_t special(0);
2288 _foreach (blob
, blobs
)
2289 special
= std::max(special
, blob
.first
);
2290 _foreach (slot
, posts
)
2291 special
= std::max(special
, slot
.first
);
2292 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2294 CodeDirectory directory
;
2295 directory
.version
= Swap(uint32_t(0x00020400));
2296 directory
.flags
= Swap(uint32_t(flags
));
2297 directory
.nSpecialSlots
= Swap(special
);
2298 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2299 directory
.nCodeSlots
= Swap(normal
);
2300 directory
.hashSize
= algorithm
.size_
;
2301 directory
.hashType
= algorithm
.type_
;
2302 directory
.platform
= platform
? 0x01 : 0x00;
2303 directory
.pageSize
= PageShift_
;
2304 directory
.spare2
= Swap(uint32_t(0));
2305 directory
.scatterOffset
= Swap(uint32_t(0));
2306 directory
.spare3
= Swap(uint32_t(0));
2307 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2308 directory
.execSegBase
= Swap(uint64_t(left
));
2309 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2310 directory
.execSegFlags
= Swap(execs
);
2312 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2314 directory
.identOffset
= Swap(uint32_t(offset
));
2315 offset
+= identifier
.size() + 1;
2318 directory
.teamIDOffset
= Swap(uint32_t(0));
2320 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2321 offset
+= team
.size() + 1;
2324 offset
+= special
* algorithm
.size_
;
2325 directory
.hashOffset
= Swap(uint32_t(offset
));
2326 offset
+= normal
* algorithm
.size_
;
2328 put(data
, &directory
, sizeof(directory
));
2330 put(data
, identifier
.c_str(), identifier
.size() + 1);
2332 put(data
, team
.c_str(), team
.size() + 1);
2334 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2335 auto *hashes(&storage
[special
* algorithm
.size_
]);
2337 memset(storage
.data(), 0, special
* algorithm
.size_
);
2339 _foreach (blob
, blobs
) {
2340 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2341 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2344 _foreach (slot
, posts
)
2345 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2349 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2350 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2351 progress(double(i
) / normal
);
2354 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2357 put(data
, storage
.data(), storage
.size());
2359 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2360 algorithm(hash
, save
.data(), save
.size());
2365 #ifndef LDID_NOSMIME
2368 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2369 _scope({ CFRelease(plist
); });
2371 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2372 _scope({ CFRelease(cdhashes
); });
2374 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2376 auto plist(plist_new_dict());
2377 _scope({ plist_free(plist
); });
2379 auto cdhashes(plist_new_array());
2380 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2384 for (Algorithm
*pointer
: GetAlgorithms()) {
2385 Algorithm
&algorithm(*pointer
);
2388 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2391 std::vector
<char> hash
;
2392 algorithm(hash
, blob
.data(), blob
.size());
2396 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2397 _scope({ CFRelease(value
); });
2398 CFArrayAppendValue(cdhashes
, value
);
2400 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2405 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2406 _scope({ CFRelease(created
); });
2407 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2408 auto size(CFDataGetLength(created
));
2412 plist_to_xml(plist
, &xml
, &size
);
2413 _scope({ free(xml
); });
2416 std::stringbuf data
;
2417 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2422 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2423 Buffer
result(signature
);
2424 std::string
value(result
);
2425 put(data
, value
.data(), value
.size());
2427 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2428 _assert(save
.size() <= certificate
);
2432 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2438 #ifndef LDID_NOTOOLS
2439 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2440 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2442 }), fun([](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2447 std::string
DiskFolder::Path(const std::string
&path
) const {
2448 return path_
+ path
;
2451 DiskFolder::DiskFolder(const std::string
&path
) :
2454 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2457 DiskFolder::~DiskFolder() {
2458 if (!std::uncaught_exception())
2459 for (const auto &commit
: commit_
)
2460 Commit(commit
.first
, commit
.second
);
2464 std::string
readlink(const std::string
&path
) {
2465 for (size_t size(1024); ; size
*= 2) {
2469 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2470 if (size_t(writ
) >= size
)
2479 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 {
2480 std::string
path(Path(root
) + base
);
2482 DIR *dir(opendir(path
.c_str()));
2483 _assert(dir
!= NULL
);
2484 _scope({ _syscall(closedir(dir
)); });
2486 while (auto child
= readdir(dir
)) {
2487 std::string
name(child
->d_name
);
2488 if (name
== "." || name
== "..")
2490 if (Starts(name
, ".ldid."))
2497 _syscall(stat((path
+ name
).c_str(), &info
));
2499 else if (S_ISDIR(info
.st_mode
))
2501 else if (S_ISREG(info
.st_mode
))
2504 _assert_(false, "st_mode=%x", info
.st_mode
);
2506 switch (child
->d_type
) {
2514 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2517 _assert_(false, "d_type=%u", child
->d_type
);
2522 Find(root
, base
+ name
+ "/", code
, link
);
2528 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2534 auto from(Path(path
));
2535 commit_
[from
] = Temporary(save
, from
);
2540 bool DiskFolder::Look(const std::string
&path
) const {
2541 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2544 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2546 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2547 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2549 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2550 data
.pubseekpos(0, std::ios::in
);
2551 code(data
, length
, NULL
);
2554 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 {
2555 Find(path
, "", code
, link
);
2559 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2563 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2566 std::string
SubFolder::Path(const std::string
&path
) const {
2567 return path_
+ path
;
2570 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2571 return parent_
.Save(Path(path
), edit
, flag
, code
);
2574 bool SubFolder::Look(const std::string
&path
) const {
2575 return parent_
.Look(Path(path
));
2578 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2579 return parent_
.Open(Path(path
), code
);
2582 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 {
2583 return parent_
.Find(Path(path
), code
, link
);
2586 std::string
UnionFolder::Map(const std::string
&path
) const {
2587 auto remap(remaps_
.find(path
));
2588 if (remap
== remaps_
.end())
2590 return remap
->second
;
2593 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 {
2594 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2595 code(file
.substr(path
.size()));
2598 UnionFolder::UnionFolder(Folder
&parent
) :
2603 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2604 return parent_
.Save(Map(path
), edit
, flag
, code
);
2607 bool UnionFolder::Look(const std::string
&path
) const {
2608 auto file(resets_
.find(path
));
2609 if (file
!= resets_
.end())
2611 return parent_
.Look(Map(path
));
2614 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2615 auto file(resets_
.find(path
));
2616 if (file
== resets_
.end())
2617 return parent_
.Open(Map(path
), code
);
2618 auto &entry(file
->second
);
2620 auto &data(*entry
.data_
);
2621 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2622 data
.pubseekpos(0, std::ios::in
);
2623 code(data
, length
, entry
.flag_
);
2626 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 {
2627 for (auto &reset
: resets_
)
2628 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2629 auto &entry(reset
.second
);
2630 auto &data(*entry
.data_
);
2631 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2632 data
.pubseekpos(0, std::ios::in
);
2633 code(data
, length
, entry
.flag_
);
2636 for (auto &remap
: remaps_
)
2637 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2638 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2639 code(data
, length
, flag
);
2643 parent_
.Find(path
, fun([&](const std::string
&name
) {
2644 if (deletes_
.find(path
+ name
) == deletes_
.end())
2646 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2647 if (deletes_
.find(path
+ name
) == deletes_
.end())
2652 #ifndef LDID_NOTOOLS
2653 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2657 char data
[4096 * 4];
2658 size_t writ(source
.sgetn(data
, sizeof(data
)));
2661 _assert(target
.sputn(data
, writ
) == writ
);
2663 progress(double(total
) / length
);
2667 #ifndef LDID_NOPLIST
2668 static plist_t
plist(const std::string
&data
) {
2670 return plist_new_dict();
2671 plist_t
plist(NULL
);
2672 if (Starts(data
, "bplist00"))
2673 plist_from_bin(data
.data(), data
.size(), &plist
);
2675 plist_from_xml(data
.data(), data
.size(), &plist
);
2676 _assert(plist
!= NULL
);
2680 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2681 std::stringbuf data
;
2682 copy(buffer
, data
, length
, dummy_
);
2683 auto node(plist(data
.str()));
2684 _scope({ plist_free(node
); });
2685 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2689 static std::string
plist_s(plist_t node
) {
2690 _assert(node
!= NULL
);
2691 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2693 plist_get_string_val(node
, &data
);
2694 _scope({ free(data
); });
2710 std::vector
<std::string
> matches_
;
2713 Expression(const std::string
&code
) {
2714 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2715 matches_
.resize(regex_
.re_nsub
+ 1);
2722 bool operator ()(const std::string
&data
) {
2723 regmatch_t matches
[matches_
.size()];
2724 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2725 if (value
== REG_NOMATCH
)
2727 _assert_(value
== 0, "regexec()");
2728 for (size_t i(0); i
!= matches_
.size(); ++i
)
2729 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2733 const std::string
&operator [](size_t index
) const {
2734 return matches_
[index
];
2743 mutable std::unique_ptr
<Expression
> regex_
;
2745 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2752 Rule(const Rule
&rhs
) :
2753 weight_(rhs
.weight_
),
2759 void Compile() const {
2760 regex_
.reset(new Expression(code_
));
2763 bool operator ()(const std::string
&data
) const {
2764 _assert(regex_
.get() != NULL
);
2765 return (*regex_
)(data
);
2768 bool operator <(const Rule
&rhs
) const {
2769 if (weight_
> rhs
.weight_
)
2771 if (weight_
< rhs
.weight_
)
2773 return mode_
> rhs
.mode_
;
2778 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2779 return lhs
->code_
< rhs
->code_
;
2783 #ifndef LDID_NOPLIST
2784 static Hash
Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, Hash
&hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2785 // XXX: this is a miserable fail
2786 std::stringbuf temp
;
2787 put(temp
, prefix
, size
);
2788 copy(buffer
, temp
, length
- size
, progress
);
2789 // XXX: this is a stupid hack
2790 pad(temp
, 0x10 - (length
& 0xf));
2791 auto data(temp
.str());
2793 HashProxy
proxy(hash
, save
);
2794 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2798 std::map
<std::string
, Hash
> files
;
2799 std::map
<std::string
, std::string
> links
;
2801 void Merge(const std::string
&root
, const State
&state
) {
2802 for (const auto &entry
: state
.files
)
2803 files
[root
+ entry
.first
] = entry
.second
;
2804 for (const auto &entry
: state
.links
)
2805 links
[root
+ entry
.first
] = entry
.second
;
2809 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&local
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2810 std::string executable
;
2811 std::string identifier
;
2815 std::string
info("Info.plist");
2817 SubFolder
folder(parent
, [&]() {
2818 if (parent
.Look(info
))
2822 else if (parent
.Look("Contents/" + info
))
2824 else if (parent
.Look("Resources/" + info
)) {
2825 info
= "Resources/" + info
;
2828 fprintf(stderr
, "ldid: Could not find Info.plist\n");
2833 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2834 plist_d(buffer
, length
, fun([&](plist_t node
) {
2835 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2836 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2840 if (mac
&& info
== "Info.plist")
2841 executable
= "MacOS/" + executable
;
2843 progress(root
+ "*");
2845 std::string entitlements
;
2846 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2847 // XXX: this is a miserable fail
2848 std::stringbuf temp
;
2849 copy(buffer
, temp
, length
, progress
);
2850 // XXX: this is a stupid hack
2851 pad(temp
, 0x10 - (length
& 0xf));
2852 auto data(temp
.str());
2853 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2856 static const std::string
directory("_CodeSignature/");
2857 static const std::string
signature(directory
+ "CodeResources");
2859 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2861 auto &rules1(versions
[""]);
2862 auto &rules2(versions
["2"]);
2864 const std::string
resources(mac
? "Resources/" : "");
2867 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2868 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2869 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2870 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2871 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2875 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2876 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2877 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2878 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2879 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2880 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2881 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2882 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2883 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2884 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2885 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2886 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2887 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2888 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2891 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2892 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2893 std::map
<std::string
, Bundle
> bundles
;
2895 folder
.Find("", fun([&](const std::string
&name
) {
2898 auto bundle(Split(name
).dir
);
2900 _assert(!bundle
.empty());
2901 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2903 SubFolder
subfolder(folder
, bundle
);
2906 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2907 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2909 local
.Merge(bundle
, remote
);
2910 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2913 std::set
<std::string
> excludes
;
2915 auto exclude([&](const std::string
&name
) {
2916 // BundleDiskRep::adjustResources -> builder.addExclusion
2917 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2920 for (const auto &bundle
: bundles
)
2921 if (Starts(name
, bundle
.first
+ "/")) {
2922 excludes
.insert(name
);
2929 folder
.Find("", fun([&](const std::string
&name
) {
2933 if (local
.files
.find(name
) != local
.files
.end())
2935 auto &hash(local
.files
[name
]);
2937 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2938 progress(root
+ name
);
2949 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2951 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2952 switch (Swap(header
.magic
)) {
2954 // Java class file format
2955 if (Swap(header
.count
) >= 40)
2958 case MH_MAGIC
: case MH_MAGIC_64
:
2959 case MH_CIGAM
: case MH_CIGAM_64
:
2960 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2962 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2967 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2968 HashProxy
proxy(hash
, save
);
2969 put(proxy
, header
.bytes
, size
);
2970 copy(data
, proxy
, length
- size
, progress
);
2973 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2977 local
.links
[name
] = read();
2980 auto plist(plist_new_dict());
2981 _scope({ plist_free(plist
); });
2983 for (const auto &version
: versions
) {
2984 auto files(plist_new_dict());
2985 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2987 for (const auto &rule
: version
.second
)
2990 bool old(&version
.second
== &rules1
);
2992 for (const auto &hash
: local
.files
)
2993 for (const auto &rule
: version
.second
)
2994 if (rule(hash
.first
)) {
2995 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2996 else if (old
&& rule
.mode_
== NoMode
)
2997 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2998 else if (rule
.mode_
!= OmitMode
) {
2999 auto entry(plist_new_dict());
3000 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3002 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
3003 if (rule
.mode_
== OptionalMode
)
3004 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3005 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3012 for (const auto &link
: local
.links
)
3013 for (const auto &rule
: version
.second
)
3014 if (rule(link
.first
)) {
3015 if (rule
.mode_
!= OmitMode
) {
3016 auto entry(plist_new_dict());
3017 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3018 if (rule
.mode_
== OptionalMode
)
3019 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3020 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3027 for (const auto &bundle
: bundles
) {
3028 auto entry(plist_new_dict());
3029 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3030 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3031 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3035 for (const auto &version
: versions
) {
3036 auto rules(plist_new_dict());
3037 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3039 std::multiset
<const Rule
*, RuleCode
> ordered
;
3040 for (const auto &rule
: version
.second
)
3041 ordered
.insert(&rule
);
3043 for (const auto &rule
: ordered
)
3044 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3045 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3047 auto entry(plist_new_dict());
3048 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3050 switch (rule
->mode_
) {
3054 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3057 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3060 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3063 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3067 if (rule
->weight_
>= 10000)
3068 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3069 else if (rule
->weight_
!= 1)
3070 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3074 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3075 HashProxy
proxy(local
.files
[signature
], save
);
3078 plist_to_xml(plist
, &xml
, &size
);
3079 _scope({ free(xml
); });
3080 put(proxy
, xml
, size
);
3084 bundle
.path
= folder
.Path(executable
);
3086 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3087 progress(root
+ executable
);
3088 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3090 slots
[1] = local
.files
.at(info
);
3091 slots
[3] = local
.files
.at(signature
);
3092 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3099 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
) {
3101 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3108 std::string
Hex(const uint8_t *data
, size_t size
) {
3110 hex
.reserve(size
* 2);
3111 for (size_t i(0); i
!= size
; ++i
) {
3112 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3113 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3118 static void usage(const char *argv0
) {
3119 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3120 fprintf(stderr
, "Usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3121 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3122 fprintf(stderr
, " [-Enum:file] [-e] [-H[sha1 | sha256]] [-h] [-Iname]\n");
3123 fprintf(stderr
, " [-Kkey.p12 [-Upassword]] [-M] [-P] [-Qrequirements.xml] [-q]\n");
3124 fprintf(stderr
, " [-r | -Sfile.xml | -s] [-Ttimestamp] [-u] [-arch arch_type] file ...\n");
3125 fprintf(stderr
, "Options:\n");
3126 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3127 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3128 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3129 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3130 fprintf(stderr
, " -h Print CDHash of file\n\n");
3131 fprintf(stderr
, "More information: 'man ldid'\n");
3134 #ifndef LDID_NOTOOLS
3135 int main(int argc
, char *argv
[]) {
3136 #ifndef LDID_NOSMIME
3137 OpenSSL_add_all_algorithms();
3138 # if OPENSSL_VERSION_MAJOR >= 3
3139 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3140 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3149 little_
= endian
.byte
[0];
3158 #ifndef LDID_NOFLAGT
3176 bool platform(false);
3178 uint32_t flag_CPUType(_not(uint32_t));
3179 uint32_t flag_CPUSubtype(_not(uint32_t));
3181 const char *flag_I(NULL
);
3183 #ifndef LDID_NOFLAGT
3193 std::vector
<std::string
> files
;
3200 for (int argi(1); argi
!= argc
; ++argi
)
3201 if (argv
[argi
][0] != '-')
3202 files
.push_back(argv
[argi
]);
3203 else if (strcmp(argv
[argi
], "-arch") == 0) {
3204 bool foundarch
= false;
3208 fprintf(stderr
, "ldid: -arch must be followed by an architecture string\n");
3211 for (int i
= 0; archs
[i
].name
!= NULL
; i
++) {
3212 if (strcmp(archs
[i
].name
, argv
[argi
]) == 0) {
3213 flag_CPUType
= archs
[i
].cputype
;
3214 flag_CPUSubtype
= archs
[i
].cpusubtype
;
3222 fprintf(stderr
, "error: unknown architecture specification flag: -arch %s\n", argv
[argi
]);
3225 } else switch (argv
[argi
][1]) {
3227 if (flag_s
|| flag_S
) {
3228 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3234 case 'e': flag_e
= true; break;
3237 const char *string
= argv
[argi
] + 2;
3238 const char *colon
= strchr(string
, ':');
3239 _assert(colon
!= NULL
);
3240 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3242 unsigned number(strtoul(string
, &arge
, 0));
3243 _assert(arge
== colon
);
3244 auto &slot(slots
[number
]);
3245 for (Algorithm
*algorithm
: GetAlgorithms())
3246 (*algorithm
)(slot
, file
.data(), file
.size());
3249 case 'q': flag_q
= true; break;
3252 const char *hash
= argv
[argi
] + 2;
3262 else if (strcmp(hash
, "sha1") == 0)
3264 else if (strcmp(hash
, "sha256") == 0)
3267 fprintf(stderr
, "ldid: only sha1 and sha256 are supported at this time\n");
3272 case 'h': flag_h
= true; break;
3275 const char *xml
= argv
[argi
] + 2;
3276 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3279 case 'D': flag_D
= true; break;
3280 case 'd': flag_d
= true; break;
3282 case 'a': flag_a
= true; break;
3286 fprintf(stderr
, "ldid: -A can only be specified once\n");
3290 if (argv
[argi
][2] != '\0') {
3291 const char *cpu
= argv
[argi
] + 2;
3292 const char *colon
= strchr(cpu
, ':');
3293 _assert(colon
!= NULL
);
3295 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3296 _assert(arge
== colon
);
3297 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3298 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3303 const char *name
= argv
[argi
] + 2;
3305 else if (strcmp(name
, "host") == 0)
3306 flags
|= kSecCodeSignatureHost
;
3307 else if (strcmp(name
, "adhoc") == 0)
3308 flags
|= kSecCodeSignatureAdhoc
;
3309 else if (strcmp(name
, "hard") == 0)
3310 flags
|= kSecCodeSignatureForceHard
;
3311 else if (strcmp(name
, "kill") == 0)
3312 flags
|= kSecCodeSignatureForceKill
;
3313 else if (strcmp(name
, "expires") == 0)
3314 flags
|= kSecCodeSignatureForceExpiration
;
3315 else if (strcmp(name
, "restrict") == 0)
3316 flags
|= kSecCodeSignatureRestrict
;
3317 else if (strcmp(name
, "enforcement") == 0)
3318 flags
|= kSecCodeSignatureEnforcement
;
3319 else if (strcmp(name
, "library-validation") == 0)
3320 flags
|= kSecCodeSignatureLibraryValidation
;
3321 else if (strcmp(name
, "runtime") == 0)
3322 flags
|= kSecCodeSignatureRuntime
;
3324 fprintf(stderr
, "ldid: -C: Unsupported option\n");
3334 if (flag_r
|| flag_S
) {
3335 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3342 if (flag_r
|| flag_s
) {
3343 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3347 if (argv
[argi
][2] != '\0') {
3348 const char *xml
= argv
[argi
] + 2;
3349 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3358 password
= argv
[argi
] + 2;
3362 if (argv
[argi
][2] != '\0')
3363 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3366 #ifndef LDID_NOFLAGT
3369 if (argv
[argi
][2] == '-')
3373 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3374 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3384 flag_I
= argv
[argi
] + 2;
3393 _assert(flag_S
|| key
.empty());
3394 _assert(flag_S
|| flag_I
== NULL
);
3396 if (flag_d
&& !flag_h
) {
3398 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3404 size_t filei(0), filee(0);
3405 _foreach (file
, files
) try {
3406 std::string
path(file
);
3409 if (stat(path
.c_str(), &info
) == -1) {
3410 fprintf(stderr
, "ldid: %s: %s\n", path
.c_str(), strerror(errno
));
3414 if (S_ISDIR(info
.st_mode
)) {
3416 fprintf(stderr
, "ldid: Only -S can be used on directories\n");
3419 #ifndef LDID_NOPLIST
3420 ldid::DiskFolder
folder(path
+ "/");
3421 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3425 } else if (flag_S
|| flag_r
) {
3426 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3428 std::filebuf output
;
3430 auto temp(Temporary(output
, split
));
3433 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3435 std::string
identifier(flag_I
?: split
.base
.c_str());
3436 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3443 #ifndef LDID_NOFLAGT
3450 Map
mapping(path
, modify
);
3451 FatHeader
fat_header(mapping
.data(), mapping
.size());
3453 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3454 struct linkedit_data_command
*signature(NULL
);
3455 struct encryption_info_command
*encryption(NULL
);
3458 if (mach_header
.GetCPUType() != flag_CPUType
)
3460 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3465 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3467 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3468 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3471 else if (cmd
== LC_CODE_SIGNATURE
)
3472 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3473 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3474 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3475 else if (cmd
== LC_LOAD_DYLIB
) {
3476 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3477 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3479 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3482 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3483 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3487 #ifndef LDID_NOFLAGT
3488 else if (cmd
== LC_ID_DYLIB
) {
3489 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3497 dylib_command
->dylib
.timestamp
= 0;
3498 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3501 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3507 if (flag_d
&& encryption
!= NULL
) {
3508 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3512 _assert(encryption
!= NULL
);
3513 encryption
->cryptid
= mach_header
.Swap(0);
3516 if ((flag_e
|| flag_q
|| flag_s
|| flag_h
) && signature
== NULL
) {
3517 fprintf(stderr
, "ldid: -e, -q, -s, and -h requre a signed binary\n");
3522 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3524 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3525 uint8_t *blob
= top
+ data
;
3526 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3528 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3529 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3530 uint32_t begin
= Swap(super
->index
[index
].offset
);
3531 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3532 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3537 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3539 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3540 uint8_t *blob
= top
+ data
;
3541 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3543 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3544 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3545 uint32_t begin
= Swap(super
->index
[index
].offset
);
3546 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3547 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3552 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3554 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3555 uint8_t *blob
= top
+ data
;
3556 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3558 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3559 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3560 uint32_t begin
= Swap(super
->index
[index
].offset
);
3561 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3563 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3564 uint32_t pages
= Swap(directory
->nCodeSlots
);
3567 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3568 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3570 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3575 auto algorithms(GetAlgorithms());
3577 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3579 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3580 uint8_t *blob
= top
+ data
;
3581 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3584 CodeDirectory
*directory_
;
3586 Algorithm
&algorithm_
;
3590 std::map
<uint8_t, Candidate
> candidates
;
3592 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3593 auto type(Swap(super
->index
[index
].type
));
3594 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3595 uint32_t begin
= Swap(super
->index
[index
].offset
);
3596 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3597 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3598 auto type(directory
->hashType
);
3599 _assert(type
> 0 && type
<= algorithms
.size());
3600 auto &algorithm(*algorithms
[type
- 1]);
3601 uint8_t hash
[algorithm
.size_
];
3602 algorithm(hash
, blob
+ begin
, end
- begin
);
3603 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3607 _assert(!candidates
.empty());
3608 auto best(candidates
.end());
3611 const auto directory(best
->second
.directory_
);
3612 const auto flags(Swap(directory
->flags
));
3615 if (flags
& kSecCodeSignatureHost
)
3617 if (flags
& kSecCodeSignatureAdhoc
)
3619 if (flags
& kSecCodeSignatureForceHard
)
3621 if (flags
& kSecCodeSignatureForceKill
)
3623 if (flags
& kSecCodeSignatureForceExpiration
)
3624 names
+= ",expires";
3625 if (flags
& kSecCodeSignatureRestrict
)
3626 names
+= ",restrict";
3627 if (flags
& kSecCodeSignatureEnforcement
)
3628 names
+= ",enforcement";
3629 if (flags
& kSecCodeSignatureLibraryValidation
)
3630 names
+= ",library-validation";
3631 if (flags
& kSecCodeSignatureRuntime
)
3632 names
+= ",runtime";
3634 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3635 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3636 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3638 std::string choices
;
3639 for (const auto &candidate
: candidates
) {
3640 auto choice(candidate
.second
.algorithm_
.name());
3643 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3645 printf("Hash choices=%s\n", choices
.c_str() + 1);
3647 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3652 } catch (const char *) {
3657 #ifndef LDID_NOSMIME
3658 # if OPENSSL_VERSION_MAJOR >= 3
3659 OSSL_PROVIDER_unload(legacy
);
3660 OSSL_PROVIDER_unload(deflt
);