ipsec.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. package layers
  7. import (
  8. "encoding/binary"
  9. "errors"
  10. "github.com/google/gopacket"
  11. )
  12. // IPSecAH is the authentication header for IPv4/6 defined in
  13. // http://tools.ietf.org/html/rfc2402
  14. type IPSecAH struct {
  15. // While the auth header can be used for both IPv4 and v6, its format is that of
  16. // an IPv6 extension (NextHeader, PayloadLength, etc...), so we use ipv6ExtensionBase
  17. // to build it.
  18. ipv6ExtensionBase
  19. Reserved uint16
  20. SPI, Seq uint32
  21. AuthenticationData []byte
  22. }
  23. // LayerType returns LayerTypeIPSecAH.
  24. func (i *IPSecAH) LayerType() gopacket.LayerType { return LayerTypeIPSecAH }
  25. func decodeIPSecAH(data []byte, p gopacket.PacketBuilder) error {
  26. if len(data) < 12 {
  27. p.SetTruncated()
  28. return errors.New("IPSec AH packet less than 12 bytes")
  29. }
  30. i := &IPSecAH{
  31. ipv6ExtensionBase: ipv6ExtensionBase{
  32. NextHeader: IPProtocol(data[0]),
  33. HeaderLength: data[1],
  34. },
  35. Reserved: binary.BigEndian.Uint16(data[2:4]),
  36. SPI: binary.BigEndian.Uint32(data[4:8]),
  37. Seq: binary.BigEndian.Uint32(data[8:12]),
  38. }
  39. i.ActualLength = (int(i.HeaderLength) + 2) * 4
  40. if len(data) < i.ActualLength {
  41. p.SetTruncated()
  42. return errors.New("Truncated AH packet < ActualLength")
  43. }
  44. i.AuthenticationData = data[12:i.ActualLength]
  45. i.Contents = data[:i.ActualLength]
  46. i.Payload = data[i.ActualLength:]
  47. p.AddLayer(i)
  48. return p.NextDecoder(i.NextHeader)
  49. }
  50. // IPSecESP is the encapsulating security payload defined in
  51. // http://tools.ietf.org/html/rfc2406
  52. type IPSecESP struct {
  53. BaseLayer
  54. SPI, Seq uint32
  55. // Encrypted contains the encrypted set of bytes sent in an ESP
  56. Encrypted []byte
  57. }
  58. // LayerType returns LayerTypeIPSecESP.
  59. func (i *IPSecESP) LayerType() gopacket.LayerType { return LayerTypeIPSecESP }
  60. func decodeIPSecESP(data []byte, p gopacket.PacketBuilder) error {
  61. i := &IPSecESP{
  62. BaseLayer: BaseLayer{data, nil},
  63. SPI: binary.BigEndian.Uint32(data[:4]),
  64. Seq: binary.BigEndian.Uint32(data[4:8]),
  65. Encrypted: data[8:],
  66. }
  67. p.AddLayer(i)
  68. return nil
  69. }