doc.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright 2012 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. /*
  7. Package gopacket provides packet decoding for the Go language.
  8. gopacket contains many sub-packages with additional functionality you may find
  9. useful, including:
  10. * layers: You'll probably use this every time. This contains of the logic
  11. built into gopacket for decoding packet protocols. Note that all example
  12. code below assumes that you have imported both gopacket and
  13. gopacket/layers.
  14. * pcap: C bindings to use libpcap to read packets off the wire.
  15. * pfring: C bindings to use PF_RING to read packets off the wire.
  16. * afpacket: C bindings for Linux's AF_PACKET to read packets off the wire.
  17. * tcpassembly: TCP stream reassembly
  18. Also, if you're looking to dive right into code, see the examples subdirectory
  19. for numerous simple binaries built using gopacket libraries.
  20. Minimum go version required is 1.5 except for pcapgo/EthernetHandle, afpacket,
  21. and bsdbpf which need at least 1.7 due to x/sys/unix dependencies.
  22. Basic Usage
  23. gopacket takes in packet data as a []byte and decodes it into a packet with
  24. a non-zero number of "layers". Each layer corresponds to a protocol
  25. within the bytes. Once a packet has been decoded, the layers of the packet
  26. can be requested from the packet.
  27. // Decode a packet
  28. packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default)
  29. // Get the TCP layer from this packet
  30. if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
  31. fmt.Println("This is a TCP packet!")
  32. // Get actual TCP data from this layer
  33. tcp, _ := tcpLayer.(*layers.TCP)
  34. fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
  35. }
  36. // Iterate over all layers, printing out each layer type
  37. for _, layer := range packet.Layers() {
  38. fmt.Println("PACKET LAYER:", layer.LayerType())
  39. }
  40. Packets can be decoded from a number of starting points. Many of our base
  41. types implement Decoder, which allow us to decode packets for which
  42. we don't have full data.
  43. // Decode an ethernet packet
  44. ethP := gopacket.NewPacket(p1, layers.LayerTypeEthernet, gopacket.Default)
  45. // Decode an IPv6 header and everything it contains
  46. ipP := gopacket.NewPacket(p2, layers.LayerTypeIPv6, gopacket.Default)
  47. // Decode a TCP header and its payload
  48. tcpP := gopacket.NewPacket(p3, layers.LayerTypeTCP, gopacket.Default)
  49. Reading Packets From A Source
  50. Most of the time, you won't just have a []byte of packet data lying around.
  51. Instead, you'll want to read packets in from somewhere (file, interface, etc)
  52. and process them. To do that, you'll want to build a PacketSource.
  53. First, you'll need to construct an object that implements the PacketDataSource
  54. interface. There are implementations of this interface bundled with gopacket
  55. in the gopacket/pcap and gopacket/pfring subpackages... see their documentation
  56. for more information on their usage. Once you have a PacketDataSource, you can
  57. pass it into NewPacketSource, along with a Decoder of your choice, to create
  58. a PacketSource.
  59. Once you have a PacketSource, you can read packets from it in multiple ways.
  60. See the docs for PacketSource for more details. The easiest method is the
  61. Packets function, which returns a channel, then asynchronously writes new
  62. packets into that channel, closing the channel if the packetSource hits an
  63. end-of-file.
  64. packetSource := ... // construct using pcap or pfring
  65. for packet := range packetSource.Packets() {
  66. handlePacket(packet) // do something with each packet
  67. }
  68. You can change the decoding options of the packetSource by setting fields in
  69. packetSource.DecodeOptions... see the following sections for more details.
  70. Lazy Decoding
  71. gopacket optionally decodes packet data lazily, meaning it
  72. only decodes a packet layer when it needs to handle a function call.
  73. // Create a packet, but don't actually decode anything yet
  74. packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
  75. // Now, decode the packet up to the first IPv4 layer found but no further.
  76. // If no IPv4 layer was found, the whole packet will be decoded looking for
  77. // it.
  78. ip4 := packet.Layer(layers.LayerTypeIPv4)
  79. // Decode all layers and return them. The layers up to the first IPv4 layer
  80. // are already decoded, and will not require decoding a second time.
  81. layers := packet.Layers()
  82. Lazily-decoded packets are not concurrency-safe. Since layers have not all been
  83. decoded, each call to Layer() or Layers() has the potential to mutate the packet
  84. in order to decode the next layer. If a packet is used
  85. in multiple goroutines concurrently, don't use gopacket.Lazy. Then gopacket
  86. will decode the packet fully, and all future function calls won't mutate the
  87. object.
  88. NoCopy Decoding
  89. By default, gopacket will copy the slice passed to NewPacket and store the
  90. copy within the packet, so future mutations to the bytes underlying the slice
  91. don't affect the packet and its layers. If you can guarantee that the
  92. underlying slice bytes won't be changed, you can use NoCopy to tell
  93. gopacket.NewPacket, and it'll use the passed-in slice itself.
  94. // This channel returns new byte slices, each of which points to a new
  95. // memory location that's guaranteed immutable for the duration of the
  96. // packet.
  97. for data := range myByteSliceChannel {
  98. p := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.NoCopy)
  99. doSomethingWithPacket(p)
  100. }
  101. The fastest method of decoding is to use both Lazy and NoCopy, but note from
  102. the many caveats above that for some implementations either or both may be
  103. dangerous.
  104. Pointers To Known Layers
  105. During decoding, certain layers are stored in the packet as well-known
  106. layer types. For example, IPv4 and IPv6 are both considered NetworkLayer
  107. layers, while TCP and UDP are both TransportLayer layers. We support 4
  108. layers, corresponding to the 4 layers of the TCP/IP layering scheme (roughly
  109. anagalous to layers 2, 3, 4, and 7 of the OSI model). To access these,
  110. you can use the packet.LinkLayer, packet.NetworkLayer,
  111. packet.TransportLayer, and packet.ApplicationLayer functions. Each of
  112. these functions returns a corresponding interface
  113. (gopacket.{Link,Network,Transport,Application}Layer). The first three
  114. provide methods for getting src/dst addresses for that particular layer,
  115. while the final layer provides a Payload function to get payload data.
  116. This is helpful, for example, to get payloads for all packets regardless
  117. of their underlying data type:
  118. // Get packets from some source
  119. for packet := range someSource {
  120. if app := packet.ApplicationLayer(); app != nil {
  121. if strings.Contains(string(app.Payload()), "magic string") {
  122. fmt.Println("Found magic string in a packet!")
  123. }
  124. }
  125. }
  126. A particularly useful layer is ErrorLayer, which is set whenever there's
  127. an error parsing part of the packet.
  128. packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default)
  129. if err := packet.ErrorLayer(); err != nil {
  130. fmt.Println("Error decoding some part of the packet:", err)
  131. }
  132. Note that we don't return an error from NewPacket because we may have decoded
  133. a number of layers successfully before running into our erroneous layer. You
  134. may still be able to get your Ethernet and IPv4 layers correctly, even if
  135. your TCP layer is malformed.
  136. Flow And Endpoint
  137. gopacket has two useful objects, Flow and Endpoint, for communicating in a protocol
  138. independent manner the fact that a packet is coming from A and going to B.
  139. The general layer types LinkLayer, NetworkLayer, and TransportLayer all provide
  140. methods for extracting their flow information, without worrying about the type
  141. of the underlying Layer.
  142. A Flow is a simple object made up of a set of two Endpoints, one source and one
  143. destination. It details the sender and receiver of the Layer of the Packet.
  144. An Endpoint is a hashable representation of a source or destination. For
  145. example, for LayerTypeIPv4, an Endpoint contains the IP address bytes for a v4
  146. IP packet. A Flow can be broken into Endpoints, and Endpoints can be combined
  147. into Flows:
  148. packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
  149. netFlow := packet.NetworkLayer().NetworkFlow()
  150. src, dst := netFlow.Endpoints()
  151. reverseFlow := gopacket.NewFlow(dst, src)
  152. Both Endpoint and Flow objects can be used as map keys, and the equality
  153. operator can compare them, so you can easily group together all packets
  154. based on endpoint criteria:
  155. flows := map[gopacket.Endpoint]chan gopacket.Packet
  156. packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy)
  157. // Send all TCP packets to channels based on their destination port.
  158. if tcp := packet.Layer(layers.LayerTypeTCP); tcp != nil {
  159. flows[tcp.TransportFlow().Dst()] <- packet
  160. }
  161. // Look for all packets with the same source and destination network address
  162. if net := packet.NetworkLayer(); net != nil {
  163. src, dst := net.NetworkFlow().Endpoints()
  164. if src == dst {
  165. fmt.Println("Fishy packet has same network source and dst: %s", src)
  166. }
  167. }
  168. // Find all packets coming from UDP port 1000 to UDP port 500
  169. interestingFlow := gopacket.FlowFromEndpoints(layers.NewUDPPortEndpoint(1000), layers.NewUDPPortEndpoint(500))
  170. if t := packet.NetworkLayer(); t != nil && t.TransportFlow() == interestingFlow {
  171. fmt.Println("Found that UDP flow I was looking for!")
  172. }
  173. For load-balancing purposes, both Flow and Endpoint have FastHash() functions,
  174. which provide quick, non-cryptographic hashes of their contents. Of particular
  175. importance is the fact that Flow FastHash() is symmetric: A->B will have the same
  176. hash as B->A. An example usage could be:
  177. channels := [8]chan gopacket.Packet
  178. for i := 0; i < 8; i++ {
  179. channels[i] = make(chan gopacket.Packet)
  180. go packetHandler(channels[i])
  181. }
  182. for packet := range getPackets() {
  183. if net := packet.NetworkLayer(); net != nil {
  184. channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet
  185. }
  186. }
  187. This allows us to split up a packet stream while still making sure that each
  188. stream sees all packets for a flow (and its bidirectional opposite).
  189. Implementing Your Own Decoder
  190. If your network has some strange encapsulation, you can implement your own
  191. decoder. In this example, we handle Ethernet packets which are encapsulated
  192. in a 4-byte header.
  193. // Create a layer type, should be unique and high, so it doesn't conflict,
  194. // giving it a name and a decoder to use.
  195. var MyLayerType = gopacket.RegisterLayerType(12345, gopacket.LayerTypeMetadata{Name: "MyLayerType", Decoder: gopacket.DecodeFunc(decodeMyLayer)})
  196. // Implement my layer
  197. type MyLayer struct {
  198. StrangeHeader []byte
  199. payload []byte
  200. }
  201. func (m MyLayer) LayerType() gopacket.LayerType { return MyLayerType }
  202. func (m MyLayer) LayerContents() []byte { return m.StrangeHeader }
  203. func (m MyLayer) LayerPayload() []byte { return m.payload }
  204. // Now implement a decoder... this one strips off the first 4 bytes of the
  205. // packet.
  206. func decodeMyLayer(data []byte, p gopacket.PacketBuilder) error {
  207. // Create my layer
  208. p.AddLayer(&MyLayer{data[:4], data[4:]})
  209. // Determine how to handle the rest of the packet
  210. return p.NextDecoder(layers.LayerTypeEthernet)
  211. }
  212. // Finally, decode your packets:
  213. p := gopacket.NewPacket(data, MyLayerType, gopacket.Lazy)
  214. See the docs for Decoder and PacketBuilder for more details on how coding
  215. decoders works, or look at RegisterLayerType and RegisterEndpointType to see how
  216. to add layer/endpoint types to gopacket.
  217. Fast Decoding With DecodingLayerParser
  218. TLDR: DecodingLayerParser takes about 10% of the time as NewPacket to decode
  219. packet data, but only for known packet stacks.
  220. Basic decoding using gopacket.NewPacket or PacketSource.Packets is somewhat slow
  221. due to its need to allocate a new packet and every respective layer. It's very
  222. versatile and can handle all known layer types, but sometimes you really only
  223. care about a specific set of layers regardless, so that versatility is wasted.
  224. DecodingLayerParser avoids memory allocation altogether by decoding packet
  225. layers directly into preallocated objects, which you can then reference to get
  226. the packet's information. A quick example:
  227. func main() {
  228. var eth layers.Ethernet
  229. var ip4 layers.IPv4
  230. var ip6 layers.IPv6
  231. var tcp layers.TCP
  232. parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp)
  233. decoded := []gopacket.LayerType{}
  234. for packetData := range somehowGetPacketData() {
  235. if err := parser.DecodeLayers(packetData, &decoded); err != nil {
  236. fmt.Fprintf(os.Stderr, "Could not decode layers: %v\n", err)
  237. continue
  238. }
  239. for _, layerType := range decoded {
  240. switch layerType {
  241. case layers.LayerTypeIPv6:
  242. fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP)
  243. case layers.LayerTypeIPv4:
  244. fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP)
  245. }
  246. }
  247. }
  248. }
  249. The important thing to note here is that the parser is modifying the passed in
  250. layers (eth, ip4, ip6, tcp) instead of allocating new ones, thus greatly
  251. speeding up the decoding process. It's even branching based on layer type...
  252. it'll handle an (eth, ip4, tcp) or (eth, ip6, tcp) stack. However, it won't
  253. handle any other type... since no other decoders were passed in, an (eth, ip4,
  254. udp) stack will stop decoding after ip4, and only pass back [LayerTypeEthernet,
  255. LayerTypeIPv4] through the 'decoded' slice (along with an error saying it can't
  256. decode a UDP packet).
  257. Unfortunately, not all layers can be used by DecodingLayerParser... only those
  258. implementing the DecodingLayer interface are usable. Also, it's possible to
  259. create DecodingLayers that are not themselves Layers... see
  260. layers.IPv6ExtensionSkipper for an example of this.
  261. Faster And Customized Decoding with DecodingLayerContainer
  262. By default, DecodingLayerParser uses native map to store and search for a layer
  263. to decode. Though being versatile, in some cases this solution may be not so
  264. optimal. For example, if you have only few layers faster operations may be
  265. provided by sparse array indexing or linear array scan.
  266. To accomodate these scenarios, DecodingLayerContainer interface is introduced
  267. along with its implementations: DecodingLayerSparse, DecodingLayerArray and
  268. DecodingLayerMap. You can specify a container implementation to
  269. DecodingLayerParser with SetDecodingLayerContainer method. Example:
  270. dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet)
  271. dlp.SetDecodingLayerContainer(gopacket.DecodingLayerSparse(nil))
  272. var eth layers.Ethernet
  273. dlp.AddDecodingLayer(&eth)
  274. // ... add layers and use DecodingLayerParser as usual...
  275. To skip one level of indirection (though sacrificing some capabilities) you may
  276. also use DecodingLayerContainer as a decoding tool as it is. In this case you have to
  277. handle unknown layer types and layer panics by yourself. Example:
  278. func main() {
  279. var eth layers.Ethernet
  280. var ip4 layers.IPv4
  281. var ip6 layers.IPv6
  282. var tcp layers.TCP
  283. dlc := gopacket.DecodingLayerContainer(gopacket.DecodingLayerArray(nil))
  284. dlc = dlc.Put(&eth)
  285. dlc = dlc.Put(&ip4)
  286. dlc = dlc.Put(&ip6)
  287. dlc = dlc.Put(&tcp)
  288. // you may specify some meaningful DecodeFeedback
  289. decoder := dlc.LayersDecoder(LayerTypeEthernet, gopacket.NilDecodeFeedback)
  290. decoded := make([]gopacket.LayerType, 0, 20)
  291. for packetData := range somehowGetPacketData() {
  292. lt, err := decoder(packetData, &decoded)
  293. if err != nil {
  294. fmt.Fprintf(os.Stderr, "Could not decode layers: %v\n", err)
  295. continue
  296. }
  297. if lt != gopacket.LayerTypeZero {
  298. fmt.Fprintf(os.Stderr, "unknown layer type: %v\n", lt)
  299. continue
  300. }
  301. for _, layerType := range decoded {
  302. // examine decoded layertypes just as already shown above
  303. }
  304. }
  305. }
  306. DecodingLayerSparse is the fastest but most effective when LayerType values
  307. that layers in use can decode are not large because otherwise that would lead
  308. to bigger memory footprint. DecodingLayerArray is very compact and primarily
  309. usable if the number of decoding layers is not big (up to ~10-15, but please do
  310. your own benchmarks). DecodingLayerMap is the most versatile one and used by
  311. DecodingLayerParser by default. Please refer to tests and benchmarks in layers
  312. subpackage to further examine usage examples and performance measurements.
  313. You may also choose to implement your own DecodingLayerContainer if you want to
  314. make use of your own internal packet decoding logic.
  315. Creating Packet Data
  316. As well as offering the ability to decode packet data, gopacket will allow you
  317. to create packets from scratch, as well. A number of gopacket layers implement
  318. the SerializableLayer interface; these layers can be serialized to a []byte in
  319. the following manner:
  320. ip := &layers.IPv4{
  321. SrcIP: net.IP{1, 2, 3, 4},
  322. DstIP: net.IP{5, 6, 7, 8},
  323. // etc...
  324. }
  325. buf := gopacket.NewSerializeBuffer()
  326. opts := gopacket.SerializeOptions{} // See SerializeOptions for more details.
  327. err := ip.SerializeTo(buf, opts)
  328. if err != nil { panic(err) }
  329. fmt.Println(buf.Bytes()) // prints out a byte slice containing the serialized IPv4 layer.
  330. SerializeTo PREPENDS the given layer onto the SerializeBuffer, and they treat
  331. the current buffer's Bytes() slice as the payload of the serializing layer.
  332. Therefore, you can serialize an entire packet by serializing a set of layers in
  333. reverse order (Payload, then TCP, then IP, then Ethernet, for example). The
  334. SerializeBuffer's SerializeLayers function is a helper that does exactly that.
  335. To generate a (empty and useless, because no fields are set)
  336. Ethernet(IPv4(TCP(Payload))) packet, for example, you can run:
  337. buf := gopacket.NewSerializeBuffer()
  338. opts := gopacket.SerializeOptions{}
  339. gopacket.SerializeLayers(buf, opts,
  340. &layers.Ethernet{},
  341. &layers.IPv4{},
  342. &layers.TCP{},
  343. gopacket.Payload([]byte{1, 2, 3, 4}))
  344. packetData := buf.Bytes()
  345. A Final Note
  346. If you use gopacket, you'll almost definitely want to make sure gopacket/layers
  347. is imported, since when imported it sets all the LayerType variables and fills
  348. in a lot of interesting variables/maps (DecodersByLayerName, etc). Therefore,
  349. it's recommended that even if you don't use any layers functions directly, you still import with:
  350. import (
  351. _ "github.com/google/gopacket/layers"
  352. )
  353. */
  354. package gopacket