github.com/zartbot/goflow@v0.0.0-20221001080520-456f7dfad288/service/flowinfo/lib.go (about) 1 package flowinfo 2 3 import ( 4 "crypto/md5" 5 "encoding/binary" 6 "encoding/hex" 7 "fmt" 8 "net" 9 10 "github.com/zartbot/goflow/lib/iputil" 11 ) 12 13 /* 14 var FlowTable ksyncmap.Map 15 16 func init() { 17 FlowTable.CheckFreq = 10 18 FlowTable.Timeout = 20 19 go FlowTable.Run() 20 } 21 */ 22 23 /* FlowInfo used mark flow 24 in many Netflow/IPFIX implementation may use multiple field 25 mark the SRC/DST IPAddr or Connection Initial/Response Addr 26 it's very hard for future flow correlation. 27 This package is trying to compare address pair ,and use the 28 inner address in IPAddress_A ,outer in IPAddressB */ 29 30 func ip2int(ip net.IP) uint32 { 31 if len(ip) == 16 { 32 return binary.BigEndian.Uint32(ip[12:16]) 33 } 34 return binary.BigEndian.Uint32(ip) 35 } 36 37 func Less(IPA net.IP, PortA uint16, IPB net.IP, PortB uint16) bool { 38 a := ip2int(IPA) 39 b := ip2int(IPB) 40 41 if a < b { 42 return true 43 } else if a > b { 44 return false 45 } else { 46 // should not be IPA == IPB case in NF record, but still 47 // write code here to handle this case. 48 if PortA < PortB { 49 return true 50 } else { 51 return false 52 } 53 } 54 } 55 56 func GetMD5Hash(text string) string { 57 hasher := md5.New() 58 hasher.Write([]byte(text)) 59 return hex.EncodeToString(hasher.Sum(nil)) 60 } 61 62 func NewFlowInfo(IPA net.IP, PortA uint16, IPB net.IP, PortB uint16) iputil.FlowInfo { 63 var f iputil.FlowInfo 64 f.Direction = Less(IPA, PortA, IPB, PortB) 65 if f.Direction { 66 f.FlowID = fmt.Sprintf("%s-%s", IPA, IPB) 67 f.FlowIDWithPort = fmt.Sprintf("%s:%d-%s:%d", IPA, PortA, IPB, PortB) 68 69 } else { 70 f.FlowID = fmt.Sprintf("%s-%s", IPB, IPA) 71 f.FlowIDWithPort = fmt.Sprintf("%s:%d-%s:%d", IPB, PortB, IPA, PortA) 72 73 } 74 //this field used to find user/server identity(Geo/DNS/uid...),especially to handle NAT case 75 //src in flowbased, client in conn based.. 76 f.IPAddress_A = IPA 77 f.Port_A = PortA 78 //dst in flowbased, server in conn based.. 79 f.IPAddress_B = IPB 80 f.Port_B = PortB 81 return f 82 }