-
Notifications
You must be signed in to change notification settings - Fork 0
/
activation.go
254 lines (224 loc) · 6.93 KB
/
activation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package handler
import (
"fmt"
"time"
pb_broker "github.com/TheThingsNetwork/ttn/api/broker"
pb "github.com/TheThingsNetwork/ttn/api/handler"
"github.com/TheThingsNetwork/ttn/api/trace"
"github.com/TheThingsNetwork/ttn/core/handler/device"
"github.com/TheThingsNetwork/ttn/core/types"
"github.com/TheThingsNetwork/ttn/utils/errors"
"github.com/TheThingsNetwork/ttn/utils/otaa"
"github.com/TheThingsNetwork/ttn/utils/random"
"github.com/apex/log"
"github.com/brocaar/lorawan"
)
func (h *handler) getActivationMetadata(ctx log.Interface, activation *pb_broker.DeduplicatedDeviceActivationRequest, device *device.Device) (types.Metadata, error) {
ttnUp := &pb_broker.DeduplicatedUplinkMessage{
ProtocolMetadata: activation.ProtocolMetadata,
GatewayMetadata: activation.GatewayMetadata,
ServerTime: activation.ServerTime,
}
mqttUp := &types.UplinkMessage{}
err := h.ConvertMetadata(ctx, ttnUp, mqttUp, device)
if err != nil {
return types.Metadata{}, err
}
return mqttUp.Metadata, nil
}
func (h *handler) HandleActivationChallenge(challenge *pb_broker.ActivationChallengeRequest) (*pb_broker.ActivationChallengeResponse, error) {
// Find Device
dev, err := h.devices.Get(challenge.AppId, challenge.DevId)
if err != nil {
return nil, err
}
if dev.AppKey.IsEmpty() {
err = errors.NewErrNotFound(fmt.Sprintf("AppKey for device %s", challenge.DevId))
return nil, err
}
// Unmarshal LoRaWAN
var reqPHY lorawan.PHYPayload
if err = reqPHY.UnmarshalBinary(challenge.Payload); err != nil {
return nil, err
}
// Set MIC
if err := reqPHY.SetMIC(lorawan.AES128Key(dev.AppKey)); err != nil {
err = errors.NewErrNotFound("Could not set MIC")
return nil, err
}
// Marshal
bytes, err := reqPHY.MarshalBinary()
if err != nil {
return nil, err
}
return &pb_broker.ActivationChallengeResponse{
Payload: bytes,
}, nil
}
func (h *handler) HandleActivation(activation *pb_broker.DeduplicatedDeviceActivationRequest) (res *pb.DeviceActivationResponse, err error) {
appID, devID := activation.AppId, activation.DevId
var appEUI types.AppEUI
if activation.AppEui != nil {
appEUI = *activation.AppEui
}
var devEUI types.DevEUI
if activation.DevEui != nil {
devEUI = *activation.DevEui
}
ctx := h.Ctx.WithFields(log.Fields{
"DevEUI": devEUI,
"AppEUI": appEUI,
"AppID": appID,
"DevID": devID,
})
start := time.Now()
defer func() {
if err != nil {
h.mqttEvent <- &types.DeviceEvent{
AppID: appID,
DevID: devID,
Event: types.ActivationErrorEvent,
Data: types.ErrorEventData{Error: err.Error()},
}
ctx.WithError(err).Warn("Could not handle activation")
} else {
ctx.WithField("Duration", time.Now().Sub(start)).Info("Handled activation")
}
}()
h.status.activations.Mark(1)
activation.Trace = activation.Trace.WithEvent(trace.ReceiveEvent)
if activation.ResponseTemplate == nil {
err = errors.NewErrInternal("No downlink available")
return nil, err
}
// Find Device
var dev *device.Device
dev, err = h.devices.Get(appID, devID)
if err != nil {
return nil, err
}
if dev.AppKey.IsEmpty() {
err = errors.NewErrNotFound(fmt.Sprintf("AppKey for device %s", devID))
return nil, err
}
// Check for LoRaWAN
if lorawan := activation.ActivationMetadata.GetLorawan(); lorawan == nil {
err = errors.NewErrInvalidArgument("Activation", "does not contain LoRaWAN metadata")
return nil, err
}
// Unmarshal LoRaWAN
var reqPHY lorawan.PHYPayload
if err = reqPHY.UnmarshalBinary(activation.Payload); err != nil {
return nil, err
}
reqMAC, ok := reqPHY.MACPayload.(*lorawan.JoinRequestPayload)
if !ok {
err = errors.NewErrInvalidArgument("Activation", "does not contain a JoinRequestPayload")
return nil, err
}
// Validate MIC
activation.Trace = activation.Trace.WithEvent(trace.CheckMICEvent)
if ok, err = reqPHY.ValidateMIC(lorawan.AES128Key(dev.AppKey)); err != nil || !ok {
err = errors.NewErrNotFound("MIC does not match device")
return nil, err
}
// Validate DevNonce
var alreadyUsed bool
for _, usedNonce := range dev.UsedDevNonces {
if usedNonce == device.DevNonce(reqMAC.DevNonce) {
alreadyUsed = true
break
}
}
if alreadyUsed {
err = errors.NewErrInvalidArgument("Activation DevNonce", "already used")
return nil, err
}
ctx.Debug("Accepting Join Request")
activation.Trace = activation.Trace.WithEvent(trace.AcceptEvent)
// Prepare Device Activation Response
var resPHY lorawan.PHYPayload
if err = resPHY.UnmarshalBinary(activation.ResponseTemplate.Payload); err != nil {
return nil, err
}
resMAC, ok := resPHY.MACPayload.(*lorawan.DataPayload)
if !ok {
err = errors.NewErrInvalidArgument("Activation ResponseTemplate", "MACPayload must be a *DataPayload")
return nil, err
}
joinAccept := &lorawan.JoinAcceptPayload{}
if err = joinAccept.UnmarshalBinary(false, resMAC.Bytes); err != nil {
return nil, err
}
resPHY.MACPayload = joinAccept
// Publish Activation
mqttMetadata, _ := h.getActivationMetadata(ctx, activation, dev)
h.mqttEvent <- &types.DeviceEvent{
AppID: appID,
DevID: devID,
Event: types.ActivationEvent,
Data: types.ActivationEventData{
AppEUI: *activation.AppEui,
DevEUI: *activation.DevEui,
DevAddr: types.DevAddr(joinAccept.DevAddr),
Metadata: mqttMetadata,
},
}
// Generate random AppNonce
var appNonce device.AppNonce
for {
// NOTE: As DevNonces are only 2 bytes, we will start rejecting those before we run out of AppNonces.
// It might just take some time to get one we didn't use yet...
alreadyUsed = false
copy(appNonce[:], random.Bytes(3))
for _, usedNonce := range dev.UsedAppNonces {
if usedNonce == appNonce {
alreadyUsed = true
break
}
}
if !alreadyUsed {
break
}
}
joinAccept.AppNonce = appNonce
// Calculate session keys
appSKey, nwkSKey, err := otaa.CalculateSessionKeys(dev.AppKey, joinAccept.AppNonce, joinAccept.NetID, reqMAC.DevNonce)
if err != nil {
return nil, err
}
// Update Device
dev.StartUpdate()
dev.DevAddr = types.DevAddr(joinAccept.DevAddr)
dev.AppSKey = appSKey
dev.NwkSKey = nwkSKey
dev.UsedAppNonces = append(dev.UsedAppNonces, appNonce)
dev.UsedDevNonces = append(dev.UsedDevNonces, reqMAC.DevNonce)
err = h.devices.Set(dev)
if err != nil {
return nil, err
}
if err = resPHY.SetMIC(lorawan.AES128Key(dev.AppKey)); err != nil {
return nil, err
}
if err = resPHY.EncryptJoinAcceptPayload(lorawan.AES128Key(dev.AppKey)); err != nil {
return nil, err
}
var resBytes []byte
resBytes, err = resPHY.MarshalBinary()
if err != nil {
return nil, err
}
metadata := activation.ActivationMetadata
metadata.GetLorawan().NwkSKey = &dev.NwkSKey
metadata.GetLorawan().DevAddr = &dev.DevAddr
res = &pb.DeviceActivationResponse{
Payload: resBytes,
DownlinkOption: activation.ResponseTemplate.DownlinkOption,
ActivationMetadata: metadata,
Trace: activation.Trace,
}
return res, nil
}