Go

Go (or Golang) is an open-source programming language designed for efficiency and scalability. Its simplicity and strong performance make it ideal for security tasks, including scripting and penetration testing.

Setting Up the Go Environment

  1. Install Go:

    • Download from the official website.

    • Follow installation instructions for your operating system.

  2. Verify Installation:

    go version
  3. Setting Up GOPATH:

    • GOPATH is the workspace for Go projects.

    export GOPATH=$HOME/go
    export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

Basic Syntax

  1. Hello World:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello, World!")
    }
  2. Variables:

    var a string = "Initial"
    b := 2 // Short variable declaration
  3. Loops:

    goCopy codefor i := 0; i < 10; i++ {
        fmt.Println(i)
    }
  4. Conditional Statements:

    if x > 10 {
        fmt.Println("x is greater than 10")
    } else {
        fmt.Println("x is less than or equal to 10")
    }

Handling HTTP Requests

  1. GET Request:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    func main() {
        resp, err := http.Get("http://example.com")
        if err != nil {
            fmt.Println(err)
            return
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(body))
    }
  2. POST Request:

    package main
    
    import (
        "bytes"
        "fmt"
        "net/http"
    )
    
    func main() {
        jsonData := []byte(`{"key":"value"}`)
        resp, err := http.Post("http://example.com", "application/json", bytes.NewBuffer(jsonData))
        if err != nil {
            fmt.Println(err)
            return
        }
        defer resp.Body.Close()
        fmt.Println("Response Status:", resp.Status)
    }

Parsing JSON

  1. Parsing JSON Response:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Response struct {
        Key string `json:"key"`
    }
    
    func main() {
        jsonStr := `{"key": "value"}`
        var res Response
        json.Unmarshal([]byte(jsonStr), &res)
        fmt.Println(res.Key)
    }
  2. Encoding JSON:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Payload struct {
        Key string `json:"key"`
    }
    
    func main() {
        data := Payload{Key: "value"}
        jsonData, _ := json.Marshal(data)
        fmt.Println(string(jsonData))
    }

Concurrency in Go

  1. Goroutines:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        go func() {
            fmt.Println("Hello from Goroutine")
        }()
        time.Sleep(time.Second) // Wait for Goroutine to finish
    }
  2. Channels:

    package main
    
    import "fmt"
    
    func main() {
        messages := make(chan string)
    
        go func() {
            messages <- "ping"
        }()
    
        msg := <-messages
        fmt.Println(msg)
    }

Writing Secure Code

  1. Input Validation:

    • Always validate user input to avoid injection attacks.

  2. Using Context for Timeouts:

    package main
    
    import (
        "context"
        "fmt"
        "net/http"
        "time"
    )
    
    func main() {
        ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
        defer cancel()
    
        req, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            fmt.Println("Request failed:", err)
            return
        }
        defer resp.Body.Close()
        fmt.Println("Response Status:", resp.Status)
    }

File Handling

  1. Reading Files:

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func main() {
        content, err := ioutil.ReadFile("file.txt")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(content))
    }
  2. Writing Files:

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func main() {
        content := []byte("Hello, World!")
        err := ioutil.WriteFile("file.txt", content, 0644)
        if err != nil {
            fmt.Println(err)
        }
    }

Networking

  1. Simple TCP Client:

    package main
    
    import (
        "bufio"
        "fmt"
        "net"
    )
    
    func main() {
        conn, err := net.Dial("tcp", "example.com:80")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
        status, err := bufio.NewReader(conn).ReadString('\n')
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(status)
    }
  2. Simple TCP Server:

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        ln, err := net.Listen("tcp", ":8080")
        if err != nil {
            fmt.Println(err)
            return
        }
        for {
            conn, err := ln.Accept()
            if err != nil {
                fmt.Println(err)
                continue
            }
            go handleConnection(conn)
        }
    }
    
    func handleConnection(conn net.Conn) {
        fmt.Fprintln(conn, "Hello, World!")
        conn.Close()
    }

Using Go for Penetration Testing

  1. Port Scanner:

    package main
    
    import (
        "fmt"
        "net"
        "time"
    )
    
    func main() {
        for i := 1; i <= 1024; i++ {
            address := fmt.Sprintf("scanme.nmap.org:%d", i)
            conn, err := net.DialTimeout("tcp", address, time.Second)
            if err != nil {
                continue
            }
            conn.Close()
            fmt.Printf("Port %d is open\n", i)
        }
    }
  2. HTTP Basic Authentication Brute Force:

    package main
    
    import (
        "fmt"
        "net/http"
        "strings"
    )
    
    func main() {
        url := "http://example.com"
        username := "admin"
        passwords := []string{"password1", "password2", "password3"}
    
        for _, password := range passwords {
            client := &http.Client{}
            req, _ := http.NewRequest("GET", url, nil)
            req.SetBasicAuth(username, password)
            resp, err := client.Do(req)
            if err != nil {
                fmt.Println("Request failed:", err)
                continue
            }
            if resp.StatusCode == 200 {
                fmt.Printf("Found valid credentials: %s:%s\n", username, password)
                break
            }
        }
    }

Libraries and Tools

  1. Gorilla Web Toolkit:

  2. GoPacket:

    • Library for packet processing with Go.

  3. Zerolog:

    • Fast and efficient structured logging library.

Last updated

Was this helpful?