github.com/crowdsecurity/crowdsec@v1.6.1/pkg/acquisition/modules/syslog/internal/parser/utils/utils.go (about) 1 package utils 2 3 import "net" 4 5 func isValidIP(ip string) bool { 6 return net.ParseIP(ip) != nil 7 } 8 9 func IsAlphaNumeric(c byte) bool { 10 return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' 11 } 12 13 //This function is lifted from go source 14 //See https://github.com/golang/go/blob/master/src/net/dnsclient.go#L75 15 func isValidHostname(s string) bool { 16 // The root domain name is valid. See golang.org/issue/45715. 17 if s == "." { 18 return true 19 } 20 21 // See RFC 1035, RFC 3696. 22 // Presentation format has dots before every label except the first, and the 23 // terminal empty label is optional here because we assume fully-qualified 24 // (absolute) input. We must therefore reserve space for the first and last 25 // labels' length octets in wire format, where they are necessary and the 26 // maximum total length is 255. 27 // So our _effective_ maximum is 253, but 254 is not rejected if the last 28 // character is a dot. 29 l := len(s) 30 if l == 0 || l > 254 || l == 254 && s[l-1] != '.' { 31 return false 32 } 33 34 last := byte('.') 35 nonNumeric := false // true once we've seen a letter or hyphen 36 partlen := 0 37 for i := 0; i < len(s); i++ { 38 c := s[i] 39 switch { 40 default: 41 return false 42 case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_': 43 nonNumeric = true 44 partlen++ 45 case '0' <= c && c <= '9': 46 // fine 47 partlen++ 48 case c == '-': 49 // Byte before dash cannot be dot. 50 if last == '.' { 51 return false 52 } 53 partlen++ 54 nonNumeric = true 55 case c == '.': 56 // Byte before dot cannot be dot, dash. 57 if last == '.' || last == '-' { 58 return false 59 } 60 if partlen > 63 || partlen == 0 { 61 return false 62 } 63 partlen = 0 64 } 65 last = c 66 } 67 if last == '-' || partlen > 63 { 68 return false 69 } 70 71 return nonNumeric 72 } 73 74 func IsValidHostnameOrIP(hostname string) bool { 75 return isValidIP(hostname) || isValidHostname(hostname) 76 }