diff --git a/knockr.go b/knockr.go index 0002e58..32ca437 100644 --- a/knockr.go +++ b/knockr.go @@ -20,16 +20,19 @@ var whitelist = make(map[string]int64) var arguments *knockArguments func main() { + // Parse command line arguments cli.Run(new(knockArguments), func(ctx *cli.Context) error { arguments = ctx.Argv() . (*knockArguments) return nil }) + // Launch listeners go listener(arguments.WhitelistPort, whitelist_handler) listener(arguments.GatewayPort, gateway_handler) } func listener(port int, listen_func func(c net.Conn)) { + // Set up listening sockets on specified port and hand over to specified listen_func ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { @@ -49,6 +52,7 @@ func listener(port int, listen_func func(c net.Conn)) { } func whitelist_handler(c net.Conn) { + // Handler function for whitelist socket connections, whitelisting the connecting host host, _, _ := net.SplitHostPort(c.RemoteAddr().String()) io.WriteString(c, fmt.Sprintf("Knock Knock, %s.", host)) @@ -57,6 +61,7 @@ func whitelist_handler(c net.Conn) { } func gateway_handler(c net.Conn) { + // Filter connections whether or not the connecting host is whitelisted host, _, _ := net.SplitHostPort(c.RemoteAddr().String()) if is_whitelisted(host) { @@ -70,16 +75,19 @@ func gateway_handler(c net.Conn) { } func add_to_whitelist(addr string) { + // Add the specified address to the whitelist if ! is_whitelisted(addr) { update_whitelist_time(addr) } } func remove_from_whitelist(addr string) { + // Remove specified address from whitelist delete(whitelist, addr) } func is_whitelisted(addr string) bool { + // Check whether or not the specified address is whitelisted and inside the timing window if _, present := whitelist[addr]; present { // Key is present in whitelist map if (whitelist[addr] + arguments.Timeout) >= time.Now().Unix() { @@ -97,10 +105,12 @@ func is_whitelisted(addr string) bool { } func update_whitelist_time(addr string) { + // Update whitelist - prevent timeout of connection whitelist[addr] = time.Now().Unix() } func proxy(c net.Conn) { + // Proxy connection between the destination server and our connecting client ln, err := net.Dial("tcp", arguments.Destination) if err != nil { fmt.Println("[ERR] Proxy connection to server failed")