doc.go 15 KB

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