pflog.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "fmt"
  11. "github.com/google/gopacket"
  12. )
  13. type PFDirection uint8
  14. const (
  15. PFDirectionInOut PFDirection = 0
  16. PFDirectionIn PFDirection = 1
  17. PFDirectionOut PFDirection = 2
  18. )
  19. // PFLog provides the layer for 'pf' packet-filter logging, as described at
  20. // http://www.freebsd.org/cgi/man.cgi?query=pflog&sektion=4
  21. type PFLog struct {
  22. BaseLayer
  23. Length uint8
  24. Family ProtocolFamily
  25. Action, Reason uint8
  26. IFName, Ruleset []byte
  27. RuleNum, SubruleNum uint32
  28. UID uint32
  29. PID int32
  30. RuleUID uint32
  31. RulePID int32
  32. Direction PFDirection
  33. // The remainder is padding
  34. }
  35. func (pf *PFLog) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  36. if len(data) < 60 {
  37. df.SetTruncated()
  38. return errors.New("PFLog data less than 60 bytes")
  39. }
  40. pf.Length = data[0]
  41. pf.Family = ProtocolFamily(data[1])
  42. pf.Action = data[2]
  43. pf.Reason = data[3]
  44. pf.IFName = data[4:20]
  45. pf.Ruleset = data[20:36]
  46. pf.RuleNum = binary.BigEndian.Uint32(data[36:40])
  47. pf.SubruleNum = binary.BigEndian.Uint32(data[40:44])
  48. pf.UID = binary.BigEndian.Uint32(data[44:48])
  49. pf.PID = int32(binary.BigEndian.Uint32(data[48:52]))
  50. pf.RuleUID = binary.BigEndian.Uint32(data[52:56])
  51. pf.RulePID = int32(binary.BigEndian.Uint32(data[56:60]))
  52. pf.Direction = PFDirection(data[60])
  53. if pf.Length%4 != 1 {
  54. return errors.New("PFLog header length should be 3 less than multiple of 4")
  55. }
  56. actualLength := int(pf.Length) + 3
  57. if len(data) < actualLength {
  58. return fmt.Errorf("PFLog data size < %d", actualLength)
  59. }
  60. pf.Contents = data[:actualLength]
  61. pf.Payload = data[actualLength:]
  62. return nil
  63. }
  64. // LayerType returns layers.LayerTypePFLog
  65. func (pf *PFLog) LayerType() gopacket.LayerType { return LayerTypePFLog }
  66. func (pf *PFLog) CanDecode() gopacket.LayerClass { return LayerTypePFLog }
  67. func (pf *PFLog) NextLayerType() gopacket.LayerType {
  68. return pf.Family.LayerType()
  69. }
  70. func decodePFLog(data []byte, p gopacket.PacketBuilder) error {
  71. pf := &PFLog{}
  72. return decodingLayerDecoder(pf, data, p)
  73. }