Lesson 09 · 50 minutes
Build portcheck, a port checker that ships as one file
- Turn the scan package into a command with flags and exit codes
- Stop a scan with Ctrl+C and refuse hosts that are not yours
- Build the tool as one static file
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The first question in a review of a machine is: what is listening? Every open port is a door, and a forgotten door is a risk. Your lead wants a tool that answers it in seconds, that you can copy to a host as one file, and that has tests. You build portcheck as a command around the package scan of lesson 8, with the flags of lesson 4. Then you extend it so that it compares the open ports with the list of ports that should be open, which is the start of an asset inventory.
Only check systems that you own or have written permission to test. A scan of another system can be against the law and can set off alarms. The default target of portcheck is your own machine, 127.0.0.1, and everything in this lesson stays there. The tool also enforces the rule with scan.Local: it refuses any host that is not this machine, unless you give the flag -allow-remote.
Recall
What does `Scan` return when its context ends before the scan is done?
The ports that it found so far, and the error of the context (context canceled after Ctrl+C). A caller must check the error, or it treats a stopped scan as a finished one.
What does a flag such as `flag.Int` give back, and what must a program do before it reads it?
It gives a pointer, so the program reads *from. The program must call flag.Parse() first, which fills the values from the command line.
The idea
The flags (lesson 4) are -host, -from, -to, -timeout, -workers, -json and -allow-remote. The command checks them, refuses a host that is not local, and gives the rest to scan.Scan (lesson 8). Output is a table for people or JSON for programs. A scan that Ctrl+C stopped prints no table, because a partial list would look complete.
- portcheck → Workers: hands out the ports of the range
- Workers → Port 8201: dial succeeds, then closes: open
- Workers → Port 8202: dial is refused: closed
- portcheck → Host 192.0.2.1 (blocked): refused by the tool, no packet sent
Worked example
1. Write the command
Go into the module of lesson 8 and write main.go. It reads the flags, checks them, runs the scan and prints the result. A host that is not local, without -allow-remote, exits with 2 before any packet is sent. A bad flag exits with 2. A scan that Ctrl+C stopped exits with 1 and prints no table.
cd ~/krlab/go/portcheckThese names are new:
| Name | Job |
|---|---|
flag.Int, flag.Duration, flag.Bool | Define options of those types. Each gives a pointer (lesson 4), so the program reads *host. |
signal.NotifyContext | Gives a context that ends when the user presses Ctrl+C (the signal os.Interrupt). |
json.NewEncoder(os.Stdout).Encode | Writes JSON to the screen. |
any | A value of any type, so the map can hold a string and a list. |
%-6s, %-6d | Print the value in a field 6 characters wide, with the value on the left. This lines up the columns of the table. |
main.go
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"time"
"krlab/portcheck/scan"
)
func main() {
host := flag.String("host", "127.0.0.1", "host to check (yours, or with permission)")
from := flag.Int("from", 1, "first port")
to := flag.Int("to", 1024, "last port")
timeout := flag.Duration("timeout", 500*time.Millisecond, "wait for each port")
workers := flag.Int("workers", 100, "connections at one time")
asJSON := flag.Bool("json", false, "print JSON and not a table")
remote := flag.Bool("allow-remote", false, "check a host that is not this machine (only with written permission)")
flag.Parse()
if *from < 1 || *to > 65535 || *from > *to || *workers < 1 || *timeout <= 0 {
fmt.Fprintln(os.Stderr, "portcheck: need 1 <= from <= to <= 65535, workers >= 1, timeout > 0")
os.Exit(2)
}
if !*remote && !scan.Local(*host) {
fmt.Fprintln(os.Stderr, "portcheck: refused, the host is not local. Use -allow-remote only with written permission.")
os.Exit(2)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
open, err := scan.Scan(ctx, *host, *from, *to, *workers, *timeout)
if err != nil {
fmt.Fprintln(os.Stderr, "portcheck: stopped early:", err)
os.Exit(1)
}
if *asJSON {
if open == nil {
open = []int{}
}
json.NewEncoder(os.Stdout).Encode(map[string]any{"host": *host, "open": open})
return
}
fmt.Printf("%-6s %s\n", "PORT", "STATE")
for _, p := range open {
fmt.Printf("%-6d open\n", p)
}
fmt.Printf("%d open of %d checked on %s\n", len(open), *to-*from+1, *host)
}2. Run the tool against a local server
In a second terminal, start the server from lesson 5 (cd ~/krlab/go/web and go run ./server). It listens on 127.0.0.1:8201. In the first terminal, build the tool and check eleven ports around it. If your output has more lines than the one shown, another program uses a port in that range.
go build -o portcheck .
./portcheck -from 8200 -to 8210PORT STATE
8201 open
1 open of 11 checked on 127.0.0.1Ask for JSON, which a script can read. Then give bad input, and a host that is not local (192.0.2.1 is an address that is reserved for examples). Read the exit codes.
./portcheck -from 8200 -to 8210 -json
./portcheck -from 8000 -to 80; echo "exit=$?"
./portcheck -host 192.0.2.1 -from 1 -to 5; echo "exit=$?"{"host":"127.0.0.1","open":[8201]}
portcheck: need 1 <= from <= to <= 65535, workers >= 1, timeout > 0
exit=2
portcheck: refused, the host is not local. Use -allow-remote only with written permission.
exit=2Stop the server with Ctrl+C.
3. Build the one file
CGO_ENABLED=0 turns off the use of C code (cgo). -trimpath and -ldflags="-s -w" make the file smaller and remove local paths (see lesson 1). CGO_ENABLED=0 matters: a program that uses net links to the C library by default, and is then not static.
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o portcheck .
ls -l portcheck
file portcheck-rwxrwxr-x 1 you you 3199136 Nov 21 08:49 portcheck
portcheck: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, ...Copy this file to another Linux amd64 machine of yours, and it runs.
Your turn
Teach portcheck to compare what it finds with what should be there. There are no steps here: use what the lesson showed.
First make a helper that opens test listeners. It is the input of the task: it listens on 127.0.0.1 only, for the ports that you name, until you press Ctrl+C. It uses signal.NotifyContext as the lesson did: <-ctx.Done() waits until Ctrl+C, so the program stays alive and the listeners stay open. Write listeners/main.go.
portcheck/listeners/main.go
// Command listeners opens test listeners on 127.0.0.1 and waits for Ctrl+C.
package main
import (
"context"
"fmt"
"net"
"os"
"os/signal"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
for _, port := range os.Args[1:] {
l, err := net.Listen("tcp", "127.0.0.1:"+port)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
defer l.Close()
fmt.Println("listening on", l.Addr())
}
<-ctx.Done()
}Build it with go build -o listeners-bin ./listeners, and start it in a second terminal with ./listeners-bin 8252 8254 8256. Nothing else on your machine may use the ports 8250 to 8260.
Now add the flag -expect to portcheck: a list of ports that should be open, separated by commas, such as 8252,8254. (strings.Split(s, ",") cuts a string at every comma, strconv.Atoi reads each part, and slices.Contains asks if a slice holds a port.) When it is given, the tool prints these lines after the table, and then exits:
missing PORTfor each expected port that is not open, in the order of the list.unexpected PORTfor each open port that is not expected, from the lowest port.inventory matcheswhen there is no difference, and exit code 0.- Exit code 3 when there is a difference.
- A value that is not a number gives a message and exit code 2.
Run ./portcheck -from 8250 -to 8260 -expect 8252,8254,8258, and then the same with -expect 8252,8254,8256. Stop the listeners with Ctrl+C when you are done.
Check yourself
Why does a scan stopped by Ctrl+C print no table?
A partial list that looks complete would mislead. The command prints the reason on the error stream and exits with 1.
The `-expect` run exits with 3 when there is a difference, and not with 1. Why?
Exit code 1 means that the tool failed, for example a stopped scan. Code 3 means that the tool worked and found a difference. A script that calls the tool needs to tell the two apart: the first one is a fault to repair, the second one is a finding to review.
Why does the build set `CGO_ENABLED=0`?
A program that uses the package net links to the C library of the machine by default, and then it is not static. With cgo off, Go uses its own code for names and connections, and the file runs on any Linux machine of the same kind.
Field notes
- A port check of your own systems is the start of an asset inventory: compare the result with the list of what should listen, and treat each difference as a finding. NIST SP 800-53 has a control for the inventory of system components (CM-8).
- Hashing files and checking certificates are common next tools. The standard library has
crypto/sha256andcrypto/tls. The ideas behind them are in the courses Networking hands-on (TLS) and Python for security work (hashing). - Keep the dependencies at zero, as here. Put a version into the binary with
-ldflags "-X main.version=..."so every report names the build that made it.