1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* SPDX-License-Identifier: AGPL-3.0-only */
6 /* GNU Affero General Public License, Version 3 {{{ */
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 #include <sys/types.h>
47 #include <openssl/opensslv.h>
48 # if OPENSSL_VERSION_MAJOR >= 3
49 # include <openssl/provider.h>
51 #include <openssl/err.h>
52 #include <openssl/pem.h>
53 #include <openssl/pkcs7.h>
54 #include <openssl/pkcs12.h>
55 #include <openssl/ui.h>
57 #include <openssl/sha.h>
59 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
60 #define LDID_SHA1 SHA1
61 #define LDID_SHA1_CTX SHA_CTX
62 #define LDID_SHA1_Init SHA1_Init
63 #define LDID_SHA1_Update SHA1_Update
64 #define LDID_SHA1_Final SHA1_Final
66 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
67 #define LDID_SHA256 SHA256
68 #define LDID_SHA256_CTX SHA256_CTX
69 #define LDID_SHA256_Init SHA256_Init
70 #define LDID_SHA256_Update SHA256_Update
71 #define LDID_SHA256_Final SHA256_Final
73 #include <plist/plist.h>
79 #define _assert___(line) \
81 #define _assert__(line) \
85 #define $(value) value
89 #define _assert_(expr, format, ...) \
91 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
92 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
95 // XXX: this is not acceptable
96 #define _assert_(expr, format, ...) \
98 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
103 #define _assert(expr) \
104 _assert_(expr, "%s", $(#expr))
106 #define _syscall(expr, ...) [&] { for (;;) { \
108 if ((long) _value != -1) \
111 if (error == EINTR) \
113 /* XXX: EINTR is included in this list to fix g++ */ \
114 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
115 if (error == success) \
116 return (decltype(expr)) -success; \
117 fprintf(stderr, "ldid: %s: %s\n", __func__, strerror(error)); \
122 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
128 __attribute__((packed))
130 std::string password
;
131 std::vector
<std::string
> cleanup
;
133 template <typename Type_
>
135 typedef typename
Type_::const_iterator Result
;
138 #define _foreach(item, list) \
139 for (bool _stop(true); _stop; ) \
140 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
141 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
142 for (bool _suck(true); _suck; _suck = false) \
143 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
148 template <typename Function_
>
156 Scope(const Function_
&function
) :
166 template <typename Function_
>
167 Scope
<Function_
> _scope(const Function_
&function
) {
168 return Scope
<Function_
>(function
);
171 #define _scope__(counter, function) \
172 __attribute__((__unused__)) \
173 const _Scope &_scope ## counter(_scope([&]function))
174 #define _scope_(counter, function) \
175 _scope__(counter, function)
176 #define _scope(function) \
177 _scope_(__COUNTER__, function)
184 #define FAT_MAGIC 0xcafebabe
185 #define FAT_CIGAM 0xbebafeca
205 #define MH_MAGIC 0xfeedface
206 #define MH_CIGAM 0xcefaedfe
208 #define MH_MAGIC_64 0xfeedfacf
209 #define MH_CIGAM_64 0xcffaedfe
211 #define MH_DYLDLINK 0x4
213 #define MH_OBJECT 0x1
214 #define MH_EXECUTE 0x2
216 #define MH_DYLINKER 0x7
217 #define MH_BUNDLE 0x8
218 #define MH_DYLIB_STUB 0x9
220 struct load_command
{
225 #define LC_REQ_DYLD uint32_t(0x80000000)
227 #define LC_SEGMENT uint32_t(0x01)
228 #define LC_SYMTAB uint32_t(0x02)
229 #define LC_DYSYMTAB uint32_t(0x0b)
230 #define LC_LOAD_DYLIB uint32_t(0x0c)
231 #define LC_ID_DYLIB uint32_t(0x0d)
232 #define LC_SEGMENT_64 uint32_t(0x19)
233 #define LC_UUID uint32_t(0x1b)
234 #define LC_CODE_SIGNATURE uint32_t(0x1d)
235 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
236 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
237 #define LC_ENCRYPTION_INFO uint32_t(0x21)
238 #define LC_DYLD_INFO uint32_t(0x22)
239 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
240 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
255 uint32_t current_version
;
256 uint32_t compatibility_version
;
259 struct dylib_command
{
265 struct uuid_command
{
271 struct symtab_command
{
280 struct dyld_info_command
{
284 uint32_t rebase_size
;
287 uint32_t weak_bind_off
;
288 uint32_t weak_bind_size
;
289 uint32_t lazy_bind_off
;
290 uint32_t lazy_bind_size
;
292 uint32_t export_size
;
295 struct dysymtab_command
{
308 uint32_t extrefsymoff
;
309 uint32_t nextrefsyms
;
310 uint32_t indirectsymoff
;
311 uint32_t nindirectsyms
;
318 struct dylib_table_of_contents
{
319 uint32_t symbol_index
;
320 uint32_t module_index
;
323 struct dylib_module
{
324 uint32_t module_name
;
333 uint32_t iinit_iterm
;
334 uint32_t ninit_nterm
;
335 uint32_t objc_module_info_addr
;
336 uint32_t objc_module_info_size
;
339 struct dylib_reference
{
344 struct relocation_info
{
346 uint32_t r_symbolnum
:24;
365 struct segment_command
{
379 struct segment_command_64
{
422 struct linkedit_data_command
{
429 struct encryption_info_command
{
437 #define BIND_OPCODE_MASK 0xf0
438 #define BIND_IMMEDIATE_MASK 0x0f
439 #define BIND_OPCODE_DONE 0x00
440 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
441 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
442 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
443 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
444 #define BIND_OPCODE_SET_TYPE_IMM 0x50
445 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
446 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
447 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
448 #define BIND_OPCODE_DO_BIND 0x90
449 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
450 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
451 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
453 struct : ldid::Progress
{
454 virtual void operator()(const std::string
&value
) const {
457 virtual void operator()(double value
) const {
461 struct Progression
: ldid::Progress
{
462 const ldid::Progress
&progress_
;
465 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
471 virtual void operator()(const std::string
&value
) const {
472 return progress_(name_
+ " (" + value
+ ")");
475 virtual void operator()(double value
) const {
476 return progress_(value
);
480 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
481 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
486 static inline void put(std::streambuf
&stream
, uint8_t value
) {
487 _assert(stream
.sputc(value
) != EOF
);
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::Progress
&progress
) {
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 progress(double(total
) / size
);
508 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
509 return put(stream
, data
.data(), data
.size());
512 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
515 if (auto writ
= read(stream
, data
, size
))
521 static inline void pad(std::streambuf
&stream
, size_t size
) {
523 memset(padding
, 0, size
);
524 put(stream
, padding
, size
);
527 template <typename Type_
>
528 Type_
Align(Type_ value
, size_t align
) {
535 static const uint8_t PageShift_(0x0c);
536 static const uint32_t PageSize_(1 << PageShift_
);
538 static inline unsigned bytes(uint64_t value
) {
539 return (64 - __builtin_clzll(value
) + 7) / 8;
542 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
544 do put(stream
, uint8_t(value
>> (length
-= 8)));
548 static void der(std::streambuf
&stream
, uint64_t value
) {
552 unsigned length(bytes(value
));
553 put(stream
, 0x80 | length
);
554 put(stream
, value
, length
);
558 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
562 put(data
, value
, length
);
566 static std::string
der(uint8_t tag
, const char *value
) {
567 return der(tag
, value
, strlen(value
)); }
568 static std::string
der(uint8_t tag
, const std::string
&value
) {
569 return der(tag
, value
.data(), value
.size()); }
571 template <typename Type_
>
572 static void der_(std::stringbuf
&data
, const Type_
&values
) {
574 for (const auto &value
: values
)
575 size
+= value
.size();
577 for (const auto &value
: values
)
581 static std::string
der(const std::vector
<std::string
> &values
) {
588 static std::string
der(const std::multiset
<std::string
> &values
) {
595 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
596 const auto key(der(0x0c, value
.first
));
599 der(data
, key
.size() + value
.second
.size());
601 put(data
, value
.second
);
605 static std::string
der(plist_t data
) {
606 switch (const auto type
= plist_get_node_type(data
)) {
607 case PLIST_BOOLEAN
: {
609 plist_get_bool_val(data
, &value
);
614 put(data
, value
!= 0 ? 1 : 0);
620 plist_get_uint_val(data
, &value
);
621 const auto length(bytes(value
));
626 put(data
, value
, length
);
631 fprintf(stderr
, "ldid: Invalid plist entry type\n");
636 fprintf(stderr
, "ldid: Invalid plist entry type\n");
643 plist_get_data_val(data
, &value
, &length
);
644 _scope({ free(value
); });
645 return der(0x04, value
, length
);
650 plist_get_string_val(data
, &value
);
651 _scope({ free(value
); });
652 return der(0x0c, value
);
656 std::vector
<std::string
> values
;
657 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
658 values
.push_back(der(plist_array_get_item(data
, i
)));
663 std::multiset
<std::string
> values
;
665 plist_dict_iter
iterator(NULL
);
666 plist_dict_new_iter(data
, &iterator
);
667 _scope({ free(iterator
); });
672 plist_dict_next_item(data
, iterator
, &key
, &value
);
675 _scope({ free(key
); });
676 values
.insert(der(std::make_pair(key
, der(value
))));
683 fprintf(stderr
, "ldid: Unsupported plist type %d", type
);
689 static inline uint16_t Swap_(uint16_t value
) {
691 ((value
>> 8) & 0x00ff) |
692 ((value
<< 8) & 0xff00);
695 static inline uint32_t Swap_(uint32_t value
) {
696 value
= ((value
>> 8) & 0x00ff00ff) |
697 ((value
<< 8) & 0xff00ff00);
698 value
= ((value
>> 16) & 0x0000ffff) |
699 ((value
<< 16) & 0xffff0000);
703 static inline uint64_t Swap_(uint64_t value
) {
704 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
705 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
706 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
710 static inline int16_t Swap_(int16_t value
) {
711 return Swap_(static_cast<uint16_t>(value
));
714 static inline int32_t Swap_(int32_t value
) {
715 return Swap_(static_cast<uint32_t>(value
));
718 static inline int64_t Swap_(int64_t value
) {
719 return Swap_(static_cast<uint64_t>(value
));
722 static bool little_(true);
724 static inline uint16_t Swap(uint16_t value
) {
725 return little_
? Swap_(value
) : value
;
728 static inline uint32_t Swap(uint32_t value
) {
729 return little_
? Swap_(value
) : value
;
732 static inline uint64_t Swap(uint64_t value
) {
733 return little_
? Swap_(value
) : value
;
736 static inline int16_t Swap(int16_t value
) {
737 return Swap(static_cast<uint16_t>(value
));
740 static inline int32_t Swap(int32_t value
) {
741 return Swap(static_cast<uint32_t>(value
));
744 static inline int64_t Swap(int64_t value
) {
745 return Swap(static_cast<uint64_t>(value
));
758 Swapped(bool swapped
) :
763 template <typename Type_
>
764 Type_
Swap(Type_ value
) const {
765 return swapped_
? Swap_(value
) : value
;
777 Data(void *base
, size_t size
) :
783 void *GetBase() const {
787 size_t GetSize() const {
798 struct mach_header
*mach_header_
;
799 struct load_command
*load_command_
;
802 MachHeader(void *base
, size_t size
) :
805 mach_header_
= (mach_header
*) base
;
807 switch (Swap(mach_header_
->magic
)) {
809 swapped_
= !swapped_
;
815 swapped_
= !swapped_
;
821 fprintf(stderr
, "ldid: Unknown header magic\nAre you sure that is a Mach-O?\n");
825 void *post
= mach_header_
+ 1;
827 post
= (uint32_t *) post
+ 1;
828 load_command_
= (struct load_command
*) post
;
830 if (Swap(mach_header_
->filetype
) != MH_EXECUTE
&&
831 Swap(mach_header_
->filetype
) != MH_DYLIB
&&
832 Swap(mach_header_
->filetype
) != MH_DYLINKER
&&
833 Swap(mach_header_
->filetype
) != MH_BUNDLE
) {
834 fprintf(stderr
, "ldid: Unsupported Mach-O type\n");
839 bool Bits64() const {
843 struct mach_header
*operator ->() const {
847 operator struct mach_header
*() const {
851 uint32_t GetCPUType() const {
852 return Swap(mach_header_
->cputype
);
855 uint32_t GetCPUSubtype() const {
856 return Swap(mach_header_
->cpusubtype
) & 0xff;
859 struct load_command
*GetLoadCommand() const {
860 return load_command_
;
863 std::vector
<struct load_command
*> GetLoadCommands() const {
864 std::vector
<struct load_command
*> load_commands
;
866 struct load_command
*load_command
= load_command_
;
867 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
868 load_commands
.push_back(load_command
);
869 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
872 return load_commands
;
875 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
876 _foreach (load_command
, GetLoadCommands())
877 switch (Swap(load_command
->cmd
)) {
879 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
880 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
881 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
882 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
883 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
886 case LC_SEGMENT_64
: {
887 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
888 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
889 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
890 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
891 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
896 template <typename Target_
>
897 Target_
*GetOffset(uint32_t offset
) const {
898 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
902 class FatMachHeader
:
909 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
910 MachHeader(base
, size
),
915 fat_arch
*GetFatArch() const {
924 fat_header
*fat_header_
;
925 std::vector
<FatMachHeader
> mach_headers_
;
928 FatHeader(void *base
, size_t size
) :
931 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
933 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
934 swapped_
= !swapped_
;
936 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
938 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
940 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
941 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
943 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
944 uint32_t arch_offset
= Swap(fat_arch
->offset
);
945 uint32_t arch_size
= Swap(fat_arch
->size
);
946 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
952 std::vector
<FatMachHeader
> &GetMachHeaders() {
953 return mach_headers_
;
957 return fat_header_
!= NULL
;
960 struct fat_header
*operator ->() const {
964 operator struct fat_header
*() const {
969 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
970 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
971 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
972 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
973 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
974 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
975 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
976 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
977 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
979 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
980 #define CSSLOT_INFOSLOT uint32_t(0x00001)
981 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
982 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
983 #define CSSLOT_APPLICATION uint32_t(0x00004)
984 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
985 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
986 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
987 #define CSSLOT_ALTERNATE uint32_t(0x01000)
989 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
991 #define CS_HASHTYPE_SHA160_160 1
992 #define CS_HASHTYPE_SHA256_256 2
993 #define CS_HASHTYPE_SHA256_160 3
994 #define CS_HASHTYPE_SHA386_386 4
997 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
998 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
999 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
1000 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1001 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1002 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1003 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1005 enum SecCodeExecSegFlags
{
1006 kSecCodeExecSegMainBinary
= 0x001,
1007 kSecCodeExecSegAllowUnsigned
= 0x010,
1008 kSecCodeExecSegDebugger
= 0x020,
1009 kSecCodeExecSegJit
= 0x040,
1010 kSecCodeExecSegSkipLibraryVal
= 0x080,
1011 kSecCodeExecSegCanLoadCdHash
= 0x100,
1012 kSecCodeExecSegCanExecCdHash
= 0x100,
1029 struct BlobIndex index
[];
1032 struct CodeDirectory
{
1035 uint32_t hashOffset
;
1036 uint32_t identOffset
;
1037 uint32_t nSpecialSlots
;
1038 uint32_t nCodeSlots
;
1045 uint32_t scatterOffset
;
1046 uint32_t teamIDOffset
;
1048 uint64_t codeLimit64
;
1049 uint64_t execSegBase
;
1050 uint64_t execSegLimit
;
1051 uint64_t execSegFlags
;
1052 #if 0 // version = 0x20500
1054 uint32_t preEncryptOffset
;
1056 #if 0 // version = 0x20600
1057 uint8_t linkageHashType
;
1058 uint8_t linkageTruncated
;
1060 uint32_t linkageOffset
;
1061 uint32_t linkageSize
;
1065 enum CodeSignatureFlags
{
1066 kSecCodeSignatureHost
= 0x0001,
1067 kSecCodeSignatureAdhoc
= 0x0002,
1068 kSecCodeSignatureForceHard
= 0x0100,
1069 kSecCodeSignatureForceKill
= 0x0200,
1070 kSecCodeSignatureForceExpiration
= 0x0400,
1071 kSecCodeSignatureRestrict
= 0x0800,
1072 kSecCodeSignatureEnforcement
= 0x1000,
1073 kSecCodeSignatureLibraryValidation
= 0x2000,
1074 kSecCodeSignatureRuntime
= 0x10000,
1077 enum Kind
: uint32_t {
1078 exprForm
= 1, // prefix expr form
1081 enum ExprOp
: uint32_t {
1082 opFalse
, // unconditionally false
1083 opTrue
, // unconditionally true
1084 opIdent
, // match canonical code [string]
1085 opAppleAnchor
, // signed by Apple as Apple's product
1086 opAnchorHash
, // match anchor [cert hash]
1087 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1088 opAnd
, // binary prefix expr AND expr [expr; expr]
1089 opOr
, // binary prefix expr OR expr [expr; expr]
1090 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1091 opNot
, // logical inverse [expr]
1092 opInfoKeyField
, // Info.plist key field [string; match suffix]
1093 opCertField
, // Certificate field [cert index; field name; match suffix]
1094 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1095 opTrustedCerts
, // require trust settings to approve the cert chain
1096 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1097 opAppleGenericAnchor
, // signed by Apple in any capacity
1098 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1099 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1100 opNamedAnchor
, // named anchor type
1101 opNamedCode
, // named subroutine
1102 opPlatform
, // platform constraint [integer]
1103 exprOpCount
// (total opcode count in use)
1106 enum MatchOperation
{
1107 matchExists
, // anything but explicit "false" - no value stored
1108 matchEqual
, // equal (CFEqual)
1109 matchContains
, // partial match (substring)
1110 matchBeginsWith
, // partial match (initial substring)
1111 matchEndsWith
, // partial match (terminal substring)
1112 matchLessThan
, // less than (string with numeric comparison)
1113 matchGreaterThan
, // greater than (string with numeric comparison)
1114 matchLessEqual
, // less or equal (string with numeric comparison)
1115 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1118 #define OID_ISO_MEMBER 42
1119 #define OID_US OID_ISO_MEMBER, 134, 72
1120 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1121 #define APPLE_ADS_OID APPLE_OID, 0x64
1122 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1129 Algorithm(size_t size
, uint8_t type
) :
1135 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1137 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1138 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1139 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1141 virtual const char *name() = 0;
1144 struct AlgorithmSHA1
:
1148 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1152 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1156 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1157 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1160 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1161 return operator()(hash
.sha1_
, data
, size
);
1164 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1165 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1166 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1169 virtual const char *name() {
1174 struct AlgorithmSHA256
:
1178 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1182 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1183 return hash
.sha256_
;
1186 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1187 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1190 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1191 return operator()(hash
.sha256_
, data
, size
);
1194 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1195 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1196 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1199 virtual const char *name() {
1204 static bool do_sha1(true);
1205 static bool do_sha256(true);
1207 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1208 static AlgorithmSHA1 sha1
;
1209 static AlgorithmSHA256 sha256
;
1211 static std::vector
<Algorithm
*> algorithms
;
1212 if (algorithms
.empty()) {
1214 algorithms
.push_back(&sha1
);
1216 algorithms
.push_back(&sha256
);
1223 std::string entitlements_
;
1224 std::string derformat_
;
1227 struct CodesignAllocation
{
1228 FatMachHeader mach_header_
;
1237 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
) :
1238 mach_header_(mach_header
),
1250 #ifndef LDID_NOTOOLS
1263 _syscall(close(file_
));
1266 void open(const char *path
, int flags
) {
1267 file_
= ::open(path
, flags
);
1269 fprintf(stderr
, "ldid: %s: %s\n", path
, strerror(errno
));
1292 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1295 open(path
, oflag
, pflag
, mflag
);
1298 Map(const std::string
&path
, bool edit
) :
1308 bool empty() const {
1309 return data_
== NULL
;
1312 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1315 file_
.open(path
.c_str(), oflag
);
1316 int file(file_
.file());
1319 _syscall(fstat(file
, &stat
));
1320 size_
= stat
.st_size
;
1322 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1325 void open(const std::string
&path
, bool edit
) {
1327 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1329 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1335 _syscall(munmap(data_
, size_
));
1340 void *data() const {
1344 size_t size() const {
1348 operator std::string() const {
1349 return std::string(static_cast<char *>(data_
), size_
);
1352 #endif // LDID_NOTOOLS
1356 static plist_t
plist(const std::string
&data
);
1358 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1359 _foreach (load_command
, mach_header
.GetLoadCommands())
1360 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1361 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1362 auto offset(mach_header
.Swap(signature
->dataoff
));
1363 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1364 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1366 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1367 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1368 auto begin(Swap(super
->index
[index
].offset
));
1369 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1370 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1371 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1376 std::string
Analyze(const void *data
, size_t size
) {
1377 std::string entitlements
;
1379 FatHeader
fat_header(const_cast<void *>(data
), size
);
1380 _foreach (mach_header
, fat_header
.GetMachHeaders())
1381 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1382 if (entitlements
.empty())
1383 entitlements
.assign(data
, size
);
1385 if (entitlements
.compare(0, entitlements
.size(), data
, size
) != 0) {
1386 fprintf(stderr
, "ldid: Entitlements do not match\n");
1391 return entitlements
;
1394 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
) {
1395 FatHeader
source(const_cast<void *>(idata
), isize
);
1399 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1401 std::vector
<CodesignAllocation
> allocations
;
1402 _foreach (mach_header
, source
.GetMachHeaders()) {
1403 struct linkedit_data_command
*signature(NULL
);
1404 struct symtab_command
*symtab(NULL
);
1406 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1407 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1408 if (cmd
== LC_CODE_SIGNATURE
)
1409 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1410 else if (cmd
== LC_SYMTAB
)
1411 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1415 if (signature
== NULL
)
1416 size
= mach_header
.GetSize();
1418 size
= mach_header
.Swap(signature
->dataoff
);
1419 _assert(size
<= mach_header
.GetSize());
1422 if (symtab
!= NULL
) {
1423 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1424 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1425 _assert(end
<= size
);
1426 _assert(end
>= size
- 0x10);
1432 size_t alloc(allocate(mach_header
, baton
, size
));
1434 auto *fat_arch(mach_header
.GetFatArch());
1437 if (fat_arch
!= NULL
)
1438 align
= source
.Swap(fat_arch
->align
);
1439 else switch (mach_header
.GetCPUType()) {
1440 case CPU_TYPE_POWERPC
:
1441 case CPU_TYPE_POWERPC64
:
1443 case CPU_TYPE_X86_64
:
1447 case CPU_TYPE_ARM64
:
1448 case CPU_TYPE_ARM64_32
:
1456 const char *arch(NULL
);
1457 switch (mach_header
.GetCPUType()) {
1458 case CPU_TYPE_POWERPC
:
1461 case CPU_TYPE_POWERPC64
:
1467 case CPU_TYPE_X86_64
:
1473 case CPU_TYPE_ARM64
:
1476 case CPU_TYPE_ARM64_32
:
1481 offset
= Align(offset
, 1 << align
);
1483 uint32_t limit(size
);
1485 limit
= Align(limit
, 0x10);
1487 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1488 offset
+= size
+ alloc
;
1489 offset
= Align(offset
, 0x10);
1494 if (source
.IsFat()) {
1495 fat_header fat_header
;
1496 fat_header
.magic
= Swap(FAT_MAGIC
);
1497 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1498 put(output
, &fat_header
, sizeof(fat_header
));
1499 position
+= sizeof(fat_header
);
1501 // XXX: support fat_arch_64 (not in my toolchain)
1502 // probably use C++14 generic lambda (not in my toolchain)
1505 _foreach (allocation
, allocations
) {
1506 const auto offset(allocation
.offset_
);
1507 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1508 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1512 }(), "FAT slice >=4GiB not currently supported");
1514 _foreach (allocation
, allocations
) {
1515 auto &mach_header(allocation
.mach_header_
);
1518 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1519 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1520 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1521 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1522 fat_arch
.align
= Swap(allocation
.align_
);
1523 put(output
, &fat_arch
, sizeof(fat_arch
));
1524 position
+= sizeof(fat_arch
);
1528 _foreach (allocation
, allocations
) {
1529 progress(allocation
.arch_
);
1530 auto &mach_header(allocation
.mach_header_
);
1532 pad(output
, allocation
.offset_
- position
);
1533 position
= allocation
.offset_
;
1538 std::vector
<std::string
> commands
;
1540 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1541 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1543 switch (mach_header
.Swap(load_command
->cmd
)) {
1544 case LC_CODE_SIGNATURE
:
1548 // XXX: this is getting ridiculous: provide a better abstraction
1551 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1553 if ((segment_command
->initprot
& 04) != 0) {
1554 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1555 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1562 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1563 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1564 segment_command
->filesize
= size
;
1565 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1569 case LC_SEGMENT_64
: {
1570 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1572 if ((segment_command
->initprot
& 04) != 0) {
1573 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1574 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1581 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1582 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1583 segment_command
->filesize
= size
;
1584 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1589 commands
.push_back(copy
);
1592 if (allocation
.alloc_
!= 0) {
1593 linkedit_data_command signature
;
1594 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1595 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1596 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1597 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1598 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1601 size_t begin(position
);
1604 _foreach(command
, commands
)
1605 after
+= command
.size();
1607 std::stringbuf altern
;
1609 struct mach_header
header(*mach_header
);
1610 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1611 header
.sizeofcmds
= mach_header
.Swap(after
);
1612 put(output
, &header
, sizeof(header
));
1613 put(altern
, &header
, sizeof(header
));
1614 position
+= sizeof(header
);
1616 if (mach_header
.Bits64()) {
1617 auto pad(mach_header
.Swap(uint32_t(0)));
1618 put(output
, &pad
, sizeof(pad
));
1619 put(altern
, &pad
, sizeof(pad
));
1620 position
+= sizeof(pad
);
1623 _foreach(command
, commands
) {
1624 put(output
, command
.data(), command
.size());
1625 put(altern
, command
.data(), command
.size());
1626 position
+= command
.size();
1629 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1630 if (before
> after
) {
1631 pad(output
, before
- after
);
1632 pad(altern
, before
- after
);
1633 position
+= before
- after
;
1636 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1638 std::string
overlap(altern
.str());
1639 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1641 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1642 position
= begin
+ allocation
.size_
;
1644 pad(output
, allocation
.limit_
- allocation
.size_
);
1645 position
+= allocation
.limit_
- allocation
.size_
;
1647 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1648 if (allocation
.alloc_
> saved
)
1649 pad(output
, allocation
.alloc_
- saved
);
1651 _assert(allocation
.alloc_
== saved
);
1652 position
+= allocation
.alloc_
;
1658 typedef std::map
<uint32_t, std::string
> Blobs
;
1660 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1661 auto value(buffer
.str());
1662 std::swap(blobs
[slot
], value
);
1665 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1666 auto value(buffer
.str());
1668 blob
.magic
= Swap(magic
);
1669 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1670 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1671 auto &save(blobs
[slot
]);
1672 std::swap(save
, value
);
1676 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1678 _foreach (blob
, blobs
)
1679 total
+= blob
.second
.size();
1681 struct SuperBlob super
;
1682 super
.blob
.magic
= Swap(magic
);
1683 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1684 super
.count
= Swap(uint32_t(blobs
.size()));
1685 put(output
, &super
, sizeof(super
));
1687 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1689 _foreach (blob
, blobs
) {
1691 index
.type
= Swap(blob
.first
);
1692 index
.offset
= Swap(uint32_t(offset
));
1693 put(output
, &index
, sizeof(index
));
1694 offset
+= blob
.second
.size();
1697 _foreach (blob
, blobs
)
1698 put(output
, blob
.second
.data(), blob
.second
.size());
1711 _assert(bio_
!= NULL
);
1715 bio_(BIO_new(BIO_s_mem()))
1719 Buffer(const char *data
, size_t size
) :
1720 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1724 Buffer(const std::string
&data
) :
1725 Buffer(data
.data(), data
.size())
1729 Buffer(PKCS7
*pkcs
) :
1732 if (i2d_PKCS7_bio(bio_
, pkcs
) == 0){
1733 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1742 operator BIO
*() const {
1746 explicit operator std::string() const {
1748 auto size(BIO_get_mem_data(bio_
, &data
));
1749 return std::string(data
, size
);
1758 STACK_OF(X509
) *ca_
;
1762 value_(d2i_PKCS12_bio(bio
, NULL
)),
1765 if (value_
== NULL
){
1766 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1770 if (!PKCS12_verify_mac(value_
, "", 0) && password
.empty()) {
1772 UI_UTIL_read_pw_string(passbuf
, 2048, "Enter password: ", 0);
1776 if (PKCS12_parse(value_
, password
.c_str(), &key_
, &cert_
, &ca_
) <= 0){
1777 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1780 if (key_
== NULL
|| cert_
== NULL
){
1781 fprintf(stderr
, "ldid: An error occured while parsing: %s\nYour p12 cert might not be valid\n", ERR_error_string(ERR_get_error(), NULL
));
1786 ca_
= sk_X509_new_null();
1788 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1793 Stuff(const std::string
&data
) :
1799 sk_X509_pop_free(ca_
, X509_free
);
1801 EVP_PKEY_free(key_
);
1802 PKCS12_free(value_
);
1805 operator PKCS12
*() const {
1809 operator EVP_PKEY
*() const {
1813 operator X509
*() const {
1817 operator STACK_OF(X509
) *() const {
1823 struct SEQUENCE_hash_sha1
{
1824 uint8_t SEQUENCE
[2] = {0x30, 0x1d}; // size
1825 uint8_t OBJECT_IDENTIFIER
[7] = {0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A}; // OBJECT IDENTIFIER 1.3.14.3.2.26 sha1 (OIW)
1826 uint8_t hash_size
[2] = {0x04, 0x14};
1830 struct SEQUENCE_hash_sha256
{
1831 uint8_t SEQUENCE
[2] = {0x30, 0x2d}; // size
1832 uint8_t OBJECT_IDENTIFIER
[11] = {0x06 ,0x09 ,0x60, 0x86, 0x48, 0x01 ,0x65, 0x03, 0x04, 0x02, 0x01}; // 2.16.840.1.101.3.4.2.1 sha-256 (NIST Algorithm)
1833 uint8_t hash_size
[2] = {0x04, 0x20}; // hash size
1842 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
, const std::vector
<char>& alternateCDSHA1
, const std::vector
<char>& alternateCDSHA256
) {
1843 value_
= PKCS7_new();
1844 if (value_
== NULL
){
1845 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1849 if (PKCS7_set_type(value_
, NID_pkcs7_signed
) == 0 ||
1850 PKCS7_content_new(value_
, NID_pkcs7_data
) == 0) {
1851 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1855 STACK_OF(X509
) *certs(stuff
);
1856 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++) {
1857 if (PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)) == 0) {
1858 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1863 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1865 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1869 X509_ATTRIBUTE
*attribute
= X509_ATTRIBUTE_new();
1870 ASN1_OBJECT
*obj2
= OBJ_txt2obj("1.2.840.113635.100.9.2", 1);
1871 X509_ATTRIBUTE_set1_object(attribute
, obj2
);
1873 SEQUENCE_hash_sha1 seq1
;
1874 memcpy((void *)seq1
.hash
,(void *)alternateCDSHA1
.data() ,alternateCDSHA1
.size());
1875 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq1
, sizeof(seq1
));
1877 SEQUENCE_hash_sha256 seq256
;
1878 memcpy((void *)seq256
.hash
,(void *)alternateCDSHA256
.data() ,alternateCDSHA256
.size());
1879 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq256
, sizeof(seq256
));
1881 STACK_OF(X509_ATTRIBUTE
) *sk
= PKCS7_get_signed_attributes(info
);
1882 if (!sk_X509_ATTRIBUTE_push(sk
, attribute
)) {
1883 fprintf(stderr
, "ldid: sk_X509_ATTRIBUTE_push failed: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1887 PKCS7_set_detached(value_
, 1);
1889 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1890 if (string
== NULL
) {
1891 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1896 if (ASN1_STRING_set(string
, xml
.data(), xml
.size()) == 0) {
1897 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1901 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1902 if (PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
) == 0) {
1903 fprintf(stderr
, "ldid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1907 ASN1_OCTET_STRING_free(string
);
1911 if (PKCS7_final(value_
, data
, PKCS7_BINARY
) == 0) {
1912 fprintf(stderr
, "ldid: Failed to sign: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1921 operator PKCS7
*() const {
1927 public std::streambuf
1930 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1934 virtual int_type
overflow(int_type next
) {
1940 public std::streambuf
1945 LDID_SHA1_CTX sha1_
;
1946 LDID_SHA256_CTX sha256_
;
1949 HashBuffer(ldid::Hash
&hash
) :
1952 LDID_SHA1_Init(&sha1_
);
1953 LDID_SHA256_Init(&sha256_
);
1957 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1958 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1961 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1962 LDID_SHA1_Update(&sha1_
, data
, size
);
1963 LDID_SHA256_Update(&sha256_
, data
, size
);
1967 virtual int_type
overflow(int_type next
) {
1968 if (next
== traits_type::eof())
1980 std::streambuf
&buffer_
;
1983 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1989 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1990 _assert(HashBuffer::xsputn(data
, size
) == size
);
1991 return buffer_
.sputn(data
, size
);
1995 #ifndef LDID_NOTOOLS
1996 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1997 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
2005 Split(const std::string
&path
) {
2006 size_t slash(path
.rfind('/'));
2007 if (slash
== std::string::npos
)
2010 dir
= path
.substr(0, slash
+ 1);
2011 base
= path
.substr(slash
+ 1);
2016 static void mkdir_p(const std::string
&path
) {
2020 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
2023 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2026 auto slash(path
.rfind('/', path
.size() - 1));
2027 if (slash
== std::string::npos
)
2029 mkdir_p(path
.substr(0, slash
));
2032 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2033 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2035 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2036 cleanup
.push_back(temp
);
2040 static void Commit(const std::string
&path
, const std::string
&temp
) {
2042 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2044 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2046 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2049 _syscall(rename(temp
.c_str(), path
.c_str()));
2050 cleanup
.erase(std::remove(cleanup
.begin(), cleanup
.end(), temp
), cleanup
.end());
2052 #endif // LDID_NOTOOLS
2056 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2057 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2059 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2062 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2064 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2067 auto entry(X509_NAME_get_entry(name
, index
));
2068 if (entry
== NULL
) {
2069 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2072 auto asn(X509_NAME_ENTRY_get_data(entry
));
2074 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2077 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2080 static void req(std::streambuf
&buffer
, uint32_t value
) {
2081 value
= Swap(value
);
2082 put(buffer
, &value
, sizeof(value
));
2085 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2086 req(buffer
, value
.size());
2087 put(buffer
, value
.data(), value
.size());
2088 static uint8_t zeros
[] = {0,0,0,0};
2089 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2092 template <size_t Size_
>
2093 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2095 put(buffer
, data
, Size_
);
2096 static uint8_t zeros
[] = {0,0,0,0};
2097 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2100 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
) {
2109 auto name(X509_get_subject_name(stuff
));
2111 fprintf(stderr
, "ldid: Your certificate might not be valid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2114 get(team
, name
, NID_organizationalUnitName
);
2115 get(common
, name
, NID_commonName
);
2119 std::stringbuf backing
;
2121 if (!requirements
.empty()) {
2122 put(backing
, requirements
.data(), requirements
.size());
2126 std::stringbuf requirement
;
2127 req(requirement
, exprForm
);
2128 req(requirement
, opAnd
);
2129 req(requirement
, opIdent
);
2130 req(requirement
, identifier
);
2131 req(requirement
, opAnd
);
2132 req(requirement
, opAppleGenericAnchor
);
2133 req(requirement
, opAnd
);
2134 req(requirement
, opCertField
);
2135 req(requirement
, 0);
2136 req(requirement
, "subject.CN");
2137 req(requirement
, matchEqual
);
2138 req(requirement
, common
);
2139 req(requirement
, opCertGeneric
);
2140 req(requirement
, 1);
2141 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2142 req(requirement
, matchExists
);
2143 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2145 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2149 // XXX: this is just a "sufficiently large number"
2150 size_t certificate(0x3000);
2152 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2153 size_t alloc(sizeof(struct SuperBlob
));
2155 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2157 uint32_t special(0);
2159 _foreach (slot
, slots
)
2160 special
= std::max(special
, slot
.first
);
2162 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2163 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2164 special
= std::max(special
, CSSLOT_INFOSLOT
);
2167 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2168 alloc
+= sizeof(struct BlobIndex
);
2169 alloc
+= backing
.str().size();
2172 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2173 baton
.entitlements_
.assign(data
, size
);
2176 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2177 auto combined(plist(baton
.entitlements_
));
2178 _scope({ plist_free(combined
); });
2179 if (plist_get_node_type(combined
) != PLIST_DICT
) {
2180 fprintf(stderr
, "ldid: Existing entitlements are in wrong format\n");
2184 auto merging(plist(entitlements
));
2185 _scope({ plist_free(merging
); });
2186 if (plist_get_node_type(merging
) != PLIST_DICT
) {
2187 fprintf(stderr
, "ldid: Entitlements need a root key of dict\n");
2191 plist_dict_iter
iterator(NULL
);
2192 plist_dict_new_iter(merging
, &iterator
);
2193 _scope({ free(iterator
); });
2197 plist_t
value(NULL
);
2198 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2201 _scope({ free(key
); });
2202 plist_dict_set_item(combined
, key
, plist_copy(value
));
2205 baton
.derformat_
= der(combined
);
2209 plist_to_xml(combined
, &xml
, &size
);
2210 _scope({ free(xml
); });
2212 baton
.entitlements_
.assign(xml
, size
);
2215 if (!baton
.entitlements_
.empty()) {
2216 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2217 alloc
+= sizeof(struct BlobIndex
);
2218 alloc
+= sizeof(struct Blob
);
2219 alloc
+= baton
.entitlements_
.size();
2222 if (!baton
.derformat_
.empty()) {
2223 special
= std::max(special
, CSSLOT_DERFORMAT
);
2224 alloc
+= sizeof(struct BlobIndex
);
2225 alloc
+= sizeof(struct Blob
);
2226 alloc
+= baton
.derformat_
.size();
2229 size_t directory(0);
2231 directory
+= sizeof(struct BlobIndex
);
2232 directory
+= sizeof(struct Blob
);
2233 directory
+= sizeof(struct CodeDirectory
);
2234 directory
+= identifier
.size() + 1;
2237 directory
+= team
.size() + 1;
2239 for (Algorithm
*algorithm
: GetAlgorithms())
2240 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2243 alloc
+= sizeof(struct BlobIndex
);
2244 alloc
+= sizeof(struct Blob
);
2245 alloc
+= certificate
;
2249 }), 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 {
2253 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2257 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2258 execs
|= kSecCodeExecSegMainBinary
;
2260 if (!baton
.entitlements_
.empty()) {
2261 std::stringbuf data
;
2262 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2263 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2265 auto entitlements(plist(baton
.entitlements_
));
2266 _scope({ plist_free(entitlements
); });
2267 if (plist_get_node_type(entitlements
) != PLIST_DICT
) {
2268 fprintf(stderr
, "ldid: Entitlements should be a plist dicionary\n");
2272 const auto entitled([&](const char *key
) {
2273 auto item(plist_dict_get_item(entitlements
, key
));
2274 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2277 plist_get_bool_val(item
, &value
);
2281 if (entitled("get-task-allow"))
2282 execs
|= kSecCodeExecSegAllowUnsigned
;
2283 if (entitled("run-unsigned-code"))
2284 execs
|= kSecCodeExecSegAllowUnsigned
;
2285 if (entitled("com.apple.private.cs.debugger"))
2286 execs
|= kSecCodeExecSegDebugger
;
2287 if (entitled("dynamic-codesigning"))
2288 execs
|= kSecCodeExecSegJit
;
2289 if (entitled("com.apple.private.skip-library-validation"))
2290 execs
|= kSecCodeExecSegSkipLibraryVal
;
2291 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2292 execs
|= kSecCodeExecSegCanLoadCdHash
;
2293 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2294 execs
|= kSecCodeExecSegCanExecCdHash
;
2297 if (!baton
.derformat_
.empty()) {
2298 std::stringbuf data
;
2299 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2300 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2305 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2306 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2307 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2308 for (Algorithm
*algorithm
: GetAlgorithms())
2309 (*algorithm
)(slot
, data
, size
);
2314 for (Algorithm
*pointer
: GetAlgorithms()) {
2315 Algorithm
&algorithm(*pointer
);
2317 std::stringbuf data
;
2319 uint32_t special(0);
2320 _foreach (blob
, blobs
)
2321 special
= std::max(special
, blob
.first
);
2322 _foreach (slot
, posts
)
2323 special
= std::max(special
, slot
.first
);
2324 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2326 CodeDirectory directory
;
2327 directory
.version
= Swap(uint32_t(0x00020400));
2328 directory
.flags
= Swap(uint32_t(flags
));
2329 directory
.nSpecialSlots
= Swap(special
);
2330 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2331 directory
.nCodeSlots
= Swap(normal
);
2332 directory
.hashSize
= algorithm
.size_
;
2333 directory
.hashType
= algorithm
.type_
;
2334 directory
.platform
= platform
? 0x01 : 0x00;
2335 directory
.pageSize
= PageShift_
;
2336 directory
.spare2
= Swap(uint32_t(0));
2337 directory
.scatterOffset
= Swap(uint32_t(0));
2338 directory
.spare3
= Swap(uint32_t(0));
2339 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2340 directory
.execSegBase
= Swap(uint64_t(left
));
2341 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2342 directory
.execSegFlags
= Swap(execs
);
2344 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2346 directory
.identOffset
= Swap(uint32_t(offset
));
2347 offset
+= identifier
.size() + 1;
2350 directory
.teamIDOffset
= Swap(uint32_t(0));
2352 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2353 offset
+= team
.size() + 1;
2356 offset
+= special
* algorithm
.size_
;
2357 directory
.hashOffset
= Swap(uint32_t(offset
));
2358 offset
+= normal
* algorithm
.size_
;
2360 put(data
, &directory
, sizeof(directory
));
2362 put(data
, identifier
.c_str(), identifier
.size() + 1);
2364 put(data
, team
.c_str(), team
.size() + 1);
2366 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2367 auto *hashes(&storage
[special
* algorithm
.size_
]);
2369 memset(storage
.data(), 0, special
* algorithm
.size_
);
2371 _foreach (blob
, blobs
) {
2372 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2373 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2376 _foreach (slot
, posts
)
2377 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2381 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2382 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2383 progress(double(i
) / normal
);
2386 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2389 put(data
, storage
.data(), storage
.size());
2391 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2392 algorithm(hash
, save
.data(), save
.size());
2398 auto plist(plist_new_dict());
2399 _scope({ plist_free(plist
); });
2401 auto cdhashes(plist_new_array());
2402 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2404 std::vector
<char> alternateCDSHA256
;
2405 std::vector
<char> alternateCDSHA1
;
2408 for (Algorithm
*pointer
: GetAlgorithms()) {
2409 Algorithm
&algorithm(*pointer
);
2412 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2415 std::vector
<char> hash
;
2416 algorithm(hash
, blob
.data(), blob
.size());
2417 if (algorithm
.type_
== CS_HASHTYPE_SHA256_256
)
2418 alternateCDSHA256
= hash
;
2419 else if (algorithm
.type_
== CS_HASHTYPE_SHA160_160
)
2420 alternateCDSHA1
= hash
;
2423 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2428 plist_to_xml(plist
, &xml
, &size
);
2429 _scope({ free(xml
); });
2431 std::stringbuf data
;
2432 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2437 Signature
signature(stuff
, sign
, std::string(xml
, size
), alternateCDSHA1
, alternateCDSHA256
);
2438 Buffer
result(signature
);
2439 std::string
value(result
);
2440 put(data
, value
.data(), value
.size());
2442 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2443 _assert(save
.size() <= certificate
);
2446 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2452 #ifndef LDID_NOTOOLS
2453 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2454 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2456 }), 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 {
2461 std::string
DiskFolder::Path(const std::string
&path
) const {
2462 return path_
+ path
;
2465 DiskFolder::DiskFolder(const std::string
&path
) :
2468 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2471 DiskFolder::~DiskFolder() {
2472 if (!std::uncaught_exception())
2473 for (const auto &commit
: commit_
)
2474 Commit(commit
.first
, commit
.second
);
2478 std::string
readlink(const std::string
&path
) {
2479 for (size_t size(1024); ; size
*= 2) {
2483 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2484 if (size_t(writ
) >= size
)
2493 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 {
2494 std::string
path(Path(root
) + base
);
2496 DIR *dir(opendir(path
.c_str()));
2497 _assert(dir
!= NULL
);
2498 _scope({ _syscall(closedir(dir
)); });
2500 while (auto child
= readdir(dir
)) {
2501 std::string
name(child
->d_name
);
2502 if (name
== "." || name
== "..")
2504 if (Starts(name
, ".ldid."))
2511 _syscall(stat((path
+ name
).c_str(), &info
));
2512 if (S_ISDIR(info
.st_mode
))
2514 else if (S_ISREG(info
.st_mode
))
2517 _assert_(false, "st_mode=%x", info
.st_mode
);
2519 switch (child
->d_type
) {
2527 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2530 _assert_(false, "d_type=%u", child
->d_type
);
2535 Find(root
, base
+ name
+ "/", code
, link
);
2541 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2547 auto from(Path(path
));
2548 commit_
[from
] = Temporary(save
, from
);
2553 bool DiskFolder::Look(const std::string
&path
) const {
2554 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2557 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2559 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2560 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2562 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2563 data
.pubseekpos(0, std::ios::in
);
2564 code(data
, length
, NULL
);
2567 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 {
2568 Find(path
, "", code
, link
);
2570 #endif // LDID_NOTOOLS
2572 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2576 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2579 std::string
SubFolder::Path(const std::string
&path
) const {
2580 return path_
+ path
;
2583 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2584 return parent_
.Save(Path(path
), edit
, flag
, code
);
2587 bool SubFolder::Look(const std::string
&path
) const {
2588 return parent_
.Look(Path(path
));
2591 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2592 return parent_
.Open(Path(path
), code
);
2595 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 {
2596 return parent_
.Find(Path(path
), code
, link
);
2599 std::string
UnionFolder::Map(const std::string
&path
) const {
2600 auto remap(remaps_
.find(path
));
2601 if (remap
== remaps_
.end())
2603 return remap
->second
;
2606 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 {
2607 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2608 code(file
.substr(path
.size()));
2611 UnionFolder::UnionFolder(Folder
&parent
) :
2616 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2617 return parent_
.Save(Map(path
), edit
, flag
, code
);
2620 bool UnionFolder::Look(const std::string
&path
) const {
2621 auto file(resets_
.find(path
));
2622 if (file
!= resets_
.end())
2624 return parent_
.Look(Map(path
));
2627 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2628 auto file(resets_
.find(path
));
2629 if (file
== resets_
.end())
2630 return parent_
.Open(Map(path
), code
);
2631 auto &entry(file
->second
);
2633 auto &data(*entry
.data_
);
2634 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2635 data
.pubseekpos(0, std::ios::in
);
2636 code(data
, length
, entry
.flag_
);
2639 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 {
2640 for (auto &reset
: resets_
)
2641 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2642 auto &entry(reset
.second
);
2643 auto &data(*entry
.data_
);
2644 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2645 data
.pubseekpos(0, std::ios::in
);
2646 code(data
, length
, entry
.flag_
);
2649 for (auto &remap
: remaps_
)
2650 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2651 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2652 code(data
, length
, flag
);
2656 parent_
.Find(path
, fun([&](const std::string
&name
) {
2657 if (deletes_
.find(path
+ name
) == deletes_
.end())
2659 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2660 if (deletes_
.find(path
+ name
) == deletes_
.end())
2665 #ifndef LDID_NOTOOLS
2666 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2670 char data
[4096 * 4];
2671 size_t writ(source
.sgetn(data
, sizeof(data
)));
2674 _assert(target
.sputn(data
, writ
) == writ
);
2676 progress(double(total
) / length
);
2680 static plist_t
plist(const std::string
&data
) {
2682 return plist_new_dict();
2683 plist_t
plist(NULL
);
2684 if (Starts(data
, "bplist00"))
2685 plist_from_bin(data
.data(), data
.size(), &plist
);
2687 plist_from_xml(data
.data(), data
.size(), &plist
);
2688 if (plist
== NULL
) {
2689 fprintf(stderr
, "ldid: Failed to parse plist\n");
2695 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2696 std::stringbuf data
;
2697 copy(buffer
, data
, length
, dummy_
);
2698 auto node(plist(data
.str()));
2699 _scope({ plist_free(node
); });
2700 if (plist_get_node_type(node
) != PLIST_DICT
) {
2701 fprintf(stderr
, "ldid: Unexpected plist type. Expected <dict>\n");
2707 static std::string
plist_s(plist_t node
) {
2710 if (plist_get_node_type(node
) != PLIST_STRING
) {
2711 fprintf(stderr
, "ldid: Unexpected plist type. Expected <string>\n");
2715 plist_get_string_val(node
, &data
);
2716 _scope({ free(data
); });
2731 std::vector
<std::string
> matches_
;
2734 Expression(const std::string
&code
) {
2735 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2736 matches_
.resize(regex_
.re_nsub
+ 1);
2743 bool operator ()(const std::string
&data
) {
2744 regmatch_t matches
[matches_
.size()];
2745 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2746 if (value
== REG_NOMATCH
)
2748 _assert_(value
== 0, "regexec()");
2749 for (size_t i(0); i
!= matches_
.size(); ++i
)
2750 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2754 const std::string
&operator [](size_t index
) const {
2755 return matches_
[index
];
2764 mutable std::unique_ptr
<Expression
> regex_
;
2766 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2773 Rule(const Rule
&rhs
) :
2774 weight_(rhs
.weight_
),
2780 void Compile() const {
2781 regex_
.reset(new Expression(code_
));
2784 bool operator ()(const std::string
&data
) const {
2785 _assert(regex_
.get() != NULL
);
2786 return (*regex_
)(data
);
2789 bool operator <(const Rule
&rhs
) const {
2790 if (weight_
> rhs
.weight_
)
2792 if (weight_
< rhs
.weight_
)
2794 return mode_
> rhs
.mode_
;
2799 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2800 return lhs
->code_
< rhs
->code_
;
2804 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
) {
2805 // XXX: this is a miserable fail
2806 std::stringbuf temp
;
2807 put(temp
, prefix
, size
);
2808 copy(buffer
, temp
, length
- size
, progress
);
2809 // XXX: this is a stupid hack
2810 pad(temp
, 0x10 - (length
& 0xf));
2811 auto data(temp
.str());
2813 HashProxy
proxy(hash
, save
);
2814 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2818 std::map
<std::string
, Hash
> files
;
2819 std::map
<std::string
, std::string
> links
;
2821 void Merge(const std::string
&root
, const State
&state
) {
2822 for (const auto &entry
: state
.files
)
2823 files
[root
+ entry
.first
] = entry
.second
;
2824 for (const auto &entry
: state
.links
)
2825 links
[root
+ entry
.first
] = entry
.second
;
2829 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
) {
2830 std::string executable
;
2831 std::string identifier
;
2835 std::string
info("Info.plist");
2837 SubFolder
folder(parent
, [&]() {
2838 if (parent
.Look(info
))
2841 if (parent
.Look("Contents/" + info
))
2843 else if (parent
.Look("Resources/" + info
)) {
2844 info
= "Resources/" + info
;
2847 fprintf(stderr
, "ldid: Could not find Info.plist\n");
2852 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2853 plist_d(buffer
, length
, fun([&](plist_t node
) {
2854 plist_t
nodebuf(plist_dict_get_item(node
, "CFBundleExecutable"));
2855 if (nodebuf
== NULL
) {
2856 fprintf(stderr
, "ldid: Cannot find key CFBundleExecutable\n");
2859 executable
= plist_s(nodebuf
);
2860 nodebuf
= plist_dict_get_item(node
, "CFBundleIdentifier");
2861 if (nodebuf
== NULL
) {
2862 fprintf(stderr
, "ldid: Cannot find key CFBundleIdentifier\n");
2865 identifier
= plist_s(nodebuf
);
2869 if (mac
&& info
== "Info.plist")
2870 executable
= "MacOS/" + executable
;
2872 progress(root
+ "*");
2874 std::string entitlements
;
2875 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2876 // XXX: this is a miserable fail
2877 std::stringbuf temp
;
2878 copy(buffer
, temp
, length
, progress
);
2879 // XXX: this is a stupid hack
2880 pad(temp
, 0x10 - (length
& 0xf));
2881 auto data(temp
.str());
2882 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2885 static const std::string
directory("_CodeSignature/");
2886 static const std::string
signature(directory
+ "CodeResources");
2888 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2890 auto &rules1(versions
[""]);
2891 auto &rules2(versions
["2"]);
2893 const std::string
resources(mac
? "Resources/" : "");
2896 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2897 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2898 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2899 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2900 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2904 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2905 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2906 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2907 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2908 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2909 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2910 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2911 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2912 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2913 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2914 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2915 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2916 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2917 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2920 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2921 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2922 std::map
<std::string
, Bundle
> bundles
;
2924 folder
.Find("", fun([&](const std::string
&name
) {
2927 auto bundle(Split(name
).dir
);
2929 _assert(!bundle
.empty());
2930 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2932 SubFolder
subfolder(folder
, bundle
);
2935 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2936 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2938 local
.Merge(bundle
, remote
);
2939 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2942 std::set
<std::string
> excludes
;
2944 auto exclude([&](const std::string
&name
) {
2945 // BundleDiskRep::adjustResources -> builder.addExclusion
2946 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2949 for (const auto &bundle
: bundles
)
2950 if (Starts(name
, bundle
.first
+ "/")) {
2951 excludes
.insert(name
);
2958 folder
.Find("", fun([&](const std::string
&name
) {
2962 if (local
.files
.find(name
) != local
.files
.end())
2964 auto &hash(local
.files
[name
]);
2966 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2967 progress(root
+ name
);
2978 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2980 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2981 switch (Swap(header
.magic
)) {
2983 // Java class file format
2984 if (Swap(header
.count
) >= 40)
2987 case MH_MAGIC
: case MH_MAGIC_64
:
2988 case MH_CIGAM
: case MH_CIGAM_64
:
2989 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2991 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2996 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2997 HashProxy
proxy(hash
, save
);
2998 put(proxy
, header
.bytes
, size
);
2999 copy(data
, proxy
, length
- size
, progress
);
3002 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
3006 local
.links
[name
] = read();
3009 auto plist(plist_new_dict());
3010 _scope({ plist_free(plist
); });
3012 for (const auto &version
: versions
) {
3013 auto files(plist_new_dict());
3014 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
3016 for (const auto &rule
: version
.second
)
3019 bool old(&version
.second
== &rules1
);
3021 for (const auto &hash
: local
.files
)
3022 for (const auto &rule
: version
.second
)
3023 if (rule(hash
.first
)) {
3024 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
3025 else if (old
&& rule
.mode_
== NoMode
)
3026 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3027 else if (rule
.mode_
!= OmitMode
) {
3028 auto entry(plist_new_dict());
3029 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3031 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
3032 if (rule
.mode_
== OptionalMode
)
3033 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3034 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3041 for (const auto &link
: local
.links
)
3042 for (const auto &rule
: version
.second
)
3043 if (rule(link
.first
)) {
3044 if (rule
.mode_
!= OmitMode
) {
3045 auto entry(plist_new_dict());
3046 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3047 if (rule
.mode_
== OptionalMode
)
3048 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3049 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3056 for (const auto &bundle
: bundles
) {
3057 auto entry(plist_new_dict());
3058 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3059 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3060 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3064 for (const auto &version
: versions
) {
3065 auto rules(plist_new_dict());
3066 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3068 std::multiset
<const Rule
*, RuleCode
> ordered
;
3069 for (const auto &rule
: version
.second
)
3070 ordered
.insert(&rule
);
3072 for (const auto &rule
: ordered
)
3073 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3074 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3076 auto entry(plist_new_dict());
3077 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3079 switch (rule
->mode_
) {
3083 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3086 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3089 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3092 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3096 if (rule
->weight_
>= 10000)
3097 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3098 else if (rule
->weight_
!= 1)
3099 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3103 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3104 HashProxy
proxy(local
.files
[signature
], save
);
3107 plist_to_xml(plist
, &xml
, &size
);
3108 _scope({ free(xml
); });
3109 put(proxy
, xml
, size
);
3113 bundle
.path
= folder
.Path(executable
);
3115 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3116 progress(root
+ executable
);
3117 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3119 slots
[1] = local
.files
.at(info
);
3120 slots
[3] = local
.files
.at(signature
);
3121 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3128 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
) {
3130 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3136 std::string
Hex(const uint8_t *data
, size_t size
) {
3138 hex
.reserve(size
* 2);
3139 for (size_t i(0); i
!= size
; ++i
) {
3140 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3141 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3146 static void usage(const char *argv0
) {
3147 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3148 fprintf(stderr
, "Usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3149 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3150 fprintf(stderr
, " [-Enum:file] [-e] [-H[sha1 | sha256]] [-h] [-Iname]\n");
3151 fprintf(stderr
, " [-Kkey.p12 [-Upassword]] [-M] [-P] [-Qrequirements.xml] [-q]\n");
3152 fprintf(stderr
, " [-r | -Sfile.xml | -s] [-Ttimestamp] [-u] [-arch arch_type] file ...\n");
3153 fprintf(stderr
, "Options:\n");
3154 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3155 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3156 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3157 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3158 fprintf(stderr
, " -h Print CDHash of file\n\n");
3159 fprintf(stderr
, "More information: 'man ldid'\n");
3162 void cleanupfunc(void) {
3163 for (const auto &temp
: cleanup
)
3164 remove(temp
.c_str());
3167 #ifndef LDID_NOTOOLS
3168 int main(int argc
, char *argv
[]) {
3169 std::atexit(cleanupfunc
);
3170 OpenSSL_add_all_algorithms();
3171 # if OPENSSL_VERSION_MAJOR >= 3
3172 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3173 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3181 little_
= endian
.byte
[0];
3205 bool platform(false);
3207 uint32_t flag_CPUType(_not(uint32_t));
3208 uint32_t flag_CPUSubtype(_not(uint32_t));
3210 const char *flag_I(NULL
);
3218 std::vector
<std::string
> files
;
3225 for (int argi(1); argi
!= argc
; ++argi
)
3226 if (argv
[argi
][0] != '-')
3227 files
.push_back(argv
[argi
]);
3228 else if (strcmp(argv
[argi
], "-arch") == 0) {
3229 bool foundarch
= false;
3233 fprintf(stderr
, "ldid: -arch must be followed by an architecture string\n");
3236 for (int i
= 0; archs
[i
].name
!= NULL
; i
++) {
3237 if (strcmp(archs
[i
].name
, argv
[argi
]) == 0) {
3238 flag_CPUType
= archs
[i
].cputype
;
3239 flag_CPUSubtype
= archs
[i
].cpusubtype
;
3247 fprintf(stderr
, "error: unknown architecture specification flag: -arch %s\n", argv
[argi
]);
3250 } else switch (argv
[argi
][1]) {
3252 if (flag_s
|| flag_S
) {
3253 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3259 case 'e': flag_e
= true; break;
3262 const char *string
= argv
[argi
] + 2;
3263 const char *colon
= strchr(string
, ':');
3264 if (colon
== NULL
) {
3268 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3270 unsigned number(strtoul(string
, &arge
, 0));
3271 if (arge
!= colon
|| (number
== 0 && errno
== EINVAL
)) {
3275 auto &slot(slots
[number
]);
3276 for (Algorithm
*algorithm
: GetAlgorithms())
3277 (*algorithm
)(slot
, file
.data(), file
.size());
3280 case 'q': flag_q
= true; break;
3283 const char *hash
= argv
[argi
] + 2;
3292 if (strcmp(hash
, "sha1") == 0)
3294 else if (strcmp(hash
, "sha256") == 0)
3297 fprintf(stderr
, "ldid: only sha1 and sha256 are supported at this time\n");
3302 case 'h': flag_h
= true; break;
3305 const char *xml
= argv
[argi
] + 2;
3306 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3309 case 'D': flag_D
= true; break;
3310 case 'd': flag_d
= true; break;
3312 case 'a': flag_a
= true; break;
3316 fprintf(stderr
, "ldid: -A can only be specified once\n");
3320 if (argv
[argi
][2] != '\0') {
3321 const char *cpu
= argv
[argi
] + 2;
3322 const char *colon
= strchr(cpu
, ':');
3323 if (colon
== NULL
) {
3328 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3329 if (arge
!= colon
|| (flag_CPUType
== 0 && errno
== EINVAL
)) {
3333 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3334 if (arge
!= argv
[argi
] + strlen(argv
[argi
]) || (flag_CPUSubtype
== 0 && errno
== EINVAL
)) {
3342 const char *name
= argv
[argi
] + 2;
3343 if (strcmp(name
, "host") == 0)
3344 flags
|= kSecCodeSignatureHost
;
3345 else if (strcmp(name
, "adhoc") == 0)
3346 flags
|= kSecCodeSignatureAdhoc
;
3347 else if (strcmp(name
, "hard") == 0)
3348 flags
|= kSecCodeSignatureForceHard
;
3349 else if (strcmp(name
, "kill") == 0)
3350 flags
|= kSecCodeSignatureForceKill
;
3351 else if (strcmp(name
, "expires") == 0)
3352 flags
|= kSecCodeSignatureForceExpiration
;
3353 else if (strcmp(name
, "restrict") == 0)
3354 flags
|= kSecCodeSignatureRestrict
;
3355 else if (strcmp(name
, "enforcement") == 0)
3356 flags
|= kSecCodeSignatureEnforcement
;
3357 else if (strcmp(name
, "library-validation") == 0)
3358 flags
|= kSecCodeSignatureLibraryValidation
;
3359 else if (strcmp(name
, "runtime") == 0)
3360 flags
|= kSecCodeSignatureRuntime
;
3362 fprintf(stderr
, "ldid: -C: Unsupported option\n");
3372 if (flag_r
|| flag_S
) {
3373 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3377 entitlements
.clear();
3382 if (flag_r
|| flag_s
) {
3383 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3387 if (argv
[argi
][2] != '\0') {
3388 const char *xml
= argv
[argi
] + 2;
3389 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3398 password
= argv
[argi
] + 2;
3402 if (argv
[argi
][2] != '\0')
3403 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3413 flag_I
= argv
[argi
] + 2;
3422 if (flag_I
!= NULL
&& !flag_S
) {
3423 fprintf(stderr
, "ldid: -I requires -S\n");
3430 size_t filei(0), filee(0);
3431 _foreach (file
, files
) try {
3432 std::string
path(file
);
3435 if (stat(path
.c_str(), &info
) == -1) {
3436 fprintf(stderr
, "ldid: %s: %s\n", path
.c_str(), strerror(errno
));
3440 if (S_ISDIR(info
.st_mode
)) {
3442 fprintf(stderr
, "ldid: Only -S can be used on directories\n");
3445 ldid::DiskFolder
folder(path
+ "/");
3446 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3447 } else if (flag_S
|| flag_r
) {
3448 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3450 std::filebuf output
;
3452 auto temp(Temporary(output
, split
));
3455 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3457 std::string
identifier(flag_I
?: split
.base
.c_str());
3458 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3464 Map
mapping(path
, flag_D
? true : false);
3465 FatHeader
fat_header(mapping
.data(), mapping
.size());
3467 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3468 struct linkedit_data_command
*signature(NULL
);
3469 struct encryption_info_command
*encryption(NULL
);
3472 if (mach_header
.GetCPUType() != flag_CPUType
)
3474 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3479 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3481 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3482 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3484 if (cmd
== LC_CODE_SIGNATURE
)
3485 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3486 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3487 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3488 else if (cmd
== LC_LOAD_DYLIB
) {
3489 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3490 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3492 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3495 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3496 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3502 if (flag_d
&& encryption
!= NULL
) {
3503 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3507 if (encryption
== NULL
) {
3508 fprintf(stderr
, "ldid: -D requires an encrypted binary\n");
3511 encryption
->cryptid
= mach_header
.Swap(0);
3514 if ((flag_e
|| flag_q
|| flag_h
) && signature
== NULL
) {
3515 fprintf(stderr
, "ldid: -e, -q, and -h requre a signed binary\n");
3520 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3522 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3523 uint8_t *blob
= top
+ data
;
3524 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3526 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3527 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3528 uint32_t begin
= Swap(super
->index
[index
].offset
);
3529 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3530 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3535 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3537 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3538 uint8_t *blob
= top
+ data
;
3539 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3541 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3542 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3543 uint32_t begin
= Swap(super
->index
[index
].offset
);
3544 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3545 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3550 auto algorithms(GetAlgorithms());
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
);
3559 CodeDirectory
*directory_
;
3561 Algorithm
&algorithm_
;
3565 std::map
<uint8_t, Candidate
> candidates
;
3567 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3568 auto type(Swap(super
->index
[index
].type
));
3569 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3570 uint32_t begin
= Swap(super
->index
[index
].offset
);
3571 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3572 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3573 auto type(directory
->hashType
);
3574 _assert(type
> 0 && type
<= algorithms
.size());
3575 auto &algorithm(*algorithms
[type
- 1]);
3576 uint8_t hash
[algorithm
.size_
];
3577 algorithm(hash
, blob
+ begin
, end
- begin
);
3578 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3582 _assert(!candidates
.empty());
3583 auto best(candidates
.end());
3586 const auto directory(best
->second
.directory_
);
3587 const auto flags(Swap(directory
->flags
));
3590 if (flags
& kSecCodeSignatureHost
)
3592 if (flags
& kSecCodeSignatureAdhoc
)
3594 if (flags
& kSecCodeSignatureForceHard
)
3596 if (flags
& kSecCodeSignatureForceKill
)
3598 if (flags
& kSecCodeSignatureForceExpiration
)
3599 names
+= ",expires";
3600 if (flags
& kSecCodeSignatureRestrict
)
3601 names
+= ",restrict";
3602 if (flags
& kSecCodeSignatureEnforcement
)
3603 names
+= ",enforcement";
3604 if (flags
& kSecCodeSignatureLibraryValidation
)
3605 names
+= ",library-validation";
3606 if (flags
& kSecCodeSignatureRuntime
)
3607 names
+= ",runtime";
3609 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3610 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3611 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3613 std::string choices
;
3614 for (const auto &candidate
: candidates
) {
3615 auto choice(candidate
.second
.algorithm_
.name());
3618 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3620 printf("Hash choices=%s\n", choices
.c_str() + 1);
3622 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3627 } catch (const char *) {
3632 # if OPENSSL_VERSION_MAJOR >= 3
3633 OSSL_PROVIDER_unload(legacy
);
3634 OSSL_PROVIDER_unload(deflt
);
3639 #endif // LDID_NOTOOLS