Here is a rough sketch:

type allowedIPsListener struct {
        allowed []net.IP
        inner   net.Listener
}

func (ln *allowedIPsListener) Accept() (net.Conn, error) {
        for {
                conn, err := ln.inner.Accept()
                if err != nil {
                        return nil, err
                }
                if !ln.allowed(conn.RemoteAddr()) {
                        conn.Close()
                        continue
                }
                return conn, nil
        }
}

func (ln *allowedIPsListener) Close() error {
        return ln.inner.Close()
}

func (ln *allowedIPsListener) Addr() net.Addr {
        return ln.inner.Addr()
}

func (ln *allowedIPsListener) allowed(addr net.Addr) bool {
        // TODO: implement
        return true
}

Then, to use:

ln, err := net.Listen("tcp", addr)
if err != nil {
        log.Fatal(err)
}
aln := &allowedIPsListener{allowed: yourListOfIPs, inner: ln}
tlsln := tls.NewListener(aln, yourTLSConfig)

// use tlsln

On 3/15/19 2:58 PM, Glen Huang wrote:
> Thanks for the quick reply.
> 
> I want to use tcp, is it possible to leverage TCPListener or I have to 
> invent my own? It seems I'll face the same issue as I do with tls?
> 
> On Friday, March 15, 2019 at 9:46:00 PM UTC+8, Andrei Tudor Călin wrote:
>>
>> Begin by implementing a `net.Listener` which checks the list of allowed 
>> IPs. 
>> You'll be able to run code before the connection is passed on to 
>> crypto/tls. 
>> Wrap it using https://golang.org/pkg/crypto/tls/#NewListener. 
>>
>> On 3/15/19 2:10 PM, Glen Huang wrote: 
>>> I'm trying to limit which clients are allowed to connect to my tls 
>> server 
>>> by their IPs. 
>>>
>>> I know I can do that after Accept, check their IPs and close the 
>> connection 
>>> if they're not whitelisted. But that means the full tls handshake has to 
>>> complete before I can do that. 
>>>
>>> Another option is that I can use nftables to whitelist clients at the 
>>> kernel level. But to do that, I either have to spawn a subprocess to 
>> call 
>>> nft, which is kinda slow or use google/nftables that isn't production 
>> ready 
>>> yet (also missing some features I need). 
>>>
>>> Is there anyway I can drop the tls connection when a client sends SYN? 
>>>
>>> Thanks in advance. 
>>>
>>
>> -- 
>> Andrei Tudor Călin 
>>
> 

-- 
Andrei Tudor Călin

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to