goknockr/knockr.go

95 lines
2.0 KiB
Go
Raw Normal View History

2017-09-27 13:44:02 +00:00
package main
import (
"fmt"
"io"
"net"
"github.com/mkideal/cli"
2017-09-27 13:44:02 +00:00
)
type knockArguments struct {
cli.Helper
WhitelistPort int `cli:'wp' usage:'The port to launch the whitelist server on'`
GatewayPort int `cli:'gp' usage:'The port to protect'`
Destination string `cli:'d' usage:'The destination to relay traffic to'`
}
2017-09-27 13:44:02 +00:00
var whitelist []string
var arguments *knockArguments
2017-09-27 13:44:02 +00:00
func main() {
cli.Run(new(knockArguments), func(ctx *cli.Context) error {
arguments = ctx.Argv() . (*knockArguments)
return nil
})
go listener(arguments.WhitelistPort, whitelist_handler)
listener(arguments.GatewayPort, gateway_handler)
}
func listener(port int, listen_func func(c net.Conn)) {
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
2017-09-27 13:44:02 +00:00
if err != nil {
2017-09-27 21:08:23 +00:00
fmt.Println("[ERR] Creating listener for Port ", port)
2017-09-28 08:56:36 +00:00
fmt.Println(" Error is ", err)
2017-09-27 13:44:02 +00:00
} else {
2017-09-27 21:08:23 +00:00
fmt.Println("[OK ] Creating listener for Port ", port)
2017-09-27 13:44:02 +00:00
for {
conn, err := ln.Accept()
if err != nil {
2017-09-27 21:08:23 +00:00
fmt.Println("[ERR] Accepting on Port ", port)
2017-09-27 13:44:02 +00:00
} else {
go listen_func(conn)
2017-09-27 13:44:02 +00:00
}
}
}
}
func whitelist_handler(c net.Conn) {
2017-09-27 13:44:02 +00:00
host, _, _ := net.SplitHostPort(c.RemoteAddr().String())
2017-09-27 14:44:52 +00:00
io.WriteString(c, fmt.Sprintf("Knock Knock, %s.", host))
add_to_whitelist(host)
c.Close()
}
func gateway_handler(c net.Conn) {
host, _, _ := net.SplitHostPort(c.RemoteAddr().String())
2017-09-27 13:44:02 +00:00
if is_whitelisted(host) {
2017-09-27 21:08:23 +00:00
fmt.Println("[OK ] Whitelisted host ", host, " connected")
2017-09-27 14:40:29 +00:00
proxy(c)
2017-09-27 13:44:02 +00:00
} else {
2017-09-27 21:08:23 +00:00
fmt.Println("[BLK] Blocking host ", host)
2017-09-27 13:44:02 +00:00
}
c.Close()
}
func add_to_whitelist(addr string) {
if ! is_whitelisted(addr) {
whitelist = append(whitelist, addr)
}
}
func is_whitelisted(addr string) bool {
for i:=0; i < len(whitelist); i++ {
if whitelist[i] == addr {
return true
}
}
return false
}
2017-09-27 14:40:29 +00:00
func proxy(c net.Conn) {
ln, err := net.Dial("tcp", arguments.Destination)
2017-09-27 14:40:29 +00:00
if err != nil {
2017-09-27 21:08:23 +00:00
fmt.Println("[ERR] Proxy connection to server failed")
2017-09-28 08:56:36 +00:00
fmt.Println(" Error is ", err)
2017-09-27 14:40:29 +00:00
} else {
go io.Copy(c, ln)
io.Copy(ln, c)
}
}