Skip to content

Golang Unsafe Block

What does this mean ?

Using the unsafe package in Go gives you low-level memory management and many of the strength of the C language but also gives flexibility to the attacker of your application. The pointer arithmetic is one of the examples from the unsafe package which can be used for data leak, memory corruption or even execution of attackers own script.Also, you should keep in mind that the "unsafe" package is not protected by Go 1 compatibility guidelines.

What can happen ?

Package unsafe contains operations that step around the type safety of Go programs.Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.


Use of unsafe calls should be audited to prevent DOS attacks or craches during the run time.

Sample Code

Vulnerable :

package main

import (

func main() {
    harmlessData := [8]byte{'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'}
    // might be e.g. private key data
    secret := [17]byte{'l', '3', '3', 't', '-', 'h', '4', 'x', 'x', '0', 'r', '-', 'w', '1', 'n', 's', '!'}

    // read from memory behind buffer
    var leakingInformation = (*[8+17]byte)(unsafe.Pointer(&harmlessData[0]))


    // avoid optimization of variable
    if secret[0] == 42 {
        fmt.Println("do not optimize secret")