aboutsummaryrefslogtreecommitdiffstats
path: root/src/nkeys.zig
diff options
context:
space:
mode:
authorLibravatar Rutger Broekhoff2021-05-21 00:16:17 +0200
committerLibravatar Rutger Broekhoff2021-05-21 00:16:17 +0200
commitcfb10566fdb3093363fc39d21a8c5aa5c4deeeeb (patch)
tree80774851a87bf93583bcdfaaf233be32eff227b2 /src/nkeys.zig
downloadzig-nkeys-cfb10566fdb3093363fc39d21a8c5aa5c4deeeeb.tar.gz
zig-nkeys-cfb10566fdb3093363fc39d21a8c5aa5c4deeeeb.zip
Initial commit
Diffstat (limited to 'src/nkeys.zig')
-rw-r--r--src/nkeys.zig518
1 files changed, 518 insertions, 0 deletions
diff --git a/src/nkeys.zig b/src/nkeys.zig
new file mode 100644
index 0000000..7ce44f9
--- /dev/null
+++ b/src/nkeys.zig
@@ -0,0 +1,518 @@
1const std = @import("std");
2const ascii = std.ascii;
3const base32 = @import("base32.zig");
4const crc16 = @import("crc16.zig");
5const crypto = std.crypto;
6const Ed25519 = crypto.sign.Ed25519;
7const mem = std.mem;
8const testing = std.testing;
9
10const Error = error{
11 InvalidPrefixByte,
12 InvalidEncoding,
13 InvalidSeed,
14 NoNKeySeedFound,
15 NoNKeyUserSeedFound,
16};
17
18pub fn fromText(text: []const u8) !Key {
19 if (!isValidEncoding(text)) return error.InvalidEncoding;
20 switch (text[0]) {
21 'S' => {
22 // It's a seed.
23 if (text.len != text_seed_len) return error.InvalidSeed;
24 return Key{ .seed_key_pair = try fromSeed(text[0..text_seed_len]) };
25 },
26 'P' => return error.InvalidEncoding, // unsupported for now
27 else => {
28 if (text.len != text_public_len) return error.InvalidEncoding;
29 return Key{ .public_key = try fromPublicKey(text[0..text_public_len]) };
30 },
31 }
32}
33
34pub const Key = union(enum) {
35 seed_key_pair: SeedKeyPair,
36 public_key: PublicKey,
37
38 const Self = @This();
39
40 pub fn publicKey(self: *const Self) !text_public {
41 return switch (self.*) {
42 .seed_key_pair => |*kp| try kp.publicKey(),
43 .public_key => |*pk| try pk.publicKey(),
44 };
45 }
46
47 pub fn intoPublicKey(self: *const Self) !PublicKey {
48 return switch (self.*) {
49 .seed_key_pair => |*kp| try kp.intoPublicKey(),
50 .public_key => |pk| pk,
51 };
52 }
53
54 pub fn verify(
55 self: *const Self,
56 msg: []const u8,
57 sig: [Ed25519.signature_length]u8,
58 ) !void {
59 return switch (self.*) {
60 .seed_key_pair => |*kp| try kp.verify(msg, sig),
61 .public_key => |*pk| try pk.verify(msg, sig),
62 };
63 }
64
65 pub fn wipe(self: *Self) void {
66 return switch (self.*) {
67 .seed_key_pair => |*kp| kp.wipe(),
68 .public_key => |*pk| pk.wipe(),
69 };
70 }
71};
72
73pub const KeyTypePrefixByte = enum(u8) {
74 seed = 18 << 3, // S
75 private = 15 << 3, // P
76 unknown = 23 << 3, // U
77};
78
79pub const PublicPrefixByte = enum(u8) {
80 account = 0, // A
81 cluster = 2 << 3, // C
82 operator = 14 << 3, // O
83 server = 13 << 3, // N
84 user = 20 << 3, // U
85
86 fn fromU8(b: u8) !PublicPrefixByte {
87 return switch (b) {
88 @enumToInt(PublicPrefixByte.server) => .server,
89 @enumToInt(PublicPrefixByte.cluster) => .cluster,
90 @enumToInt(PublicPrefixByte.operator) => .operator,
91 @enumToInt(PublicPrefixByte.account) => .account,
92 @enumToInt(PublicPrefixByte.user) => .user,
93 else => error.InvalidPrefixByte,
94 };
95 }
96};
97
98pub const SeedKeyPair = struct {
99 const Self = @This();
100
101 seed: text_seed,
102
103 pub fn init(prefix: PublicPrefixByte) !Self {
104 var raw_seed: [Ed25519.seed_length]u8 = undefined;
105 crypto.random.bytes(&raw_seed);
106 defer wipeBytes(&raw_seed);
107
108 var seed = try encodeSeed(prefix, &raw_seed);
109 return Self{ .seed = seed };
110 }
111
112 pub fn initFromSeed(seed: *const text_seed) !Self {
113 var decoded = try decodeSeed(seed);
114 defer decoded.wipe();
115
116 return Self{ .seed = seed.* };
117 }
118
119 fn rawSeed(self: *const Self) ![Ed25519.seed_length]u8 {
120 return (try decodeSeed(&self.seed)).seed;
121 }
122
123 fn keys(self: *const Self) !Ed25519.KeyPair {
124 return Ed25519.KeyPair.create(try rawSeed(self));
125 }
126
127 pub fn privateKey(self: *const Self) !text_private {
128 var kp = try self.keys();
129 defer wipeKeyPair(&kp);
130 return try encodePrivate(&kp.secret_key);
131 }
132
133 pub fn publicKey(self: *const Self) !text_public {
134 var decoded = try decodeSeed(&self.seed);
135 defer decoded.wipe();
136 var kp = try Ed25519.KeyPair.create(decoded.seed);
137 defer wipeKeyPair(&kp);
138 return try encodePublic(decoded.prefix, &kp.public_key);
139 }
140
141 pub fn intoPublicKey(self: *const Self) !PublicKey {
142 var decoded = try decodeSeed(&self.seed);
143 var kp = try Ed25519.KeyPair.create(decoded.seed);
144 defer wipeKeyPair(&kp);
145 return PublicKey{
146 .prefix = decoded.prefix,
147 .key = kp.public_key,
148 };
149 }
150
151 pub fn sign(
152 self: *const Self,
153 msg: []const u8,
154 ) ![Ed25519.signature_length]u8 {
155 var kp = try self.keys();
156 defer wipeKeyPair(&kp);
157 return try Ed25519.sign(msg, kp, null);
158 }
159
160 pub fn verify(
161 self: *const Self,
162 msg: []const u8,
163 sig: [Ed25519.signature_length]u8,
164 ) !void {
165 var kp = try self.keys();
166 defer wipeKeyPair(&kp);
167 try Ed25519.verify(sig, msg, kp.public_key);
168 }
169
170 pub fn wipe(self: *Self) void {
171 wipeBytes(&self.seed);
172 }
173
174 fn wipeKeyPair(kp: *Ed25519.KeyPair) void {
175 wipeBytes(&kp.secret_key);
176 }
177};
178
179fn wipeBytes(bs: []u8) void {
180 for (bs) |*b| b.* = 0;
181}
182
183pub const PublicKey = struct {
184 const Self = @This();
185
186 prefix: PublicPrefixByte,
187 key: [Ed25519.public_length]u8,
188
189 pub fn publicKey(self: *const Self) !text_public {
190 return try encodePublic(self.prefix, &self.key);
191 }
192
193 pub fn verify(
194 self: *const Self,
195 msg: []const u8,
196 sig: [Ed25519.signature_length]u8,
197 ) !void {
198 try Ed25519.verify(sig, msg, self.key);
199 }
200
201 pub fn wipe(self: *Self) void {
202 self.prefix = .user;
203 std.crypto.random.bytes(&self.key);
204 }
205};
206
207// One prefix byte, two CRC bytes
208const binary_private_size = 1 + Ed25519.secret_length + 2;
209// One prefix byte, two CRC bytes
210const binary_public_size = 1 + Ed25519.public_length + 2;
211// Two prefix bytes, two CRC bytes
212const binary_seed_size = 2 + Ed25519.seed_length + 2;
213
214pub const text_private_len = base32.encodedLen(binary_private_size);
215pub const text_public_len = base32.encodedLen(binary_public_size);
216pub const text_seed_len = base32.encodedLen(binary_seed_size);
217
218pub const text_private = [text_private_len]u8;
219pub const text_public = [text_public_len]u8;
220pub const text_seed = [text_seed_len]u8;
221
222pub fn encodePublic(prefix: PublicPrefixByte, key: *const [Ed25519.public_length]u8) !text_public {
223 return encode(1, key.len, &[_]u8{@enumToInt(prefix)}, key);
224}
225
226pub fn encodePrivate(key: *const [Ed25519.secret_length]u8) !text_private {
227 return encode(1, key.len, &[_]u8{@enumToInt(KeyTypePrefixByte.private)}, key);
228}
229
230fn EncodedKey(comptime prefix_len: usize, comptime data_len: usize) type {
231 return [base32.encodedLen(prefix_len + data_len + 2)]u8;
232}
233
234fn encode(
235 comptime prefix_len: usize,
236 comptime data_len: usize,
237 prefix: *const [prefix_len]u8,
238 data: *const [data_len]u8,
239) !EncodedKey(prefix_len, data_len) {
240 var buf: [prefix_len + data_len + 2]u8 = undefined;
241 defer wipeBytes(&buf);
242
243 mem.copy(u8, &buf, prefix[0..]);
244 mem.copy(u8, buf[prefix_len..], data[0..]);
245 var off = prefix_len + data_len;
246 var checksum = crc16.make(buf[0..off]);
247 mem.writeIntLittle(u16, buf[buf.len - 2 .. buf.len], checksum);
248
249 var text: EncodedKey(prefix_len, data_len) = undefined;
250 std.debug.assert(base32.encode(&buf, &text) == text.len);
251
252 return text;
253}
254
255pub fn encodeSeed(prefix: PublicPrefixByte, src: *const [Ed25519.seed_length]u8) !text_seed {
256 var full_prefix = [_]u8{
257 @enumToInt(KeyTypePrefixByte.seed) | (@enumToInt(prefix) >> 5),
258 (@enumToInt(prefix) & 0b00011111) << 3,
259 };
260 return encode(full_prefix.len, src.len, &full_prefix, src);
261}
262
263pub fn decodePrivate(text: *const text_private) ![Ed25519.secret_length]u8 {
264 var decoded = try decode(1, Ed25519.secret_length, text);
265 defer wipeBytes(&decoded.data);
266 if (decoded.prefix[0] != @enumToInt(KeyTypePrefixByte.private))
267 return error.InvalidPrefixByte;
268 return decoded.data;
269}
270
271pub fn decodePublic(prefix: PublicPrefixByte, text: *const text_public) ![Ed25519.public_length]u8 {
272 var decoded = try decode(1, Ed25519.public_length, text);
273 if (decoded.data[0] != @enumToInt(prefix))
274 return error.InvalidPrefixByte;
275 return decoded.data;
276}
277
278fn DecodedNKey(comptime prefix_len: usize, comptime data_len: usize) type {
279 return struct {
280 prefix: [prefix_len]u8,
281 data: [data_len]u8,
282 };
283}
284
285fn decode(
286 comptime prefix_len: usize,
287 comptime data_len: usize,
288 text: *const [base32.encodedLen(prefix_len + data_len + 2)]u8,
289) !DecodedNKey(prefix_len, data_len) {
290 var raw: [prefix_len + data_len + 2]u8 = undefined;
291 defer wipeBytes(&raw);
292 std.debug.assert((try base32.decode(text[0..], &raw)) == raw.len);
293
294 var checksum = mem.readIntLittle(u16, raw[raw.len - 2 .. raw.len]);
295 try crc16.validate(raw[0 .. raw.len - 2], checksum);
296
297 return DecodedNKey(prefix_len, data_len){
298 .prefix = raw[0..prefix_len].*,
299 .data = raw[prefix_len .. raw.len - 2].*,
300 };
301}
302
303pub const DecodedSeed = struct {
304 const Self = @This();
305
306 prefix: PublicPrefixByte,
307 seed: [Ed25519.seed_length]u8,
308
309 pub fn wipe(self: *Self) void {
310 self.prefix = .account;
311 wipeBytes(&self.seed);
312 }
313};
314
315pub fn decodeSeed(text: *const text_seed) !DecodedSeed {
316 var decoded = try decode(2, Ed25519.seed_length, text);
317 defer wipeBytes(&decoded.data); // gets copied
318
319 var key_ty_prefix = decoded.prefix[0] & 0b11111000;
320 var entity_ty_prefix = (decoded.prefix[0] & 0b00000111) << 5 | ((decoded.prefix[1] & 0b11111000) >> 3);
321
322 if (key_ty_prefix != @enumToInt(KeyTypePrefixByte.seed))
323 return error.InvalidSeed;
324
325 return DecodedSeed{
326 .prefix = try PublicPrefixByte.fromU8(entity_ty_prefix),
327 .seed = decoded.data,
328 };
329}
330
331pub fn fromPublicKey(text: *const text_public) !PublicKey {
332 var decoded = try decode(1, Ed25519.public_length, text);
333 defer wipeBytes(&decoded.data); // gets copied
334
335 return PublicKey{
336 .prefix = try PublicPrefixByte.fromU8(decoded.prefix[0]),
337 .key = decoded.data,
338 };
339}
340
341pub fn fromSeed(text: *const text_seed) !SeedKeyPair {
342 var res = try decodeSeed(text);
343 wipeBytes(&res.seed);
344 return SeedKeyPair{ .seed = text.* };
345}
346
347pub fn isValidEncoding(text: []const u8) bool {
348 if (text.len < 4) return false;
349 var made_crc: u16 = 0;
350 var dec = base32.Decoder{};
351 var crc_buf: [2]u8 = undefined;
352 var crc_buf_len: u8 = 0;
353 var expect_len: usize = base32.decodedLen(text.len);
354 var wrote_n_total: usize = 0;
355 for (text) |c, i| {
356 var b = (dec.read(c) catch return false) orelse continue;
357 wrote_n_total += 1;
358 if (crc_buf_len == 2) made_crc = crc16.update(made_crc, &.{crc_buf[0]});
359 crc_buf[0] = crc_buf[1];
360 crc_buf[1] = b;
361 if (crc_buf_len != 2) crc_buf_len += 1;
362 }
363 if (dec.out_off != 0 and wrote_n_total < expect_len) {
364 if (crc_buf_len == 2) made_crc = crc16.update(made_crc, &.{crc_buf[0]});
365 crc_buf[0] = crc_buf[1];
366 crc_buf[1] = dec.buf;
367 if (crc_buf_len != 2) crc_buf_len += 1;
368 }
369 if (crc_buf_len != 2) unreachable;
370 var got_crc = mem.readIntLittle(u16, &crc_buf);
371 return made_crc == got_crc;
372}
373
374pub fn isValidSeed(text: *const text_seed) bool {
375 var res = decodeSeed(text) catch return false;
376 wipeBytes(&res.seed);
377 return true;
378}
379
380pub fn isValidPublicKey(text: *const text_public, with_type: ?PublicPrefixByte) bool {
381 var res = decode(1, Ed25519.public_length, text) catch return false;
382 var public = PublicPrefixByte.fromU8(res.data[0]) catch return false;
383 return if (with_type) |ty| public == ty else true;
384}
385
386pub fn fromRawSeed(prefix: PublicPrefixByte, raw_seed: *const [Ed25519.seed_length]u8) !SeedKeyPair {
387 return SeedKeyPair{ .seed = try encodeSeed(prefix, raw_seed) };
388}
389
390pub fn getNextLine(text: []const u8, off: *usize) ?[]const u8 {
391 if (off.* <= text.len) return null;
392 var newline_pos = mem.indexOfPos(u8, text, off.*, "\n") orelse return null;
393 var start = off.*;
394 var end = newline_pos;
395 if (newline_pos > 0 and text[newline_pos - 1] == '\r') end -= 1;
396 off.* = newline_pos + 1;
397 return text[start..end];
398}
399
400// `line` must not contain CR or LF characters.
401pub fn isKeySectionBarrier(line: []const u8) bool {
402 return line.len >= 6 and mem.startsWith(u8, line, "---") and mem.endsWith(u8, line, "---");
403}
404
405pub fn areKeySectionContentsValid(contents: []const u8) bool {
406 const allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.=";
407
408 for (contents) |c| {
409 var is_c_allowed = false;
410 for (allowed_chars) |allowed_c| {
411 if (c == allowed_c) {
412 is_c_allowed = true;
413 break;
414 }
415 }
416 if (!is_c_allowed) return false;
417 }
418
419 return true;
420}
421
422pub fn findKeySection(text: []const u8, off: *usize) ?[]const u8 {
423 // Skip all space
424 // Lines end with \n, but \r\n is also fine
425 // Contents of the key may consist of abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.=
426 // However, if a line seems to be in the form of ---stuff---, the section is ended.
427 // A newline must be present at the end of the key footer
428 // See https://regex101.com/r/pEaqcJ/1 for a weird edge case in the github.com/nats-io/nkeys library
429 // Another weird edge case: https://regex101.com/r/Xmqj1h/1
430 while (true) {
431 var opening_line = getNextLine(text, off) orelse return null;
432 if (!isKeySectionBarrier(opening_line)) continue;
433
434 var contents_line = getNextLine(text, off) orelse return null;
435 if (!areKeySectionContentsValid(contents_line)) continue;
436
437 var closing_line = getNextLine(text, off) orelse return null;
438 if (!isKeySectionBarrier(closing_line)) continue;
439
440 return contents_line;
441 }
442}
443
444pub fn parseDecoratedJwt(contents: []const u8) ![]const u8 {
445 var current_off: usize = 0;
446 return findKeySection(contents, &current_off) orelse return contents;
447}
448
449fn validNKey(text: []const u8) bool {
450 var valid_prefix =
451 mem.startsWith(u8, text, "SO") or
452 mem.startsWith(u8, text, "SA") or
453 mem.startsWith(u8, text, "SU");
454 var valid_len = text.len >= text_seed_len;
455 return valid_prefix and valid_len;
456}
457
458fn findNKey(text: []const u8) ?[]const u8 {
459 var current_off: usize = 0;
460 while (true) {
461 var line = getNextLine(text, &current_off) orelse return null;
462 for (line) |c, i| {
463 if (!ascii.isSpace(c)) {
464 if (validNKey(line[i..])) return line[i..];
465 break;
466 }
467 }
468 }
469}
470
471pub fn parseDecoratedNKey(contents: []const u8) !SeedKeyPair {
472 var current_off: usize = 0;
473
474 var seed: ?[]const u8 = null;
475 if (findKeySection(contents, &current_off) != null)
476 seed = findKeySection(contents, &current_off);
477 if (seed != null)
478 seed = findNKey(contents) orelse return error.NoNKeySeedFound;
479 if (!validNKey(seed.?))
480 return error.NoNKeySeedFound;
481 return fromSeed(contents[0..text_seed_len]);
482}
483
484pub fn parseDecoratedUserNKey(contents: []const u8) !SeedKeyPair {
485 var key = try parseDecoratedNKey(contents);
486 if (!mem.startsWith(u8, &key.seed, "SU")) return error.NoNKeyUserSeedFound;
487 defer key.wipe();
488 return key;
489}
490
491test {
492 testing.refAllDecls(@This());
493 testing.refAllDecls(Key);
494 testing.refAllDecls(SeedKeyPair);
495 testing.refAllDecls(PublicKey);
496}
497
498test {
499 var key_pair = try SeedKeyPair.init(PublicPrefixByte.server);
500 defer key_pair.wipe();
501
502 var decoded_seed = try decodeSeed(&key_pair.seed);
503 var encoded_second_time = try encodeSeed(decoded_seed.prefix, &decoded_seed.seed);
504 try testing.expectEqualSlices(u8, &key_pair.seed, &encoded_second_time);
505 try testing.expect(isValidEncoding(&key_pair.seed));
506
507 var pub_key_str_a = try key_pair.publicKey();
508 var priv_key_str = try key_pair.privateKey();
509 try testing.expect(pub_key_str_a.len != 0);
510 try testing.expect(priv_key_str.len != 0);
511 try testing.expect(isValidEncoding(&pub_key_str_a));
512 try testing.expect(isValidEncoding(&priv_key_str));
513 wipeBytes(&priv_key_str);
514
515 var pub_key = try key_pair.intoPublicKey();
516 var pub_key_str_b = try pub_key.publicKey();
517 try testing.expectEqualSlices(u8, &pub_key_str_a, &pub_key_str_b);
518}