/
cryptoutil.go
174 lines (162 loc) · 5.63 KB
/
cryptoutil.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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cryptoutil implements cryptography utilities.
package cryptoutil
import (
"context"
"fmt"
"runtime/trace"
"go.thethings.network/lorawan-stack/v3/pkg/crypto"
"go.thethings.network/lorawan-stack/v3/pkg/errors"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
"go.thethings.network/lorawan-stack/v3/pkg/types"
)
var (
errKeyNotFound = errors.DefineNotFound("key_not_found", "key with label `{label}` not found")
errCertificateNotFound = errors.DefineNotFound(
"certificate_not_found", "certificate with label `{label}` not found",
)
errClientCertificateNotFound = errors.DefineNotFound("client_certificate_not_found", "client certificate not found")
)
// WrapAES128Key performs the RFC 3394 Wrap algorithm on the given key using the given key service and KEK label.
// If the KEK label is empty, the key will be returned in the clear.
func WrapAES128Key(
ctx context.Context, key types.AES128Key, kekLabel string, ks crypto.KeyService,
) (*ttnpb.KeyEnvelope, error) {
defer trace.StartRegion(ctx, "wrap AES-128 key").End()
if kekLabel == "" {
return &ttnpb.KeyEnvelope{
EncryptedKey: key[:],
}, nil
}
wrapped, err := ks.Wrap(ctx, key[:], kekLabel)
if err != nil {
return nil, err
}
return &ttnpb.KeyEnvelope{
EncryptedKey: wrapped,
KekLabel: kekLabel,
}, nil
}
// WrapAES128KeyWithKEK wraps the key with the given KEK.
// If the KEK label is empty, the key will be returned in the clear.
func WrapAES128KeyWithKEK(
ctx context.Context, key types.AES128Key, kekLabel string, kek types.AES128Key,
) (*ttnpb.KeyEnvelope, error) {
defer trace.StartRegion(ctx, "wrap AES-128 key").End()
if kekLabel == "" {
return &ttnpb.KeyEnvelope{
EncryptedKey: key[:],
}, nil
}
wrapped, err := crypto.WrapKey(key[:], kek[:])
if err != nil {
return nil, err
}
return &ttnpb.KeyEnvelope{
EncryptedKey: wrapped,
KekLabel: kekLabel,
}, nil
}
var errInvalidLength = errors.DefineInvalidArgument("invalid_length", "invalid slice length")
// UnwrapAES128Key performs the RFC 3394 Unwrap algorithm on the given key envelope using the given key service.
// If the KEK label is empty, the key is assumed to be stored in the clear.
func UnwrapAES128Key(
ctx context.Context, wrapped *ttnpb.KeyEnvelope, ks crypto.KeyService,
) (key types.AES128Key, err error) {
defer trace.StartRegion(ctx, "unwrap AES-128 key").End()
if wrapped.Key != nil {
return *types.MustAES128Key(wrapped.Key), nil
}
if wrapped.KekLabel == "" {
if len(wrapped.EncryptedKey) != 16 {
return key, errInvalidLength.New()
}
copy(key[:], wrapped.EncryptedKey)
} else {
keyBytes, err := ks.Unwrap(ctx, wrapped.EncryptedKey, wrapped.KekLabel)
if err != nil {
return key, err
}
if len(keyBytes) != 16 {
return key, errInvalidLength.New()
}
copy(key[:], keyBytes)
}
return key, nil
}
// UnwrapKeyEnvelope calls UnwrapAES128Key on the given key envelope using the given key service if necessary and
// returns the result as a key envelope.
// NOTE: UnwrapKeyEnvelope returns ke if unwrapping is not necessary.
func UnwrapKeyEnvelope(ctx context.Context, ke *ttnpb.KeyEnvelope, ks crypto.KeyService) (*ttnpb.KeyEnvelope, error) {
if !types.MustAES128Key(ke.GetKey()).OrZero().IsZero() || len(ke.GetEncryptedKey()) == 0 {
return ke, nil
}
k, err := UnwrapAES128Key(ctx, ke, ks)
if err != nil {
return nil, err
}
return &ttnpb.KeyEnvelope{
Key: k.Bytes(),
}, nil
}
func pathWithPrefix(prefix, path string) string {
if prefix == "" {
return path
}
return fmt.Sprintf("%s.%s", prefix, path)
}
// UnwrapSelectedSessionKeys unwraps the selected session keys in the given session keys using the given key service.
func UnwrapSelectedSessionKeys(
ctx context.Context, ks crypto.KeyService, sk *ttnpb.SessionKeys, prefix string, paths ...string,
) (*ttnpb.SessionKeys, error) {
var (
fNwkSIntKeyEnvelope *ttnpb.KeyEnvelope
sNwkSIntKeyEnvelope *ttnpb.KeyEnvelope
nwkSEncKeyEnvelope *ttnpb.KeyEnvelope
appSKeyEnvelope *ttnpb.KeyEnvelope
err error
)
if ttnpb.HasAnyField(paths, pathWithPrefix(prefix, "app_s_key.key")) && sk.GetAppSKey() != nil {
appSKeyEnvelope, err = UnwrapKeyEnvelope(ctx, sk.AppSKey, ks)
if err != nil {
return nil, err
}
}
if ttnpb.HasAnyField(paths, pathWithPrefix(prefix, "f_nwk_s_int_key.key")) && sk.GetFNwkSIntKey() != nil {
fNwkSIntKeyEnvelope, err = UnwrapKeyEnvelope(ctx, sk.FNwkSIntKey, ks)
if err != nil {
return nil, err
}
}
if ttnpb.HasAnyField(paths, pathWithPrefix(prefix, "nwk_s_enc_key.key")) && sk.GetNwkSEncKey() != nil {
nwkSEncKeyEnvelope, err = UnwrapKeyEnvelope(ctx, sk.NwkSEncKey, ks)
if err != nil {
return nil, err
}
}
if ttnpb.HasAnyField(paths, pathWithPrefix(prefix, "s_nwk_s_int_key.key")) && sk.GetSNwkSIntKey() != nil {
sNwkSIntKeyEnvelope, err = UnwrapKeyEnvelope(ctx, sk.SNwkSIntKey, ks)
if err != nil {
return nil, err
}
}
return &ttnpb.SessionKeys{
SessionKeyId: sk.GetSessionKeyId(),
FNwkSIntKey: fNwkSIntKeyEnvelope,
NwkSEncKey: nwkSEncKeyEnvelope,
SNwkSIntKey: sNwkSIntKeyEnvelope,
AppSKey: appSKeyEnvelope,
}, nil
}