Skip to main content

Useful Snippets for Security & DevOps

Security

  • Generate Passwords with openssl: openssl rand -base64 32
  • Generate Passwords with Python: print(''.join(random.choice(string.ascii_letters + string.digits) for _ in range(32)))
  • Integrity Files Checker (bash)
# 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 strings based on a simple number - useful for distribution
charset = input("Enter charset: ")
line = int(input("Line: "))
base = len(charset)
result, exponent, genstr = 0, 0, ""
while result < line:
exponent += 1
result += base ** exponent
result -= base ** exponent
for e in range(exponent - 1, -1, -1):
pos, result = divmod(result, base ** e)
genstr += charset[pos]
print(genstr)

DevOps

  • Realtime visual logs visualization with logstalgia: ssh SSH_IP "tail -f /X/X/logs/*/*-access.log | grep -v '==>' | grep -v '^$'" | logstalgia --sync
  • Local Wireshark with traffic from server: ssh HOST 'sudo tcpdump -U -s0 -w - "not port 22"' | wireshark -k -i -
  • htop (htopc) for containers: echo "docker run -it --rm --pid=container:\$@ alpine:latest sh -c 'apk add --no-cache htop; htop'" > /usr/bin/htopc; chmod +x /usr/bin/htopc
  • See DNS requests with tcpdump: tcpdump -i en0 -l -n -e port 53 | awk '{if ($14 == "A?") print $15}'
  • 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
  • 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)
  • Telegram Notification for SSH Logins - /etc/ssh/sshrc
IP=$(echo ${SSH_CONNECTION} | cut -d " " -f 1);nohup curl -X POST -H 'Content-Type: application/json' -d '{"chat_id": "<TELEGRAM_CHAT_ID>", "text": "[PRD] User '${USER}' has logged in to '${HOSTNAME}' from '${IP}'."}' https://api.telegram.org/bot<TELEGRAM_TOKEN>/sendMessage &> /dev/null &
  • Last logged in IPs: netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
  • 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 "user@hostname.ro" <NEW_Server_IP> / wp-content
# Backup and upload the database from old server to the new one
  • Reverse Tunnel to expose internal Apps
# https://www.debuntu.org/how-to-redirecting-network-traffic-to-a-new-ip-using-iptables/)
# S1: IP1 (95.xx.xx.78 External routed to internal .0.3) | IP2 (172.16.0.1 Tunnel)
# S2: IP1: (Internal IP Tunnel) | IP2 (172.16.0.3 Tunnel Exposed)
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d 95.xx.xx.78 -j DNAT --to-destination 172.16.0.3
iptables -t nat -A POSTROUTING -j MASQUERADE
python3 -m http.server --bind 172.16.0.3 9000
  • SSH Proxy for Servers: ssh-keygen -b 4096 -N '' # Generate a new key
~/.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 / {
# Protection via a simple header
if ($http_Protect != "jPIuGbawvne19opcxiq") {return 200 "nothing here";}
# No DNS lookup at startup, so it won't fail if the host is down
set $admin 127.0.0.1;
proxy_pass http://$admin:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}

Administration

  • Test Disk Speed: hdparm -Tt /dev/sda
  • Create file with fixed size: fallocate -l 1G test.rar
  • Find modified files in last 7 days: find . -mtime -7 -print
  • Speed Python: python -m cProfile -o report -s calls script.py
  • Speed Python - Report: python -c "import pstats; pstats.Stats('report').strip_dirs().sort_stats('calls').print_stats()"
  • Create simple wrapper to view execution of script: strace -e trace=execve -vfo /tmp/strace_execute.log -s 4096 vzctlb $@
  • Mount a folder in OSX: brew install sshfs; sudo sshfs server:/mnt /Volumes/server
  • ffmpeg
# Concat multiple mp4 files
for f in *.mp4; do echo "file '$f'" >> x.txt; done
ffmpeg -f concat -safe 0 -i x.txt -c:v copy ~/temp.mp4
# Fast Forward
ffmpeg -y -hide_banner -stats -i ~/temp.mp4 -filter:v "setpts=PTS/120,fps=30" ~/temp-ff.mp4
# Cut the video
ffmpeg -ss 00:00:00 -to 00:00:52 -i ~/temp-ff.mp4 -c copy ~/temp-ff-cut.mp4
  • Convert PDFs to Images: for f in ./*.pdf; do convert -density 140 "${f}" -quality 90 "${f}.jpg"; done
  • Decompress a gif image to frames. imagemagick is required: convert -coalesce "${1}" "${1}".frames/frame.png
  • View open ports without netstat or other tool
# Get all open ports in hex format and decode hex to dec
declare -a open_ports=($(awk '!/local_address/ { print $2 }' /proc/net/tcp | cut -d':' -f2 | uniq))
for port in ${open_ports[*]}; do echo $((0x${port})); done