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

Lesson 02 · 35 minutes

Model hosts, ports and findings in Go

After this lesson you can
  • Declare variables and name the basic types
  • Hold lists and lookups in slices and maps
  • Group the fields of a finding in a struct
Lab files of this lesson (5)

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

A scan has found five services on your lab network. The lead wants a short triage list: how many findings are high, medium and low, and which hosts to review first. You will hold the findings in a Go program, count them and print the hosts that need a review. First you learn the few data types that this takes.

Recall

Which file holds the name of a Go module, and which command creates it?

go.mod holds the module name and the Go version. go mod init <name> creates it.

Why does `go build` give a file that runs on a server without Go?

The binary is static: it holds your code and the Go runtime, so it needs no other library.

The idea

Go checks every type when it compiles. A value of type int is not a string, and the compiler does not convert one to the other for you.

TypeHoldsZero value
inta whole number0
stringtext, as bytes of UTF-8""
booltrue or falsefalse
[]T (slice)an ordered list of T that can grownil
map[K]Va lookup from keys of type K to values of type Vnil
structa fixed set of named fieldseach field has its own zero

If you know Python, this table maps the ideas. Later lessons teach the Go side of each row.

In PythonIn Go
lista slice, []T, with one type for all items
dicta map, map[K]V
Nonethe zero value of the type (0, "", nil)
try and excepta returned error and if err != nil (lesson 3)
finally and withdefer (lesson 3)
a thread, asyncioa goroutine and a channel (lesson 6)

A zero value is what a variable holds when you give it nothing. In Go a variable is never undefined. A rune is one Unicode character, stored as a number of type rune (an int32).

One value of a struct type
Finding{the type and the start of one valueHost: "10.0.0.7"textPort: 3306a whole numberService: "mysql"textSeverity: "high"text}the end of the struct valueFinding{the type and the start of one valueHost: "10.0.0.7"textPort: 3306a whole numberService: "mysql"textSeverity: "high"text}the end of the struct value

Worked example

Work in ~/krlab/go/types. For each step, replace the whole of main.go.

1. Declare variables

mkdir, cd and go mod init work as in lesson 1. Then write main.go. var declares a variable with a type. := declares and infers the type. const fixes a value for good.

mkdir -p ~/krlab/go/types
cd ~/krlab/go/types
go mod init krlab/types

go mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:

go.mod

module krlab/types

go 1.22

main.go

package main

import "fmt"

func main() {
	var host string = "127.0.0.1"
	port := 8080
	const proto = "tcp"
	fmt.Printf("%s %s/%d\n", host, proto, port)
	fmt.Printf("%T %T %T\n", host, port, port > 1023)
	var n int
	var s string
	var open bool
	fmt.Printf("%d %q %t\n", n, s, open)
}
go run .
127.0.0.1 tcp/8080
string int bool
0 "" false

fmt.Printf prints with a pattern: %s, %d, %t print a string, a number and a boolean. %q prints a string in quotes, so an empty string is visible. %T prints the type. The last line shows the zero values.

2. Keep ports in a slice

A slice is a list. append adds to it and returns the new slice, so you must keep the result. for i, p := range ports walks the slice and gives the index i and the value p of each item. A slice also has a window:

A window on the slice ports
portsthe slice [22 80 443 8080][1start: index 1 is the first item (80):3]end: index 3 is not in the windowportsthe slice [22 80 443 8080][1start: index 1 is the first item (80):3]end: index 3 is not in the window

main.go

package main

import "fmt"

func main() {
	ports := []int{22, 80, 443}
	ports = append(ports, 8080)
	fmt.Println(ports, len(ports), ports[1:3])
	for i, p := range ports {
		fmt.Println(i, p)
	}
	var none []int
	fmt.Println(len(none), none == nil)
}
[22 80 443 8080] 4 [80 443]
0 22
1 80
2 443
3 8080
0 true

An empty nil slice is safe: you can append to it.

3. Look up a service name in a map

A map finds a value by its key. The form name, ok := m[key] tells you if the key was there.

A lookup that tells if the key exists
ifstart of a testname, ok :=the value, and ok: true if foundnames[8080]look up key 8080 in the map; ok {the part before ; runs firstifstart of a testname, ok :=the value, and ok: true if foundnames[8080]look up key 8080 in the map; ok {the part before ; runs first

The variables live only inside the if. A missing key gives the zero value, so without ok you cannot tell "missing" from "empty". The same rule lets you count: m[key]++ starts from the zero value 0 for a new key. The order of a map is random on purpose, so sort the keys when you print. delete(m, key) removes a key from a map. sort.Ints (from the package sort) sorts a slice of numbers in place. sort.Strings does the same for text.

main.go

package main

import (
	"fmt"
	"sort"
)

func main() {
	names := map[int]string{22: "ssh", 80: "http", 443: "https"}
	names[3306] = "mysql"
	seen := map[string]int{}
	for _, n := range []string{"ssh", "http", "ssh"} {
		seen[n]++
	}
	fmt.Println(seen["ssh"], seen["ftp"])
	if name, ok := names[8080]; ok {
		fmt.Println("known:", name)
	} else {
		fmt.Println("8080 is not in the map")
	}
	fmt.Printf("%q\n", names[9999])
	delete(names, 80)
	var keys []int
	for p := range names {
		keys = append(keys, p)
	}
	sort.Ints(keys)
	for _, p := range keys {
		fmt.Println(p, names[p])
	}
}
2 0
8080 is not in the map
""
22 ssh
443 https
3306 mysql

4. Describe a finding with a struct

A struct groups named fields into one type. The program below fills one by field name, builds a list, sorts it and copies a struct. These are new:

NameJob
%v and %+v%v prints the values. %+v adds the field names.
Finding{Host: "10.0.0.5"}Fills a struct by field name, as f below. The second item of list fills it by position, in the order of the fields. Names are clearer.
sort.Slice(s, less)Sorts s by a rule that you give as a function without a name. The rule asks "does item i come before item j?". Here the highest port comes first.
g := fCopies the struct, so a change to g does not touch f.

main.go

package main

import (
	"fmt"
	"sort"
)

type Finding struct {
	Host     string
	Port     int
	Service  string
	Severity string
}

func main() {
	f := Finding{Host: "10.0.0.5", Port: 22, Service: "ssh", Severity: "low"}
	fmt.Printf("%v\n%+v\n", f, f)
	list := []Finding{f, {"10.0.0.7", 3306, "mysql", "high"}}
	for _, x := range list {
		if x.Severity == "high" {
			fmt.Println("review", x.Host, x.Port)
		}
	}
	sort.Slice(list, func(i, j int) bool { return list[i].Port > list[j].Port })
	fmt.Println(list[0].Host)
	g := f
	g.Port = 2222
	fmt.Println(f.Port, g.Port)
}
{10.0.0.5 22 ssh low}
{Host:10.0.0.5 Port:22 Service:ssh Severity:low}
review 10.0.0.7 3306
10.0.0.7
22 2222

A slice of structs is the shape of most reports. A name with a capital letter (Host) is visible outside the package. Lesson 4 needs this for JSON.

5. Two traps to know

These two are traps, not tools. First, a string holds bytes. The letter ï takes two bytes in UTF-8. len counts bytes. Converting to []rune splits the text into characters. for ... range over a string walks it one rune at a time and gives the byte position. string(r) turns a rune back into text. Second, an assignment of a slice copies the window, not the data, so two names can change the same numbers. make([]int, n) creates a slice of n zeros, and copy fills a real second list.

main.go

package main

import "fmt"

func main() {
	word := "naïve"
	fmt.Println(len(word), len([]rune(word)))
	for i, r := range "né" {
		fmt.Println(i, string(r), r)
	}

	a := []int{1, 2, 3}
	b := a
	b[0] = 99
	fmt.Println(a, b)
	c := make([]int, len(a))
	copy(c, a)
	c[0] = 1
	fmt.Println(a, c)
}
6 5
0 n 110
1 é 233
[99 2 3] [99 2 3]
[99 2 3] [1 2 3]

If you cut a string at a fixed position, you can cut a character in half. Changing b changed a.

Your turn

Do the triage. There are no steps here: use what the worked example showed.

In ~/krlab/go/triage, write a program with these five findings (host, port, service, severity) in a slice of structs:

HostPortServiceSeverity
10.0.0.522sshlow
10.0.0.73306mysqlhigh
10.0.0.880httpmedium
10.0.0.96379redishigh
10.0.0.10443httpslow

The program must do two things:

  1. Count the findings for each severity in a map, and print one line for each severity as severity count, in alphabetical order of the severity.
  2. Then print review host port for each finding with severity high, in the order of the table.

Check yourself

What does `var m map[string]int` followed by `m["x"] = 1` do?

The program stops with panic: assignment to entry in nil map. A map variable without a value is nil. You can read from a nil map, but you cannot write. Make it first: m := map[string]int{} or make(map[string]int).

`len("naïve")` prints 6. Why not 5?

len counts bytes, and ï is two bytes in UTF-8. Use len([]rune(s)) to count characters.

Why sort the keys before you print a map in a report?

Go gives the order of a map at random on purpose. A report with a changing order is hard to compare between two runs. Sorted output is stable.

Field notes

  • Ports are numbers from 0 to 65535. int is too wide and uint16 fits exactly. For a tool the plain int is simpler, but check the range at the edge, where the user gives you the value, and reject 0 and 70000.
  • Do not compare IP addresses as strings. ::1 and 0:0:0:0:0:0:0:1 are one address with two spellings. Parse both with net/netip and compare the parsed values.
  • A map is not safe for use by two goroutines when one of them writes. The program may crash with fatal error: concurrent map writes. Lesson 6 shows the lock (sync.Mutex) on a counter. The same lock protects a map.
  • Use named types for ideas that differ: type Severity string with constants for Low, Medium and High. The compiler then stops you from putting a free-form word where a level belongs.