Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / Go for security tools

Go for security tools cheat sheet

Run and build

TaskCode
Check the versiongo version
Start a modulego mod init krlab/hello
Run the programgo run . a b
Build a binarygo build -o hello .
Cross-build for WindowsGOOS=windows GOARCH=arm64 go build -o hello.exe .
List unformatted filesgofmt -l .
Build a small static releaseCGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o portcheck .
Show modules inside a binarygo version -m hello
Read the documentation of a functiongo doc strings.Cut
List the names of a packagego doc -short strings

Types and collections

TaskCode
Declare with a typevar host string = "127.0.0.1"
Declare and inferport := 8080
Append to a sliceports = append(ports, 8080)
Copy a slicecopy(c, a)
Test a map keyname, ok := names[8080]
Remove a map keydelete(names, 80)
Sort a slice by a rulesort.Slice(list, func(i, j int) bool { return list[i].Port > list[j].Port })
Count characterslen([]rune(word))
Print a struct with field namesfmt.Printf("%+v\n", f)

Functions, errors and packages

TaskCode
Split at the first colonhost, port, found := strings.Cut(t, ":")
Turn text into a numbern, err := strconv.Atoi(s)
Wrap an errorfmt.Errorf("parse port %q: %w", s, err)
Test for a known errorerrors.Is(err, portspec.ErrRange)
Close a file on exitdefer f.Close()
Give a type a methodfunc (f Finding) String() string { ... }
Name what a method must havetype Checker interface { Check(host string) string }
var ErrRange = errors.New("port out of range")

func Parse(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, fmt.Errorf("parse port %q: %w", s, err)
	}
	return n, nil
}

Files, JSON and flags

TaskCode
Read linessc := bufio.NewScanner(f), sc.Scan()
Check a scan errorsc.Err()
Write JSONjson.MarshalIndent(list, "", " ")
Read JSONjson.Unmarshal([]byte(text), &f)
Take an address, and write through itp := &x, *p = 6
Write a private fileos.WriteFile(out, append(data, '\n'), 0o600)
Define a flagin := flag.String("in", "hosts.txt", "input file")
Parse flagsflag.Parse()
Exit with a codeos.Exit(2)

HTTP client and server

TaskCode
Make a client with a timeout&http.Client{Timeout: 3 * time.Second}
Build a request with a contexthttp.NewRequestWithContext(ctx, http.MethodGet, url, nil)
Limit the body to 1 MBio.LimitReader(resp.Body, 1<<20)
Add a deadlinectx, cancel := context.WithTimeout(context.Background(), time.Second)
Route one methodmux.HandleFunc("GET /health", handler)
Bind a test server to loopbackAddr: "127.0.0.1:8201"
Split a URLu, err := url.Parse(raw), u.Hostname()
Do not follow a redirectCheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }

Concurrency

TaskCode
Start a goroutinego f()
Wait for all goroutineswg.Add(1), defer wg.Done(), wg.Wait()
Protect a shared countermu.Lock(), count++, mu.Unlock()
Find a data racego run -race .
Tell workers no more jobs comeclose(jobCh)

Tests and fuzzing

TaskCode
Run all testsgo test ./...
Skip the test cachego test -count=1 ./...
Check for suspect codego vet ./...
Test with the race detectorgo test -race ./...
Run a fuzz testgo test -fuzz=FuzzParse -fuzztime=5s ./portspec
Show each test and its resultgo test -race -v ./scan
Open a free test portnet.Listen("tcp", "127.0.0.1:0")
Start a test serversrv := httptest.NewServer(handler), defer srv.Close(), srv.URL
Get a folder for a test filedir := t.TempDir()
tests := []struct {
	in   string
	want int
}{
	{"80", 80},
	{"443", 443},
}
for _, tc := range tests {
	t.Run(tc.in, func(t *testing.T) {
		got, err := Parse(tc.in)
		if err != nil || got != tc.want {
			t.Errorf("Parse(%q) = %d, %v; want %d", tc.in, got, err, tc.want)
		}
	})
}

Network tools

TaskCode
Define a number, a time and a switchflag.Int(...), flag.Duration(...), flag.Bool(...)
Stop on Ctrl+Cctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
Open a connection that obeys a contextconn, err := d.DialContext(ctx, "tcp", addr)
Join a host and a portnet.JoinHostPort(host, strconv.Itoa(p))
Run the port checker./portcheck -from 1 -to 1024 -json

Exit codes

CodeMeaning
0Success.
1A failure while running (a file or a network error).
2Wrong use of the command line, or a refused target.
3The tool ran, and found a difference or a down endpoint.

Safety habits