| 1 |
// Copyright 2018-2024 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bufio" |
| 18 |
"encoding/base64" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"strings" |
| 22 |
"testing" |
| 23 |
"time" |
| 24 |
|
| 25 |
crand "crypto/rand" |
| 26 |
mrand "math/rand" |
| 27 |
|
| 28 |
"github.com/nats-io/nkeys" |
| 29 |
) |
| 30 |
|
| 31 |
// Nonce has to be a string since we used different encoding by default than json.Unmarshal. |
| 32 |
type nonceInfo struct { |
| 33 |
Id string `json:"server_id"` |
| 34 |
CID uint64 `json:"client_id,omitempty"` |
| 35 |
Nonce string `json:"nonce,omitempty"` |
| 36 |
} |
| 37 |
|
| 38 |
// This is a seed for a user. We can extract public and private keys from this for testing. |
| 39 |
var seed = []byte("SUAKYRHVIOREXV7EUZTBHUHL7NUMHPMAS7QMDU3GTIUWEI5LDNOXD43IZY") |
| 40 |
|
| 41 |
func nkeyBasicSetup() (*Server, *testAsyncClient, *bufio.Reader, string) { |
| 42 |
kp, _ := nkeys.FromSeed(seed) |
| 43 |
pub, _ := kp.PublicKey() |
| 44 |
opts := defaultServerOptions |
| 45 |
opts.Nkeys = []*NkeyUser{{Nkey: string(pub)}} |
| 46 |
return rawSetup(opts) |
| 47 |
} |
| 48 |
|
| 49 |
func mixedSetup() (*Server, *testAsyncClient, *bufio.Reader, string) { |
| 50 |
kp, _ := nkeys.FromSeed(seed) |
| 51 |
pub, _ := kp.PublicKey() |
| 52 |
opts := defaultServerOptions |
| 53 |
opts.Nkeys = []*NkeyUser{{Nkey: string(pub)}} |
| 54 |
opts.Users = []*User{{Username: "derek", Password: "foo"}} |
| 55 |
return rawSetup(opts) |
| 56 |
} |
| 57 |
|
| 58 |
func TestServerInfoNonceAlwaysEnabled(t *testing.T) { |
| 59 |
opts := defaultServerOptions |
| 60 |
opts.AlwaysEnableNonce = true |
| 61 |
s, c, _, l := rawSetup(opts) |
| 62 |
defer s.WaitForShutdown() |
| 63 |
defer s.Shutdown() |
| 64 |
defer c.close() |
| 65 |
|
| 66 |
if !strings.HasPrefix(l, "INFO ") { |
| 67 |
t.Fatalf("INFO response incorrect: %s\n", l) |
| 68 |
} |
| 69 |
|
| 70 |
var info nonceInfo |
| 71 |
err := json.Unmarshal([]byte(l[5:]), &info) |
| 72 |
if err != nil { |
| 73 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 74 |
} |
| 75 |
if info.Nonce == "" { |
| 76 |
t.Fatalf("Expected a non-empty nonce with AlwaysEnableNonce set") |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
func TestServerInfoNonce(t *testing.T) { |
| 81 |
c, l := setUpClientWithResponse() |
| 82 |
defer c.close() |
| 83 |
if !strings.HasPrefix(l, "INFO ") { |
| 84 |
t.Fatalf("INFO response incorrect: %s\n", l) |
| 85 |
} |
| 86 |
// Make sure payload is proper json |
| 87 |
var info nonceInfo |
| 88 |
err := json.Unmarshal([]byte(l[5:]), &info) |
| 89 |
if err != nil { |
| 90 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 91 |
} |
| 92 |
if info.Nonce != "" { |
| 93 |
t.Fatalf("Expected an empty nonce with no nkeys defined") |
| 94 |
} |
| 95 |
|
| 96 |
// Now setup server with auth and nkeys to trigger nonce generation |
| 97 |
s, c, _, l := nkeyBasicSetup() |
| 98 |
defer c.close() |
| 99 |
|
| 100 |
if !strings.HasPrefix(l, "INFO ") { |
| 101 |
t.Fatalf("INFO response incorrect: %s\n", l) |
| 102 |
} |
| 103 |
// Make sure payload is proper json |
| 104 |
err = json.Unmarshal([]byte(l[5:]), &info) |
| 105 |
if err != nil { |
| 106 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 107 |
} |
| 108 |
if info.Nonce == "" { |
| 109 |
t.Fatalf("Expected a non-empty nonce with nkeys defined") |
| 110 |
} |
| 111 |
|
| 112 |
// Make sure new clients get new nonces |
| 113 |
oldNonce := info.Nonce |
| 114 |
|
| 115 |
c, _, l = newClientForServer(s) |
| 116 |
defer c.close() |
| 117 |
|
| 118 |
err = json.Unmarshal([]byte(l[5:]), &info) |
| 119 |
if err != nil { |
| 120 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 121 |
} |
| 122 |
if info.Nonce == "" { |
| 123 |
t.Fatalf("Expected a non-empty nonce") |
| 124 |
} |
| 125 |
if strings.Compare(oldNonce, info.Nonce) == 0 { |
| 126 |
t.Fatalf("Expected subsequent nonces to be different\n") |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
func TestNkeyClientConnect(t *testing.T) { |
| 131 |
s, c, cr, _ := nkeyBasicSetup() |
| 132 |
defer c.close() |
| 133 |
// Send CONNECT with no signature or nkey, should fail. |
| 134 |
connectOp := "CONNECT {\"verbose\":true,\"pedantic\":true}\r\n" |
| 135 |
c.parseAsync(connectOp) |
| 136 |
l, _ := cr.ReadString('\n') |
| 137 |
if !strings.HasPrefix(l, "-ERR ") { |
| 138 |
t.Fatalf("Expected an error") |
| 139 |
} |
| 140 |
|
| 141 |
kp, _ := nkeys.FromSeed(seed) |
| 142 |
pubKey, _ := kp.PublicKey() |
| 143 |
|
| 144 |
// Send nkey but no signature |
| 145 |
c, cr, _ = newClientForServer(s) |
| 146 |
defer c.close() |
| 147 |
cs := fmt.Sprintf("CONNECT {\"nkey\":%q, \"verbose\":true,\"pedantic\":true}\r\n", pubKey) |
| 148 |
c.parseAsync(cs) |
| 149 |
l, _ = cr.ReadString('\n') |
| 150 |
if !strings.HasPrefix(l, "-ERR ") { |
| 151 |
t.Fatalf("Expected an error") |
| 152 |
} |
| 153 |
|
| 154 |
// Now improperly sign etc. |
| 155 |
c, cr, _ = newClientForServer(s) |
| 156 |
defer c.close() |
| 157 |
cs = fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":%q,\"verbose\":true,\"pedantic\":true}\r\n", pubKey, "bad_sig") |
| 158 |
c.parseAsync(cs) |
| 159 |
l, _ = cr.ReadString('\n') |
| 160 |
if !strings.HasPrefix(l, "-ERR ") { |
| 161 |
t.Fatalf("Expected an error") |
| 162 |
} |
| 163 |
|
| 164 |
// Now properly sign the nonce |
| 165 |
c, cr, l = newClientForServer(s) |
| 166 |
defer c.close() |
| 167 |
// Check for Nonce |
| 168 |
var info nonceInfo |
| 169 |
err := json.Unmarshal([]byte(l[5:]), &info) |
| 170 |
if err != nil { |
| 171 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 172 |
} |
| 173 |
if info.Nonce == "" { |
| 174 |
t.Fatalf("Expected a non-empty nonce with nkeys defined") |
| 175 |
} |
| 176 |
sigraw, err := kp.Sign([]byte(info.Nonce)) |
| 177 |
if err != nil { |
| 178 |
t.Fatalf("Failed signing nonce: %v", err) |
| 179 |
} |
| 180 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 181 |
|
| 182 |
// PING needed to flush the +OK to us. |
| 183 |
cs = fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig) |
| 184 |
c.parseAsync(cs) |
| 185 |
l, _ = cr.ReadString('\n') |
| 186 |
if !strings.HasPrefix(l, "+OK") { |
| 187 |
t.Fatalf("Expected an OK, got: %v", l) |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
func TestMixedClientConnect(t *testing.T) { |
| 192 |
s, c, cr, _ := mixedSetup() |
| 193 |
defer c.close() |
| 194 |
// Normal user/pass |
| 195 |
c.parseAsync("CONNECT {\"user\":\"derek\",\"pass\":\"foo\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n") |
| 196 |
l, _ := cr.ReadString('\n') |
| 197 |
if !strings.HasPrefix(l, "+OK") { |
| 198 |
t.Fatalf("Expected an OK, got: %v", l) |
| 199 |
} |
| 200 |
|
| 201 |
kp, _ := nkeys.FromSeed(seed) |
| 202 |
pubKey, _ := kp.PublicKey() |
| 203 |
|
| 204 |
c, cr, l = newClientForServer(s) |
| 205 |
defer c.close() |
| 206 |
// Check for Nonce |
| 207 |
var info nonceInfo |
| 208 |
err := json.Unmarshal([]byte(l[5:]), &info) |
| 209 |
if err != nil { |
| 210 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 211 |
} |
| 212 |
if info.Nonce == "" { |
| 213 |
t.Fatalf("Expected a non-empty nonce with nkeys defined") |
| 214 |
} |
| 215 |
sigraw, err := kp.Sign([]byte(info.Nonce)) |
| 216 |
if err != nil { |
| 217 |
t.Fatalf("Failed signing nonce: %v", err) |
| 218 |
} |
| 219 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 220 |
|
| 221 |
// PING needed to flush the +OK to us. |
| 222 |
cs := fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig) |
| 223 |
c.parseAsync(cs) |
| 224 |
l, _ = cr.ReadString('\n') |
| 225 |
if !strings.HasPrefix(l, "+OK") { |
| 226 |
t.Fatalf("Expected an OK, got: %v", l) |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
func TestMixedClientConfig(t *testing.T) { |
| 231 |
confFileName := createConfFile(t, []byte(` |
| 232 |
authorization { |
| 233 |
users = [ |
| 234 |
{nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV"} |
| 235 |
{user: alice, password: foo} |
| 236 |
] |
| 237 |
}`)) |
| 238 |
opts, err := ProcessConfigFile(confFileName) |
| 239 |
if err != nil { |
| 240 |
t.Fatalf("Received an error processing config file: %v", err) |
| 241 |
} |
| 242 |
if len(opts.Nkeys) != 1 { |
| 243 |
t.Fatalf("Expected 1 nkey, got %d", len(opts.Nkeys)) |
| 244 |
} |
| 245 |
if len(opts.Users) != 1 { |
| 246 |
t.Fatalf("Expected 1 user, got %d", len(opts.Users)) |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
func BenchmarkCryptoRandGeneration(b *testing.B) { |
| 251 |
data := make([]byte, 16) |
| 252 |
for i := 0; i < b.N; i++ { |
| 253 |
crand.Read(data) |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
func BenchmarkMathRandGeneration(b *testing.B) { |
| 258 |
data := make([]byte, 16) |
| 259 |
prng := mrand.New(mrand.NewSource(time.Now().UnixNano())) |
| 260 |
for i := 0; i < b.N; i++ { |
| 261 |
prng.Read(data) |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
func BenchmarkNonceGeneration(b *testing.B) { |
| 266 |
data := make([]byte, nonceRawLen) |
| 267 |
b64 := make([]byte, nonceLen) |
| 268 |
prand := mrand.New(mrand.NewSource(time.Now().UnixNano())) |
| 269 |
for i := 0; i < b.N; i++ { |
| 270 |
prand.Read(data) |
| 271 |
base64.RawURLEncoding.Encode(b64, data) |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
func BenchmarkPublicVerify(b *testing.B) { |
| 276 |
data := make([]byte, nonceRawLen) |
| 277 |
nonce := make([]byte, nonceLen) |
| 278 |
crand.Read(data) |
| 279 |
base64.RawURLEncoding.Encode(nonce, data) |
| 280 |
|
| 281 |
user, err := nkeys.CreateUser() |
| 282 |
if err != nil { |
| 283 |
b.Fatalf("Error creating User Nkey: %v", err) |
| 284 |
} |
| 285 |
sig, err := user.Sign(nonce) |
| 286 |
if err != nil { |
| 287 |
b.Fatalf("Error sigining nonce: %v", err) |
| 288 |
} |
| 289 |
pk, err := user.PublicKey() |
| 290 |
if err != nil { |
| 291 |
b.Fatalf("Could not extract public key from user: %v", err) |
| 292 |
} |
| 293 |
pub, err := nkeys.FromPublicKey(pk) |
| 294 |
if err != nil { |
| 295 |
b.Fatalf("Could not create public key pair from public key string: %v", err) |
| 296 |
} |
| 297 |
|
| 298 |
b.ResetTimer() |
| 299 |
for i := 0; i < b.N; i++ { |
| 300 |
if err := pub.Verify(nonce, sig); err != nil { |
| 301 |
b.Fatalf("Error verifying nonce: %v", err) |
| 302 |
} |
| 303 |
} |
| 304 |
} |