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