Skip to content

Instantly share code, notes, and snippets.

@ryankennedy
Last active December 12, 2024 19:57
Show Gist options
  • Save ryankennedy/3e1e4aacd104fb94995354936106c847 to your computer and use it in GitHub Desktop.
Save ryankennedy/3e1e4aacd104fb94995354936106c847 to your computer and use it in GitHub Desktop.
How to macOS sandbox a Go application

Sandboxing a Go program in macOS

This sample Go file shows how to use sandbox_init on macOS (now deprecated, but it still works) to prevent a Go application from accessing the network beyond localhost.

package main
/*
#include <stdlib.h>
#include <sandbox.h>
*/
import "C"
import (
"log"
"os"
"os/signal"
"unsafe"
)
func main() {
Sandbox(`
(version 1)
(allow default)
(deny network-outbound)
(allow network-outbound (remote ip "localhost:*"))
`)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
log.Println("main is now sandboxed, ctrl+c to quit")
<-c
}
func Sandbox(policy string) {
cPolicy := C.CString(policy)
defer C.free(unsafe.Pointer(cPolicy))
var errorBuffer *C.char
defer C.free(unsafe.Pointer(errorBuffer))
if result := C.sandbox_init(cPolicy, 0, &errorBuffer); result != 0 {
log.Fatalf("Failed to initialize sandbox: return=%d; error=%s", result, C.GoString(errorBuffer))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment