|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + _ "embed" |
| 5 | + "fmt" |
| 6 | + "html/template" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +//go:embed main.c.tmpl |
| 13 | +var tmplS string |
| 14 | + |
| 15 | +// byteArray returns a string representation of a C byte array |
| 16 | +func byteArray(b []byte) string { |
| 17 | + var s strings.Builder |
| 18 | + fmt.Fprint(&s, "{ ") |
| 19 | +full: |
| 20 | + for i := 0; i < len(b); i += 16 { |
| 21 | + for j := 0; j < 16; j++ { |
| 22 | + if i+j >= len(b)-1 { |
| 23 | + fmt.Fprintf(&s, "0x%x", b[i+j]) |
| 24 | + break full |
| 25 | + } |
| 26 | + fmt.Fprintf(&s, "0x%x, ", b[i+j]) |
| 27 | + } |
| 28 | + fmt.Fprint(&s, "\n") |
| 29 | + } |
| 30 | + fmt.Fprint(&s, " }") |
| 31 | + return s.String() |
| 32 | +} |
| 33 | + |
| 34 | +func add(a int, b int) int { |
| 35 | + return a + b |
| 36 | +} |
| 37 | + |
| 38 | +type State struct { |
| 39 | + Shellcode []byte |
| 40 | + RWX bool |
| 41 | + Prepend bool |
| 42 | +} |
| 43 | + |
| 44 | +func generate(shellcode string, rwx bool, prepend bool, out string) error { |
| 45 | + tmpl := template.Must(template.New("output").Funcs(template.FuncMap{ |
| 46 | + "add": add, |
| 47 | + "byteArray": byteArray, |
| 48 | + }).Parse(tmplS)) |
| 49 | + |
| 50 | + shellcodeB, err := os.ReadFile(shellcode) |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("unable to open shellcode: %v", err) |
| 53 | + } |
| 54 | + |
| 55 | + state := State{ |
| 56 | + Shellcode: shellcodeB, |
| 57 | + RWX: rwx, |
| 58 | + Prepend: prepend, |
| 59 | + } |
| 60 | + |
| 61 | + output, err := os.CreateTemp("", "example-options-*.c") |
| 62 | + if err != nil { |
| 63 | + return fmt.Errorf("unable to open output file: %v", err) |
| 64 | + } |
| 65 | + defer os.Remove(output.Name()) |
| 66 | + |
| 67 | + if err = tmpl.Execute(output, &state); err != nil { |
| 68 | + return fmt.Errorf("unable to template output file: %v", err) |
| 69 | + } |
| 70 | + |
| 71 | + if out, err := exec.Command("gcc", output.Name(), "-o", out).CombinedOutput(); err != nil { |
| 72 | + return fmt.Errorf("unable to compile (%s): %v", out, err) |
| 73 | + } |
| 74 | + |
| 75 | + return nil |
| 76 | +} |
| 77 | + |
| 78 | +func main() { |
| 79 | + if len(os.Args) != 3 { |
| 80 | + fmt.Printf("usage: %v <shellcode_file> <output_file>", os.Args[0]) |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + if err := generate(os.Args[1], true, true, os.Args[2]); err != nil { |
| 85 | + fmt.Printf("failed to generate: %v", err) |
| 86 | + return |
| 87 | + } |
| 88 | +} |
0 commit comments