protobuf

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Decoder = &decoder.StreamDecoder{
	Type:        types.Type_NC_Protobuf,
	Name:        "Protobuf",
	Description: "Generic Protocol Buffer wire format decoder for unknown protobuf traffic",
	PostInit: func(sd *decoder.StreamDecoder) error {
		var err error
		pbLog, _, err = logging.InitZapLogger(
			decoderconfig.Instance.Out,
			"protobuf",
			decoderconfig.Instance.Debug,
		)
		if err != nil {
			return err
		}

		if decoderconfig.Instance.ProtoShowAlternatives {
			SetShowAlternatives(true)
		}

		if len(decoderconfig.Instance.ProtoSearchPaths) > 0 {
			registry, rErr := NewSchemaRegistry(decoderconfig.Instance.ProtoSearchPaths)
			if rErr != nil {
				pbLog.Warn("failed to initialize proto schema registry", zap.Error(rErr))
			} else {
				SetSchemaRegistry(registry)
				pbLog.Info("proto schema registry initialized",
					zap.Int("files", registry.FileCount()),
					zap.Int("messages", registry.MessageCount()),
				)
			}
		}

		if len(decoderconfig.Instance.ProtoMessageTypes) > 0 {
			ParseMessageTypeMappings(decoderconfig.Instance.ProtoMessageTypes)
		}

		return nil
	},

	Specificity: core.SpecificityHeuristic,

	CanDecode: func(client, server []byte) bool {
		return IsProtobufData(client) || IsProtobufData(server)
	},
	DeInit: func(sd *decoder.StreamDecoder) error {
		return pbLog.Sync()
	},
	Factory: &protobufReader{},
	Typ:     core.All,
}

Decoder for generic Protocol Buffer wire format detection and analysis.

Functions

func CalculateEntropy

func CalculateEntropy(data []byte) float64

CalculateEntropy computes Shannon entropy of the data in bits.

func DecodeMessages

func DecodeMessages(data []byte) ([][]Field, error)

DecodeMessages attempts to decode one or more protobuf messages from raw bytes.

func DetectMessageType

func DetectMessageType(fields []Field) string

DetectMessageType classifies a decoded message based on field patterns.

func DetectServiceName

func DetectServiceName(srcPort, dstPort int32) string

DetectServiceName guesses the service type from port numbers.

func IsPrintable

func IsPrintable(data []byte) bool

IsPrintable returns true if all bytes are printable ASCII.

func IsProtobufData

func IsProtobufData(data []byte) bool

IsProtobufData uses heuristics to detect if data might be protobuf encoded. It requires a structurally valid opening tag, then applies byte statistics: varint continuation patterns, wire type spread, and sufficient entropy to distinguish from text protocols.

The statistics alone are a weak signature and were the sole test until 2026-09-22. They reduce to "contains a byte >= 0x80 and has entropy above 3.0", which uniform random bytes of length >= 12 satisfy essentially always, so this decoder adopted any unrecognised binary conversation it was offered. Because it registers as core.All it takes part in every UDP fallback scan, and it was producing Protobuf audit records for NetBIOS Name Service and DNS traffic -- 20 of them across the test corpus, every one unparseable.

Raising the entropy threshold cannot fix that: the tightest payload this must still accept measures 3.278 bits and the lowest observed false positive 3.521, which is no margin at all. Validating the tag is what separates them.

func ParseMessageTypeMappings

func ParseMessageTypeMappings(mappings []string)

ParseMessageTypeMappings parses "port:MessageType" strings into portMessageTypes.

func PopulateFields

func PopulateFields(fields []Field, out map[string]string, order *[]string)

PopulateFields converts ordered decoded fields into the audit record's Fields map (keyed as "type_fieldnum") and FieldOrder slice (preserving wire order). Alternative interpretations are NOT stored here — they go into the dedicated FieldAlternatives map in processData.

func ReadVarint

func ReadVarint(buf *bytes.Reader) (uint64, error)

ReadVarint reads a varint-encoded uint64 from the reader.

func ResolveFields

func ResolveFields(fields []Field, md protoreflect.MessageDescriptor) map[string]string

ResolveFields takes raw wire-format fields and a message descriptor, and returns a map of named fields with their values. Unknown field numbers (not in schema) are kept with their wire-format keys.

func SetSchemaRegistry

func SetSchemaRegistry(r *SchemaRegistry)

SetSchemaRegistry sets the global schema registry in a thread-safe manner.

func SetShowAlternatives

func SetShowAlternatives(enabled bool)

SetShowAlternatives enables or disables multi-interpretation mode.

Types

type EnumValueInfo

type EnumValueInfo struct {
	Name   string `json:"name"`
	Number int    `json:"number"`
}

EnumValueInfo describes a single enum value.

type Field

type Field struct {
	Number       uint64            // protobuf field number
	Type         string            // "varint", "fixed64", "string", "bytes", "nested", "fixed32", "packed_varint", "packed_fixed32", "packed_fixed64"
	Value        string            // string representation of the value
	Alternatives map[string]string // alternative interpretations keyed by type name (e.g. "sint64", "double", "bool")
}

Field represents a single decoded protobuf field, preserving wire order.

func ParseMessage

func ParseMessage(buf *bytes.Reader) ([]Field, error)

ParseMessage parses a single protobuf message from a reader. Returns fields in wire order.

type FieldInfo

type FieldInfo struct {
	Name       string          `json:"name"`
	Number     int             `json:"number"`
	Type       string          `json:"type"`
	Label      string          `json:"label"`
	TypeName   string          `json:"typeName,omitempty"`
	EnumValues []EnumValueInfo `json:"enumValues,omitempty"`
}

FieldInfo describes a single field within a message.

type MessageInfo

type MessageInfo struct {
	FullName  string      `json:"fullName"`
	Package   string      `json:"package"`
	Name      string      `json:"name"`
	ProtoFile string      `json:"protoFile"`
	Fields    []FieldInfo `json:"fields"`
}

MessageInfo describes a protobuf message type for API responses.

type SchemaRegistry

type SchemaRegistry struct {
	// contains filtered or unexported fields
}

SchemaRegistry holds compiled .proto file descriptors and provides message/field lookup by fully qualified name.

func GetSchemaRegistry

func GetSchemaRegistry() *SchemaRegistry

GetSchemaRegistry returns the global schema registry in a thread-safe manner.

func NewSchemaRegistry

func NewSchemaRegistry(searchPaths []string) (*SchemaRegistry, error)

NewSchemaRegistry creates a schema registry by compiling all .proto files found in the given search paths. Import resolution follows the same semantics as protoc: each search path is a root for import resolution.

func (*SchemaRegistry) FileCount

func (r *SchemaRegistry) FileCount() int

FileCount returns the number of compiled .proto files.

func (*SchemaRegistry) ListMessages

func (r *SchemaRegistry) ListMessages() []MessageInfo

ListMessages returns information about all indexed message types.

func (*SchemaRegistry) LookupMessage

func (r *SchemaRegistry) LookupMessage(fullName string) (protoreflect.MessageDescriptor, bool)

LookupMessage returns the message descriptor for a fully qualified name.

func (*SchemaRegistry) MessageCount

func (r *SchemaRegistry) MessageCount() int

MessageCount returns the number of indexed message types.

func (*SchemaRegistry) MessageNames

func (r *SchemaRegistry) MessageNames() []string

MessageNames returns all fully qualified message names.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL