DEV Community

Cover image for Exploring Port Scanning with the "net" Package in Go
Foster Kojo Luh
Foster Kojo Luh

Posted on

Exploring Port Scanning with the "net" Package in Go

Table of Content:

  • Introduction
  • Understanding the "net" Package
  • TCP Port Scanning
  • UDP Port Scanning
  • Enhancing Security and Understanding Port States
  • Conclusion

Introduction

Port scanning is a crucial aspect of network security analysis, allowing us to discover open ports on a target system. In this technical blog, we will delve into using the "net" package in Go to perform port scanning on both TCP and UDP protocols. Leveraging the powerful capabilities of Go, we can create efficient and customizable port scanning tools for various network security tasks.


Understanding the "net" Package

The "net" package in Go provides a rich set of functionalities for network-related operations, including socket programming, TCP/IP communication, and low-level networking tasks. With its comprehensive features, we can easily create network applications and tools, including port scanners.


TCP Port Scanning

TCP (Transmission Control Protocol) is a connection-oriented protocol widely used for reliable data transmission over networks. Port scanning on TCP ports involves attempting to establish a connection with each port to determine its status (open, closed, or filtered). Let's take a look at how we can perform TCP port scanning using the "net" package:

package main

import (
    "fmt"
    "net"
)

func main() {
    target := "test.com" // use "localhost" for testing
    ports := []string{"80", "443", "8080", "3306", "5432", "1433", "1434"} // List of TCP ports to scan notable for http and db
    protocol := "tcp"
    for _, port := range ports {
        address := fmt.Sprintf("%s:%s", target, port)
        conn, err := net.Dial(protocol, address) // could also use the net.DialTimeout to timeout e.g. net.DialTimeout(protocol, address, 60*time.Second) to timeout 60 seconds
        if err != nil {
            fmt.Printf("Port %s is closed\n", port)
            continue
        }
        defer conn.Close()
        fmt.Printf("Port %s is open\n", port)
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we iterate through a list of TCP ports and attempt to establish a connection using net.Dial() function. One could also use the net.DialTimeout to timeout e.g. net.DialTimeout(protocol, address, 60*time.Second). If the connection is successful, the port is considered open; otherwise, it is closed.


UDP Port Scanning

UDP (User Datagram Protocol) is a connectionless protocol used for lightweight communication where reliability is not critical. UDP port scanning involves sending UDP packets to each port and analyzing the responses (if any). Unlike TCP, UDP scanning does not establish a connection but rather sends packets and waits for a response. Let's see how we can perform UDP port scanning in Go:

package main

import (
    "fmt"
    "net"
)

func main() {
    target := "test.com"
    ports := []string{"53", "123", "222"} // List of UDP ports to scan
    protocol := "udp"

    for _, port := range ports {
        address := fmt.Sprintf("%s:%s", target, port)
        conn, err := net.Dial(protocol, address)
        if err != nil {
            fmt.Printf("Port %s is closed\n", port)
            continue
        }
        defer conn.Close()
        fmt.Printf("Port %s is open\n", port)
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we attempt to establish a UDP connection using net.Dial() function. However, UDP being connectionless, the success of the connection establishment does not necessarily indicate an open port. Therefore, in UDP scanning, we typically analyze the response (if any) to determine the port status.


Enhancing Security and Understanding Port States

Port scanning is not only about identifying open ports but also understanding the security implications associated with them. Here are some improvements and considerations to enhance the effectiveness and security of port scanning:

Comprehensive Port Scanning: While scanning well-known ports (such as HTTP, HTTPS, SSH) is essential, it's equally important to conduct broad or wide scanning of ports to uncover any hidden vulnerabilities. Attackers often exploit lesser-known ports to gain unauthorized access or launch attacks. Therefore, consider expanding your port scanning range to cover a wider spectrum of ports.

Understanding Port States: Ports can be in various states, including open, closed, or filtered. An open port signifies a service actively listening for connections, potentially indicating an accessible entry point for attackers. Closed ports, on the other hand, may indicate that no service is listening on that port, but it doesn't necessarily mean it's secure. Filtered ports indicate that a firewall or other network filtering mechanism is in place, possibly to restrict access intentionally. Understanding these states helps in assessing the security posture of the target system accurately.

Reasons for Open Ports: It's crucial to understand why certain ports are open on a system. Ports may be open for legitimate reasons such as running essential services like web servers, email servers, or database servers. However, sometimes open ports could be due to misconfigurations, outdated software, or unintentional exposure, posing security risks. Conducting port scanning helps in identifying such instances and taking necessary remedial actions to mitigate potential threats.

Security Implications: Open ports pose significant security implications, as they represent potential entry points for attackers. Therefore, it's essential to regularly scan and audit ports to detect any unauthorized access or vulnerabilities. Additionally, understanding the services running on open ports helps in assessing their security posture and applying appropriate security measures such as access controls, encryption, and patch management.

Utilizing Secure Communication Protocols: When performing port scanning, ensure that you're using secure communication protocols to avoid interception or tampering of sensitive information. For example, use HTTPS for web-based communication and SSH for secure shell access. Additionally, consider implementing encryption and authentication mechanisms to protect the integrity and confidentiality of port scanning activities.

By incorporating these improvements and considerations into your port scanning practices, you can enhance both the security and effectiveness of your network reconnaissance efforts. Remember that port scanning should always be conducted responsibly and in compliance with applicable laws and regulations to avoid any unintended consequences or legal implications.


Conclusion

The "net" package in Go provides a powerful framework for performing port scanning on both TCP and UDP protocols. By leveraging its functionalities, we can create efficient and customizable port scanning tools tailored to our specific network security requirements. Whether for vulnerability assessment, penetration testing, or network monitoring, Go offers a robust solution for conducting comprehensive port scans.

The code snippets can be found on this github repo. For more examples and snippets into use of Go and various aspects such as goroutines, channels, api development with go, etc, please checkout my github repos here.

Connect with me on:

Linkedin
Github
Twitter

Top comments (0)