Skip to content

Instantly share code, notes, and snippets.

@MrGossett
Last active May 11, 2022 15:57
Show Gist options
  • Save MrGossett/750eb25a2a3646d6d1b9edc0a3c21bdf to your computer and use it in GitHub Desktop.
Save MrGossett/750eb25a2a3646d6d1b9edc0a3c21bdf to your computer and use it in GitHub Desktop.
Patching a binary in Go
package main
import (
"bytes"
"os"
)
func main() {
// find the file "program" and read it all into memory as a byte slice
bs, err := os.ReadFile("program")
if err != nil {
panic(err)
}
// find the index of the first occurence of "Hello, world!"
i := bytes.Index(bs, []byte("Hello, world!"))
if i == -1 {
// an index of -1 means that the string was not found
println("string not found in binary")
os.Exit(1)
}
// overwrite the bytes starting at index i with new values
copy(bs[i:], []byte("Hello, there!"))
// write the updated byte slice out to a file called "patched"
if err := os.WriteFile("patched", bs, 0o755); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment