├── pwn.go ├── README.md ├── processes_test.go ├── .travis.yml ├── cmd └── scan │ └── scan.go ├── iface_test.go ├── pwn_test.go ├── net_test.go ├── io_test.go ├── io.go ├── iface.go ├── net.go ├── processes.go └── LICENSE /pwn.go: -------------------------------------------------------------------------------- 1 | // Package pwn implements tools for capture the flag compititions. 2 | package pwn 3 | 4 | // Bytes takes type interface{} and converts it to []byte, if it can't convert 5 | // to []byte it will panic 6 | func Bytes(t interface{}) (output []byte) { 7 | switch x := t.(type) { 8 | case string: 9 | output = []byte(x) 10 | case []byte: 11 | output = x 12 | case byte: 13 | output = append(output, x) 14 | case rune: 15 | output = []byte(string(x)) 16 | default: 17 | panic("failed to convert t to type []byte") 18 | } 19 | 20 | return output 21 | } 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **Abandoned** 2 | I don't really feel like working on this, feel free to fork/do whatever you want with it! i might end up making a utility library with some functions i like (readUntil) but for now i'm not working on this. 3 | 4 | 5 | # pwntools for go! 6 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/gopwn/pwn/blob/master/LICENSE) 7 | [![godoc](https://img.shields.io/badge/go-documentation-blue.svg)](https://godoc.org/github.com/gopwn/pwn) 8 | [![Go Report Card](https://goreportcard.com/badge/github.com/gopwn/pwn)](https://goreportcard.com/report/github.com/gopwn/pwn) 9 | [![Coverage Status](https://coveralls.io/repos/github/gopwn/pwn/badge.svg?branch=master)](https://coveralls.io/github/gopwn/pwn?branch=master) 10 | [![Build status](https://travis-ci.org/gopwn/pwn.svg?branch=master)](https://travis-ci.org/gopwn/pwn) 11 | -------------------------------------------------------------------------------- /processes_test.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestEcho(t *testing.T) { 10 | t.Parallel() 11 | expected := []byte("Hello, world!") 12 | p, err := Spawn("echo", "Hello, world!") 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | 17 | output, err := p.ReadLine(time.Second) 18 | if err != nil { 19 | t.Fatal(err) 20 | } 21 | 22 | // now make sure we got what we expected 23 | if !bytes.Equal(output, expected) { 24 | t.Fatalf("%q != %q", output, expected) 25 | } 26 | } 27 | 28 | func TestSh(t *testing.T) { 29 | expected := []byte("Hello, world") 30 | p, err := Spawn("sh") 31 | if err != nil { 32 | t.Fatal(err) 33 | } 34 | 35 | err = p.WriteLine("echo Hello, world") 36 | if err != nil { 37 | t.Fatal(err) 38 | } 39 | 40 | out, err := p.ReadLine(time.Second) 41 | if err != nil { 42 | t.Fatal(err) 43 | } 44 | 45 | // now check that we got the expected output 46 | if !bytes.Equal(out, expected) { 47 | t.Fatalf("%q != %q", out, expected) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | before_install: 4 | - go get github.com/mattn/goveralls 5 | - go get golang.org/x/tools/cmd/cover 6 | - go get github.com/mattn/goveralls 7 | - go get github.com/golang/net/nettest 8 | 9 | script: 10 | go test -v -covermode=count -coverprofile=coverage.out 11 | $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN 12 | 13 | env: 14 | global: 15 | secure: PkV4Hq8ydQNGiRGE8Jv7NflS6chy5/pmkHwMsw/56qrVULTuUJRNsaWfxaUFnQT7teTXskkDhyuV9/xqC5RuS4pfYBn+h3ZBkRlclriqUuH62eumPuVajb3aQUObpNc/MAjpNoXCaDqFptfVMwEBco58SS1h6Tq7LCB+JOmrKq17vihemv2OD/dt4A6Yz5RfqbIUsthcftKxpCQAafAWlYxXTKuDV3a6sK0DQBMIVFtLfxhFHiivrRw4wR+8UlvaNBxui7HVQAdPGfHEPR7YvY5j0sRYxOBD4l4XNE8rcAgAPIuHqzw/C5deAvMnh3RGMPDc3yNzXRRg29s3dzHFXUk3bEGZCMSjebfzAbKp0JqL2NwbDHBbohmyAj9eTSqcu6ICEQPStGaItTWPnRyGzKfoMtDpvfkJN+U3N4XG7xEom0b12Ui32DBBhboXu9i+LaL4YCe9au4fiH8GmaD2HU7uT7TZ3zuL9wYTzkW/6Pko12lvF5Z9s/upstbAkslfYdUbIcnJ08RecRsDTqG5R02qWfqeADggL63RdvjjZ1ZB3QH+lSpOMJkzPQT+58maE6nlms1BByeNR20nWrKySCD3UX0fxyxhjRJiWFLRJ8qSKhvkLshnn4u6Pj4i37FhcMyUEDaR41m04hFqjopZtB3GCSbIuor+yeTLuyRlMTQ= 16 | script: 17 | - $HOME/gopath/bin/goveralls -v -service=travis-ci 18 | -------------------------------------------------------------------------------- /cmd/scan/scan.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "net" 5 | "strconv" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | // 100 milliseconds 11 | const SLEEP_TIME = time.Millisecond * 100 12 | 13 | // this is the maximum THEORETICAL number of ports, event though 14 | const MAX_PORTS = 16777214 15 | 16 | var wg1 sync.WaitGroup 17 | 18 | func PortScan(host string, portFrom int, portTo int, threadCount int) []int { 19 | threadsPer := (portTo - portFrom) / threadCount 20 | curPortsScanning := 0 21 | var openPorts []int 22 | openPorts = make([]int, 0, MAX_PORTS) 23 | for x := 0; x < threadsPer; x++ { 24 | go scanRange(host, curPortsScanning, curPortsScanning+threadsPer, &openPorts) 25 | curPortsScanning += threadsPer 26 | } 27 | wg1.Wait() 28 | return openPorts 29 | } 30 | 31 | // scanRange - This is used by its wrapper function, PortScan, in order 32 | // to individually scan a port range. 33 | func scanRange(host string, portFrom int, portTo int, resultBuff *[]int) { 34 | wg1.Add(1) 35 | defer wg1.Done() 36 | for x := portFrom; x < portTo; x++ { 37 | _, err := net.Dial("tcp", host+":"+strconv.Itoa(x)) 38 | if err == nil { 39 | *resultBuff = append(*resultBuff, x) 40 | } 41 | if x%5 == 0 { 42 | // for every five connections tried, try a different 43 | // range for SLEEP_TIME 44 | time.Sleep(SLEEP_TIME) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /iface_test.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | // TODO: implement mock of []net.Interface for testing 9 | // not that they work. 10 | /* 11 | interfaces := []net.Interface{ 12 | { 13 | Index: 1, 14 | MTU: 313, 15 | Name: "test iface", 16 | HardwareAddr: net.HardwareAddr, 17 | Flags: net.Flags, 18 | } 19 | } 20 | ifaces, err := getInterfaceAddrs(interfaces) 21 | if err != nil { 22 | t.Fatal(err) 23 | } 24 | */ 25 | 26 | // Test IFace NOTE: there is a small chance of this failing if a new interface 27 | // appears while this test is running 28 | func TestIFace(t *testing.T) { 29 | t.Parallel() 30 | // currently only test that the function can be called 31 | ifaces, err := GetInterfaceAddrs() 32 | if err != nil { 33 | t.Fatal(err) 34 | } 35 | if len(ifaces) < 1 { 36 | t.Skip("len(ifaces) < 1") 37 | } 38 | 39 | t.Run("GetIFaceByName", func(t *testing.T) { 40 | t.Parallel() 41 | iface, err := GetIFaceByName(ifaces[0].Name) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | 46 | if !reflect.DeepEqual(iface, ifaces[0]) { 47 | t.Fatal("iface != ifaces[0]") 48 | } 49 | }) 50 | 51 | t.Run("GetIFaceByIndex", func(t *testing.T) { 52 | t.Parallel() 53 | iface, err := GetIFaceByIndex(1) 54 | if err != nil { 55 | t.Fatal(err) 56 | } 57 | 58 | if !reflect.DeepEqual(iface, ifaces[0]) { 59 | t.Fatal("iface != ifaces[0]") 60 | } 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /pwn_test.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | ) 7 | 8 | // Test the ToBytes function in misc.go 9 | func TestToBytes(t *testing.T) { 10 | t.Parallel() 11 | var tt = []struct { 12 | // name of the subtest to execute 13 | name string 14 | 15 | // expected inputs and outputs 16 | input interface{} 17 | output []byte 18 | 19 | // do you expect the conversion to fail? 20 | fail bool 21 | }{ 22 | { 23 | name: "test string", 24 | input: "hello", 25 | output: []byte("hello"), 26 | }, 27 | { 28 | // may be convertable some day 29 | name: "test int", 30 | input: 42, 31 | 32 | fail: true, 33 | }, 34 | { 35 | name: "test byte", 36 | input: byte(5), 37 | output: []byte{5}, 38 | }, 39 | { 40 | name: "test struct", 41 | input: struct{}{}, 42 | fail: true, 43 | }, 44 | { 45 | name: "test rune", 46 | input: 'h', 47 | output: []byte{'h'}, 48 | }, 49 | { 50 | name: "test []byte", 51 | input: []byte{131, 41, 48}, 52 | output: []byte{131, 41, 48}, 53 | }, 54 | } 55 | 56 | // execute the tests 57 | for _, tc := range tt { 58 | t.Run(tc.name, func(t *testing.T) { 59 | defer func() { 60 | e := recover() 61 | // if the error is not nil and it is not expected then fail 62 | if e != nil && !tc.fail { 63 | t.Fatal(e) 64 | } 65 | }() 66 | 67 | b := Bytes(tc.input) 68 | if !bytes.Equal(b, tc.output) { 69 | t.Fatalf("wanted %q got %q", tc.output, b) 70 | } 71 | }) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /net_test.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "math/rand" 5 | "net" 6 | "strconv" 7 | "testing" 8 | "time" 9 | 10 | "github.com/golang/net/nettest" 11 | ) 12 | 13 | func init() { 14 | rand.Seed(time.Now().Unix()) 15 | } 16 | 17 | // TestNet uses the nettest package to test that pwn.Conn works 18 | // testing readtill is pointless since io_test already covers it as long 19 | // as it has a valid reader. 20 | func TestNet(t *testing.T) { 21 | t.Parallel() 22 | nettest.TestConn(t, mp) 23 | } 24 | 25 | // mp connects a pwn.Listener with a pwn.Dialer 26 | // c2 is the client c1 is the server 27 | func mp() (c1, c2 net.Conn, stop func(), err error) { 28 | addr := "127.0.0.1:" + randPort() 29 | connChan := make(chan net.Conn) 30 | errChan := make(chan error) 31 | go func() { 32 | l, err := Listen("tcp", addr) 33 | if err != nil { 34 | errChan <- err 35 | return 36 | } 37 | conn, err := l.Accept() 38 | if err != nil { 39 | errChan <- err 40 | return 41 | } 42 | connChan <- conn 43 | }() 44 | 45 | time.Sleep(20 * time.Millisecond) 46 | c2, err = Dial("tcp", addr) 47 | if err != nil { 48 | return 49 | } 50 | 51 | // check possible error from the server goroutine 52 | select { 53 | case err = <-errChan: 54 | if err != nil { 55 | return 56 | } 57 | case c1 = <-connChan: 58 | break 59 | } 60 | 61 | stop = func() { 62 | c1.Close() 63 | c2.Close() 64 | } 65 | return 66 | } 67 | 68 | // get a random port from min 1024 to max 65535 69 | func randPort() string { 70 | var port int 71 | for port <= 1024 { 72 | port = rand.Intn(65535) 73 | } 74 | return strconv.Itoa(port) 75 | } 76 | -------------------------------------------------------------------------------- /io_test.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "io" 7 | "testing" 8 | ) 9 | 10 | // TestReadTill testcases the ReadTill function in io.go 11 | func TestReadTill(t *testing.T) { 12 | t.Parallel() 13 | var testcases = []struct { 14 | // expected input and expecteds 15 | input []byte 16 | expected []byte 17 | 18 | delim byte 19 | // do we expect ErrMaxLen? 20 | overMaxLen bool 21 | maxLen int 22 | }{ 23 | { 24 | input: []byte("AAAAAAAAAABBBBBBBBBB"), 25 | expected: []byte("AAAAAAAAAA"), 26 | 27 | delim: 'B', 28 | }, 29 | { 30 | input: []byte("Hello\n World"), 31 | expected: []byte("Hello"), 32 | delim: '\n', 33 | }, 34 | { 35 | // What happens with a nil delim? 36 | input: []byte("Hello\n World"), 37 | expected: []byte("Hello\n World"), 38 | }, 39 | { 40 | // test max len 41 | input: []byte("Hello, World!"), 42 | expected: []byte("Hello,"), 43 | maxLen: 6, 44 | overMaxLen: true, 45 | }, 46 | } 47 | 48 | for _, tc := range testcases { 49 | r := bytes.NewBuffer(tc.input) 50 | output, err := ReadTill(r, tc.maxLen, tc.delim) 51 | if err != nil && err != io.EOF { 52 | if !tc.overMaxLen && err != ErrMaxLen { 53 | t.Fatal(err) 54 | } 55 | } 56 | 57 | if !bytes.Equal(output, tc.expected) { 58 | t.Fatalf("wanted %q got %q", tc.expected, output) 59 | } 60 | } 61 | 62 | // test that readtill returns correctly on a nil reader 63 | t.Run("test nil", func(t *testing.T) { 64 | _, err := ReadTill(nil, 0, '\n') 65 | if err != ErrNilReader { 66 | t.Fatalf("expected ErrNilReader, got: %v", err) 67 | } 68 | }) 69 | } 70 | 71 | // badwriter returns its own string as an error when write is called. 72 | type badReader string 73 | 74 | func (b badReader) Read([]byte) (int, error) { 75 | return 0, errors.New(string(b)) 76 | } 77 | -------------------------------------------------------------------------------- /io.go: -------------------------------------------------------------------------------- 1 | // Some useful io utils, because io/ioutil is not enough 2 | 3 | package pwn 4 | 5 | import ( 6 | "context" 7 | "errors" 8 | "io" 9 | ) 10 | 11 | // ErrMaxLen indecates that the max length was reached for ReadTill. 12 | var ErrMaxLen = errors.New("max length reached") 13 | 14 | // ErrNilReader indecates that a nil reader was supplied. 15 | var ErrNilReader = errors.New("nil reader") 16 | 17 | // MaxLenDefault is the max length default for the ReadTill function. 18 | const MaxLenDefault = 256 19 | 20 | // ReadByte reads one byte from r and returns it, 21 | // if it fails it will return io.ErrUnexpectedEOF. 22 | func ReadByte(r io.Reader) (byte, error) { 23 | var buf [1]byte 24 | 25 | // read into buf 26 | _, err := io.ReadFull(r, buf[:]) 27 | return buf[0], err 28 | } 29 | 30 | // ReadTill reads till 'delim' (non inclusive) and returns bytes read and possible error. 31 | // if maxLen is <= 0 it will use MaxLenDefault. 32 | func ReadTill(r io.Reader, maxLen int, delim byte) ([]byte, error) { 33 | return ReadTillContext(r, maxLen, delim, context.Background()) 34 | } 35 | 36 | // this function's params are very long, i don't want to create a struct 37 | // just for it though, should not be too long when calling it 38 | 39 | // ReadTill reads till 'delim' (non inclusive) or ctx.Done() 40 | // and returns bytes read and possible error. 41 | // if maxLen is <= 0 it will use MaxLenDefault. 42 | func ReadTillContext(r io.Reader, maxLen int, delim byte, 43 | ctx context.Context) (ret []byte, err error) { 44 | 45 | if maxLen <= 0 { 46 | maxLen = MaxLenDefault 47 | } 48 | if r == nil { 49 | return ret, ErrNilReader 50 | } 51 | 52 | for { 53 | select { 54 | case <-ctx.Done(): 55 | return ret, err 56 | default: 57 | } 58 | 59 | // read one byte 60 | b, err := ReadByte(r) 61 | if err != nil { 62 | return ret, err 63 | } 64 | 65 | // if the byte is equal to delim stop reading 66 | if b == delim { 67 | break 68 | } 69 | 70 | // append the byte to ret 71 | ret = append(ret, b) 72 | if len(ret) >= maxLen { 73 | return ret, ErrMaxLen 74 | } 75 | } 76 | 77 | return ret, nil 78 | } 79 | 80 | // WriteLine writes a line to the writer 81 | // it will panic if it ToBytes fails to convert t to []byte 82 | func WriteLine(w io.Writer, t interface{}) error { 83 | // convert t to bytes 84 | b := Bytes(t) 85 | 86 | // add the newline, we are "WriteLine" after all! 87 | b = append(b, '\n') 88 | _, err := w.Write(b) 89 | return err 90 | } 91 | -------------------------------------------------------------------------------- /iface.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "net" 5 | ) 6 | 7 | // IFace is a networking interface, expanded by more information 8 | type IFace struct { 9 | Index int 10 | MTU int 11 | Name string 12 | HardwareAddr net.HardwareAddr 13 | Flags net.Flags 14 | Addrs []net.Addr 15 | MulticastAddrs []net.Addr 16 | } 17 | 18 | // GetInterfaceAddrs Returns all ifaces with Addrs and MulticastAddrs 19 | func GetInterfaceAddrs() ([]IFace, error) { 20 | ifaces, err := net.Interfaces() 21 | if err != nil { 22 | return []IFace{}, err 23 | } 24 | 25 | return getInterfaceAddrs(ifaces) 26 | } 27 | 28 | // the actual implementation of GetInterfaceAddrs, with an extra argument for testing 29 | func getInterfaceAddrs(ifaces []net.Interface) ([]IFace, error) { 30 | IFaces := []IFace{} 31 | for i := 0; i < len(ifaces); i++ { 32 | // Create a new IFaces instance inline and append it to the IFaces slice 33 | IFaces = append(IFaces, IFace{ 34 | Index: ifaces[i].Index, 35 | MTU: ifaces[i].MTU, 36 | Name: ifaces[i].Name, 37 | HardwareAddr: ifaces[i].HardwareAddr, 38 | Flags: ifaces[i].Flags, 39 | }) 40 | 41 | // now you can add the other fields, because append grows the slice 42 | 43 | // if there is an error, addrs will be returned as its zero value 44 | // aka nil, so the "error checking" was pointless. 45 | addrs, _ := ifaces[i].Addrs() 46 | IFaces[i].Addrs = addrs 47 | 48 | multiAddrs, _ := ifaces[i].MulticastAddrs() 49 | IFaces[i].MulticastAddrs = multiAddrs 50 | } 51 | 52 | return IFaces, nil 53 | } 54 | 55 | // GetIFaceByName returns requested interface by name ('eth0', 'lo', etc) 56 | func GetIFaceByName(name string) (IFace, error) { 57 | iface, err := net.InterfaceByName(name) 58 | if err != nil { 59 | return IFace{}, err 60 | } 61 | IFace := IFace{} // will this give problems with the naming? 62 | 63 | IFace.Index = iface.Index 64 | IFace.MTU = iface.MTU 65 | IFace.Name = iface.Name 66 | IFace.HardwareAddr = iface.HardwareAddr 67 | IFace.Flags = iface.Flags 68 | IFace.Addrs, _ = iface.Addrs() 69 | IFace.MulticastAddrs, _ = iface.MulticastAddrs() 70 | 71 | return IFace, nil 72 | } 73 | 74 | // GetIFaceByIndex returns an interface based on its index 75 | func GetIFaceByIndex(index int) (IFace, error) { 76 | iface, err := net.InterfaceByIndex(index) 77 | if err != nil { 78 | return IFace{}, err 79 | } 80 | IFace := IFace{} // will this give problems with the naming? 81 | 82 | IFace.Index = iface.Index 83 | IFace.MTU = iface.MTU 84 | IFace.Name = iface.Name 85 | IFace.HardwareAddr = iface.HardwareAddr 86 | IFace.Flags = iface.Flags 87 | IFace.Addrs, _ = iface.Addrs() 88 | IFace.MulticastAddrs, _ = iface.MulticastAddrs() 89 | 90 | return IFace, nil 91 | } 92 | -------------------------------------------------------------------------------- /net.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "net" 5 | "sync" 6 | ) 7 | 8 | // A Listener is a generic network listener for stream-oriented protocols. 9 | // Multiple goroutines may invoke methods on a Listener simultaneously. 10 | type Listener interface { 11 | // Accept waits for and returns the next Connection to the listener. 12 | Accept() (Conn, error) 13 | 14 | // Close closes the listener. 15 | // Any blocked Accept operations will be unblocked and return errors. 16 | Close() error 17 | 18 | // Addr returns the listener's network address. 19 | Addr() net.Addr 20 | } 21 | 22 | type listener struct { 23 | l net.Listener 24 | } 25 | 26 | func (l listener) Addr() net.Addr { 27 | return l.l.Addr() 28 | } 29 | 30 | func (l listener) Close() error { 31 | return l.l.Close() 32 | } 33 | 34 | func (l listener) Accept() (Conn, error) { 35 | rawConn, err := l.l.Accept() 36 | if err != nil { 37 | return Conn{}, err 38 | } 39 | 40 | return Conn{ 41 | rawConn, 42 | // the default line length to be used with Conn.ReadLine 43 | MaxLenDefault, 44 | 45 | sync.Mutex{}, 46 | }, nil 47 | } 48 | 49 | // Conn is a generic stream-oriented network connection. 50 | // 51 | // Multiple goroutines may invoke methods on a Conn simultaneously. 52 | type Conn struct { 53 | // the embeedded net.Conn 54 | net.Conn 55 | 56 | // the max length for ReadLine and ReadTill. 57 | maxLen int 58 | 59 | // mu is used for protecting struct variables from concurrent reads / writes 60 | mu sync.Mutex 61 | } 62 | 63 | // MaxLen changes the max length for ReadLine and ReadTill in the conn 64 | func (c *Conn) MaxLen(length int) { 65 | // prevent panics 66 | if c == nil { 67 | return 68 | } 69 | 70 | c.mu.Lock() 71 | defer c.mu.Unlock() 72 | c.maxLen = length 73 | } 74 | 75 | // ReadLine reads until '\n' and returns bytes read and possible error. 76 | func (c *Conn) ReadLine() ([]byte, error) { 77 | return ReadTill(c, c.maxLen, '\n') 78 | } 79 | 80 | // ReadTill reads till 'delim' and returns bytes read and possible error. 81 | func (c *Conn) ReadTill(delim byte) ([]byte, error) { 82 | return ReadTill(c, c.maxLen, delim) 83 | } 84 | 85 | // WriteLine writes a line to the Connection. 86 | // t can be anything convertable to []byte (see Bytes function) 87 | // Bytes will panic if it fails to convert to []byte 88 | func (c *Conn) WriteLine(t interface{}) error { 89 | return WriteLine(c, t) 90 | } 91 | 92 | // Dial creates a new network Connection returning a Conn, 93 | // MaxLineLength is by default set to MaxLenDefault, you can change it in the returned 94 | // Conn using Conn.MaxLen(i int). 95 | func Dial(network, addr string) (Conn, error) { 96 | rawConn, err := net.Dial(network, addr) 97 | if err != nil { 98 | return Conn{}, err 99 | } 100 | 101 | return Conn{ 102 | rawConn, 103 | // the default line length to be used with Conn.ReadLine 104 | MaxLenDefault, 105 | 106 | // mutex to protect concurrent calls 107 | sync.Mutex{}, 108 | }, nil 109 | } 110 | 111 | // Listen creates a net.Listener that will accept Connections 112 | // and wrap them in a pwn.Conn 113 | func Listen(network, addr string) (Listener, error) { 114 | rawListener, err := net.Listen(network, addr) 115 | if err != nil { 116 | return nil, err 117 | } 118 | 119 | return listener{ 120 | l: rawListener, 121 | }, nil 122 | } 123 | -------------------------------------------------------------------------------- /processes.go: -------------------------------------------------------------------------------- 1 | package pwn 2 | 3 | import ( 4 | "io" 5 | "os" 6 | "os/exec" 7 | "time" 8 | ) 9 | 10 | // Start starts cmd and returns a Process for it 11 | func Start(cmd *exec.Cmd) (Process, error) { 12 | // file descriptors 13 | stdin, err := cmd.StdinPipe() 14 | if err != nil { 15 | return Process{}, err 16 | } 17 | stdout, err := cmd.StdoutPipe() 18 | if err != nil { 19 | return Process{}, err 20 | } 21 | stderr, err := cmd.StderrPipe() 22 | if err != nil { 23 | return Process{}, err 24 | } 25 | 26 | err = cmd.Start() 27 | if err != nil { 28 | return Process{}, err 29 | } 30 | return Process{ 31 | cmd: cmd, 32 | Stdin: stdin, 33 | Stdout: stdout, 34 | Stderr: stderr, 35 | // the maximum line length to be used with ReadLine 36 | maxLen: MaxLenDefault, 37 | }, nil 38 | } 39 | 40 | // Spawn spawns a new process and returns it 41 | func Spawn(path string, args ...string) (Process, error) { 42 | cmd := exec.Command(path, args...) 43 | return Start(cmd) 44 | } 45 | 46 | // Process represents a spawned process 47 | // It has the methods of a os.Process and os.Cmd 48 | type Process struct { 49 | // the underlying cmd 50 | cmd *exec.Cmd 51 | 52 | // file descriptors we can manipulate 53 | Stdin io.WriteCloser 54 | Stdout io.ReadCloser 55 | Stderr io.ReadCloser 56 | 57 | // the max length to be used with ReadLine 58 | maxLen int 59 | } 60 | 61 | // WriteLine writes a line to the standard input of the running process 62 | // t can be anything convertable to []byte (see ToBytes function) 63 | // ToBytes will panic if it fails to convert to bytes 64 | func (p Process) WriteLine(t interface{}) error { 65 | // write the data to the processes standard input 66 | return WriteLine(p.Stdin, t) 67 | } 68 | 69 | // ReadLine reads until newline or timeout expires 70 | // TODO: implement timeout 71 | func (p Process) ReadLine(timeout time.Duration) ([]byte, error) { 72 | b, err := ReadTill(p.Stdout, p.maxLen, '\n') 73 | if err != nil { 74 | return nil, err 75 | } 76 | 77 | return b, nil 78 | } 79 | 80 | // Interactive sets the file descriptors to os.Stderr os.Stdout and os.Stdin 81 | func (p Process) Interactive() error { 82 | return interactive(p, os.Stdin, os.Stdout, os.Stderr) 83 | } 84 | 85 | // the actual implementation of Process.Interactive 86 | func interactive(p Process, in io.Reader, out, err io.Writer) error { 87 | // Make it interactive 88 | go io.Copy(p.Stdin, in) 89 | go io.Copy(out, p.Stdout) 90 | go io.Copy(err, p.Stderr) 91 | 92 | // Wait for the process to exit 93 | return p.Wait() 94 | } 95 | 96 | // os/exec.Cmd methods 97 | 98 | // StdinPipe returns a pipe that will be connected to the command's 99 | // standard input when the command starts. 100 | // The pipe will be closed automatically after Wait sees the command exit. 101 | // A caller need only call Close to force the pipe to close sooner. 102 | // For example, if the command being run will not exit until standard input 103 | // is closed, the caller must close the pipe. 104 | func (p *Process) StdinPipe() (io.WriteCloser, error) { return p.cmd.StdinPipe() } 105 | 106 | // StderrPipe returns a pipe that will be connected to the command's 107 | // standard error when the command starts. 108 | // 109 | // Wait will close the pipe after seeing the command exit, so most callers 110 | // need not close the pipe themselves; however, an implication is that 111 | // it is incorrect to call Wait before all reads from the pipe have completed. 112 | // For the same reason, it is incorrect to use Run when using StderrPipe. 113 | // See the StdoutPipe example for idiomatic usage. 114 | func (p *Process) StderrPipe() (io.ReadCloser, error) { return p.cmd.StderrPipe() } 115 | 116 | // StdoutPipe returns a pipe that will be connected to the command's 117 | // standard output when the command starts. 118 | // 119 | // Wait will close the pipe after seeing the command exit, so most callers 120 | // need not close the pipe themselves; however, an implication is that 121 | // it is incorrect to call Wait before all reads from the pipe have completed. 122 | // For the same reason, it is incorrect to call Run when using StdoutPipe. 123 | // See the example for idiomatic usage. 124 | func (p *Process) StdoutPipe() (io.ReadCloser, error) { return p.cmd.StdoutPipe() } 125 | 126 | // Wait waits for the command to exit and waits for any copying to 127 | // stdin or copying from stdout or stderr to complete. 128 | // 129 | // The command must have been started by Start. 130 | // 131 | // The returned error is nil if the command runs, has no problems 132 | // copying stdin, stdout, and stderr, and exits with a zero exit 133 | // status. 134 | // 135 | // If the command fails to run or doesn't complete successfully, the 136 | // error is of type *ExitError. Other error types may be 137 | // returned for I/O problems. 138 | // 139 | // If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits 140 | // for the respective I/O loop copying to or from the process to complete. 141 | // 142 | // Wait releases any resources associated with the Cmd. 143 | // NOTE: this is the Wait method for cmd.Wait NOT cmd.Process.Wait 144 | func (p *Process) Wait() error { return p.cmd.Wait() } 145 | 146 | // os.Process methods 147 | 148 | // Kill causes the Process to exit immediately. Kill does not wait until 149 | // the Process has actually exited. This only kills the Process itself, 150 | // not any other processes it may have started. 151 | func (p *Process) Kill() error { return p.cmd.Process.Kill() } 152 | 153 | // Release releases any resources associated with the Process p, 154 | // rendering it unusable in the future. 155 | // Release only needs to be called if Wait is not. 156 | func (p *Process) Release() error { return p.cmd.Process.Release() } 157 | 158 | // Signal sends a signal to the Process. 159 | // Sending Interrupt on Windows is not implemented. 160 | func (p *Process) Signal(sig os.Signal) error { return p.cmd.Process.Signal(sig) } 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [https://github.com/Gopwn] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------