wireguard-go-awg2-lx/device/magic-header.go
Leadaxe ee7ff1b77f lx: fix transport padding buffer overrun + harden AWG config guards
Transport padding (s4) crashed the whole process with
"index out of range" in RoutineSequentialSender on the first data
packet: InputPacket/InputPackets sized elem.buffer without headroom
for the in-buffer right-shift that prepends the random prefix.

- send.go: reserve paddings.transport in both injection-path
  allocLength computations; replace the manual backward byte loop
  with an overlap-safe copy; defensively grow the buffer (pool-backed)
  if it still lacks headroom, dropping packets that cannot fit a
  single WG message instead of overrunning.
- receive.go: drop the rxBytes/timers block duplicated by the AWG
  re-graft (rx accounting was doubled, keepKeyFreshReceiving fired
  twice per batch).
- send.go: swap jmin/jmax when configured inverted (UAPI validates
  the fields only individually; a swapped pair panicked rand.Int
  with a non-positive bound on the first handshake).
- obf*.go: bound obfuscator length args to [0, MaxMessageSize]
  (negative panicked slice bounds, huge ones OOMed the handshake).
- magic-header.go: widen to int64 before end-start+1 so a full-range
  header cannot wrap to a zero rand.Int bound.

Tests: transport_padding_test.go reproduces the on-device crash
byte-for-byte (red on the previous commit, green now) across both
injection paths and the tun path; obf_guards_test.go pins the
config-value guards.
2026-08-05 16:55:02 +03:00

65 lines
1.3 KiB
Go

package device
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
)
type magicHeader struct {
start uint32
end uint32
}
func newMagicHeader(spec string) (*magicHeader, error) {
parts := strings.Split(spec, "-")
if len(parts) < 1 || len(parts) > 2 {
return nil, errors.New("bad format")
}
start, err := strconv.ParseUint(parts[0], 10, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", parts[0], err)
}
var end uint64
if len(parts) > 1 {
end, err = strconv.ParseUint(parts[1], 10, 32)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", parts[1], err)
}
} else {
end = start
}
if end < start {
return nil, errors.New("wrong range specified")
}
return &magicHeader{
start: uint32(start),
end: uint32(end),
}, nil
}
func (h *magicHeader) GenSpec() string {
if h.start == h.end {
return fmt.Sprintf("%d", h.start)
}
return fmt.Sprintf("%d-%d", h.start, h.end)
}
func (h *magicHeader) Validate(val uint32) bool {
return h.start <= val && val <= h.end
}
func (h *magicHeader) Generate() uint32 {
// Widen before arithmetic: end-start+1 in uint32 wraps to 0 for the
// full 0..2^32-1 range, which would panic rand.Int (bound <= 0).
high := int64(h.end) - int64(h.start) + 1
r, _ := rand.Int(rand.Reader, big.NewInt(high))
return h.start + uint32(r.Int64())
}