Mining/pkg/ueps/reader.go
Claude 89e70a4449
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
ax(ueps): eliminate duplicated HMAC buffer writes in ReadAndVerify switch
The switch in ReadAndVerify duplicated the same three hmacInputBuffer.WriteByte/Write
calls across five cases plus default. Extracted to a single conditional after the switch:
all tags except TagHMAC feed the authenticated input buffer. Behaviour is identical;
declarative intent is now clear (AX principle 5 — declarative over imperative).

Co-Authored-By: Charon <charon@lethean.io>
2026-04-02 14:15:06 +01:00

103 lines
2.9 KiB
Go

package ueps
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"io"
)
// packet, err := ReadAndVerify(bufio.NewReader(conn), secret)
// if err == errMissingHMAC { /* no HMAC tag found in frame */ }
var errMissingHMAC = sentinelError("UEPS packet missing HMAC signature")
// packet, err := ReadAndVerify(bufio.NewReader(conn), wrongSecret)
// if err == errIntegrityViolation { header.ThreatScore += 100; /* reject packet */ }
var errIntegrityViolation = sentinelError("integrity violation: HMAC mismatch")
// dispatch(packet.Header.IntentID, packet.Header.ThreatScore, packet.Payload)
type ParsedPacket struct {
Header UEPSHeader // packet.Header.Version == 0x09; packet.Header.IntentID == 0x01; packet.Header.ThreatScore == 0
Payload []byte // packet.Payload == []byte("hello world")
}
// packet, err := ueps.ReadAndVerify(bufio.NewReader(conn), []byte("my-shared-secret"))
// if err == errMissingHMAC { return } // unauthenticated: no HMAC tag in stream
// if err == errIntegrityViolation { return } // tampered: HMAC mismatch; reject and raise threat score
// if err == nil { dispatch(packet.Header.IntentID, packet.Header.ThreatScore, packet.Payload) }
func ReadAndVerify(reader *bufio.Reader, sharedSecret []byte) (*ParsedPacket, error) {
var (
hmacInputBuffer bytes.Buffer
packetHeader UEPSHeader
hmacSignature []byte
payload []byte
)
for {
tagType, err := reader.ReadByte()
if err != nil {
return nil, err
}
if tagType == TagPayload {
payload, err = io.ReadAll(reader)
if err != nil {
return nil, err
}
break
}
tagLength, err := reader.ReadByte()
if err != nil {
return nil, err
}
tagValue := make([]byte, int(tagLength))
if _, err := io.ReadFull(reader, tagValue); err != nil {
return nil, err
}
switch tagType {
case TagVersion:
packetHeader.Version = tagValue[0]
case TagCurrentLayer:
packetHeader.CurrentLayer = tagValue[0]
case TagTargetLayer:
packetHeader.TargetLayer = tagValue[0]
case TagIntent:
packetHeader.IntentID = tagValue[0]
case TagThreatScore:
packetHeader.ThreatScore = binary.BigEndian.Uint16(tagValue)
case TagHMAC:
hmacSignature = tagValue
}
// All tags except TagHMAC contribute to the authenticated input;
// hmacInputBuffer.Write(tagBytes) covers header TLVs and unknown extension tags.
if tagType != TagHMAC {
hmacInputBuffer.WriteByte(tagType)
hmacInputBuffer.WriteByte(tagLength)
hmacInputBuffer.Write(tagValue)
}
}
if len(hmacSignature) == 0 {
return nil, errMissingHMAC
}
messageAuthCode := hmac.New(sha256.New, sharedSecret)
messageAuthCode.Write(hmacInputBuffer.Bytes())
messageAuthCode.Write(payload)
expectedMessageAuthCode := messageAuthCode.Sum(nil)
if !hmac.Equal(hmacSignature, expectedMessageAuthCode) {
return nil, errIntegrityViolation
}
return &ParsedPacket{
Header: packetHeader,
Payload: payload,
}, nil
}