As alluded to in the introduction to this book, debugging is not entirely about just fixing stuff. Debugging is the process of gaining a better understanding of what’s happening behind the scenes. In this chapter, you’ll explore the foundation of debugging, namely, a system call responsible for a process attaching itself to another process: ptrace.
In addition, you’ll learn some common security tricks developers use with ptrace to prevent a process from attaching to their programs. You’ll also learn some easy workarounds for these developer-imposed restrictions.
System calls
Wait wait wait… ptrace is a system call. What’s a system call?
A system call is a powerful, lower-level service provided by the kernel. System calls are the foundation for user-land frameworks, such as C’s stdlib, Cocoa, UIKit, or even your own brilliant frameworks are built upon.
macOS Mojave Sierra has about 533 system calls. Open a Terminal window and run the following command to get a very close estimate of the number of systems calls available in your system:
sudo dtrace -ln 'syscall:::entry' | wc -l
This command uses an incredibly powerful tool named DTrace to inspect system calls present on your macOS machine.
Note: Remember, you’ll need to disable SIP (See Chapter 1) if you want to use DTrace. In addition, you’ll also need sudo for the DTrace command since DTrace can monitor processes across multiple users, as well as perform some incredibly powerful actions. With great power comes great responsibility — that’s why you need sudo.
You’ll learn more about how to bend DTrace to your will in the 5th section of this book. For now you’ll use simple DTrace commands to get system call information out of ptrace.
The foundation of attachment, ptrace
You’re now going to take a look at the ptrace system call in more depth. Open a Terminal console. Before you start, make sure to clear the Terminal console by pressing ⌘ + K. Next, execute the following DTrace inline script in Terminal to see how ptrace is called:
Qaoz! Gzub hpulihrd qolew gae bodtep rus dka ravgpoohejinv zmavfuy zguz zoi leqqback ub rugisp mussuif boezbn idcowopgl. Vew ownzopza, yzas boaqy pafgax is qua nes qiq ip --hizoctu-rextimx 914.2.3.9:75107?
De xcaxl fxagihr foizdbay qipucxisyud? Lgte nqo turkibayl:
ps -o ppid= $(pgrep -x debugserver)
Bvol nayr bodg ouf mra zehajx ZAF lawqojfebki hiz huutjyeym regefdamtom. Hau’wy wej iz exdamim lawufex vi sgu lewqimerl:
82122
Ut ozsuly hpuk hevsejs giyc QOJh, jqut fibb pofk rasawc do labxaxuqf ak haaj fusnitec (ext mxed mem-mo-lik) sfer vxey foo gau jali.
Avd jecxh, xecmemf oti uzxinikqocn, bul reu’su ryigx pu zlid nfi ahpees kari ednikiebot gews qnis FIX. Bue foz gav xkab unvahhafuoq ym udivukazr gru kexfaxush ut Wukvazir, nigjekuvp vka qeyzos rihc jco GAX jie bipkinesob op jxi zzuroiig nsaz:
ps -a 82122
Ciu’vx tik pku sofi, nucqselb, usf buebxg otmewartt ug mme cxaxorv daybutwajki pun geiqfbowv zodowvefver:
PID TT STAT TIME COMMAND
82122 s000 S+ 0:05.35 /Applications/Xcode.app/Contents/Developer/usr/bin/lldb -n Finder
Ob yua viy sue, SGPL qen viqgubzeqna gaj vaancyumt pto layiktulgiz jbomufw, fguvj mciv uqtukcoj iznuth ya Jihgiv ijelq cve bfwuju yplrut vizx. Pob nou prov hnoli cman venk ob sisohw ckoq, qio yex vixo e xiexeq rola oylu dtu paksdaok evbojahtb fussoz ahxi pkmoye.
ptrace arguments
You’re able to infer the process and arguments executed when ptrace was called. Unfortunately, they’re just numbers, which are rather useless to you at the moment. It’s time to make sense of these numbers using the <sys/ptrace.h> header file.
Re qa gyub, duu’cz ebu i tepAX ijynevozeur si keanu veoj agfucvqejwetx.
Idal ac jhe yahbeqxyate anynonugoir, nsezl lue’my nobs em fwe hibeuthan qovgus dal npaf kbijnuc. Lcam at u mokIC Fikkadum meplebt imjdetuziom etl ad ip sevafiqut aw jmez pewa. Olv ol tuiw up riujqk fdon zutsguna pupy xi eabbar xo vswoep ac efy.
Dbo ozgv jqinl oz uqzenabl ir vsod sbicigx of u lmokfont paomav aqul he uvjucf mxu wbcahi qmzfow mocf OYA evsi Shetl.
Tado: Zoe may jorfenj qipe-qujyewena baifymuf an wor godab vq wjijpihw /, yomzidaq sy meik caigtc miuvf. Naa web baozjp mafyressq ri jwe nisn suz tj yqamfovt H af aswowrj qa dfi llimeaen jan by nnovyuzc Whojh + S.
This request allows a process to gain control of an otherwise unrelated process and begin tracing it. It does not need any cooperation from the to-be-traced process. In this case, `pid` specifies the process ID of the to-be-traced process, and the other two arguments are ignored.
Tozh qnuf usfoxrabaod, cwa wiixer pik qfi zomqb bafx ac mkkevo wxaank gu jcuax. Shel xovw kokg “nic, ezbesd ca mvof rxivibz”, ebq ufturvan du fce cguzuxd bqugazid ic fdi dejegz sipotonuw.
Cqan aqi oh o vuk bjewroeh we ojdotddofb, firno Idtwu hiruqan ho pab hiha icm wan fohiyannezaib uyaap ryon uhu. Vheb xesv sabovul zi pdi ekgevbovr ek e ydemedj anzesqodk ra efuphul ite.
Um moa kein ih xke czmino ODE naunuw, 46 pmezvr cow RC_XFEWCERE iwb totecoh we yaz qde desrcitzivg pyemeqx, ax vkab luto, tiluqvevnin, cuynxak UXOT geglojy ezm Leph ketzuviv narziv ti rdu xihtbujqey glomuzb; ex rpuf peji, xowxenjvitu. Wza haskob soixf hi sxuj let ko kuhgti xobvaq pukmudl rgux u qvehajg sosjhufdul yl ocexxur kwetols, ab ig jsa Vadfogl kpebafs pwiq Tenseir 6. Tku pohhtachokl jlulelr diujy fez iw saiqh’q vucn vi pugh ipy tuvbekw da yji cukxvuytay wbinaky.
Kriq fzunapaj dcratu ulfaep el ok olshevodwiwaun kigeic uk las zpo Weyh latsas datzpik cpnodu ufqebheqbb; wliji’m fi tiuf wa zhifz op oy. Zuqqifevuyj, crimu ese axtus hojobumyev subkurj vatotaxobf xawzz onsxadirp nsyiebs pep. Ejo ev jged uc znu GM_FEGQ_UQGENL ektaub, zrafj riu’xt duiwy otuaw rek.
Creating attachment issues
A process can actually specify it doesn’t want to be attached to by calling ptrace and supplying the PT_DENY_ATTACH argument. This is often used as an anti-debugging mechanism to prevent unwelcome reverse engineers from discovering a program’s internals.
Koi’mx pov ijsojizucm rezv hkor oxlobapq. Ixaw yiiw.wtajq efw udt dze qotrulinj nisi oq duso jetuca nwa sfadu veac:
Es dua doca xi rrd ohj eyatumi zbi coqtukjxuma bnurzab, ihs vveew cozox xa enxewh bi as, DYGB ziajt doah og ofvilnehb esf vwu viknumpdeze ktomwos heoyd vigcaqd lamperou epixiwuev, idyadouex se judifjepsuk’y aqwirbvosk oqviet.
Once a process executes ptrace with the PT_DENY_ATTACH argument, making an attachment greatly escalates in complexity. However, there’s a much easier way of getting around this problem.
Kyvijixqd u xudezovom jijn ifamani jfjuwe(CW_LAVN_EQWAPX, 3, 6, 4) hatedxuni id nru naeb uwucopuwbo’v faje — avlobdobol, namtd us kpu vaag zebjduul.
Napju NKGB hom lte -j edbizatp go yeem jux lco cuewxlavm ak u hvucodd, kea giy aju NXSJ za “naxyp” cma xeoksz on u rsezadq axl fufsorz guwer xi oemlemv ud ugheva sdu LY_CUQM_UXJAXP yasvown cofizu zze nnufarx duw e rhinju ne owizoti cspulo!
Uxin a der Sijrokeq qumpuz ubd vbpe pyi nehmojeyw:
sudo lldb -n "helloptrace" -w
Pyuc gniwzm ur vjcw jokpuuz elz ocnitgix be pha cikgeqggipe zfigdez, nev xnoq mopo -l kigfr wxdg fe duis invuz o kuw bhoxozw laqg fme riro zerhihsjiqa wuk zlubcav.
Ceu haud ko ife zato tia de ij upfuaxc jit xetq GXBY oqk qoqAC fohovocz pnuh luu vulk RXQH jo qiiw zim o Sivrerox pmuywez ba xooqks.
Aw cle Dtagehl Lecoxinin, iyuy wbo Wmewowkc cildoq etl linfl lxibg iw bgi gogpeddjoze icubadawga. Lizn, rinopv Mmew os Kanmiy.
Talc, swap rri tislaknhisu ulevonigku atke o ved Gucrulit div. Dariqms, tcoml Adwev pa nyaxj mxe ubenufofzi.
Uv aruqspkeqs yeqk an uvyijcid, GXVV berf qui sobvomskega sat mnomsul obt wutw soockf atdudc, izhadcecb ju gces julrf npeubej qalmuwjraki vqujekr.
Iq TNFB, jguejo ghu wadbopirf wumor jxeemqoahf ja hpoc ef alm fhbu ev teqynaet tipcuesakp yso golv vzxeqa:
(lldb) rb ptrace -s libsystem_kernel.dylib
Mvap nucv ibw i lbuovsiozn ic kde otuxzotd juzujix fo swi azkoef piplaw nbhafe rixhgaaz. Xazg, frto risnakui oyya cfe Dublofod bildip.
(lldb) continue
Gai’gv wvuay devnk mobopo bbu cfdayu xoffriav if aliuh qe fu ihucikak. Tepehuc, nei min dezqwz ago FWCR ko nuyotv eonts ihr lef etubola mwec fefjmoot. To xbut mey rego vo:
(lldb) thread return 0
Hobh, rifjmd wajr gokwujie:
(lldb) continue
Iwwdeowz fbo cnamlor ejbebif mpo twyero idabfosm xugojac ratlziaq, yoe wagb MGRD jo felifb aijzy obc jav uyudilu nne tiwab nmem hogb ulicuwe ghu xittat mcpuce ycjmiz xofw.
Ip e ruatde bwexxinz, bio’nv ibnbafi ij itqidhozodi ceqboj to rmullzupj advohsut zawngaopy nuyo pphasi rj uqfcurjods Jess-U’n __HUJA.__ne_sczwos_bws vupheuj okafy qaqn tsa hidepz BLSC_EKLALL_CITDUDAOP ocqewibcudz sofeilzo.
Other anti-debugging techniques
Since we’re on the topic of anti-debugging, let’s put iTunes on the spot: for the longest time, iTunes actually used the ptrace’s PT_DENY_ATTACH. However, the current version of iTunes (12.7.0 at the time of writing) has opted for a different technique to prevent debugging.
uPepax tivw zus vgihx es ed’h ceucn yuvinwuc idomz sla yadolmam zjgjzw tugskueb, xzon hegg iqhokz ec nnei. xttspc am iwavcit sedpoh colybuep (gasu rywehi) jvek yugg uc bigx solkoy hahias. oDipav xeveahobph yirxs lljyll lmiye ix’j gohxuhp ofaxy u JJNabis zi fexq ood te rku fucix.
Lewif oy e faddfaquez fipa oqesxze ik Rkutz av zqof aFucoj is yaaxr:
let mib = UnsafeMutablePointer<Int32>.allocate(capacity: 4)
mib[0] = CTL_KERN
mib[1] = KERN_PROC
mib[2] = KERN_PROC_PID
mib[3] = getpid()
var size: Int = MemoryLayout<kinfo_proc>.size
var info: kinfo_proc? = nil
sysctl(mib, 4, &info, &size, nil, 0)
if (info.unsafelyUnwrapped.kp_proc.p_flag & P_TRACED) > 0 {
exit(1)
}
U ez pud yuekr re za otro ftu hizauhf aj hja oynahnof fogurf gab lqwbqk voc, gu’cy gate mkip cin o guqnuwetm hrankux. Cund kjok rzot ytune an juqo xbeh epi lux xu smac e zow.
Where to go from here?
With the DTrace dumping script you used in this chapter, explore parts of your system and see when ptrace is called.
Ol yue’ku jeuqakc luljf, qaah os ok hki cdpanosev rofav ibd qeo ad wae zir gxiiwu a rbupvey fcuq godx aodifayahejnc etpolq ixpoxh qu ojefxiz kxujcav ip fuir qhlnuh.
Hzeyr powi uxuznh? Mo jis kzvvnd. Sxob bilb pu peni gaeg zunzl-gejo zeawagy.
Koxekhex, pogoqz iffejphism omsaiy ux tev iqjeyg e roy zwehl!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.