├── data
├── ipsw
│ └── .ipsws
├── boot
│ └── .kernels_and_ramdisks
├── bin
│ ├── ioreg
│ └── sysctl
├── ssh.tar.gz
└── libncurses.5.dylib
├── python_scripts
├── crypto
│ ├── __init__.py
│ ├── aes.pyc
│ ├── gcm.pyc
│ ├── PBKDF2.pyc
│ ├── __init__.pyc
│ ├── aeswrap.pyc
│ ├── curve25519.pyc
│ ├── aes.py
│ ├── curve25519.py
│ └── aeswrap.py
├── hfs
│ ├── __init__.py
│ ├── emf.pyc
│ ├── hfs.pyc
│ ├── btree.pyc
│ ├── __init__.pyc
│ ├── journal.pyc
│ ├── structs.pyc
│ └── fastunicode.pyc
├── icloud
│ ├── __init__.py
│ ├── pbuf.py
│ ├── icloud.proto
│ └── chunkserver.proto
├── nand
│ ├── __init__.py
│ ├── ppn.pyc
│ ├── vfl.pyc
│ ├── image.pyc
│ ├── nand.pyc
│ ├── vsvfl.pyc
│ ├── yaftl.pyc
│ ├── __init__.pyc
│ ├── carver.pyc
│ ├── remote.pyc
│ ├── structs.pyc
│ ├── legacyftl.pyc
│ ├── ppn_carver.pyc
│ ├── partition_tables.pyc
│ ├── IOFlashPartitionScheme.pyc
│ ├── structs.py
│ ├── remote.py
│ └── image.py
├── usbmux
│ ├── __init__.py
│ ├── usbmux.pyc
│ ├── __init__.pyc
│ └── tcprelay.py
├── backups
│ ├── __init__.py
│ ├── backup3.pyc
│ ├── backup4.pyc
│ ├── __init__.pyc
│ └── backup3.py
├── firmware
│ ├── __init__.py
│ ├── img2.pyc
│ ├── img3.pyc
│ ├── scfg.pyc
│ ├── __init__.pyc
│ ├── img2.py
│ └── scfg.py
├── keystore
│ ├── __init__.py
│ ├── keybag.pyc
│ ├── __init__.pyc
│ ├── effaceable.pyc
│ └── effaceable.py
├── util
│ ├── tlv.pyc
│ ├── bdev.pyc
│ ├── cert.pyc
│ ├── lzss.pyc
│ ├── __init__.pyc
│ ├── bplist.pyc
│ ├── bruteforce.pyc
│ ├── asciitables.pyc
│ ├── ramdiskclient.pyc
│ ├── tlv.py
│ ├── cert.py
│ ├── asciitables.py
│ ├── lzss.py
│ ├── bruteforce.py
│ └── __init__.py
├── keychain
│ ├── store.pyc
│ ├── __init__.pyc
│ ├── keychain.pyc
│ ├── keychain3.pyc
│ ├── keychain4.pyc
│ ├── managedconfiguration.pyc
│ ├── __init__.py
│ ├── managedconfiguration.py
│ ├── keychain3.py
│ ├── store.py
│ └── keychain4.py
├── README.txt
├── windows_redsn0w_keys.py
├── wordlist.dict
├── emf_undelete.py
├── emf_decrypter.py
├── demo_escrow.py
├── keychain_tool.py
└── backup_tool.py
├── ramdisk_tools
├── image.h
├── registry.h
├── IOKit
├── dump_data_partition.sh
├── device_info.h
├── plist_server.h
├── tfp0.plist
├── entitlements.plist
├── keystore_device.xml
├── remote_functions.h
├── ioflash
│ ├── Makefile
│ ├── externalMethod.h
│ ├── ioflashstoragekit.c
│ ├── IOFlashPartitionScheme.h
│ └── externalMethod.S
├── scripts
│ └── mount_partitions.sh
├── IOKit.h
├── bsdcrypto
│ ├── sha1.h
│ ├── pbkdf2.h
│ ├── key_wrap.h
│ ├── rijndael.h
│ └── key_wrap.c
├── AppleEffaceableStorage.h
├── IOAESAccelerator.h
├── device_infos.c
├── AppleEffaceableStorage.c
├── kernel_patcher.c
├── image.c
├── Makefile
├── AppleKeyStore.h
├── IOKit.c
├── util.h
└── device_info.c
├── .DS_Store
├── emf_decrypter
├── common
│ └── CMakeLists.txt
├── emf
│ ├── CMakeLists.txt
│ ├── emf.h
│ └── emf_init.c
├── includes
│ ├── dmg
│ │ ├── dmgfile.h
│ │ ├── dmglib.h
│ │ └── filevault.h
│ ├── hfs
│ │ ├── hfslib.h
│ │ └── hfscompress.h
│ ├── abstractfile.h
│ └── common.h
├── hfs
│ ├── CMakeLists.txt
│ ├── utility.c
│ ├── flatfile.c
│ └── extents.c
├── README.txt
├── CMakeLists.txt
└── BUILD
├── ssh.tar.gz
├── tcprelay.bat
├── old
├── emf_decrypter
│ ├── common
│ │ └── CMakeLists.txt
│ ├── emf
│ │ ├── CMakeLists.txt
│ │ ├── emf.h
│ │ └── emf_init.c
│ ├── includes
│ │ ├── dmg
│ │ │ ├── dmgfile.h
│ │ │ ├── dmglib.h
│ │ │ └── filevault.h
│ │ ├── hfs
│ │ │ ├── hfslib.h
│ │ │ └── hfscompress.h
│ │ ├── abstractfile.h
│ │ └── common.h
│ ├── hfs
│ │ ├── CMakeLists.txt
│ │ ├── utility.c
│ │ ├── flatfile.c
│ │ └── extents.c
│ ├── README.txt
│ ├── CMakeLists.txt
│ └── BUILD
└── img3fs
│ ├── Makefile
│ └── README
├── tcprelay.sh
├── tmp
└── .DS_Store
├── usbmuxd-python-client
├── relay.bat
└── usbmux.pyc
├── CREDITS.txt
├── boot.bat
├── dependencies
└── M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
├── .gitignore
├── img3fs
├── Makefile
└── README
├── dump_data_partition.sh
├── make_ramdisk_n92ap.sh
├── README.txt
├── ios7.patch.v3
├── boot.py
├── IOKit.frameworkHeaders
└── IOCFPlugIn.h
└── README.md
/data/ipsw/.ipsws:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/data/boot/.kernels_and_ramdisks:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/crypto/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/hfs/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/icloud/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/nand/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/usbmux/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/backups/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/firmware/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/python_scripts/keystore/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ramdisk_tools/image.h:
--------------------------------------------------------------------------------
1 | int drawImage(const char* pngFileName);
2 |
--------------------------------------------------------------------------------
/ramdisk_tools/registry.h:
--------------------------------------------------------------------------------
1 | void get_device_infos(CFMutableDictionaryRef out);
--------------------------------------------------------------------------------
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/.DS_Store
--------------------------------------------------------------------------------
/emf_decrypter/common/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | add_library(common abstractfile.c base64.c)
2 |
3 |
--------------------------------------------------------------------------------
/ramdisk_tools/IOKit:
--------------------------------------------------------------------------------
1 | /System/Library/Frameworks/IOKit.framework/Versions/Current/Headers
--------------------------------------------------------------------------------
/ssh.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/ssh.tar.gz
--------------------------------------------------------------------------------
/tcprelay.bat:
--------------------------------------------------------------------------------
1 | c:\Python27\python.exe python_scripts\usbmux\tcprelay.py -t 22:2222
2 |
--------------------------------------------------------------------------------
/data/bin/ioreg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/data/bin/ioreg
--------------------------------------------------------------------------------
/old/emf_decrypter/common/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | add_library(common abstractfile.c base64.c)
2 |
3 |
--------------------------------------------------------------------------------
/tcprelay.sh:
--------------------------------------------------------------------------------
1 | #/bin/sh
2 |
3 | python python_scripts/usbmux/tcprelay.py -t 22:2222
4 |
5 |
--------------------------------------------------------------------------------
/tmp/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/tmp/.DS_Store
--------------------------------------------------------------------------------
/data/bin/sysctl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/data/bin/sysctl
--------------------------------------------------------------------------------
/data/ssh.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/data/ssh.tar.gz
--------------------------------------------------------------------------------
/ramdisk_tools/dump_data_partition.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | cat /dev/rdisk0s2s1 | netcat -l -p 1234
4 |
--------------------------------------------------------------------------------
/data/libncurses.5.dylib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/data/libncurses.5.dylib
--------------------------------------------------------------------------------
/usbmuxd-python-client/relay.bat:
--------------------------------------------------------------------------------
1 | c:\Python26\python.exe tcprelay.py -t 22:2222 5900:5900 1999:1999 1234:1234
2 |
--------------------------------------------------------------------------------
/python_scripts/hfs/emf.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/emf.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/hfs.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/hfs.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/ppn.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/ppn.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/vfl.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/vfl.pyc
--------------------------------------------------------------------------------
/python_scripts/util/tlv.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/tlv.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/aes.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/aes.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/gcm.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/gcm.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/btree.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/btree.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/image.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/image.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/nand.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/nand.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/vsvfl.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/vsvfl.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/yaftl.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/yaftl.pyc
--------------------------------------------------------------------------------
/python_scripts/util/bdev.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/bdev.pyc
--------------------------------------------------------------------------------
/python_scripts/util/cert.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/cert.pyc
--------------------------------------------------------------------------------
/python_scripts/util/lzss.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/lzss.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/PBKDF2.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/PBKDF2.pyc
--------------------------------------------------------------------------------
/python_scripts/firmware/img2.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/firmware/img2.pyc
--------------------------------------------------------------------------------
/python_scripts/firmware/img3.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/firmware/img3.pyc
--------------------------------------------------------------------------------
/python_scripts/firmware/scfg.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/firmware/scfg.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/journal.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/journal.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/structs.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/structs.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/carver.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/carver.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/remote.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/remote.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/structs.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/structs.pyc
--------------------------------------------------------------------------------
/python_scripts/usbmux/usbmux.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/usbmux/usbmux.pyc
--------------------------------------------------------------------------------
/python_scripts/util/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/util/bplist.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/bplist.pyc
--------------------------------------------------------------------------------
/usbmuxd-python-client/usbmux.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/usbmuxd-python-client/usbmux.pyc
--------------------------------------------------------------------------------
/python_scripts/backups/backup3.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/backups/backup3.pyc
--------------------------------------------------------------------------------
/python_scripts/backups/backup4.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/backups/backup4.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/aeswrap.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/aeswrap.pyc
--------------------------------------------------------------------------------
/python_scripts/hfs/fastunicode.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/hfs/fastunicode.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/store.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/store.pyc
--------------------------------------------------------------------------------
/python_scripts/keystore/keybag.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keystore/keybag.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/legacyftl.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/legacyftl.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/ppn_carver.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/ppn_carver.pyc
--------------------------------------------------------------------------------
/python_scripts/usbmux/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/usbmux/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/util/bruteforce.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/bruteforce.pyc
--------------------------------------------------------------------------------
/python_scripts/backups/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/backups/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/crypto/curve25519.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/crypto/curve25519.pyc
--------------------------------------------------------------------------------
/python_scripts/firmware/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/firmware/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/keychain.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/keychain.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/keychain3.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/keychain3.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/keychain4.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/keychain4.pyc
--------------------------------------------------------------------------------
/python_scripts/keystore/__init__.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keystore/__init__.pyc
--------------------------------------------------------------------------------
/python_scripts/util/asciitables.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/asciitables.pyc
--------------------------------------------------------------------------------
/python_scripts/util/ramdiskclient.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/util/ramdiskclient.pyc
--------------------------------------------------------------------------------
/python_scripts/keystore/effaceable.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keystore/effaceable.pyc
--------------------------------------------------------------------------------
/CREDITS.txt:
--------------------------------------------------------------------------------
1 | comex
2 | chronic dev team
3 | idroid/openiboot team
4 | iphone dev team
5 | Jonathan Zdziarski
6 | msftguy
7 | planetbeing
8 |
--------------------------------------------------------------------------------
/python_scripts/README.txt:
--------------------------------------------------------------------------------
1 | Dependencies
2 | pycrypto (https://www.dlitz.net/software/pycrypto/)
3 | construct (http://construct.wikispaces.com/)
--------------------------------------------------------------------------------
/python_scripts/nand/partition_tables.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/partition_tables.pyc
--------------------------------------------------------------------------------
/python_scripts/nand/IOFlashPartitionScheme.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/nand/IOFlashPartitionScheme.pyc
--------------------------------------------------------------------------------
/python_scripts/keychain/managedconfiguration.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/python_scripts/keychain/managedconfiguration.pyc
--------------------------------------------------------------------------------
/boot.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | c:\python27\python.exe boot.py
4 |
5 | c:\Python27\python.exe python_scripts\usbmux\tcprelay.py -t 22:2222
6 |
7 | IF %0 == "%~0" pause
8 |
--------------------------------------------------------------------------------
/dependencies/M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/as0ler/iphone-dataprotection/HEAD/dependencies/M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
--------------------------------------------------------------------------------
/ramdisk_tools/device_info.h:
--------------------------------------------------------------------------------
1 | #ifndef HGVERSION
2 | #define HGVERSION "unknown"
3 | #endif
4 |
5 | CFMutableDictionaryRef device_info(int socket, CFDictionaryRef request);
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | Keychain/*
2 | *.plist
3 | .DS_Store
4 | *.pyc
5 | c595c8469d031223391aa9b0bdf84841b4abd81d/
6 | Keys/
7 | keychain-2.db
8 | c595c8469d.plist
9 | python_scripts/keychain-2.db
10 | Keychains/
11 |
--------------------------------------------------------------------------------
/old/img3fs/Makefile:
--------------------------------------------------------------------------------
1 | img3fs: img3fs.c
2 | gcc -o $@ $^ -Wall -lfuse_ino64 -lcrypto -I/usr/local/include/osxfuse || gcc -o $@ $^ -Wall -losxfuse_i64 -lcrypto -I/usr/local/include/osxfuse
3 |
4 | clean:
5 | rm img3fs
6 |
--------------------------------------------------------------------------------
/ramdisk_tools/plist_server.h:
--------------------------------------------------------------------------------
1 | #define PLIST_MAX_SIZE 50*1024*1024
2 |
3 | int create_listening_socket(int port);
4 | int send_progress_message(int socket, int progress, int total);
5 | int send_object(int socket, CFTypeRef obj);
6 | void serve_plist_rpc(int port, CFDictionaryRef handlers);
--------------------------------------------------------------------------------
/python_scripts/windows_redsn0w_keys.py:
--------------------------------------------------------------------------------
1 | #HAX
2 |
3 | d=open("redsn0w_win_0.9.9b4/redsn0w.exe", "rb").read()
4 |
5 | i = d.find("IV")
6 | i = d.rfind("", i)
8 |
9 | assert i != -1
10 | assert j != -1
11 |
12 | open("Keys.plist", "wb").write(d[i:j+8])
13 |
--------------------------------------------------------------------------------
/img3fs/Makefile:
--------------------------------------------------------------------------------
1 | img3fs: img3fs.c
2 | gcc -o $@ $^ -Wall -L/usr/local/lib/ -lfuse_ino64 -lcrypto -I/usr/local/include/osxfuse -I/usr/local/Cellar/openssl/1.0.2a-1/include || gcc -o $@ $^ -Wall -L/usr/local/lib/ -losxfuse_i64 -lcrypto -I/usr/local/Cellar/openssl/1. 0.2a-1/include -I/usr/local/include/osxfuse
3 | clean:
4 | rm img3fs
5 |
--------------------------------------------------------------------------------
/ramdisk_tools/tfp0.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | get-task-allow
6 |
7 | run-unsigned-code
8 |
9 | task_for_pid-allow
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/python_scripts/firmware/img2.py:
--------------------------------------------------------------------------------
1 | from construct.core import Struct
2 | from construct.macros import *
3 |
4 | IMG2 = Struct("IMG2",
5 | String("magic",4),
6 | ULInt32("block_size"),
7 | ULInt32("images_offset"),
8 | ULInt32("images_block"),
9 | ULInt32("images_length"),
10 | Padding(0x1C),
11 | ULInt32("crc32"),
12 | )
--------------------------------------------------------------------------------
/emf_decrypter/emf/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | link_directories(${PROJECT_BINARY_DIR}/common ${PROJECT_BINARY_DIR}/hfs)
2 |
3 | #set(COREFOUNDATION_LIBRARY CoreFoundation)
4 |
5 | IF (APPLE)
6 | FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation)
7 | ENDIF (APPLE)
8 |
9 | add_executable(emf_decrypter emf_decrypter.c emf_init.c)
10 | target_link_libraries (emf_decrypter hfs common crypto ${COREFOUNDATION_LIBRARY})
11 |
12 | install(TARGETS emf_decrypter DESTINATION .)
13 |
--------------------------------------------------------------------------------
/ramdisk_tools/entitlements.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.keystore.device
6 |
7 | get-task-allow
8 |
9 | run-unsigned-code
10 |
11 | task_for_pid-allow
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ramdisk_tools/keystore_device.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.keystore.device
6 |
7 | get-task-allow
8 |
9 | run-unsigned-code
10 |
11 | task_for_pid-allow
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ramdisk_tools/remote_functions.h:
--------------------------------------------------------------------------------
1 |
2 | CFDictionaryRef load_system_keybag(int socket, CFDictionaryRef dict);
3 | CFDictionaryRef bruteforce_system_keybag(int socket, CFDictionaryRef dict);
4 | CFDictionaryRef keybag_get_passcode_key(int socket, CFDictionaryRef dict);
5 | CFDictionaryRef get_escrow_record(int socket, CFDictionaryRef dict);
6 | CFDictionaryRef download_file(int socket, CFDictionaryRef dict);
7 | CFDictionaryRef remote_aes(int socket, CFDictionaryRef dict);
8 |
--------------------------------------------------------------------------------
/old/emf_decrypter/emf/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | link_directories(${PROJECT_BINARY_DIR}/common ${PROJECT_BINARY_DIR}/hfs)
2 |
3 | #set(COREFOUNDATION_LIBRARY CoreFoundation)
4 |
5 | IF (APPLE)
6 | FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation)
7 | ENDIF (APPLE)
8 |
9 | add_executable(emf_decrypter emf_decrypter.c emf_init.c)
10 | target_link_libraries (emf_decrypter hfs common crypto ${COREFOUNDATION_LIBRARY})
11 |
12 | install(TARGETS emf_decrypter DESTINATION .)
13 |
--------------------------------------------------------------------------------
/img3fs/README:
--------------------------------------------------------------------------------
1 | FUSE img3 filesystem
2 | read/write/encryption support
3 |
4 | Usage example:
5 |
6 | mkdir /tmp/img3
7 | img3fs /tmp/img3 038-0032-002.dmg -iv 9b20ae16bebf4cf1b9101374c3ab0095 -key 06849aead2e9a6ca8a82c3929bad5c2368942e3681a3d5751720d2aacf0694c0
8 | hdiutil attach /tmp/img3/DATA.dmg
9 | rm -rf /Volumes/ramdisk/usr/local/standalone/firmware/*
10 | echo "Hello World!" > /Volumes/ramdisk/hello.txt
11 | hdiutil eject /Volumes/ramdisk
12 | umount /tmp/img3
--------------------------------------------------------------------------------
/emf_decrypter/includes/dmg/dmgfile.h:
--------------------------------------------------------------------------------
1 | /*
2 | * dmgfile.h
3 | * libdmg-hfsplus
4 | *
5 | */
6 |
7 | #include
8 |
9 | io_func* openDmgFile(AbstractFile* dmg);
10 | io_func* openDmgFilePartition(AbstractFile* dmg, int partition);
11 |
12 | typedef struct DMG {
13 | AbstractFile* dmg;
14 | ResourceKey* resources;
15 | uint32_t numBLKX;
16 | BLKXTable** blkx;
17 | void* runData;
18 | uint64_t runStart;
19 | uint64_t runEnd;
20 | uint64_t offset;
21 | } DMG;
22 |
--------------------------------------------------------------------------------
/old/img3fs/README:
--------------------------------------------------------------------------------
1 | FUSE img3 filesystem
2 | read/write/encryption support
3 |
4 | Usage example:
5 |
6 | mkdir /tmp/img3
7 | img3fs /tmp/img3 038-0032-002.dmg -iv 9b20ae16bebf4cf1b9101374c3ab0095 -key 06849aead2e9a6ca8a82c3929bad5c2368942e3681a3d5751720d2aacf0694c0
8 | hdiutil attach /tmp/img3/DATA.dmg
9 | rm -rf /Volumes/ramdisk/usr/local/standalone/firmware/*
10 | echo "Hello World!" > /Volumes/ramdisk/hello.txt
11 | hdiutil eject /Volumes/ramdisk
12 | umount /tmp/img3
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/dmg/dmgfile.h:
--------------------------------------------------------------------------------
1 | /*
2 | * dmgfile.h
3 | * libdmg-hfsplus
4 | *
5 | */
6 |
7 | #include
8 |
9 | io_func* openDmgFile(AbstractFile* dmg);
10 | io_func* openDmgFilePartition(AbstractFile* dmg, int partition);
11 |
12 | typedef struct DMG {
13 | AbstractFile* dmg;
14 | ResourceKey* resources;
15 | uint32_t numBLKX;
16 | BLKXTable** blkx;
17 | void* runData;
18 | uint64_t runStart;
19 | uint64_t runEnd;
20 | uint64_t offset;
21 | } DMG;
22 |
--------------------------------------------------------------------------------
/python_scripts/util/tlv.py:
--------------------------------------------------------------------------------
1 | import struct
2 |
3 | def tlvToDict(blob):
4 | d = {}
5 | for tag,data in loopTLVBlocks(blob):
6 | d[tag] = data
7 | return d
8 |
9 | def tlvToList(blob):
10 | return list(loopTLVBlocks(blob))
11 |
12 | def loopTLVBlocks(blob):
13 | i = 0
14 | while i + 8 <= len(blob):
15 | tag = blob[i:i+4]
16 | length = struct.unpack(">L",blob[i+4:i+8])[0]
17 | data = blob[i+8:i+8+length]
18 | yield (tag,data)
19 | i += 8 + length
--------------------------------------------------------------------------------
/python_scripts/util/cert.py:
--------------------------------------------------------------------------------
1 | import base64
2 |
3 | def chunks(l, n):
4 | return (l[i:i+n] for i in xrange(0, len(l), n))
5 |
6 | def RSA_KEY_DER_to_PEM(data):
7 | a = ["-----BEGIN RSA PRIVATE KEY-----"]
8 | a.extend(chunks(base64.b64encode(data),64))
9 | a.append("-----END RSA PRIVATE KEY-----")
10 | return "\n".join(a)
11 |
12 | def CERT_DER_to_PEM(data):
13 | a = ["-----BEGIN CERTIFICATE-----"]
14 | a.extend(chunks(base64.b64encode(data),64))
15 | a.append("-----END CERTIFICATE-----")
16 | return "\n".join(a)
--------------------------------------------------------------------------------
/python_scripts/keychain/__init__.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | from keychain3 import Keychain3
3 | from keychain4 import Keychain4
4 |
5 | def keychain_load(filename, keybag, key835):
6 | version = sqlite3.connect(filename).execute("SELECT version FROM tversion").fetchone()[0]
7 | print "Keychain version : %d" % version
8 | #version = 3
9 | if version == 3:
10 | return Keychain3(filename, key835)
11 | elif version >= 4:
12 | return Keychain4(filename, keybag)
13 | raise Exception("Unknown keychain version %d" % version)
14 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/dmg/dmglib.h:
--------------------------------------------------------------------------------
1 | #ifndef DMGLIB_H
2 | #define DMGLIB_H
3 |
4 | #include
5 | #include "abstractfile.h"
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | int extractDmg(AbstractFile* abstractIn, AbstractFile* abstractOut, int partNum);
11 | int buildDmg(AbstractFile* abstractIn, AbstractFile* abstractOut, unsigned int BlockSize);
12 |
13 | int convertToDMG(AbstractFile* abstractIn, AbstractFile* abstractOut);
14 | int convertToISO(AbstractFile* abstractIn, AbstractFile* abstractOut);
15 | #ifdef __cplusplus
16 | }
17 | #endif
18 |
19 | #endif
20 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/dmg/dmglib.h:
--------------------------------------------------------------------------------
1 | #ifndef DMGLIB_H
2 | #define DMGLIB_H
3 |
4 | #include
5 | #include "abstractfile.h"
6 |
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | int extractDmg(AbstractFile* abstractIn, AbstractFile* abstractOut, int partNum);
11 | int buildDmg(AbstractFile* abstractIn, AbstractFile* abstractOut, unsigned int BlockSize);
12 |
13 | int convertToDMG(AbstractFile* abstractIn, AbstractFile* abstractOut);
14 | int convertToISO(AbstractFile* abstractIn, AbstractFile* abstractOut);
15 | #ifdef __cplusplus
16 | }
17 | #endif
18 |
19 | #endif
20 |
--------------------------------------------------------------------------------
/ramdisk_tools/ioflash/Makefile:
--------------------------------------------------------------------------------
1 | SDKVER?=5.1
2 | ARCH?=armv7
3 | SDK=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS$(SDKVER).sdk/
4 | CC=clang -arch $(ARCH)
5 | CFLAGS=-Wall -isysroot $(SDK)
6 |
7 | externalMethod.h: externalMethod.bin
8 | xxd -i $^ > $@
9 |
10 | #hexdump hax to get correct endianness
11 | externalMethod.bin: externalMethod.o
12 | otool -tX $^ | xxd -r | hexdump -v -e '/4 "%08x"' | xxd -r -p > $@
13 |
14 | externalMethod.o: externalMethod.S
15 | $(CC) -c -o $@ $^
16 |
17 | clean:
18 | rm -f externalMethod.o externalMethod.bin
19 |
20 |
--------------------------------------------------------------------------------
/ramdisk_tools/scripts/mount_partitions.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | if [ -a /dev/disk0s1s2 ]; then # test for iOS 5 data partition
4 | mount_hfs /dev/disk0s1s1 /mnt1 2>/dev/null
5 | mount_hfs /dev/disk0s1s2 /mnt2 2>/dev/null
6 | elif [ -a /dev/disk0s2s1 ]; then # test for iOS 4 data partition
7 | mount_hfs /dev/disk0s1 /mnt1 2>/dev/null
8 | mount_hfs /dev/disk0s2s1 /mnt2 2>/dev/null
9 | elif [ -a /dev/disk0s2 ]; then
10 | mount_hfs /dev/disk0s1 /mnt1 2>/dev/null
11 | mount_hfs /dev/disk0s2 /mnt2 2>/dev/null
12 | else
13 | echo "Error mounting partitions. Please try it manually"
14 | fi
--------------------------------------------------------------------------------
/ramdisk_tools/IOKit.h:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | io_connect_t IOKit_getConnect(const char* serviceName);
4 |
5 | IOReturn IOKit_call(const char* serviceName,
6 | uint32_t selector,
7 | const uint64_t *input,
8 | uint32_t inputCnt,
9 | const void *inputStruct,
10 | size_t inputStructCnt,
11 | uint64_t *output,
12 | uint32_t *outputCnt,
13 | void *outputStruct,
14 | size_t *outputStructCnt);
--------------------------------------------------------------------------------
/emf_decrypter/hfs/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | INCLUDE(FindZLIB)
2 |
3 | IF(NOT ZLIB_FOUND)
4 | message(FATAL_ERROR "zlib is required for hfs!")
5 | ENDIF(NOT ZLIB_FOUND)
6 |
7 | include_directories(${ZLIB_INCLUDE_DIR})
8 | link_directories(${ZLIB_LIBRARIES})
9 |
10 | link_directories (${PROJECT_BINARY_DIR}/common)
11 | add_library(hfs btree.c catalog.c extents.c xattr.c fastunicodecompare.c flatfile.c hfslib.c rawfile.c utility.c volume.c hfscompress.c)
12 | target_link_libraries(hfs common z)
13 |
14 | add_executable(hfsplus hfs.c)
15 | target_link_libraries (hfsplus hfs)
16 |
17 | install(TARGETS hfsplus DESTINATION .)
18 |
19 |
--------------------------------------------------------------------------------
/dump_data_partition.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | SSHOPTS="-p 2222 -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null"
3 |
4 | UDID=`ssh $SSHOPTS root@localhost "./device_infos udid"`
5 |
6 | if [ "$UDID" == "" ]; then
7 | exit
8 | fi
9 |
10 | echo "Device UDID : $UDID"
11 |
12 | mkdir -p $UDID
13 |
14 | DATE=`date +"%Y%m%d-%H%M"`
15 | OUT1=$UDID/data_$DATE"_disks1s1.dmg"
16 | OUT2=$UDID/data_$DATE"_disks1s2.dmg"
17 |
18 |
19 | echo "Dumping data partition in $OUT1 ..."
20 |
21 | ssh $SSHOPTS root@localhost "dd if=/dev/rdisk0s1s1 bs=8192" > $OUT1
22 | ssh $SSHOPTS root@localhost "dd if=/dev/rdisk0s1s2 bs=8192" > $OUT2
23 |
--------------------------------------------------------------------------------
/old/emf_decrypter/hfs/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | INCLUDE(FindZLIB)
2 |
3 | IF(NOT ZLIB_FOUND)
4 | message(FATAL_ERROR "zlib is required for hfs!")
5 | ENDIF(NOT ZLIB_FOUND)
6 |
7 | include_directories(${ZLIB_INCLUDE_DIR})
8 | link_directories(${ZLIB_LIBRARIES})
9 |
10 | link_directories (${PROJECT_BINARY_DIR}/common)
11 | add_library(hfs btree.c catalog.c extents.c xattr.c fastunicodecompare.c flatfile.c hfslib.c rawfile.c utility.c volume.c hfscompress.c)
12 | target_link_libraries(hfs common z)
13 |
14 | add_executable(hfsplus hfs.c)
15 | target_link_libraries (hfsplus hfs)
16 |
17 | install(TARGETS hfsplus DESTINATION .)
18 |
19 |
--------------------------------------------------------------------------------
/python_scripts/wordlist.dict:
--------------------------------------------------------------------------------
1 | 12345
2 | 123456
3 | 123456
4 | 1234567
5 | 12345678
6 | 123456789
7 | 1234567890
8 | 09876
9 | 098765
10 | 0987654
11 | 09876543
12 | 098765432
13 | 0987654321
14 | abcd
15 | abcd1
16 | abcde
17 | abcde1
18 | abcdef
19 | abcdef1
20 | abcdefg
21 | abcdefg1
22 | qwer
23 | qwer1
24 | qwert
25 | qwert1
26 | qwertz
27 | qwertz1
28 | asdf
29 | asdfg
30 | asdfg1
31 | asdfgh
32 | asdfgh1
33 | yxcv
34 | yxcv1
35 | yxcvb
36 | yxcvb1
37 | yxcvbn
38 | yxcvbn1
39 | yxcvbnm
40 | yxcvbnm1
41 | mnbv
42 | mnbv1
43 | mnbvc
44 | mnbvc1
45 | mnbvcx
46 | mnbvcx1
47 | mnbvcxy
48 | mnbvcxy1
--------------------------------------------------------------------------------
/emf_decrypter/README.txt:
--------------------------------------------------------------------------------
1 | DEPRECATED: use the python version instead
2 |
3 | Decrypts files data forks in raw iOS 4 disk images.
4 | Reads encryption keys from plist file named after the volume ID.
5 | The plist file must have at least the EMF and DKey fields set.
6 | For now the tool decrypts the data forks but does not mark the files as
7 | "decrypted" : running it twice on the same image will produce garbage.
8 | Interrupting the process will also leave the image "half decrypted".
9 |
10 | Uses planetbeing/dev team HFS implementation
11 | https://github.com/planetbeing/xpwn
12 |
13 | Only builds on Mac OS X, requires CoreFoundation for plist access.
--------------------------------------------------------------------------------
/old/emf_decrypter/README.txt:
--------------------------------------------------------------------------------
1 | DEPRECATED: use the python version instead
2 |
3 | Decrypts files data forks in raw iOS 4 disk images.
4 | Reads encryption keys from plist file named after the volume ID.
5 | The plist file must have at least the EMF and DKey fields set.
6 | For now the tool decrypts the data forks but does not mark the files as
7 | "decrypted" : running it twice on the same image will produce garbage.
8 | Interrupting the process will also leave the image "half decrypted".
9 |
10 | Uses planetbeing/dev team HFS implementation
11 | https://github.com/planetbeing/xpwn
12 |
13 | Only builds on Mac OS X, requires CoreFoundation for plist access.
--------------------------------------------------------------------------------
/emf_decrypter/hfs/utility.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | void hfs_panic(const char* hfs_panicString) {
6 | fprintf(stderr, "%s\n", hfs_panicString);
7 | exit(1);
8 | }
9 |
10 | void printUnicode(HFSUniStr255* str) {
11 | int i;
12 |
13 | for(i = 0; i < str->length; i++) {
14 | printf("%c", (char)(str->unicode[i] & 0xff));
15 | }
16 | }
17 |
18 | char* unicodeToAscii(HFSUniStr255* str) {
19 | int i;
20 | char* toReturn;
21 |
22 | toReturn = (char*) malloc(sizeof(char) * (str->length + 1));
23 |
24 | for(i = 0; i < str->length; i++) {
25 | toReturn[i] = (char)(str->unicode[i] & 0xff);
26 | }
27 | toReturn[i] = '\0';
28 |
29 | return toReturn;
30 | }
31 |
--------------------------------------------------------------------------------
/old/emf_decrypter/hfs/utility.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | void hfs_panic(const char* hfs_panicString) {
6 | fprintf(stderr, "%s\n", hfs_panicString);
7 | exit(1);
8 | }
9 |
10 | void printUnicode(HFSUniStr255* str) {
11 | int i;
12 |
13 | for(i = 0; i < str->length; i++) {
14 | printf("%c", (char)(str->unicode[i] & 0xff));
15 | }
16 | }
17 |
18 | char* unicodeToAscii(HFSUniStr255* str) {
19 | int i;
20 | char* toReturn;
21 |
22 | toReturn = (char*) malloc(sizeof(char) * (str->length + 1));
23 |
24 | for(i = 0; i < str->length; i++) {
25 | toReturn[i] = (char)(str->unicode[i] & 0xff);
26 | }
27 | toReturn[i] = '\0';
28 |
29 | return toReturn;
30 | }
31 |
--------------------------------------------------------------------------------
/ramdisk_tools/bsdcrypto/sha1.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: sha1.h,v 1.5 2007/09/10 22:19:42 henric Exp $ */
2 |
3 | /*
4 | * SHA-1 in C
5 | * By Steve Reid
6 | * 100% Public Domain
7 | */
8 |
9 | #ifndef _SHA1_H_
10 | #define _SHA1_H_
11 |
12 | #define SHA1_BLOCK_LENGTH 64
13 | #define SHA1_DIGEST_LENGTH 20
14 |
15 | typedef struct {
16 | u_int32_t state[5];
17 | u_int64_t count;
18 | unsigned char buffer[SHA1_BLOCK_LENGTH];
19 | } SHA1_CTX;
20 |
21 | void SHA1Init(SHA1_CTX * context);
22 | void SHA1Transform(u_int32_t state[5], const unsigned char buffer[SHA1_BLOCK_LENGTH]);
23 | void SHA1Update(SHA1_CTX *context, const unsigned char *data, unsigned int len);
24 | void SHA1Final(unsigned char digest[SHA1_DIGEST_LENGTH], SHA1_CTX *context);
25 |
26 | #endif /* _SHA1_H_ */
27 |
--------------------------------------------------------------------------------
/python_scripts/keychain/managedconfiguration.py:
--------------------------------------------------------------------------------
1 | """
2 | 0
3 | 1:MCSHA256DigestWithSalt
4 | 2:SecKeyFromPassphraseDataHMACSHA1
5 | """
6 | from crypto.PBKDF2 import PBKDF2
7 | import plistlib
8 | import hashlib
9 |
10 | SALT1 = "F92F024CA2CB9754".decode("hex")
11 |
12 | hashMethods={
13 | 1: (lambda p,salt:hashlib.sha256(SALT1 + p)),
14 | 2: (lambda p,salt:PBKDF2(p, salt, iterations=1000).read(20))
15 | }
16 |
17 | def bruteforce_old_pass(h):
18 | salt = h["salt"].data
19 | hash = h["hash"].data
20 | f = hashMethods.get(h["hashMethod"])
21 |
22 | if f:
23 | print "Bruteforcing hash %s (4 digits)" % hash.encode("hex")
24 | for i in xrange(10000):
25 | p = "%04d" % (i % 10000)
26 | if f(p,salt) == hash:
27 | return p
28 |
--------------------------------------------------------------------------------
/emf_decrypter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.6)
2 | set(CMAKE_LEGACY_CYGWIN_WIN32 0)
3 |
4 | project (XPwn)
5 |
6 | # We want win32 executables to build staticly by default, since it's more difficult to keep the shared libraries straight on Windows
7 | IF(WIN32)
8 | SET(BUILD_STATIC ON CACHE BOOL "Force compilation with static libraries")
9 | ELSE(WIN32)
10 | SET(BUILD_STATIC OFF CACHE BOOL "Force compilation with static libraries")
11 | ENDIF(WIN32)
12 |
13 | IF(BUILD_STATIC)
14 | SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
15 | ENDIF(BUILD_STATIC)
16 |
17 | include_directories (${PROJECT_SOURCE_DIR}/includes)
18 |
19 | add_subdirectory (common)
20 | add_subdirectory (hfs)
21 | add_subdirectory (emf)
22 |
23 | IF(WIN32 OR APPLE)
24 | SET(CPACK_GENERATOR "ZIP")
25 | ELSE(WIN32 OR APPLE)
26 | SET(CPACK_GENERATOR "TBZ2")
27 | ENDIF(WIN32 OR APPLE)
28 |
29 | INCLUDE(CPack)
30 |
--------------------------------------------------------------------------------
/old/emf_decrypter/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.6)
2 | set(CMAKE_LEGACY_CYGWIN_WIN32 0)
3 |
4 | project (XPwn)
5 |
6 | # We want win32 executables to build staticly by default, since it's more difficult to keep the shared libraries straight on Windows
7 | IF(WIN32)
8 | SET(BUILD_STATIC ON CACHE BOOL "Force compilation with static libraries")
9 | ELSE(WIN32)
10 | SET(BUILD_STATIC OFF CACHE BOOL "Force compilation with static libraries")
11 | ENDIF(WIN32)
12 |
13 | IF(BUILD_STATIC)
14 | SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
15 | ENDIF(BUILD_STATIC)
16 |
17 | include_directories (${PROJECT_SOURCE_DIR}/includes)
18 |
19 | add_subdirectory (common)
20 | add_subdirectory (hfs)
21 | add_subdirectory (emf)
22 |
23 | IF(WIN32 OR APPLE)
24 | SET(CPACK_GENERATOR "ZIP")
25 | ELSE(WIN32 OR APPLE)
26 | SET(CPACK_GENERATOR "TBZ2")
27 | ENDIF(WIN32 OR APPLE)
28 |
29 | INCLUDE(CPack)
30 |
--------------------------------------------------------------------------------
/python_scripts/emf_undelete.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | import os
3 | import sys
4 | from hfs.emf import EMFVolume
5 | from hfs.journal import do_emf_carving
6 | from util.bdev import FileBlockDevice
7 |
8 | if __name__ == "__main__":
9 | if len(sys.argv) < 2:
10 | print "Usage: emf_undelete.py disk_image.bin"
11 | sys.exit(0)
12 | filename = sys.argv[1]
13 | volume = EMFVolume(FileBlockDevice(filename), None)
14 | dirname = os.path.dirname(filename)
15 | if dirname == "":
16 | dirname = "."
17 | outdir = dirname + "/" + volume.volumeID().encode("hex") + "_" + os.path.basename(filename)
18 | carveokdir = outdir + "/undelete/"
19 | carvenokdir = outdir + "/junk/"
20 | try:
21 | os.makedirs(carveokdir)
22 | os.makedirs(carvenokdir)
23 | except:
24 | pass
25 |
26 | do_emf_carving(volume, carveokdir, carvenokdir)
27 |
--------------------------------------------------------------------------------
/python_scripts/util/asciitables.py:
--------------------------------------------------------------------------------
1 |
2 | def print_table(title, headers, rows):
3 | widths = []
4 |
5 | for i in xrange(len(headers)):
6 | z = map(len, [str(row[i]) for row in rows])
7 | z.append(len(headers[i]))
8 | widths.append(max(z))
9 |
10 | width = sum(widths) + len(headers) + 1
11 | print "-"* width
12 | print "|" + title.center(width-2) + "|"
13 | print "-"* width
14 | hline = "|"
15 | for i in xrange(len(headers)):
16 | hline += headers[i].ljust(widths[i]) + "|"
17 | print hline
18 |
19 | print "-"* width
20 | for row in rows:
21 | line = "|"
22 | for i in xrange(len(row)):
23 | line += str(row[i]).ljust(widths[i]) + "|"
24 | print line
25 |
26 | if len(rows) == 0:
27 | print "|" + "No entries".center(width-2) + "|"
28 | print "-"* width
29 | print ""
30 |
--------------------------------------------------------------------------------
/python_scripts/firmware/scfg.py:
--------------------------------------------------------------------------------
1 | from construct.core import Struct
2 | from construct.macros import *
3 | from construct import RepeatUntil, OneOf
4 | from util import hexdump
5 |
6 | SCFGItem = Struct("SCFGItem",
7 | String("tag", 4),
8 | String("data", 16, padchar="\x00")
9 | )
10 |
11 | SCFG = Struct("SCFG",
12 | OneOf(String("magic", 4), ["gfCS"]),
13 | ULInt32("length"),
14 | ULInt32("unk1"),
15 | ULInt32("unk2"),
16 | ULInt32("unk3"),
17 | ULInt32("unk4")
18 | )
19 |
20 | def parse_SCFG(data):
21 | res = {}
22 | scfg = SCFG.parse(data)
23 | assert scfg.length > 0x18
24 | for i in Array((scfg.length - 0x18) / 20, SCFGItem).parse(data[0x18:scfg.length]):
25 | if i.tag != "\xFF\xFF\xFF\xFF":
26 | res[str(i.tag)[::-1]] = str(i.data)
27 | return res
28 |
--------------------------------------------------------------------------------
/make_ramdisk_n92ap.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | for VER in 7.0
4 | do
5 | #if [ -f "/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS$VER.sdk/System/Library/Frameworks/IOKit.framework/IOKit" ];
6 | if [ -f "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit" ];
7 | then
8 | SDKVER=$VER
9 | echo "Found iOS SDK $SDKVER"
10 | break
11 | fi
12 | done
13 | if [ "$SDKVER" == "" ]; then
14 | echo "iOS SDK not found"
15 | exit
16 | fi
17 | SDKVER=$SDKVER make -C ramdisk_tools
18 |
19 | ./build_ramdisk.sh iPhone3,3_5.0.1_9A405_Restore.ipsw 038-3715-001.dmg 3aeab4ceb61e011f3013873998bfcf01c585bb548f91e19c9085473f93f6a708 02d55437d1fd7c9d24aeb312a78dbd49 myramdisk_n92ap.dmg
20 |
21 | if [ "$?" == "0" ]
22 | then
23 | echo "You can boot the ramdisk using the following command (fix paths)"
24 | echo "redsn0w -i iPhone3,3_5.0.1_9A405_Restore.ipsw -r myramdisk_n92ap.dmg -k kernelcache.release.n92.patched"
25 | echo "Add -a \"-v rd=md0 nand-disable=1\" for nand dump/read only access"
26 | fi
27 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/hfs/hfslib.h:
--------------------------------------------------------------------------------
1 | #include "common.h"
2 | #include "hfsplus.h"
3 | #include "abstractfile.h"
4 |
5 | #ifdef __cplusplus
6 | extern "C" {
7 | #endif
8 | void writeToFile(HFSPlusCatalogFile* file, AbstractFile* output, Volume* volume);
9 | void writeToHFSFile(HFSPlusCatalogFile* file, AbstractFile* input, Volume* volume);
10 | void get_hfs(Volume* volume, const char* inFileName, AbstractFile* output);
11 | int add_hfs(Volume* volume, AbstractFile* inFile, const char* outFileName);
12 | void grow_hfs(Volume* volume, uint64_t newSize);
13 | void removeAllInFolder(HFSCatalogNodeID folderID, Volume* volume, const char* parentName);
14 | void addAllInFolder(HFSCatalogNodeID folderID, Volume* volume, const char* parentName);
15 | void addall_hfs(Volume* volume, const char* dirToMerge, const char* dest);
16 | void extractAllInFolder(HFSCatalogNodeID folderID, Volume* volume);
17 | int copyAcrossVolumes(Volume* volume1, Volume* volume2, char* path1, char* path2);
18 |
19 | void hfs_untar(Volume* volume, AbstractFile* tarFile);
20 | void hfs_ls(Volume* volume, const char* path);
21 | void hfs_setsilence(int s);
22 | #ifdef __cplusplus
23 | }
24 | #endif
25 |
26 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/hfs/hfslib.h:
--------------------------------------------------------------------------------
1 | #include "common.h"
2 | #include "hfsplus.h"
3 | #include "abstractfile.h"
4 |
5 | #ifdef __cplusplus
6 | extern "C" {
7 | #endif
8 | void writeToFile(HFSPlusCatalogFile* file, AbstractFile* output, Volume* volume);
9 | void writeToHFSFile(HFSPlusCatalogFile* file, AbstractFile* input, Volume* volume);
10 | void get_hfs(Volume* volume, const char* inFileName, AbstractFile* output);
11 | int add_hfs(Volume* volume, AbstractFile* inFile, const char* outFileName);
12 | void grow_hfs(Volume* volume, uint64_t newSize);
13 | void removeAllInFolder(HFSCatalogNodeID folderID, Volume* volume, const char* parentName);
14 | void addAllInFolder(HFSCatalogNodeID folderID, Volume* volume, const char* parentName);
15 | void addall_hfs(Volume* volume, const char* dirToMerge, const char* dest);
16 | void extractAllInFolder(HFSCatalogNodeID folderID, Volume* volume);
17 | int copyAcrossVolumes(Volume* volume1, Volume* volume2, char* path1, char* path2);
18 |
19 | void hfs_untar(Volume* volume, AbstractFile* tarFile);
20 | void hfs_ls(Volume* volume, const char* path);
21 | void hfs_setsilence(int s);
22 | #ifdef __cplusplus
23 | }
24 | #endif
25 |
26 |
--------------------------------------------------------------------------------
/ramdisk_tools/bsdcrypto/pbkdf2.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: pbkdf2.h,v 1.1 2008/06/14 06:28:27 djm Exp $ */
2 |
3 | /*-
4 | * Copyright (c) 2008 Damien Bergamini
5 | *
6 | * Permission to use, copy, modify, and distribute this software for any
7 | * purpose with or without fee is hereby granted, provided that the above
8 | * copyright notice and this permission notice appear in all copies.
9 | *
10 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 | */
18 |
19 | /*
20 | * Password-Based Key Derivation Function 2 (PKCS #5 v2.0).
21 | * Code based on IEEE Std 802.11-2007, Annex H.4.2.
22 | */
23 | int pkcs5_pbkdf2(const char *, size_t, const char *, size_t,
24 | u_int8_t *, size_t, u_int);
25 |
--------------------------------------------------------------------------------
/ramdisk_tools/ioflash/externalMethod.h:
--------------------------------------------------------------------------------
1 | unsigned char externalMethod_bin[] = {
2 | 0x2d, 0xe9, 0xf0, 0x4f, 0x96, 0xb0, 0xdf, 0xf8, 0xa0, 0xb0, 0xfb, 0x44,
3 | 0x04, 0x46, 0xd6, 0x69, 0x00, 0x25, 0xd2, 0xf8, 0x30, 0x70, 0x01, 0x22,
4 | 0x30, 0x68, 0x01, 0x90, 0x70, 0x68, 0x00, 0x90, 0x01, 0x20, 0x03, 0x90,
5 | 0x02, 0x95, 0x71, 0x7a, 0x11, 0xf0, 0x01, 0x0f, 0x1c, 0xbf, 0x09, 0x21,
6 | 0x02, 0x91, 0x05, 0x95, 0x08, 0x95, 0x11, 0x95, 0x0f, 0x95, 0x0d, 0x95,
7 | 0x04, 0x90, 0x01, 0xa8, 0x06, 0x90, 0x68, 0x46, 0x0b, 0x90, 0xd6, 0xe9,
8 | 0x03, 0x01, 0xe3, 0x6f, 0xd8, 0x47, 0x07, 0x90, 0x70, 0x69, 0x08, 0xb9,
9 | 0x2e, 0x46, 0x11, 0xe0, 0xb0, 0x69, 0x01, 0x22, 0x0d, 0x90, 0x70, 0x69,
10 | 0xb1, 0x69, 0xe3, 0x6f, 0xd8, 0x47, 0x29, 0x46, 0x05, 0x46, 0x2a, 0x68,
11 | 0xd2, 0xf8, 0x98, 0x20, 0x90, 0x47, 0x06, 0x46, 0x31, 0x68, 0x89, 0x6b,
12 | 0x88, 0x47, 0x0c, 0x90, 0xa0, 0x6f, 0x02, 0xaa, 0x01, 0x68, 0xd1, 0xf8,
13 | 0x4c, 0x33, 0x00, 0x21, 0x98, 0x47, 0xc7, 0xf8, 0x00, 0x00, 0x07, 0x98,
14 | 0x01, 0x68, 0x4c, 0x69, 0xa0, 0x47, 0x1e, 0xb1, 0x30, 0x46, 0xa0, 0x47,
15 | 0x28, 0x46, 0xa0, 0x47, 0x00, 0x20, 0x16, 0xb0, 0xbd, 0xe8, 0xf0, 0x8f
16 | };
17 | unsigned int externalMethod_bin_len = 168;
18 |
--------------------------------------------------------------------------------
/ramdisk_tools/AppleEffaceableStorage.h:
--------------------------------------------------------------------------------
1 | /*
2 | AppleEffaceableStorage
3 | 0 : getCapacity
4 | 1 : getBytes (kernel debug)
5 | 2 : setBytes (kernel debug)
6 | 3 : isFormatted
7 | 4 : format
8 | 5 : getLocker
9 | 6 : setLocker
10 | 7 : effaceLocker
11 | 8 : lockerSpace
12 | */
13 | #define kAppleEffaceableStorageGetBytes 1
14 | #define kAppleEffaceableStorageGetLocker 5
15 |
16 |
17 | #define LOCKER_DKEY 0x446B6579
18 | #define LOCKER_EMF 0x454D4621
19 | #define LOCKER_BAG1 0x42414731
20 | #define LOCKER_LWVM 0x4C77564d
21 |
22 | struct EffaceableLocker
23 | {
24 | unsigned short magic; //0x4c6B = "kL"
25 | unsigned short len;
26 | unsigned int tag; //BAG1, EMF, Dkey, DONE
27 | unsigned char data[1];
28 | };
29 |
30 | struct BAG1Locker
31 | {
32 | unsigned int magic;//'BAG1';
33 | unsigned char iv[16];
34 | unsigned char key[32];
35 | };
36 |
37 | int AppleEffaceableStorage__getLocker(uint32_t lockerId, uint8_t* buffer, size_t len);
38 | int AppleEffaceableStorage__getBytes(uint8_t* buffer, size_t len);
39 | int AppleEffaceableStorage__getLockerFromBytes(uint32_t tag, uint8_t* lockers, size_t lockers_len, uint8_t* buffer, size_t len);
40 |
41 |
--------------------------------------------------------------------------------
/emf_decrypter/emf/emf.h:
--------------------------------------------------------------------------------
1 | //As of iOS 4, class keys 1 to 4 are used for files, class 5 usage is unknown
2 | #define MAX_CLASS_KEYS 5
3 | #define CLASS_DKEY 4
4 |
5 | typedef struct EMFInfo
6 | {
7 | Volume* volume;
8 | uint64_t volume_id;
9 | uint64_t volume_offset;
10 | uint32_t classKeys_bitset;
11 | AES_KEY emfkey;
12 | AES_KEY classKeys[MAX_CLASS_KEYS];
13 | }EMFInfo;
14 |
15 | EMFInfo* EMF_init(Volume*, char*);
16 |
17 | #define CPROTECT_V2_LENGTH 0x38 //56
18 | #define CP_WRAPPEDKEYSIZE 40 /* 2x4 = 8, 8x8 = 64 */
19 |
20 | //http://www.opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
21 | typedef struct cprotect_xattr_v2
22 | {
23 | uint16_t xattr_major_version; // =2
24 | uint16_t xattr_minor_version; // =0
25 | uint32_t flags; // leaks stack dword in one code path (cp_handle_vnop)
26 | uint32_t persistent_class;
27 | uint32_t key_size; //0x28
28 | uint8_t persistent_key[0x28];
29 | } cprotect_xattr_v2;
30 |
31 | #define CPROTECT_V4_LENGTH 0x4C //76
32 |
33 | typedef struct cprotect_xattr_v4
34 | {
35 | uint16_t xattr_major_version; // =4
36 | uint16_t xattr_minor_version; // =0
37 | uint32_t xxx_length; // 0xc
38 | uint32_t protection_class_id;
39 | uint32_t wrapped_length; //0x28
40 | uint8_t xxx_junk[20]; //uninitialized ?
41 | uint8_t wrapped_key[0x28];
42 | } cprotect_xattr_v4;
--------------------------------------------------------------------------------
/old/emf_decrypter/emf/emf.h:
--------------------------------------------------------------------------------
1 | //As of iOS 4, class keys 1 to 4 are used for files, class 5 usage is unknown
2 | #define MAX_CLASS_KEYS 5
3 | #define CLASS_DKEY 4
4 |
5 | typedef struct EMFInfo
6 | {
7 | Volume* volume;
8 | uint64_t volume_id;
9 | uint64_t volume_offset;
10 | uint32_t classKeys_bitset;
11 | AES_KEY emfkey;
12 | AES_KEY classKeys[MAX_CLASS_KEYS];
13 | }EMFInfo;
14 |
15 | EMFInfo* EMF_init(Volume*, char*);
16 |
17 | #define CPROTECT_V2_LENGTH 0x38 //56
18 | #define CP_WRAPPEDKEYSIZE 40 /* 2x4 = 8, 8x8 = 64 */
19 |
20 | //http://www.opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
21 | typedef struct cprotect_xattr_v2
22 | {
23 | uint16_t xattr_major_version; // =2
24 | uint16_t xattr_minor_version; // =0
25 | uint32_t flags; // leaks stack dword in one code path (cp_handle_vnop)
26 | uint32_t persistent_class;
27 | uint32_t key_size; //0x28
28 | uint8_t persistent_key[0x28];
29 | } cprotect_xattr_v2;
30 |
31 | #define CPROTECT_V4_LENGTH 0x4C //76
32 |
33 | typedef struct cprotect_xattr_v4
34 | {
35 | uint16_t xattr_major_version; // =4
36 | uint16_t xattr_minor_version; // =0
37 | uint32_t xxx_length; // 0xc
38 | uint32_t protection_class_id;
39 | uint32_t wrapped_length; //0x28
40 | uint8_t xxx_junk[20]; //uninitialized ?
41 | uint8_t wrapped_key[0x28];
42 | } cprotect_xattr_v4;
--------------------------------------------------------------------------------
/ramdisk_tools/IOAESAccelerator.h:
--------------------------------------------------------------------------------
1 | #define kIOAESAcceleratorInfo 0
2 | #define kIOAESAcceleratorTask 1
3 | #define kIOAESAcceleratorTest 2
4 |
5 | #define kIOAESAcceleratorEncrypt 0
6 | #define kIOAESAcceleratorDecrypt 1
7 |
8 | #define kIOAESAcceleratorGIDMask 0x3E8
9 | #define kIOAESAcceleratorUIDMask 0x7D0
10 | #define kIOAESAcceleratorUIDPlusMask 0x7D1
11 | #define kIOAESAcceleratorCustomMask 0
12 |
13 | typedef struct//sizeof=0x2C
14 | {
15 | uint32_t data_length;
16 | char data[0x20];
17 | uint32_t one;//=1
18 | uint32_t zzz;
19 | } IOAES_UIDPlus_Params;
20 |
21 | typedef struct
22 | {
23 | void* cleartext;
24 | void* ciphertext;
25 | uint32_t size;
26 | uint8_t iv[16];
27 | uint32_t mode;
28 | uint32_t bits;
29 | uint8_t keybuf[32];
30 | uint32_t mask;
31 | uint32_t length_of_uidplus_params; //ios 4.2.1
32 | IOAES_UIDPlus_Params uidplus_params;
33 | } IOAESStruct;
34 |
35 | #define IOAESStruct_size41 (sizeof(IOAESStruct))
36 | #define IOAESStruct_sizeold (sizeof(IOAESStruct) - 4)
37 |
38 | void aes_init();
39 | io_connect_t IOAESAccelerator_getIOconnect();
40 | int doAES(void* cleartext, void *ciphertext, uint32_t size, uint32_t keyMask, void* key, void* iv, int mode, int bits);
41 | int AES_UID_Encrypt(void* cleartext, void* ciphertext, size_t len);
42 |
43 | uint8_t* IOAES_key835();
44 | uint8_t* IOAES_key89A();
45 | uint8_t* IOAES_key89B();
46 |
47 |
--------------------------------------------------------------------------------
/python_scripts/emf_decrypter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | from optparse import OptionParser
3 | from hfs.emf import EMFVolume
4 | from util.bdev import FileBlockDevice
5 | import plistlib
6 |
7 | def main():
8 | parser = OptionParser(usage="emf_decrypter.py disk_image.bin")
9 | parser.add_option("-w", "--nowrite", dest="write", action="store_false", default=True,
10 | help="disable modifications of input file, for testing")
11 | (options, args) = parser.parse_args()
12 | if len(args) < 1:
13 | parser.print_help()
14 | return
15 | device_infos = None
16 | if len(args) >= 2: device_infos = plistlib.readPlist(args[1])
17 |
18 | p = FileBlockDevice(args[0], 0, options.write)
19 | v = EMFVolume(p, device_infos)
20 | if not v.keybag.unlocked:
21 | print "Keybag locked, protected files won't be decrypted, continue anyway ?"
22 | if raw_input() == "n":
23 | return
24 | if options.write:
25 | print "WARNING ! This tool will modify the hfs image and possibly wreck it if something goes wrong !"
26 | print "Make sure to backup the image before proceeding"
27 | print "You can use the --nowrite option to do a dry run instead"
28 | else:
29 | print "Test mode : the input file will not be modified"
30 | print "Press a key to continue or CTRL-C to abort"
31 | raw_input()
32 | v.decryptAllFiles()
33 |
34 | if __name__ == "__main__":
35 | main()
36 |
--------------------------------------------------------------------------------
/python_scripts/crypto/aes.py:
--------------------------------------------------------------------------------
1 | from Crypto.Cipher import AES
2 |
3 | ZEROIV = "\x00"*16
4 | def removePadding(blocksize, s):
5 | 'Remove rfc 1423 padding from string.'
6 | n = ord(s[-1]) # last byte contains number of padding bytes
7 | if n > blocksize or n > len(s):
8 | raise Exception('invalid padding')
9 | return s[:-n]
10 |
11 |
12 | def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
13 | if len(data) % 16:
14 | print "AESdecryptCBC: data length not /16, truncating"
15 | data = data[0:(len(data)/16) * 16]
16 | data = AES.new(key, AES.MODE_CBC, iv).decrypt(data)
17 | if padding:
18 | return removePadding(16, data)
19 | return data
20 |
21 | def AESencryptCBC(data, key, iv=ZEROIV, padding=False):
22 | if len(data) % 16:
23 | print "AESencryptCBC: data length not /16, truncating"
24 | data = data[0:(len(data)/16) * 16]
25 | data = AES.new(key, AES.MODE_CBC, iv).encrypt(data)
26 | return data
27 |
28 | #pycrypto MODE_CFB seems to give wrong results on icloud chunks ?
29 | def AESdecryptCFB(data, key, iv=ZEROIV):
30 | res = ""
31 | a = AES.new(key)
32 | ks = a.encrypt(iv)
33 |
34 | for i in xrange(0,len(data), 16):
35 | block = data[i:i+16]
36 | for j in xrange(0, len(block)):
37 | res += chr(ord(block[j]) ^ ord(ks[j]))
38 | if len(block) == 16:
39 | ks = a.encrypt(block)
40 | return res
41 |
--------------------------------------------------------------------------------
/ramdisk_tools/device_infos.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include "device_info.h"
5 | #include "util.h"
6 |
7 | int main(int argc, char* argv[])
8 | {
9 | CFMutableDictionaryRef out = device_info(-1, NULL);
10 |
11 | if (out == NULL)
12 | {
13 | fprintf(stderr, "device_info(-1, NULL) failed\n");
14 | return -1;
15 | }
16 |
17 | if (argc > 1 )
18 | {
19 | CFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault, argv[1], kCFStringEncodingASCII);
20 | CFTypeRef value = CFDictionaryGetValue(out, key);
21 | if (value != NULL)
22 | {
23 | *stderr = *stdout;//HAX
24 | CFShow(value);
25 | }
26 | else
27 | fprintf(stderr, "key %s not found\n", argv[1]);
28 | CFRelease(key);
29 | CFRelease(out);
30 | return 0;
31 | }
32 |
33 | writePlistToStdout(out);
34 | /*CFStringRef plistFileName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@.plist"), CFDictionaryGetValue(out, CFSTR("dataVolumeUUID")));
35 |
36 | CFStringRef printString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Writing results to %@\n"), plistFileName);
37 | CFShow(printString);
38 | CFRelease(printString);
39 |
40 | saveResults(plistFileName, out);
41 | CFRelease(plistFileName);*/
42 | CFRelease(out);
43 | return 0;
44 | }
45 |
--------------------------------------------------------------------------------
/python_scripts/demo_escrow.py:
--------------------------------------------------------------------------------
1 | import os
2 | import plistlib
3 | from keystore.keybag import Keybag
4 | from util.ramdiskclient import RamdiskToolClient
5 |
6 | """
7 | this wont work on iOS 5 unless the passcode was already bruteforced
8 | """
9 | def escrow():
10 | client = RamdiskToolClient()
11 | di = client.getDeviceInfos()
12 | key835 = di.get("key835").decode("hex")
13 |
14 | plist = os.environ["ALLUSERSPROFILE"] + "/Apple/Lockdown/%s.plist" % di["udid"]
15 | lockdown = plistlib.readPlist(plist)
16 | kb = Keybag.createWithDataSignBlob(lockdown["EscrowBag"].data, key835)
17 |
18 | keybags = di.setdefault("keybags", {})
19 | kbuuid = kb.uuid.encode("hex")
20 | if not keybags.has_key(kbuuid):
21 | print lockdown["HostID"]
22 | res = client.getEscrowRecord(lockdown["HostID"])
23 | bagkey = res.get("BagKey")
24 | print "Bag key" + bagkey.data.encode("hex")
25 | res = client.getPasscodeKey(lockdown["EscrowBag"].data, bagkey)
26 | print res
27 | passcodeKey = res["passcodeKey"].decode("hex")
28 | keybags[kbuuid] = {"KeyBagKeys": lockdown["EscrowBag"],
29 | "passcode": bagkey,
30 | "passcodeKey": passcodeKey.encode("hex")}
31 | pl.update(keybags[kbuuid])
32 | else:
33 | passcodeKey = keybags[kbuuid].get("passcodeKey").decode("hex")
34 |
35 | print kb.unlockWithPasscodeKey(passcodeKey)
36 | kb.printClassKeys()
37 |
38 | escrow()
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | iOS forensics tools
2 |
3 | Supported devices
4 | (iPhone 2G)
5 | iPhone 3G
6 | iPhone 3GS
7 | iPad 1
8 | iPhone 4 GSM
9 | iPhone 4 GSM rev A
10 | iPhone 4 CDMA
11 | Newer devices are NOT supported
12 |
13 | Requirements
14 | Mac OS X 10.8/10.9
15 | Xcode with iOS SDK (open Xcode to accept the license agreement)
16 | redsn0w_mac_0.9.15b3 (downloaded by build.py)
17 | Supported IPSW for the target device in data/ipsw (downloaded by build.py)
18 |
19 | Building a custom ramdisk
20 | Run ./build.py DEVICE_NAME to create the patched kernel + custom ramdisk
21 | IPSW wont match the installed iOS version on the device, this is normal
22 | Use ./boot.py to start redsn0w with the correct parameters, then place the device in DFU mode
23 |
24 | ./build_ramdisk_v2.sh can be used to recompile ramdisk_tools and update existing ramdisks (data/boot/*.dmg)
25 |
26 | SSH access
27 | Boot using ./boot.py wait for "OK" on screen
28 | Run ./tcprelay.sh in a new terminal window
29 | Run ssh -p 2222 root@localhost
30 | root password is alpine
31 |
32 | Python scripts
33 | Install dependencies
34 | sudo easy_install M2crypto construct progressbar setuptools pyasn1 protobuf
35 | sudo ARCHFLAGS='-arch i386 -arch x86_64' easy_install pycrypto
36 | M2Crypto for OS X 10.9
37 | curl -O http://chandlerproject.org/pub/Projects/MeTooCrypto/M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
38 | sudo easy_install M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
39 |
40 |
--------------------------------------------------------------------------------
/ramdisk_tools/bsdcrypto/key_wrap.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: key_wrap.h,v 1.1 2008/08/12 15:43:00 damien Exp $ */
2 |
3 | /*-
4 | * Copyright (c) 2008 Damien Bergamini
5 | *
6 | * Permission to use, copy, modify, and distribute this software for any
7 | * purpose with or without fee is hereby granted, provided that the above
8 | * copyright notice and this permission notice appear in all copies.
9 | *
10 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 | */
18 |
19 | #ifndef _KEY_WRAP_H_
20 | #define _KEY_WRAP_H_
21 |
22 | typedef unsigned char u_int8_t;
23 |
24 | typedef struct _aes_key_wrap_ctx {
25 | rijndael_ctx ctx;
26 | } aes_key_wrap_ctx;
27 |
28 | #include
29 |
30 | __BEGIN_DECLS
31 |
32 | void aes_key_wrap_set_key(aes_key_wrap_ctx *, const u_int8_t *, size_t);
33 | void aes_key_wrap_set_key_wrap_only(aes_key_wrap_ctx *, const u_int8_t *,
34 | size_t);
35 | void aes_key_wrap(aes_key_wrap_ctx *, const u_int8_t *, size_t, u_int8_t *);
36 | int aes_key_unwrap(aes_key_wrap_ctx *, const u_int8_t *, u_int8_t *,
37 | size_t);
38 | __END_DECLS
39 |
40 | #endif /* _KEY_WRAP_H_ */
41 |
--------------------------------------------------------------------------------
/python_scripts/icloud/pbuf.py:
--------------------------------------------------------------------------------
1 | def decode_protobuf_array(data, obj_class):
2 | n = len(data)
3 | i = 0
4 | res = []
5 | while i < n:
6 | (length, i) = _DecodeVarint(data, i)
7 | l3 = obj_class()
8 | l3.ParseFromString(data[i:i+length])
9 | res.append(l3)
10 | i += length
11 | return res
12 |
13 | def encode_protobuf_array(res):
14 | z = ""
15 | for o in res:
16 | d = o.SerializeToString()
17 | z += _EncodeVarint(len(d))
18 | z += d
19 | return z
20 |
21 | #decoder.py
22 | def _VarintDecoder(mask):
23 | local_ord = ord
24 | def DecodeVarint(buffer, pos):
25 | result = 0
26 | shift = 0
27 | while 1:
28 | b = local_ord(buffer[pos])
29 | result |= ((b & 0x7f) << shift)
30 | pos += 1
31 | if not (b & 0x80):
32 | result &= mask
33 | return (result, pos)
34 | shift += 7
35 | if shift >= 64:
36 | raise _DecodeError('Too many bytes when decoding varint.')
37 | return DecodeVarint
38 |
39 | _DecodeVarint = _VarintDecoder((1 << 64) - 1)
40 |
41 |
42 | def _VarintEncoder():
43 | """Return an encoder for a basic varint value (does not include tag)."""
44 |
45 | local_chr = chr
46 | def EncodeVarint( value):
47 | bits = value & 0x7f
48 | value >>= 7
49 | z=""
50 | while value:
51 | z += local_chr(0x80|bits)
52 | bits = value & 0x7f
53 | value >>= 7
54 | return z + local_chr(bits)
55 |
56 | return EncodeVarint
57 |
58 | _EncodeVarint = _VarintEncoder()
59 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/hfs/hfscompress.h:
--------------------------------------------------------------------------------
1 | #ifndef HFSCOMPRESS_H
2 | #define HFSCOMPRESS_H
3 |
4 | #include
5 | #include "common.h"
6 |
7 | #define CMPFS_MAGIC 0x636D7066
8 |
9 | typedef struct HFSPlusDecmpfs {
10 | uint32_t magic;
11 | uint32_t flags;
12 | uint64_t size;
13 | uint8_t data[0];
14 | } __attribute__ ((packed)) HFSPlusDecmpfs;
15 |
16 | typedef struct HFSPlusCmpfRsrcHead {
17 | uint32_t headerSize;
18 | uint32_t totalSize;
19 | uint32_t dataSize;
20 | uint32_t flags;
21 | } __attribute__ ((packed)) HFSPlusCmpfRsrcHead;
22 |
23 | typedef struct HFSPlusCmpfRsrcBlock {
24 | uint32_t offset;
25 | uint32_t size;
26 | } __attribute__ ((packed)) HFSPlusCmpfRsrcBlock;
27 |
28 | typedef struct HFSPlusCmpfRsrcBlockHead {
29 | uint32_t dataSize;
30 | uint32_t numBlocks;
31 | HFSPlusCmpfRsrcBlock blocks[0];
32 | } __attribute__ ((packed)) HFSPlusCmpfRsrcBlockHead;
33 |
34 | typedef struct HFSPlusCmpfEnd {
35 | uint32_t pad[6];
36 | uint16_t unk1;
37 | uint16_t unk2;
38 | uint16_t unk3;
39 | uint32_t magic;
40 | uint32_t flags;
41 | uint64_t size;
42 | uint32_t unk4;
43 | } __attribute__ ((packed)) HFSPlusCmpfEnd;
44 |
45 | typedef struct HFSPlusCompressed {
46 | Volume* volume;
47 | HFSPlusCatalogFile* file;
48 | io_func* io;
49 | size_t decmpfsSize;
50 | HFSPlusDecmpfs* decmpfs;
51 |
52 | HFSPlusCmpfRsrcHead rsrcHead;
53 | HFSPlusCmpfRsrcBlockHead* blocks;
54 |
55 | int dirty;
56 |
57 | uint8_t* cached;
58 | uint32_t cachedStart;
59 | uint32_t cachedEnd;
60 | } HFSPlusCompressed;
61 |
62 | #ifdef __cplusplus
63 | extern "C" {
64 | #endif
65 | void flipHFSPlusDecmpfs(HFSPlusDecmpfs* compressData);
66 | io_func* openHFSPlusCompressed(Volume* volume, HFSPlusCatalogFile* file);
67 | #ifdef __cplusplus
68 | }
69 | #endif
70 |
71 | #endif
72 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/hfs/hfscompress.h:
--------------------------------------------------------------------------------
1 | #ifndef HFSCOMPRESS_H
2 | #define HFSCOMPRESS_H
3 |
4 | #include
5 | #include "common.h"
6 |
7 | #define CMPFS_MAGIC 0x636D7066
8 |
9 | typedef struct HFSPlusDecmpfs {
10 | uint32_t magic;
11 | uint32_t flags;
12 | uint64_t size;
13 | uint8_t data[0];
14 | } __attribute__ ((packed)) HFSPlusDecmpfs;
15 |
16 | typedef struct HFSPlusCmpfRsrcHead {
17 | uint32_t headerSize;
18 | uint32_t totalSize;
19 | uint32_t dataSize;
20 | uint32_t flags;
21 | } __attribute__ ((packed)) HFSPlusCmpfRsrcHead;
22 |
23 | typedef struct HFSPlusCmpfRsrcBlock {
24 | uint32_t offset;
25 | uint32_t size;
26 | } __attribute__ ((packed)) HFSPlusCmpfRsrcBlock;
27 |
28 | typedef struct HFSPlusCmpfRsrcBlockHead {
29 | uint32_t dataSize;
30 | uint32_t numBlocks;
31 | HFSPlusCmpfRsrcBlock blocks[0];
32 | } __attribute__ ((packed)) HFSPlusCmpfRsrcBlockHead;
33 |
34 | typedef struct HFSPlusCmpfEnd {
35 | uint32_t pad[6];
36 | uint16_t unk1;
37 | uint16_t unk2;
38 | uint16_t unk3;
39 | uint32_t magic;
40 | uint32_t flags;
41 | uint64_t size;
42 | uint32_t unk4;
43 | } __attribute__ ((packed)) HFSPlusCmpfEnd;
44 |
45 | typedef struct HFSPlusCompressed {
46 | Volume* volume;
47 | HFSPlusCatalogFile* file;
48 | io_func* io;
49 | size_t decmpfsSize;
50 | HFSPlusDecmpfs* decmpfs;
51 |
52 | HFSPlusCmpfRsrcHead rsrcHead;
53 | HFSPlusCmpfRsrcBlockHead* blocks;
54 |
55 | int dirty;
56 |
57 | uint8_t* cached;
58 | uint32_t cachedStart;
59 | uint32_t cachedEnd;
60 | } HFSPlusCompressed;
61 |
62 | #ifdef __cplusplus
63 | extern "C" {
64 | #endif
65 | void flipHFSPlusDecmpfs(HFSPlusDecmpfs* compressData);
66 | io_func* openHFSPlusCompressed(Volume* volume, HFSPlusCatalogFile* file);
67 | #ifdef __cplusplus
68 | }
69 | #endif
70 |
71 | #endif
72 |
--------------------------------------------------------------------------------
/python_scripts/keychain/keychain3.py:
--------------------------------------------------------------------------------
1 | from keychain import Keychain
2 | from crypto.aes import AESdecryptCBC, AESencryptCBC
3 | import hashlib
4 |
5 | class Keychain3(Keychain):
6 | def __init__(self, filename, key835=None):
7 | Keychain.__init__(self, filename)
8 | self.key835 = key835
9 |
10 | def decrypt_data(self, data):
11 | if data == None:
12 | return ""
13 | data = str(data)
14 |
15 | if not self.key835:
16 | print "Key 835 not availaible"
17 | return ""
18 |
19 | data = AESdecryptCBC(data[16:], self.key835, data[:16], padding=True)
20 |
21 | #data_column = iv + AES128_K835(iv, data + sha1(data))
22 | if hashlib.sha1(data[:-20]).digest() != data[-20:]:
23 | print "data field hash mismatch : bad key ?"
24 | return "ERROR decrypting data : bad key ?"
25 |
26 | return data[:-20]
27 |
28 | def change_key835(self, newkey):
29 | tables = {"genp": "SELECT rowid, data FROM genp",
30 | "inet": "SELECT rowid, data FROM inet",
31 | "cert": "SELECT rowid, data FROM cert",
32 | "keys": "SELECT rowid, data FROM keys"}
33 |
34 | for t in tables.keys():
35 | for row in self.conn.execute(tables[t]):
36 | rowid = row["rowid"]
37 | data = str(row["data"])
38 | iv = data[:16]
39 | data = AESdecryptCBC(data[16:], self.key835, iv)
40 | data = AESencryptCBC(data, newkey, iv)
41 | data = iv + data
42 | data = buffer(data)
43 | self.conn.execute("UPDATE %s SET data=? WHERE rowid=?" % t, (data, rowid))
44 | self.conn.commit()
--------------------------------------------------------------------------------
/python_scripts/keychain/store.py:
--------------------------------------------------------------------------------
1 | import plistlib
2 | import sqlite3
3 | import struct
4 | from util import readPlist
5 |
6 | class KeychainStore(object):
7 | def __init__(self):
8 | pass
9 |
10 | def convertDict(self, d):
11 | return d
12 |
13 | def returnResults(self, r):
14 | for a in r:
15 | yield self.convertDict(a)
16 |
17 | def get_items(self, table):
18 | return []
19 |
20 | class SQLiteKeychain(KeychainStore):
21 | def __init__(self, filename):
22 | self.conn = sqlite3.connect(filename)
23 | self.conn.row_factory = sqlite3.Row
24 |
25 | def convertDict(self, row):
26 | d = dict(row)
27 | for k,v in d.items():
28 | if type(v) == buffer:
29 | d[k] = str(v)
30 | return d
31 |
32 | def get_items(self, table):
33 | sql = {"genp": "SELECT rowid, data, svce, acct, agrp FROM genp",
34 | "inet": "SELECT rowid, data, acct, srvr, port, agrp FROM inet",
35 | "cert": "SELECT rowid, data, pkhh, agrp FROM cert",
36 | "keys": "SELECT rowid, data, klbl, agrp FROM keys"}
37 | return self.returnResults(self.conn.execute(sql[table]))
38 |
39 | class PlistKeychain(KeychainStore):
40 | def __init__(self, filename):
41 | self.plist = readPlist(filename)
42 |
43 | def convertDict(self, d):
44 | for k, v in d.items():
45 | if isinstance(v, plistlib.Data):
46 | if k == "v_Data":
47 | d["data"] = v.data
48 | elif k == "v_PersistentRef":
49 | #format tablename (4 chars) + rowid (64 bits)
50 | d["rowid"] = struct.unpack("
2 | #include
3 | #include
4 | #include
5 | #include "AppleEffaceableStorage.h"
6 | #include "IOKit.h"
7 |
8 | int AppleEffaceableStorage__getLocker(uint32_t lockerId, uint8_t* buffer, size_t len) {
9 | uint64_t outScalar = 0;
10 | uint32_t one = 1;
11 | uint64_t inScalar = lockerId;
12 |
13 | return IOKit_call("AppleEffaceableStorage",
14 | kAppleEffaceableStorageGetLocker,
15 | &inScalar,
16 | 1,
17 | NULL,
18 | 0,
19 | &outScalar,
20 | &one,
21 | buffer,
22 | &len);
23 | }
24 |
25 | int AppleEffaceableStorage__getBytes(uint8_t* buffer, size_t len)
26 | {
27 | const uint64_t offset = 0;
28 |
29 | return IOKit_call("AppleEffaceableStorage",
30 | kAppleEffaceableStorageGetBytes,
31 | &offset,
32 | 1,
33 | NULL,
34 | 0,
35 | NULL,
36 | NULL,
37 | buffer,
38 | &len);
39 | }
40 |
41 |
42 | int AppleEffaceableStorage__getLockerFromBytes(uint32_t tag, uint8_t* lockers, size_t lockers_len, uint8_t* buffer, size_t len)
43 | {
44 | struct EffaceableLocker* p = (struct EffaceableLocker*) lockers;
45 | unsigned int i=0;
46 |
47 | while (i < lockers_len)
48 | {
49 | //printf("p->magic=%x\n", p->magic);
50 | if (p->magic != 0x4c6B) //'Lk'
51 | break;
52 | if (p->len == 0 || ((i+8+p->len) > lockers_len))
53 | break;
54 | //printf("p->tag=%x\n", p->tag);
55 | if ((p->tag & ~0x80000000) == tag)
56 | {
57 | len = len < p->len ? len : p->len;
58 | memcpy(buffer, p->data, len);
59 | return 0;
60 | }
61 | i = i + 8 + p->len;
62 | p = (struct EffaceableLocker*) (&lockers[i]);
63 | }
64 | return -1;
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/abstractfile.h:
--------------------------------------------------------------------------------
1 | #ifndef ABSTRACTFILE_H
2 | #define ABSTRACTFILE_H
3 |
4 | #include "common.h"
5 | #include
6 |
7 | typedef struct AbstractFile AbstractFile;
8 | typedef struct AbstractFile2 AbstractFile2;
9 |
10 | typedef size_t (*WriteFunc)(AbstractFile* file, const void* data, size_t len);
11 | typedef size_t (*ReadFunc)(AbstractFile* file, void* data, size_t len);
12 | typedef int (*SeekFunc)(AbstractFile* file, off_t offset);
13 | typedef off_t (*TellFunc)(AbstractFile* file);
14 | typedef void (*CloseFunc)(AbstractFile* file);
15 | typedef off_t (*GetLengthFunc)(AbstractFile* file);
16 | typedef void (*SetKeyFunc)(AbstractFile2* file, const unsigned int* key, const unsigned int* iv);
17 |
18 | typedef enum AbstractFileType {
19 | AbstractFileTypeFile,
20 | AbstractFileType8900,
21 | AbstractFileTypeImg2,
22 | AbstractFileTypeImg3,
23 | AbstractFileTypeLZSS,
24 | AbstractFileTypeIBootIM,
25 | AbstractFileTypeMem,
26 | AbstractFileTypeMemFile,
27 | AbstractFileTypeDummy
28 | } AbstractFileType;
29 |
30 | struct AbstractFile {
31 | void* data;
32 | WriteFunc write;
33 | ReadFunc read;
34 | SeekFunc seek;
35 | TellFunc tell;
36 | GetLengthFunc getLength;
37 | CloseFunc close;
38 | AbstractFileType type;
39 | };
40 |
41 | struct AbstractFile2 {
42 | AbstractFile super;
43 | SetKeyFunc setKey;
44 | };
45 |
46 |
47 | typedef struct {
48 | size_t offset;
49 | void** buffer;
50 | size_t bufferSize;
51 | } MemWrapperInfo;
52 |
53 | typedef struct {
54 | size_t offset;
55 | void** buffer;
56 | size_t* bufferSize;
57 | size_t actualBufferSize;
58 | } MemFileWrapperInfo;
59 |
60 | #ifdef __cplusplus
61 | extern "C" {
62 | #endif
63 | AbstractFile* createAbstractFileFromFile(FILE* file);
64 | AbstractFile* createAbstractFileFromDummy();
65 | AbstractFile* createAbstractFileFromMemory(void** buffer, size_t size);
66 | AbstractFile* createAbstractFileFromMemoryFile(void** buffer, size_t* size);
67 | AbstractFile* createAbstractFileFromMemoryFileBuffer(void** buffer, size_t* size, size_t actualBufferSize);
68 | void abstractFilePrint(AbstractFile* file, const char* format, ...);
69 | io_func* IOFuncFromAbstractFile(AbstractFile* file);
70 | #ifdef __cplusplus
71 | }
72 | #endif
73 |
74 | #endif
75 |
76 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/abstractfile.h:
--------------------------------------------------------------------------------
1 | #ifndef ABSTRACTFILE_H
2 | #define ABSTRACTFILE_H
3 |
4 | #include "common.h"
5 | #include
6 |
7 | typedef struct AbstractFile AbstractFile;
8 | typedef struct AbstractFile2 AbstractFile2;
9 |
10 | typedef size_t (*WriteFunc)(AbstractFile* file, const void* data, size_t len);
11 | typedef size_t (*ReadFunc)(AbstractFile* file, void* data, size_t len);
12 | typedef int (*SeekFunc)(AbstractFile* file, off_t offset);
13 | typedef off_t (*TellFunc)(AbstractFile* file);
14 | typedef void (*CloseFunc)(AbstractFile* file);
15 | typedef off_t (*GetLengthFunc)(AbstractFile* file);
16 | typedef void (*SetKeyFunc)(AbstractFile2* file, const unsigned int* key, const unsigned int* iv);
17 |
18 | typedef enum AbstractFileType {
19 | AbstractFileTypeFile,
20 | AbstractFileType8900,
21 | AbstractFileTypeImg2,
22 | AbstractFileTypeImg3,
23 | AbstractFileTypeLZSS,
24 | AbstractFileTypeIBootIM,
25 | AbstractFileTypeMem,
26 | AbstractFileTypeMemFile,
27 | AbstractFileTypeDummy
28 | } AbstractFileType;
29 |
30 | struct AbstractFile {
31 | void* data;
32 | WriteFunc write;
33 | ReadFunc read;
34 | SeekFunc seek;
35 | TellFunc tell;
36 | GetLengthFunc getLength;
37 | CloseFunc close;
38 | AbstractFileType type;
39 | };
40 |
41 | struct AbstractFile2 {
42 | AbstractFile super;
43 | SetKeyFunc setKey;
44 | };
45 |
46 |
47 | typedef struct {
48 | size_t offset;
49 | void** buffer;
50 | size_t bufferSize;
51 | } MemWrapperInfo;
52 |
53 | typedef struct {
54 | size_t offset;
55 | void** buffer;
56 | size_t* bufferSize;
57 | size_t actualBufferSize;
58 | } MemFileWrapperInfo;
59 |
60 | #ifdef __cplusplus
61 | extern "C" {
62 | #endif
63 | AbstractFile* createAbstractFileFromFile(FILE* file);
64 | AbstractFile* createAbstractFileFromDummy();
65 | AbstractFile* createAbstractFileFromMemory(void** buffer, size_t size);
66 | AbstractFile* createAbstractFileFromMemoryFile(void** buffer, size_t* size);
67 | AbstractFile* createAbstractFileFromMemoryFileBuffer(void** buffer, size_t* size, size_t actualBufferSize);
68 | void abstractFilePrint(AbstractFile* file, const char* format, ...);
69 | io_func* IOFuncFromAbstractFile(AbstractFile* file);
70 | #ifdef __cplusplus
71 | }
72 | #endif
73 |
74 | #endif
75 |
76 |
--------------------------------------------------------------------------------
/ramdisk_tools/kernel_patcher.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | mach_port_t kernel_task=0;
9 |
10 | kern_return_t write_kernel(mach_port_t p, void* addr, uint32_t value)
11 | {
12 | pointer_t buf;
13 | unsigned int sz;
14 |
15 | kern_return_t r = vm_write(p, (vm_address_t)addr, (vm_address_t)&value, sizeof(value));
16 | if (r)
17 | {
18 | fprintf(stderr, "vm_write into kernel_task failed\n");
19 | }
20 | else
21 | {
22 | //fix cache issue
23 | vm_read(p, (vm_address_t) addr, sizeof(value), &buf, &sz);
24 | fprintf(stderr, "vm_write into kernel_task OK %x\n", *((uint32_t*) buf));
25 | }
26 | return r;
27 | }
28 |
29 | int patch_IOAESAccelerator()
30 | {
31 | kern_return_t r = task_for_pid(mach_task_self(), 0, &kernel_task);
32 |
33 | if( r != 0)
34 | {
35 | fprintf(stderr, "task_for_pid returned %x : missing tfp0 kernel patch or wrong entitlements\n", r);
36 | return 0;
37 | }
38 | uint32_t i;
39 | pointer_t buf;
40 | unsigned int sz;
41 |
42 | vm_address_t addr = 0x80002000;
43 |
44 | while( addr < (0x80002000 + 0xA00000))
45 | {
46 | vm_read(kernel_task, addr, 2048, &buf, &sz);
47 | if( buf == 0 || sz == 0)
48 | continue;
49 | uint8_t* p = (uint8_t*) buf;
50 |
51 | for(i=0; i < sz; i++)
52 | {
53 | //"IOAESAccelerator enable UID" : (h("67 D0 40 F6"), h("00 20 40 F6")),
54 | if (*((uint32_t*)&p[i]) == 0xF640d067)
55 | {
56 | fprintf(stderr, "Found IOAESAccelerator UID ptr at %x, patching kernel\n", (uint32_t) addr + i);
57 | write_kernel(kernel_task, (void*) (addr + i), (uint32_t) 0xF6402000);
58 | return 0;
59 | }
60 | }
61 | addr += 2048;
62 | }
63 | fprintf(stderr, "IOAESAccelerator Kernel patching failed\n");
64 | return -1;
65 | }
66 |
67 | /*
68 | int main(int argc, char** argv)
69 | {
70 | return patch_IOAESAccelerator();
71 | }
72 | */
--------------------------------------------------------------------------------
/ramdisk_tools/ioflash/ioflashstoragekit.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include "ioflash/ioflash.h"
7 | #include "util.h"
8 |
9 | #define LISTEN_PORT 2000
10 |
11 | #define CMD_DUMP 0
12 | #define CMD_PROXY 1
13 |
14 | IOFlashController_client* iofc = NULL;
15 |
16 | void* proxy_thread(void* arg)
17 | {
18 | int sock = (int) arg;
19 | nand_proxy(iofc, sock);
20 | shutdown(sock, SHUT_RDWR);
21 | close(sock);
22 | return NULL;
23 | }
24 |
25 | int main(int argc, char* argv[])
26 | {
27 | int one=1;
28 | int cmd=0;
29 | pthread_t th;
30 | size_t bootargs_len = 255;
31 | char bootargs[256]={0};
32 |
33 | sysctlbyname("kern.bootargs", bootargs, &bootargs_len, NULL, 0);
34 | if (!strstr(bootargs, "rd=md0"))
35 | {
36 | printf("Not running on a ramdisk, trying to patch kernel\n");
37 | if(!IOFlashStorage_kernel_patch())
38 | return -1;
39 | }
40 |
41 | iofc = IOFlashController_init();
42 | if(iofc == NULL)
43 | {
44 | fprintf(stderr, "FAILed to get NAND infos");
45 | return -1;
46 | }
47 | IOFlashController_print(iofc);
48 | check_special_pages(iofc);
49 |
50 | int sl = create_listening_socket(LISTEN_PORT);
51 | if(sl == -1)
52 | {
53 | fprintf(stderr, "Error calling create_listening_socket\n");
54 | return -1;
55 | }
56 |
57 | fprintf(stderr, "NAND dumper listening on port %d\n", LISTEN_PORT);
58 |
59 | while(1)
60 | {
61 | int s = accept(sl, NULL, NULL);
62 | setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void *)&one, sizeof(int));
63 |
64 | int r = read(s, (void*) &cmd, sizeof(int));
65 | if(r == sizeof(int))
66 | {
67 | if(cmd == CMD_DUMP)
68 | {
69 | nand_dump(iofc, s);
70 | }
71 | else if(cmd == CMD_PROXY)
72 | {
73 | pthread_create(&th, NULL, proxy_thread, (void*) s);
74 | continue;
75 | }
76 | }
77 | shutdown(s, SHUT_RDWR);
78 | close(s);
79 | }
80 | return 0;
81 | }
--------------------------------------------------------------------------------
/python_scripts/util/lzss.py:
--------------------------------------------------------------------------------
1 | """
2 | /**************************************************************
3 | LZSS.C -- A Data Compression Program
4 | ***************************************************************
5 | 4/6/1989 Haruhiko Okumura
6 | Use, distribute, and modify this program freely.
7 | Please send me your improved versions.
8 | PC-VAN SCIENCE
9 | NIFTY-Serve PAF01022
10 | CompuServe 74050,1022
11 |
12 | **************************************************************/
13 | /*
14 | * lzss.c - Package for decompressing lzss compressed objects
15 | *
16 | * Copyright (c) 2003 Apple Computer, Inc.
17 | *
18 | * DRI: Josh de Cesare
19 | */
20 | """
21 | from array import array
22 | import struct
23 |
24 | N = 4096
25 | F = 18
26 | THRESHOLD = 2
27 | NIL = N
28 |
29 | def decompress_lzss(str):
30 | if str[:8] !="complzss":
31 | print "decompress_lzss: complzss magic missing"
32 | return
33 | decompsize = struct.unpack(">L", str[12:16])[0]
34 | text_buf = array("B", " "*(N + F - 1))
35 | src = array("B", str[0x180:])
36 | srclen = len(src)
37 | dst = array("B", " "*decompsize)
38 | r = N - F
39 | srcidx, dstidx, flags, c = 0, 0, 0, 0
40 |
41 | while True:
42 | flags >>= 1
43 | if ((flags & 0x100) == 0):
44 | if (srcidx >= srclen):
45 | break
46 | c = src[srcidx]; srcidx += 1
47 | flags = c | 0xFF00;
48 |
49 | if (flags & 1):
50 | if (srcidx >= srclen):
51 | break
52 | c = src[srcidx]; srcidx += 1
53 | dst[dstidx] = c; dstidx += 1
54 | text_buf[r] = c; r += 1
55 | r &= (N - 1);
56 | else:
57 | if (srcidx >= srclen):
58 | break
59 | i = src[srcidx]; srcidx += 1
60 | if (srcidx >= srclen):
61 | break
62 | j = src[srcidx]; srcidx += 1
63 | i |= ((j & 0xF0) << 4)
64 | j = (j & 0x0F) + THRESHOLD
65 | for k in xrange(j+1):
66 | c = text_buf[(i + k) & (N - 1)]
67 | dst[dstidx] = c; dstidx += 1
68 | text_buf[r] = c; r += 1
69 | r &= (N - 1)
70 | return dst.tostring()
71 |
72 |
--------------------------------------------------------------------------------
/emf_decrypter/hfs/flatfile.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | static int flatFileRead(io_func* io, off_t location, size_t size, void *buffer) {
5 | FILE* file;
6 | file = (FILE*) io->data;
7 |
8 | if(size == 0) {
9 | return TRUE;
10 | }
11 |
12 | //printf("%d %d\n", location, size); fflush(stdout);
13 |
14 | if(fseeko(file, location, SEEK_SET) != 0) {
15 | perror("fseek");
16 | return FALSE;
17 | }
18 |
19 | if(fread(buffer, size, 1, file) != 1) {
20 | perror("fread");
21 | return FALSE;
22 | } else {
23 | return TRUE;
24 | }
25 | }
26 |
27 | static int flatFileWrite(io_func* io, off_t location, size_t size, void *buffer) {
28 | FILE* file;
29 |
30 | /*int i;
31 |
32 | printf("write: %lld %d - ", location, size); fflush(stdout);
33 |
34 | for(i = 0; i < size; i++) {
35 | printf("%x ", ((unsigned char*)buffer)[i]);
36 | fflush(stdout);
37 | }
38 | printf("\n"); fflush(stdout);*/
39 |
40 | if(size == 0) {
41 | return TRUE;
42 | }
43 |
44 | file = (FILE*) io->data;
45 |
46 | if(fseeko(file, location, SEEK_SET) != 0) {
47 | perror("fseek");
48 | return FALSE;
49 | }
50 |
51 | if(fwrite(buffer, size, 1, file) != 1) {
52 | perror("fwrite");
53 | return FALSE;
54 | } else {
55 | return TRUE;
56 | }
57 |
58 | return TRUE;
59 | }
60 |
61 | static void closeFlatFile(io_func* io) {
62 | FILE* file;
63 |
64 | file = (FILE*) io->data;
65 |
66 | fclose(file);
67 | free(io);
68 | }
69 |
70 | io_func* openFlatFile(const char* fileName) {
71 | io_func* io;
72 |
73 | io = (io_func*) malloc(sizeof(io_func));
74 | io->data = fopen(fileName, "rb+");
75 |
76 | if(io->data == NULL) {
77 | perror("fopen");
78 | return NULL;
79 | }
80 |
81 | io->read = &flatFileRead;
82 | io->write = &flatFileWrite;
83 | io->close = &closeFlatFile;
84 |
85 | return io;
86 | }
87 |
88 | io_func* openFlatFileRO(const char* fileName) {
89 | io_func* io;
90 |
91 | io = (io_func*) malloc(sizeof(io_func));
92 | io->data = fopen(fileName, "rb");
93 |
94 | if(io->data == NULL) {
95 | perror("fopen");
96 | return NULL;
97 | }
98 |
99 | io->read = &flatFileRead;
100 | io->write = &flatFileWrite;
101 | io->close = &closeFlatFile;
102 |
103 | return io;
104 | }
105 |
--------------------------------------------------------------------------------
/old/emf_decrypter/hfs/flatfile.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | static int flatFileRead(io_func* io, off_t location, size_t size, void *buffer) {
5 | FILE* file;
6 | file = (FILE*) io->data;
7 |
8 | if(size == 0) {
9 | return TRUE;
10 | }
11 |
12 | //printf("%d %d\n", location, size); fflush(stdout);
13 |
14 | if(fseeko(file, location, SEEK_SET) != 0) {
15 | perror("fseek");
16 | return FALSE;
17 | }
18 |
19 | if(fread(buffer, size, 1, file) != 1) {
20 | perror("fread");
21 | return FALSE;
22 | } else {
23 | return TRUE;
24 | }
25 | }
26 |
27 | static int flatFileWrite(io_func* io, off_t location, size_t size, void *buffer) {
28 | FILE* file;
29 |
30 | /*int i;
31 |
32 | printf("write: %lld %d - ", location, size); fflush(stdout);
33 |
34 | for(i = 0; i < size; i++) {
35 | printf("%x ", ((unsigned char*)buffer)[i]);
36 | fflush(stdout);
37 | }
38 | printf("\n"); fflush(stdout);*/
39 |
40 | if(size == 0) {
41 | return TRUE;
42 | }
43 |
44 | file = (FILE*) io->data;
45 |
46 | if(fseeko(file, location, SEEK_SET) != 0) {
47 | perror("fseek");
48 | return FALSE;
49 | }
50 |
51 | if(fwrite(buffer, size, 1, file) != 1) {
52 | perror("fwrite");
53 | return FALSE;
54 | } else {
55 | return TRUE;
56 | }
57 |
58 | return TRUE;
59 | }
60 |
61 | static void closeFlatFile(io_func* io) {
62 | FILE* file;
63 |
64 | file = (FILE*) io->data;
65 |
66 | fclose(file);
67 | free(io);
68 | }
69 |
70 | io_func* openFlatFile(const char* fileName) {
71 | io_func* io;
72 |
73 | io = (io_func*) malloc(sizeof(io_func));
74 | io->data = fopen(fileName, "rb+");
75 |
76 | if(io->data == NULL) {
77 | perror("fopen");
78 | return NULL;
79 | }
80 |
81 | io->read = &flatFileRead;
82 | io->write = &flatFileWrite;
83 | io->close = &closeFlatFile;
84 |
85 | return io;
86 | }
87 |
88 | io_func* openFlatFileRO(const char* fileName) {
89 | io_func* io;
90 |
91 | io = (io_func*) malloc(sizeof(io_func));
92 | io->data = fopen(fileName, "rb");
93 |
94 | if(io->data == NULL) {
95 | perror("fopen");
96 | return NULL;
97 | }
98 |
99 | io->read = &flatFileRead;
100 | io->write = &flatFileWrite;
101 | io->close = &closeFlatFile;
102 |
103 | return io;
104 | }
105 |
--------------------------------------------------------------------------------
/python_scripts/backups/backup3.py:
--------------------------------------------------------------------------------
1 | from crypto.PBKDF2 import PBKDF2
2 | from crypto.aes import AESdecryptCBC
3 | from util import read_file, write_file, makedirs, readPlist
4 | from util.bplist import BPlistReader
5 | import hashlib
6 | import struct
7 | import glob
8 | import sys
9 | import os
10 | import re
11 |
12 | """
13 | decrypt iOS 3 backup blob (metadata and file contents)
14 | """
15 |
16 | def decrypt_blob(blob, auth_key):
17 | len = struct.unpack(">H", blob[0:2])[0]
18 | if len != 66:
19 | print "blob len != 66"
20 | magic = struct.unpack(">H", blob[2:4])[0]
21 | if magic != 0x0100:
22 | print "magic != 0x0100"
23 | iv = blob[4:20]
24 |
25 | blob_key = AESdecryptCBC(blob[20:68], auth_key, iv)[:32]
26 |
27 | return AESdecryptCBC(blob[68:], blob_key, iv, padding=True)
28 |
29 | def decrypt_backup3(backupfolder, outputfolder, passphrase):
30 | auth_key = None
31 | manifest = readPlist(backupfolder + "/Manifest.plist")
32 |
33 | if manifest["IsEncrypted"]:
34 | manifest_data = manifest["Data"].data
35 |
36 | authdata = manifest["AuthData"].data
37 |
38 | pkbdf_salt = authdata[:8]
39 | iv = authdata[8:24]
40 | key = PBKDF2(passphrase,pkbdf_salt,iterations=2000).read(32)
41 |
42 | data = AESdecryptCBC(authdata[24:], key, iv)
43 | auth_key = data[:32]
44 |
45 | if hashlib.sha1(auth_key).digest() != data[32:52]:
46 | print "wrong auth key (hash mismatch) => wrong passphrase"
47 | return
48 |
49 | print "Passphrase seems OK"
50 |
51 | for mdinfo_name in glob.glob(backupfolder + "/*.mdinfo"):
52 |
53 | mddata_name = mdinfo_name[:-7] + ".mddata"
54 | mdinfo = readPlist(mdinfo_name)
55 | metadata = mdinfo["Metadata"].data
56 | if mdinfo["IsEncrypted"]:
57 | metadata = decrypt_blob(metadata, auth_key)
58 | metadata = BPlistReader.plistWithString(metadata)
59 |
60 | print metadata["Path"]
61 |
62 | filedata = read_file(mddata_name)
63 | if mdinfo["IsEncrypted"]:
64 | filedata = decrypt_blob(filedata, auth_key)
65 |
66 | filename = re.sub(r'[:|*<>?"]', "_", metadata["Path"])
67 | makedirs(outputfolder + "/" + os.path.dirname(filename))
68 | write_file(outputfolder + "/" + filename, filedata)
69 |
--------------------------------------------------------------------------------
/boot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import glob, os,sys
4 |
5 | #return list of (ipsw,kernel,ramdisk)
6 | def list_bootable():
7 | res = []
8 | for ipsw in glob.glob("data/ipsw/*.ipsw"):
9 | ipsw_id = os.path.basename(ipsw).replace("_Restore.ipsw", "")
10 | kernel = os.path.join("data", "boot", "kernel_%s.patched" % ipsw_id)
11 | ramdisk = os.path.join("data", "boot", "ramdisk_%s.dmg" % ipsw_id)
12 |
13 | if os.path.exists(kernel) and os.path.exists(ramdisk):
14 | res.append((ipsw, kernel, ramdisk))
15 | return res
16 |
17 | def main():
18 | l = list_bootable()
19 |
20 | if len(l) == 0:
21 | print "Nothing to boot, run ./build.py"
22 | return
23 | elif len(l) == 1:
24 | ipsw, kernel, ramdisk = l[0]
25 | else:
26 | print "Choose IPSW :"
27 | for i in xrange(len(l)):
28 | print "[%d] %s" % (i+1, os.path.basename(l[i][0]))
29 | while True:
30 | x = raw_input("> ")
31 | if x.isdigit():
32 | x = int(x)
33 | if x > 0 and (x-1) < len(l):
34 | ipsw, kernel, ramdisk = l[x-1]
35 | break
36 | print "Invalid choice"
37 |
38 | REDSN0W_VERSION = "0.9.15b3"
39 | if ipsw.find("iPod2,1") != -1:
40 | REDSN0W_VERSION = "0.9.14b2" #older version for ipt2
41 | if sys.platform != "darwin":
42 | print "redsn0w steaks4uce exploit for ipt2 seems broken on Windows, but it works on OSX"
43 | return
44 |
45 | if sys.platform == "darwin":
46 | REDSNOW_PATH = "redsn0w_mac_%s/redsn0w.app/Contents/MacOS/redsn0w" % REDSN0W_VERSION
47 | else:
48 | REDSNOW_PATH = "redsn0w_win_%s\\redsn0w.exe" % REDSN0W_VERSION
49 |
50 | if not os.path.exists(REDSNOW_PATH):
51 | print "Extract %s in current directory" % REDSNOW_PATH.split(os.sep)[0]
52 | return
53 |
54 | print "Using %s" % ipsw
55 | #cs_enforcement_disable=1
56 | bootargs = "-v rd=md0 amfi=0xff msgbuf=409600"
57 |
58 | if raw_input("Use nand-disable boot flag ? [y/n] ") == "y":
59 | bootargs += " nand-disable=1"
60 |
61 | cmdline = "%s -i %s -k %s -r %s -a \"%s\"" % (REDSNOW_PATH, ipsw, kernel, ramdisk, bootargs)
62 |
63 | print "Boot args: %s" % bootargs
64 | print "Command line: %s" % cmdline
65 | print "Launching redsn0w..."
66 | os.system(cmdline)
67 |
68 | if __name__ == "__main__":
69 | main()
70 |
--------------------------------------------------------------------------------
/ramdisk_tools/image.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int screenWidth, screenHeight;
7 | CGContextRef context = NULL;
8 |
9 | CGContextRef fb_open() {
10 | io_connect_t conn = NULL;
11 | int bytesPerRow;
12 | void *surfaceBuffer;
13 | void *frameBuffer;
14 | CGColorSpaceRef colorSpace;
15 |
16 | if (context != NULL)
17 | return context;
18 |
19 | io_service_t fb_service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleCLCD"));
20 | if (!fb_service) {
21 | fb_service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleM2CLCD"));
22 | if (!fb_service) {
23 | printf("Couldn't find framebuffer.\n");
24 | return NULL;
25 | }
26 | }
27 |
28 | IOMobileFramebufferOpen(fb_service, mach_task_self(), 0, &conn);
29 | IOMobileFramebufferGetLayerDefaultSurface(conn, 0, &surfaceBuffer);
30 |
31 | screenHeight = CoreSurfaceBufferGetHeight(surfaceBuffer);
32 | screenWidth = CoreSurfaceBufferGetWidth(surfaceBuffer);
33 | bytesPerRow = CoreSurfaceBufferGetBytesPerRow(surfaceBuffer);
34 |
35 | CoreSurfaceBufferLock(surfaceBuffer, 3);
36 | frameBuffer = CoreSurfaceBufferGetBaseAddress(surfaceBuffer);
37 | CoreSurfaceBufferUnlock(surfaceBuffer);
38 |
39 | // create bitmap context
40 | colorSpace = CGColorSpaceCreateDeviceRGB();
41 | context = CGBitmapContextCreate(frameBuffer, screenWidth, screenHeight, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
42 | if(context == NULL) {
43 | printf("Couldn't create screen context!\n");
44 | return NULL;
45 | }
46 |
47 | CGColorSpaceRelease(colorSpace);
48 |
49 | return context;
50 | }
51 |
52 | int drawImage(const char* pngFileName)
53 | {
54 | CGContextRef c = fb_open();
55 | if (c == NULL)
56 | return -1;
57 |
58 | CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, pngFileName, strlen(pngFileName), 0);
59 | void* imageSource = CGImageSourceCreateWithURL(url, NULL);
60 | CFRelease(url);
61 |
62 | if (imageSource != NULL)
63 | {
64 | CGImageRef img = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
65 | if (img != NULL)
66 | {
67 | CGContextClearRect (c, CGRectMake(0, 0, screenWidth, screenHeight));
68 | CGContextDrawImage(c, CGRectMake(0, 0, screenWidth, screenHeight), img);
69 | }
70 | }
71 | return 0;
72 | }
73 |
--------------------------------------------------------------------------------
/ramdisk_tools/Makefile:
--------------------------------------------------------------------------------
1 | SDKVER?=7.0
2 | ARCH?=armv7
3 | MINIOS=4.0
4 | SDK=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS$(SDKVER).sdk/
5 | HGVERSION:= $(shell hg parents --template '{node|short}' || echo "unknown")
6 | CC=clang -arch $(ARCH)
7 | CFLAGS=-Wall -Wno-pointer-sign -isysroot $(SDK) -DHGVERSION="\"${HGVERSION}\"" -O3 -I.
8 | CFLAGS+= -framework CoreFoundation -framework IOKit -framework Security
9 | CFLAGS+= -miphoneos-version-min=$(MINIOS)
10 | CODESIGN=codesign -s - --entitlements entitlements.plist
11 |
12 | all: $(SDK) device_infos restored_external bruteforce ioflashstoragekit ttbthingy
13 |
14 | $(SDK):
15 | @echo "iOS SDK not found in $(SDK)"
16 | @echo "=> check SDKVER/SDK in Makefile"
17 | exit -1
18 |
19 | IOKit:
20 | ln -s /System/Library/Frameworks/IOKit.framework/Versions/Current/Headers IOKit
21 |
22 | device_infos: device_infos.c device_info.c IOAESAccelerator.c AppleEffaceableStorage.c AppleKeyStore.c bsdcrypto/pbkdf2.c bsdcrypto/sha1.c bsdcrypto/key_wrap.c bsdcrypto/rijndael.c util.c IOKit.c registry.c ioflash/ioflash.c ioflash/IOFlashPartitionScheme.c kernel_patcher.c
23 | $(CC) $(CFLAGS) -o $@ $^
24 | $(CODESIGN) $@
25 |
26 | restored_external: restored_external.c device_info.c remote_functions.c plist_server.c AppleKeyStore.c AppleEffaceableStorage.c IOKit.c IOAESAccelerator.c util.c registry.c AppleKeyStore_kdf.c bsdcrypto/pbkdf2.c bsdcrypto/sha1.c bsdcrypto/rijndael.c bsdcrypto/key_wrap.c ioflash/ioflash.c ioflash/IOFlashPartitionScheme.c kernel_patcher.c
27 | $(CC) $(CFLAGS) -o $@ $^
28 | $(CODESIGN) $@
29 |
30 | bruteforce: systemkb_bruteforce.c AppleKeyStore.c AppleEffaceableStorage.c IOKit.c IOAESAccelerator.c util.c registry.c AppleKeyStore_kdf.c bsdcrypto/pbkdf2.c bsdcrypto/sha1.c bsdcrypto/rijndael.c bsdcrypto/key_wrap.c device_info.c ioflash/ioflash.c ioflash/IOFlashPartitionScheme.c kernel_patcher.c
31 | $(CC) $(CFLAGS) -o $@ $^
32 | $(CODESIGN) $@
33 |
34 | ioflashstoragekit: ioflash/ioflash.c ioflash/ioflash_kernel.c ioflash/ioflashstoragekit.c ioflash/IOFlashPartitionScheme.c util.c
35 | $(CC) $(CFLAGS) -o $@ $^
36 | $(CODESIGN) $@
37 |
38 | kernel_patcher: kernel_patcher.c
39 | $(CC) $(CFLAGS) -o $@ $^
40 | $(CODESIGN) $@
41 |
42 | ttbthingy: ttbthingy.c
43 | $(CC) $(CFLAGS) -o $@ $^
44 | $(CODESIGN) $@
45 |
46 | shsh_dump: ioflash/ioflash.c ioflash/ioflash_kernel.c shsh_dump.c util.c
47 | $(CC) $(CFLAGS) -o $@ $^
48 | $(CODESIGN) $@
49 |
50 | clean:
51 | rm -f bruteforce restored_external device_infos ioflashstoragekit shsh_dump
52 |
53 | rebuild: clean all
54 |
--------------------------------------------------------------------------------
/ramdisk_tools/bsdcrypto/rijndael.h:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: rijndael.h,v 1.13 2008/06/09 07:49:45 djm Exp $ */
2 |
3 | /**
4 | * rijndael-alg-fst.h
5 | *
6 | * @version 3.0 (December 2000)
7 | *
8 | * Optimised ANSI C code for the Rijndael cipher (now AES)
9 | *
10 | * @author Vincent Rijmen
11 | * @author Antoon Bosselaers
12 | * @author Paulo Barreto
13 | *
14 | * This code is hereby placed in the public domain.
15 | *
16 | * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
17 | * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 | * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
25 | * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | */
28 | #ifndef __RIJNDAEL_H
29 | #define __RIJNDAEL_H
30 |
31 | #define AES_MAXKEYBITS (256)
32 | #define AES_MAXKEYBYTES (AES_MAXKEYBITS/8)
33 | /* for 256-bit keys, fewer for less */
34 | #define AES_MAXROUNDS 14
35 |
36 | typedef unsigned char u_char;
37 | typedef unsigned char u8;
38 | typedef unsigned short u16;
39 | typedef unsigned int u32;
40 |
41 | /* The structure for key information */
42 | typedef struct {
43 | int enc_only; /* context contains only encrypt schedule */
44 | int Nr; /* key-length-dependent number of rounds */
45 | u32 ek[4*(AES_MAXROUNDS + 1)]; /* encrypt key schedule */
46 | u32 dk[4*(AES_MAXROUNDS + 1)]; /* decrypt key schedule */
47 | } rijndael_ctx;
48 |
49 | int rijndael_set_key(rijndael_ctx *, const u_char *, int);
50 | int rijndael_set_key_enc_only(rijndael_ctx *, const u_char *, int);
51 | void rijndael_decrypt(rijndael_ctx *, const u_char *, u_char *);
52 | void rijndael_encrypt(rijndael_ctx *, const u_char *, u_char *);
53 |
54 | int rijndaelKeySetupEnc(unsigned int [], const unsigned char [], int);
55 | int rijndaelKeySetupDec(unsigned int [], const unsigned char [], int);
56 | void rijndaelEncrypt(const unsigned int [], int, const unsigned char [],
57 | unsigned char []);
58 |
59 | #endif /* __RIJNDAEL_H */
60 |
--------------------------------------------------------------------------------
/python_scripts/keystore/effaceable.py:
--------------------------------------------------------------------------------
1 | from construct import RepeatUntil
2 | from construct.core import Struct, Union
3 | from construct.macros import *
4 | from crypto.aes import AESdecryptCBC
5 | from crypto.aeswrap import AESUnwrap
6 | from zipfile import crc32
7 | import struct
8 |
9 | Dkey = 0x446B6579
10 | EMF = 0x454D4621
11 | BAG1 = 0x42414731
12 | DONE = 0x444f4e45 #locker sentinel
13 | #**** = 0x2A2A2A2A #wildcard for erase
14 |
15 | #MAGIC (kL) | LEN (2bytes) | TAG (4) | DATA (LEN)
16 | Locker = Struct("Locker",
17 | String("magic",2),
18 | ULInt16("length"),
19 | Union("tag",
20 | ULInt32("int"),
21 | String("tag",4))
22 | ,
23 | String("data", lambda ctx: ctx["length"])
24 | )
25 |
26 | Lockers = RepeatUntil(lambda obj, ctx: obj.tag.int == DONE, Locker)
27 |
28 | def xor_strings(s, key):
29 | res = ""
30 | for i in xrange(len(s)):
31 | res += chr(ord(s[i]) ^ ord(key[i%len(key)]))
32 | return res
33 |
34 | def check_effaceable_header(plog):
35 | z = xor_strings(plog[:16], plog[16:32])
36 | if z[:4] != "ecaF":
37 | return False
38 | plog_generation = struct.unpack("
29 |
30 | __BEGIN_DECLS
31 |
32 | #include
33 | #if COREFOUNDATION_CFPLUGINCOM_SEPARATE
34 | #include
35 | #endif
36 |
37 | #include
38 |
39 | /* C244E858-109C-11D4-91D4-0050E4C6426F */
40 | #define kIOCFPlugInInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \
41 | 0xC2, 0x44, 0xE8, 0x58, 0x10, 0x9C, 0x11, 0xD4, \
42 | 0x91, 0xD4, 0x00, 0x50, 0xE4, 0xC6, 0x42, 0x6F)
43 |
44 |
45 | #define IOCFPLUGINBASE \
46 | UInt16 version; \
47 | UInt16 revision; \
48 | IOReturn (*Probe)(void *thisPointer, CFDictionaryRef propertyTable, \
49 | io_service_t service, SInt32 * order); \
50 | IOReturn (*Start)(void *thisPointer, CFDictionaryRef propertyTable, \
51 | io_service_t service); \
52 | IOReturn (*Stop)(void *thisPointer)
53 |
54 | typedef struct IOCFPlugInInterfaceStruct {
55 | IUNKNOWN_C_GUTS;
56 | IOCFPLUGINBASE;
57 | } IOCFPlugInInterface;
58 |
59 |
60 | kern_return_t
61 | IOCreatePlugInInterfaceForService(io_service_t service,
62 | CFUUIDRef pluginType, CFUUIDRef interfaceType,
63 | IOCFPlugInInterface *** theInterface, SInt32 * theScore);
64 |
65 | kern_return_t
66 | IODestroyPlugInInterface(IOCFPlugInInterface ** interface);
67 |
68 | __END_DECLS
69 |
70 | #endif /* !_IOKIT_IOCFPLUGIN_H_ */
71 |
--------------------------------------------------------------------------------
/python_scripts/crypto/curve25519.py:
--------------------------------------------------------------------------------
1 | from Crypto.Util import number
2 |
3 | CURVE_P = (2**255 - 19)
4 | CURVE_A = 121665
5 |
6 | def curve25519_monty(x1, z1, x2, z2, qmqp):
7 | a = (x1 + z1) * (x2 - z2) % CURVE_P
8 | b = (x1 - z1) * (x2 + z2) % CURVE_P
9 | x4 = (a + b) * (a + b) % CURVE_P
10 |
11 | e = (a - b) * (a - b) % CURVE_P
12 | z4 = e * qmqp % CURVE_P
13 |
14 | a = (x1 + z1) * (x1 + z1) % CURVE_P
15 | b = (x1 - z1) * (x1 - z1) % CURVE_P
16 | x3 = a * b % CURVE_P
17 |
18 | g = (a - b) % CURVE_P
19 | h = (a + CURVE_A * g) % CURVE_P
20 | z3 = (g * h) % CURVE_P
21 |
22 | return x3, z3, x4, z4
23 |
24 | def curve25519_mult(n, q):
25 | nqpqx, nqpqz = q, 1
26 | nqx, nqz = 1, 0
27 |
28 | for i in range(255, -1, -1):
29 | if (n >> i) & 1:
30 | nqpqx,nqpqz,nqx,nqz = curve25519_monty(nqpqx, nqpqz, nqx, nqz, q)
31 | else:
32 | nqx,nqz,nqpqx,nqpqz = curve25519_monty(nqx, nqz, nqpqx, nqpqz, q)
33 | return nqx, nqz
34 |
35 | def curve25519(secret, basepoint):
36 | a = ord(secret[0])
37 | a &= 248
38 | b = ord(secret[31])
39 | b &= 127
40 | b |= 64
41 | s = chr(a) + secret[1:-1] + chr(b)
42 |
43 | s = number.bytes_to_long(s[::-1])
44 | basepoint = number.bytes_to_long(basepoint[::-1])
45 |
46 | x, z = curve25519_mult(s, basepoint)
47 | zmone = number.inverse(z, CURVE_P)
48 | z = x * zmone % CURVE_P
49 | return number.long_to_bytes(z)[::-1]
50 |
51 |
52 | if __name__ == "__main__":
53 | from crypto.aeswrap import AESUnwrap
54 | from Crypto.Hash import SHA256
55 |
56 | z="04000000080000000200000048000000000000000000000000000000000000000000000002917dc2542198edeb1078c4d1ebab74d9ca87890657ba02b9825dadf20a002f44360c6f87743fac0236df1f9eedbea801e31677aef3a09adfb4e10a37ae27facf419ab3ea3f39f4".decode("hex")
57 |
58 | mysecret = "99b66345829d8c05041eea1ba1ed5b2984c3e5ec7a756ef053473c7f22b49f14".decode("hex")
59 | mypublic = "b1c652786697a5feef36a56f36fde524a21193f4e563627977ab515f600fdb3a".decode("hex")
60 | hispublic = z[36:36+32]
61 |
62 | #c4d9fe462a2ebbf0745195ce7dc5e8b49947bbd5b42da74175d5f8125b44582b
63 | shared = curve25519(mysecret, hispublic)
64 | print shared.encode("hex")
65 |
66 | h = SHA256.new()
67 | h.update('\x00\x00\x00\x01')
68 | h.update(shared)
69 | h.update(hispublic)
70 | h.update(mypublic)
71 | md = h.digest()
72 |
73 | #e442c81b91ea876d3cf42d3aea75f4b0c3f90f9fd045e1f5784b91260f3bdc9c
74 | print AESUnwrap(md, z[32+36:]).encode("hex")
75 |
--------------------------------------------------------------------------------
/ramdisk_tools/ioflash/IOFlashPartitionScheme.h:
--------------------------------------------------------------------------------
1 | #define CEMETARY_GATE 0xdeadcafe
2 |
3 | #define kIOFlashPartitionSchemePool 0x008
4 | #define kIOFlashPartitionSchemeUseSLCBlocks 0x100
5 | #define kIOFlashPartitionSchemeUseFullPages 0x200
6 |
7 | struct IOFlashPartitionDesc
8 | {
9 | uint32_t name;
10 | uint32_t start_block;
11 | uint32_t num_blocks;
12 | uint32_t flags;
13 | } __attribute__((packed));
14 |
15 | struct IOFlashPartitionSchemeCemetary
16 | {
17 | uint32_t magic;
18 | uint8_t pad[6];
19 | uint8_t cemetary[32];
20 | uint16_t checksum;
21 | } __attribute__((packed));
22 |
23 | struct IOFlashPartitionSchemeSpares
24 | {
25 | uint32_t magic;
26 | uint16_t num_spares;
27 | uint32_t pad;
28 | uint32_t spares[64];
29 | uint16_t checksum;
30 | } __attribute__((packed));
31 |
32 | struct IOFlashPartitionSchemeSubs
33 | {
34 | uint32_t magic;
35 | uint16_t num_subs;
36 | uint32_t pad;
37 | uint8_t subs[64];
38 | uint16_t checksum;
39 | } __attribute__((packed));
40 |
41 | struct IOFlashPartitionBBTEntry
42 | {
43 | uint32_t ce;
44 | uint32_t block;
45 | } __attribute__((packed));
46 |
47 | struct IOFlashPartitionTable
48 | {
49 | uint32_t magic;//'ndrG'
50 | uint32_t zero;
51 | uint32_t major_version;
52 | uint32_t minor_version;
53 | uint32_t generation;
54 | uint16_t checksum1;
55 | uint8_t unk1[0xA];
56 |
57 | struct IOFlashPartitionBBTEntry factoryBBT[60];
58 | uint8_t unk2[0x24];
59 |
60 | //0x224
61 | struct IOFlashPartitionSchemeCemetary cemetary;
62 | //0x250
63 | struct IOFlashPartitionSchemeSpares spares;
64 | //0x35c
65 | struct IOFlashPartitionSchemeSubs subs;
66 |
67 | uint8_t unk3[0x58];
68 |
69 | //0x400
70 | struct IOFlashPartitionDesc partitions[32];
71 |
72 | } __attribute__((packed));
73 |
74 | typedef struct IOFlashPartitionScheme
75 | {
76 | IOFlashController_client* flash;
77 | uint32_t ceCount;
78 |
79 | struct IOFlashPartitionTable ptable;
80 |
81 | } IOFlashPartitionScheme;
82 |
83 | IOFlashPartitionScheme* IOFlashPartitionScheme_init(IOFlashController_client*, uint8_t*);
84 |
85 | uint32_t IOFlashPartitionScheme_get_flags_for_block(IOFlashPartitionScheme*, uint32_t ce, uint32_t block);
86 | uint32_t IOFlashPartitionScheme_remap_bootloader_block(IOFlashPartitionScheme*, uint32_t ce, uint32_t block, uint32_t flags, uint32_t* realCE, uint32_t* realBlock);
87 | uint32_t IOFlashPartitionScheme_read_partition(IOFlashPartitionScheme*, const char*, uint8_t**, uint32_t*);
88 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/dmg/filevault.h:
--------------------------------------------------------------------------------
1 | #ifndef FILEVAULT_H
2 | #define FILEVAULT_H
3 |
4 | #include
5 | #include "dmg.h"
6 |
7 | #ifdef HAVE_CRYPT
8 |
9 | #include
10 | #include
11 |
12 | #define FILEVAULT_CIPHER_KEY_LENGTH 16
13 | #define FILEVAULT_CIPHER_BLOCKSIZE 16
14 | #define FILEVAULT_CHUNK_SIZE 4096
15 | #define FILEVAULT_PBKDF2_ITER_COUNT 1000
16 | #define FILEVAULT_MSGDGST_LENGTH 20
17 |
18 | /*
19 | * Information about the FileVault format was yoinked from vfdecrypt, which was written by Ralf-Philipp Weinmann ,
20 | * Jacob Appelbaum , and Christian Fromme
21 | */
22 |
23 | #define FILEVAULT_V2_SIGNATURE 0x656e637263647361ULL
24 |
25 | typedef struct FileVaultV1Header {
26 | uint8_t padding1[48];
27 | uint32_t kdfIterationCount;
28 | uint32_t kdfSaltLen;
29 | uint8_t kdfSalt[48];
30 | uint8_t unwrapIV[0x20];
31 | uint32_t wrappedAESKeyLen;
32 | uint8_t wrappedAESKey[296];
33 | uint32_t wrappedHMACSHA1KeyLen;
34 | uint8_t wrappedHMACSHA1Key[300];
35 | uint32_t integrityKeyLen;
36 | uint8_t integrityKey[48];
37 | uint8_t padding2[484];
38 | } __attribute__((__packed__)) FileVaultV1Header;
39 |
40 | typedef struct FileVaultV2Header {
41 | uint64_t signature;
42 | uint32_t version;
43 | uint32_t encIVSize;
44 | uint32_t unk1;
45 | uint32_t unk2;
46 | uint32_t unk3;
47 | uint32_t unk4;
48 | uint32_t unk5;
49 | UDIFID uuid;
50 | uint32_t blockSize;
51 | uint64_t dataSize;
52 | uint64_t dataOffset;
53 | uint8_t padding[0x260];
54 | uint32_t kdfAlgorithm;
55 | uint32_t kdfPRNGAlgorithm;
56 | uint32_t kdfIterationCount;
57 | uint32_t kdfSaltLen;
58 | uint8_t kdfSalt[0x20];
59 | uint32_t blobEncIVSize;
60 | uint8_t blobEncIV[0x20];
61 | uint32_t blobEncKeyBits;
62 | uint32_t blobEncAlgorithm;
63 | uint32_t blobEncPadding;
64 | uint32_t blobEncMode;
65 | uint32_t encryptedKeyblobSize;
66 | uint8_t encryptedKeyblob[0x30];
67 | } __attribute__((__packed__)) FileVaultV2Header;
68 |
69 | typedef struct FileVaultInfo {
70 | union {
71 | FileVaultV1Header v1;
72 | FileVaultV2Header v2;
73 | } header;
74 |
75 | uint8_t version;
76 | uint64_t dataOffset;
77 | uint64_t dataSize;
78 | uint32_t blockSize;
79 |
80 | AbstractFile* file;
81 |
82 | HMAC_CTX hmacCTX;
83 | AES_KEY aesKey;
84 | AES_KEY aesEncKey;
85 |
86 | off_t offset;
87 |
88 | uint32_t curChunk;
89 | unsigned char chunk[FILEVAULT_CHUNK_SIZE];
90 |
91 | char dirty;
92 | char headerDirty;
93 | } FileVaultInfo;
94 | #endif
95 |
96 | AbstractFile* createAbstractFileFromFileVault(AbstractFile* file, const char* key);
97 |
98 | #endif
99 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/dmg/filevault.h:
--------------------------------------------------------------------------------
1 | #ifndef FILEVAULT_H
2 | #define FILEVAULT_H
3 |
4 | #include
5 | #include "dmg.h"
6 |
7 | #ifdef HAVE_CRYPT
8 |
9 | #include
10 | #include
11 |
12 | #define FILEVAULT_CIPHER_KEY_LENGTH 16
13 | #define FILEVAULT_CIPHER_BLOCKSIZE 16
14 | #define FILEVAULT_CHUNK_SIZE 4096
15 | #define FILEVAULT_PBKDF2_ITER_COUNT 1000
16 | #define FILEVAULT_MSGDGST_LENGTH 20
17 |
18 | /*
19 | * Information about the FileVault format was yoinked from vfdecrypt, which was written by Ralf-Philipp Weinmann ,
20 | * Jacob Appelbaum , and Christian Fromme
21 | */
22 |
23 | #define FILEVAULT_V2_SIGNATURE 0x656e637263647361ULL
24 |
25 | typedef struct FileVaultV1Header {
26 | uint8_t padding1[48];
27 | uint32_t kdfIterationCount;
28 | uint32_t kdfSaltLen;
29 | uint8_t kdfSalt[48];
30 | uint8_t unwrapIV[0x20];
31 | uint32_t wrappedAESKeyLen;
32 | uint8_t wrappedAESKey[296];
33 | uint32_t wrappedHMACSHA1KeyLen;
34 | uint8_t wrappedHMACSHA1Key[300];
35 | uint32_t integrityKeyLen;
36 | uint8_t integrityKey[48];
37 | uint8_t padding2[484];
38 | } __attribute__((__packed__)) FileVaultV1Header;
39 |
40 | typedef struct FileVaultV2Header {
41 | uint64_t signature;
42 | uint32_t version;
43 | uint32_t encIVSize;
44 | uint32_t unk1;
45 | uint32_t unk2;
46 | uint32_t unk3;
47 | uint32_t unk4;
48 | uint32_t unk5;
49 | UDIFID uuid;
50 | uint32_t blockSize;
51 | uint64_t dataSize;
52 | uint64_t dataOffset;
53 | uint8_t padding[0x260];
54 | uint32_t kdfAlgorithm;
55 | uint32_t kdfPRNGAlgorithm;
56 | uint32_t kdfIterationCount;
57 | uint32_t kdfSaltLen;
58 | uint8_t kdfSalt[0x20];
59 | uint32_t blobEncIVSize;
60 | uint8_t blobEncIV[0x20];
61 | uint32_t blobEncKeyBits;
62 | uint32_t blobEncAlgorithm;
63 | uint32_t blobEncPadding;
64 | uint32_t blobEncMode;
65 | uint32_t encryptedKeyblobSize;
66 | uint8_t encryptedKeyblob[0x30];
67 | } __attribute__((__packed__)) FileVaultV2Header;
68 |
69 | typedef struct FileVaultInfo {
70 | union {
71 | FileVaultV1Header v1;
72 | FileVaultV2Header v2;
73 | } header;
74 |
75 | uint8_t version;
76 | uint64_t dataOffset;
77 | uint64_t dataSize;
78 | uint32_t blockSize;
79 |
80 | AbstractFile* file;
81 |
82 | HMAC_CTX hmacCTX;
83 | AES_KEY aesKey;
84 | AES_KEY aesEncKey;
85 |
86 | off_t offset;
87 |
88 | uint32_t curChunk;
89 | unsigned char chunk[FILEVAULT_CHUNK_SIZE];
90 |
91 | char dirty;
92 | char headerDirty;
93 | } FileVaultInfo;
94 | #endif
95 |
96 | AbstractFile* createAbstractFileFromFileVault(AbstractFile* file, const char* key);
97 |
98 | #endif
99 |
--------------------------------------------------------------------------------
/emf_decrypter/BUILD:
--------------------------------------------------------------------------------
1 | INSTRUCTIONS FOR BUILDING XPWN
2 | ------------------------------
3 |
4 | These are very basic instructions on how to build xpwn related projects, they
5 | are tailored to Debian based systems. They are not meant to be a substitute
6 | for experience in programming in GNU/Linux environments, but it should be a
7 | good starting point.
8 |
9 | 1. Install a basic build environment (compilers, etc.):
10 |
11 | sudo apt-get install build-essential
12 |
13 | 2. Install some prerequisites libraries required by xpwn:
14 |
15 | sudo apt-get install libcrypt-dev libz-dev libbz2-dev3 libusb-dev
16 |
17 | 3. Install cmake. It is recommended you download and build it from the
18 | official cmake website, since versions >= 2.6.0 are recommended.
19 |
20 | wget http://www.cmake.org/files/v2.6/cmake-2.6.2.tar.gz
21 | tar zxvf cmake-2.6.2.tar.gz
22 | cd cmake-2.6.2
23 | ./configure
24 | make
25 | sudo make install
26 |
27 | Now you are ready to build xpwn. It is highly recommended that you build
28 | out-of-source (that is, the build products are not placed into the same
29 | folders as the sources). This is much neater and cleaning up is as simple as
30 | deleting the build products folder.
31 |
32 | Assuming xpwn sources are in ~/xpwn:
33 |
34 | 4. Create a build folder
35 |
36 | cd ~
37 | mkdir build
38 | cd build
39 |
40 | 5. Create Makefiles
41 |
42 | cmake ~/xpwn
43 |
44 | 6. Build
45 |
46 | make
47 |
48 | 7. Package
49 |
50 | make package
51 |
52 | BUILDING USEFUL LIBRARIES
53 | -------------------------
54 |
55 | These command-lines can be substituted in for step 6. The products are in the
56 | subfolders (make package will not include them).
57 |
58 | xpwn library (for IPSW generation)
59 |
60 | make libXPwn.a
61 |
62 | Windows pwnmetheus library (for QuickPwn)
63 |
64 | make libpwnmetheus.dll
65 |
66 | HELPFUL MAKEFILE GENERATION COMMAND-LINES
67 | -----------------------------------------
68 |
69 | These command-lines can be substituted in for step 5.
70 |
71 | Add debugging symbols:
72 |
73 | cmake ~/xpwn -DCMAKE_C_FLAGS=-g
74 |
75 | Try to only use static libraries:
76 |
77 | cmake ~/xpwn -DBUILD_STATIC=YES
78 |
79 |
80 | CROSS-COMPILING
81 | ---------------
82 |
83 | This is a complex and advanced topic, but it is possible with the appropriate
84 | CMake toolchain files and properly configured build environment. I have
85 | crossbuilt Windows, OS X, Linux x86, Linux x64, and iPhone binaries from one
86 | Ubuntu machine. The source trees are properly configured for this task.
87 |
88 | MORE HELP
89 | ---------
90 |
91 | Consult the CMake documentation and wiki and look in the CMakeLists.txt files
92 | for hints on how things are supposed to work.
93 |
--------------------------------------------------------------------------------
/old/emf_decrypter/BUILD:
--------------------------------------------------------------------------------
1 | INSTRUCTIONS FOR BUILDING XPWN
2 | ------------------------------
3 |
4 | These are very basic instructions on how to build xpwn related projects, they
5 | are tailored to Debian based systems. They are not meant to be a substitute
6 | for experience in programming in GNU/Linux environments, but it should be a
7 | good starting point.
8 |
9 | 1. Install a basic build environment (compilers, etc.):
10 |
11 | sudo apt-get install build-essential
12 |
13 | 2. Install some prerequisites libraries required by xpwn:
14 |
15 | sudo apt-get install libcrypt-dev libz-dev libbz2-dev3 libusb-dev
16 |
17 | 3. Install cmake. It is recommended you download and build it from the
18 | official cmake website, since versions >= 2.6.0 are recommended.
19 |
20 | wget http://www.cmake.org/files/v2.6/cmake-2.6.2.tar.gz
21 | tar zxvf cmake-2.6.2.tar.gz
22 | cd cmake-2.6.2
23 | ./configure
24 | make
25 | sudo make install
26 |
27 | Now you are ready to build xpwn. It is highly recommended that you build
28 | out-of-source (that is, the build products are not placed into the same
29 | folders as the sources). This is much neater and cleaning up is as simple as
30 | deleting the build products folder.
31 |
32 | Assuming xpwn sources are in ~/xpwn:
33 |
34 | 4. Create a build folder
35 |
36 | cd ~
37 | mkdir build
38 | cd build
39 |
40 | 5. Create Makefiles
41 |
42 | cmake ~/xpwn
43 |
44 | 6. Build
45 |
46 | make
47 |
48 | 7. Package
49 |
50 | make package
51 |
52 | BUILDING USEFUL LIBRARIES
53 | -------------------------
54 |
55 | These command-lines can be substituted in for step 6. The products are in the
56 | subfolders (make package will not include them).
57 |
58 | xpwn library (for IPSW generation)
59 |
60 | make libXPwn.a
61 |
62 | Windows pwnmetheus library (for QuickPwn)
63 |
64 | make libpwnmetheus.dll
65 |
66 | HELPFUL MAKEFILE GENERATION COMMAND-LINES
67 | -----------------------------------------
68 |
69 | These command-lines can be substituted in for step 5.
70 |
71 | Add debugging symbols:
72 |
73 | cmake ~/xpwn -DCMAKE_C_FLAGS=-g
74 |
75 | Try to only use static libraries:
76 |
77 | cmake ~/xpwn -DBUILD_STATIC=YES
78 |
79 |
80 | CROSS-COMPILING
81 | ---------------
82 |
83 | This is a complex and advanced topic, but it is possible with the appropriate
84 | CMake toolchain files and properly configured build environment. I have
85 | crossbuilt Windows, OS X, Linux x86, Linux x64, and iPhone binaries from one
86 | Ubuntu machine. The source trees are properly configured for this task.
87 |
88 | MORE HELP
89 | ---------
90 |
91 | Consult the CMake documentation and wiki and look in the CMakeLists.txt files
92 | for hints on how things are supposed to work.
93 |
--------------------------------------------------------------------------------
/ramdisk_tools/AppleKeyStore.h:
--------------------------------------------------------------------------------
1 | #include "IOKit.h"
2 |
3 | /*
4 | AppleKeyStore
5 | 0 : initUserClient scalarOutSize=1
6 | 1 :
7 | 2 : AppleKeyStoreKeyBagCreate
8 | 3 : AppleKeyStoreKeyBagCopyData inscalars=id structOutSize=0x8000
9 | 4 : keybagrelease inscalars":[0]}
10 | 5 : AppleKeyStoreKeyBagSetSystem
11 | 6 : AppleKeyStoreKeyBagCreateWithData
12 | 7 : getlockstate "inscalars":[0], "scalarOutSize":1}
13 | 8 : AppleKeyStoreLockDevice
14 | 9 : AppleKeyStoreUnlockDevice instruct
15 | 10: AppleKeyStoreKeyWrap
16 | 11: AppleKeyStoreKeyUnwrap
17 | 12: AppleKeyStoreKeyBagUnlock
18 | 13: AppleKeyStoreKeyBagLock
19 | 14: AppleKeyStoreKeyBagGetSystem scalarOutSize=1
20 | 15: AppleKeyStoreKeyBagChangeSecret
21 | 17: AppleKeyStoreGetDeviceLockState scalarOutSize=1
22 | 18: AppleKeyStoreRecoverWithEscrowBag
23 | 19: AppleKeyStoreOblitClassD
24 | */
25 | #define kAppleKeyStoreInitUserClient 0
26 | #define kAppleKeyStoreKeyBagSetSystem 5
27 | #define kAppleKeyStoreKeyBagCreateWithData 6
28 | #define kAppleKeyStoreUnlockDevice 9
29 |
30 | #define MAX_CLASS_KEYS 20
31 |
32 | struct KeyBagBlobItem
33 | {
34 | unsigned int tag;
35 | unsigned int len;
36 | union
37 | {
38 | unsigned int intvalue;
39 | unsigned char bytes[1];
40 | } data;
41 | };
42 |
43 | typedef struct ClassKey
44 | {
45 | unsigned char uuid[16];
46 | unsigned int clas;
47 | unsigned int wrap;
48 | unsigned char wpky[40];
49 | } ClassKey;
50 |
51 | typedef struct KeyBag
52 | {
53 | unsigned int version;
54 | unsigned int type;
55 | unsigned char uuid[16];
56 | unsigned char hmck[40];
57 | unsigned char salt[20];
58 | unsigned int iter;
59 |
60 | unsigned int numKeys;
61 |
62 | struct ClassKey keys[MAX_CLASS_KEYS];
63 | } KeyBag;
64 |
65 |
66 | int AppleKeyStoreKeyBagInit();
67 | CFDictionaryRef AppleKeyStore_loadKeyBag(const char* folder, const char* filename);
68 | int AppleKeyStoreKeyBagCreateWithData(CFDataRef data, uint64_t* keybagId);
69 | int AppleKeyStoreKeyBagSetSystem(uint64_t keybagId);
70 | int AppleKeyStoreUnlockDevice(io_connect_t conn, CFDataRef passcode);
71 |
72 | KeyBag* AppleKeyStore_parseBinaryKeyBag(CFDataRef kb);
73 | void AppleKeyStore_printKeyBag(KeyBag* kb);
74 |
75 | int AppleKeyStore_getPasscodeKey(KeyBag* keybag,
76 | const char* passcode,
77 | size_t passcodeLen,
78 | uint8_t* passcodeKey);
79 |
80 | int AppleKeyStore_unlockKeybagFromUserland(KeyBag* kb,
81 | const char* passcode,
82 | size_t passcodeLen,
83 | uint8_t* key835);
84 |
85 | CFMutableDictionaryRef AppleKeyStore_getClassKeys(KeyBag*);
86 |
--------------------------------------------------------------------------------
/ramdisk_tools/IOKit.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "IOKit.h"
4 |
5 | struct ioconnectCache {
6 | const char* serviceName;
7 | io_connect_t conn;
8 | };
9 |
10 | struct ioconnectCache cache[10]={{NULL, 0}};
11 |
12 | void __attribute__((destructor)) IOKit_destruct()
13 | {
14 | int i;
15 | for (i=0; i < 10 && cache[i].conn != 0; i++) {
16 | //printf("Closing %s\n", cache[i].serviceName);
17 | IOServiceClose(cache[i].conn);
18 | }
19 | }
20 |
21 | io_connect_t IOKit_getConnect(const char* serviceName)
22 | {
23 | IOReturn ret;
24 | io_connect_t conn = 0;
25 | int i;
26 |
27 | for (i=0; i < 10 && cache[i].serviceName != NULL; i++) {
28 | if (!strcmp(serviceName, cache[i].serviceName))
29 | {
30 | //printf("got cache for %s\n", serviceName);
31 | return cache[i].conn;
32 | }
33 | }
34 |
35 | CFMutableDictionaryRef dict = IOServiceMatching(serviceName);
36 | io_service_t dev = IOServiceGetMatchingService(kIOMasterPortDefault, dict);
37 |
38 | if(!dev) {
39 | fprintf(stderr, "FAIL: Could not get %s service\n", serviceName);
40 | return -1;
41 | }
42 |
43 | ret = IOServiceOpen(dev, mach_task_self(), 0, &conn);
44 |
45 | IOObjectRelease(dev);
46 | if(ret != kIOReturnSuccess) {
47 | fprintf(stderr, "FAIL: Cannot open service %s\n", serviceName);
48 | return -1;
49 | }
50 |
51 | if (i < 10) {
52 | cache[i].serviceName = serviceName;
53 | cache[i].conn = conn;
54 | }
55 |
56 | return conn;
57 | }
58 |
59 | IOReturn IOKit_call(const char* serviceName,
60 | uint32_t selector,
61 | const uint64_t *input,
62 | uint32_t inputCnt,
63 | const void *inputStruct,
64 | size_t inputStructCnt,
65 | uint64_t *output,
66 | uint32_t *outputCnt,
67 | void *outputStruct,
68 | size_t *outputStructCnt)
69 | {
70 | IOReturn ret;
71 | io_connect_t conn = IOKit_getConnect(serviceName);
72 |
73 | ret = IOConnectCallMethod(conn,
74 | selector,
75 | input,
76 | inputCnt,
77 | inputStruct,
78 | inputStructCnt,
79 | output,
80 | outputCnt,
81 | outputStruct,
82 | outputStructCnt);
83 |
84 | if (ret != kIOReturnSuccess)
85 | {
86 | fprintf(stderr, "IOConnectCallMethod on %s selector %d returned %x\n", serviceName, selector, ret);
87 | }
88 |
89 | return ret;
90 | }
--------------------------------------------------------------------------------
/ramdisk_tools/ioflash/externalMethod.S:
--------------------------------------------------------------------------------
1 | .text
2 | .thumb
3 | //IOFlashControllerUserClient::externalMethod for iOS 5/6 in-place kernel patching
4 | //modified from clang -Os output
5 |
6 | externalMethod:
7 | push {r4, r5, r6, r7, r8, r9, r10, r11, lr}
8 | sub sp, #88
9 |
10 | ldr r11, IOMemoryDescriptor__withAddress_delta
11 | add r11, pc //pc points 4 bytes ahead
12 | mov r4, r0
13 |
14 | //IOMemoryDescriptor__withAddress_delta should hold the delta between here (externalMethod+0xC) and IOMemoryDescriptor__withAddress(+1)
15 |
16 | // cmp r1, #1
17 | // bne.n epilog
18 |
19 | ldr r6, [r2, #28]
20 |
21 | movs r5, #0
22 |
23 | ldr.w r7, [r2, #48]
24 | movs r2, #1
25 | ldr r0, [r6, #0]
26 | str r0, [sp, #4]
27 | ldr r0, [r6, #4]
28 | str r0, [sp, #0]
29 | movs r0, #1
30 | str r0, [sp, #12]
31 | str r5, [sp, #8]
32 | ldrb r1, [r6, #9]
33 | tst.w r1, #1 @ 0x1
34 | itt ne
35 | movne r1, #9
36 | strne r1, [sp, #8]
37 | str r5, [sp, #20]
38 | str r5, [sp, #32]
39 | str r5, [sp, #68]
40 | str r5, [sp, #60]
41 | str r5, [sp, #52]
42 |
43 | str r0, [sp, #16]
44 | add r0, sp, #4
45 | str r0, [sp, #24]
46 | mov r0, sp
47 | str r0, [sp, #44]
48 | ldrd r0, r1, [r6, #12]
49 | ldr r3, [r4, #124]
50 | blx r11
51 | str r0, [sp, #28]
52 | ldr r0, [r6, #20]
53 | cbnz r0, prepare_spare
54 | mov r6, r5
55 | b.n docommand
56 |
57 | prepare_spare:
58 | ldr r0, [r6, #24]
59 | movs r2, #1
60 | str r0, [sp, #52]
61 | ldr r0, [r6, #20]
62 | ldr r1, [r6, #24]
63 | ldr r3, [r4, #124]
64 | blx r11
65 | mov r1, r5
66 | mov r5, r0
67 | ldr r2, [r5, #0]
68 | ldr.w r2, [r2, #152]
69 | blx r2 //map(0)
70 | mov r6, r0
71 | ldr r1, [r6, #0]
72 | ldr r1, [r1, #56]
73 | blx r1 //getVirtualAddress
74 | str r0, [sp, #48]
75 |
76 | docommand:
77 | ldr r0, [r4, #120]
78 | add r2, sp, #8
79 | ldr r1, [r0, #0]
80 | //ldr.w r3, [r1, #836] //XXX: ios5
81 | ldr.w r3, [r1, #844] //XXX: ios6/7 ?
82 | movs r1, #0
83 | blx r3
84 | str.w r0, [r7]
85 | ldr r0, [sp, #28]
86 | ldr r1, [r0, #0]
87 | ldr r4, [r1, #20]
88 | blx r4
89 | cbz r6, epilog
90 | mov r0, r6
91 | blx r4
92 | mov r0, r5
93 | blx r4
94 |
95 | epilog:
96 | movs r0, #0
97 | add sp, #88
98 | pop {r4, r5, r6, r7, r8, r9, r10, r11, pc}
99 |
100 | .align 2
101 | IOMemoryDescriptor__withAddress_delta:
102 | //delta between externalMethod+0xC and IOMemoryDescriptor__withAddress (+1) appended here by kernel_patcher.py
103 | //.long 0xdeadbeef
104 |
--------------------------------------------------------------------------------
/python_scripts/icloud/icloud.proto:
--------------------------------------------------------------------------------
1 | package icloud;
2 |
3 | message MBSAccount {
4 | optional string AccountID = 1;
5 | repeated bytes backupUDID = 2;
6 | }
7 |
8 | message MBSBackup {
9 | optional bytes backupUDID = 1;
10 | optional uint64 QuotaUsed = 2;
11 | optional MBSSnapshot Snapshot = 3;
12 | optional MBSBackupAttributes Attributes = 4;
13 | optional uint64 KeysLastModified = 5;
14 | }
15 |
16 | message MBSBackupAttributes {
17 | optional string DeviceClass = 1;
18 | optional string ProductType = 2;
19 | optional string SerialNumber = 3;
20 | optional string DeviceColor = 4;
21 | optional string HardwareModel = 5;
22 | optional string MarketingName = 6;
23 | }
24 |
25 | message MBSFile {
26 | optional bytes FileID = 1;
27 | optional string Domain = 2;
28 | optional string RelativePath = 3;
29 | optional bytes Signature = 4;
30 | optional uint64 Size = 5;
31 | optional MBSFileAttributes Attributes = 6;
32 | }
33 |
34 | message MBSFileAttributes {
35 | optional uint32 KeybagID = 1;
36 | optional string Target = 2;
37 | optional bytes EncryptionKey = 3;
38 | optional uint64 InodeNumber = 4;
39 | optional uint32 Mode = 5;
40 | optional uint32 UserID = 6;
41 | optional uint32 GroupID = 7;
42 | optional uint64 LastModified = 8;
43 | optional uint64 LastStatusChange = 9;
44 | optional uint64 Birth = 10;
45 | optional uint32 ProtectionClass = 12;
46 | optional MBSFileExtendedAttribute ExtendedAttribute = 13;
47 | optional uint32 EncryptionKeyVersion = 14;
48 | optional uint64 DecryptedSize = 15;
49 | }
50 |
51 | message MBSSnapshot {
52 | optional uint32 SnapshotID = 1;
53 | optional uint64 QuotaReserved = 2;
54 | optional uint64 LastModified = 3;
55 | optional MBSSnapshotAttributes Attributes = 5;
56 | optional uint64 Committed = 6;
57 | }
58 |
59 | message MBSSnapshotAttributes {
60 | optional string DeviceName = 1;
61 | optional string ProductVersion = 2;
62 | optional string BuildVersion = 3;
63 | optional uint32 KeybagID = 4;
64 | optional bytes KeybagUUID = 5;
65 | optional int32 BackupReason = 6;
66 | optional int32 BackupType = 7;
67 | }
68 |
69 | message MBSSnapshotID {
70 | optional uint32 SnapshotID = 1;
71 | }
72 |
73 | message MBSFileAuthToken {
74 | required bytes FileID = 1;
75 | optional string AuthToken = 2;
76 | }
77 | message MBSFileAuthTokens {
78 | repeated MBSFileAuthToken tokens = 1;
79 | }
80 |
81 | message MBSFileID {
82 | required bytes FileID = 1;
83 | }
84 |
85 | message MBSKey {
86 | optional uint32 KeyID = 1;
87 | optional bytes KeyData = 2;
88 | }
89 |
90 | message MBSKeySet {
91 | repeated MBSKey Key = 1;
92 | }
93 |
94 | message MBSFileExtendedAttribute {
95 | optional string Name = 1;
96 | optional bytes Value = 2;
97 | }
98 |
--------------------------------------------------------------------------------
/ramdisk_tools/util.h:
--------------------------------------------------------------------------------
1 | struct HFSInfos {
2 | uint64_t volumeUUID;
3 | uint32_t blockSize;
4 | uint32_t dataVolumeOffset;
5 | };
6 |
7 | struct HFSPlusVolumeHeader {
8 | uint16_t signature;
9 | uint16_t version;
10 | uint32_t attributes;
11 | uint32_t lastMountedVersion;
12 | uint32_t journalInfoBlock;
13 |
14 | uint32_t createDate;
15 | uint32_t modifyDate;
16 | uint32_t backupDate;
17 | uint32_t checkedDate;
18 |
19 | uint32_t fileCount;
20 | uint32_t folderCount;
21 |
22 | uint32_t blockSize;
23 | uint32_t totalBlocks;
24 | uint32_t freeBlocks;
25 |
26 | uint32_t nextAllocation;
27 | uint32_t rsrcClumpSize;
28 | uint32_t dataClumpSize;
29 | uint32_t nextCatalogID;
30 |
31 | uint32_t writeCount;
32 | uint64_t encodingsBitmap;
33 |
34 | uint32_t finderInfo[6];
35 | uint64_t volumeUUID;
36 | /*
37 | HFSPlusForkData allocationFile;
38 | HFSPlusForkData extentsFile;
39 | HFSPlusForkData catalogFile;
40 | HFSPlusForkData attributesFile;
41 | HFSPlusForkData startupFile;*/
42 | } __attribute__((packed));
43 |
44 | //https://github.com/iDroid-Project/openiBoot/blob/master/openiboot/includes/bdev.h
45 | typedef struct _LwVMPartitionRecord {
46 | uint64_t type[2];
47 | uint64_t guid[2];
48 | uint64_t begin;
49 | uint64_t end;
50 | uint64_t attribute; // 0 == unencrypted; 0x1000000000000 == encrypted
51 | char partitionName[0x48];
52 | } __attribute__ ((packed)) LwVMPartitionRecord;
53 |
54 | typedef struct _LwVM {
55 | uint64_t type[2];
56 | uint64_t guid[2];
57 | uint64_t mediaSize;
58 | uint32_t numPartitions;
59 | uint32_t crc32;
60 | uint8_t unkn[464];
61 | LwVMPartitionRecord partitions[12];
62 | uint16_t chunks[1024]; // chunks[0] should be 0xF000
63 | } __attribute__ ((packed)) LwVM;
64 |
65 | static const char LwVMType[] = { 0x6A, 0x90, 0x88, 0xCF, 0x8A, 0xFD, 0x63, 0x0A, 0xE3, 0x51, 0xE2, 0x48, 0x87, 0xE0, 0xB9, 0x8B };
66 |
67 | int getHFSInfos(struct HFSInfos *infos);
68 |
69 | CFMutableStringRef CreateHexaCFString(uint8_t* buffer, size_t len);
70 |
71 | void printBytesToHex(const uint8_t* buffer, size_t bytes);
72 | void printHexString(const char* description, const uint8_t* buffer, size_t bytes);
73 | int write_file(const char* filename, uint8_t* data, size_t len);
74 |
75 | void addHexaString(CFMutableDictionaryRef out, CFStringRef key, uint8_t* buffer, size_t len);
76 | void saveResults(CFStringRef filename, CFMutableDictionaryRef out);
77 | void writePlistToStdout(CFDictionaryRef out);
78 |
79 | int mountDataPartition(const char* mountpoint);
80 |
81 | int create_listening_socket(int port);
--------------------------------------------------------------------------------
/python_scripts/keychain_tool.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | from optparse import OptionParser
3 | from keystore.keybag import Keybag
4 | from keychain import keychain_load
5 | from keychain.managedconfiguration import bruteforce_old_pass
6 | from util import readPlist
7 | from keychain.keychain4 import Keychain4
8 | import plistlib
9 |
10 | def main():
11 | parser = OptionParser(usage="%prog keychain.db/keychain-backup.plist keyfile.plist/Manifest.plist")
12 | parser.add_option("-d", "--display", dest="display", action="store_true", default=False,
13 | help="Show keychain items on stdout")
14 | parser.add_option("-s", "--sanitize", dest="sanitize", action="store_true", default=False,
15 | help="Hide secrets on stdout with ***")
16 | parser.add_option("-p", "--passwords", dest="passwords", action="store_true", default=False,
17 | help="Save generic & internet passwords as CSV file")
18 | parser.add_option("-c", "--certs", dest="certs", action="store_true", default=False,
19 | help="Extract certificates and keys")
20 | parser.add_option("-o", "--old", dest="oldpass", action="store_true", default=False,
21 | help="Bruteforce old passcodes")
22 |
23 | (options, args) = parser.parse_args()
24 | if len(args) < 2:
25 | parser.print_help()
26 | return
27 |
28 | p = readPlist(args[1])
29 |
30 | if p.has_key("BackupKeyBag"):
31 | deviceKey = None
32 | if p.has_key("key835"):
33 | deviceKey = p["key835"].decode("hex")
34 | else:
35 | if not p["IsEncrypted"]:
36 | print "This backup is not encrypted, without key 835 nothing in the keychain can be decrypted"
37 | print "If you have key835 for device %s enter it (in hex)" % p["Lockdown"]["UniqueDeviceID"]
38 | d = raw_input()
39 | if len(d) == 32:
40 | p["key835"] = d
41 | deviceKey = d.decode("hex")
42 | plistlib.writePlist(p, args[1])
43 |
44 | kb = Keybag.createWithBackupManifest(p, p.get("password",""), deviceKey)
45 | if not kb:
46 | return
47 | k = Keychain4(args[0], kb)
48 | else:
49 | kb = Keybag.createWithPlist(p)
50 | k = keychain_load(args[0], kb, p["key835"].decode("hex"))
51 |
52 | if options.display:
53 | k.print_all(options.sanitize)
54 | if options.passwords:
55 | k.save_passwords()
56 | if options.certs:
57 | k.save_certs_keys()
58 |
59 | if options.oldpass:
60 | mc = k.get_managed_configuration()
61 | if not mc:
62 | print "Managed configuration not found"
63 | return
64 | print "Bruteforcing %d old passcodes" % len(mc.get("history",[]))
65 | for h in mc["history"]:
66 | p = bruteforce_old_pass(h)
67 | if p:
68 | print "Found : %s" % p
69 | else:
70 | print "Not Found"
71 |
72 | if __name__ == "__main__":
73 | main()
74 |
--------------------------------------------------------------------------------
/python_scripts/backup_tool.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | from backups.backup3 import decrypt_backup3
3 | from backups.backup4 import MBDB
4 | from keystore.keybag import Keybag
5 | from util import readPlist, makedirs
6 | import os
7 | import sys
8 | import plistlib
9 |
10 | showinfo = ["Device Name", "Display Name", "Last Backup Date", "IMEI",
11 | "Serial Number", "Product Type", "Product Version", "iTunes Version"]
12 |
13 | def extract_backup(backup_path, output_path, password=""):
14 | if not os.path.exists(backup_path + "/Manifest.plist"):
15 | print "Manifest.plist not found"
16 | return
17 | manifest = readPlist(backup_path + "/Manifest.plist")
18 |
19 | info = readPlist( backup_path + "/Info.plist")
20 | for i in showinfo:
21 | print i + " : " + unicode(info.get(i, "missing"))
22 |
23 | print "Extract backup to %s ? (y/n)" % output_path
24 | if raw_input() == "n":
25 | return
26 |
27 | print "Backup is %sencrypted" % (int(not manifest["IsEncrypted"]) * "not ")
28 |
29 | if manifest["IsEncrypted"] and password == "":
30 | print "Enter backup password : "
31 | password = raw_input()
32 |
33 | if not manifest.has_key("BackupKeyBag"):
34 | print "No BackupKeyBag in manifest, assuming iOS 3.x backup"
35 | decrypt_backup3(backup_path, output_path, password)
36 | else:
37 | mbdb = MBDB(backup_path)
38 |
39 | kb = Keybag.createWithBackupManifest(manifest, password)
40 | if not kb:
41 | return
42 | manifest["password"] = password
43 | makedirs(output_path)
44 | plistlib.writePlist(manifest, output_path + "/Manifest.plist")
45 |
46 | mbdb.keybag = kb
47 | mbdb.extract_backup(output_path)
48 |
49 | print "You can decrypt the keychain using the following command : "
50 | print "python keychain_tool.py -d \"%s\" \"%s\"" % (output_path + "/KeychainDomain/keychain-backup.plist", output_path + "/Manifest.plist")
51 |
52 | def extract_all():
53 | if sys.platform == "win32":
54 | mobilesync = os.environ["APPDATA"] + "/Apple Computer/MobileSync/Backup/"
55 | elif sys.platform == "darwin":
56 | mobilesync = os.environ["HOME"] + "/Library/Application Support/MobileSync/Backup/"
57 | else:
58 | print "Unsupported operating system"
59 | return
60 | print "-" * 60
61 | print "Searching for iTunes backups"
62 | print "-" * 60
63 |
64 | for udid in os.listdir(mobilesync):
65 | extract_backup(mobilesync + "/" + udid, udid + "_extract")
66 |
67 | def main():
68 | if len(sys.argv) < 2:
69 | print "Usage: %s [output path]" % sys.argv[0]
70 | return
71 | backup_path = sys.argv[1]
72 | output_path = os.path.dirname(backup_path) + "_extract"
73 | if len(sys.argv) >= 3:
74 | output_path = sys.argv[2]
75 |
76 | if backup_path == "icloud":
77 | from icloud.backup import download_backup
78 | print "Downloading iCloud backup"
79 | download_backup(None, None, output_path)
80 | else:
81 | extract_backup(backup_path, output_path)
82 |
83 | if __name__ == "__main__":
84 | main()
85 |
--------------------------------------------------------------------------------
/emf_decrypter/includes/common.h:
--------------------------------------------------------------------------------
1 | #ifndef COMMON_H
2 | #define COMMON_H
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | #ifdef WIN32
11 | #define fseeko fseeko64
12 | #define ftello ftello64
13 | #define off_t off64_t
14 | #define mkdir(x, y) mkdir(x)
15 | #define PATH_SEPARATOR "\\"
16 | #else
17 | #define PATH_SEPARATOR "/"
18 | #endif
19 |
20 | #define TRUE 1
21 | #define FALSE 0
22 |
23 | #define FLIPENDIAN(x) flipEndian((unsigned char *)(&(x)), sizeof(x))
24 | #define FLIPENDIANLE(x) flipEndianLE((unsigned char *)(&(x)), sizeof(x))
25 |
26 | #define IS_BIG_ENDIAN 0
27 | #define IS_LITTLE_ENDIAN 1
28 |
29 | #define TIME_OFFSET_FROM_UNIX 2082844800L
30 | #define APPLE_TO_UNIX_TIME(x) ((x) - TIME_OFFSET_FROM_UNIX)
31 | #define UNIX_TO_APPLE_TIME(x) ((x) + TIME_OFFSET_FROM_UNIX)
32 |
33 | #define ASSERT(x, m) if(!(x)) { fflush(stdout); fprintf(stderr, "error: %s\n", m); perror("error"); fflush(stderr); exit(1); }
34 |
35 | extern char endianness;
36 |
37 | static inline void flipEndian(unsigned char* x, int length) {
38 | int i;
39 | unsigned char tmp;
40 |
41 | if(endianness == IS_BIG_ENDIAN) {
42 | return;
43 | } else {
44 | for(i = 0; i < (length / 2); i++) {
45 | tmp = x[i];
46 | x[i] = x[length - i - 1];
47 | x[length - i - 1] = tmp;
48 | }
49 | }
50 | }
51 |
52 | static inline void flipEndianLE(unsigned char* x, int length) {
53 | int i;
54 | unsigned char tmp;
55 |
56 | if(endianness == IS_LITTLE_ENDIAN) {
57 | return;
58 | } else {
59 | for(i = 0; i < (length / 2); i++) {
60 | tmp = x[i];
61 | x[i] = x[length - i - 1];
62 | x[length - i - 1] = tmp;
63 | }
64 | }
65 | }
66 |
67 | static inline void hexToBytes(const char* hex, uint8_t** buffer, size_t* bytes) {
68 | *bytes = strlen(hex) / 2;
69 | *buffer = (uint8_t*) malloc(*bytes);
70 | size_t i;
71 | for(i = 0; i < *bytes; i++) {
72 | uint32_t byte;
73 | sscanf(hex, "%2x", &byte);
74 | (*buffer)[i] = byte;
75 | hex += 2;
76 | }
77 | }
78 |
79 | static inline void hexToInts(const char* hex, unsigned int** buffer, size_t* bytes) {
80 | *bytes = strlen(hex) / 2;
81 | *buffer = (unsigned int*) malloc((*bytes) * sizeof(int));
82 | size_t i;
83 | for(i = 0; i < *bytes; i++) {
84 | sscanf(hex, "%2x", &((*buffer)[i]));
85 | hex += 2;
86 | }
87 | }
88 |
89 | struct io_func_struct;
90 |
91 | typedef int (*readFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
92 | typedef int (*writeFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
93 | typedef void (*closeFunc)(struct io_func_struct* io);
94 |
95 | typedef struct io_func_struct {
96 | void* data;
97 | readFunc read;
98 | writeFunc write;
99 | closeFunc close;
100 | } io_func;
101 |
102 | struct AbstractFile;
103 |
104 | unsigned char* decodeBase64(char* toDecode, size_t* dataLength);
105 | void writeBase64(struct AbstractFile* file, unsigned char* data, size_t dataLength, int tabLength, int width);
106 | char* convertBase64(unsigned char* data, size_t dataLength, int tabLength, int width);
107 |
108 | #endif
109 |
--------------------------------------------------------------------------------
/old/emf_decrypter/includes/common.h:
--------------------------------------------------------------------------------
1 | #ifndef COMMON_H
2 | #define COMMON_H
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | #ifdef WIN32
11 | #define fseeko fseeko64
12 | #define ftello ftello64
13 | #define off_t off64_t
14 | #define mkdir(x, y) mkdir(x)
15 | #define PATH_SEPARATOR "\\"
16 | #else
17 | #define PATH_SEPARATOR "/"
18 | #endif
19 |
20 | #define TRUE 1
21 | #define FALSE 0
22 |
23 | #define FLIPENDIAN(x) flipEndian((unsigned char *)(&(x)), sizeof(x))
24 | #define FLIPENDIANLE(x) flipEndianLE((unsigned char *)(&(x)), sizeof(x))
25 |
26 | #define IS_BIG_ENDIAN 0
27 | #define IS_LITTLE_ENDIAN 1
28 |
29 | #define TIME_OFFSET_FROM_UNIX 2082844800L
30 | #define APPLE_TO_UNIX_TIME(x) ((x) - TIME_OFFSET_FROM_UNIX)
31 | #define UNIX_TO_APPLE_TIME(x) ((x) + TIME_OFFSET_FROM_UNIX)
32 |
33 | #define ASSERT(x, m) if(!(x)) { fflush(stdout); fprintf(stderr, "error: %s\n", m); perror("error"); fflush(stderr); exit(1); }
34 |
35 | extern char endianness;
36 |
37 | static inline void flipEndian(unsigned char* x, int length) {
38 | int i;
39 | unsigned char tmp;
40 |
41 | if(endianness == IS_BIG_ENDIAN) {
42 | return;
43 | } else {
44 | for(i = 0; i < (length / 2); i++) {
45 | tmp = x[i];
46 | x[i] = x[length - i - 1];
47 | x[length - i - 1] = tmp;
48 | }
49 | }
50 | }
51 |
52 | static inline void flipEndianLE(unsigned char* x, int length) {
53 | int i;
54 | unsigned char tmp;
55 |
56 | if(endianness == IS_LITTLE_ENDIAN) {
57 | return;
58 | } else {
59 | for(i = 0; i < (length / 2); i++) {
60 | tmp = x[i];
61 | x[i] = x[length - i - 1];
62 | x[length - i - 1] = tmp;
63 | }
64 | }
65 | }
66 |
67 | static inline void hexToBytes(const char* hex, uint8_t** buffer, size_t* bytes) {
68 | *bytes = strlen(hex) / 2;
69 | *buffer = (uint8_t*) malloc(*bytes);
70 | size_t i;
71 | for(i = 0; i < *bytes; i++) {
72 | uint32_t byte;
73 | sscanf(hex, "%2x", &byte);
74 | (*buffer)[i] = byte;
75 | hex += 2;
76 | }
77 | }
78 |
79 | static inline void hexToInts(const char* hex, unsigned int** buffer, size_t* bytes) {
80 | *bytes = strlen(hex) / 2;
81 | *buffer = (unsigned int*) malloc((*bytes) * sizeof(int));
82 | size_t i;
83 | for(i = 0; i < *bytes; i++) {
84 | sscanf(hex, "%2x", &((*buffer)[i]));
85 | hex += 2;
86 | }
87 | }
88 |
89 | struct io_func_struct;
90 |
91 | typedef int (*readFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
92 | typedef int (*writeFunc)(struct io_func_struct* io, off_t location, size_t size, void *buffer);
93 | typedef void (*closeFunc)(struct io_func_struct* io);
94 |
95 | typedef struct io_func_struct {
96 | void* data;
97 | readFunc read;
98 | writeFunc write;
99 | closeFunc close;
100 | } io_func;
101 |
102 | struct AbstractFile;
103 |
104 | unsigned char* decodeBase64(char* toDecode, size_t* dataLength);
105 | void writeBase64(struct AbstractFile* file, unsigned char* data, size_t dataLength, int tabLength, int width);
106 | char* convertBase64(unsigned char* data, size_t dataLength, int tabLength, int width);
107 |
108 | #endif
109 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | See http://code.google.com/p/iphone-dataprotection/wiki/README
2 |
3 | #Usage
4 |
5 | It works using OSX and the following:
6 |
7 | - Xcode 4.3 (xcode_43_lion.dmg) => Can be download from https://developer.apple.com/downloads/
8 | - SDK 5.0
9 | - iTunes 11.1.1
10 | - redsnow 0.9.15b3 (redsnow_mac_0.9.15b3)
11 |
12 |
13 | To run it, execute "boot.py" script.
14 |
15 |
16 | #Compilation instructions
17 |
18 | In order to compile ramdisk tools, you need to follow the next steps:
19 | - Copy "IOKit.frameworkHeaders" content to /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks/IOKit.framework/Headers/."
20 | - Execute build.py
21 |
22 | # Installation
23 |
24 | ## Santoku Linux
25 |
26 | - Install swig
27 |
28 | `
29 | sudo apt-get install swig
30 | `
31 |
32 | - Install PIP
33 |
34 | `
35 | sudo apt-get install python-pip
36 | `
37 |
38 | - Install Python dependencies
39 |
40 | ```
41 | sudo pip install progressbar
42 | sudo pip install setuptools
43 | sudo pip install construct==2.5.3
44 | sudo pip install pyasn1
45 | ```
46 |
47 | ## OSX
48 |
49 |
50 | - Download and install LDID
51 |
52 | ```
53 | sudo mkdir -p /usr/local/bin
54 | curl -O http://networkpx.googlecode.com/files/ldid $ chmod +x ldid
55 | sudo mv ldid /usr/local/bin
56 | ```
57 |
58 | - Verify codesign Allocate Tool
59 |
60 | ```
61 | which codesign_allocate
62 | /usr/bin/codesign_allocate
63 | sudo ln -s /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate /usr/local/bin/codesign_allocate
64 | ```
65 |
66 | - Install OSXFuse from:
67 | https://github.com/downloads/osxfuse/osxfuse/OSXFUSE-2.3.8.dmg
68 |
69 |
70 | - Install swig
71 |
72 | `
73 | brew install swig
74 | `
75 |
76 | - Install M2Crypto
77 |
78 | ```
79 | git clone https://github.com/M2Crypto/
80 | python setup.py build build_ext --openssl=/usr/local/Cellar/openssl/1.0.2/
81 | sudo python setup.py install build_ext --openssl=/usr/local/Cellar/openssl/1.0.2
82 | ```
83 |
84 | - Install python modules
85 |
86 | ```
87 | pip install progressbar
88 | pip install setuptools
89 | pip install construct
90 | pip install pyasn1
91 | pip install M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
92 | ```
93 | - Install M2Crypto for OSX
94 |
95 | ```
96 | curl -O http://chandlerproject.org/pub/Projects/MeTooCrypto/M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
97 | sudo easy_install M2Crypto-0.21.1-py2.7-macosx-10.9-intel.egg
98 | ```
99 |
100 | - Install pycrypto
101 |
102 | `
103 | sudo ARCHFLAGS='-arch i386 -arch x86_64' easy_install pycrypto
104 | `
105 |
106 | - Copy the Keys.plsit file to iPhone Data Protection tools directory:
107 |
108 | `
109 | ln -s redsn0w_mac_0.9.15b3/redsn0w.app/Contents/MacOS/Keys.plist .
110 | `
111 |
112 | - Install libssl
113 |
114 | `
115 | brew install openssl
116 | `
117 |
118 | - Build IMG3FS Tool
119 |
120 | ```
121 | cd img3fs
122 | make
123 | ```
124 |
125 | - Redefine the Xcode File-System Location
126 |
127 | `
128 | sudo ln -s /Applications/Xcode.app/Contents/Developer/ /Developer
129 | `
130 |
131 | #References
132 | http://www.dinosec.com/docs/Apple%20iOS%20Key%20Recovery%20with%20iPhone%20Data%20Protection%20Tools%2020121003.pdf
133 |
--------------------------------------------------------------------------------
/python_scripts/util/bruteforce.py:
--------------------------------------------------------------------------------
1 | from keystore.keybag import Keybag
2 | from keystore.effaceable import EffaceableLockers
3 | from util.ramdiskclient import RamdiskToolClient
4 | import plistlib
5 |
6 | COMPLEXITY={
7 | 0: "4 digits",
8 | 1: "n digits",
9 | 2: "n alphanum"
10 | }
11 |
12 | def checkPasscodeComplexity(data_volume):
13 | pl = data_volume.readFile("/mobile/Library/ConfigurationProfiles/UserSettings.plist", returnString=True)
14 | if not pl:
15 | print "Failed to read UserSettings.plist, assuming simple passcode"
16 | return 0
17 | pl = plistlib.readPlistFromString(pl)
18 | #print "passcodeKeyboardComplexity :", pl["restrictedValue"]["passcodeKeyboardComplexity"]
19 | value = pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"]
20 | print "passcodeKeyboardComplexity %d => %s" % (value, COMPLEXITY.get(value))
21 | return pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"]
22 |
23 | def loadKeybagFromVolume(volume, device_infos):
24 | systembag = volume.readFile("/keybags/systembag.kb", returnString=True)
25 | if not systembag or not systembag.startswith("bplist"):
26 | print "FAIL: could not read /keybags/systembag.kb from data partition"
27 | return False
28 | lockers = EffaceableLockers(device_infos["lockers"].data)
29 | bag1key = lockers.get("BAG1")[-32:]
30 | keybag = Keybag.createWithSystemkbfile(systembag, bag1key, device_infos.get("key835", "").decode("hex"))
31 | keybag.setDKey(device_infos)
32 | if device_infos.has_key("passcodeKey"):
33 | keybag.unlockWithPasscodeKey(device_infos.get("passcodeKey").decode("hex"))
34 | return keybag
35 |
36 | def bruteforcePasscode(device_infos, data_volume):
37 | if device_infos.has_key("passcode"):
38 | print "Passcode already found, no bruteforce required"
39 | return False
40 | kb = data_volume.keybag
41 | if not kb:
42 | return False
43 |
44 | rd = RamdiskToolClient.get()
45 | if rd.device_infos.udid != device_infos.udid:
46 | print "Wrong device connected"
47 | return
48 |
49 | print "Passcode comlexity (from OpaqueStuff) : %s" % COMPLEXITY.get(kb.passcodeComplexity)
50 | print "Enter passcode or leave blank for bruteforce:"
51 | z = raw_input()
52 | bf = rd.getPasscodeKey(kb.KeyBagKeys, z)
53 | if kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")):
54 | print "Passcode \"%s\" OK" % z
55 | else:
56 | if z != "":
57 | print "Wrong passcode, trying to bruteforce !"
58 | if kb.passcodeComplexity != 0:
59 | print "Complex passcode used, not bruteforcing"
60 | return False
61 |
62 | bf = rd.bruteforceKeyBag(kb.KeyBagKeys)
63 | if bf and kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")):
64 | print "Bruteforce successful, passcode : %s" % bf["passcode"]
65 | print "Passcode key : %s" % bf.get("passcodeKey")
66 | if kb.unlocked:
67 | device_infos.update(bf)
68 | device_infos["classKeys"] = kb.getClearClassKeysDict()
69 | device_infos["KeyBagKeys"] = plistlib.Data(kb.KeyBagKeys)
70 | return True
71 | return False
72 |
--------------------------------------------------------------------------------
/python_scripts/crypto/aeswrap.py:
--------------------------------------------------------------------------------
1 | import struct
2 | from Crypto.Cipher import AES
3 |
4 | """
5 | http://www.ietf.org/rfc/rfc3394.txt
6 | quick'n'dirty AES wrap implementation
7 | used by iOS 4 KeyStore kernel extension for wrapping/unwrapping encryption keys
8 | """
9 | def unpack64bit(s):
10 | return struct.unpack(">Q",s)[0]
11 | def pack64bit(s):
12 | return struct.pack(">Q",s)
13 |
14 | def AESUnwrap(kek, wrapped):
15 | C = []
16 | for i in xrange(len(wrapped)/8):
17 | C.append(unpack64bit(wrapped[i*8:i*8+8]))
18 | n = len(C) - 1
19 | R = [0] * (n+1)
20 | A = C[0]
21 |
22 | for i in xrange(1,n+1):
23 | R[i] = C[i]
24 |
25 | for j in reversed(xrange(0,6)):
26 | for i in reversed(xrange(1,n+1)):
27 | todec = pack64bit(A ^ (n*j+i))
28 | todec += pack64bit(R[i])
29 | B = AES.new(kek).decrypt(todec)
30 | A = unpack64bit(B[:8])
31 | R[i] = unpack64bit(B[8:])
32 |
33 | #assert A == 0xa6a6a6a6a6a6a6a6, "AESUnwrap: integrity check FAIL, wrong kek ?"
34 | if A != 0xa6a6a6a6a6a6a6a6:
35 | #print "AESUnwrap: integrity check FAIL, wrong kek ?"
36 | return None
37 | res = "".join(map(pack64bit, R[1:]))
38 | return res
39 |
40 | def AESwrap(kek, data):
41 | A = 0xa6a6a6a6a6a6a6a6
42 | R = [0]
43 | for i in xrange(len(data)/8):
44 | R.append(unpack64bit(data[i*8:i*8+8]))
45 | n = len(R) - 1
46 |
47 | for j in xrange(0,6):
48 | for i in xrange(1,n+1):
49 | B = AES.new(kek).encrypt(pack64bit(A) + pack64bit(R[i]))
50 | A = unpack64bit(B[:8]) ^ (n*j+i)
51 | R[i] = unpack64bit(B[8:])
52 |
53 | res = pack64bit(A) + "".join(map(pack64bit, R[1:]))
54 | return res
55 |
56 | if __name__ == "__main__":
57 | #format (kek, data, expected_ciphertext)
58 | test_vectors = [
59 | ("000102030405060708090A0B0C0D0E0F", "00112233445566778899AABBCCDDEEFF", "1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5"),
60 | ("000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF", "96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D"),
61 | ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF", "64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7"),
62 | ("000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF0001020304050607", "031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2"),
63 | ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF0001020304050607", "A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1"),
64 | ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F", "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21")
65 | ]
66 | for kek, data, expected in test_vectors:
67 | ciphertext = AESwrap(kek.decode("hex"), data.decode("hex"))
68 | assert ciphertext == expected.decode("hex")
69 | assert AESUnwrap(kek.decode("hex"), ciphertext) == data.decode("hex")
70 | print "All tests OK !"
71 |
--------------------------------------------------------------------------------
/python_scripts/nand/structs.py:
--------------------------------------------------------------------------------
1 | from construct.core import Struct, Union
2 | from construct.macros import *
3 |
4 | #hardcoded iOS keys
5 | META_KEY = "92a742ab08c969bf006c9412d3cc79a5".decode("hex")
6 | FILESYSTEM_KEY = "f65dae950e906c42b254cc58fc78eece".decode("hex")
7 |
8 | def next_power_of_two(z):
9 | i = 1
10 | while i < z:
11 | i <<= 1
12 | return i
13 |
14 | def CEIL_DIVIDE(val, amt):
15 | return (((val) + (amt) - 1) / (amt))
16 |
17 | #from openiboot/plat-s5l8920/h2fmi.c
18 | #blocks_per_ce, pages_per_block, bytes_per_page, bytes_per_spare, unk5, unk6, unk7, banks_per_ce, unk9
19 | #some values change in openiboot/plat-a4/h2fmi.c, but banks_per_ce is ok
20 | nand_chip_info = {
21 | 0x7294D7EC : [ 0x1038, 0x80, 0x2000, 0x1B4, 0xC, 0, 8, 1, 0 ],
22 | 0x72D5DEEC : [ 0x2070, 0x80, 0x2000, 0x1B4, 0xC, 0, 8, 2, 0 ],
23 | 0x29D5D7EC : [ 0x2000, 0x80, 0x1000, 0xDA, 8, 0, 2, 2, 0 ],
24 | 0x2994D5EC : [ 0x1000, 0x80, 0x1000, 0xDA, 8, 0, 2, 1, 0 ],
25 | 0xB614D5EC : [ 0x1000, 0x80, 0x1000, 0x80, 4, 0, 2, 1, 0 ],
26 | 0xB655D7EC : [ 0x2000, 0x80, 0x1000, 0x80, 4, 0, 2, 2, 0 ],
27 | 0xB614D5AD : [ 0x1000, 0x80, 0x1000, 0x80, 4, 0, 3, 1, 0 ],
28 | 0x3294E798 : [ 0x1004, 0x80, 0x2000, 0x1C0, 0x10, 0, 1, 1, 0 ],
29 | 0xBA94D598 : [ 0x1000, 0x80, 0x1000, 0xDA, 8, 0, 1, 1, 0 ],
30 | 0xBA95D798 : [ 0x2000, 0x80, 0x1000, 0xDA, 8, 0, 1, 2, 0 ],
31 | 0x3294D798 : [ 0x1034, 0x80, 0x2000, 0x178, 8, 0, 1, 1, 0 ],
32 | 0x3295DE98 : [ 0x2068, 0x80, 0x2000, 0x178, 8, 0, 1, 2, 0 ],
33 | 0x3295EE98 : [ 0x2008, 0x80, 0x2000, 0x1C0, 0x18, 0, 1, 2, 0 ],
34 | 0x3E94D789 : [ 0x2000, 0x80, 0x1000, 0xDA, 0x10, 0, 5, 1, 0 ],
35 | 0x3ED5D789 : [ 0x2000, 0x80, 0x1000, 0xDA, 8, 0, 6, 2, 0 ],
36 | 0x3ED5D72C : [ 0x2000, 0x80, 0x1000, 0xDA, 8, 0, 5, 2, 0 ],
37 | 0x3E94D72C : [ 0x2000, 0x80, 0x1000, 0xDA, 0xC, 0, 7, 1, 0 ],
38 | 0x4604682C : [ 0x1000, 0x100, 0x1000, 0xE0, 0xC, 0, 7, 1, 0 ],
39 | 0x3294D745 : [ 0x1000, 0x80, 0x2000, 0x178, 8, 0, 9, 1, 0 ],
40 | 0x3295DE45 : [ 0x2000, 0x80, 0x2000, 0x178, 8, 0, 9, 2, 0 ],
41 | 0x32944845 : [ 0x1000, 0x80, 0x2000, 0x1C0, 8, 0, 9, 1, 0 ],
42 | 0x32956845 : [ 0x2000, 0x80, 0x2000, 0x1C0, 8, 0, 9, 2, 0 ],
43 | 0x7ad5deec : [ 0x0000, 0x00, 0x0000, 0x000, 0, 0, 0, 2, 0 ] #iPad2 gsm 64gb
44 | }
45 |
46 | #https://github.com/iDroid-Project/openiBoot/blob/master/openiboot/plat-a4/h2fmi.c
47 | def gen_h2fmi_hash_table():
48 | val = 0x50F4546A;
49 | h2fmi_hash_table = [0]*256
50 | for i in xrange(256):
51 | val = ((0x19660D * val) + 0x3C6EF35F) & 0xffffffff;
52 | for j in xrange(762):
53 | val = ((0x19660D * val) + 0x3C6EF35F) & 0xffffffff;
54 | h2fmi_hash_table[i] = val & 0xffffffff
55 | return h2fmi_hash_table
56 |
57 | # Page types (as defined in the spare data "type" bitfield)
58 | PAGETYPE_INDEX = 0x4 #Index block indicator
59 | PAGETYPE_LBN = 0x10 # User data
60 | PAGETYPE_FTL_CLEAN = 0x20 # FTL context (unmounted, clean)
61 | PAGETYPE_VFL = 0x80 #/ VFL context
62 |
63 | SpareData = Struct("SpareData",
64 | ULInt32("lpn"),
65 | ULInt32("usn"),
66 | ULInt8("field_8"),
67 | ULInt8("type"),
68 | ULInt16("field_A")
69 | )
70 |
71 | # Block status (as defined in the BlockStruct structure)
72 | BLOCKSTATUS_ALLOCATED = 0x1
73 | BLOCKSTATUS_FTLCTRL = 0x2
74 | BLOCKSTATUS_GC = 0x4
75 | BLOCKSTATUS_CURRENT = 0x8
76 | BLOCKSTATUS_FTLCTRL_SEL = 0x10
77 | BLOCKSTATUS_I_GC = 0x20
78 | BLOCKSTATUS_I_ALLOCATED = 0x40
79 | BLOCKSTATUS_I_CURRENT = 0x80
80 | BLOCKSTATUS_FREE = 0xFF
81 |
82 | ERROR_ARG = 0x80000001
83 | ERROR_NAND = 0x80000002
84 | ERROR_EMPTY = 0x80000003
85 |
--------------------------------------------------------------------------------
/ramdisk_tools/bsdcrypto/key_wrap.c:
--------------------------------------------------------------------------------
1 | /* $OpenBSD: key_wrap.c,v 1.3 2011/01/11 15:42:05 deraadt Exp $ */
2 |
3 | /*-
4 | * Copyright (c) 2008 Damien Bergamini
5 | *
6 | * Permission to use, copy, modify, and distribute this software for any
7 | * purpose with or without fee is hereby granted, provided that the above
8 | * copyright notice and this permission notice appear in all copies.
9 | *
10 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 | */
18 |
19 | /*
20 | * This code implements the AES Key Wrap algorithm described in RFC 3394.
21 | */
22 |
23 | #include
24 | #include
25 |
26 | //haxs to compile on osx
27 | #include
28 | #define timingsafe_bcmp bcmp
29 | #define ovbcopy bcopy
30 | #define explicit_bzero bzero
31 | #define htobe64 CFSwapInt64BigToHost
32 | #include "rijndael.h"
33 | #include "key_wrap.h"
34 |
35 |
36 | static const u_int8_t IV[8] =
37 | { 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6 };
38 |
39 | void
40 | aes_key_wrap_set_key(aes_key_wrap_ctx *ctx, const u_int8_t *K, size_t K_len)
41 | {
42 | rijndael_set_key(&ctx->ctx, K, K_len * NBBY);
43 | }
44 |
45 | void
46 | aes_key_wrap_set_key_wrap_only(aes_key_wrap_ctx *ctx, const u_int8_t *K,
47 | size_t K_len)
48 | {
49 | rijndael_set_key_enc_only(&ctx->ctx, K, K_len * NBBY);
50 | }
51 |
52 | void
53 | aes_key_wrap(aes_key_wrap_ctx *ctx, const u_int8_t *P, size_t n, u_int8_t *C)
54 | {
55 | u_int64_t B[2], t;
56 | u_int8_t *A, *R;
57 | size_t i;
58 | int j;
59 |
60 | ovbcopy(P, C + 8, n * 8); /* P and C may overlap */
61 | A = C; /* A points to C[0] */
62 | memcpy(A, IV, 8); /* A = IV, an initial value */
63 |
64 | for (j = 0, t = 1; j <= 5; j++) {
65 | R = C + 8;
66 | for (i = 1; i <= n; i++, t++) {
67 | /* B = A | R[i] */
68 | memcpy(&B[0], A, 8);
69 | memcpy(&B[1], R, 8);
70 | /* B = AES(K, B) */
71 | rijndael_encrypt(&ctx->ctx, (caddr_t)B, (caddr_t)B);
72 | /* MSB(64, B) = MSB(64, B) ^ t */
73 | B[0] ^= htobe64(t);
74 | /* A = MSB(64, B) */
75 | memcpy(A, &B[0], 8);
76 | /* R[i] = LSB(64, B) */
77 | memcpy(R, &B[1], 8);
78 |
79 | R += 8;
80 | }
81 | }
82 | explicit_bzero(B, sizeof B);
83 | }
84 |
85 | int
86 | aes_key_unwrap(aes_key_wrap_ctx *ctx, const u_int8_t *C, u_int8_t *P, size_t n)
87 | {
88 | u_int64_t B[2], t;
89 | u_int8_t A[8], *R;
90 | size_t i;
91 | int j;
92 |
93 | memcpy(A, C, 8); /* A = C[0] */
94 | ovbcopy(C + 8, P, n * 8); /* P and C may overlap */
95 |
96 | for (j = 5, t = 6 * n; j >= 0; j--) {
97 | R = P + (n - 1) * 8;
98 | for (i = n; i >= 1; i--, t--) {
99 | /* MSB(64, B) = A */
100 | memcpy(&B[0], A, 8);
101 | /* MSB(64, B) = MSB(64, B) ^ t */
102 | B[0] ^= htobe64(t);
103 | /* B = MSB(64, B) | R[i] */
104 | memcpy(&B[1], R, 8);
105 | /* B = AES-1(K, B) */
106 | rijndael_decrypt(&ctx->ctx, (caddr_t)B, (caddr_t)B);
107 | /* A = MSB(64, B) */
108 | memcpy(A, &B[0], 8);
109 | /* R[i] = LSB(64, B) */
110 | memcpy(R, &B[1], 8);
111 |
112 | R -= 8;
113 | }
114 | }
115 | explicit_bzero(B, sizeof B);
116 |
117 | /* check that A is an appropriate initial value */
118 | return timingsafe_bcmp(A, IV, 8) != 0;
119 | }
120 |
--------------------------------------------------------------------------------
/emf_decrypter/hfs/extents.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | static inline void flipExtentDescriptor(HFSPlusExtentDescriptor* extentDescriptor) {
6 | FLIPENDIAN(extentDescriptor->startBlock);
7 | FLIPENDIAN(extentDescriptor->blockCount);
8 | }
9 |
10 | void flipExtentRecord(HFSPlusExtentRecord* extentRecord) {
11 | HFSPlusExtentDescriptor *extentDescriptor;
12 | extentDescriptor = (HFSPlusExtentDescriptor*)extentRecord;
13 |
14 | flipExtentDescriptor(&extentDescriptor[0]);
15 | flipExtentDescriptor(&extentDescriptor[1]);
16 | flipExtentDescriptor(&extentDescriptor[2]);
17 | flipExtentDescriptor(&extentDescriptor[3]);
18 | flipExtentDescriptor(&extentDescriptor[4]);
19 | flipExtentDescriptor(&extentDescriptor[5]);
20 | flipExtentDescriptor(&extentDescriptor[6]);
21 | flipExtentDescriptor(&extentDescriptor[7]);
22 | }
23 |
24 | static int extentCompare(BTKey* vLeft, BTKey* vRight) {
25 | HFSPlusExtentKey* left;
26 | HFSPlusExtentKey* right;
27 |
28 | left = (HFSPlusExtentKey*) vLeft;
29 | right =(HFSPlusExtentKey*) vRight;
30 |
31 | if(left->forkType < right->forkType) {
32 | return -1;
33 | } else if(left->forkType > right->forkType) {
34 | return 1;
35 | } else {
36 | if(left->fileID < right->fileID) {
37 | return -1;
38 | } else if(left->fileID > right->fileID) {
39 | return 1;
40 | } else {
41 | if(left->startBlock < right->startBlock) {
42 | return -1;
43 | } else if(left->startBlock > right->startBlock) {
44 | return 1;
45 | } else {
46 | /* do a safety check on key length. Otherwise, bad things may happen later on when we try to add or remove with this key */
47 | if(left->keyLength == right->keyLength) {
48 | return 0;
49 | } else if(left->keyLength < right->keyLength) {
50 | return -1;
51 | } else {
52 | return 1;
53 | }
54 | return 0;
55 | }
56 | }
57 | }
58 | }
59 |
60 | static BTKey* extentKeyRead(off_t offset, io_func* io) {
61 | HFSPlusExtentKey* key;
62 |
63 | key = (HFSPlusExtentKey*) malloc(sizeof(HFSPlusExtentKey));
64 |
65 | if(!READ(io, offset, sizeof(HFSPlusExtentKey), key))
66 | return NULL;
67 |
68 | FLIPENDIAN(key->keyLength);
69 | FLIPENDIAN(key->forkType);
70 | FLIPENDIAN(key->fileID);
71 | FLIPENDIAN(key->startBlock);
72 |
73 | return (BTKey*)key;
74 | }
75 |
76 | static int extentKeyWrite(off_t offset, BTKey* toWrite, io_func* io) {
77 | HFSPlusExtentKey* key;
78 |
79 | key = (HFSPlusExtentKey*) malloc(sizeof(HFSPlusExtentKey));
80 |
81 | memcpy(key, toWrite, sizeof(HFSPlusExtentKey));
82 |
83 | FLIPENDIAN(key->keyLength);
84 | FLIPENDIAN(key->forkType);
85 | FLIPENDIAN(key->fileID);
86 | FLIPENDIAN(key->startBlock);
87 |
88 | if(!WRITE(io, offset, sizeof(HFSPlusExtentKey), key))
89 | return FALSE;
90 |
91 | free(key);
92 |
93 | return TRUE;
94 | }
95 |
96 | static void extentKeyPrint(BTKey* toPrint) {
97 | HFSPlusExtentKey* key;
98 |
99 | key = (HFSPlusExtentKey*)toPrint;
100 |
101 | printf("extent%d:%d:%d", key->forkType, key->fileID, key->startBlock);
102 | }
103 |
104 | static BTKey* extentDataRead(off_t offset, io_func* io) {
105 | HFSPlusExtentRecord* record;
106 |
107 | record = (HFSPlusExtentRecord*) malloc(sizeof(HFSPlusExtentRecord));
108 |
109 | if(!READ(io, offset, sizeof(HFSPlusExtentRecord), record))
110 | return NULL;
111 |
112 | flipExtentRecord(record);
113 |
114 | return (BTKey*)record;
115 | }
116 |
117 | BTree* openExtentsTree(io_func* file) {
118 | return openBTree(file, &extentCompare, &extentKeyRead, &extentKeyWrite, &extentKeyPrint, &extentDataRead);
119 | }
120 |
--------------------------------------------------------------------------------
/old/emf_decrypter/hfs/extents.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | static inline void flipExtentDescriptor(HFSPlusExtentDescriptor* extentDescriptor) {
6 | FLIPENDIAN(extentDescriptor->startBlock);
7 | FLIPENDIAN(extentDescriptor->blockCount);
8 | }
9 |
10 | void flipExtentRecord(HFSPlusExtentRecord* extentRecord) {
11 | HFSPlusExtentDescriptor *extentDescriptor;
12 | extentDescriptor = (HFSPlusExtentDescriptor*)extentRecord;
13 |
14 | flipExtentDescriptor(&extentDescriptor[0]);
15 | flipExtentDescriptor(&extentDescriptor[1]);
16 | flipExtentDescriptor(&extentDescriptor[2]);
17 | flipExtentDescriptor(&extentDescriptor[3]);
18 | flipExtentDescriptor(&extentDescriptor[4]);
19 | flipExtentDescriptor(&extentDescriptor[5]);
20 | flipExtentDescriptor(&extentDescriptor[6]);
21 | flipExtentDescriptor(&extentDescriptor[7]);
22 | }
23 |
24 | static int extentCompare(BTKey* vLeft, BTKey* vRight) {
25 | HFSPlusExtentKey* left;
26 | HFSPlusExtentKey* right;
27 |
28 | left = (HFSPlusExtentKey*) vLeft;
29 | right =(HFSPlusExtentKey*) vRight;
30 |
31 | if(left->forkType < right->forkType) {
32 | return -1;
33 | } else if(left->forkType > right->forkType) {
34 | return 1;
35 | } else {
36 | if(left->fileID < right->fileID) {
37 | return -1;
38 | } else if(left->fileID > right->fileID) {
39 | return 1;
40 | } else {
41 | if(left->startBlock < right->startBlock) {
42 | return -1;
43 | } else if(left->startBlock > right->startBlock) {
44 | return 1;
45 | } else {
46 | /* do a safety check on key length. Otherwise, bad things may happen later on when we try to add or remove with this key */
47 | if(left->keyLength == right->keyLength) {
48 | return 0;
49 | } else if(left->keyLength < right->keyLength) {
50 | return -1;
51 | } else {
52 | return 1;
53 | }
54 | return 0;
55 | }
56 | }
57 | }
58 | }
59 |
60 | static BTKey* extentKeyRead(off_t offset, io_func* io) {
61 | HFSPlusExtentKey* key;
62 |
63 | key = (HFSPlusExtentKey*) malloc(sizeof(HFSPlusExtentKey));
64 |
65 | if(!READ(io, offset, sizeof(HFSPlusExtentKey), key))
66 | return NULL;
67 |
68 | FLIPENDIAN(key->keyLength);
69 | FLIPENDIAN(key->forkType);
70 | FLIPENDIAN(key->fileID);
71 | FLIPENDIAN(key->startBlock);
72 |
73 | return (BTKey*)key;
74 | }
75 |
76 | static int extentKeyWrite(off_t offset, BTKey* toWrite, io_func* io) {
77 | HFSPlusExtentKey* key;
78 |
79 | key = (HFSPlusExtentKey*) malloc(sizeof(HFSPlusExtentKey));
80 |
81 | memcpy(key, toWrite, sizeof(HFSPlusExtentKey));
82 |
83 | FLIPENDIAN(key->keyLength);
84 | FLIPENDIAN(key->forkType);
85 | FLIPENDIAN(key->fileID);
86 | FLIPENDIAN(key->startBlock);
87 |
88 | if(!WRITE(io, offset, sizeof(HFSPlusExtentKey), key))
89 | return FALSE;
90 |
91 | free(key);
92 |
93 | return TRUE;
94 | }
95 |
96 | static void extentKeyPrint(BTKey* toPrint) {
97 | HFSPlusExtentKey* key;
98 |
99 | key = (HFSPlusExtentKey*)toPrint;
100 |
101 | printf("extent%d:%d:%d", key->forkType, key->fileID, key->startBlock);
102 | }
103 |
104 | static BTKey* extentDataRead(off_t offset, io_func* io) {
105 | HFSPlusExtentRecord* record;
106 |
107 | record = (HFSPlusExtentRecord*) malloc(sizeof(HFSPlusExtentRecord));
108 |
109 | if(!READ(io, offset, sizeof(HFSPlusExtentRecord), record))
110 | return NULL;
111 |
112 | flipExtentRecord(record);
113 |
114 | return (BTKey*)record;
115 | }
116 |
117 | BTree* openExtentsTree(io_func* file) {
118 | return openBTree(file, &extentCompare, &extentKeyRead, &extentKeyWrite, &extentKeyPrint, &extentDataRead);
119 | }
120 |
--------------------------------------------------------------------------------
/python_scripts/nand/remote.py:
--------------------------------------------------------------------------------
1 | from progressbar import ProgressBar
2 | from usbmux import usbmux
3 | from util import hexdump, sizeof_fmt
4 | import datetime
5 | import hashlib
6 | import struct
7 | import os
8 |
9 | CMD_DUMP = 0
10 | CMD_PROXY = 1
11 | kIOFlashStorageOptionRawPageIO = 0x002
12 | kIOFlashStorageOptionBootPageIO = 0x100
13 |
14 | class IOFlashStorageKitClient(object):
15 | def __init__(self, udid=None, host="localhost", port=2000):
16 | self.host = host
17 | self.port = port
18 | self.connect(udid)
19 |
20 | def connect(self, udid=None):
21 | mux = usbmux.USBMux()
22 | mux.process(1.0)
23 | if not mux.devices:
24 | print "Waiting for iOS device"
25 | while not mux.devices:
26 | mux.process(1.0)
27 | if not mux.devices:
28 | print "No device found"
29 | return
30 | dev = mux.devices[0]
31 | try:
32 | self.s = mux.connect(dev, self.port)
33 | except:
34 | raise Exception("Connexion to device %s port %d failed" % (dev.serial, self.port))
35 |
36 | def send_command(self, cmd):
37 | return self.s.send(struct.pack("= 1099511627776:
70 | terabytes = bytes / 1099511627776
71 | size = '%.2fT' % terabytes
72 | elif bytes >= 1073741824:
73 | gigabytes = bytes / 1073741824
74 | size = '%.2fG' % gigabytes
75 | elif bytes >= 1048576:
76 | megabytes = bytes / 1048576
77 | size = '%.2fM' % megabytes
78 | elif bytes >= 1024:
79 | kilobytes = bytes / 1024
80 | size = '%.2fK' % kilobytes
81 | else:
82 | size = '%.2fb' % bytes
83 | return size
84 |
85 | def xor_strings(a,b):
86 | r=""
87 | for i in xrange(len(a)):
88 | r+= chr(ord(a[i])^ord(b[i]))
89 | return r
90 |
91 | hex = lambda data: " ".join("%02X" % ord(i) for i in data)
92 | ascii = lambda data: "".join(c if 31 < ord(c) < 127 else "." for c in data)
93 |
94 | def hexdump(d):
95 | for i in xrange(0,len(d),16):
96 | data = d[i:i+16]
97 | print "%08X | %s | %s" % (i, hex(data).ljust(47), ascii(data))
98 |
99 | def search_plist(directory, matchDict):
100 | for p in map(os.path.normpath, glob.glob(directory + "/*.plist")):
101 | try:
102 | d = plistlib.readPlist(p)
103 | ok = True
104 | for k,v in matchDict.items():
105 | if d.get(k) != v:
106 | ok = False
107 | break
108 | if ok:
109 | print "Using plist file %s" % p
110 | return d
111 | except:
112 | continue
113 |
114 | def save_pickle(filename,data):
115 | f = gzip.open(filename,"wb")
116 | cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)
117 | f.close()
118 |
119 | def load_pickle(filename):
120 | f = gzip.open(filename,"rb")
121 | data = cPickle.load(f)
122 | f.close()
123 | return data
124 |
--------------------------------------------------------------------------------
/ramdisk_tools/device_info.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include "IOAESAccelerator.h"
7 | #include "AppleEffaceableStorage.h"
8 | #include "bsdcrypto/rijndael.h"
9 | #include "bsdcrypto/key_wrap.h"
10 | #include "device_info.h"
11 | #include "registry.h"
12 | #include "util.h"
13 | #include "ioflash/ioflash.h"
14 |
15 | uint8_t lockers[960]={0};
16 | uint8_t lwvm[80]={0};
17 |
18 | CFMutableDictionaryRef device_info(int socket, CFDictionaryRef request)
19 | {
20 | uint8_t dkey[40]={0};
21 | uint8_t emf[36]={0};
22 | size_t bootargs_len = 255;
23 | char bootargs[256]={0};
24 |
25 | struct HFSInfos hfsinfos={0};
26 |
27 | CFMutableDictionaryRef out = CFDictionaryCreateMutable(kCFAllocatorDefault,
28 | 0,
29 | &kCFTypeDictionaryKeyCallBacks,
30 | &kCFTypeDictionaryValueCallBacks);
31 |
32 | get_device_infos(out);
33 |
34 | CFMutableDictionaryRef nand = FSDGetInfo();
35 | if (nand != NULL)
36 | CFDictionaryAddValue(out, CFSTR("nand"), nand);
37 |
38 | getHFSInfos(&hfsinfos);
39 |
40 | uint8_t* key835 = IOAES_key835();
41 | uint8_t* key89A = IOAES_key89A();
42 | uint8_t* key89B = IOAES_key89B();
43 |
44 | if (!AppleEffaceableStorage__getBytes(lockers, 960))
45 | {
46 | CFDataRef lockersData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, lockers, 960, kCFAllocatorNull);
47 | CFDictionaryAddValue(out, CFSTR("lockers"), lockersData);
48 | CFRelease(lockersData);
49 |
50 | if (!AppleEffaceableStorage__getLockerFromBytes(LOCKER_DKEY, lockers, 960, dkey, 40))
51 | {
52 | aes_key_wrap_ctx ctx;
53 |
54 | aes_key_wrap_set_key(&ctx, key835, 16);
55 |
56 | if(aes_key_unwrap(&ctx, dkey, dkey, 32/8))
57 | printf("FAIL unwrapping DKey with key 0x835\n");
58 | else
59 | addHexaString(out, CFSTR("DKey"), dkey, 32);
60 | }
61 | if (!AppleEffaceableStorage__getLockerFromBytes(LOCKER_EMF, lockers, 960, emf, 36))
62 | {
63 | doAES(&emf[4], &emf[4], 32, kIOAESAcceleratorCustomMask, key89B, NULL, kIOAESAcceleratorDecrypt, 128);
64 | addHexaString(out, CFSTR("EMF"), &emf[4], 32);
65 | }
66 | else if (!AppleEffaceableStorage__getLockerFromBytes(LOCKER_LWVM, lockers, 960, lwvm, 0x50))
67 | {
68 | doAES(lwvm, lwvm, 0x50, kIOAESAcceleratorCustomMask, key89B, NULL, kIOAESAcceleratorDecrypt, 128);
69 | memcpy(&emf[4], &lwvm[32+16], 32);
70 | addHexaString(out, CFSTR("EMF"), &emf[4], 32);
71 | }
72 | }
73 |
74 | CFNumberRef n = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &hfsinfos.dataVolumeOffset);
75 | CFDictionaryAddValue(out, CFSTR("dataVolumeOffset"), n);
76 | CFRelease(n);
77 | addHexaString(out, CFSTR("dataVolumeUUID"), (uint8_t*) &hfsinfos.volumeUUID, 8);
78 | addHexaString(out, CFSTR("key835"), key835, 16);
79 | addHexaString(out, CFSTR("key89A"), key89A, 16);
80 | addHexaString(out, CFSTR("key89B"), key89B, 16);
81 |
82 | sysctlbyname("kern.bootargs", bootargs, &bootargs_len, NULL, 0);
83 | if (bootargs_len > 1)
84 | {
85 | CFStringRef bootargsString = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8*) bootargs, bootargs_len - 1, kCFStringEncodingASCII, 0);
86 | CFDictionaryAddValue(out, CFSTR("kern.bootargs"), bootargsString);
87 | CFRelease(bootargsString);
88 | }
89 |
90 | CFDictionaryAddValue(out, CFSTR("ramdisk revision"), CFSTR(HGVERSION));
91 | CFDictionaryAddValue(out, CFSTR("ramdisk compile time"), CFSTR(__DATE__ " " __TIME__ ));
92 |
93 | return out;
94 | }
95 |
--------------------------------------------------------------------------------
/python_scripts/nand/image.py:
--------------------------------------------------------------------------------
1 | import os
2 | import struct
3 | import sys
4 |
5 | """
6 | row-by-row dump
7 | page = data + spare metadata + iokit return code + iokit return code 2
8 | """
9 | class NANDImageFlat(object):
10 | def __init__(self, filename, geometry):
11 | flags = os.O_RDONLY
12 | if sys.platform == "win32":
13 | flags |= os.O_BINARY
14 | self.fd = os.open(filename, flags)
15 | self.nCEs = geometry["#ce"]
16 | self.ppn = geometry.get("ppn-device", False)
17 | self.pageSize = geometry["#page-bytes"]
18 | self.metaSize = geometry.get("meta-per-logical-page", 12)
19 | if self.metaSize == 0: self.metaSize = 12
20 | self.dumpedPageSize = geometry.get("dumpedPageSize", self.pageSize + self.metaSize + 8)
21 | self.hasIOKitStatus = True
22 | if self.dumpedPageSize == self.pageSize + geometry["#spare-bytes"] + 8:
23 | self.metaSize = geometry["#spare-bytes"]
24 | if self.dumpedPageSize == self.pageSize + geometry["#spare-bytes"] or self.dumpedPageSize == self.pageSize + self.metaSize:
25 | self.hasIOKitStatus = False
26 | self.blankPage = "\xFF" * self.pageSize
27 | self.blankSpare = "\xFF" * self.metaSize
28 | self.imageSize = os.path.getsize(filename)
29 | expectedSize = geometry["#ce"] * geometry["#ce-blocks"] * geometry["#block-pages"] * self.dumpedPageSize
30 | if self.imageSize < expectedSize:
31 | raise Exception("Error: image appears to be truncated, expected size=%d" % expectedSize)
32 | print "Image size matches expected size, looks ok"
33 |
34 | def _readPage(self, ce, page):
35 | i = page * self.nCEs + ce
36 | off = i * self.dumpedPageSize
37 | os.lseek(self.fd, off, os.SEEK_SET)
38 | return os.read(self.fd, self.dumpedPageSize)
39 |
40 | def readPage(self, ce, page, boot=False):
41 | d = self._readPage(ce, page)
42 | if not d or len(d) != self.dumpedPageSize:
43 | return None,None
44 | if self.hasIOKitStatus and not self.ppn:#ppn iokit codes are bogus
45 | r1,r2 = struct.unpack("
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "hfs/hfslib.h"
9 | #include "emf.h"
10 |
11 | size_t ConvertHexaCFString(CFStringRef s, uint8_t** bytes)
12 | {
13 | uint32_t len = CFStringGetLength(s);
14 | uint8_t* hex = malloc(len+1);
15 |
16 | if(hex == NULL)
17 | return 0;
18 |
19 | if(!CFStringGetCString(s, hex, len+1, kCFStringEncodingASCII))
20 | {
21 | free(hex);
22 | return 0;
23 | }
24 | size_t size = 0;
25 | hexToBytes(hex, bytes, &size);
26 | free(hex);
27 | return size;
28 | }
29 |
30 | void grabClassKey(const void *key, const void *value, void *context)
31 | {
32 | EMFInfo* emf = (EMFInfo*) context;
33 | uint8_t* class_key = NULL;
34 |
35 | if(CFGetTypeID(key) != CFStringGetTypeID() || CFGetTypeID(value) != CFStringGetTypeID())
36 | return;
37 |
38 | SInt32 clas = CFStringGetIntValue((CFStringRef)key);
39 |
40 | if(clas > 0 && clas <= MAX_CLASS_KEYS && CFStringGetLength((CFStringRef) value) == 64)
41 | {
42 | if(ConvertHexaCFString(value, &class_key) == 32)
43 | {
44 | AES_set_decrypt_key(class_key, 32*8, &(emf->classKeys[clas-1]));
45 | free(class_key);
46 | emf->classKeys_bitset |= 1 << clas;
47 | }
48 | }
49 |
50 | }
51 |
52 | EMFInfo* EMF_init(Volume* volume, char* imagePath)
53 | {
54 | uint8_t* emfk = NULL;
55 | uint8_t* dkey = NULL;
56 |
57 | uint64_t volume_id = *((uint64_t*) (&volume->volumeHeader->finderInfo[6]));
58 | FLIPENDIAN(volume_id);
59 |
60 | if(imagePath == NULL)
61 | imagePath = ".";
62 |
63 | printf("Volume identifier : %llx\n", volume_id);
64 | printf("Searching for %s/%llx.plist\n", imagePath, volume_id);
65 |
66 | CFStringRef path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%llx.plist"), imagePath, volume_id);
67 |
68 | CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, FALSE);
69 | CFRelease(path);
70 |
71 | CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, fileURL);
72 | CFRelease(fileURL);
73 |
74 | if(stream == NULL)
75 | {
76 | return NULL;
77 | }
78 | if(!CFReadStreamOpen(stream))
79 | {
80 | fprintf(stderr, "Cannot open file\n");
81 | return NULL;
82 | }
83 | CFPropertyListRef dict = CFPropertyListCreateWithStream(NULL, stream, 0, kCFPropertyListImmutable, NULL, NULL);
84 |
85 | CFRelease(stream);
86 |
87 | if (dict == NULL || CFGetTypeID(dict) != CFDictionaryGetTypeID())
88 | return NULL;
89 |
90 | CFStringRef emfHex = CFDictionaryGetValue(dict, CFSTR("EMF"));
91 | CFStringRef dkeyHex = CFDictionaryGetValue(dict, CFSTR("DKey"));
92 | CFNumberRef dataVolumeOffset = CFDictionaryGetValue (dict, CFSTR("dataVolumeOffset"));
93 |
94 | if (emfHex == NULL || CFGetTypeID(emfHex) != CFStringGetTypeID())
95 | return NULL;
96 | if (dkeyHex == NULL || CFGetTypeID(dkeyHex) != CFStringGetTypeID())
97 | return NULL;
98 | if (dataVolumeOffset == NULL || CFGetTypeID(dataVolumeOffset) != CFNumberGetTypeID())
99 | return NULL;
100 |
101 | EMFInfo* emf = malloc(sizeof(EMFInfo));
102 |
103 | if(emf == NULL)
104 | return NULL;
105 |
106 | memset(emf, 0, sizeof(EMFInfo));
107 |
108 | emf->volume = volume;
109 |
110 | CFNumberGetValue(dataVolumeOffset, kCFNumberLongType, &emf->volume_offset);
111 |
112 | printf("Data partition offset = %llx\n", emf->volume_offset);
113 |
114 | if(ConvertHexaCFString(emfHex, &emfk) != 32)
115 | {
116 | fprintf(stderr, "Invalid EMF key\n");
117 | free(emf);
118 | return NULL;
119 | }
120 | if(ConvertHexaCFString(dkeyHex, &dkey) != 32)
121 | {
122 | fprintf(stderr, "Invalid DKey key\n");
123 | free(emf);
124 | return NULL;
125 | }
126 |
127 | AES_set_encrypt_key(emfk, 32*8, &(emf->emfkey));
128 | AES_set_decrypt_key(dkey, 32*8, &(emf->classKeys[CLASS_DKEY-1]));
129 | emf->classKeys_bitset |= 1 << CLASS_DKEY;
130 |
131 | CFDictionaryRef classKeys = CFDictionaryGetValue(dict, CFSTR("classKeys"));
132 |
133 | if(classKeys != NULL && CFGetTypeID(classKeys) == CFDictionaryGetTypeID())
134 | {
135 | printf("Reading class keys, NSProtectionComplete files should be decrypted OK\n");
136 | CFDictionaryApplyFunction(classKeys, grabClassKey, (void*) emf);
137 | }
138 | else
139 | {
140 | printf("Only NSProtectionNone files will be decrypted\n");
141 | }
142 |
143 | free(emfk);
144 | free(dkey);
145 | return emf;
146 | }
147 |
--------------------------------------------------------------------------------
/old/emf_decrypter/emf/emf_init.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "hfs/hfslib.h"
9 | #include "emf.h"
10 |
11 | size_t ConvertHexaCFString(CFStringRef s, uint8_t** bytes)
12 | {
13 | uint32_t len = CFStringGetLength(s);
14 | uint8_t* hex = malloc(len+1);
15 |
16 | if(hex == NULL)
17 | return 0;
18 |
19 | if(!CFStringGetCString(s, hex, len+1, kCFStringEncodingASCII))
20 | {
21 | free(hex);
22 | return 0;
23 | }
24 | size_t size = 0;
25 | hexToBytes(hex, bytes, &size);
26 | free(hex);
27 | return size;
28 | }
29 |
30 | void grabClassKey(const void *key, const void *value, void *context)
31 | {
32 | EMFInfo* emf = (EMFInfo*) context;
33 | uint8_t* class_key = NULL;
34 |
35 | if(CFGetTypeID(key) != CFStringGetTypeID() || CFGetTypeID(value) != CFStringGetTypeID())
36 | return;
37 |
38 | SInt32 clas = CFStringGetIntValue((CFStringRef)key);
39 |
40 | if(clas > 0 && clas <= MAX_CLASS_KEYS && CFStringGetLength((CFStringRef) value) == 64)
41 | {
42 | if(ConvertHexaCFString(value, &class_key) == 32)
43 | {
44 | AES_set_decrypt_key(class_key, 32*8, &(emf->classKeys[clas-1]));
45 | free(class_key);
46 | emf->classKeys_bitset |= 1 << clas;
47 | }
48 | }
49 |
50 | }
51 |
52 | EMFInfo* EMF_init(Volume* volume, char* imagePath)
53 | {
54 | uint8_t* emfk = NULL;
55 | uint8_t* dkey = NULL;
56 |
57 | uint64_t volume_id = *((uint64_t*) (&volume->volumeHeader->finderInfo[6]));
58 | FLIPENDIAN(volume_id);
59 |
60 | if(imagePath == NULL)
61 | imagePath = ".";
62 |
63 | printf("Volume identifier : %llx\n", volume_id);
64 | printf("Searching for %s/%llx.plist\n", imagePath, volume_id);
65 |
66 | CFStringRef path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%llx.plist"), imagePath, volume_id);
67 |
68 | CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, FALSE);
69 | CFRelease(path);
70 |
71 | CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, fileURL);
72 | CFRelease(fileURL);
73 |
74 | if(stream == NULL)
75 | {
76 | return NULL;
77 | }
78 | if(!CFReadStreamOpen(stream))
79 | {
80 | fprintf(stderr, "Cannot open file\n");
81 | return NULL;
82 | }
83 | CFPropertyListRef dict = CFPropertyListCreateWithStream(NULL, stream, 0, kCFPropertyListImmutable, NULL, NULL);
84 |
85 | CFRelease(stream);
86 |
87 | if (dict == NULL || CFGetTypeID(dict) != CFDictionaryGetTypeID())
88 | return NULL;
89 |
90 | CFStringRef emfHex = CFDictionaryGetValue(dict, CFSTR("EMF"));
91 | CFStringRef dkeyHex = CFDictionaryGetValue(dict, CFSTR("DKey"));
92 | CFNumberRef dataVolumeOffset = CFDictionaryGetValue (dict, CFSTR("dataVolumeOffset"));
93 |
94 | if (emfHex == NULL || CFGetTypeID(emfHex) != CFStringGetTypeID())
95 | return NULL;
96 | if (dkeyHex == NULL || CFGetTypeID(dkeyHex) != CFStringGetTypeID())
97 | return NULL;
98 | if (dataVolumeOffset == NULL || CFGetTypeID(dataVolumeOffset) != CFNumberGetTypeID())
99 | return NULL;
100 |
101 | EMFInfo* emf = malloc(sizeof(EMFInfo));
102 |
103 | if(emf == NULL)
104 | return NULL;
105 |
106 | memset(emf, 0, sizeof(EMFInfo));
107 |
108 | emf->volume = volume;
109 |
110 | CFNumberGetValue(dataVolumeOffset, kCFNumberLongType, &emf->volume_offset);
111 |
112 | printf("Data partition offset = %llx\n", emf->volume_offset);
113 |
114 | if(ConvertHexaCFString(emfHex, &emfk) != 32)
115 | {
116 | fprintf(stderr, "Invalid EMF key\n");
117 | free(emf);
118 | return NULL;
119 | }
120 | if(ConvertHexaCFString(dkeyHex, &dkey) != 32)
121 | {
122 | fprintf(stderr, "Invalid DKey key\n");
123 | free(emf);
124 | return NULL;
125 | }
126 |
127 | AES_set_encrypt_key(emfk, 32*8, &(emf->emfkey));
128 | AES_set_decrypt_key(dkey, 32*8, &(emf->classKeys[CLASS_DKEY-1]));
129 | emf->classKeys_bitset |= 1 << CLASS_DKEY;
130 |
131 | CFDictionaryRef classKeys = CFDictionaryGetValue(dict, CFSTR("classKeys"));
132 |
133 | if(classKeys != NULL && CFGetTypeID(classKeys) == CFDictionaryGetTypeID())
134 | {
135 | printf("Reading class keys, NSProtectionComplete files should be decrypted OK\n");
136 | CFDictionaryApplyFunction(classKeys, grabClassKey, (void*) emf);
137 | }
138 | else
139 | {
140 | printf("Only NSProtectionNone files will be decrypted\n");
141 | }
142 |
143 | free(emfk);
144 | free(dkey);
145 | return emf;
146 | }
147 |
--------------------------------------------------------------------------------
/python_scripts/keychain/keychain4.py:
--------------------------------------------------------------------------------
1 | from crypto.aes import AESdecryptCBC
2 | import struct
3 | from pyasn1.codec.der.decoder import decode as der_decode
4 |
5 | """
6 | iOS 4 keychain-2.db data column format
7 |
8 | version 0x00000000
9 | key class 0x00000008
10 | kSecAttrAccessibleWhenUnlocked 6
11 | kSecAttrAccessibleAfterFirstUnlock 7
12 | kSecAttrAccessibleAlways 8
13 | kSecAttrAccessibleWhenUnlockedThisDeviceOnly 9
14 | kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 10
15 | kSecAttrAccessibleAlwaysThisDeviceOnly 11
16 | wrapped AES256 key 0x28 bytes (passed to kAppleKeyStoreKeyUnwrap)
17 | encrypted data (AES 256 CBC zero IV)
18 | """
19 | from keychain import Keychain
20 | from crypto.gcm import gcm_decrypt
21 | from util.bplist import BPlistReader
22 |
23 | KSECATTRACCESSIBLE = {
24 | 6: "kSecAttrAccessibleWhenUnlocked",
25 | 7: "kSecAttrAccessibleAfterFirstUnlock",
26 | 8: "kSecAttrAccessibleAlways",
27 | 9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
28 | 10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
29 | 11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
30 | }
31 |
32 | class Keychain4(Keychain):
33 | def __init__(self, filename, keybag):
34 | if not keybag.unlocked:
35 | print "Keychain object created with locked keybag, some items won't be decrypted"
36 | Keychain.__init__(self, filename)
37 | self.keybag = keybag
38 |
39 | def decrypt_item(self, row):
40 | version, clas = struct.unpack("= 9 and not self.keybag.deviceKey:
44 | return {}
45 | if version >= 2:
46 | dict = self.decrypt_blob(row["data"])
47 | if not dict:
48 | return {"clas": clas, "rowid": row["rowid"]}
49 | if dict.has_key("v_Data"):
50 | try:
51 | dict["data"] = dict["v_Data"].data
52 | except AttributeError:
53 | dict["data"] = dict["v_Data"]
54 | else:
55 | dict["data"] = ""
56 | dict["rowid"] = row["rowid"]
57 | dict["clas"] = clas
58 | return dict
59 | row["clas"] = clas
60 | return Keychain.decrypt_item(self, row)
61 |
62 | def decrypt_data(self, data):
63 | data = self.decrypt_blob(data)
64 | if type(data) == dict:
65 | return data["v_Data"].data
66 | return data
67 |
68 | def decrypt_blob(self, blob):
69 | if blob == None:
70 | return ""
71 |
72 | if len(blob) < 48:
73 | print "keychain blob length must be >= 48"
74 | return
75 |
76 | version, clas = struct.unpack("
6 | //
7 |
8 | package chunkserver;
9 |
10 | message ChunkInfo {
11 | required bytes chunk_checksum = 1;
12 | optional bytes chunk_encryption_key = 2;
13 | required uint32 chunk_length = 3;
14 | }
15 | message NameValuePair {
16 | required string name = 1;
17 | required string value = 2;
18 | }
19 | message HostInfo {
20 | required string hostname = 1;
21 | required uint32 port = 2;
22 | required string method = 3;
23 | required string uri = 4;
24 | required string transport_protocol = 5;
25 | required string transport_protocol_version = 6;
26 | required string scheme = 7;
27 | repeated NameValuePair headers = 8;
28 | }
29 | message ErrorResponse {
30 | required string domain = 1;
31 | required int32 error_code = 2;
32 | optional string error_description = 3;
33 | repeated ErrorResponse underlying_errors = 4;
34 | repeated NameValuePair name_value_pair = 5;
35 | }
36 | message FileError {
37 | required bytes file_checksum = 1;
38 | required ErrorResponse error_response = 2;
39 | }
40 | message ChunkError {
41 | required bytes chunk_checksum = 1;
42 | required ErrorResponse error_response = 2;
43 | }
44 | message ChunkErrorIndex {
45 | required bytes chunk_checksum = 1;
46 | required ErrorResponse error_response = 2;
47 | required uint32 chunk_index = 3;
48 | }
49 | message FileChunkError {
50 | required bytes file_checksum = 1;
51 | repeated ChunkErrorIndex chunk_error = 2;
52 | }
53 | message StorageContainerError {
54 | required string storage_container_key = 1;
55 | required ErrorResponse error_response = 2;
56 | }
57 | message MethodCompletionInfo {
58 | required string url = 1;
59 | required uint32 response_status_code = 2;
60 | optional string response_status_line = 3;
61 | repeated NameValuePair vendor_response_headers = 4;
62 | optional bytes response_body = 5;
63 | optional ErrorResponse error = 6;
64 | optional bytes client_computed_md5 = 7;
65 | repeated NameValuePair vendor_nv_pairs = 8;
66 | repeated NameValuePair client_nv_pairs = 9;
67 | required string storage_container_authorization_token = 10;
68 | }
69 | message MethodCompletionInfoList {
70 | repeated MethodCompletionInfo method_completion_info = 1;
71 | }
72 | message FileChunkList {
73 | required bytes file_checksum = 1;
74 | required string authorization = 2;
75 | repeated ChunkInfo chunk_info = 3;
76 | }
77 | message FileChunkLists {
78 | repeated FileChunkList file_chunk_list = 1;
79 | }
80 | message StorageContainerChunkList {
81 | required bytes storage_container_key = 1;
82 | required HostInfo host_info = 2;
83 | repeated bytes chunk_checksum = 3;
84 | required string storage_container_authorization_token = 4;
85 | }
86 | message StorageContainerChunkLists {
87 | repeated StorageContainerChunkList storage_container_chunk_list = 1;
88 | repeated FileError file_error = 2;
89 | optional uint32 verbosity_level = 3;
90 | }
91 | message StorageContainerErrorList {
92 | repeated StorageContainerError storage_container_error = 1;
93 | }
94 | message FileChecksumAuthorization {
95 | required bytes file_checksum = 1;
96 | required string authorization = 2;
97 | repeated bytes chunk_checksums = 3;
98 | }
99 | message FileChecksumAuthorizationList {
100 | repeated FileChecksumAuthorization file_checksum_authorization = 1;
101 | }
102 | message ChunkReference {
103 | required uint64 container_index = 1;
104 | required uint64 chunk_index = 2;
105 | }
106 | message FileChecksumChunkReferences {
107 | required bytes file_checksum = 1;
108 | repeated ChunkReference chunk_references = 2;
109 | }
110 | message FileChecksumStorageHostChunkLists {
111 | repeated StorageHostChunkList storage_host_chunk_list = 1;
112 | repeated FileChecksumChunkReferences file_checksum_chunk_references = 2;
113 | }
114 | message FileGroups {
115 | repeated FileChecksumStorageHostChunkLists file_groups = 1;
116 | repeated FileError file_error = 2;
117 | repeated FileChunkError file_chunk_error = 3;
118 | optional uint32 verbosity_level = 4;
119 | }
120 | message ChunkChecksumList {
121 | repeated bytes chunk_checksum = 1;
122 | }
123 | message StorageHostChunkList {
124 | required HostInfo host_info = 1;
125 | repeated ChunkInfo chunk_info = 2;
126 | required string storage_container_key = 3;
127 | required string storage_container_authorization_token = 4;
128 | }
129 | message StorageHostChunkLists {
130 | repeated StorageHostChunkList storage_host_chunk_list = 1;
131 | repeated ChunkError chunk_error = 2;
132 | }
133 |
134 |
--------------------------------------------------------------------------------
/python_scripts/usbmux/tcprelay.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 | #
4 | # tcprelay.py - TCP connection relay for usbmuxd
5 | #
6 | # Copyright (C) 2009 Hector Martin "marcan"
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 2 or version 3.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program; if not, write to the Free Software
19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 |
21 | import usbmux
22 | import SocketServer
23 | import select
24 | from optparse import OptionParser
25 | import sys
26 | import threading
27 |
28 | class SocketRelay(object):
29 | def __init__(self, a, b, maxbuf=65535):
30 | self.a = a
31 | self.b = b
32 | self.atob = ""
33 | self.btoa = ""
34 | self.maxbuf = maxbuf
35 | def handle(self):
36 | while True:
37 | rlist = []
38 | wlist = []
39 | xlist = [self.a, self.b]
40 | if self.atob:
41 | wlist.append(self.b)
42 | if self.btoa:
43 | wlist.append(self.a)
44 | if len(self.atob) < self.maxbuf:
45 | rlist.append(self.a)
46 | if len(self.btoa) < self.maxbuf:
47 | rlist.append(self.b)
48 | rlo, wlo, xlo = select.select(rlist, wlist, xlist)
49 | if xlo:
50 | return
51 | if self.a in wlo:
52 | n = self.a.send(self.btoa)
53 | self.btoa = self.btoa[n:]
54 | if self.b in wlo:
55 | n = self.b.send(self.atob)
56 | self.atob = self.atob[n:]
57 | if self.a in rlo:
58 | s = self.a.recv(self.maxbuf - len(self.atob))
59 | if not s:
60 | return
61 | self.atob += s
62 | if self.b in rlo:
63 | s = self.b.recv(self.maxbuf - len(self.btoa))
64 | if not s:
65 | return
66 | self.btoa += s
67 | #print "Relay iter: %8d atob, %8d btoa, lists: %r %r %r"%(len(self.atob), len(self.btoa), rlo, wlo, xlo)
68 |
69 | class TCPRelay(SocketServer.BaseRequestHandler):
70 | def handle(self):
71 | print "Incoming connection to %d"%self.server.server_address[1]
72 | mux = usbmux.USBMux(options.sockpath)
73 | print "Waiting for devices..."
74 | if not mux.devices:
75 | mux.process(1.0)
76 | if not mux.devices:
77 | print "No device found"
78 | self.request.close()
79 | return
80 | dev = mux.devices[0]
81 | print "Connecting to device %s"%str(dev)
82 | dsock = mux.connect(dev, self.server.rport)
83 | lsock = self.request
84 | print "Connection established, relaying data"
85 | try:
86 | fwd = SocketRelay(dsock, lsock, self.server.bufsize * 1024)
87 | fwd.handle()
88 | finally:
89 | dsock.close()
90 | lsock.close()
91 | print "Connection closed"
92 |
93 | class TCPServer(SocketServer.TCPServer):
94 | allow_reuse_address = True
95 |
96 | class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer):
97 | pass
98 |
99 | HOST = "localhost"
100 |
101 | parser = OptionParser(usage="usage: %prog [OPTIONS] RemotePort[:LocalPort] [RemotePort[:LocalPort]]...")
102 | parser.add_option("-t", "--threaded", dest='threaded', action='store_true', default=False, help="use threading to handle multiple connections at once")
103 | parser.add_option("-b", "--bufsize", dest='bufsize', action='store', metavar='KILOBYTES', type='int', default=128, help="specify buffer size for socket forwarding")
104 | parser.add_option("-s", "--socket", dest='sockpath', action='store', metavar='PATH', type='str', default=None, help="specify the path of the usbmuxd socket")
105 |
106 | options, args = parser.parse_args()
107 |
108 | serverclass = TCPServer
109 | if options.threaded:
110 | serverclass = ThreadedTCPServer
111 |
112 | if len(args) == 0:
113 | parser.print_help()
114 | sys.exit(1)
115 |
116 | ports = []
117 |
118 | for arg in args:
119 | try:
120 | if ':' in arg:
121 | rport, lport = arg.split(":")
122 | rport = int(rport)
123 | lport = int(lport)
124 | ports.append((rport, lport))
125 | else:
126 | ports.append((int(arg), int(arg)))
127 | except:
128 | parser.print_help()
129 | sys.exit(1)
130 |
131 | servers=[]
132 |
133 | for rport, lport in ports:
134 | print "Forwarding local port %d to remote port %d"%(lport, rport)
135 | server = serverclass((HOST, lport), TCPRelay)
136 | server.rport = rport
137 | server.bufsize = options.bufsize
138 | servers.append(server)
139 |
140 | alive = True
141 |
142 | while alive:
143 | try:
144 | rl, wl, xl = select.select(servers, [], [])
145 | for server in rl:
146 | server.handle_request()
147 | except:
148 | alive = False
149 |
--------------------------------------------------------------------------------