CVE-2020-28349 (published 2020-11-09T01:15Z)

An inaccurate frame deduplication process in ChirpStack Network Server 3.9.0 allows a malicious gateway to perform uplink Denial of Service via malformed frequency attributes in CollectAndCallOnceCollect in internal/uplink/collect.go. NOTE: the vendor\'s position is that there are no "guarantees that allowing untrusted LoRa gateways to the network should still result in a secure network.

Severity: MEDIUM
CVSS v2 base score: 6.8 (AV:N/AC:L/Au:S/C:N/I:N/A:C)
CVSS v3 base score: 6.5, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/brocaar/chirpstack-network-server
commit_details: repo_url: https://github.com/brocaar/chirpstack-network-server
author: Orne Brocaar
author_date: 2020-08-31 15:28:32+01:00
msg: Improve uplink de-duplication.

This removes the de-duplication at the MQTT backend. Some MQTT brokers
provide shared subscription options in which case this additional
de-duplication is not needed.

For MQTT brokers that do not support shared subscriptions, the
collectAndCallOnce function will still filter out duplicated uplinks.

By adding the TXInfo object (hex encoded) to the de-duplication key,
uplink messages received on multiple channels will be handled
separately as they will result in different de-duplication keys.
repository: repo_url: https://github.com/brocaar/chirpstack-network-server
repo_name: brocaar/chirpstack-network-server
description: ChirpStack Network Server is an open-source LoRaWAN network-server.
repo_language: Go
owner: brocaar
file_changes: filename: backend.go
change_type: ModificationType.MODIFY
diff: @@ -5,7 +5,6 @@ import (
 	"crypto/tls"
 	"crypto/x509"
 	"encoding/base64"
-	"encoding/hex"
 	"fmt"
 	"io/ioutil"
 	"strings"
@@ -249,20 +248,6 @@ func (b *Backend) rxPacketHandler(c paho.Client, msg paho.Message) {
 		"gateway_id": gatewayID,
 	}).Info("gateway/mqtt: uplink frame received")
 
-	// Since with MQTT all subscribers will receive the uplink messages sent
-	// by all the gateways, the first instance receiving the message must lock it,
-	// so that other instances can ignore the same message (from the same gw).
-	key := fmt.Sprintf("lora:ns:uplink:lock:%s:%d:%d:%d:%s", gatewayID, uplinkFrame.TxInfo.Frequency, uplinkFrame.RxInfo.Board, uplinkFrame.RxInfo.Antenna, hex.EncodeToString(uplinkFrame.PhyPayload))
-	if locked, err := b.isLocked(key); err != nil || locked {
-		if err != nil {
-			log.WithError(err).WithFields(log.Fields{
-				"uplink_id": uplinkID,
-				"key":       key,
-			}).Error("gateway/mqtt: acquire lock error")
-		}
-		return
-	}
-
 	b.rxPacketChan <- uplinkFrame
 }
 

programming_language: Go
filename: collect.go
change_type: ModificationType.MODIFY
diff: @@ -19,8 +19,8 @@ import (
 
 // Templates used for generating Redis keys
 const (
-	CollectKeyTempl     = "lora:ns:rx:collect:%s"
-	CollectLockKeyTempl = "lora:ns:rx:collect:%s:lock"
+	CollectKeyTempl     = "lora:ns:rx:collect:%s:%s"
+	CollectLockKeyTempl = "lora:ns:rx:collect:%s:%s:lock"
 )
 
 // collectAndCallOnce collects the package, sleeps the configured duraction and
@@ -33,8 +33,14 @@ const (
 // unique set per gateway MAC and packet MIC.
 func collectAndCallOnce(rxPacket gw.UplinkFrame, callback func(packet models.RXPacket) error) error {
 	phyKey := hex.EncodeToString(rxPacket.PhyPayload)
-	key := fmt.Sprintf(CollectKeyTempl, phyKey)
-	lockKey := fmt.Sprintf(CollectLockKeyTempl, phyKey)
+	txInfoB, err := proto.Marshal(rxPacket.TxInfo)
+	if err != nil {
+		return errors.Wrap(err, "marshal protobuf error")
+	}
+	txInfoHEX := hex.EncodeToString(txInfoB)
+
+	key := fmt.Sprintf(CollectKeyTempl, txInfoHEX, phyKey)
+	lockKey := fmt.Sprintf(CollectLockKeyTempl, txInfoHEX, phyKey)
 
 	// this way we can set a really low DeduplicationDelay for testing, without
 	// the risk that the set already expired in redis on read

programming_language: Go
repo_url: https://github.com/brocaar/chirpstack-network-server
commit_details: repo_url: https://github.com/brocaar/chirpstack-network-server
author: Orne Brocaar
author_date: 2020-07-09 08:45:02+02:00
msg: Improve error handling of unknown gateways.
repository: repo_url: https://github.com/brocaar/chirpstack-network-server
repo_name: brocaar/chirpstack-network-server
description: ChirpStack Network Server is an open-source LoRaWAN network-server.
repo_language: Go
owner: brocaar
file_changes: filename: rx_info.go
change_type: ModificationType.MODIFY
diff: @@ -25,68 +25,53 @@ import (
 //   - add the gateway location
 //   - set the FPGA id if available
 //   - decrypt the fine-timestamp (if available and AES key is set)
-func UpdateMetaDataInRxInfoSet(ctx context.Context, db sqlx.Queryer, rxInfo []*gw.UplinkRXInfo) error {
-	for i := range rxInfo {
-		id := helpers.GetGatewayID(rxInfo[i])
+func UpdateMetaDataInRxInfoSet(ctx context.Context, db sqlx.Queryer, rxInfoSet []*gw.UplinkRXInfo) []*gw.UplinkRXInfo {
+	var out []*gw.UplinkRXInfo
+
+	for i := range rxInfoSet {
+		rxInfo := rxInfoSet[i]
+
+		id := helpers.GetGatewayID(rxInfo)
 		g, err := storage.GetAndCacheGateway(ctx, db, id)
 		if err != nil {
-			log.WithFields(log.Fields{
-				"ctx_id":     ctx.Value(logging.ContextIDKey),
-				"gateway_id": id,
-			}).WithError(err).Error("get gateway error")
+			if errors.Cause(err) == storage.ErrDoesNotExist {
+				log.WithFields(log.Fields{
+					"ctx_id":     ctx.Value(logging.ContextIDKey),
+					"gateway_id": id,
+				}).Warning("uplink received by unknown gateway")
+			} else {
+				log.WithFields(log.Fields{
+					"ctx_id":     ctx.Value(logging.ContextIDKey),
+					"gateway_id": id,
+				}).WithError(err).Error("get gateway error")
+			}
 			continue
 		}
 
 		// set gateway location
-		rxInfo[i].Location = &common.Location{
+		rxInfo.Location = &common.Location{
 			Latitude:  g.Location.Latitude,
 			Longitude: g.Location.Longitude,
 			Altitude:  g.Altitude,
 		}
 
 		var board storage.GatewayBoard
-		if int(rxInfo[i].Board) < len(g.Boards) {
-			board = g.Boards[int(rxInfo[i].Board)]
+		if int(rxInfo.Board) < len(g.Boards) {
+			board = g.Boards[int(rxInfo.Board)]
 		}
 
 		// set FPGA ID
 		// this is useful when the AES decryption key is not set as it
 		// indicates which key to use for decryption
-		if rxInfo[i].FineTimestampType == gw.FineTimestampType_ENCRYPTED && board.FPGAID != nil {
-			tsInfo := rxInfo[i].GetEncryptedFineTimestamp()
-			if tsInfo == nil {
-				log.WithFields(log.Fields{
-					"ctx_id":     ctx.Value(logging.ContextIDKey),
-					"gateway_id": id,
-				}).Error("encrypted_fine_timestamp must not be nil")
-				continue
-			}
-
+		if tsInfo := rxInfo.GetEncryptedFineTimestamp(); tsInfo != nil && board.FPGAID != nil {
 			if len(tsInfo.FpgaId) == 0 {
 				tsInfo.FpgaId = board.FPGAID[:]
 			}
 		}
 
 		// decrypt fine-timestamp when the AES key is known
-		if rxInfo[i].FineTimestampType == gw.FineTimestampType_ENCRYPTED && board.FineTimestampKey != nil {
-			tsInfo := rxInfo[i].GetEncryptedFineTimestamp()
-			if tsInfo == nil {
-				log.WithFields(log.Fields{
-					"ctx_id":     ctx.Value(logging.ContextIDKey),
-					"gateway_id": id,
-				}).Error("encrypted_fine_timestamp must not be nil")
-				continue
-			}
-
-			if rxInfo[i].Time == nil {
-				log.WithFields(log.Fields{
-					"ctx_id":     ctx.Value(logging.ContextIDKey),
-					"gateway_id": id,
-				}).Error("time must not be nil")
-				continue
-			}
-
-			rxTime, err := ptypes.Timestamp(rxInfo[i].Time)
+		if tsInfo := rxInfo.GetEncryptedFineTimestamp(); tsInfo != nil && board.FineTimestampKey != nil {
+			rxTime, err := ptypes.Timestamp(rxInfo.GetTime())
 			if err != nil {
 				log.WithFields(log.Fields{
 					"ctx_id":     ctx.Value(logging.ContextIDKey),
@@ -103,14 +88,16 @@ func UpdateMetaDataInRxInfoSet(ctx context.Context, db sqlx.Queryer, rxInfo []*g
 				continue
 			}
 
-			rxInfo[i].FineTimestampType = gw.FineTimestampType_PLAIN
-			rxInfo[i].FineTimestamp = &gw.UplinkRXInfo_PlainFineTimestamp{
+			rxInfo.FineTimestampType = gw.FineTimestampType_PLAIN
+			rxInfo.FineTimestamp = &gw.UplinkRXInfo_PlainFineTimestamp{
 				PlainFineTimestamp: &plainTS,
 			}
 		}
+
+		out = append(out, rxInfo)
 	}
 
-	return nil
+	return out
 }
 
 func decryptFineTimestamp(key lorawan.AES128Key, rxTime time.Time, ts gw.EncryptedFineTimestamp) (gw.PlainFineTimestamp, error) {

programming_language: Go
filename: stats.go
change_type: ModificationType.MODIFY
diff: @@ -18,6 +18,8 @@ import (
 	loraband "github.com/brocaar/lorawan/band"
 )
 
+var ErrAbort = errors.New("abort")
+
 type statsContext struct {
 	ctx          context.Context
 	gateway      storage.Gateway
@@ -40,6 +42,9 @@ func Handle(ctx context.Context, stats gw.GatewayStats) error {
 
 	for _, t := range tasks {
 		if err := t(&sctx); err != nil {
+			if err == ErrAbort {
+				return nil
+			}
 			return err
 		}
 	}
@@ -51,7 +56,15 @@ func getGateway(ctx *statsContext) error {
 	gatewayID := helpers.GetGatewayID(&ctx.gatewayStats)
 	gw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID)
 	if err != nil {
-		return errors.Wrap(err, "get gateway error")
+		if errors.Cause(err) == storage.ErrDoesNotExist {
+			log.WithFields(log.Fields{
+				"ctx_id":     ctx.ctx.Value(logging.ContextIDKey),
+				"gateway_id": gatewayID,
+			}).Warning("gateway/stats: stats received by unknown gateway")
+			return ErrAbort
+		} else {
+			return errors.Wrap(err, "get gateway error")
+		}
 	}
 
 	ctx.gateway = gw

programming_language: Go
filename: uplink.go
change_type: ModificationType.MODIFY
diff: @@ -178,6 +178,14 @@ func collectUplinkFrames(ctx context.Context, uplinkFrame gw.UplinkFrame) error
 }
 
 func handleCollectedUplink(ctx context.Context, uplinkFrame gw.UplinkFrame, rxPacket models.RXPacket) error {
+	// update the gateway meta-data
+	rxPacket.RXInfoSet = gateway.UpdateMetaDataInRxInfoSet(ctx, storage.DB(), rxPacket.RXInfoSet)
+
+	// Return if the RXInfoSet is empty.
+	if len(rxPacket.RXInfoSet) == 0 {
+		return nil
+	}
+
 	var uplinkIDs []uuid.UUID
 	for _, p := range rxPacket.RXInfoSet {
 		uplinkIDs = append(uplinkIDs, helpers.GetUplinkID(p))
@@ -189,11 +197,6 @@ func handleCollectedUplink(ctx context.Context, uplinkFrame gw.UplinkFrame, rxPa
 		"ctx_id":     ctx.Value(logging.ContextIDKey),
 	}).Info("uplink: frame(s) collected")
 
-	// update the gateway meta-data
-	if err := gateway.UpdateMetaDataInRxInfoSet(ctx, storage.DB(), rxPacket.RXInfoSet); err != nil {
-		log.WithError(err).Error("uplink: update gateway meta-data in rx-info set error")
-	}
-
 	// log the frame for each receiving gateway.
 	if err := framelog.LogUplinkFrameForGateways(ctx, ns.UplinkFrameLog{
 		PhyPayload: uplinkFrame.PhyPayload,

programming_language: Go