├── .gitignore ├── src ├── adc.h ├── base64.h ├── gpt.h ├── mntcmd.h ├── base64.c ├── adc.c ├── vfdecrypt.h ├── dmg2img.h ├── vfdecrypt.c └── dmg2img.c ├── CMakeLists.txt ├── vfdecrypt.1 ├── README └── COPYING /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | vfdecrypt 3 | dmg2img 4 | .*.sw? 5 | -------------------------------------------------------------------------------- /src/adc.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define ADC_PLAIN 0x01 5 | #define ADC_2BYTE 0x02 6 | #define ADC_3BYTE 0x03 7 | 8 | #define bool short 9 | #define true 1 10 | #define false 0 11 | 12 | int adc_decompress(int in_size, unsigned char *input, int avail_size, unsigned char *output, int *bytes_written); 13 | int adc_chunk_type(char _byte); 14 | int adc_chunk_size(char _byte); 15 | int adc_chunk_offset(unsigned char *chunk_start); 16 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.4) 2 | 3 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 4 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pie") 5 | add_compile_options(-fPIE) 6 | set(CMAKE_C_STANDARD 11) 7 | 8 | project(dmg2img) 9 | include_directories(src) 10 | add_executable(dmg2img 11 | src/adc.c 12 | src/adc.h 13 | src/base64.c 14 | src/base64.h 15 | src/dmg2img.c 16 | src/dmg2img.h 17 | src/gpt.h 18 | src/mntcmd.h) 19 | 20 | target_link_libraries(dmg2img z bz2) 21 | 22 | 23 | project(vfdecrypt) 24 | add_compile_options(-fPIE) 25 | include_directories(src) 26 | add_executable(vfdecrypt 27 | src/vfdecrypt.c 28 | src/vfdecrypt.h) 29 | 30 | target_link_libraries(vfdecrypt crypto) 31 | -------------------------------------------------------------------------------- /vfdecrypt.1: -------------------------------------------------------------------------------- 1 | .TH "vfdecrypt" 1 2 | .SH NAME 3 | vfdecrypt \- decrypt encrypted filevault disk images 4 | .SH SYNOPSIS 5 | .B vfdecrypt 6 | -i in-file -p password -o out-file 7 | .SH DESCRIPTION 8 | vile fault decrypts encrypted Mac OS X disk image files. It supports both version 1 and 2 of the non-documented proprietary format. 9 | .SH OPTIONS 10 | .TP 11 | .B \-i 12 | Path to the input file. Usually an encrypted disk image. It's also kosher to redirect from STDIN. 13 | .TP 14 | .B \-e 15 | Try to extract key from input file. 16 | .TP 17 | .B \-k 18 | The alphanumeric key you wish to use to decrypt the disk file. 19 | .TP 20 | .B \-p 21 | The password you wish to use to decrypt the disk file. 22 | .TP 23 | .B \-o 24 | The output file. It's also kosher to redirect to STDOUT. 25 | .SH "SEE ALSO" 26 | vfcrack(1) 27 | .SH BUGS 28 | Feel free to report them or to submit patches. 29 | .SH AUTHORS 30 | Ralf-Philipp Weinmann 31 | .TP 32 | David Hulton 33 | .TP 34 | Jacob Appelbaum 35 | -------------------------------------------------------------------------------- /src/base64.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DMG2ISO base64.h 3 | * 4 | * Copyright (c) 2004 vu1tur This program is free software; you 5 | * can redistribute it and/or modify it under the terms of the GNU General 6 | * Public License as published by the Free Software Foundation. 7 | * 8 | * This program is distributed in the hope that it will be useful, but WITHOUT ANY 9 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 10 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 11 | * details. 12 | * 13 | * You should have received a copy of the GNU General Public License along with 14 | * this program; if not, write to the Free Software Foundation, Inc., 51 15 | * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | */ 17 | 18 | #define bool short 19 | #define true 1 20 | #define false 0 21 | 22 | void decode_base64(const char *inp, unsigned int isize, 23 | char *out, unsigned int *osize); 24 | 25 | unsigned char decode_base64_char(const char c); 26 | void cleanup_base64(char *inp, const unsigned int size); 27 | bool is_base64(const char c); 28 | -------------------------------------------------------------------------------- /src/gpt.h: -------------------------------------------------------------------------------- 1 | #define GPT_HDR_SIG "EFI PART" 2 | #define GPT_HDR_REVISION 0x00010000 3 | 4 | #define GPT_ENT_TYPE_UNUSED \ 5 | {0x00000000,0x0000,0x0000,0x00,0x00,{0x00,0x00,0x00,0x00,0x00,0x00}} 6 | #define GPT_ENT_TYPE_EFI \ 7 | {0xc12a7328,0xf81f,0x11d2,0xba,0x4b,{0x00,0xa0,0xc9,0x3e,0xc9,0x3b}} 8 | #define GPT_ENT_TYPE_MBR \ 9 | {0x024dee41,0x33e7,0x11d3,0x9d,0x69,{0x00,0x08,0xc7,0x81,0xf3,0x9f}} 10 | #define GPT_ENT_TYPE_HFSPLUS \ 11 | {0x48465300,0x0000,0x11aa,0xaa,0x11,{0x00,0x30,0x65,0x43,0xec,0xac}} 12 | #define GPT_ENT_TYPE_APPLEUFS \ 13 | {0x55465300,0x0000,0x11aa,0xaa,0x11,{0x00,0x30,0x65,0x43,0xec,0xac}} 14 | #define GPT_ENT_TYPE_ZFS \ 15 | {0x6a898cc3,0x1dd2,0x11b2,0x99,0xa6,{0x08,0x00,0x20,0x73,0x66,0x31}} 16 | 17 | #define GPT_ENT_TYPE_MS_RESERVED \ 18 | {0xe3c9e316,0x0b5c,0x4db8,0x81,0x7d,{0xf9,0x2d,0xf0,0x02,0x15,0xae}} 19 | #define GPT_ENT_TYPE_MS_BASIC_DATA \ 20 | {0xebd0a0a2,0xb9e5,0x4433,0x87,0xc0,{0x68,0xb6,0xb7,0x26,0x99,0xc7}} 21 | #define GPT_ENT_TYPE_MS_LDM_METADATA \ 22 | {0x5808c8aa,0x7e8f,0x42e0,0x85,0xd2,{0xe1,0xe9,0x04,0x34,0xcf,0xb3}} 23 | #define GPT_ENT_TYPE_MS_LDM_DATA \ 24 | {0xaf9b60a0,0x1431,0x4f62,0xbc,0x68,{0x33,0x11,0x71,0x4a,0x69,0xad}} 25 | 26 | struct _guid { 27 | uint32_t time_low; 28 | uint16_t time_mid; 29 | uint16_t time_hi_and_version; 30 | uint8_t clock_seq_hi_and_reserved; 31 | uint8_t clock_seq_low; 32 | uint8_t node[6]; 33 | } __attribute__((__packed__)); 34 | 35 | struct _gpt_header { 36 | char hdr_sig[8]; 37 | uint32_t hdr_revision; 38 | uint32_t hdr_size; 39 | uint32_t hdr_crc_self; 40 | uint32_t __reserved; 41 | uint64_t hdr_lba_self; 42 | uint64_t hdr_lba_backup; 43 | uint64_t hdr_lba_start; 44 | uint64_t hdr_lba_end; 45 | struct _guid hdr_guid; 46 | uint64_t hdr_lba_table; 47 | uint32_t hdr_entries; 48 | uint32_t hdr_entsz; 49 | uint32_t hdr_crc_table; 50 | uint32_t padding; 51 | } __attribute__((__packed__)); 52 | 53 | struct _gpt_entry { 54 | struct _guid ent_type; 55 | struct _guid ent_guid; 56 | uint64_t ent_lba_start; 57 | uint64_t ent_lba_end; 58 | uint64_t ent_attr; 59 | uint16_t name[36]; /* UTF-16 */ 60 | } __attribute__((__packed__)); 61 | -------------------------------------------------------------------------------- /src/mntcmd.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "gpt.h" 3 | 4 | static struct _guid guid_hfsplus = GPT_ENT_TYPE_HFSPLUS; 5 | 6 | #define EQGUID(a,b) (memcmp(a, b, sizeof(struct _guid)) == 0) 7 | 8 | void read_gpt_header(FILE * F, struct _gpt_header *h) 9 | { 10 | memset(h, 0, sizeof(struct _gpt_header)); 11 | fread(h, sizeof(struct _gpt_header), 1, F); 12 | } 13 | 14 | void read_gpt_entry(FILE * F, struct _gpt_entry *e) 15 | { 16 | memset(e, 0, sizeof(struct _gpt_entry)); 17 | fread(e, sizeof(struct _gpt_entry), 1, F); 18 | } 19 | 20 | int print_mountcmd(char *filename) 21 | { 22 | if (!filename) 23 | return (-1); 24 | 25 | unsigned int i, pn = 0; 26 | char tmp[128]; 27 | struct _gpt_header gpt_header; 28 | struct _gpt_entry gpt_entry; 29 | struct _gpt_entry *gpt_ent_array; 30 | 31 | FILE *F = fopen(filename, "rb"); 32 | fseeko(F, 0x200, SEEK_SET); 33 | read_gpt_header(F, &gpt_header); 34 | 35 | if (memcmp(gpt_header.hdr_sig, GPT_HDR_SIG, sizeof(gpt_header.hdr_sig)) == 0) { 36 | gpt_ent_array = (struct _gpt_entry *)malloc(gpt_header.hdr_entries * sizeof(struct _gpt_entry)); 37 | if (!gpt_ent_array) { 38 | return (-1); 39 | } 40 | fseeko(F, 0x400, SEEK_SET); 41 | for (i = 0; i < gpt_header.hdr_entries; i++) { 42 | fseeko(F, 0x400 + i * gpt_header.hdr_entsz, SEEK_SET); 43 | read_gpt_entry(F, &gpt_entry); 44 | 45 | if (!EQGUID(&guid_hfsplus, &gpt_entry.ent_type)) 46 | break; 47 | ++pn; 48 | memcpy(&gpt_ent_array[i], &gpt_entry, sizeof(struct _gpt_entry)); 49 | } 50 | 51 | fprintf(stderr, "\nImage appears to have GUID Partition Table with %d HFS+ partition%s.\n", pn, pn == 1 ? "" : "s"); 52 | if (pn > 0) { 53 | fprintf(stderr, "You should be able to mount %s [as root] by:\n\n", pn == 1 ? "it" : "them"); 54 | fprintf(stderr, "modprobe hfsplus\n"); 55 | for (i = 0; i < pn; i++) { 56 | sprintf(tmp, " (for partition %d)", i + 1); 57 | fprintf(stderr, "mount -t hfsplus -o loop,offset=%" PRIu64 " %s /mnt%s\n", gpt_ent_array[i].ent_lba_start * 0x200, filename, pn > 1 ? tmp : ""); 58 | } 59 | } else { 60 | fprintf(stderr, "\ 61 | But you might be able to mount the image [as root] by:\n\n\ 62 | modprobe hfsplus\n\ 63 | mount -t hfsplus -o loop %s /mnt\n\n", filename); 64 | } 65 | if (F != NULL) 66 | fclose(F); 67 | 68 | free(gpt_ent_array); 69 | } else { 70 | fprintf(stderr, "\n\ 71 | You should be able to mount the image [as root] by:\n\n\ 72 | modprobe hfsplus\n\ 73 | mount -t hfsplus -o loop %s /mnt\n\n", filename); 74 | } 75 | return (pn); 76 | } 77 | -------------------------------------------------------------------------------- /src/base64.c: -------------------------------------------------------------------------------- 1 | /* 2 | * DMG2ISO base64.cc 3 | * 4 | * Copyright (c) 2004 vu1tur This program is free software; you 5 | * can redistribute it and/or modify it under the terms of the GNU General 6 | * Public License as published by the Free Software Foundation. 7 | * 8 | * This program is distributed in the hope that it will be useful, but WITHOUT ANY 9 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 10 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 11 | * details. 12 | * 13 | * You should have received a copy of the GNU General Public License along with 14 | * this program; if not, write to the Free Software Foundation, Inc., 51 15 | * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | */ 17 | 18 | #include "base64.h" 19 | #include 20 | 21 | bool is_base64(const char c) 22 | { 23 | if ((c >= 'A' && c <= 'Z') || 24 | (c >= 'a' && c <= 'z') || 25 | (c >= '0' && c <= '9') || 26 | c == '+' || 27 | c == '/' || 28 | c == '=') 29 | return true; 30 | return false; 31 | } 32 | 33 | void cleanup_base64(char *inp, const unsigned int size) 34 | { 35 | char *tinp1, *tinp2; 36 | unsigned int i; 37 | tinp1 = inp; 38 | tinp2 = inp; 39 | for (i = 0; i < size; i++) { 40 | if (is_base64(*tinp2)) { 41 | *tinp1++ = *tinp2++; 42 | } else { 43 | *tinp1 = *tinp2++; 44 | } 45 | } 46 | *(tinp1) = 0; 47 | } 48 | 49 | unsigned char decode_base64_char(const char c) 50 | { 51 | if (c >= 'A' && c <= 'Z') 52 | return c - 'A'; 53 | if (c >= 'a' && c <= 'z') 54 | return c - 'a' + 26; 55 | if (c >= '0' && c <= '9') 56 | return c - '0' + 52; 57 | if (c == '+') 58 | return 62; 59 | if (c == '=') 60 | return 0; 61 | return 63; 62 | } 63 | 64 | void decode_base64(const char *inp, unsigned int isize, 65 | char *out, unsigned int *osize) 66 | { 67 | char *tinp = (char *)inp; 68 | char *tout; 69 | unsigned int i; 70 | 71 | *osize = isize / 4 * 3; 72 | if (inp != out) { 73 | tout = (char *)malloc(*osize); 74 | out = tout; 75 | } else { 76 | tout = tinp; 77 | } 78 | for (i = 0; i < (isize >> 2); i++) { 79 | *tout = decode_base64_char(*tinp++) << 2; 80 | *tout++ |= decode_base64_char(*tinp) >> 4; 81 | *tout = decode_base64_char(*tinp++) << 4; 82 | *tout++ |= decode_base64_char(*tinp) >> 2; 83 | *tout = decode_base64_char(*tinp++) << 6; 84 | *tout++ |= decode_base64_char(*tinp++); 85 | } 86 | if (*(tinp - 1) == '=') 87 | (*osize)--; 88 | if (*(tinp - 2) == '=') 89 | (*osize)--; 90 | } 91 | -------------------------------------------------------------------------------- /src/adc.c: -------------------------------------------------------------------------------- 1 | #include "adc.h" 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | int adc_decompress(int in_size, unsigned char *input, int avail_size, unsigned char *output, int *bytes_written) 8 | { 9 | if (in_size == 0) 10 | return 0; 11 | bool output_full = false; 12 | unsigned char *inp = input; 13 | unsigned char *outp = output; 14 | int chunk_type; 15 | int chunk_size; 16 | int offset; 17 | int i; 18 | 19 | while (inp - input < in_size) { 20 | chunk_type = adc_chunk_type(*inp); 21 | switch (chunk_type) { 22 | case ADC_PLAIN: 23 | chunk_size = adc_chunk_size(*inp); 24 | if (outp + chunk_size - output > avail_size) { 25 | output_full = true; 26 | break; 27 | } 28 | memcpy(outp, inp + 1, chunk_size); 29 | inp += chunk_size + 1; 30 | outp += chunk_size; 31 | break; 32 | 33 | case ADC_2BYTE: 34 | chunk_size = adc_chunk_size(*inp); 35 | offset = adc_chunk_offset(inp); 36 | if (outp + chunk_size - output > avail_size) { 37 | output_full = true; 38 | break; 39 | } 40 | if (offset == 0) { 41 | memset(outp, *(outp - offset - 1), chunk_size); 42 | outp += chunk_size; 43 | inp += 2; 44 | } else { 45 | for (i = 0; i < chunk_size; i++) { 46 | memcpy(outp, outp - offset - 1, 1); 47 | outp++; 48 | } 49 | inp += 2; 50 | } 51 | break; 52 | 53 | case ADC_3BYTE: 54 | chunk_size = adc_chunk_size(*inp); 55 | offset = adc_chunk_offset(inp); 56 | if (outp + chunk_size - output > avail_size) { 57 | output_full = true; 58 | break; 59 | } 60 | if (offset == 0) { 61 | memset(outp, *(outp - offset - 1), chunk_size); 62 | outp += chunk_size; 63 | inp += 3; 64 | } else { 65 | for (i = 0; i < chunk_size; i++) { 66 | memcpy(outp, outp - offset - 1, 1); 67 | outp++; 68 | } 69 | inp += 3; 70 | } 71 | break; 72 | } 73 | if (output_full) 74 | break; 75 | } 76 | *bytes_written = outp - output; 77 | return inp - input; 78 | } 79 | 80 | int adc_chunk_type(char _byte) 81 | { 82 | if (_byte & 0x80) 83 | return ADC_PLAIN; 84 | if (_byte & 0x40) 85 | return ADC_3BYTE; 86 | return ADC_2BYTE; 87 | } 88 | 89 | int adc_chunk_size(char _byte) 90 | { 91 | switch (adc_chunk_type(_byte)) { 92 | case ADC_PLAIN: 93 | return (_byte & 0x7F) + 1; 94 | case ADC_2BYTE: 95 | return ((_byte & 0x3F) >> 2) + 3; 96 | case ADC_3BYTE: 97 | return (_byte & 0x3F) + 4; 98 | } 99 | return -1; 100 | } 101 | 102 | int adc_chunk_offset(unsigned char *chunk_start) 103 | { 104 | unsigned char *c = chunk_start; 105 | switch (adc_chunk_type(*c)) { 106 | case ADC_PLAIN: 107 | return 0; 108 | case ADC_2BYTE: 109 | return ((((unsigned char)*c & 0x03)) << 8) + (unsigned char)*(c + 1); 110 | case ADC_3BYTE: 111 | return (((unsigned char)*(c + 1)) << 8) + (unsigned char)*(c + 2); 112 | } 113 | return -1; 114 | } 115 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | 2 | DMG2IMG is a tool which allows converting Apple compressed dmg 3 | archives to standard (hfsplus) image disk files. 4 | 5 | This tool handles zlib and bzip2 compressed dmg images. 6 | 7 | 8 | USAGE: 9 | dmg2img [-l] [-p N] [-s] [-v] [-V] [-d] [] 10 | or 11 | dmg2img -i -o 12 | 13 | It is derived from dmg2iso v0.2c by vu1tur 14 | 15 | 16 | NOTES: 17 | 18 | 1. An equivalent command under Mac OS X would be: 19 | hdiutil convert -format UDTO -o 20 | 21 | 2. Under linux, the image disk file can be mounted with the commands 22 | 23 | modprobe hfsplus 24 | mount -t hfsplus -o loop /mnt 25 | 26 | [normally, only 'root' might be able to do this] 27 | 28 | 3. Windows users should be able to open the image disk file with UltraISO. 29 | 30 | Jean-Pierre Demailly 31 | 32 | 33 | COMPILATION: 34 | 35 | The default included Makefile is for Linux/gcc. The development files 36 | in zlib-dev and libbz2-dev are needed to compile dmg2img, and those 37 | in openssl-dev are needed to compile vfdecrypt. 38 | 39 | 40 | CHANGELOG: 41 | 42 | 1.0 3 August 2007 43 | * Initial version 44 | 45 | 1.1 4 August 2008 46 | * Fixed segfault bug occurring when decompressing certain dmg files 47 | beyond the actual end of the file (due to not correctly setting 48 | the size of the compressed parts ...) 49 | * Added slightly modified vfdecrypt utility from 50 | Weinmann-Appelbaum-Fromme in order to decrypt encrypted dmg files. 51 | 52 | 1.2 17 September 2008 53 | * Fixed segfault bug due to buffer overflow (buffer sizes 54 | incorrectly set, resulting in insufficient memory allocation). 55 | * Fixed most compilation warnings - remaining ones are 56 | irrelevant with standard compilers. 57 | 58 | 1.3 19 September 2008 59 | * Further fixes which (hopefully) enable dmg2img to work on 60 | dmg archives of arbitrary size, while reducing RAM usage a lot. 61 | * A lot of thanks to Alfred E. Hegge and Randy Broman for testing 62 | and reporting bugs. 63 | 64 | 1.4 5 April 2009 65 | * Applied patch from Vladimir 'phcoder' Serbinenko which brings 66 | correct handling of 64bit integers in koly signature and 67 | plist data, and should enable dmg2img to work on huge 68 | archives > 4GBytes (tested by 'phcoder'). 69 | * Added support for dmg archives involving bzip2 instead of zlib 70 | compression (this has not received much testing yet, as those 71 | archives are still unfrequent). 72 | * Many thanks to Pierre Duhem for useful hints. 73 | 74 | 1.4.1 6 April 2009 75 | * Fixed a bug in writing the output file that caused some DMG images 76 | to convert to a broken unmountable IMG image. 77 | 78 | 1.5 8 April 2009 79 | * Fixed a bug in parsing plist for image partitions. 80 | * Added support for ADC-compressed dmg images. 81 | 82 | 1.5.1 11 April 2009 83 | * Added missing zero block type. 84 | * Small fixes and clean up. 85 | 86 | 1.6 15 April 2009 87 | * Added support for dmg images that only have binary resource fork 88 | but no XML plist. 89 | * Refined koly block processing. 90 | * Fixed a bug in finding the offset for the next compressed block 91 | when offsets are defined relative to the current partition. 92 | * Fixed broken progress indicator. 93 | * Added detection of images with GUID Partition Table and respective 94 | mount commands in linux. 95 | 96 | 1.6.1 12 August 2009 97 | * Fixed a bug in handling large files on win32 systems. 98 | 99 | 1.6.2 24 March 2010 100 | * Fixed a bug in processing a terminal block type. 101 | * Added periodic flushing of debug log file. 102 | 103 | 1.6.3 07 April 2012 104 | * Added option -l to list partitions 105 | * Added option -p to extract only specific partition 106 | * Added support for a rare case scenario of koly block being at the 107 | the beginning of the image (thanks to Friik) 108 | 109 | 1.6.4 25 April 2012 110 | * Compilation bugfix (Linux) 111 | 112 | 1.6.5 23 July 2013 113 | * Fixed a bug in handling some types of dmg files 114 | 115 | http://vu1tur.eu.org/dmg2img -------------------------------------------------------------------------------- /src/vfdecrypt.h: -------------------------------------------------------------------------------- 1 | #ifndef _FVDECRYPT_H 2 | 3 | #define _FVDECRYPT_H 1 4 | 5 | /* length of message digest output in bytes (160 bits) */ 6 | #define MD_LENGTH 20 7 | /* length of cipher key in bytes (128 bits) */ 8 | #define CIPHER_KEY_LENGTH 16 9 | /* block size of cipher in bytes (128 bits) */ 10 | #define CIPHER_BLOCKSIZE 16 11 | /* chunk size (FileVault specific) */ 12 | #define CHUNK_SIZE 4096 13 | /* number of iterations for PBKDF2 key derivation */ 14 | #define PBKDF2_ITERATION_COUNT 1000 15 | 16 | typedef struct { 17 | /* 0x000: */ uint8_t filler1[48]; 18 | /* 0x034: */ uint32_t kdf_iteration_count; 19 | /* 0x034: */ uint32_t kdf_salt_len; 20 | /* 0x038: */ uint8_t kdf_salt[48]; /* salt value for key derivation */ 21 | /* 0x068: */ uint8_t unwrap_iv[32]; /* IV for encryption-key unwrapping */ 22 | /* 0x088: */ uint32_t len_wrapped_aes_key; 23 | /* 0x08c: */ uint8_t wrapped_aes_key[296]; 24 | /* 0x1b4: */ uint32_t len_hmac_sha1_key; 25 | /* 0x1b8: */ uint8_t wrapped_hmac_sha1_key[300]; 26 | /* 0x1b4: */ uint32_t len_integrity_key; 27 | /* 0x2e8: */ uint8_t wrapped_integrity_key[48]; 28 | /* 0x318: */ uint8_t filler6[484]; 29 | } cencrypted_v1_header; 30 | 31 | /* this structure is valid only if there's a recovery key defined */ 32 | typedef struct { 33 | unsigned char sig[8]; 34 | uint32_t version; 35 | uint32_t enc_iv_size; 36 | uint32_t unk1; 37 | uint32_t unk2; 38 | uint32_t unk3; 39 | uint32_t unk4; 40 | uint32_t unk5; 41 | unsigned char uuid[16]; 42 | uint32_t blocksize; 43 | uint64_t datasize; 44 | uint64_t dataoffset; 45 | uint8_t filler1[0x260]; 46 | uint32_t kdf_algorithm; 47 | uint32_t kdf_prng_algorithm; 48 | uint32_t kdf_iteration_count; 49 | uint32_t kdf_salt_len; /* in bytes */ 50 | uint8_t kdf_salt[32]; 51 | uint32_t blob_enc_iv_size; 52 | uint8_t blob_enc_iv[32]; 53 | uint32_t blob_enc_key_bits; 54 | uint32_t blob_enc_algorithm; 55 | uint32_t blob_enc_padding; 56 | uint32_t blob_enc_mode; 57 | uint32_t encrypted_keyblob_size; 58 | uint8_t encrypted_keyblob[0x30]; 59 | } cencrypted_v2_pwheader; 60 | 61 | /* PasswordHeader: 62 | 0x2a8: 63 | aHeader.keyDerivationAlgorithm %ld 64 | aHeader.keyDerivationPRNGAlgorithm %ld 65 | 0x70: 66 | aHeader.keyDerivationIterationCount %ld 67 | 0x74: 68 | aHeader.keyDerivationSaltSize %ld 69 | 0x78: 70 | aHeader.keyDerivationSalt 71 | 72 | aHeader.blobEncryptionIVSize %ld 73 | aHeader.blobEncryptionIV %ld 74 | aHeader.blobEncryptionKeySizeInBits %ld 75 | aHeader.blobEncryptionAlgorithm %ld 76 | aHeader.blobEncryptionPadding %ld 77 | aHeader.blobEncryptionMode %ld 78 | aHeader.encryptedBlobSize %ld 79 | aHeader.encryptedBlob 80 | */ 81 | 82 | 83 | /* 84 | aHeader.uuid 85 | aHeader.dataBlockSize %u 86 | aHeader.keyWrappingAlgorithm %ld 87 | aHeader.keyWrappingPadding 88 | aHeader.keyWrappingMode %ld 89 | aHeader.keyWrappingKeySizeInBits %ld 90 | aHeader.keyWrappingIVSize %ld 91 | aHeader.keyDerivationAlgorithm %ld 92 | aHeader.keyDerivationPRNGAlgorithm %ld 93 | aHeader.keyDerivationIterationCount %ld 94 | aHeader.keyDerivationSaltSize %ld 95 | aHeader.keyDerivationSalt 96 | aHeader.encryptionIVSize %ld 97 | aHeader.encryptionMode %ld 98 | aHeader.encryptionAlgorithm %ld 99 | aHeader.encryptionKeySizeInBits %ld 100 | aHeader.encryptionKeyWrappingIV 101 | aHeader.wrappedEncryptionKeySize %ld 102 | aHeader.wrappedEncryptionKey 103 | aHeader.prngAlgorithm %ld 104 | aHeader.prngKeySizeInBits %ld 105 | aHeader.prngKeyWrappingIV 106 | aHeader.wrappedPrngKeySize %ld 107 | aHeader.wrappedPrngKey 108 | aHeader.signingAlgorithm %ld 109 | aHeader.signingKeySizeInBits %ld 110 | aHeader.signingKeyWrappingIV 111 | aHeader.wrappedSigningKeySize %ld 112 | aHeader.wrappedSigningKey 113 | aHeader.signatureSize %ld 114 | aHeader.signature 115 | aHeader.dataForkSize %qd 116 | aHeader.version %ld 117 | aHeader.signature2 %4.4s 118 | aHeader.signature1 %4.4s 119 | aHeader.version %u 120 | aHeader.dataForkStartOffset 121 | %qd 122 | aHeader.blobEncryptionIVSize %ld 123 | aHeader.blobEncryptionIV 124 | aHeader.blobEncryptionKeySizeInBits %ld 125 | aHeader.blobEncryptionAlgorithm %ld 126 | aHeader.blobEncryptionPadding %ld 127 | aHeader.blobEncryptionMode %ld 128 | aHeader.encryptedBlobSize %ld 129 | aHeader.encryptedBlob 130 | aHeader.publicKeyHashSize %ld 131 | aHeader.publicKeyHash 132 | */ 133 | #endif 134 | -------------------------------------------------------------------------------- /src/dmg2img.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DMG2IMG dmg2img.h 3 | * 4 | * Copyright (c) 2004 vu1tur This program is free software; you 5 | * can redistribute it and/or modify it under the terms of the GNU General 6 | * Public License as published by the Free Software Foundation. 7 | * 8 | * This program is distributed in the hope that it will be useful, but WITHOUT ANY 9 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 10 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 11 | * details. 12 | * 13 | * You should have received a copy of the GNU General Public License along with 14 | * this program; if not, write to the Free Software Foundation, Inc., 51 15 | * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | */ 17 | 18 | #include 19 | #include 20 | #include "adc.h" 21 | #include 22 | 23 | #define BT_ADC 0x80000004 24 | #define BT_ZLIB 0x80000005 25 | #define BT_BZLIB 0x80000006 26 | 27 | #define BT_ZERO 0x00000000 28 | #define BT_RAW 0x00000001 29 | #define BT_IGNORE 0x00000002 30 | #define BT_COMMENT 0x7ffffffe 31 | #define BT_TERM 0xffffffff 32 | 33 | #define SECTOR_SIZE 0x200 34 | 35 | #ifdef __MINGW32__ 36 | #define fseeko fseeko64 37 | #endif 38 | 39 | z_stream z; 40 | bz_stream bz; 41 | 42 | const char plist_begin[] = ""; 43 | const char plist_end[] = ""; 44 | const char list_begin[] = ""; 45 | const char list_end[] = ""; 46 | const char chunk_begin[] = ""; 47 | const char chunk_end[] = ""; 48 | const char blkx_begin[] = "blkx"; 49 | const char name_key[] = "Name"; 50 | const char name_begin[] = ""; 51 | const char name_end[] = ""; 52 | 53 | int convert_int(int i) 54 | { 55 | int o; 56 | char *p_i = (char *) &i; 57 | char *p_o = (char *) &o; 58 | p_o[0] = p_i[3]; 59 | p_o[1] = p_i[2]; 60 | p_o[2] = p_i[1]; 61 | p_o[3] = p_i[0]; 62 | return o; 63 | } 64 | 65 | uint64_t convert_int64(uint64_t i) 66 | { 67 | uint64_t o; 68 | char *p_i = (char *) &i; 69 | char *p_o = (char *) &o; 70 | p_o[0] = p_i[7]; 71 | p_o[1] = p_i[6]; 72 | p_o[2] = p_i[5]; 73 | p_o[3] = p_i[4]; 74 | p_o[4] = p_i[3]; 75 | p_o[5] = p_i[2]; 76 | p_o[6] = p_i[1]; 77 | p_o[7] = p_i[0]; 78 | return o; 79 | } 80 | 81 | uint32_t convert_char4(unsigned char *c) 82 | { 83 | return (((uint32_t) c[0]) << 24) | (((uint32_t) c[1]) << 16) | 84 | (((uint32_t) c[2]) << 8) | ((uint32_t) c[3]); 85 | } 86 | 87 | uint64_t convert_char8(unsigned char *c) 88 | { 89 | return ((uint64_t) convert_char4(c) << 32) | (convert_char4(c + 4)); 90 | } 91 | 92 | struct _kolyblk { 93 | uint32_t Signature; 94 | uint32_t Version; 95 | uint32_t HeaderSize; 96 | uint32_t Flags; 97 | uint64_t RunningDataForkOffset; 98 | uint64_t DataForkOffset; 99 | uint64_t DataForkLength; 100 | uint64_t RsrcForkOffset; 101 | uint64_t RsrcForkLength; 102 | uint32_t SegmentNumber; 103 | uint32_t SegmentCount; 104 | uint32_t SegmentID1; 105 | uint32_t SegmentID2; 106 | uint32_t SegmentID3; 107 | uint32_t SegmentID4; 108 | uint32_t DataForkChecksumType; 109 | uint32_t Reserved1; 110 | uint32_t DataForkChecksum; 111 | uint32_t Reserved2; 112 | char Reserved3[120]; 113 | uint64_t XMLOffset; 114 | uint64_t XMLLength; 115 | char Reserved4[120]; 116 | uint32_t MasterChecksumType; 117 | uint32_t Reserved5; 118 | uint32_t MasterChecksum; 119 | uint32_t Reserved6; 120 | char Reserved7[120]; 121 | uint32_t ImageVariant; 122 | uint64_t SectorCount; 123 | char Reserved8[12]; 124 | } __attribute__ ((__packed__)); 125 | struct _kolyblk kolyblk; 126 | 127 | 128 | struct _mishblk { 129 | uint32_t BlocksSignature; 130 | uint32_t InfoVersion; 131 | uint64_t FirstSectorNumber; 132 | uint64_t SectorCount; 133 | uint64_t DataStart; 134 | uint32_t DecompressedBufferRequested; 135 | uint32_t BlocksDescriptor; 136 | char Reserved1[24]; 137 | uint32_t ChecksumType; 138 | uint32_t Reserved2; 139 | uint32_t Checksum; 140 | uint32_t Reserved3; 141 | char Reserved4[120]; 142 | uint32_t BlocksRunCount; 143 | char *Data; 144 | } __attribute__ ((__packed__)); 145 | 146 | 147 | void read_kolyblk(FILE* F, struct _kolyblk* k) 148 | { 149 | fread(k, 0x200, 1, F); 150 | k->Signature = convert_int(k->Signature); 151 | k->Version = convert_int(k->Version); 152 | k->HeaderSize = convert_int(k->HeaderSize); 153 | k->Flags = convert_int(k->Flags); 154 | k->RunningDataForkOffset = convert_int64(k->RunningDataForkOffset); 155 | k->DataForkOffset = convert_int64(k->DataForkOffset); 156 | k->DataForkLength = convert_int64(k->DataForkLength); 157 | k->RsrcForkOffset = convert_int64(k->RsrcForkOffset); 158 | k->RsrcForkLength = convert_int64(k->RsrcForkLength); 159 | k->SegmentNumber = convert_int(k->SegmentNumber); 160 | k->SegmentCount = convert_int(k->SegmentCount); 161 | k->DataForkChecksumType = convert_int(k->DataForkChecksumType); 162 | k->DataForkChecksum = convert_int(k->DataForkChecksum); 163 | k->XMLOffset = convert_int64(k->XMLOffset); 164 | k->XMLLength = convert_int64(k->XMLLength); 165 | k->MasterChecksumType = convert_int(k->MasterChecksumType); 166 | k->MasterChecksum = convert_int(k->MasterChecksum); 167 | k->ImageVariant = convert_int(k->ImageVariant); 168 | k->SectorCount = convert_int64(k->SectorCount); 169 | } 170 | 171 | void print_mishblk(FILE *f, struct _mishblk *m) 172 | { 173 | fprintf(f, "%-28s: %08" PRIx32 "\n", "BlocksSignature", m->BlocksSignature); 174 | fprintf(f, "%-28s: %08" PRIx32 "\n", "InfoVersion", m->InfoVersion); 175 | fprintf(f, "%-28s: %016" PRIx64 "\n", "FirstSectorNumber", m->FirstSectorNumber); 176 | fprintf(f, "%-28s: %016" PRIx64 "\n", "SectorCount", m->SectorCount); 177 | fprintf(f, "%-28s: %016" PRIx64 "\n", "DataStart", m->DataStart); 178 | fprintf(f, "%-28s: %08" PRIx32 "\n", "DecompressedBufferRequested", m->DecompressedBufferRequested); 179 | fprintf(f, "%-28s: %08" PRIx32 "\n", "BlocksDescriptor", m->BlocksDescriptor); 180 | fprintf(f, "%-28s: %08" PRIx32 "\n", "ChecksumType", m->ChecksumType); 181 | fprintf(f, "%-28s: %08" PRIx32 "\n", "Checksum", m->Checksum); 182 | fprintf(f, "%-28s: %08" PRIx32 "\n", "BlocksRunCount", m->BlocksRunCount); 183 | } 184 | 185 | void fill_mishblk(char* c, struct _mishblk* m) 186 | { 187 | memset(m, 0, sizeof(struct _mishblk)); 188 | memcpy(m, c, 0xCC); 189 | m->BlocksSignature = convert_int(m->BlocksSignature); 190 | m->InfoVersion = convert_int(m->InfoVersion); 191 | m->FirstSectorNumber = convert_int64(m->FirstSectorNumber); 192 | m->SectorCount = convert_int64(m->SectorCount); 193 | m->DataStart = convert_int64(m->DataStart); 194 | m->DecompressedBufferRequested = convert_int(m->DecompressedBufferRequested); 195 | m->BlocksDescriptor = convert_int(m->BlocksDescriptor); 196 | m->ChecksumType = convert_int(m->ChecksumType); 197 | m->Checksum = convert_int(m->Checksum); 198 | m->BlocksRunCount = convert_int(m->BlocksRunCount); 199 | } 200 | 201 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /src/vfdecrypt.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** Copyright (c) 2006 3 | ** Ralf-Philipp Weinmann 4 | ** Jacob Appelbaum 5 | ** Christian Fromme 6 | ** 7 | ** Decrypt a AES-128 encrypted disk image given the encryption key 8 | ** and the hmacsha1key of the image. These two keys can be found 9 | ** out by running hdiutil attach with -debug on the disk image. 10 | ** 11 | ** Permission is hereby granted, free of charge, to any person 12 | ** obtaining a copy of this software and associated documentation 13 | ** files (the "Software"), to deal in the Software without 14 | ** restriction, including without limitation the rights to use, 15 | ** copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | ** copies of the Software, and to permit persons to whom the 17 | ** Software is furnished to do so, subject to the following 18 | ** conditions: 19 | ** 20 | ** The above copyright notice and this permission notice shall be 21 | ** included in all copies or substantial portions of the Software. 22 | ** 23 | ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 24 | ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 25 | ** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 26 | ** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 27 | ** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 28 | ** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 29 | ** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 30 | ** OTHER DEALINGS IN THE SOFTWARE. 31 | **/ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | #define OSSwapHostToBigInt32(x) ntohl(x) 45 | 46 | /* length of message digest output in bytes (160 bits) */ 47 | #define MD_LENGTH 20 48 | /* length of cipher key in bytes (128 bits) */ 49 | #define CIPHER_KEY_LENGTH 16 50 | /* block size of cipher in bytes (128 bits) */ 51 | #define CIPHER_BLOCKSIZE 16 52 | /* number of iterations for PBKDF2 key derivation */ 53 | #define PBKDF2_ITERATION_COUNT 1000 54 | 55 | typedef struct { 56 | /* 0x000: */ uint8_t filler1[48]; 57 | /* 0x034: */ uint32_t kdf_iteration_count; 58 | /* 0x034: */ uint32_t kdf_salt_len; 59 | /* 0x038: */ uint8_t kdf_salt[48]; /* salt value for key derivation */ 60 | /* 0x068: */ uint8_t unwrap_iv[32]; /* IV for encryption-key unwrapping */ 61 | /* 0x088: */ uint32_t len_wrapped_aes_key; 62 | /* 0x08c: */ uint8_t wrapped_aes_key[296]; 63 | /* 0x1b4: */ uint32_t len_hmac_sha1_key; 64 | /* 0x1b8: */ uint8_t wrapped_hmac_sha1_key[300]; 65 | /* 0x1b4: */ uint32_t len_integrity_key; 66 | /* 0x2e8: */ uint8_t wrapped_integrity_key[48]; 67 | /* 0x318: */ uint8_t filler6[484]; 68 | } cencrypted_v1_header; 69 | 70 | typedef struct { 71 | unsigned char sig[8]; 72 | uint32_t version; 73 | uint32_t enc_iv_size; 74 | uint32_t unk1; 75 | uint32_t unk2; 76 | uint32_t unk3; 77 | uint32_t unk4; 78 | uint32_t unk5; 79 | unsigned char uuid[16]; 80 | uint32_t blocksize; 81 | uint64_t datasize; 82 | uint64_t dataoffset; 83 | uint8_t filler1[0x260]; 84 | uint32_t kdf_algorithm; 85 | uint32_t kdf_prng_algorithm; 86 | uint32_t kdf_iteration_count; 87 | uint32_t kdf_salt_len; /* in bytes */ 88 | uint8_t kdf_salt[32]; 89 | uint32_t blob_enc_iv_size; 90 | uint8_t blob_enc_iv[32]; 91 | uint32_t blob_enc_key_bits; 92 | uint32_t blob_enc_algorithm; 93 | uint32_t blob_enc_padding; 94 | uint32_t blob_enc_mode; 95 | uint32_t encrypted_keyblob_size; 96 | uint8_t encrypted_keyblob[0x30]; 97 | } cencrypted_v2_pwheader; 98 | 99 | void print_hex(uint8_t * /* data */, uint32_t /* len */); 100 | void convert_hex(char * /* str */, uint8_t * /* bytes */, 101 | int /* maxlen */); 102 | void dump_v2_header(void * /* hdr */); 103 | void adjust_v1_header_byteorder(cencrypted_v1_header * /* hdr */); 104 | void adjust_v2_header_byteorder(cencrypted_v2_pwheader * /* pwhdr */); 105 | 106 | void print_hex(uint8_t *data, uint32_t len) { 107 | uint32_t ctr; 108 | char *sep; 109 | 110 | if (len > 64) len = 64; 111 | 112 | for(ctr = 0; ctr < len; ctr++) { 113 | sep = (((ctr&7)==0)&&ctr) ? "\n" : ""; 114 | fprintf(stderr, "%s%02x ", sep, data[ctr]); 115 | } 116 | fprintf(stderr, "\n\n"); 117 | } 118 | 119 | void convert_hex(char *str, uint8_t *bytes, int maxlen) { 120 | int bytelen = maxlen; 121 | int rpos, wpos = 0; 122 | 123 | for(rpos = 0; rpos < bytelen; rpos++) { 124 | sscanf(&str[rpos*2], "%02hhx", &bytes[wpos++]); 125 | } 126 | } 127 | 128 | void dump_v2_header(void *hdr) { 129 | cencrypted_v2_pwheader *pwhdr = (cencrypted_v2_pwheader *) hdr; 130 | 131 | fprintf(stderr, "sig\t%8s\n", pwhdr->sig); 132 | fprintf(stderr, "blocksize\t%"PRIX32"\n", pwhdr->blocksize); 133 | fprintf(stderr, "datasize\t%"PRIu64"\n", pwhdr->datasize); 134 | fprintf(stderr, "dataoffset\t%"PRIu64"\n", pwhdr->dataoffset); 135 | 136 | /* 103: CSSM_ALGID_PKCS5_PBKDF2 */ 137 | fprintf(stderr, "keyDerivationAlgorithm %lu\n", (unsigned long) pwhdr->kdf_algorithm); 138 | fprintf(stderr, "keyDerivationPRNGAlgorithm %lu\n", (unsigned long) pwhdr->kdf_prng_algorithm); 139 | /* by default the iteration count should be 1000 iterations */ 140 | fprintf(stderr, "keyDerivationIterationCount %lu\n", (unsigned long) pwhdr->kdf_iteration_count); 141 | fprintf(stderr, "keyDerivationSaltSize %lu\n", (unsigned long) pwhdr->kdf_salt_len); 142 | fprintf(stderr, "keyDerivationSalt \n"); 143 | print_hex(pwhdr->kdf_salt, pwhdr->kdf_salt_len); 144 | fprintf(stderr, "blobEncryptionIVSize %lu\n", (unsigned long) pwhdr->blob_enc_iv_size); 145 | fprintf(stderr, "blobEncryptionIV \n"); 146 | print_hex(pwhdr->blob_enc_iv, pwhdr->blob_enc_iv_size); 147 | fprintf(stderr, "blobEncryptionKeySizeInBits %lu\n", (unsigned long) pwhdr->blob_enc_key_bits); 148 | /* 17: CSSM_ALGID_3DES_3KEY_EDE */ 149 | fprintf(stderr, "blobEncryptionAlgorithm %lu\n", (unsigned long) pwhdr->blob_enc_algorithm); 150 | /* 7: CSSM_PADDING_PKCS7 */ 151 | fprintf(stderr, "blobEncryptionPadding %lu\n", (unsigned long) pwhdr->blob_enc_padding); 152 | /* 6: CSSM_ALGMODE_CBCPadIV8 */ 153 | fprintf(stderr, "blobEncryptionMode %lu\n", (unsigned long) pwhdr->blob_enc_mode); 154 | fprintf(stderr, "encryptedBlobSize %lu\n", (unsigned long) pwhdr->encrypted_keyblob_size); 155 | fprintf(stderr, "encryptedBlob \n"); 156 | print_hex(pwhdr->encrypted_keyblob, pwhdr->encrypted_keyblob_size); 157 | } 158 | 159 | void adjust_v1_header_byteorder(cencrypted_v1_header *hdr) { 160 | hdr->kdf_iteration_count = htonl(hdr->kdf_iteration_count); 161 | hdr->kdf_salt_len = htonl(hdr->kdf_salt_len); 162 | hdr->len_wrapped_aes_key = htonl(hdr->len_wrapped_aes_key); 163 | hdr->len_hmac_sha1_key = htonl(hdr->len_hmac_sha1_key); 164 | hdr->len_integrity_key = htonl(hdr->len_integrity_key); 165 | } 166 | 167 | #define swap32(x) x = OSSwapHostToBigInt32(x) 168 | #define swap64(x) x = ((uint64_t) ntohl(x >> 32)) | (((uint64_t) ntohl((uint32_t) (x & 0xFFFFFFFF))) << 32) 169 | 170 | void adjust_v2_header_byteorder(cencrypted_v2_pwheader *pwhdr) { 171 | swap32(pwhdr->blocksize); 172 | swap64(pwhdr->datasize); 173 | swap64(pwhdr->dataoffset); 174 | pwhdr->kdf_algorithm = htonl(pwhdr->kdf_algorithm); 175 | pwhdr->kdf_prng_algorithm = htonl(pwhdr->kdf_prng_algorithm); 176 | pwhdr->kdf_iteration_count = htonl(pwhdr->kdf_iteration_count); 177 | pwhdr->kdf_salt_len = htonl(pwhdr->kdf_salt_len); 178 | pwhdr->blob_enc_iv_size = htonl(pwhdr->blob_enc_iv_size); 179 | pwhdr->blob_enc_key_bits = htonl(pwhdr->blob_enc_key_bits); 180 | pwhdr->blob_enc_algorithm = htonl(pwhdr->blob_enc_algorithm); 181 | pwhdr->blob_enc_padding = htonl(pwhdr->blob_enc_padding); 182 | pwhdr->blob_enc_mode = htonl(pwhdr->blob_enc_mode); 183 | pwhdr->encrypted_keyblob_size = htonl(pwhdr->encrypted_keyblob_size); 184 | } 185 | 186 | HMAC_CTX *hmacsha1_ctx; 187 | AES_KEY aes_decrypt_key; 188 | int CHUNK_SIZE=4096; // default 189 | 190 | /** 191 | * * Compute IV of current block as 192 | * * truncate128(HMAC-SHA1(hmacsha1key||blockno)) 193 | * */ 194 | void compute_iv(uint32_t chunk_no, uint8_t *iv) { 195 | unsigned char mdResult[MD_LENGTH]; 196 | unsigned int mdLen; 197 | 198 | chunk_no = OSSwapHostToBigInt32(chunk_no); 199 | HMAC_Init_ex(hmacsha1_ctx, NULL, 0, NULL, NULL); 200 | HMAC_Update(hmacsha1_ctx, (void *) &chunk_no, sizeof(uint32_t)); 201 | HMAC_Final(hmacsha1_ctx, mdResult, &mdLen); 202 | memcpy(iv, mdResult, CIPHER_BLOCKSIZE); 203 | } 204 | 205 | void decrypt_chunk(uint8_t *ctext, uint8_t *ptext, uint32_t chunk_no) { 206 | uint8_t iv[CIPHER_BLOCKSIZE]; 207 | 208 | compute_iv(chunk_no, iv); 209 | AES_cbc_encrypt(ctext, ptext, CHUNK_SIZE, &aes_decrypt_key, iv, AES_DECRYPT); 210 | } 211 | 212 | /* DES3-EDE unwrap operation loosely based on to RFC 2630, section 12.6 213 | * wrapped_key has to be 40 bytes in length. */ 214 | int apple_des3_ede_unwrap_key(uint8_t *wrapped_key, int wrapped_key_len, uint8_t *decryptKey, uint8_t *unwrapped_key) { 215 | EVP_CIPHER_CTX *ctx; 216 | uint8_t *TEMP1, *TEMP2, *CEKICV; 217 | uint8_t IV[8] = { 0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05 }; 218 | int outlen, tmplen, i; 219 | 220 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 221 | ctx = EVP_CIPHER_CTX_new(); 222 | #else 223 | ctx = malloc(sizeof(*ctx)); 224 | #endif 225 | if (!ctx) { 226 | fprintf(stderr, "Out of memory: EVP_CIPHER_CTX!\n"); 227 | return(-1); 228 | } 229 | 230 | EVP_CIPHER_CTX_init(ctx); 231 | /* result of the decryption operation shouldn't be bigger than ciphertext */ 232 | TEMP1 = malloc(wrapped_key_len); 233 | TEMP2 = malloc(wrapped_key_len); 234 | CEKICV = malloc(wrapped_key_len); 235 | /* uses PKCS#7 padding for symmetric key operations by default */ 236 | EVP_DecryptInit_ex(ctx, EVP_des_ede3_cbc(), NULL, decryptKey, IV); 237 | 238 | if(!EVP_DecryptUpdate(ctx, TEMP1, &outlen, wrapped_key, wrapped_key_len)) { 239 | fprintf(stderr, "internal error (1) during key unwrap operation!\n"); 240 | return(-1); 241 | } 242 | if(!EVP_DecryptFinal_ex(ctx, TEMP1 + outlen, &tmplen)) { 243 | fprintf(stderr, "internal error (2) during key unwrap operation!\n"); 244 | return(-1); 245 | } 246 | outlen += tmplen; 247 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 248 | EVP_CIPHER_CTX_reset(ctx); 249 | #else 250 | EVP_CIPHER_CTX_cleanup(ctx); 251 | #endif 252 | 253 | /* reverse order of TEMP3 */ 254 | for(i = 0; i < outlen; i++) TEMP2[i] = TEMP1[outlen - i - 1]; 255 | 256 | EVP_CIPHER_CTX_init(ctx); 257 | /* uses PKCS#7 padding for symmetric key operations by default */ 258 | EVP_DecryptInit_ex(ctx, EVP_des_ede3_cbc(), NULL, decryptKey, TEMP2); 259 | if(!EVP_DecryptUpdate(ctx, CEKICV, &outlen, TEMP2+8, outlen-8)) { 260 | fprintf(stderr, "internal error (3) during key unwrap operation!\n"); 261 | return(-1); 262 | } 263 | if(!EVP_DecryptFinal_ex(ctx, CEKICV + outlen, &tmplen)) { 264 | fprintf(stderr, "internal error (4) during key unwrap operation!\n"); 265 | return(-1); 266 | } 267 | 268 | outlen += tmplen; 269 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 270 | EVP_CIPHER_CTX_reset(ctx); 271 | #else 272 | EVP_CIPHER_CTX_cleanup(ctx); 273 | #endif 274 | 275 | memcpy(unwrapped_key, CEKICV+4, outlen-4); 276 | free(TEMP1); 277 | free(TEMP2); 278 | free(CEKICV); 279 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 280 | EVP_CIPHER_CTX_free(ctx); 281 | #else 282 | free(ctx); 283 | #endif 284 | return(0); 285 | } 286 | 287 | int unwrap_v1_header(char *passphrase, cencrypted_v1_header *header, uint8_t *aes_key, uint8_t *hmacsha1_key) { 288 | /* derived key is a 3DES-EDE key */ 289 | uint8_t derived_key[192/8]; 290 | 291 | PKCS5_PBKDF2_HMAC_SHA1(passphrase, strlen(passphrase), (unsigned char*)header->kdf_salt, 20, 292 | PBKDF2_ITERATION_COUNT, sizeof(derived_key), derived_key); 293 | 294 | if (apple_des3_ede_unwrap_key(header->wrapped_aes_key, 40, derived_key, aes_key) != 0) 295 | return(-1); 296 | if (apple_des3_ede_unwrap_key(header->wrapped_hmac_sha1_key, 48, derived_key, hmacsha1_key) != 0) 297 | return(-1); 298 | 299 | return(0); 300 | } 301 | 302 | int unwrap_v2_header(char *passphrase, cencrypted_v2_pwheader *header, uint8_t *aes_key, uint8_t *hmacsha1_key) { 303 | /* derived key is a 3DES-EDE key */ 304 | uint8_t derived_key[192/8]; 305 | EVP_CIPHER_CTX *ctx; 306 | uint8_t *TEMP1; 307 | int outlen, tmplen; 308 | 309 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 310 | ctx = EVP_CIPHER_CTX_new(); 311 | #else 312 | ctx = malloc(sizeof(*ctx)); 313 | #endif 314 | if (!ctx) { 315 | fprintf(stderr, "Out of memory: EVP_CIPHER_CTX!\n"); 316 | return(-1); 317 | } 318 | 319 | PKCS5_PBKDF2_HMAC_SHA1(passphrase, strlen(passphrase), (unsigned char*)header->kdf_salt, 20, 320 | PBKDF2_ITERATION_COUNT, sizeof(derived_key), derived_key); 321 | 322 | print_hex(derived_key, 192/8); 323 | 324 | EVP_CIPHER_CTX_init(ctx); 325 | /* result of the decryption operation shouldn't be bigger than ciphertext */ 326 | TEMP1 = malloc(header->encrypted_keyblob_size); 327 | /* uses PKCS#7 padding for symmetric key operations by default */ 328 | EVP_DecryptInit_ex(ctx, EVP_des_ede3_cbc(), NULL, derived_key, header->blob_enc_iv); 329 | 330 | if(!EVP_DecryptUpdate(ctx, TEMP1, &outlen, header->encrypted_keyblob, header->encrypted_keyblob_size)) { 331 | fprintf(stderr, "internal error (1) during key unwrap operation!\n"); 332 | return(-1); 333 | } 334 | if(!EVP_DecryptFinal_ex(ctx, TEMP1 + outlen, &tmplen)) { 335 | fprintf(stderr, "internal error (2) during key unwrap operation!\n"); 336 | return(-1); 337 | } 338 | outlen += tmplen; 339 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 340 | EVP_CIPHER_CTX_free(ctx); 341 | #else 342 | EVP_CIPHER_CTX_cleanup(ctx); 343 | free(ctx); 344 | #endif 345 | memcpy(aes_key, TEMP1, 16); 346 | memcpy(hmacsha1_key, TEMP1, 20); 347 | 348 | return(0); 349 | } 350 | 351 | int determine_header_version(FILE *dmg) { 352 | return(2); 353 | } 354 | 355 | int usage(char *message) { 356 | fprintf(stderr, "%s\n", message); 357 | fprintf(stderr, "Usage: vfdecrypt [-e] [-p password] [-k key] -i in-file -o out-file\n"); 358 | fprintf(stderr, "Option -e attempts to extract key from \n"); 359 | exit(1); 360 | } 361 | 362 | int main(int argc, char *argv[]) { 363 | FILE *in, *out; 364 | cencrypted_v1_header v1header; 365 | cencrypted_v2_pwheader v2header; 366 | 367 | uint8_t hmacsha1_key[20], aes_key[16], inbuf[CHUNK_SIZE], outbuf[CHUNK_SIZE]; 368 | uint32_t chunk_no; 369 | int hdr_version, c, optError = 0; 370 | char inFile[512], outFile[512], passphrase[512], cmd[640]; 371 | int iflag = 0, oflag = 0, pflag = 0, kflag = 0, verbose = 0; 372 | extern char *optarg; 373 | extern int optind, optopt; 374 | 375 | memset(inFile, 0, 512); 376 | memset(outFile, 0, 512); 377 | memset(passphrase, 0, 512); 378 | memset(cmd, 0, 640); 379 | 380 | /* This was the key used in iPhone1,1_1.0_1A543a_Restore.ipsw ... */ 381 | /* 382 | convert_hex("28c909fc6d322fa18940f03279d70880", aes_key, 16); 383 | convert_hex("e59a4507998347c70d5b8ca7ef090ecccc15e82d", hmacsha1_key, 20); 384 | kflag = 1; 385 | */ 386 | 387 | while((c = getopt(argc, argv, "hvei:o:p:k:")) != -1) { 388 | switch(c) { 389 | case 'h': 390 | usage("Help is on the way. Stay calm."); 391 | break; 392 | case 'v': 393 | verbose++; 394 | break; 395 | case 'e': 396 | *cmd = 1; 397 | break; 398 | case 'i': 399 | if(optarg) strncpy(inFile, optarg, sizeof(inFile)-1); 400 | iflag = 1; 401 | break; 402 | case 'o': 403 | if (optarg) strncpy(outFile, optarg, sizeof(outFile)-1); 404 | oflag = 1; 405 | break; 406 | case 'p': 407 | if (optarg) strncpy(passphrase, optarg, sizeof(passphrase)-1); 408 | pflag = 1; 409 | break; 410 | case 'k': 411 | convert_hex(optarg, aes_key, 16); 412 | convert_hex(optarg+32, hmacsha1_key, 20); 413 | kflag=1; 414 | break; 415 | case '?': 416 | fprintf(stderr, "Unknown option: -%c\n", optopt); 417 | optError++; 418 | break; 419 | } 420 | } 421 | 422 | /* check to see if our user gave incorrect options */ 423 | if (optError) usage("Incorrect arguments."); 424 | 425 | if (strlen(inFile) == 0) { 426 | in = stdin; 427 | } else { 428 | if ((in = fopen(inFile, "rb")) == NULL) { 429 | fprintf(stderr, "Error: unable to open %s\n", inFile); 430 | exit(1); 431 | } 432 | } 433 | 434 | if (*cmd && *inFile) { 435 | sprintf(cmd, 436 | "strings %s | grep '^[0-9a-fA-F]*$' | awk '{ if (length($1) == 72) print; }'", 437 | inFile); 438 | system(cmd); 439 | exit(0); 440 | } 441 | 442 | if (strlen(outFile) == 0) { 443 | out = stdout; 444 | } else { 445 | if ((out = fopen(outFile, "wb")) == NULL) { 446 | fprintf(stderr, "Error: unable to open %s\n", outFile); 447 | exit(1); 448 | } 449 | } 450 | 451 | if (!pflag && !kflag) { 452 | usage("No Passphrase given."); 453 | exit(1); 454 | } 455 | 456 | hdr_version = determine_header_version(in); 457 | 458 | if (verbose >= 1) { 459 | if (hdr_version > 0) { 460 | fprintf(stderr, "v%d header detected.\n", hdr_version); 461 | } else { 462 | fprintf(stderr, "unknown format.\n"); 463 | exit(1); 464 | } 465 | } 466 | 467 | if (hdr_version == 1) { 468 | fseek(in, (long) -sizeof(cencrypted_v1_header), SEEK_END); 469 | if (fread(&v1header, sizeof(cencrypted_v1_header), 1, in) < 1) { 470 | fprintf(stderr, "header corrupted?\n"), exit(1); 471 | } 472 | adjust_v1_header_byteorder(&v1header); 473 | if(!kflag) unwrap_v1_header(passphrase, &v1header, aes_key, hmacsha1_key); 474 | } 475 | 476 | if (hdr_version == 2) { 477 | fseek(in, 0L, SEEK_SET); 478 | if (fread(&v2header, sizeof(cencrypted_v2_pwheader), 1, in) < 1) { 479 | fprintf(stderr, "header corrupted?\n"), exit(1); 480 | } 481 | adjust_v2_header_byteorder(&v2header); 482 | dump_v2_header(&v2header); 483 | if(!kflag) unwrap_v2_header(passphrase, &v2header, aes_key, hmacsha1_key); 484 | CHUNK_SIZE = v2header.blocksize; 485 | } 486 | 487 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 488 | hmacsha1_ctx = HMAC_CTX_new(); 489 | #else 490 | hmacsha1_ctx = malloc(sizeof(*hmacsha1_ctx)); 491 | #endif 492 | if (!hmacsha1_ctx) { 493 | fprintf(stderr, "Out of memory: HMAC CTX!\n"); 494 | exit(1); 495 | } 496 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 497 | HMAC_CTX_reset(hmacsha1_ctx); 498 | #else 499 | HMAC_CTX_init(hmacsha1_ctx); 500 | #endif 501 | HMAC_Init_ex(hmacsha1_ctx, hmacsha1_key, sizeof(hmacsha1_key), EVP_sha1(), NULL); 502 | AES_set_decrypt_key(aes_key, CIPHER_KEY_LENGTH * 8, &aes_decrypt_key); 503 | 504 | if (verbose >= 1) { 505 | printf("AES Key: \n"); 506 | print_hex(aes_key, 16); 507 | printf("SHA1 seed: \n"); 508 | print_hex(hmacsha1_key, 20); 509 | } 510 | 511 | if (hdr_version == 2) fseek(in, v2header.dataoffset, SEEK_SET); 512 | else fseek(in, 0L, SEEK_SET); 513 | 514 | chunk_no = 0; 515 | while(fread(inbuf, CHUNK_SIZE, 1, in) > 0) { 516 | decrypt_chunk(inbuf, outbuf, chunk_no); 517 | chunk_no++; 518 | if(hdr_version == 2 && (v2header.datasize-ftell(out)) < CHUNK_SIZE) { 519 | fwrite(outbuf, v2header.datasize - ftell(out), 1, out); 520 | break; 521 | } 522 | fwrite(outbuf, CHUNK_SIZE, 1, out); 523 | } 524 | 525 | if (verbose) fprintf(stderr, "%"PRIX32" chunks written\n", chunk_no); 526 | #if OPENSSL_VERSION_NUMBER >= 0x10100000L 527 | HMAC_CTX_free(hmacsha1_ctx); 528 | #else 529 | HMAC_CTX_cleanup(hmacsha1_ctx); 530 | free(hmacsha1_ctx); 531 | #endif 532 | return(0); 533 | } 534 | -------------------------------------------------------------------------------- /src/dmg2img.c: -------------------------------------------------------------------------------- 1 | /* 2 | * DMG2IMG dmg2img.c 3 | * 4 | * Copyright (c) 2004 vu1tur This program is free software; you 5 | * can redistribute it and/or modify it under the terms of the GNU General 6 | * Public License as published by the Free Software Foundation. 7 | * 8 | * This program is distributed in the hope that it will be useful, but WITHOUT ANY 9 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 10 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 11 | * details. 12 | * 13 | * You should have received a copy of the GNU General Public License along with 14 | * this program; if not, write to the Free Software Foundation, Inc., 51 15 | * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 | */ 17 | 18 | #define _FILE_OFFSET_BITS 64 19 | #define VERSION "dmg2img v1.6.5 (c) vu1tur (to@vu1tur.eu.org)" 20 | #define USAGE "\ 21 | Usage: dmg2img [-l] [-p N] [-s] [-v] [-V] [-d] [ | -]\n\ 22 | or dmg2img [-l] [-p N] [-s] [-v] [-V] [-d] -i -o \n\n\ 23 | Options: -s (silent) -v (verbose) -V (extremely verbose) -d (debug)\n\ 24 | -l (list partitions) -p N (extract only partition N)" 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "dmg2img.h" 33 | #include "base64.h" 34 | #include "mntcmd.h" 35 | 36 | /* take chunk size to be 1 MByte so it will work even with little RAM */ 37 | #define CHUNKSIZE 0x100000 38 | #define DECODEDSIZE 0x100000 39 | 40 | FILE *FIN = NULL, *FOUT = NULL, *FDBG = NULL; 41 | int debug = 0; 42 | int verbose = 1; 43 | int listparts = 0; 44 | int extractpart = -1; 45 | double percent; 46 | unsigned int offset; 47 | 48 | void mem_overflow() 49 | { 50 | fprintf(stderr, "not enough memory!\n"); 51 | if (FIN != NULL) 52 | fclose(FIN); 53 | if (FDBG != NULL) 54 | fclose(FDBG); 55 | if (FOUT != NULL) 56 | fclose(FOUT); 57 | exit(-1); 58 | } 59 | 60 | void error_dmg_corrupted() 61 | { 62 | fprintf(stderr, "dmg image is corrupted!\n"); 63 | if (FIN != NULL) 64 | fclose(FIN); 65 | if (FDBG != NULL) 66 | fclose(FDBG); 67 | if (FOUT != NULL) 68 | fclose(FOUT); 69 | exit(-1); 70 | } 71 | 72 | void percentage() 73 | { 74 | int i, s; 75 | char sp[128]; 76 | 77 | if (verbose < 1) 78 | return; 79 | s = offset / 0x28; 80 | if (verbose >= 3) 81 | fprintf(stderr, "[%d] %6.2f%%\n", s, percent); 82 | else if (verbose == 2) { 83 | sprintf(sp, "[%d] %6.2f%%", s, percent); 84 | for (i = 0; i < strlen(sp); i++) 85 | fprintf(stderr, "\b"); 86 | fprintf(stderr, "%s", sp); 87 | } else { 88 | sprintf(sp, "%6.2f%%", percent); 89 | for (i = 0; i < strlen(sp); i++) 90 | fprintf(stderr, "\b"); 91 | fprintf(stderr, "%s", sp); 92 | } 93 | fflush(stderr); 94 | } 95 | 96 | int main(int argc, char *argv[]) 97 | { 98 | int i, err, partnum = 0, scb; 99 | Bytef *tmp = NULL, *otmp = NULL, *dtmp = NULL; 100 | char *input_file = NULL, *output_file = NULL; 101 | char *plist = NULL; 102 | char *blkx = NULL; 103 | unsigned int blkx_size; 104 | struct _mishblk *parts = NULL; 105 | char *data_begin = NULL, *data_end = NULL; 106 | char *partname_begin = NULL, *partname_end = NULL; 107 | char *mish_begin = NULL; 108 | char partname[255] = ""; 109 | unsigned int *partlen = NULL; 110 | unsigned int data_size; 111 | uint64_t out_offs, out_size, in_offs, in_size, in_offs_add, add_offs, to_read, 112 | to_write, chunk; 113 | char reserved[5] = " "; 114 | char sztype[64] = ""; 115 | unsigned int block_type, dw_reserved; 116 | unsigned long long total_written = 0; 117 | 118 | for (i = 1; i < argc; i++) { 119 | if (!strcmp(argv[i], "-s")) 120 | verbose = 0; 121 | else if (!strcmp(argv[i], "-v")) 122 | verbose = 2; 123 | else if (!strcmp(argv[i], "-V")) 124 | verbose = 3; 125 | else if (!strcmp(argv[i], "-d")) 126 | debug = 1; 127 | else if (!strcmp(argv[i], "-l")) 128 | listparts = 1; 129 | else if (!strcmp(argv[i], "-p")) 130 | sscanf(argv[++i], "%d", &extractpart); 131 | else if (!strcmp(argv[i], "-i") && i < argc - 1) 132 | input_file = argv[++i]; 133 | else if (!strcmp(argv[i], "-o") && i < argc - 1) 134 | output_file = argv[++i]; 135 | else if (!input_file) 136 | input_file = argv[i]; 137 | else if (!output_file) 138 | output_file = argv[i]; 139 | } 140 | 141 | if (!input_file) { 142 | fprintf(stderr, "\n%s\n\n%s\n\n", VERSION, USAGE); 143 | return 0; 144 | } 145 | if (!output_file) { 146 | i = strlen(input_file); 147 | output_file = (char *)malloc(i + 6); 148 | if (!output_file) 149 | mem_overflow(); 150 | strcpy(output_file, input_file); 151 | if (i < 4 || strcasecmp(&output_file[i - 4], ".dmg")) 152 | strcat(output_file, ".img"); 153 | else 154 | strcpy(&output_file[i - 4], ".img"); 155 | } else if (!strcmp(output_file, "-")) { 156 | /* treat NULL output_file as stdout */ 157 | output_file = "(stdout)"; 158 | } 159 | if (verbose) 160 | fprintf(stderr, "\n%s\n\n", VERSION); 161 | if (debug) { 162 | FDBG = fopen("dmg2img.log", "wb"); 163 | if (FDBG == NULL) { 164 | debug = 0; 165 | perror("Failed to create dmg2img.log"); 166 | } 167 | } 168 | FIN = fopen(input_file, "rb"); 169 | if (FIN == NULL) { 170 | fprintf(stderr, "Can't open input file %s: %s\n", input_file, strerror(errno)); 171 | return 0; 172 | } 173 | //parsing koly block 174 | fseeko(FIN, -0x200, SEEK_END); 175 | read_kolyblk(FIN, &kolyblk); 176 | if (kolyblk.Signature != 0x6b6f6c79) { 177 | fseeko(FIN, 0, SEEK_SET); 178 | read_kolyblk(FIN, &kolyblk); 179 | } 180 | char szSignature[5]; 181 | szSignature[4] = '\0'; 182 | int rSignature = convert_int(kolyblk.Signature); 183 | memcpy(szSignature, &rSignature, 4); 184 | 185 | if (debug) { 186 | fprintf(FDBG, "Signature:\t\t0x%08" PRIX32 " (%s)\n", kolyblk.Signature, szSignature); 187 | fprintf(FDBG, "Version:\t\t0x%08" PRIX32 "\n", kolyblk.Version); 188 | fprintf(FDBG, "HeaderSize:\t\t0x%08" PRIX32 "\n", kolyblk.HeaderSize); 189 | fprintf(FDBG, "Flags:\t\t\t0x%08" PRIX32 "\n", kolyblk.Flags); 190 | fprintf(FDBG, "RunningDataForkOffset:\t0x%016" PRIX64 "\n", kolyblk.RunningDataForkOffset); 191 | fprintf(FDBG, "DataForkOffset:\t\t0x%016" PRIX64 "\n", kolyblk.DataForkOffset); 192 | fprintf(FDBG, "DataForkLength:\t\t0x%016" PRIX64 "\n", kolyblk.DataForkLength); 193 | fprintf(FDBG, "RsrcForkOffset:\t\t0x%016" PRIX64 "\n", kolyblk.RsrcForkOffset); 194 | fprintf(FDBG, "RsrcForkLength:\t\t0x%016" PRIX64 "\n", kolyblk.RsrcForkLength); 195 | fprintf(FDBG, "SegmentNumber:\t\t0x%08" PRIX32 "\n", kolyblk.SegmentNumber); 196 | fprintf(FDBG, "SegmentCount:\t\t0x%08" PRIX32 "\n", kolyblk.SegmentCount); 197 | fprintf(FDBG, "SegmentID:\t\t0x%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "%08" PRIX32 "\n", kolyblk.SegmentID1, kolyblk.SegmentID2, kolyblk.SegmentID3, kolyblk.SegmentID4); 198 | fprintf(FDBG, "DataForkChecksumType:\t0x%08" PRIX32 " %s\n", kolyblk.DataForkChecksumType, kolyblk.DataForkChecksumType == 0x02 ? "CRC-32" : ""); 199 | fprintf(FDBG, "DataForkChecksum:\t0x%08" PRIX32 "\n", kolyblk.DataForkChecksum); 200 | fprintf(FDBG, "XMLOffset:\t\t0x%016" PRIX64 "\n", kolyblk.XMLOffset); 201 | fprintf(FDBG, "XMLLength:\t\t0x%016" PRIX64 "\n", kolyblk.XMLLength); 202 | fprintf(FDBG, "MasterChecksumType:\t0x%08" PRIX32 " %s\n", kolyblk.MasterChecksumType, kolyblk.MasterChecksumType == 0x02 ? "CRC-32" : ""); 203 | fprintf(FDBG, "MasterChecksum:\t\t0x%08" PRIX32 "\n", kolyblk.MasterChecksum); 204 | fprintf(FDBG, "ImageVariant:\t\t0x%08" PRIX32 "\n", kolyblk.ImageVariant); 205 | fprintf(FDBG, "SectorCount:\t\t0x%016" PRIX64 "\n", kolyblk.SectorCount); 206 | 207 | fprintf(FDBG, "\n"); 208 | } 209 | if (kolyblk.Signature != 0x6b6f6c79) { 210 | error_dmg_corrupted(); 211 | } 212 | if (verbose) { 213 | if (input_file) 214 | fprintf(stderr, "%s --> %s\n\n", input_file, listparts ? "(partition list)" : output_file); 215 | } 216 | if (debug) 217 | fprintf(stderr, "Debug info will be written to dmg2img.log\n\n"); 218 | 219 | if (kolyblk.XMLOffset != 0 && kolyblk.XMLLength != 0) { 220 | //We have a plist to parse 221 | if (verbose > 1) 222 | fprintf(stderr, "reading property list, %llu bytes from address %llu ...\n", (unsigned long long)kolyblk.XMLLength, (unsigned long long)kolyblk.XMLOffset); 223 | 224 | plist = (char *)malloc(kolyblk.XMLLength + 1); 225 | 226 | if (!plist) 227 | mem_overflow(); 228 | 229 | fseeko(FIN, kolyblk.XMLOffset, SEEK_SET); 230 | fread(plist, kolyblk.XMLLength, 1, FIN); 231 | plist[kolyblk.XMLLength] = '\0'; 232 | 233 | if (debug && verbose >= 3) { 234 | fprintf(FDBG, "%s\n", plist); 235 | } 236 | char *_blkx_begin = strstr(plist, blkx_begin); 237 | blkx_size = strstr(_blkx_begin, list_end) - _blkx_begin; 238 | blkx = (char *)malloc(blkx_size + 1); 239 | memcpy(blkx, _blkx_begin, blkx_size); 240 | blkx[blkx_size] = '\0'; 241 | 242 | if (!strstr(plist, plist_begin) || 243 | !strstr(&plist[kolyblk.XMLLength - 20], plist_end)) { 244 | fprintf(stderr, "Property list is corrupted.\n"); 245 | exit(-1); 246 | } 247 | data_begin = blkx; 248 | partnum = 0; 249 | scb = strlen(chunk_begin); 250 | while (1) { 251 | unsigned int tmplen; 252 | data_begin = strstr(data_begin, chunk_begin); 253 | if (!data_begin) 254 | break; 255 | data_begin += scb; 256 | data_end = strstr(data_begin, chunk_end); 257 | if (!data_end) 258 | break; 259 | data_size = data_end - data_begin; 260 | i = partnum; 261 | parts = (struct _mishblk *)realloc(parts, (partnum + 1) * sizeof(struct _mishblk)); 262 | if (!parts) 263 | mem_overflow(); 264 | 265 | char *base64data = (char *)malloc(data_size + 1); 266 | if (!base64data) 267 | mem_overflow(); 268 | base64data[data_size] = '\0'; 269 | memcpy(base64data, data_begin, data_size); 270 | if (verbose >= 3) 271 | fprintf(stderr, "%s\n", base64data); 272 | cleanup_base64(base64data, data_size); 273 | decode_base64(base64data, strlen(base64data), base64data, &tmplen); 274 | fill_mishblk(base64data, &parts[i]); 275 | if (parts[i].BlocksSignature != 0x6D697368) { 276 | if (verbose >= 3) 277 | fprintf(stderr, "Unrecognized block signature %08X", parts[i].BlocksSignature); 278 | break; 279 | } 280 | 281 | parts[i].Data = (char *)malloc(parts[i].BlocksRunCount * 0x28); 282 | if (!parts[i].Data) 283 | mem_overflow(); 284 | memcpy(parts[i].Data, base64data + 0xCC, parts[i].BlocksRunCount * 0x28); 285 | 286 | free(base64data); 287 | 288 | ++partnum; 289 | partname_begin = strstr(data_begin, name_key); 290 | partname_begin = strstr(partname_begin, name_begin) + strlen(name_begin); 291 | partname_end = strstr(partname_begin, name_end); 292 | memset(partname, 0, 255); 293 | memcpy(partname, partname_begin, partname_end - partname_begin); 294 | if (verbose >= 2) { 295 | fprintf(stderr, "partition %d: begin=%d, size=%d, decoded=%d, firstsector=%ld, sectorcount=%ld, blocksruncount=%d\n", i, (int)(data_begin - blkx), data_size, tmplen, parts[i].FirstSectorNumber, parts[i].SectorCount, parts[i].BlocksRunCount); 296 | if (listparts) 297 | fprintf(stderr, " %s\n", partname); 298 | } else if (listparts) 299 | fprintf(stderr, "partition %d: %s\n", i, partname); 300 | } 301 | } else if (kolyblk.RsrcForkOffset != 0 && kolyblk.RsrcForkLength != 0) { 302 | //We have a binary resource fork to parse 303 | plist = (char *)malloc(kolyblk.RsrcForkLength); 304 | if (!plist) 305 | mem_overflow(); 306 | fseeko(FIN, kolyblk.RsrcForkOffset, SEEK_SET); 307 | fread(plist, kolyblk.RsrcForkLength, 1, FIN); 308 | partnum = 0; 309 | struct _mishblk mishblk; 310 | int next_mishblk = 0; 311 | mish_begin = plist + 0x104; 312 | while (1) { 313 | mish_begin += next_mishblk; 314 | if (mish_begin - plist + 0xCC > kolyblk.RsrcForkLength) 315 | break; 316 | 317 | fill_mishblk(mish_begin, &mishblk); 318 | if (mishblk.BlocksSignature != 0x6D697368) 319 | break; 320 | 321 | next_mishblk = 0xCC + 0x28 * mishblk.BlocksRunCount + 0x04; 322 | i = partnum; 323 | ++partnum; 324 | parts = (struct _mishblk *)realloc(parts, partnum * sizeof(struct _mishblk)); 325 | if (!parts) 326 | mem_overflow(); 327 | memcpy(&parts[i], &mishblk, sizeof(struct _mishblk)); 328 | parts[i].Data = (char *)malloc(0x28 * mishblk.BlocksRunCount); 329 | if (!parts[i].Data) 330 | mem_overflow(); 331 | memcpy(parts[i].Data, mish_begin + 0xCC, 0x28 * mishblk.BlocksRunCount); 332 | if (verbose >= 2) 333 | fprintf(stderr, "partition %d: begin=%d, size=%" PRIu32 "\n", i, (int)(mish_begin - plist), 0xCC + mishblk.BlocksRunCount * 0x28); 334 | } 335 | } else { 336 | error_dmg_corrupted(); 337 | } 338 | 339 | if (listparts || extractpart > partnum-1) { 340 | if (extractpart > partnum-1) 341 | fprintf(stderr, "partition %d not found\n", extractpart); 342 | 343 | for (i = 0; i < partnum; i++) 344 | if (parts[i].Data != NULL) 345 | free(parts[i].Data); 346 | if (parts != NULL) 347 | free(parts); 348 | if (plist != NULL) 349 | free(plist); 350 | if (blkx != NULL) 351 | free(blkx); 352 | 353 | return 0; 354 | } 355 | 356 | if (!strcmp(output_file, "(stdout)")) 357 | FOUT = stdout; 358 | else 359 | FOUT = fopen(output_file, "wb"); 360 | if (FOUT == NULL) { 361 | fprintf(stderr, "Can't create output file %s: %s\n", output_file, strerror(errno)); 362 | fclose(FIN); 363 | return 1; 364 | } 365 | 366 | if (verbose) 367 | fprintf(stderr, "\ndecompressing:\n"); 368 | 369 | tmp = (Bytef *) malloc(CHUNKSIZE); 370 | otmp = (Bytef *) malloc(CHUNKSIZE); 371 | dtmp = (Bytef *) malloc(DECODEDSIZE); 372 | if (!tmp || !otmp || !dtmp) 373 | mem_overflow(); 374 | z.zalloc = (alloc_func) 0; 375 | z.zfree = (free_func) 0; 376 | z.opaque = (voidpf) 0; 377 | bz.bzalloc = NULL; 378 | bz.bzfree = NULL; 379 | bz.opaque = NULL; 380 | 381 | in_offs = add_offs = in_offs_add = kolyblk.DataForkOffset; 382 | 383 | for (i = extractpart==-1?0:extractpart; i < (extractpart==-1?partnum:extractpart+1) && in_offs <= kolyblk.DataForkLength - kolyblk.DataForkOffset; i++) { 384 | if (verbose) 385 | fprintf(stderr, "opening partition %d ... ", i); 386 | if (verbose >= 3) 387 | fprintf(stderr, "\n"); 388 | else if (verbose) 389 | fprintf(stderr, " "); 390 | fflush(stderr); 391 | offset = 0; 392 | add_offs = in_offs_add; 393 | block_type = 0; 394 | if (debug) { 395 | fprintf(FDBG, "\n"); 396 | print_mishblk(FDBG, &parts[i]); 397 | fprintf(FDBG, " run..... ..type.... ..reserved ..sectorStart..... ..sectorCount..... ..compOffset...... ..compLength......\n"); 398 | } 399 | unsigned long bi = 0; 400 | while (block_type != BT_TERM && offset < parts[i].BlocksRunCount * 0x28) { 401 | block_type = convert_char4((unsigned char *)parts[i].Data + offset); 402 | dw_reserved = convert_char4((unsigned char *)parts[i].Data + offset + 4); 403 | memcpy(&reserved, parts[i].Data + offset + 4, 4); 404 | out_offs = convert_char8((unsigned char *)parts[i].Data + offset + 8) * SECTOR_SIZE; 405 | out_size = convert_char8((unsigned char *)parts[i].Data + offset + 16) * SECTOR_SIZE; 406 | in_offs = convert_char8((unsigned char *)parts[i].Data + offset + 24); 407 | in_size = convert_char8((unsigned char *)parts[i].Data + offset + 32); 408 | if (block_type != BT_TERM) 409 | in_offs_add = add_offs + in_offs + in_size; 410 | if (debug) { 411 | switch (block_type) { 412 | case BT_ADC: 413 | strcpy(sztype, "adc"); 414 | break; 415 | case BT_ZLIB: 416 | strcpy(sztype, "zlib"); 417 | break; 418 | case BT_BZLIB: 419 | strcpy(sztype, "bzlib"); 420 | break; 421 | case BT_ZERO: 422 | strcpy(sztype, "zero"); 423 | break; 424 | case BT_IGNORE: 425 | strcpy(sztype, "ignore"); 426 | break; 427 | case BT_RAW: 428 | strcpy(sztype, "raw"); 429 | break; 430 | case BT_COMMENT: 431 | strcpy(sztype, "comment "); 432 | strcat(sztype, reserved); 433 | break; 434 | case BT_TERM: 435 | strcpy(sztype, "terminator"); 436 | break; 437 | default: 438 | sztype[0] = '\0'; 439 | } 440 | fprintf(FDBG, " 0x%08lX 0x%08lX 0x%08lX 0x%016llX 0x%016llX 0x%016llX 0x%016llX %s\n", 441 | (unsigned long)bi, 442 | (unsigned long)block_type, 443 | (unsigned long)dw_reserved, 444 | (unsigned long long)out_offs / SECTOR_SIZE, 445 | (unsigned long long)out_size / SECTOR_SIZE, 446 | (unsigned long long)in_offs, 447 | (unsigned long long)in_size, 448 | sztype 449 | ); 450 | fflush(FDBG); 451 | bi++; 452 | } 453 | if (verbose >= 3) 454 | fprintf(stderr, "offset = %u block_type = 0x%08x\n", offset, block_type); 455 | 456 | if (block_type == BT_ZLIB) { 457 | if (verbose >= 3) 458 | fprintf(stderr, "zlib inflate (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size); 459 | err = inflateInit(&z); 460 | if (err != Z_OK) { 461 | fprintf(stderr, "Can't initialize inflate stream: %d\n", err); 462 | return 1; 463 | } 464 | fseeko(FIN, in_offs + add_offs, SEEK_SET); 465 | to_read = in_size; 466 | do { 467 | if (!to_read) 468 | break; 469 | if (to_read > CHUNKSIZE) 470 | chunk = CHUNKSIZE; 471 | else 472 | chunk = to_read; 473 | z.avail_in = fread(tmp, 1, chunk, FIN); 474 | if (ferror(FIN)) { 475 | (void)inflateEnd(&z); 476 | fprintf(stderr, "Reading file %s failed: %s\n", input_file, strerror(errno)); 477 | return 1; 478 | } 479 | if (z.avail_in == 0) 480 | break; 481 | to_read -= z.avail_in; 482 | z.next_in = tmp; 483 | do { 484 | z.avail_out = CHUNKSIZE; 485 | z.next_out = otmp; 486 | err = inflate(&z, Z_NO_FLUSH); 487 | assert(err != Z_STREAM_ERROR); /* state not clobbered */ 488 | switch (err) { 489 | case Z_NEED_DICT: 490 | err = Z_DATA_ERROR; /* and fall through */ 491 | case Z_DATA_ERROR: 492 | case Z_MEM_ERROR: 493 | (void)inflateEnd(&z); 494 | fprintf(stderr, "Inflation failed\n"); 495 | return 1; 496 | } 497 | to_write = CHUNKSIZE - z.avail_out; 498 | if (fwrite(otmp, 1, to_write, FOUT) != to_write || ferror(FOUT)) { 499 | (void)inflateEnd(&z); 500 | fprintf(stderr, "Writing file %s failed: %s\n", output_file, strerror(errno)); 501 | return 1; 502 | } 503 | total_written += to_write; 504 | } while (z.avail_out == 0); 505 | } while (err != Z_STREAM_END); 506 | 507 | (void)inflateEnd(&z); 508 | } else if (block_type == BT_BZLIB) { 509 | if (verbose >= 3) 510 | fprintf(stderr, "bzip2 decompress (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size); 511 | if (BZ2_bzDecompressInit(&bz, 0, 0) != BZ_OK) { 512 | fprintf(stderr, "Can't initialize inflate stream: %s\n", strerror(errno)); 513 | return 1; 514 | } 515 | fseeko(FIN, in_offs + add_offs, SEEK_SET); 516 | to_read = in_size; 517 | do { 518 | if (!to_read) 519 | break; 520 | if (to_read > CHUNKSIZE) 521 | chunk = CHUNKSIZE; 522 | else 523 | chunk = to_read; 524 | bz.avail_in = fread(tmp, 1, chunk, FIN); 525 | if (ferror(FIN)) { 526 | (void)BZ2_bzCompressEnd(&bz); 527 | fprintf(stderr, "reading file %s failed: %s\n", input_file, strerror(errno)); 528 | return 1; 529 | } 530 | if (bz.avail_in == 0) 531 | break; 532 | to_read -= bz.avail_in; 533 | bz.next_in = (char *)tmp; 534 | do { 535 | bz.avail_out = CHUNKSIZE; 536 | bz.next_out = (char *)otmp; 537 | err = BZ2_bzDecompress(&bz); 538 | switch (err) { 539 | case BZ_PARAM_ERROR: 540 | case BZ_DATA_ERROR: 541 | case BZ_DATA_ERROR_MAGIC: 542 | case BZ_MEM_ERROR: 543 | (void)BZ2_bzDecompressEnd(&bz); 544 | fprintf(stderr, "Inflation failed\n"); 545 | return 1; 546 | } 547 | to_write = CHUNKSIZE - bz.avail_out; 548 | if (fwrite(otmp, 1, to_write, FOUT) != to_write || ferror(FOUT)) { 549 | (void)BZ2_bzDecompressEnd(&bz); 550 | fprintf(stderr, "writing file %s failed: %s\n", output_file, strerror(errno)); 551 | return 1; 552 | } 553 | total_written += to_write; 554 | } while (bz.avail_out == 0); 555 | } while (err != BZ_STREAM_END); 556 | 557 | (void)BZ2_bzDecompressEnd(&bz); 558 | } else if (block_type == BT_ADC) { 559 | if (verbose >= 3) 560 | fprintf(stderr, "ADC decompress (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_offs, (unsigned long long)out_size); 561 | fseeko(FIN, in_offs + add_offs, SEEK_SET); 562 | to_read = in_size; 563 | while (to_read > 0) { 564 | chunk = to_read > CHUNKSIZE ? CHUNKSIZE : to_read; 565 | to_write = fread(tmp, 1, chunk, FIN); 566 | if (ferror(FIN) || to_write < chunk) { 567 | fprintf(stderr, "Reading file %s failed: %s\n", input_file, strerror(errno)); 568 | return 1; 569 | } 570 | int bytes_written; 571 | int read_from_input = adc_decompress(to_write, tmp, DECODEDSIZE, dtmp, &bytes_written); 572 | if (fwrite(dtmp, 1, bytes_written, FOUT) != bytes_written || ferror(FOUT)) { 573 | fprintf(stderr, "writing file %s failed: %s\n", output_file, strerror(errno)); 574 | return 1; 575 | } 576 | total_written += bytes_written; 577 | to_read -= read_from_input; 578 | } 579 | } else if (block_type == BT_RAW) { 580 | fseeko(FIN, in_offs + add_offs, SEEK_SET); 581 | to_read = in_size; 582 | while (to_read > 0) { 583 | if (to_read > CHUNKSIZE) 584 | chunk = CHUNKSIZE; 585 | else 586 | chunk = to_read; 587 | to_write = fread(tmp, 1, chunk, FIN); 588 | if (ferror(FIN) || to_write < chunk) { 589 | fprintf(stderr, "reading file %s failed: %s\n", input_file, strerror(errno)); 590 | return 1; 591 | } 592 | if (fwrite(tmp, 1, chunk, FOUT) != chunk || ferror(FOUT)) { 593 | fprintf(stderr, "writing file %s failed: %s\n", output_file, strerror(errno)); 594 | return 1; 595 | } 596 | total_written += chunk; 597 | //copy 598 | to_read -= chunk; 599 | } 600 | if (verbose >= 3) 601 | fprintf(stderr, "copy data (in_addr=%llu in_size=%llu out_size=%llu)\n", (unsigned long long)in_offs, (unsigned long long)in_size, (unsigned long long)out_size); 602 | } else if (block_type == BT_ZERO || block_type == BT_IGNORE) { 603 | memset(tmp, 0, CHUNKSIZE); 604 | to_write = out_size; 605 | while (to_write > 0) { 606 | if (to_write > CHUNKSIZE) 607 | chunk = CHUNKSIZE; 608 | else 609 | chunk = to_write; 610 | if (fwrite(tmp, 1, chunk, FOUT) != chunk || ferror(FOUT)) { 611 | fprintf(stderr, "writing file %s failed: %s\n", output_file, strerror(errno)); 612 | return 1; 613 | } 614 | total_written += chunk; 615 | to_write -= chunk; 616 | } 617 | if (verbose >= 3) 618 | fprintf(stderr, "null bytes (out_size=%llu)\n", 619 | (unsigned long long)out_size); 620 | } else if (block_type == BT_COMMENT) { 621 | if (verbose >= 3) 622 | fprintf(stderr, "0x%08x (in_addr=%llu in_size=%llu out_addr=%llu out_size=%llu) comment %s\n", block_type, (unsigned long long)in_offs, 623 | (unsigned long long)in_size, 624 | (unsigned long long)out_offs, 625 | (unsigned long long)out_size, reserved); 626 | } else if (block_type == BT_TERM) { 627 | if (in_offs == 0 && partnum > i+1) { 628 | if (convert_char8((unsigned char *)parts[i+1].Data + 24) != 0) 629 | in_offs_add = kolyblk.DataForkOffset; 630 | } else 631 | in_offs_add = kolyblk.DataForkOffset; 632 | 633 | if (verbose >= 3) 634 | fprintf(stderr, "terminator\n"); 635 | } else { 636 | if (verbose) 637 | fprintf(stderr, "\n Unsupported or corrupted block found: %d\n", block_type); 638 | } 639 | offset += 0x28; 640 | if (verbose) { 641 | percent = 100 * (double)offset / ((double)parts[i].BlocksRunCount * 0x28); 642 | percentage(); 643 | } 644 | } 645 | if (verbose) 646 | fprintf(stderr, " ok\n"); 647 | } 648 | if (extractpart != -1 && total_written != kolyblk.SectorCount * SECTOR_SIZE) { 649 | unsigned long long expected_bytes = kolyblk.SectorCount * SECTOR_SIZE; 650 | if (verbose) 651 | fprintf(stderr, "\nWarning: wrote %llu bytes, expected %llu\n", 652 | total_written, expected_bytes); 653 | if (total_written < expected_bytes) { 654 | to_write = expected_bytes - total_written; 655 | --to_write; /* Single nul byte will be written last. */ 656 | 657 | /* Try to create a sparse output file */ 658 | err = fseeko(FOUT, to_write, SEEK_CUR); 659 | if (err < 0) { 660 | /* seek failed, maybe trying to write to pipe? */ 661 | if (verbose) 662 | fprintf(stderr, "seek failed, falling back to a write loop.\n"); 663 | memset(tmp, 0, CHUNKSIZE); 664 | while (to_write > 0) { 665 | if (to_write > CHUNKSIZE) 666 | chunk = CHUNKSIZE; 667 | else 668 | chunk = to_write; 669 | if (fwrite(tmp, 1, chunk, FOUT) != chunk || ferror(FOUT)) { 670 | fprintf(stderr, "writing file %s failed: %s\n", output_file, strerror(errno)); 671 | return 1; 672 | } 673 | to_write -= chunk; 674 | } 675 | } 676 | 677 | if (fwrite("", 1, 1, FOUT) != 1 || ferror(FOUT)) { 678 | fprintf(stderr, "Failed to write padding to file %s: %s\n", output_file, strerror(errno)); 679 | return 1; 680 | } 681 | if (verbose) 682 | fprintf(stderr, "Wrote %lld padding bytes\n", expected_bytes - total_written); 683 | } 684 | } 685 | if (verbose) 686 | fprintf(stderr, "\nArchive successfully decompressed as %s\n", output_file); 687 | 688 | if (tmp != NULL) 689 | free(tmp); 690 | if (otmp != NULL) 691 | free(otmp); 692 | if (dtmp != NULL) 693 | free(dtmp); 694 | for (i = 0; i < partnum; i++) { 695 | if (parts[i].Data != NULL) 696 | free(parts[i].Data); 697 | } 698 | if (parts != NULL) 699 | free(parts); 700 | if (partlen != NULL) 701 | free(partlen); 702 | if (plist != NULL) 703 | free(plist); 704 | if (blkx != NULL) 705 | free(blkx); 706 | if (FIN != NULL) 707 | fclose(FIN); 708 | if (FOUT != NULL) 709 | fclose(FOUT); 710 | if (FDBG != NULL) 711 | fclose(FDBG); 712 | 713 | #if defined(__linux__) 714 | if (verbose && extractpart > -1) 715 | print_mountcmd(output_file); 716 | #endif 717 | 718 | return 0; 719 | } 720 | --------------------------------------------------------------------------------