package traffic import ( "bufio" "bytes" "encoding/binary" "io" "net" "os" "strings" "time" ) // SniffedProto identifies the detected L7 protocol from a TCP stream's first bytes. type SniffedProto string const ( ProtoTCP SniffedProto = "tcp" ProtoHTTP SniffedProto = "http" ProtoTLS SniffedProto = "tls" ) // SniffResult carries the sniffed protocol plus any extracted Host / SNI. type SniffResult struct { Proto SniffedProto Host string SNI string } // PeekConn wraps a net.Conn so already-peeked bytes are transparently replayed // on subsequent Read calls. type PeekConn struct { net.Conn br *bufio.Reader } func (c *PeekConn) Read(p []byte) (int, error) { return c.br.Read(p) } // CloseWrite propagates TCP half-close to the underlying net.Conn so L4 relays // deliver EOF to the peer instead of deadlocking when one side finishes first. func (c *PeekConn) CloseWrite() error { if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok { return cw.CloseWrite() } return nil } // SniffProtocol inspects the first bytes of a newly accepted TCP connection // without consuming them from the returned net.Conn. // // If the client does not send bytes within peekTimeout (e.g. server-speaks-first // protocols like SSH, MySQL, SMTP), it classifies the stream as raw ProtoTCP // immediately without blocking the connection. func SniffProtocol(conn net.Conn, peekTimeout time.Duration) (SniffResult, net.Conn) { if peekTimeout <= 0 { peekTimeout = 250 * time.Millisecond } br := bufio.NewReaderSize(conn, 4096) wrapped := &PeekConn{Conn: conn, br: br} _ = conn.SetReadDeadline(time.Now().Add(peekTimeout)) buf, err := peekAvailable(br, 2048) _ = conn.SetReadDeadline(time.Time{}) if len(buf) == 0 { if err != nil && !os.IsTimeout(err) && err != io.EOF { return SniffResult{Proto: ProtoTCP}, wrapped } return SniffResult{Proto: ProtoTCP}, wrapped } if sni, ok := parseTLSClientHelloSNI(buf); ok { return SniffResult{Proto: ProtoTLS, SNI: sni, Host: sni}, wrapped } if host, ok := parseHTTPFirstLineHost(buf); ok { return SniffResult{Proto: ProtoHTTP, Host: host}, wrapped } return SniffResult{Proto: ProtoTCP}, wrapped } func peekAvailable(br *bufio.Reader, maxBytes int) ([]byte, error) { if _, err := br.Peek(1); err != nil { return nil, err } n := br.Buffered() if n > maxBytes { n = maxBytes } if n <= 0 { return nil, nil } return br.Peek(n) } // parseTLSClientHelloSNI checks whether buf starts with a TLS Handshake // ClientHello record and extracts the RFC 6066 server_name (SNI) if present. func parseTLSClientHelloSNI(buf []byte) (sni string, isTLS bool) { if len(buf) < 6 { return "", false } if buf[0] != 0x16 || buf[1] != 0x03 || buf[2] > 0x04 { return "", false } if buf[5] != 0x01 { return "", false } isTLS = true recLen := int(binary.BigEndian.Uint16(buf[3:5])) end := 5 + recLen if end > len(buf) { end = len(buf) } p := buf[5:end] if len(p) < 4 { return "", true } p = p[4:] // handshake header if len(p) < 34 { return "", true } p = p[34:] // version + random if len(p) < 1 { return "", true } sidLen := int(p[0]) if len(p) < 1+sidLen { return "", true } p = p[1+sidLen:] if len(p) < 2 { return "", true } csLen := int(binary.BigEndian.Uint16(p[:2])) if len(p) < 2+csLen { return "", true } p = p[2+csLen:] if len(p) < 1 { return "", true } cmLen := int(p[0]) if len(p) < 1+cmLen { return "", true } p = p[1+cmLen:] if len(p) < 2 { return "", true } extTotal := int(binary.BigEndian.Uint16(p[:2])) p = p[2:] if extTotal < len(p) { p = p[:extTotal] } for len(p) >= 4 { extType := binary.BigEndian.Uint16(p[0:2]) extLen := int(binary.BigEndian.Uint16(p[2:4])) p = p[4:] if extLen > len(p) { break } if extType == 0x0000 { // server_name ext := p[:extLen] if len(ext) < 2 { return "", true } listLen := int(binary.BigEndian.Uint16(ext[0:2])) ext = ext[2:] if listLen < len(ext) { ext = ext[:listLen] } for len(ext) >= 3 { nameType := ext[0] nameLen := int(binary.BigEndian.Uint16(ext[1:3])) ext = ext[3:] if nameLen > len(ext) { break } if nameType == 0x00 { return strings.ToLower(strings.TrimSpace(string(ext[:nameLen]))), true } ext = ext[nameLen:] } return "", true } p = p[extLen:] } return "", true } var httpMethodPrefixes = [][]byte{ []byte("GET "), []byte("POST "), []byte("PUT "), []byte("DELETE "), []byte("HEAD "), []byte("OPTIONS "), []byte("PATCH "), []byte("CONNECT "), []byte("TRACE "), } func parseHTTPFirstLineHost(buf []byte) (host string, isHTTP bool) { matched := false for _, m := range httpMethodPrefixes { if bytes.HasPrefix(buf, m) { matched = true break } } if !matched { return "", false } lineEnd := bytes.IndexByte(buf, '\n') firstLine := buf if lineEnd > 0 { firstLine = buf[:lineEnd] } if !bytes.Contains(firstLine, []byte("HTTP/1.")) && !bytes.Contains(firstLine, []byte("HTTP/2")) { return "", false } lines := bytes.Split(buf, []byte("\n")) for i := 1; i < len(lines); i++ { line := strings.TrimSpace(string(lines[i])) if line == "" { break } if len(line) > 5 && strings.EqualFold(line[:5], "host:") { return strings.TrimSpace(line[5:]), true } } return "", true }