mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 07:24:19 +00:00
Poll firmware from 2026-12-03 signs corescope-reading/v2 and corescope-claim/v2, which add poll_key, access and key, and sends requested as false for an own target. Those were all dropped. v1 still verifies, for a message with none of the new fields. reply_hops may now be left out.
331 lines
10 KiB
Go
331 lines
10 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package polling
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/ed25519"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"math"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// ErrReadingSignature marks a reading message whose signature is present and does not check out.
|
|
var ErrReadingSignature = errors.New("readings: signature does not check out")
|
|
|
|
const (
|
|
readingSigPrefix = "corescope-reading/v2"
|
|
readingSigPrefixV1 = "corescope-reading/v1"
|
|
)
|
|
|
|
// What a login can be granted, and what a reading's login presented.
|
|
var (
|
|
signedAccess = map[string]bool{"guest": true, "read_only": true, "read_write": true}
|
|
signedReadingKeys = map[string]bool{"own": true, "password": true}
|
|
)
|
|
|
|
var (
|
|
sigIntRe = regexp.MustCompile(`^(0|-?[1-9][0-9]*)$`)
|
|
sigTimeRe = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}\+00:00$`)
|
|
sigHexRe = regexp.MustCompile(`^([0-9a-fA-F]{2})*$`)
|
|
)
|
|
|
|
// The status fields a signed reading may carry.
|
|
var signedStatNames = map[string]bool{
|
|
"uptime_secs": true, "noise_floor": true, "last_rssi": true, "last_snr": true, "tx_queue": true,
|
|
"packets_recv": true, "packets_sent": true, "recv_flood": true, "recv_direct": true, "sent_flood": true,
|
|
"sent_direct": true, "tx_air_secs": true, "rx_air_secs": true, "flood_dups": true, "direct_dups": true,
|
|
"recv_errors": true, "err_events": true,
|
|
}
|
|
|
|
// checkReadingSignature reports whether a reading message is signed, and what it says of requested: nil when it is
|
|
// unsigned or signed by firmware older than the flag. One without "sig" is not signed, and is handled as before. One with it must hold exactly one reading and verify against the observer's key over
|
|
//
|
|
// corescope-reading/v2|v|origin_id|timestamp|node_id|method|sampled_at|battery_mv|temperature_c x10|snr x10|
|
|
// rssi|reply_hops|tag|packet_hash|lpp|stats|requested|poll_key|access|key
|
|
//
|
|
// built from the fields as sent: ids and hex in lowercase, an absent field as the empty string, numbers as
|
|
// integers, stats as name=value sorted by name with last_snr x100, and requested as 1 or 0. The shapes are checked
|
|
// first, so no field can carry a separator and the line reads one way only.
|
|
// Poll firmware before 2026-12-03 signs corescope-reading/v1, which ends at requested (1 or empty), and before
|
|
// 2026-12-01 without that part. Those are tried only for a reading with no poll_key, access, key or requested
|
|
// false, so none of them can be added to an old reading unsigned.
|
|
func checkReadingSignature(raw []byte, observer []byte) (bool, *bool, error) {
|
|
var top map[string]json.RawMessage
|
|
if json.Unmarshal(raw, &top) != nil {
|
|
return false, nil, nil // not an object: the ordinary parse reports it
|
|
}
|
|
if _, has := top["sig"]; !has {
|
|
return false, nil, nil
|
|
}
|
|
bad := func() (bool, *bool, error) { return false, nil, ErrReadingSignature }
|
|
if hasDuplicateKeys(raw) {
|
|
return bad()
|
|
}
|
|
// A reading is not also a claim or a key binding.
|
|
if _, has := top["nodes"]; has {
|
|
return bad()
|
|
}
|
|
if _, has := top["poll_key_sig"]; has {
|
|
return bad()
|
|
}
|
|
sigHex, ok := sigString(top["sig"])
|
|
sig, err := hex.DecodeString(sigHex)
|
|
if !ok || err != nil || len(sig) != ed25519.SignatureSize {
|
|
return bad()
|
|
}
|
|
v := string(top["v"])
|
|
originID, ok1 := sigString(top["origin_id"])
|
|
stamp, ok2 := sigString(top["timestamp"])
|
|
if (v != "1" && v != "2") || !ok1 || !ok2 || !sigTimeRe.MatchString(stamp) {
|
|
return bad()
|
|
}
|
|
var readings []map[string]json.RawMessage
|
|
if json.Unmarshal(top["readings"], &readings) != nil || len(readings) != 1 || readings[0] == nil {
|
|
return bad()
|
|
}
|
|
r := readings[0]
|
|
nodeID, ok1 := sigString(r["node_id"])
|
|
method, ok2 := sigString(r["method"])
|
|
sampled, ok3 := sigString(r["sampled_at"])
|
|
// A poller that cannot see the hop count leaves reply_hops out.
|
|
hops, hasHops := "", false
|
|
if rawHops, has := r["reply_hops"]; has {
|
|
hops, hasHops = string(rawHops), true
|
|
}
|
|
if !ok1 || !ok2 || !ok3 || len(nodeID) != 64 || !sigHexRe.MatchString(nodeID) || (method != "status" && method != "telemetry") ||
|
|
!sigTimeRe.MatchString(sampled) || (hasHops && (!sigIntRe.MatchString(hops) || strings.HasPrefix(hops, "-"))) {
|
|
return bad()
|
|
}
|
|
parts := []string{"", v, strings.ToLower(originID), stamp, strings.ToLower(nodeID), method, sampled}
|
|
// battery_mv, then the two scaled numbers, then rssi.
|
|
for _, f := range []struct {
|
|
key string
|
|
scale float64
|
|
}{{"battery_mv", 0}, {"temperature_c", 10}, {"snr", 10}, {"rssi", 0}} {
|
|
s, ok := sigNumber(r, f.key, f.scale)
|
|
if !ok {
|
|
return bad()
|
|
}
|
|
parts = append(parts, s)
|
|
}
|
|
if v == "1" && parts[7] == "" {
|
|
return bad()
|
|
}
|
|
tag, ok := sigNumber(r, "tag", 0)
|
|
if !ok {
|
|
return bad()
|
|
}
|
|
parts = append(parts, hops, tag)
|
|
for _, f := range []struct {
|
|
key string
|
|
len int // exact hex length, 0 for any
|
|
}{{"packet_hash", 16}, {"lpp", 0}} {
|
|
s := ""
|
|
if rawv, has := r[f.key]; has {
|
|
if s, ok = sigString(rawv); !ok || !sigHexRe.MatchString(s) || (f.len > 0 && len(s) != f.len) {
|
|
return bad()
|
|
}
|
|
}
|
|
parts = append(parts, strings.ToLower(s))
|
|
}
|
|
stats := ""
|
|
if rawStats, has := r["stats"]; has {
|
|
var m map[string]json.RawMessage
|
|
if json.Unmarshal(rawStats, &m) != nil || m == nil {
|
|
return bad()
|
|
}
|
|
names := make([]string, 0, len(m))
|
|
for name := range m {
|
|
if !signedStatNames[name] {
|
|
return bad()
|
|
}
|
|
names = append(names, name)
|
|
}
|
|
sort.Strings(names)
|
|
pairs := make([]string, 0, len(names))
|
|
for _, name := range names {
|
|
scale := 0.0
|
|
if name == "last_snr" {
|
|
scale = 100
|
|
}
|
|
s, ok := sigNumber(m, name, scale)
|
|
if !ok || s == "" {
|
|
return bad()
|
|
}
|
|
pairs = append(pairs, name+"="+s)
|
|
}
|
|
stats = strings.Join(pairs, ",")
|
|
}
|
|
parts = append(parts, stats)
|
|
// requested is 1, 0 or absent. Before v2 it was 1 or absent.
|
|
requested := ""
|
|
if rawReq, has := r["requested"]; has {
|
|
switch string(rawReq) {
|
|
case "true":
|
|
requested = "1"
|
|
case "false":
|
|
requested = "0"
|
|
default:
|
|
return bad()
|
|
}
|
|
}
|
|
pollKey, hasPollKey := "", false
|
|
if rawKey, has := r["poll_key"]; has {
|
|
if pollKey, ok = sigString(rawKey); !ok || len(pollKey) != 64 || !sigHexRe.MatchString(pollKey) {
|
|
return bad()
|
|
}
|
|
hasPollKey = true
|
|
}
|
|
rawAccess, hasAccess := r["access"]
|
|
rawKeyMode, hasKeyMode := r["key"]
|
|
access, keyMode := "", ""
|
|
if hasAccess != hasKeyMode {
|
|
return bad()
|
|
}
|
|
if hasAccess {
|
|
var ok1, ok2 bool
|
|
access, ok1 = sigString(rawAccess)
|
|
keyMode, ok2 = sigString(rawKeyMode)
|
|
if !ok1 || !ok2 || !signedAccess[access] || !signedReadingKeys[keyMode] {
|
|
return bad()
|
|
}
|
|
}
|
|
key := ed25519.PublicKey(observer)
|
|
line := func(prefix string, more ...string) []byte {
|
|
parts[0] = prefix
|
|
return []byte(strings.Join(append(parts[:len(parts):len(parts)], more...), "|"))
|
|
}
|
|
said := func() *bool {
|
|
if requested == "" {
|
|
return nil
|
|
}
|
|
b := requested == "1"
|
|
return &b
|
|
}
|
|
if ed25519.Verify(key, line(readingSigPrefix, requested, strings.ToLower(pollKey), access, keyMode), sig) {
|
|
return true, said(), nil
|
|
}
|
|
if requested == "0" || hasPollKey || hasAccess {
|
|
return bad()
|
|
}
|
|
// v1 writes an own target as an empty part, so a reading that verifies here does say.
|
|
if ed25519.Verify(key, line(readingSigPrefixV1, requested), sig) {
|
|
own := requested == "1"
|
|
return true, &own, nil
|
|
}
|
|
// The line of the earliest poll firmware, which has no requested part.
|
|
if requested == "" && ed25519.Verify(key, line(readingSigPrefixV1), sig) {
|
|
return true, nil, nil
|
|
}
|
|
return bad()
|
|
}
|
|
|
|
// sigString reads a JSON string; null and anything else is not one.
|
|
func sigString(raw json.RawMessage) (string, bool) {
|
|
if len(raw) == 0 || raw[0] != '"' {
|
|
return "", false
|
|
}
|
|
var s string
|
|
if json.Unmarshal(raw, &s) != nil {
|
|
return "", false
|
|
}
|
|
return s, true
|
|
}
|
|
|
|
// sigNumber is how a number enters a signed line: "" when the key is absent; an integer as sent when scale is 0;
|
|
// otherwise the value times scale, which must come out whole, since anything finer could be moved inside one
|
|
// rounding step without breaking the signature.
|
|
func sigNumber(obj map[string]json.RawMessage, key string, scale float64) (string, bool) {
|
|
raw, has := obj[key]
|
|
if !has {
|
|
return "", true
|
|
}
|
|
tok := string(raw)
|
|
if scale == 0 {
|
|
return tok, sigIntRe.MatchString(tok)
|
|
}
|
|
if len(tok) == 0 || tok[0] == '"' || tok == "null" || tok == "true" || tok == "false" {
|
|
return "", false
|
|
}
|
|
f, err := strconv.ParseFloat(tok, 64)
|
|
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || math.Abs(f) > 1e9 {
|
|
return "", false
|
|
}
|
|
scaled := f * scale
|
|
whole := math.RoundToEven(scaled)
|
|
if math.Abs(scaled-whole) > 1e-6 {
|
|
return "", false
|
|
}
|
|
return strconv.FormatInt(int64(whole), 10), true
|
|
}
|
|
|
|
// hasDuplicateKeys reports whether any object in the JSON text names a key twice, or one that is not plain
|
|
// lowercase. Go keeps the last of two; another parser may keep the first, so two readers could see different values.
|
|
func hasDuplicateKeys(raw []byte) bool {
|
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
type frame struct {
|
|
object bool
|
|
keys map[string]bool
|
|
isKey bool // the next string token in an object is a key
|
|
}
|
|
var stack []*frame
|
|
for {
|
|
tok, err := dec.Token()
|
|
if err == io.EOF {
|
|
return false
|
|
}
|
|
if err != nil {
|
|
return false // malformed: the ordinary parse reports it
|
|
}
|
|
top := func() *frame {
|
|
if len(stack) == 0 {
|
|
return nil
|
|
}
|
|
return stack[len(stack)-1]
|
|
}
|
|
if d, ok := tok.(json.Delim); ok {
|
|
switch d {
|
|
case '{':
|
|
stack = append(stack, &frame{object: true, keys: map[string]bool{}, isKey: true})
|
|
case '[':
|
|
stack = append(stack, &frame{})
|
|
case '}', ']':
|
|
stack = stack[:len(stack)-1]
|
|
if f := top(); f != nil && f.object {
|
|
f.isKey = true
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
f := top()
|
|
if f == nil || !f.object {
|
|
continue
|
|
}
|
|
if f.isKey {
|
|
key, _ := tok.(string)
|
|
// The struct decoder matches names without regard to case, so "Snr" would be stored as snr while the
|
|
// signed line reads it as absent. A name outside ASCII can fold to a letter too. No field has either.
|
|
for i := 0; i < len(key); i++ {
|
|
if key[i] >= 0x80 || (key[i] >= 'A' && key[i] <= 'Z') {
|
|
return true
|
|
}
|
|
}
|
|
if f.keys[key] {
|
|
return true
|
|
}
|
|
f.keys[key] = true
|
|
f.isKey = false
|
|
} else {
|
|
f.isKey = true
|
|
}
|
|
}
|
|
}
|