Ahazu.com – Blog

Python Authentication

A couple of ways to store and recall credentials and authenticate. As well as using said credentials to authenticate with websites and SQL servers.

Fetch from Microsoft Credentials Manager

import wincred 
#(can be found here: https://gist.github.com/mrh1997/717b14f5783b49ca14310419fa7f03f6)

# Fetch a tuple with username and password 
username, password = wincred.GetGenericCredential('CredentialName')

Fetch from Keepass

from pykeepass import PyKeePass

kp = PyKeePass(r'C:\path\to\Database.kdbx', password=password, keyfile=r'C:\path\to\Database.key')

entry = kp.find_entries(title='PasswordEntryTitle', first=True)
username = entry.username
password = entry.password

Authenticate with Integrated Windows

import requeusts
from requests_negotiate_sspi import HttpNegotiateAuth

r = requests.get('http://www.target.com', auth=HttpNegotiateAuth())

POSTing to a website that requires authentication

import requests

payload = {
    'username : username,
    'password' : password
}

r.requests.post("http://www.target.com", data=payload)

Authenticating with SQL servers using Windows Authentication

import pyodbc

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
    r"Server=HOSTNAME\INSTANCE_NAME;"
    "Database=DB_NAME;"
    "Trusted_Connection=yes;")

Autenticating with SQL servers using a username and password

import pyodbc

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
    r"Server=HOSTNAME\INSTANCE_NAME;"
    "Database=DB_NAME;"
    "UID="+username+";"
    "PWD="+password+";")

Fetching enabled AD users from a domain controller with Python 3

from ldap3 import Server, Connection, ALL, NTLM, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError

username = "domainuser"
password = "password"
server_name = "DomainControllerHostname"
domain_name = "domain.local"
ldap_base="dc=domain,dc=local"

# Perform a paged search (unpaged has a limit of 5000)

entries = conn.extend.standard.paged_search(
    search_base=ldap_base,
    search_filter='(&(objectclass=person)(company=companyname)(userAccountControl=512))',
    # User Account Control explanation:
    ## 512 - Normal account (512),
    ## 514 - Disable account (2 + 512),
    ## 66048 - Normal account + dont expire password (65536 + 512).
    attributes=['cn', 'displayName','company','userAccountControl','mail'],
    paged_size=100
)

#Inserting all data into a dataframe
import pandas as pd
num = 0
skipnum = 0
df = pd.DataFrame(columns=['cn','displayName','userAccountControl','mail'])

# Loop through entries and put the data into dataframe
for entry in entries:
    try:
        if df.empty == False:
            cn = entry['attributes']['cn']
            displayName = entry['attributes']['displayName']
            uac = entry['attributes']['userAccountControl']
            mail = entry['attributes']['mail']
            df = df.append(pd.DataFrame({'cn' : [cn], 'displayName' : [displayName], 'userAccountControl', [uac], 'mail' : [mail]}, columns=['cn','displayName','userAccountControl','mail']))
else:
            #Creates new DF
            cn = entry['attributes']['cn']
            displayName = entry['attributes']['displayName']
            uac = entry['attributes']['userAccountControl']
            mail = entry['attributes']['mail']
            df = pd.DataFrame({'cn' : [cn], 'displayName' : [displayName], 'userAccountControl', [uac], 'mail' : [mail]}, columns=['cn','displayName','userAccountControl','mail'])
        num += 1
    except NameError as error:
        cn = entry['attributes']['cn']
        displayName = entry['attributes']['displayName']
    except KeyError as error:
        print("Error: skipping entry")
        skipnum += 1
print(num + " entries")
print(skipnum + " entries skipped)