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
.
Last active
December 12, 2024 19:57
-
-
Save ryankennedy/3e1e4aacd104fb94995354936106c847 to your computer and use it in GitHub Desktop.
How to macOS sandbox a Go application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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