forked from brocaar/chirpstack-application-server
/
join.go
324 lines (274 loc) · 7.85 KB
/
join.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package join
import (
"crypto/aes"
"encoding/binary"
"fmt"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/brocaar/lora-app-server/internal/config"
"github.com/brocaar/lora-app-server/internal/eventlog"
"github.com/brocaar/lora-app-server/internal/handler"
"github.com/brocaar/lora-app-server/internal/storage"
"github.com/brocaar/lorawan"
"github.com/brocaar/lorawan/backend"
)
type context struct {
joinReqPayload backend.JoinReqPayload
joinAnsPayload backend.JoinAnsPayload
phyPayload lorawan.PHYPayload
device storage.Device
application storage.Application
deviceKeys storage.DeviceKeys
appNonce lorawan.AppNonce
nwkSKey lorawan.AES128Key
appSKey lorawan.AES128Key
netID lorawan.NetID
}
type task func(*context) error
type flow struct {
joinRequestTasks []task
}
func (f *flow) run(pl backend.JoinReqPayload) (backend.JoinAnsPayload, error) {
ctx := context{
joinReqPayload: pl,
}
for _, t := range f.joinRequestTasks {
if err := t(&ctx); err != nil {
return ctx.joinAnsPayload, err
}
}
return ctx.joinAnsPayload, nil
}
var joinFlow = &flow{
joinRequestTasks: []task{
setPHYPayload,
getDevice,
getApplication,
getDeviceKeys,
validateMIC,
setAppNonce,
setNetID,
setSessionKeys,
createDeviceActivationRecord,
flushDeviceQueueMapping,
sendJoinNotification,
createJoinAnsPayload,
},
}
// HandleJoinRequest handles a given join-request and returns a join-answer
// payload.
func HandleJoinRequest(pl backend.JoinReqPayload) backend.JoinAnsPayload {
basePayload := backend.BasePayload{
ProtocolVersion: backend.ProtocolVersion1_0,
SenderID: pl.ReceiverID,
ReceiverID: pl.SenderID,
TransactionID: pl.TransactionID,
MessageType: backend.JoinAns,
}
jaPL, err := joinFlow.run(pl)
if err != nil {
var resCode backend.ResultCode
switch errors.Cause(err) {
case storage.ErrDoesNotExist:
resCode = backend.UnknownDevEUI
case ErrInvalidMIC:
resCode = backend.MICFailed
default:
resCode = backend.Other
}
jaPL = backend.JoinAnsPayload{
BasePayload: basePayload,
Result: backend.Result{
ResultCode: resCode,
Description: err.Error(),
},
}
}
jaPL.BasePayload = basePayload
return jaPL
}
func setPHYPayload(ctx *context) error {
if err := ctx.phyPayload.UnmarshalBinary(ctx.joinReqPayload.PHYPayload[:]); err != nil {
return errors.Wrap(err, "unmarshal phypayload error")
}
return nil
}
func getDevice(ctx *context) error {
d, err := storage.GetDevice(config.C.PostgreSQL.DB, ctx.joinReqPayload.DevEUI, false)
if err != nil {
return errors.Wrap(err, "get device error")
}
ctx.device = d
return nil
}
func getApplication(ctx *context) error {
a, err := storage.GetApplication(config.C.PostgreSQL.DB, ctx.device.ApplicationID)
if err != nil {
return errors.Wrap(err, "get application error")
}
ctx.application = a
return nil
}
func getDeviceKeys(ctx *context) error {
dk, err := storage.GetDeviceKeys(config.C.PostgreSQL.DB, ctx.device.DevEUI)
if err != nil {
return errors.Wrap(err, "get device-keys error")
}
ctx.deviceKeys = dk
return nil
}
func validateMIC(ctx *context) error {
ok, err := ctx.phyPayload.ValidateMIC(ctx.deviceKeys.AppKey)
if err != nil {
return errors.Wrap(err, "validate mic error")
}
if !ok {
return ErrInvalidMIC
}
return nil
}
func setAppNonce(ctx *context) error {
ctx.deviceKeys.JoinNonce++
if ctx.deviceKeys.JoinNonce > (2<<23)-1 {
return errors.New("join-nonce overflow")
}
if err := storage.UpdateDeviceKeys(config.C.PostgreSQL.DB, &ctx.deviceKeys); err != nil {
return errors.Wrap(err, "update device-keys error")
}
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, uint32(ctx.deviceKeys.JoinNonce))
copy(ctx.appNonce[:], b[0:3])
return nil
}
func setNetID(ctx *context) error {
if err := ctx.netID.UnmarshalText([]byte(ctx.joinReqPayload.SenderID)); err != nil {
return errors.Wrap(err, "unmarshal netid error")
}
return nil
}
func setSessionKeys(ctx *context) error {
var err error
jrPL, ok := ctx.phyPayload.MACPayload.(*lorawan.JoinRequestPayload)
if !ok {
return fmt.Errorf("expected *lorawan.JoinRequestPayload, got %T", ctx.phyPayload.MACPayload)
}
ctx.nwkSKey, err = getNwkSKey(ctx.deviceKeys.AppKey, ctx.netID, ctx.appNonce, jrPL.DevNonce)
if err != nil {
return errors.Wrap(err, "get nwk_s_key error")
}
ctx.appSKey, err = getAppSKey(ctx.deviceKeys.AppKey, ctx.netID, ctx.appNonce, jrPL.DevNonce)
if err != nil {
return errors.Wrap(err, "get app_s_key error")
}
return nil
}
func createDeviceActivationRecord(ctx *context) error {
da := storage.DeviceActivation{
DevEUI: ctx.device.DevEUI,
DevAddr: ctx.joinReqPayload.DevAddr,
AppSKey: ctx.appSKey,
NwkSKey: ctx.nwkSKey,
}
if err := storage.CreateDeviceActivation(config.C.PostgreSQL.DB, &da); err != nil {
return errors.Wrap(err, "create device-activation error")
}
return nil
}
func flushDeviceQueueMapping(ctx *context) error {
if err := storage.FlushDeviceQueueMappingForDevEUI(config.C.PostgreSQL.DB, ctx.device.DevEUI); err != nil {
return errors.Wrap(err, "flush device-queue mapping error")
}
return nil
}
func sendJoinNotification(ctx *context) error {
pl := handler.JoinNotification{
ApplicationID: ctx.device.ApplicationID,
ApplicationName: ctx.application.Name,
DeviceName: ctx.device.Name,
DevEUI: ctx.device.DevEUI,
DevAddr: ctx.joinReqPayload.DevAddr,
}
err := eventlog.LogEventForDevice(ctx.device.DevEUI, eventlog.EventLog{
Type: eventlog.Join,
Payload: pl,
})
if err != nil {
log.WithError(err).Error("log event for device error")
}
err = config.C.ApplicationServer.Integration.Handler.SendJoinNotification(pl)
if err != nil {
return errors.Wrap(err, "send join notification error")
}
return nil
}
func createJoinAnsPayload(ctx *context) error {
phy := lorawan.PHYPayload{
MHDR: lorawan.MHDR{
MType: lorawan.JoinAccept,
Major: lorawan.LoRaWANR1,
},
MACPayload: &lorawan.JoinAcceptPayload{
AppNonce: ctx.appNonce,
NetID: ctx.netID,
DevAddr: ctx.joinReqPayload.DevAddr,
DLSettings: ctx.joinReqPayload.DLSettings,
RXDelay: uint8(ctx.joinReqPayload.RxDelay),
CFList: ctx.joinReqPayload.CFList,
},
}
if err := phy.SetMIC(ctx.deviceKeys.AppKey); err != nil {
return err
}
if err := phy.EncryptJoinAcceptPayload(ctx.deviceKeys.AppKey); err != nil {
return err
}
b, err := phy.MarshalBinary()
if err != nil {
return err
}
ctx.joinAnsPayload = backend.JoinAnsPayload{
PHYPayload: backend.HEXBytes(b),
Result: backend.Result{
ResultCode: backend.Success,
},
NwkSKey: &backend.KeyEnvelope{
AESKey: ctx.nwkSKey,
},
// TODO: add AppSKey and Lifetime
}
return nil
}
// getNwkSKey returns the network session key.
func getNwkSKey(appkey lorawan.AES128Key, netID lorawan.NetID, appNonce [3]byte, devNonce [2]byte) (lorawan.AES128Key, error) {
return getSKey(0x01, appkey, netID, appNonce, devNonce)
}
// getAppSKey returns the application session key.
func getAppSKey(appkey lorawan.AES128Key, netID lorawan.NetID, appNonce [3]byte, devNonce [2]byte) (lorawan.AES128Key, error) {
return getSKey(0x02, appkey, netID, appNonce, devNonce)
}
func getSKey(typ byte, appkey lorawan.AES128Key, netID lorawan.NetID, appNonce [3]byte, devNonce [2]byte) (lorawan.AES128Key, error) {
var key lorawan.AES128Key
b := make([]byte, 0, 16)
b = append(b, typ)
// little endian
for i := len(appNonce) - 1; i >= 0; i-- {
b = append(b, appNonce[i])
}
for i := len(netID) - 1; i >= 0; i-- {
b = append(b, netID[i])
}
for i := len(devNonce) - 1; i >= 0; i-- {
b = append(b, devNonce[i])
}
pad := make([]byte, 7)
b = append(b, pad...)
block, err := aes.NewCipher(appkey[:])
if err != nil {
return key, err
}
if block.BlockSize() != len(b) {
return key, fmt.Errorf("block-size of %d bytes is expected", len(b))
}
block.Encrypt(key[:], b)
return key, nil
}