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/>.
44 #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>
56 #include <openssl/sha.h>
58 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
59 #define LDID_SHA1 SHA1
60 #define LDID_SHA1_CTX SHA_CTX
61 #define LDID_SHA1_Init SHA1_Init
62 #define LDID_SHA1_Update SHA1_Update
63 #define LDID_SHA1_Final SHA1_Final
65 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
66 #define LDID_SHA256 SHA256
67 #define LDID_SHA256_CTX SHA256_CTX
68 #define LDID_SHA256_Init SHA256_Init
69 #define LDID_SHA256_Update SHA256_Update
70 #define LDID_SHA256_Final SHA256_Final
72 #include <plist/plist.h>
78 #define _assert___(line) \
80 #define _assert__(line) \
84 #define $(value) value
88 #define _assert_(expr, format, ...) \
90 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
91 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
94 // XXX: this is not acceptable
95 #define _assert_(expr, format, ...) \
97 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
102 #define _assert(expr) \
103 _assert_(expr, "%s", $(#expr))
105 #define _syscall(expr, ...) [&] { for (;;) { \
107 if ((long) _value != -1) \
110 if (error == EINTR) \
112 /* XXX: EINTR is included in this list to fix g++ */ \
113 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
114 if (error == success) \
115 return (decltype(expr)) -success; \
116 fprintf(stderr, "ldid: %s: %s\n", __func__, strerror(error)); \
121 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
127 __attribute__((packed))
129 std::string password
;
130 std::vector
<std::string
> cleanup
;
132 template <typename Type_
>
134 typedef typename
Type_::const_iterator Result
;
137 #define _foreach(item, list) \
138 for (bool _stop(true); _stop; ) \
139 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
140 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
141 for (bool _suck(true); _suck; _suck = false) \
142 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
147 template <typename Function_
>
155 Scope(const Function_
&function
) :
165 template <typename Function_
>
166 Scope
<Function_
> _scope(const Function_
&function
) {
167 return Scope
<Function_
>(function
);
170 #define _scope__(counter, function) \
171 __attribute__((__unused__)) \
172 const _Scope &_scope ## counter(_scope([&]function))
173 #define _scope_(counter, function) \
174 _scope__(counter, function)
175 #define _scope(function) \
176 _scope_(__COUNTER__, function)
183 #define FAT_MAGIC 0xcafebabe
184 #define FAT_CIGAM 0xbebafeca
204 #define MH_MAGIC 0xfeedface
205 #define MH_CIGAM 0xcefaedfe
207 #define MH_MAGIC_64 0xfeedfacf
208 #define MH_CIGAM_64 0xcffaedfe
210 #define MH_DYLDLINK 0x4
212 #define MH_OBJECT 0x1
213 #define MH_EXECUTE 0x2
215 #define MH_DYLINKER 0x7
216 #define MH_BUNDLE 0x8
217 #define MH_DYLIB_STUB 0x9
219 struct load_command
{
224 #define LC_REQ_DYLD uint32_t(0x80000000)
226 #define LC_SEGMENT uint32_t(0x01)
227 #define LC_SYMTAB uint32_t(0x02)
228 #define LC_DYSYMTAB uint32_t(0x0b)
229 #define LC_LOAD_DYLIB uint32_t(0x0c)
230 #define LC_ID_DYLIB uint32_t(0x0d)
231 #define LC_SEGMENT_64 uint32_t(0x19)
232 #define LC_UUID uint32_t(0x1b)
233 #define LC_CODE_SIGNATURE uint32_t(0x1d)
234 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
235 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
236 #define LC_ENCRYPTION_INFO uint32_t(0x21)
237 #define LC_DYLD_INFO uint32_t(0x22)
238 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
239 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
254 uint32_t current_version
;
255 uint32_t compatibility_version
;
258 struct dylib_command
{
264 struct uuid_command
{
270 struct symtab_command
{
279 struct dyld_info_command
{
283 uint32_t rebase_size
;
286 uint32_t weak_bind_off
;
287 uint32_t weak_bind_size
;
288 uint32_t lazy_bind_off
;
289 uint32_t lazy_bind_size
;
291 uint32_t export_size
;
294 struct dysymtab_command
{
307 uint32_t extrefsymoff
;
308 uint32_t nextrefsyms
;
309 uint32_t indirectsymoff
;
310 uint32_t nindirectsyms
;
317 struct dylib_table_of_contents
{
318 uint32_t symbol_index
;
319 uint32_t module_index
;
322 struct dylib_module
{
323 uint32_t module_name
;
332 uint32_t iinit_iterm
;
333 uint32_t ninit_nterm
;
334 uint32_t objc_module_info_addr
;
335 uint32_t objc_module_info_size
;
338 struct dylib_reference
{
343 struct relocation_info
{
345 uint32_t r_symbolnum
:24;
364 struct segment_command
{
378 struct segment_command_64
{
421 struct linkedit_data_command
{
428 struct encryption_info_command
{
436 #define BIND_OPCODE_MASK 0xf0
437 #define BIND_IMMEDIATE_MASK 0x0f
438 #define BIND_OPCODE_DONE 0x00
439 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
440 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
441 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
442 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
443 #define BIND_OPCODE_SET_TYPE_IMM 0x50
444 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
445 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
446 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
447 #define BIND_OPCODE_DO_BIND 0x90
448 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
449 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
450 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
452 struct : ldid::Progress
{
453 virtual void operator()(const std::string
&value
) const {
456 virtual void operator()(double value
) const {
460 struct Progression
: ldid::Progress
{
461 const ldid::Progress
&progress_
;
464 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
470 virtual void operator()(const std::string
&value
) const {
471 return progress_(name_
+ " (" + value
+ ")");
474 virtual void operator()(double value
) const {
475 return progress_(value
);
479 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
480 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
485 static inline void put(std::streambuf
&stream
, uint8_t value
) {
486 _assert(stream
.sputc(value
) != EOF
);
489 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
490 _assert(read(stream
, data
, size
) == size
);
493 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
494 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
497 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
499 for (size_t total(0); total
!= size
;) {
500 auto writ(std::min(size
- total
, size_t(4096 * 4)));
501 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
503 progress(double(total
) / size
);
507 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
508 return put(stream
, data
.data(), data
.size());
511 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
514 if (auto writ
= read(stream
, data
, size
))
520 static inline void pad(std::streambuf
&stream
, size_t size
) {
522 memset(padding
, 0, size
);
523 put(stream
, padding
, size
);
526 template <typename Type_
>
527 Type_
Align(Type_ value
, size_t align
) {
534 static const uint8_t PageShift_(0x0c);
535 static const uint32_t PageSize_(1 << PageShift_
);
537 static inline unsigned bytes(uint64_t value
) {
538 return (64 - __builtin_clzll(value
) + 7) / 8;
541 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
543 do put(stream
, uint8_t(value
>> (length
-= 8)));
547 static void der(std::streambuf
&stream
, uint64_t value
) {
551 unsigned length(bytes(value
));
552 put(stream
, 0x80 | length
);
553 put(stream
, value
, length
);
557 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
561 put(data
, value
, length
);
565 static std::string
der(uint8_t tag
, const char *value
) {
566 return der(tag
, value
, strlen(value
)); }
567 static std::string
der(uint8_t tag
, const std::string
&value
) {
568 return der(tag
, value
.data(), value
.size()); }
570 template <typename Type_
>
571 static void der_(std::stringbuf
&data
, const Type_
&values
) {
573 for (const auto &value
: values
)
574 size
+= value
.size();
576 for (const auto &value
: values
)
580 static std::string
der(const std::vector
<std::string
> &values
) {
587 static std::string
der(const std::multiset
<std::string
> &values
) {
594 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
595 const auto key(der(0x0c, value
.first
));
598 der(data
, key
.size() + value
.second
.size());
600 put(data
, value
.second
);
604 static std::string
der(plist_t data
) {
605 switch (const auto type
= plist_get_node_type(data
)) {
606 case PLIST_BOOLEAN
: {
608 plist_get_bool_val(data
, &value
);
613 put(data
, value
!= 0 ? 1 : 0);
619 plist_get_uint_val(data
, &value
);
620 const auto length(bytes(value
));
625 put(data
, value
, length
);
630 fprintf(stderr
, "ldid: Invalid plist entry type\n");
635 fprintf(stderr
, "ldid: Invalid plist entry type\n");
642 plist_get_data_val(data
, &value
, &length
);
643 _scope({ free(value
); });
644 return der(0x04, value
, length
);
649 plist_get_string_val(data
, &value
);
650 _scope({ free(value
); });
651 return der(0x0c, value
);
655 std::vector
<std::string
> values
;
656 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
657 values
.push_back(der(plist_array_get_item(data
, i
)));
662 std::multiset
<std::string
> values
;
664 plist_dict_iter
iterator(NULL
);
665 plist_dict_new_iter(data
, &iterator
);
666 _scope({ free(iterator
); });
671 plist_dict_next_item(data
, iterator
, &key
, &value
);
674 _scope({ free(key
); });
675 values
.insert(der(std::make_pair(key
, der(value
))));
682 fprintf(stderr
, "ldid: Unsupported plist type %d", type
);
688 static inline uint16_t Swap_(uint16_t value
) {
690 ((value
>> 8) & 0x00ff) |
691 ((value
<< 8) & 0xff00);
694 static inline uint32_t Swap_(uint32_t value
) {
695 value
= ((value
>> 8) & 0x00ff00ff) |
696 ((value
<< 8) & 0xff00ff00);
697 value
= ((value
>> 16) & 0x0000ffff) |
698 ((value
<< 16) & 0xffff0000);
702 static inline uint64_t Swap_(uint64_t value
) {
703 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
704 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
705 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
709 static inline int16_t Swap_(int16_t value
) {
710 return Swap_(static_cast<uint16_t>(value
));
713 static inline int32_t Swap_(int32_t value
) {
714 return Swap_(static_cast<uint32_t>(value
));
717 static inline int64_t Swap_(int64_t value
) {
718 return Swap_(static_cast<uint64_t>(value
));
721 static bool little_(true);
723 static inline uint16_t Swap(uint16_t value
) {
724 return little_
? Swap_(value
) : value
;
727 static inline uint32_t Swap(uint32_t value
) {
728 return little_
? Swap_(value
) : value
;
731 static inline uint64_t Swap(uint64_t value
) {
732 return little_
? Swap_(value
) : value
;
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
));
757 Swapped(bool swapped
) :
762 template <typename Type_
>
763 Type_
Swap(Type_ value
) const {
764 return swapped_
? Swap_(value
) : value
;
776 Data(void *base
, size_t size
) :
782 void *GetBase() const {
786 size_t GetSize() const {
797 struct mach_header
*mach_header_
;
798 struct load_command
*load_command_
;
801 MachHeader(void *base
, size_t size
) :
804 mach_header_
= (mach_header
*) base
;
806 switch (Swap(mach_header_
->magic
)) {
808 swapped_
= !swapped_
;
814 swapped_
= !swapped_
;
820 fprintf(stderr
, "ldid: Unknown header magic\nAre you sure that is a Mach-O?\n");
824 void *post
= mach_header_
+ 1;
826 post
= (uint32_t *) post
+ 1;
827 load_command_
= (struct load_command
*) post
;
829 if (Swap(mach_header_
->filetype
) != MH_EXECUTE
&&
830 Swap(mach_header_
->filetype
) != MH_DYLIB
&&
831 Swap(mach_header_
->filetype
) != MH_DYLINKER
&&
832 Swap(mach_header_
->filetype
) != MH_BUNDLE
) {
833 fprintf(stderr
, "ldid: Unsupported Mach-O type\n");
838 bool Bits64() const {
842 struct mach_header
*operator ->() const {
846 operator struct mach_header
*() const {
850 uint32_t GetCPUType() const {
851 return Swap(mach_header_
->cputype
);
854 uint32_t GetCPUSubtype() const {
855 return Swap(mach_header_
->cpusubtype
) & 0xff;
858 struct load_command
*GetLoadCommand() const {
859 return load_command_
;
862 std::vector
<struct load_command
*> GetLoadCommands() const {
863 std::vector
<struct load_command
*> load_commands
;
865 struct load_command
*load_command
= load_command_
;
866 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
867 load_commands
.push_back(load_command
);
868 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
871 return load_commands
;
874 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
875 _foreach (load_command
, GetLoadCommands())
876 switch (Swap(load_command
->cmd
)) {
878 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
879 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
880 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
881 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
882 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
885 case LC_SEGMENT_64
: {
886 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
887 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
888 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
889 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
890 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
895 template <typename Target_
>
896 Target_
*GetOffset(uint32_t offset
) const {
897 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
901 class FatMachHeader
:
908 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
909 MachHeader(base
, size
),
914 fat_arch
*GetFatArch() const {
923 fat_header
*fat_header_
;
924 std::vector
<FatMachHeader
> mach_headers_
;
927 FatHeader(void *base
, size_t size
) :
930 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
932 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
933 swapped_
= !swapped_
;
935 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
937 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
939 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
940 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
942 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
943 uint32_t arch_offset
= Swap(fat_arch
->offset
);
944 uint32_t arch_size
= Swap(fat_arch
->size
);
945 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
951 std::vector
<FatMachHeader
> &GetMachHeaders() {
952 return mach_headers_
;
956 return fat_header_
!= NULL
;
959 struct fat_header
*operator ->() const {
963 operator struct fat_header
*() const {
968 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
969 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
970 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
971 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
972 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
973 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
974 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
975 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
976 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
978 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
979 #define CSSLOT_INFOSLOT uint32_t(0x00001)
980 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
981 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
982 #define CSSLOT_APPLICATION uint32_t(0x00004)
983 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
984 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
985 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
986 #define CSSLOT_ALTERNATE uint32_t(0x01000)
988 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
990 #define CS_HASHTYPE_SHA160_160 1
991 #define CS_HASHTYPE_SHA256_256 2
992 #define CS_HASHTYPE_SHA256_160 3
993 #define CS_HASHTYPE_SHA386_386 4
996 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
997 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
998 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
999 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1000 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1001 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1002 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1004 enum SecCodeExecSegFlags
{
1005 kSecCodeExecSegMainBinary
= 0x001,
1006 kSecCodeExecSegAllowUnsigned
= 0x010,
1007 kSecCodeExecSegDebugger
= 0x020,
1008 kSecCodeExecSegJit
= 0x040,
1009 kSecCodeExecSegSkipLibraryVal
= 0x080,
1010 kSecCodeExecSegCanLoadCdHash
= 0x100,
1011 kSecCodeExecSegCanExecCdHash
= 0x100,
1028 struct BlobIndex index
[];
1031 struct CodeDirectory
{
1034 uint32_t hashOffset
;
1035 uint32_t identOffset
;
1036 uint32_t nSpecialSlots
;
1037 uint32_t nCodeSlots
;
1044 uint32_t scatterOffset
;
1045 uint32_t teamIDOffset
;
1047 uint64_t codeLimit64
;
1048 uint64_t execSegBase
;
1049 uint64_t execSegLimit
;
1050 uint64_t execSegFlags
;
1051 #if 0 // version = 0x20500
1053 uint32_t preEncryptOffset
;
1055 #if 0 // version = 0x20600
1056 uint8_t linkageHashType
;
1057 uint8_t linkageTruncated
;
1059 uint32_t linkageOffset
;
1060 uint32_t linkageSize
;
1064 enum CodeSignatureFlags
{
1065 kSecCodeSignatureHost
= 0x0001,
1066 kSecCodeSignatureAdhoc
= 0x0002,
1067 kSecCodeSignatureForceHard
= 0x0100,
1068 kSecCodeSignatureForceKill
= 0x0200,
1069 kSecCodeSignatureForceExpiration
= 0x0400,
1070 kSecCodeSignatureRestrict
= 0x0800,
1071 kSecCodeSignatureEnforcement
= 0x1000,
1072 kSecCodeSignatureLibraryValidation
= 0x2000,
1073 kSecCodeSignatureRuntime
= 0x10000,
1076 enum Kind
: uint32_t {
1077 exprForm
= 1, // prefix expr form
1080 enum ExprOp
: uint32_t {
1081 opFalse
, // unconditionally false
1082 opTrue
, // unconditionally true
1083 opIdent
, // match canonical code [string]
1084 opAppleAnchor
, // signed by Apple as Apple's product
1085 opAnchorHash
, // match anchor [cert hash]
1086 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1087 opAnd
, // binary prefix expr AND expr [expr; expr]
1088 opOr
, // binary prefix expr OR expr [expr; expr]
1089 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1090 opNot
, // logical inverse [expr]
1091 opInfoKeyField
, // Info.plist key field [string; match suffix]
1092 opCertField
, // Certificate field [cert index; field name; match suffix]
1093 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1094 opTrustedCerts
, // require trust settings to approve the cert chain
1095 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1096 opAppleGenericAnchor
, // signed by Apple in any capacity
1097 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1098 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1099 opNamedAnchor
, // named anchor type
1100 opNamedCode
, // named subroutine
1101 opPlatform
, // platform constraint [integer]
1102 exprOpCount
// (total opcode count in use)
1105 enum MatchOperation
{
1106 matchExists
, // anything but explicit "false" - no value stored
1107 matchEqual
, // equal (CFEqual)
1108 matchContains
, // partial match (substring)
1109 matchBeginsWith
, // partial match (initial substring)
1110 matchEndsWith
, // partial match (terminal substring)
1111 matchLessThan
, // less than (string with numeric comparison)
1112 matchGreaterThan
, // greater than (string with numeric comparison)
1113 matchLessEqual
, // less or equal (string with numeric comparison)
1114 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1117 #define OID_ISO_MEMBER 42
1118 #define OID_US OID_ISO_MEMBER, 134, 72
1119 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1120 #define APPLE_ADS_OID APPLE_OID, 0x64
1121 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1128 Algorithm(size_t size
, uint8_t type
) :
1134 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1136 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1137 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1138 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1140 virtual const char *name() = 0;
1143 struct AlgorithmSHA1
:
1147 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1151 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1155 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1156 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1159 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1160 return operator()(hash
.sha1_
, data
, size
);
1163 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1164 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1165 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1168 virtual const char *name() {
1173 struct AlgorithmSHA256
:
1177 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1181 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1182 return hash
.sha256_
;
1185 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1186 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1189 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1190 return operator()(hash
.sha256_
, data
, size
);
1193 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1194 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1195 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1198 virtual const char *name() {
1203 static bool do_sha1(true);
1204 static bool do_sha256(true);
1206 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1207 static AlgorithmSHA1 sha1
;
1208 static AlgorithmSHA256 sha256
;
1210 static std::vector
<Algorithm
*> algorithms
;
1211 if (algorithms
.empty()) {
1213 algorithms
.push_back(&sha1
);
1215 algorithms
.push_back(&sha256
);
1222 std::string entitlements_
;
1223 std::string derformat_
;
1226 struct CodesignAllocation
{
1227 FatMachHeader mach_header_
;
1236 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
) :
1237 mach_header_(mach_header
),
1249 #ifndef LDID_NOTOOLS
1262 _syscall(close(file_
));
1265 void open(const char *path
, int flags
) {
1266 file_
= ::open(path
, flags
);
1268 fprintf(stderr
, "ldid: %s: %s\n", path
, strerror(errno
));
1291 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1294 open(path
, oflag
, pflag
, mflag
);
1297 Map(const std::string
&path
, bool edit
) :
1307 bool empty() const {
1308 return data_
== NULL
;
1311 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1314 file_
.open(path
.c_str(), oflag
);
1315 int file(file_
.file());
1318 _syscall(fstat(file
, &stat
));
1319 size_
= stat
.st_size
;
1321 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1324 void open(const std::string
&path
, bool edit
) {
1326 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1328 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1334 _syscall(munmap(data_
, size_
));
1339 void *data() const {
1343 size_t size() const {
1347 operator std::string() const {
1348 return std::string(static_cast<char *>(data_
), size_
);
1351 #endif // LDID_NOTOOLS
1355 static plist_t
plist(const std::string
&data
);
1357 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1358 _foreach (load_command
, mach_header
.GetLoadCommands())
1359 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1360 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1361 auto offset(mach_header
.Swap(signature
->dataoff
));
1362 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1363 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1365 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1366 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1367 auto begin(Swap(super
->index
[index
].offset
));
1368 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1369 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1370 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1375 std::string
Analyze(const void *data
, size_t size
) {
1376 std::string entitlements
;
1378 FatHeader
fat_header(const_cast<void *>(data
), size
);
1379 _foreach (mach_header
, fat_header
.GetMachHeaders())
1380 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1381 if (entitlements
.empty())
1382 entitlements
.assign(data
, size
);
1384 if (entitlements
.compare(0, entitlements
.size(), data
, size
) != 0) {
1385 fprintf(stderr
, "ldid: Entitlements do not match\n");
1390 return entitlements
;
1393 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
) {
1394 FatHeader
source(const_cast<void *>(idata
), isize
);
1398 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1400 std::vector
<CodesignAllocation
> allocations
;
1401 _foreach (mach_header
, source
.GetMachHeaders()) {
1402 struct linkedit_data_command
*signature(NULL
);
1403 struct symtab_command
*symtab(NULL
);
1405 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1406 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1407 if (cmd
== LC_CODE_SIGNATURE
)
1408 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1409 else if (cmd
== LC_SYMTAB
)
1410 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1414 if (signature
== NULL
)
1415 size
= mach_header
.GetSize();
1417 size
= mach_header
.Swap(signature
->dataoff
);
1418 _assert(size
<= mach_header
.GetSize());
1421 if (symtab
!= NULL
) {
1422 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1423 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1424 _assert(end
<= size
);
1425 _assert(end
>= size
- 0x10);
1431 size_t alloc(allocate(mach_header
, baton
, size
));
1433 auto *fat_arch(mach_header
.GetFatArch());
1436 if (fat_arch
!= NULL
)
1437 align
= source
.Swap(fat_arch
->align
);
1438 else switch (mach_header
.GetCPUType()) {
1439 case CPU_TYPE_POWERPC
:
1440 case CPU_TYPE_POWERPC64
:
1442 case CPU_TYPE_X86_64
:
1446 case CPU_TYPE_ARM64
:
1447 case CPU_TYPE_ARM64_32
:
1455 const char *arch(NULL
);
1456 switch (mach_header
.GetCPUType()) {
1457 case CPU_TYPE_POWERPC
:
1460 case CPU_TYPE_POWERPC64
:
1466 case CPU_TYPE_X86_64
:
1472 case CPU_TYPE_ARM64
:
1475 case CPU_TYPE_ARM64_32
:
1480 offset
= Align(offset
, 1 << align
);
1482 uint32_t limit(size
);
1484 limit
= Align(limit
, 0x10);
1486 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1487 offset
+= size
+ alloc
;
1488 offset
= Align(offset
, 0x10);
1493 if (source
.IsFat()) {
1494 fat_header fat_header
;
1495 fat_header
.magic
= Swap(FAT_MAGIC
);
1496 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1497 put(output
, &fat_header
, sizeof(fat_header
));
1498 position
+= sizeof(fat_header
);
1500 // XXX: support fat_arch_64 (not in my toolchain)
1501 // probably use C++14 generic lambda (not in my toolchain)
1504 _foreach (allocation
, allocations
) {
1505 const auto offset(allocation
.offset_
);
1506 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1507 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1511 }(), "FAT slice >=4GiB not currently supported");
1513 _foreach (allocation
, allocations
) {
1514 auto &mach_header(allocation
.mach_header_
);
1517 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1518 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1519 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1520 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1521 fat_arch
.align
= Swap(allocation
.align_
);
1522 put(output
, &fat_arch
, sizeof(fat_arch
));
1523 position
+= sizeof(fat_arch
);
1527 _foreach (allocation
, allocations
) {
1528 progress(allocation
.arch_
);
1529 auto &mach_header(allocation
.mach_header_
);
1531 pad(output
, allocation
.offset_
- position
);
1532 position
= allocation
.offset_
;
1537 std::vector
<std::string
> commands
;
1539 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1540 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1542 switch (mach_header
.Swap(load_command
->cmd
)) {
1543 case LC_CODE_SIGNATURE
:
1547 // XXX: this is getting ridiculous: provide a better abstraction
1550 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1552 if ((segment_command
->initprot
& 04) != 0) {
1553 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1554 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1561 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1562 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1563 segment_command
->filesize
= size
;
1564 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1568 case LC_SEGMENT_64
: {
1569 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1571 if ((segment_command
->initprot
& 04) != 0) {
1572 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1573 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1580 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1581 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1582 segment_command
->filesize
= size
;
1583 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1588 commands
.push_back(copy
);
1591 if (allocation
.alloc_
!= 0) {
1592 linkedit_data_command signature
;
1593 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1594 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1595 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1596 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1597 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1600 size_t begin(position
);
1603 _foreach(command
, commands
)
1604 after
+= command
.size();
1606 std::stringbuf altern
;
1608 struct mach_header
header(*mach_header
);
1609 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1610 header
.sizeofcmds
= mach_header
.Swap(after
);
1611 put(output
, &header
, sizeof(header
));
1612 put(altern
, &header
, sizeof(header
));
1613 position
+= sizeof(header
);
1615 if (mach_header
.Bits64()) {
1616 auto pad(mach_header
.Swap(uint32_t(0)));
1617 put(output
, &pad
, sizeof(pad
));
1618 put(altern
, &pad
, sizeof(pad
));
1619 position
+= sizeof(pad
);
1622 _foreach(command
, commands
) {
1623 put(output
, command
.data(), command
.size());
1624 put(altern
, command
.data(), command
.size());
1625 position
+= command
.size();
1628 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1629 if (before
> after
) {
1630 pad(output
, before
- after
);
1631 pad(altern
, before
- after
);
1632 position
+= before
- after
;
1635 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1637 std::string
overlap(altern
.str());
1638 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1640 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1641 position
= begin
+ allocation
.size_
;
1643 pad(output
, allocation
.limit_
- allocation
.size_
);
1644 position
+= allocation
.limit_
- allocation
.size_
;
1646 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1647 if (allocation
.alloc_
> saved
)
1648 pad(output
, allocation
.alloc_
- saved
);
1650 _assert(allocation
.alloc_
== saved
);
1651 position
+= allocation
.alloc_
;
1657 typedef std::map
<uint32_t, std::string
> Blobs
;
1659 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1660 auto value(buffer
.str());
1661 std::swap(blobs
[slot
], value
);
1664 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1665 auto value(buffer
.str());
1667 blob
.magic
= Swap(magic
);
1668 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1669 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1670 auto &save(blobs
[slot
]);
1671 std::swap(save
, value
);
1675 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1677 _foreach (blob
, blobs
)
1678 total
+= blob
.second
.size();
1680 struct SuperBlob super
;
1681 super
.blob
.magic
= Swap(magic
);
1682 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1683 super
.count
= Swap(uint32_t(blobs
.size()));
1684 put(output
, &super
, sizeof(super
));
1686 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1688 _foreach (blob
, blobs
) {
1690 index
.type
= Swap(blob
.first
);
1691 index
.offset
= Swap(uint32_t(offset
));
1692 put(output
, &index
, sizeof(index
));
1693 offset
+= blob
.second
.size();
1696 _foreach (blob
, blobs
)
1697 put(output
, blob
.second
.data(), blob
.second
.size());
1710 _assert(bio_
!= NULL
);
1714 bio_(BIO_new(BIO_s_mem()))
1718 Buffer(const char *data
, size_t size
) :
1719 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1723 Buffer(const std::string
&data
) :
1724 Buffer(data
.data(), data
.size())
1728 Buffer(PKCS7
*pkcs
) :
1731 if (i2d_PKCS7_bio(bio_
, pkcs
) == 0){
1732 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1741 operator BIO
*() const {
1745 explicit operator std::string() const {
1747 auto size(BIO_get_mem_data(bio_
, &data
));
1748 return std::string(data
, size
);
1757 STACK_OF(X509
) *ca_
;
1761 value_(d2i_PKCS12_bio(bio
, NULL
)),
1764 if (value_
== NULL
){
1765 fprintf(stderr
, "ldid: An error occured while getting the PKCS12 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1769 if (!PKCS12_verify_mac(value_
, "", 0) && password
.empty()) {
1771 UI_UTIL_read_pw_string(passbuf
, 2048, "Enter password: ", 0);
1775 if (PKCS12_parse(value_
, password
.c_str(), &key_
, &cert_
, &ca_
) <= 0){
1776 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1779 if (key_
== NULL
|| cert_
== NULL
){
1780 fprintf(stderr
, "ldid: An error occured while parsing: %s\nYour p12 cert might not be valid\n", ERR_error_string(ERR_get_error(), NULL
));
1785 ca_
= sk_X509_new_null();
1787 fprintf(stderr
, "ldid: An error occured while parsing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1792 Stuff(const std::string
&data
) :
1798 sk_X509_pop_free(ca_
, X509_free
);
1800 EVP_PKEY_free(key_
);
1801 PKCS12_free(value_
);
1804 operator PKCS12
*() const {
1808 operator EVP_PKEY
*() const {
1812 operator X509
*() const {
1816 operator STACK_OF(X509
) *() const {
1822 struct SEQUENCE_hash_sha1
{
1823 uint8_t SEQUENCE
[2] = {0x30, 0x1d}; // size
1824 uint8_t OBJECT_IDENTIFIER
[7] = {0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A}; // OBJECT IDENTIFIER 1.3.14.3.2.26 sha1 (OIW)
1825 uint8_t hash_size
[2] = {0x04, 0x14};
1829 struct SEQUENCE_hash_sha256
{
1830 uint8_t SEQUENCE
[2] = {0x30, 0x2d}; // size
1831 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)
1832 uint8_t hash_size
[2] = {0x04, 0x20}; // hash size
1841 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
, const std::vector
<char>& alternateCDSHA1
, const std::vector
<char>& alternateCDSHA256
) {
1842 value_
= PKCS7_new();
1843 if (value_
== NULL
){
1844 fprintf(stderr
, "ldid: An error occured while getting creating PKCS7 file: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1848 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1849 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1851 STACK_OF(X509
) *certs(stuff
);
1852 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1853 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1855 auto info(PKCS7_sign_add_signer(value_
, stuff
, stuff
, NULL
, PKCS7_NOSMIMECAP
));
1857 fprintf(stderr
, "ldid: An error occured while signing: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1860 X509_ATTRIBUTE
*attribute
= X509_ATTRIBUTE_new();
1861 ASN1_OBJECT
*obj2
= OBJ_txt2obj("1.2.840.113635.100.9.2", 1);
1862 X509_ATTRIBUTE_set1_object(attribute
, obj2
);
1864 SEQUENCE_hash_sha1 seq1
;
1865 memcpy((void *)seq1
.hash
,(void *)alternateCDSHA1
.data() ,alternateCDSHA1
.size());
1866 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq1
, sizeof(seq1
));
1868 SEQUENCE_hash_sha256 seq256
;
1869 memcpy((void *)seq256
.hash
,(void *)alternateCDSHA256
.data() ,alternateCDSHA256
.size());
1870 X509_ATTRIBUTE_set1_data(attribute
, V_ASN1_SEQUENCE
,&seq256
, sizeof(seq256
));
1872 STACK_OF(X509_ATTRIBUTE
) *sk
= PKCS7_get_signed_attributes(info
);
1873 if (!sk_X509_ATTRIBUTE_push(sk
, attribute
)) {
1874 fprintf(stderr
, "ldid: sk_X509_ATTRIBUTE_push failed: %s\n", ERR_error_string(ERR_get_error(), NULL
));
1878 PKCS7_set_detached(value_
, 1);
1880 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1881 _assert(string
!= NULL
);
1883 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1885 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1886 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1888 ASN1_OCTET_STRING_free(string
);
1892 _assert(PKCS7_final(value_
, data
, PKCS7_BINARY
));
1899 operator PKCS7
*() const {
1905 public std::streambuf
1908 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1912 virtual int_type
overflow(int_type next
) {
1918 public std::streambuf
1923 LDID_SHA1_CTX sha1_
;
1924 LDID_SHA256_CTX sha256_
;
1927 HashBuffer(ldid::Hash
&hash
) :
1930 LDID_SHA1_Init(&sha1_
);
1931 LDID_SHA256_Init(&sha256_
);
1935 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1936 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1939 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1940 LDID_SHA1_Update(&sha1_
, data
, size
);
1941 LDID_SHA256_Update(&sha256_
, data
, size
);
1945 virtual int_type
overflow(int_type next
) {
1946 if (next
== traits_type::eof())
1958 std::streambuf
&buffer_
;
1961 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1967 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1968 _assert(HashBuffer::xsputn(data
, size
) == size
);
1969 return buffer_
.sputn(data
, size
);
1973 #ifndef LDID_NOTOOLS
1974 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1975 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1983 Split(const std::string
&path
) {
1984 size_t slash(path
.rfind('/'));
1985 if (slash
== std::string::npos
)
1988 dir
= path
.substr(0, slash
+ 1);
1989 base
= path
.substr(slash
+ 1);
1994 static void mkdir_p(const std::string
&path
) {
1998 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
2001 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2004 auto slash(path
.rfind('/', path
.size() - 1));
2005 if (slash
== std::string::npos
)
2007 mkdir_p(path
.substr(0, slash
));
2010 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2011 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2013 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2014 cleanup
.push_back(temp
);
2018 static void Commit(const std::string
&path
, const std::string
&temp
) {
2020 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2022 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2024 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2027 _syscall(rename(temp
.c_str(), path
.c_str()));
2028 cleanup
.erase(std::remove(cleanup
.begin(), cleanup
.end(), temp
), cleanup
.end());
2030 #endif // LDID_NOTOOLS
2034 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2035 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2037 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2040 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2042 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2045 auto entry(X509_NAME_get_entry(name
, index
));
2046 if (entry
== NULL
) {
2047 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2050 auto asn(X509_NAME_ENTRY_get_data(entry
));
2052 fprintf(stderr
, "ldid: An error occursed while parsing the certificate: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2055 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2058 static void req(std::streambuf
&buffer
, uint32_t value
) {
2059 value
= Swap(value
);
2060 put(buffer
, &value
, sizeof(value
));
2063 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2064 req(buffer
, value
.size());
2065 put(buffer
, value
.data(), value
.size());
2066 static uint8_t zeros
[] = {0,0,0,0};
2067 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2070 template <size_t Size_
>
2071 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2073 put(buffer
, data
, Size_
);
2074 static uint8_t zeros
[] = {0,0,0,0};
2075 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2078 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
) {
2087 auto name(X509_get_subject_name(stuff
));
2089 fprintf(stderr
, "ldid: Your certificate might not be valid: %s\n", ERR_error_string(ERR_get_error(), NULL
));
2092 get(team
, name
, NID_organizationalUnitName
);
2093 get(common
, name
, NID_commonName
);
2097 std::stringbuf backing
;
2099 if (!requirements
.empty()) {
2100 put(backing
, requirements
.data(), requirements
.size());
2104 std::stringbuf requirement
;
2105 req(requirement
, exprForm
);
2106 req(requirement
, opAnd
);
2107 req(requirement
, opIdent
);
2108 req(requirement
, identifier
);
2109 req(requirement
, opAnd
);
2110 req(requirement
, opAppleGenericAnchor
);
2111 req(requirement
, opAnd
);
2112 req(requirement
, opCertField
);
2113 req(requirement
, 0);
2114 req(requirement
, "subject.CN");
2115 req(requirement
, matchEqual
);
2116 req(requirement
, common
);
2117 req(requirement
, opCertGeneric
);
2118 req(requirement
, 1);
2119 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2120 req(requirement
, matchExists
);
2121 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2123 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2127 // XXX: this is just a "sufficiently large number"
2128 size_t certificate(0x3000);
2130 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2131 size_t alloc(sizeof(struct SuperBlob
));
2133 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2135 uint32_t special(0);
2137 _foreach (slot
, slots
)
2138 special
= std::max(special
, slot
.first
);
2140 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2141 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2142 special
= std::max(special
, CSSLOT_INFOSLOT
);
2145 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2146 alloc
+= sizeof(struct BlobIndex
);
2147 alloc
+= backing
.str().size();
2150 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2151 baton
.entitlements_
.assign(data
, size
);
2154 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2155 auto combined(plist(baton
.entitlements_
));
2156 _scope({ plist_free(combined
); });
2157 if (plist_get_node_type(combined
) != PLIST_DICT
) {
2158 fprintf(stderr
, "ldid: Existing entitlements are in wrong format\n");
2162 auto merging(plist(entitlements
));
2163 _scope({ plist_free(merging
); });
2164 if (plist_get_node_type(merging
) != PLIST_DICT
) {
2165 fprintf(stderr
, "ldid: Entitlements need a root key of dict\n");
2169 plist_dict_iter
iterator(NULL
);
2170 plist_dict_new_iter(merging
, &iterator
);
2171 _scope({ free(iterator
); });
2175 plist_t
value(NULL
);
2176 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2179 _scope({ free(key
); });
2180 plist_dict_set_item(combined
, key
, plist_copy(value
));
2183 baton
.derformat_
= der(combined
);
2187 plist_to_xml(combined
, &xml
, &size
);
2188 _scope({ free(xml
); });
2190 baton
.entitlements_
.assign(xml
, size
);
2193 if (!baton
.entitlements_
.empty()) {
2194 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2195 alloc
+= sizeof(struct BlobIndex
);
2196 alloc
+= sizeof(struct Blob
);
2197 alloc
+= baton
.entitlements_
.size();
2200 if (!baton
.derformat_
.empty()) {
2201 special
= std::max(special
, CSSLOT_DERFORMAT
);
2202 alloc
+= sizeof(struct BlobIndex
);
2203 alloc
+= sizeof(struct Blob
);
2204 alloc
+= baton
.derformat_
.size();
2207 size_t directory(0);
2209 directory
+= sizeof(struct BlobIndex
);
2210 directory
+= sizeof(struct Blob
);
2211 directory
+= sizeof(struct CodeDirectory
);
2212 directory
+= identifier
.size() + 1;
2215 directory
+= team
.size() + 1;
2217 for (Algorithm
*algorithm
: GetAlgorithms())
2218 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2221 alloc
+= sizeof(struct BlobIndex
);
2222 alloc
+= sizeof(struct Blob
);
2223 alloc
+= certificate
;
2227 }), 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 {
2231 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2235 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2236 execs
|= kSecCodeExecSegMainBinary
;
2238 if (!baton
.entitlements_
.empty()) {
2239 std::stringbuf data
;
2240 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2241 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2243 auto entitlements(plist(baton
.entitlements_
));
2244 _scope({ plist_free(entitlements
); });
2245 if (plist_get_node_type(entitlements
) != PLIST_DICT
) {
2246 fprintf(stderr
, "ldid: Entitlements should be a plist dicionary\n");
2250 const auto entitled([&](const char *key
) {
2251 auto item(plist_dict_get_item(entitlements
, key
));
2252 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2255 plist_get_bool_val(item
, &value
);
2259 if (entitled("get-task-allow"))
2260 execs
|= kSecCodeExecSegAllowUnsigned
;
2261 if (entitled("run-unsigned-code"))
2262 execs
|= kSecCodeExecSegAllowUnsigned
;
2263 if (entitled("com.apple.private.cs.debugger"))
2264 execs
|= kSecCodeExecSegDebugger
;
2265 if (entitled("dynamic-codesigning"))
2266 execs
|= kSecCodeExecSegJit
;
2267 if (entitled("com.apple.private.skip-library-validation"))
2268 execs
|= kSecCodeExecSegSkipLibraryVal
;
2269 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2270 execs
|= kSecCodeExecSegCanLoadCdHash
;
2271 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2272 execs
|= kSecCodeExecSegCanExecCdHash
;
2275 if (!baton
.derformat_
.empty()) {
2276 std::stringbuf data
;
2277 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2278 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2283 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2284 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2285 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2286 for (Algorithm
*algorithm
: GetAlgorithms())
2287 (*algorithm
)(slot
, data
, size
);
2292 for (Algorithm
*pointer
: GetAlgorithms()) {
2293 Algorithm
&algorithm(*pointer
);
2295 std::stringbuf data
;
2297 uint32_t special(0);
2298 _foreach (blob
, blobs
)
2299 special
= std::max(special
, blob
.first
);
2300 _foreach (slot
, posts
)
2301 special
= std::max(special
, slot
.first
);
2302 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2304 CodeDirectory directory
;
2305 directory
.version
= Swap(uint32_t(0x00020400));
2306 directory
.flags
= Swap(uint32_t(flags
));
2307 directory
.nSpecialSlots
= Swap(special
);
2308 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2309 directory
.nCodeSlots
= Swap(normal
);
2310 directory
.hashSize
= algorithm
.size_
;
2311 directory
.hashType
= algorithm
.type_
;
2312 directory
.platform
= platform
? 0x01 : 0x00;
2313 directory
.pageSize
= PageShift_
;
2314 directory
.spare2
= Swap(uint32_t(0));
2315 directory
.scatterOffset
= Swap(uint32_t(0));
2316 directory
.spare3
= Swap(uint32_t(0));
2317 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2318 directory
.execSegBase
= Swap(uint64_t(left
));
2319 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2320 directory
.execSegFlags
= Swap(execs
);
2322 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2324 directory
.identOffset
= Swap(uint32_t(offset
));
2325 offset
+= identifier
.size() + 1;
2328 directory
.teamIDOffset
= Swap(uint32_t(0));
2330 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2331 offset
+= team
.size() + 1;
2334 offset
+= special
* algorithm
.size_
;
2335 directory
.hashOffset
= Swap(uint32_t(offset
));
2336 offset
+= normal
* algorithm
.size_
;
2338 put(data
, &directory
, sizeof(directory
));
2340 put(data
, identifier
.c_str(), identifier
.size() + 1);
2342 put(data
, team
.c_str(), team
.size() + 1);
2344 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2345 auto *hashes(&storage
[special
* algorithm
.size_
]);
2347 memset(storage
.data(), 0, special
* algorithm
.size_
);
2349 _foreach (blob
, blobs
) {
2350 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2351 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2354 _foreach (slot
, posts
)
2355 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2359 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2360 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2361 progress(double(i
) / normal
);
2364 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2367 put(data
, storage
.data(), storage
.size());
2369 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2370 algorithm(hash
, save
.data(), save
.size());
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
);
2382 std::vector
<char> alternateCDSHA256
;
2383 std::vector
<char> alternateCDSHA1
;
2386 for (Algorithm
*pointer
: GetAlgorithms()) {
2387 Algorithm
&algorithm(*pointer
);
2390 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2393 std::vector
<char> hash
;
2394 algorithm(hash
, blob
.data(), blob
.size());
2395 if (algorithm
.type_
== CS_HASHTYPE_SHA256_256
)
2396 alternateCDSHA256
= hash
;
2397 else if (algorithm
.type_
== CS_HASHTYPE_SHA160_160
)
2398 alternateCDSHA1
= hash
;
2401 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2406 plist_to_xml(plist
, &xml
, &size
);
2407 _scope({ free(xml
); });
2409 std::stringbuf data
;
2410 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2415 Signature
signature(stuff
, sign
, std::string(xml
, size
), alternateCDSHA1
, alternateCDSHA256
);
2416 Buffer
result(signature
);
2417 std::string
value(result
);
2418 put(data
, value
.data(), value
.size());
2420 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2421 _assert(save
.size() <= certificate
);
2424 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2430 #ifndef LDID_NOTOOLS
2431 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2432 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2434 }), 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 {
2439 std::string
DiskFolder::Path(const std::string
&path
) const {
2440 return path_
+ path
;
2443 DiskFolder::DiskFolder(const std::string
&path
) :
2446 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2449 DiskFolder::~DiskFolder() {
2450 if (!std::uncaught_exception())
2451 for (const auto &commit
: commit_
)
2452 Commit(commit
.first
, commit
.second
);
2456 std::string
readlink(const std::string
&path
) {
2457 for (size_t size(1024); ; size
*= 2) {
2461 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2462 if (size_t(writ
) >= size
)
2471 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 {
2472 std::string
path(Path(root
) + base
);
2474 DIR *dir(opendir(path
.c_str()));
2475 _assert(dir
!= NULL
);
2476 _scope({ _syscall(closedir(dir
)); });
2478 while (auto child
= readdir(dir
)) {
2479 std::string
name(child
->d_name
);
2480 if (name
== "." || name
== "..")
2482 if (Starts(name
, ".ldid."))
2489 _syscall(stat((path
+ name
).c_str(), &info
));
2490 if (S_ISDIR(info
.st_mode
))
2492 else if (S_ISREG(info
.st_mode
))
2495 _assert_(false, "st_mode=%x", info
.st_mode
);
2497 switch (child
->d_type
) {
2505 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2508 _assert_(false, "d_type=%u", child
->d_type
);
2513 Find(root
, base
+ name
+ "/", code
, link
);
2519 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2525 auto from(Path(path
));
2526 commit_
[from
] = Temporary(save
, from
);
2531 bool DiskFolder::Look(const std::string
&path
) const {
2532 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2535 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2537 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2538 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2540 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2541 data
.pubseekpos(0, std::ios::in
);
2542 code(data
, length
, NULL
);
2545 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 {
2546 Find(path
, "", code
, link
);
2548 #endif // LDID_NOTOOLS
2550 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2554 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2557 std::string
SubFolder::Path(const std::string
&path
) const {
2558 return path_
+ path
;
2561 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2562 return parent_
.Save(Path(path
), edit
, flag
, code
);
2565 bool SubFolder::Look(const std::string
&path
) const {
2566 return parent_
.Look(Path(path
));
2569 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2570 return parent_
.Open(Path(path
), code
);
2573 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 {
2574 return parent_
.Find(Path(path
), code
, link
);
2577 std::string
UnionFolder::Map(const std::string
&path
) const {
2578 auto remap(remaps_
.find(path
));
2579 if (remap
== remaps_
.end())
2581 return remap
->second
;
2584 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 {
2585 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2586 code(file
.substr(path
.size()));
2589 UnionFolder::UnionFolder(Folder
&parent
) :
2594 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2595 return parent_
.Save(Map(path
), edit
, flag
, code
);
2598 bool UnionFolder::Look(const std::string
&path
) const {
2599 auto file(resets_
.find(path
));
2600 if (file
!= resets_
.end())
2602 return parent_
.Look(Map(path
));
2605 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2606 auto file(resets_
.find(path
));
2607 if (file
== resets_
.end())
2608 return parent_
.Open(Map(path
), code
);
2609 auto &entry(file
->second
);
2611 auto &data(*entry
.data_
);
2612 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2613 data
.pubseekpos(0, std::ios::in
);
2614 code(data
, length
, entry
.flag_
);
2617 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 {
2618 for (auto &reset
: resets_
)
2619 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2620 auto &entry(reset
.second
);
2621 auto &data(*entry
.data_
);
2622 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2623 data
.pubseekpos(0, std::ios::in
);
2624 code(data
, length
, entry
.flag_
);
2627 for (auto &remap
: remaps_
)
2628 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2629 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2630 code(data
, length
, flag
);
2634 parent_
.Find(path
, fun([&](const std::string
&name
) {
2635 if (deletes_
.find(path
+ name
) == deletes_
.end())
2637 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2638 if (deletes_
.find(path
+ name
) == deletes_
.end())
2643 #ifndef LDID_NOTOOLS
2644 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2648 char data
[4096 * 4];
2649 size_t writ(source
.sgetn(data
, sizeof(data
)));
2652 _assert(target
.sputn(data
, writ
) == writ
);
2654 progress(double(total
) / length
);
2658 static plist_t
plist(const std::string
&data
) {
2660 return plist_new_dict();
2661 plist_t
plist(NULL
);
2662 if (Starts(data
, "bplist00"))
2663 plist_from_bin(data
.data(), data
.size(), &plist
);
2665 plist_from_xml(data
.data(), data
.size(), &plist
);
2666 if (plist
== NULL
) {
2667 fprintf(stderr
, "ldid: Failed to parse plist\n");
2673 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2674 std::stringbuf data
;
2675 copy(buffer
, data
, length
, dummy_
);
2676 auto node(plist(data
.str()));
2677 _scope({ plist_free(node
); });
2678 if (plist_get_node_type(node
) != PLIST_DICT
) {
2679 fprintf(stderr
, "ldid: Unexpected plist type. Expected <dict>\n");
2685 static std::string
plist_s(plist_t node
) {
2688 if (plist_get_node_type(node
) != PLIST_STRING
) {
2689 fprintf(stderr
, "ldid: Unexpected plist type. Expected <string>\n");
2693 plist_get_string_val(node
, &data
);
2694 _scope({ free(data
); });
2709 std::vector
<std::string
> matches_
;
2712 Expression(const std::string
&code
) {
2713 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2714 matches_
.resize(regex_
.re_nsub
+ 1);
2721 bool operator ()(const std::string
&data
) {
2722 regmatch_t matches
[matches_
.size()];
2723 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2724 if (value
== REG_NOMATCH
)
2726 _assert_(value
== 0, "regexec()");
2727 for (size_t i(0); i
!= matches_
.size(); ++i
)
2728 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2732 const std::string
&operator [](size_t index
) const {
2733 return matches_
[index
];
2742 mutable std::unique_ptr
<Expression
> regex_
;
2744 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2751 Rule(const Rule
&rhs
) :
2752 weight_(rhs
.weight_
),
2758 void Compile() const {
2759 regex_
.reset(new Expression(code_
));
2762 bool operator ()(const std::string
&data
) const {
2763 _assert(regex_
.get() != NULL
);
2764 return (*regex_
)(data
);
2767 bool operator <(const Rule
&rhs
) const {
2768 if (weight_
> rhs
.weight_
)
2770 if (weight_
< rhs
.weight_
)
2772 return mode_
> rhs
.mode_
;
2777 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2778 return lhs
->code_
< rhs
->code_
;
2782 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
) {
2783 // XXX: this is a miserable fail
2784 std::stringbuf temp
;
2785 put(temp
, prefix
, size
);
2786 copy(buffer
, temp
, length
- size
, progress
);
2787 // XXX: this is a stupid hack
2788 pad(temp
, 0x10 - (length
& 0xf));
2789 auto data(temp
.str());
2791 HashProxy
proxy(hash
, save
);
2792 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2796 std::map
<std::string
, Hash
> files
;
2797 std::map
<std::string
, std::string
> links
;
2799 void Merge(const std::string
&root
, const State
&state
) {
2800 for (const auto &entry
: state
.files
)
2801 files
[root
+ entry
.first
] = entry
.second
;
2802 for (const auto &entry
: state
.links
)
2803 links
[root
+ entry
.first
] = entry
.second
;
2807 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
) {
2808 std::string executable
;
2809 std::string identifier
;
2813 std::string
info("Info.plist");
2815 SubFolder
folder(parent
, [&]() {
2816 if (parent
.Look(info
))
2819 if (parent
.Look("Contents/" + info
))
2821 else if (parent
.Look("Resources/" + info
)) {
2822 info
= "Resources/" + info
;
2825 fprintf(stderr
, "ldid: Could not find Info.plist\n");
2830 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2831 plist_d(buffer
, length
, fun([&](plist_t node
) {
2832 plist_t
nodebuf(plist_dict_get_item(node
, "CFBundleExecutable"));
2833 if (nodebuf
== NULL
) {
2834 fprintf(stderr
, "ldid: Cannot find key CFBundleExecutable\n");
2837 executable
= plist_s(nodebuf
);
2838 nodebuf
= plist_dict_get_item(node
, "CFBundleIdentifier");
2839 if (nodebuf
== NULL
) {
2840 fprintf(stderr
, "ldid: Cannot find key CFBundleIdentifier\n");
2843 identifier
= plist_s(nodebuf
);
2847 if (mac
&& info
== "Info.plist")
2848 executable
= "MacOS/" + executable
;
2850 progress(root
+ "*");
2852 std::string entitlements
;
2853 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2854 // XXX: this is a miserable fail
2855 std::stringbuf temp
;
2856 copy(buffer
, temp
, length
, progress
);
2857 // XXX: this is a stupid hack
2858 pad(temp
, 0x10 - (length
& 0xf));
2859 auto data(temp
.str());
2860 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2863 static const std::string
directory("_CodeSignature/");
2864 static const std::string
signature(directory
+ "CodeResources");
2866 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2868 auto &rules1(versions
[""]);
2869 auto &rules2(versions
["2"]);
2871 const std::string
resources(mac
? "Resources/" : "");
2874 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2875 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2876 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2877 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2878 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2882 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2883 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2884 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2885 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2886 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2887 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2888 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2889 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2890 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2891 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2892 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2893 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2894 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2895 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2898 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2899 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2900 std::map
<std::string
, Bundle
> bundles
;
2902 folder
.Find("", fun([&](const std::string
&name
) {
2905 auto bundle(Split(name
).dir
);
2907 _assert(!bundle
.empty());
2908 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2910 SubFolder
subfolder(folder
, bundle
);
2913 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2914 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2916 local
.Merge(bundle
, remote
);
2917 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2920 std::set
<std::string
> excludes
;
2922 auto exclude([&](const std::string
&name
) {
2923 // BundleDiskRep::adjustResources -> builder.addExclusion
2924 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2927 for (const auto &bundle
: bundles
)
2928 if (Starts(name
, bundle
.first
+ "/")) {
2929 excludes
.insert(name
);
2936 folder
.Find("", fun([&](const std::string
&name
) {
2940 if (local
.files
.find(name
) != local
.files
.end())
2942 auto &hash(local
.files
[name
]);
2944 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2945 progress(root
+ name
);
2956 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2958 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2959 switch (Swap(header
.magic
)) {
2961 // Java class file format
2962 if (Swap(header
.count
) >= 40)
2965 case MH_MAGIC
: case MH_MAGIC_64
:
2966 case MH_CIGAM
: case MH_CIGAM_64
:
2967 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2969 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2974 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2975 HashProxy
proxy(hash
, save
);
2976 put(proxy
, header
.bytes
, size
);
2977 copy(data
, proxy
, length
- size
, progress
);
2980 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2984 local
.links
[name
] = read();
2987 auto plist(plist_new_dict());
2988 _scope({ plist_free(plist
); });
2990 for (const auto &version
: versions
) {
2991 auto files(plist_new_dict());
2992 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2994 for (const auto &rule
: version
.second
)
2997 bool old(&version
.second
== &rules1
);
2999 for (const auto &hash
: local
.files
)
3000 for (const auto &rule
: version
.second
)
3001 if (rule(hash
.first
)) {
3002 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
3003 else if (old
&& rule
.mode_
== NoMode
)
3004 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3005 else if (rule
.mode_
!= OmitMode
) {
3006 auto entry(plist_new_dict());
3007 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3009 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
3010 if (rule
.mode_
== OptionalMode
)
3011 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3012 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3019 for (const auto &link
: local
.links
)
3020 for (const auto &rule
: version
.second
)
3021 if (rule(link
.first
)) {
3022 if (rule
.mode_
!= OmitMode
) {
3023 auto entry(plist_new_dict());
3024 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3025 if (rule
.mode_
== OptionalMode
)
3026 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3027 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3034 for (const auto &bundle
: bundles
) {
3035 auto entry(plist_new_dict());
3036 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3037 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3038 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3042 for (const auto &version
: versions
) {
3043 auto rules(plist_new_dict());
3044 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3046 std::multiset
<const Rule
*, RuleCode
> ordered
;
3047 for (const auto &rule
: version
.second
)
3048 ordered
.insert(&rule
);
3050 for (const auto &rule
: ordered
)
3051 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3052 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3054 auto entry(plist_new_dict());
3055 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3057 switch (rule
->mode_
) {
3061 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3064 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3067 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3070 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3074 if (rule
->weight_
>= 10000)
3075 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3076 else if (rule
->weight_
!= 1)
3077 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3081 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3082 HashProxy
proxy(local
.files
[signature
], save
);
3085 plist_to_xml(plist
, &xml
, &size
);
3086 _scope({ free(xml
); });
3087 put(proxy
, xml
, size
);
3091 bundle
.path
= folder
.Path(executable
);
3093 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3094 progress(root
+ executable
);
3095 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3097 slots
[1] = local
.files
.at(info
);
3098 slots
[3] = local
.files
.at(signature
);
3099 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3106 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
) {
3108 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3114 std::string
Hex(const uint8_t *data
, size_t size
) {
3116 hex
.reserve(size
* 2);
3117 for (size_t i(0); i
!= size
; ++i
) {
3118 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3119 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3124 static void usage(const char *argv0
) {
3125 fprintf(stderr
, "Link Identity Editor %s\n\n", LDID_VERSION
);
3126 fprintf(stderr
, "Usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0
);
3127 fprintf(stderr
, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3128 fprintf(stderr
, " [-Enum:file] [-e] [-H[sha1 | sha256]] [-h] [-Iname]\n");
3129 fprintf(stderr
, " [-Kkey.p12 [-Upassword]] [-M] [-P] [-Qrequirements.xml] [-q]\n");
3130 fprintf(stderr
, " [-r | -Sfile.xml | -s] [-Ttimestamp] [-u] [-arch arch_type] file ...\n");
3131 fprintf(stderr
, "Options:\n");
3132 fprintf(stderr
, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3133 fprintf(stderr
, " -Kkey.p12 Sign using private key in key.p12\n");
3134 fprintf(stderr
, " -Upassword Use password to unlock key.p12\n");
3135 fprintf(stderr
, " -M Merge entitlements with any existing\n");
3136 fprintf(stderr
, " -h Print CDHash of file\n\n");
3137 fprintf(stderr
, "More information: 'man ldid'\n");
3140 void cleanupfunc(void) {
3141 for (const auto &temp
: cleanup
)
3142 remove(temp
.c_str());
3145 #ifndef LDID_NOTOOLS
3146 int main(int argc
, char *argv
[]) {
3147 std::atexit(cleanupfunc
);
3148 OpenSSL_add_all_algorithms();
3149 # if OPENSSL_VERSION_MAJOR >= 3
3150 OSSL_PROVIDER
*legacy
= OSSL_PROVIDER_load(NULL
, "legacy");
3151 OSSL_PROVIDER
*deflt
= OSSL_PROVIDER_load(NULL
, "default");
3159 little_
= endian
.byte
[0];
3183 bool platform(false);
3185 uint32_t flag_CPUType(_not(uint32_t));
3186 uint32_t flag_CPUSubtype(_not(uint32_t));
3188 const char *flag_I(NULL
);
3196 std::vector
<std::string
> files
;
3203 for (int argi(1); argi
!= argc
; ++argi
)
3204 if (argv
[argi
][0] != '-')
3205 files
.push_back(argv
[argi
]);
3206 else if (strcmp(argv
[argi
], "-arch") == 0) {
3207 bool foundarch
= false;
3211 fprintf(stderr
, "ldid: -arch must be followed by an architecture string\n");
3214 for (int i
= 0; archs
[i
].name
!= NULL
; i
++) {
3215 if (strcmp(archs
[i
].name
, argv
[argi
]) == 0) {
3216 flag_CPUType
= archs
[i
].cputype
;
3217 flag_CPUSubtype
= archs
[i
].cpusubtype
;
3225 fprintf(stderr
, "error: unknown architecture specification flag: -arch %s\n", argv
[argi
]);
3228 } else switch (argv
[argi
][1]) {
3230 if (flag_s
|| flag_S
) {
3231 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3237 case 'e': flag_e
= true; break;
3240 const char *string
= argv
[argi
] + 2;
3241 const char *colon
= strchr(string
, ':');
3242 if (colon
== NULL
) {
3246 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3248 unsigned number(strtoul(string
, &arge
, 0));
3249 if (arge
!= colon
|| (number
== 0 && errno
== EINVAL
)) {
3253 auto &slot(slots
[number
]);
3254 for (Algorithm
*algorithm
: GetAlgorithms())
3255 (*algorithm
)(slot
, file
.data(), file
.size());
3258 case 'q': flag_q
= true; break;
3261 const char *hash
= argv
[argi
] + 2;
3270 if (strcmp(hash
, "sha1") == 0)
3272 else if (strcmp(hash
, "sha256") == 0)
3275 fprintf(stderr
, "ldid: only sha1 and sha256 are supported at this time\n");
3280 case 'h': flag_h
= true; break;
3283 const char *xml
= argv
[argi
] + 2;
3284 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3287 case 'D': flag_D
= true; break;
3288 case 'd': flag_d
= true; break;
3290 case 'a': flag_a
= true; break;
3294 fprintf(stderr
, "ldid: -A can only be specified once\n");
3298 if (argv
[argi
][2] != '\0') {
3299 const char *cpu
= argv
[argi
] + 2;
3300 const char *colon
= strchr(cpu
, ':');
3301 if (colon
== NULL
) {
3306 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3307 if (arge
!= colon
|| (flag_CPUType
== 0 && errno
== EINVAL
)) {
3311 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3312 if (arge
!= argv
[argi
] + strlen(argv
[argi
]) || (flag_CPUSubtype
== 0 && errno
== EINVAL
)) {
3320 const char *name
= argv
[argi
] + 2;
3321 if (strcmp(name
, "host") == 0)
3322 flags
|= kSecCodeSignatureHost
;
3323 else if (strcmp(name
, "adhoc") == 0)
3324 flags
|= kSecCodeSignatureAdhoc
;
3325 else if (strcmp(name
, "hard") == 0)
3326 flags
|= kSecCodeSignatureForceHard
;
3327 else if (strcmp(name
, "kill") == 0)
3328 flags
|= kSecCodeSignatureForceKill
;
3329 else if (strcmp(name
, "expires") == 0)
3330 flags
|= kSecCodeSignatureForceExpiration
;
3331 else if (strcmp(name
, "restrict") == 0)
3332 flags
|= kSecCodeSignatureRestrict
;
3333 else if (strcmp(name
, "enforcement") == 0)
3334 flags
|= kSecCodeSignatureEnforcement
;
3335 else if (strcmp(name
, "library-validation") == 0)
3336 flags
|= kSecCodeSignatureLibraryValidation
;
3337 else if (strcmp(name
, "runtime") == 0)
3338 flags
|= kSecCodeSignatureRuntime
;
3340 fprintf(stderr
, "ldid: -C: Unsupported option\n");
3350 if (flag_r
|| flag_S
) {
3351 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3355 entitlements
.clear();
3360 if (flag_r
|| flag_s
) {
3361 fprintf(stderr
, "ldid: Can only specify one of -r, -S, -s\n");
3365 if (argv
[argi
][2] != '\0') {
3366 const char *xml
= argv
[argi
] + 2;
3367 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3376 password
= argv
[argi
] + 2;
3380 if (argv
[argi
][2] != '\0')
3381 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3391 flag_I
= argv
[argi
] + 2;
3400 if (flag_I
!= NULL
&& !flag_S
) {
3401 fprintf(stderr
, "ldid: -I requires -S\n");
3408 size_t filei(0), filee(0);
3409 _foreach (file
, files
) try {
3410 std::string
path(file
);
3413 if (stat(path
.c_str(), &info
) == -1) {
3414 fprintf(stderr
, "ldid: %s: %s\n", path
.c_str(), strerror(errno
));
3418 if (S_ISDIR(info
.st_mode
)) {
3420 fprintf(stderr
, "ldid: Only -S can be used on directories\n");
3423 ldid::DiskFolder
folder(path
+ "/");
3424 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_
);
3442 Map
mapping(path
, flag_D
? true : false);
3443 FatHeader
fat_header(mapping
.data(), mapping
.size());
3445 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3446 struct linkedit_data_command
*signature(NULL
);
3447 struct encryption_info_command
*encryption(NULL
);
3450 if (mach_header
.GetCPUType() != flag_CPUType
)
3452 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3457 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3459 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3460 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3462 if (cmd
== LC_CODE_SIGNATURE
)
3463 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3464 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3465 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3466 else if (cmd
== LC_LOAD_DYLIB
) {
3467 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3468 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3470 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3473 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3474 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3480 if (flag_d
&& encryption
!= NULL
) {
3481 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3485 if (encryption
== NULL
) {
3486 fprintf(stderr
, "ldid: -D requires an encrypted binary\n");
3489 encryption
->cryptid
= mach_header
.Swap(0);
3492 if ((flag_e
|| flag_q
|| flag_h
) && signature
== NULL
) {
3493 fprintf(stderr
, "ldid: -e, -q, and -h requre a signed binary\n");
3498 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3500 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3501 uint8_t *blob
= top
+ data
;
3502 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3504 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3505 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3506 uint32_t begin
= Swap(super
->index
[index
].offset
);
3507 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3508 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3513 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3515 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3516 uint8_t *blob
= top
+ data
;
3517 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3519 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3520 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3521 uint32_t begin
= Swap(super
->index
[index
].offset
);
3522 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3523 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3528 auto algorithms(GetAlgorithms());
3530 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3532 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3533 uint8_t *blob
= top
+ data
;
3534 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3537 CodeDirectory
*directory_
;
3539 Algorithm
&algorithm_
;
3543 std::map
<uint8_t, Candidate
> candidates
;
3545 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3546 auto type(Swap(super
->index
[index
].type
));
3547 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3548 uint32_t begin
= Swap(super
->index
[index
].offset
);
3549 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3550 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3551 auto type(directory
->hashType
);
3552 _assert(type
> 0 && type
<= algorithms
.size());
3553 auto &algorithm(*algorithms
[type
- 1]);
3554 uint8_t hash
[algorithm
.size_
];
3555 algorithm(hash
, blob
+ begin
, end
- begin
);
3556 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3560 _assert(!candidates
.empty());
3561 auto best(candidates
.end());
3564 const auto directory(best
->second
.directory_
);
3565 const auto flags(Swap(directory
->flags
));
3568 if (flags
& kSecCodeSignatureHost
)
3570 if (flags
& kSecCodeSignatureAdhoc
)
3572 if (flags
& kSecCodeSignatureForceHard
)
3574 if (flags
& kSecCodeSignatureForceKill
)
3576 if (flags
& kSecCodeSignatureForceExpiration
)
3577 names
+= ",expires";
3578 if (flags
& kSecCodeSignatureRestrict
)
3579 names
+= ",restrict";
3580 if (flags
& kSecCodeSignatureEnforcement
)
3581 names
+= ",enforcement";
3582 if (flags
& kSecCodeSignatureLibraryValidation
)
3583 names
+= ",library-validation";
3584 if (flags
& kSecCodeSignatureRuntime
)
3585 names
+= ",runtime";
3587 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3588 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3589 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3591 std::string choices
;
3592 for (const auto &candidate
: candidates
) {
3593 auto choice(candidate
.second
.algorithm_
.name());
3596 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3598 printf("Hash choices=%s\n", choices
.c_str() + 1);
3600 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3605 } catch (const char *) {
3610 # if OPENSSL_VERSION_MAJOR >= 3
3611 OSSL_PROVIDER_unload(legacy
);
3612 OSSL_PROVIDER_unload(deflt
);
3617 #endif // LDID_NOTOOLS