SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · GO · 44 OF 229

Go for Security Tools: Why Scanners Use Go

Why Trivy, Nuclei, Gitleaks, Vault and most new security tools are written in Go: one static binary with no runtime to install, easy cross-compiling, cheap concurrency with goroutines, and memory safety. Shown by rebuilding the port checker in about 40 lines: a 3.3 MB binary that checked 10,000 ports in 115 ms, ten times faster than the Python version.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • One static binary
  • cross-compiles anywhere
  • goroutines: 10,000 ports in 115 ms
  • memory safe

Notes

Reason 1 · One file

The first reason is deployment. A Go program compiles to one executable file that contains everything it needs. Ours is three point three megabytes. There is no interpreter to install on the target, no package manager, no version conflicts. During an incident you copy one file to a server and run it. Compare that with a Python tool that needs the right Python version and a dozen packages, on a production machine where you would rather install nothing.

build once, copy anywhere
$ go build -o portcheck .
$ ls -l portcheck
3313650 bytes        (3.3 MB)

# no interpreter, no pip install,
# no virtualenv, no version
# mismatch on the target

# fully static:
$ CGO_ENABLED=0 go build ...

Reason 2 · Any platform

The second reason is reach. Set two environment variables and the same source builds for another operating system and processor. From our Linux machine we built a Windows executable, three point four megabytes, with one command, and the same works for Mac and for ARM servers. A security team has to cover laptops, servers and containers of every kind. With Go, one codebase and one build step produce a tool for all of them.

cross-compile
$ GOOS=windows GOARCH=amd64 \
    go build -o portcheck.exe .
$ ls -l portcheck.exe
3408384 bytes        (3.4 MB)

$ GOOS=linux GOARCH=arm64 go build
$ GOOS=darwin GOARCH=arm64 go build

# built on Linux, runs on
# Windows, macOS, ARM servers

The code · part 1

Here is the program. The flag package from the standard library defines the command-line options, with help text included. Then four pieces for concurrency. A slice to collect open ports, and a mutex to protect it, because many tasks will append at once. A wait group, to know when every task has finished. And a channel with room for two hundred items, used as a counter so that no more than two hundred connections are open at the same time.

main.go, setup
host := flag.String("host",
    "127.0.0.1", "host to check")
last := flag.Int("ports", 1024, "1..N")
timeout := flag.Duration("timeout",
    500*time.Millisecond, "per port")
flag.Parse()

var mu sync.Mutex
var open []int
var wg sync.WaitGroup
sem := make(chan struct{}, 200)

The code · part 2

The loop starts one task per port with the keyword go. That creates a goroutine, a task so light that tens of thousands are normal. Each one tries to connect with a timeout, exactly like the Python version. If it fails, the task ends. If it succeeds, it closes the connection, locks the mutex, records the port and unlocks. The two defer lines guarantee that the task always reports that it is done and always frees its slot, even on an error.

main.go, the scan
for port := 1; port <= *last; port++ {
  wg.Add(1); sem <- struct{}{}
  go func(p int) {
    defer wg.Done()
    defer func() { <-sem }()
    c, err := net.DialTimeout("tcp",
        addr(*host, p), *timeout)
    if err != nil { return }
    c.Close(); mu.Lock()
    open = append(open, p); mu.Unlock()
  }(port) }

Reason 3 · Speed

The third reason is speed. We ran it against the local machine with a test web server on port eight thousand and eighty. Ten thousand ports in one hundred and fifteen milliseconds. The Python version, on the same machine, took one point one five seconds, ten times longer. For one scan nobody cares. For a tool that checks every image in a registry, or every file in a thousand repositories on every commit, a factor of ten decides whether developers tolerate it.

our run
$ ./portcheck -ports 10000
open: [2024 8080] (10000 ports
  in 115ms)

# Python version, same machine:
# 10000 ports in 1.15 s

# 8080: a test web server we
# started; 2024: one we had not

Reason 4 · Safety

The fourth reason is safety, which matters for tools that parse untrusted input all day. Go is memory safe: bounds are checked and memory is managed, so the buffer overflows from Part one do not happen in normal code. Its standard library includes TLS, HTTP, cryptography and JSON, so tools need few third-party packages. Checks for common mistakes and for race conditions are built in, and a tool called govulncheck reports vulnerable dependencies that your code actually calls.

Memory safe, strong library
  • bounds-checked and garbage- collected: no buffer overflows or use-after-free in normal code
  • standard library includes TLS, HTTP, crypto, JSON
  • so: few dependencies
  • go vet and the race detector are built in govulncheck: finds vulnerable dependencies you really call

What this means for you

This is why the tools in Part nine are so easy to adopt. Trivy, Grype and Syft for images and dependencies. Gitleaks and TruffleHog for secrets. Nuclei, ffuf and Subfinder for testing. Cosign for signing. OPA for policy. Each is one binary that you download and run, and it behaves the same on your laptop and in a pipeline. When you evaluate a new security tool, how hard is it to run everywhere is one of the first questions, and Go tools tend to answer it well.

Go tools in this track
  • Trivy, Grype, Syft: image and dependency scanning
  • Gitleaks, TruffleHog: secrets
  • Nuclei, ffuf, Subfinder, Amass: testing and recon
  • Cosign: signing
  • OPA, Conftest: policy
  • Vault, Terraform, Kubernetes
  • each: one binary, runs the same on a laptop and in CI

When to choose what

Go does not replace the other two languages in this part. Bash is for glue and one-liners. Python is for logic, APIs and data, and it is the fastest to write and change, which is why most automation stays in Python. Go is for a tool that many people or machines will run, where speed, concurrency and easy installation matter. Rust aims at similar goals with more control and a steeper learning curve. A working security engineer reads all three and writes at least two.

Pick the right tool
  • Bash: glue, one-liners, a few commands in a row
  • Python: logic, APIs, data, quick to write and change
  • Go: a tool many people or machines will run, where speed, concurrency and easy install matter
  • Rust: similar goals, more control, steeper to learn

Reading Go

You will read far more Go than you write, usually to understand what a tool really does, or to add a small feature. Five things unlock most of it. Colon equals declares a variable. Errors are ordinary values, checked with if err not equals nil after nearly every call. The keyword go starts a concurrent task, and channels pass values between tasks. Defer runs something when the function exits. And go dot mod lists the dependencies, which is the first file to open when you assess a tool.

Enough to read a Go tool
  • x := value declare and assign
  • if err != nil { return err } errors are values, checked after every call
  • go f() run concurrently
  • ch <- v ; v := <-ch channels
  • defer f() run at function exit, like finally
  • struct + methods, no classes
  • go.mod lists the dependencies

Common mistakes

Mistakes. Discarding errors, which hides the one failure you needed to see. Starting unlimited goroutines, so a scan opens a hundred thousand connections at once. Sharing data between tasks without a mutex; the race detector finds this for you. No timeouts on network calls. Downloading and running a security tool's binary without checking its signature or hash, which is its own supply chain risk. And rewriting in Go what twenty lines of Python already do well.

Avoid these
  • ignoring errors with _
  • unlimited goroutines: no bound on connections
  • shared data with no mutex (run tests with -race)
  • no timeouts on network calls
  • trusting a random binary: check signatures and hashes
  • rewriting in Go what a 20-line Python script does

Say it like this

In the interview: security tools are often written in Go because it compiles to a single static binary with no runtime to install, cross-compiles to any platform with two variables, and has cheap concurrency through goroutines, which suits scanning networks and files. It is memory safe, and its standard library covers TLS, HTTP and cryptography, so tools have few dependencies. The result is tooling that is fast and trivial to run on laptops, servers and in pipelines.

In the interview
  • "A single static binary with no runtime, trivial cross- compilation, cheap concurrency
  • with goroutines for network
  • and file work, memory safety, and a standard library with TLS, HTTP and crypto. That makes tools fast and easy to run on laptops, servers and in CI."

Interview questions

Q1Why are many security tools written in Go?

Go compiles to a single static binary with no runtime dependency, cross-compiles easily to any OS and architecture, offers lightweight concurrency through goroutines, is memory safe, and has a strong standard library for networking, TLS and cryptography, making tools fast and easy to distribute.

Q2What is a goroutine?

A lightweight concurrent task managed by the Go runtime rather than the operating system, started with the go keyword. Thousands or more can run at once, which suits I/O-heavy work such as scanning many hosts, ports or files.

Q3How do you limit concurrency in a Go program?

Commonly with a buffered channel used as a semaphore: a task sends into the channel before starting and receives from it when done, so at most the channel’s capacity run simultaneously. Worker pools and errgroup with a limit achieve the same.

Q4What does cross-compilation mean in Go?

Building an executable for a different operating system or CPU architecture than the one you are on, by setting GOOS and GOARCH (for example GOOS=windows GOARCH=amd64 go build), with no extra toolchain needed for pure Go code.

Q5Why does a single static binary matter for security tooling?

It can be copied to a server, container or CI runner and executed without installing an interpreter or packages, which is safer on production systems, simpler during incidents and more reproducible in pipelines.

Q6How does Go handle errors, and why does it matter?

Functions return errors as ordinary values that the caller must check (if err != nil). Ignoring them hides failures, so in security tools an unchecked error can turn a failed check into a false pass.

Q7When would you choose Python over Go for a security task?

For automation, glue and data work that changes often: API calls, parsing, one-off analysis. Python is quicker to write and modify; Go is preferable when the tool will be widely distributed or performance and concurrency matter.

Q8What should you check before running a downloaded security tool binary?

That it comes from the official source, that its checksum or signature (for example with Cosign) verifies, which version you are running, and ideally that it is pinned in your pipeline, since a tampered tool runs with your credentials.