also looking at this
Harden encrypted mail storage, recovery, and forwarding
#8
50 files
+1701
-9001
| @@ -1,663 +0,0 @@ | ||
| 1 | const std = @import("std"); | |
| 2 | const builtin = @import("builtin"); | |
| 3 | const mem = std.mem; | |
| 4 | const Io = std.Io; | |
| 5 | const assert = std.debug.assert; | |
| 6 | ||
| 7 | const proto = @import("protocol.zig"); | |
| 8 | const record = @import("record.zig"); | |
| 9 | const Record = record.Record; | |
| 10 | const cipher = @import("cipher.zig"); | |
| 11 | const Cipher = cipher.Cipher; | |
| 12 | const SessionResumption = @import("handshake_client.zig").Options.SessionResumption; | |
| 13 | ||
| 14 | const log = std.log.scoped(.tls); | |
| 15 | ||
| 16 | pub const Connection = struct { | |
| 17 | /// Underlying network connection stream reader/writer pair. | |
| 18 | input: *Io.Reader, // source of the encrypted (ciphertext) data | |
| 19 | output: *Io.Writer, // sink to send encrypted (ciphertext) data | |
| 20 | cipher: Cipher, | |
| 21 | ||
| 22 | max_encrypt_seq: u64 = std.math.maxInt(u64) - 1, | |
| 23 | key_update_requested: bool = false, | |
| 24 | received_close_notify: bool = false, | |
| 25 | /// Part of the cleartext record returned from next but not yet read by client. | |
| 26 | cleartext_buf: []const u8 = &.{}, | |
| 27 | ||
| 28 | session_resumption: ?*SessionResumption = null, | |
| 29 | session_resumption_secret_idx: ?usize = null, | |
| 30 | ||
| 31 | const Self = @This(); | |
| 32 | ||
| 33 | /// Encrypts and writes single tls record to the stream. | |
| 34 | fn writeRecord(c: *Self, content_type: proto.ContentType, bytes: []const u8) !void { | |
| 35 | assert(bytes.len <= cipher.max_cleartext_len); | |
| 36 | // If key update is requested send key update message and update | |
| 37 | // my encryption keys. | |
| 38 | if (c.cipher.encryptSeq() >= c.max_encrypt_seq or @atomicLoad(bool, &c.key_update_requested, .monotonic)) { | |
| 39 | @atomicStore(bool, &c.key_update_requested, false, .monotonic); | |
| 40 | ||
| 41 | // If the request_update field is set to "update_requested", | |
| 42 | // then the receiver MUST send a KeyUpdate of its own with | |
| 43 | // request_update set to "update_not_requested" prior to sending | |
| 44 | // its next Application Data record. This mechanism allows | |
| 45 | // either side to force an update to the entire connection, but | |
| 46 | // causes an implementation which receives multiple KeyUpdates | |
| 47 | // while it is silent to respond with a single update. | |
| 48 | // | |
| 49 | // rfc: https://datatracker.ietf.org/doc/html/rfc8446#autoid-57 | |
| 50 | const key_update = &record.handshakeHeader(.key_update, 1) ++ [_]u8{0}; | |
| 51 | try c.encryptWrite(.handshake, key_update); | |
| 52 | try c.cipher.keyUpdateEncrypt(); | |
| 53 | } | |
| 54 | try c.encryptWrite(content_type, bytes); | |
| 55 | } | |
| 56 | ||
| 57 | fn encryptWrite(c: *Self, content_type: proto.ContentType, bytes: []const u8) !void { | |
| 58 | const encrypted_len = c.cipher.recordLen(bytes.len); | |
| 59 | const writable = try c.output.writableSliceGreedy(encrypted_len); | |
| 60 | const rec = try c.cipher.encrypt(writable, content_type, bytes); | |
| 61 | c.output.advance(rec.len); | |
| 62 | try c.output.flush(); | |
| 63 | } | |
| 64 | ||
| 65 | /// Returns next record of cleartext data. Null on end of stream. | |
| 66 | /// Can be used in iterator like loop without memcpy to another buffer: | |
| 67 | /// while (try client.next()) |buf| { ... } | |
| 68 | pub fn next(c: *Self) anyerror!?[]const u8 { | |
| 69 | return c.nextRecord(&.{}) catch |err| { | |
| 70 | if (err == error.EndOfStream) return null; | |
| 71 | // Write alert on tls errors. | |
| 72 | // Stream errors return to the caller. | |
| 73 | if (mem.startsWith(u8, @errorName(err), "Tls")) | |
| 74 | try c.encryptWrite(.alert, &proto.alertFromError(err)); | |
| 75 | return err; | |
| 76 | }; | |
| 77 | } | |
| 78 | ||
| 79 | /// Decrypt next tls record into buffer, if buffer is not big enough reuse | |
| 80 | /// input ciphertext buffer for cleartext. Returns cleartext of the next tls | |
| 81 | /// record. | |
| 82 | fn nextRecord(c: *Self, buffer: []u8) ![]const u8 { | |
| 83 | assert(c.cleartext_buf.len == 0); | |
| 84 | if (c.received_close_notify) return error.EndOfStream; | |
| 85 | while (true) { | |
| 86 | const rec = try Record.read(c.input); | |
| 87 | if (rec.protocol_version != .tls_1_2) return error.TlsBadVersion; | |
| 88 | ||
| 89 | // If provided buffer is not big enought reuse input buffer for | |
| 90 | // cleartext. `rec.header` and `rec.payload`(ciphertext) are | |
| 91 | // pointing somewhere in this buffer. Decrypter is first reading | |
| 92 | // then writing a block, cleartext has less length then ciphertext, | |
| 93 | // cleartext starts from the beginning of the buffer, so ciphertext | |
| 94 | // is always ahead of cleartext. | |
| 95 | const cleartext_buf = if (buffer.len >= rec.payload.len) buffer else @constCast(rec.buffer); | |
| 96 | const content_type, const cleartext = try c.cipher.decrypt(cleartext_buf, rec); | |
| 97 | ||
| 98 | switch (content_type) { | |
| 99 | .application_data => {}, | |
| 100 | .handshake => { | |
| 101 | const handshake_type: proto.Handshake = @fromBackingInt(@intCast(cleartext[0])); | |
| 102 | switch (handshake_type) { | |
| 103 | .new_session_ticket => { | |
| 104 | if (c.session_resumption) |r| { | |
| 105 | r.pushTicket(cleartext, c.session_resumption_secret_idx.?) catch {}; | |
| 106 | } | |
| 107 | continue; | |
| 108 | }, | |
| 109 | .key_update => { | |
| 110 | if (cleartext.len != 5) return error.TlsDecodeError; | |
| 111 | // rfc: Upon receiving a KeyUpdate, the receiver MUST | |
| 112 | // update its receiving keys. | |
| 113 | try c.cipher.keyUpdateDecrypt(); | |
| 114 | const key: proto.KeyUpdateRequest = @fromBackingInt(@intCast(cleartext[4])); | |
| 115 | switch (key) { | |
| 116 | .update_requested => { | |
| 117 | @atomicStore(bool, &c.key_update_requested, true, .monotonic); | |
| 118 | }, | |
| 119 | .update_not_requested => {}, | |
| 120 | else => return error.TlsIllegalParameter, | |
| 121 | } | |
| 122 | // this record is handled read next | |
| 123 | continue; | |
| 124 | }, | |
| 125 | else => {}, | |
| 126 | } | |
| 127 | }, | |
| 128 | .alert => { | |
| 129 | if (cleartext.len < 2) return error.TlsUnexpectedMessage; | |
| 130 | try proto.Alert.parse(cleartext[0..2].*).toError(); | |
| 131 | // server side clean shutdown | |
| 132 | c.received_close_notify = true; | |
| 133 | return error.EndOfStream; | |
| 134 | }, | |
| 135 | else => return error.TlsUnexpectedMessage, | |
| 136 | } | |
| 137 | return cleartext; | |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | pub fn eof(c: *Self) bool { | |
| 142 | return c.received_close_notify and c.cleartext_buf.len == 0; | |
| 143 | } | |
| 144 | ||
| 145 | pub fn close(c: *Self) anyerror!void { | |
| 146 | if (c.received_close_notify) return; | |
| 147 | try c.writeRecord(.alert, &proto.Alert.closeNotify()); | |
| 148 | } | |
| 149 | ||
| 150 | // write/read | |
| 151 | ||
| 152 | /// Encrypts cleartext and writes it to the underlying stream as single | |
| 153 | /// tls record. Max single tls record payload length is 1<<14 (16K) | |
| 154 | /// bytes. | |
| 155 | pub fn write(c: *Self, bytes: []const u8) !usize { | |
| 156 | const encrypt_overhead = c.cipher.encryptOverhead(); | |
| 157 | assert(c.output.buffer.len > encrypt_overhead); | |
| 158 | // Find maximum number of bytes which can fit into output buffer as encrypted ciphertext | |
| 159 | const n = @min(bytes.len, cipher.max_cleartext_len, c.output.buffer.len - encrypt_overhead); | |
| 160 | try c.writeRecord(.application_data, bytes[0..n]); | |
| 161 | return n; | |
| 162 | } | |
| 163 | ||
| 164 | /// Encrypts cleartext and writes it to the underlying stream. If needed | |
| 165 | /// splits cleartext into multiple tls record. | |
| 166 | pub fn writeAll(c: *Self, bytes: []const u8) !void { | |
| 167 | var index: usize = 0; | |
| 168 | while (index < bytes.len) { | |
| 169 | index += try c.write(bytes[index..]); | |
| 170 | } | |
| 171 | } | |
| 172 | ||
| 173 | pub fn read(c: *Self, buffer: []u8) !usize { | |
| 174 | if (c.cleartext_buf.len == 0) { | |
| 175 | const cleartext = c.nextRecord(buffer) catch |err| { | |
| 176 | if (err == error.EndOfStream) return 0; | |
| 177 | if (mem.startsWith(u8, @errorName(err), "Tls")) | |
| 178 | try c.encryptWrite(.alert, &proto.alertFromError(err)); | |
| 179 | return err; | |
| 180 | }; | |
| 181 | if (cleartext.ptr == buffer.ptr) { | |
| 182 | // provided buffer is used for cleartext | |
| 183 | return cleartext.len; | |
| 184 | } | |
| 185 | // Buffer was too small input ciphertext buffer was used for cleartext | |
| 186 | // Store referenct to the cleartext | |
| 187 | c.cleartext_buf = cleartext; | |
| 188 | } | |
| 189 | // move part of the cleartext_buf into provided buffer | |
| 190 | const n = @min(c.cleartext_buf.len, buffer.len); | |
| 191 | @memcpy(buffer[0..n], c.cleartext_buf[0..n]); | |
| 192 | c.cleartext_buf = c.cleartext_buf[n..]; | |
| 193 | return n; | |
| 194 | } | |
| 195 | ||
| 196 | /// Returns the number of bytes read. If the number read is smaller than | |
| 197 | /// `buffer.len`, it means the stream reached the end. | |
| 198 | pub fn readAll(c: *Self, buffer: []u8) !usize { | |
| 199 | return c.readAtLeast(buffer, buffer.len); | |
| 200 | } | |
| 201 | ||
| 202 | /// Returns the number of bytes read, calling the underlying read function | |
| 203 | /// the minimal number of times until the buffer has at least `len` bytes | |
| 204 | /// filled. If the number read is less than `len` it means the stream | |
| 205 | /// reached the end. | |
| 206 | pub fn readAtLeast(c: *Self, buffer: []u8, len: usize) !usize { | |
| 207 | assert(len <= buffer.len); | |
| 208 | var index: usize = 0; | |
| 209 | while (index < len) { | |
| 210 | const amt = try c.read(buffer[index..]); | |
| 211 | if (amt == 0) break; | |
| 212 | index += amt; | |
| 213 | } | |
| 214 | return index; | |
| 215 | } | |
| 216 | ||
| 217 | /// Returns the number of bytes read. If the number read is less than | |
| 218 | /// the space provided it means the stream reached the end. | |
| 219 | pub fn readv(c: *Self, iovecs: []std.posix.iovec) !usize { | |
| 220 | var vp: VecPut = .{ .iovecs = iovecs }; | |
| 221 | while (true) { | |
| 222 | if (c.cleartext_buf.len == 0) { | |
| 223 | c.cleartext_buf = try c.next() orelse break; | |
| 224 | } | |
| 225 | const n = vp.put(c.cleartext_buf); | |
| 226 | const read_buf_len = c.cleartext_buf.len; | |
| 227 | c.cleartext_buf = c.cleartext_buf[n..]; | |
| 228 | if (n < read_buf_len) break; | |
| 229 | } | |
| 230 | return vp.total; | |
| 231 | } | |
| 232 | ||
| 233 | // Io.Reader interface | |
| 234 | ||
| 235 | pub const Reader = struct { | |
| 236 | conn: *Connection, | |
| 237 | interface: Io.Reader, | |
| 238 | err: ?anyerror = null, | |
| 239 | ||
| 240 | pub fn init(c: *Connection, buffer: []u8) Reader { | |
| 241 | return .{ | |
| 242 | .conn = c, | |
| 243 | .interface = .{ | |
| 244 | .vtable = &.{ | |
| 245 | .stream = stream, | |
| 246 | }, | |
| 247 | .buffer = buffer, | |
| 248 | .seek = 0, | |
| 249 | .end = 0, | |
| 250 | }, | |
| 251 | }; | |
| 252 | } | |
| 253 | ||
| 254 | fn stream(r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { | |
| 255 | const self: *Reader = @fieldParentPtr("interface", r); | |
| 256 | const n = self.conn.read(limit.slice(w.unusedCapacitySlice())) catch |err| { | |
| 257 | self.err = err; | |
| 258 | if (err == error.EndOfStream) return error.EndOfStream; | |
| 259 | return error.ReadFailed; | |
| 260 | }; | |
| 261 | if (n == 0) return error.EndOfStream; | |
| 262 | w.advance(n); | |
| 263 | return n; | |
| 264 | } | |
| 265 | }; | |
| 266 | ||
| 267 | /// There is no strict requirement on buffer size. | |
| 268 | /// If the buffer is big enough tls record will be decrypted directly into | |
| 269 | /// provided buffer. If not input buffer will be used for record decryption | |
| 270 | /// and than cleartext will be copied to the reader buffer when needed. | |
| 271 | pub fn reader(c: *Self, buffer: []u8) Reader { | |
| 272 | return .init(c, buffer); | |
| 273 | } | |
| 274 | ||
| 275 | // Io.Writer interface | |
| 276 | ||
| 277 | pub const Writer = struct { | |
| 278 | conn: *Connection, | |
| 279 | interface: Io.Writer, | |
| 280 | err: ?anyerror = null, | |
| 281 | ||
| 282 | pub fn init(c: *Connection, buffer: []u8) Writer { | |
| 283 | return .{ | |
| 284 | .conn = c, | |
| 285 | .interface = .{ | |
| 286 | .vtable = &.{ | |
| 287 | .drain = drain, | |
| 288 | }, | |
| 289 | .buffer = buffer, | |
| 290 | .end = 0, | |
| 291 | }, | |
| 292 | }; | |
| 293 | } | |
| 294 | ||
| 295 | fn drain(w: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize { | |
| 296 | const self: *Writer = @fieldParentPtr("interface", w); | |
| 297 | // w.buffer is consumed first | |
| 298 | try self.writeAll(w.buffered()); | |
| 299 | w.end = 0; | |
| 300 | ||
| 301 | if (data.len == 0) return 0; | |
| 302 | // Followed by each slice of `data` in order | |
| 303 | var n: usize = 0; | |
| 304 | for (data[0 .. data.len - 1]) |bytes| { | |
| 305 | try self.writeAll(bytes); | |
| 306 | n += bytes.len; | |
| 307 | } | |
| 308 | ||
| 309 | // Last element of `data` is repeated as necessary so that it is | |
| 310 | // written `splat` number of times, which may be zero. | |
| 311 | const pattern = data[data.len - 1]; | |
| 312 | for (0..splat) |_| { | |
| 313 | try self.writeAll(pattern); | |
| 314 | n += pattern.len; | |
| 315 | } | |
| 316 | ||
| 317 | // Number of bytes consumed from `data` is returned, excluding bytes | |
| 318 | // from w.buffer. | |
| 319 | return n; | |
| 320 | } | |
| 321 | ||
| 322 | fn writeAll(self: *Writer, bytes: []const u8) Io.Writer.Error!void { | |
| 323 | self.conn.writeAll(bytes) catch |err| { | |
| 324 | self.err = err; | |
| 325 | return error.WriteFailed; | |
| 326 | }; | |
| 327 | } | |
| 328 | }; | |
| 329 | ||
| 330 | pub fn writer(c: *Self, buffer: []u8) Writer { | |
| 331 | return .init(c, buffer); | |
| 332 | } | |
| 333 | }; | |
| 334 | ||
| 335 | const testing = std.testing; | |
| 336 | const data12 = @import("testdata/tls12.zig"); | |
| 337 | const testu = @import("testu.zig"); | |
| 338 | ||
| 339 | test "encrypt decrypt" { | |
| 340 | var output_buf: [1024]u8 = undefined; | |
| 341 | const server_pongs = data12.server_pong ++ data12.server_pong ++ | |
| 342 | data12.server_pong ++ data12.server_pong; | |
| 343 | var stream_reader: Io.Reader = .fixed(&server_pongs); | |
| 344 | var stream_writer: Io.Writer = .fixed(&output_buf); | |
| 345 | var conn: Connection = .{ | |
| 346 | .input = &stream_reader, | |
| 347 | .output = &stream_writer, | |
| 348 | .cipher = try Cipher.initTls12(.ECDHE_RSA_WITH_AES_128_CBC_SHA, &data12.key_material, .client), | |
| 349 | }; | |
| 350 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.rnd = testu.random(0); // use fixed rng | |
| 351 | ||
| 352 | { // encrypt verify data from example | |
| 353 | _ = testu.random(0x40); // sets iv to 40, 41, ... 4f | |
| 354 | try conn.writeRecord(.handshake, &data12.client_finished); | |
| 355 | try testing.expectEqualSlices(u8, &data12.verify_data_encrypted_msg, conn.output.buffered()); | |
| 356 | } | |
| 357 | _ = conn.output.consumeAll(); // reset writer buffer | |
| 358 | { // encrypt ping | |
| 359 | const cleartext = "ping"; | |
| 360 | _ = testu.random(0); // sets iv to 00, 01, ... 0f | |
| 361 | ||
| 362 | try conn.writeAll(cleartext); | |
| 363 | try testing.expectEqualSlices(u8, &data12.encrypted_ping_msg, conn.output.buffered()); | |
| 364 | } | |
| 365 | _ = conn.output.consumeAll(); | |
| 366 | { // writer interface | |
| 367 | const cleartext = "ping"; | |
| 368 | _ = testu.random(0); // sets iv to 00, 01, ... 0f | |
| 369 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.encrypt_seq = 1; // reset sequence | |
| 370 | ||
| 371 | var writer = conn.writer(&.{}); | |
| 372 | var w = &writer.interface; | |
| 373 | try w.writeAll(cleartext); | |
| 374 | try testing.expectEqualSlices(u8, &data12.encrypted_ping_msg, conn.output.buffered()); | |
| 375 | } | |
| 376 | { // decrypt server pong message | |
| 377 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.decrypt_seq = 1; | |
| 378 | try testing.expectEqualStrings("pong", (try conn.next()).?); | |
| 379 | } | |
| 380 | { // test reader interface | |
| 381 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.decrypt_seq = 1; | |
| 382 | var buffer: [2]u8 = undefined; | |
| 383 | var reader = conn.reader(&buffer); | |
| 384 | var rdr = &reader.interface; | |
| 385 | try testing.expectEqualStrings("", conn.cleartext_buf); | |
| 386 | try testing.expectEqualStrings("po", try rdr.take(rdr.buffer.len)); | |
| 387 | // cleartext record part which didn't fit into reader buffer | |
| 388 | try testing.expectEqualStrings("ng", conn.cleartext_buf); | |
| 389 | try testing.expectEqualStrings("n", try rdr.take(1)); | |
| 390 | try testing.expectEqualStrings("", conn.cleartext_buf); | |
| 391 | try testing.expectEqualStrings("g", try rdr.take(1)); | |
| 392 | } | |
| 393 | { // reader discard | |
| 394 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.decrypt_seq = 1; | |
| 395 | var buffer: [5]u8 = undefined; | |
| 396 | var reader = conn.reader(&buffer); | |
| 397 | var rdr = &reader.interface; | |
| 398 | try testing.expectEqual(1, try rdr.discard(.limited(1))); | |
| 399 | try testing.expectEqualStrings("ong", conn.cleartext_buf); | |
| 400 | try testing.expectEqual(3, try rdr.discard(.limited(3))); | |
| 401 | } | |
| 402 | { // test readv interface | |
| 403 | conn.cipher.ECDHE_RSA_WITH_AES_128_CBC_SHA.decrypt_seq = 1; | |
| 404 | var buffer: [9]u8 = undefined; | |
| 405 | var iovecs = [_]std.posix.iovec{ | |
| 406 | .{ .base = &buffer, .len = 3 }, | |
| 407 | .{ .base = buffer[3..], .len = 3 }, | |
| 408 | .{ .base = buffer[6..], .len = 3 }, | |
| 409 | }; | |
| 410 | const n = try conn.readv(iovecs[0..]); | |
| 411 | try testing.expectEqual(4, n); | |
| 412 | try testing.expectEqualStrings("pong", buffer[0..n]); | |
| 413 | } | |
| 414 | } | |
| 415 | ||
| 416 | // Copied from: https://github.com/ziglang/zig/blob/455899668b620dfda40252501c748c0a983555bd/lib/std/crypto/tls/Client.zig#L1354 | |
| 417 | /// Abstraction for sending multiple byte buffers to a slice of iovecs. | |
| 418 | pub const VecPut = struct { | |
| 419 | iovecs: []const std.posix.iovec, | |
| 420 | idx: usize = 0, | |
| 421 | off: usize = 0, | |
| 422 | total: usize = 0, | |
| 423 | ||
| 424 | /// Returns the amount actually put which is always equal to bytes.len | |
| 425 | /// unless the vectors ran out of space. | |
| 426 | pub fn put(vp: *VecPut, bytes: []const u8) usize { | |
| 427 | if (vp.idx >= vp.iovecs.len) return 0; | |
| 428 | var bytes_i: usize = 0; | |
| 429 | while (true) { | |
| 430 | const v = vp.iovecs[vp.idx]; | |
| 431 | const dest = v.base[vp.off..v.len]; | |
| 432 | const src = bytes[bytes_i..][0..@min(dest.len, bytes.len - bytes_i)]; | |
| 433 | @memcpy(dest[0..src.len], src); | |
| 434 | bytes_i += src.len; | |
| 435 | vp.off += src.len; | |
| 436 | if (vp.off >= v.len) { | |
| 437 | vp.off = 0; | |
| 438 | vp.idx += 1; | |
| 439 | if (vp.idx >= vp.iovecs.len) { | |
| 440 | vp.total += bytes_i; | |
| 441 | return bytes_i; | |
| 442 | } | |
| 443 | } | |
| 444 | if (bytes_i >= bytes.len) { | |
| 445 | vp.total += bytes_i; | |
| 446 | return bytes_i; | |
| 447 | } | |
| 448 | } | |
| 449 | } | |
| 450 | }; | |
| 451 | ||
| 452 | test "client/server connection" { | |
| 453 | // create ciphers pair | |
| 454 | const cipher_client, const cipher_server = brk: { | |
| 455 | const Transcript = @import("transcript.zig").Transcript; | |
| 456 | const CipherSuite = @import("cipher.zig").CipherSuite; | |
| 457 | const cipher_suite: CipherSuite = .AES_256_GCM_SHA384; | |
| 458 | ||
| 459 | var rnd: [128]u8 = undefined; | |
| 460 | @import("random.zig").fill(&rnd); | |
| 461 | const secret = Transcript.Secret{ | |
| 462 | .client = rnd[0..64], | |
| 463 | .server = rnd[64..], | |
| 464 | }; | |
| 465 | ||
| 466 | break :brk .{ | |
| 467 | try Cipher.initTls13(cipher_suite, secret, .client), | |
| 468 | try Cipher.initTls13(cipher_suite, secret, .server), | |
| 469 | }; | |
| 470 | }; | |
| 471 | ||
| 472 | var client_conn: Connection = .{ | |
| 473 | .input = undefined, | |
| 474 | .output = undefined, | |
| 475 | .cipher = cipher_client, | |
| 476 | }; | |
| 477 | var server_conn: Connection = .{ | |
| 478 | .input = undefined, | |
| 479 | .output = undefined, | |
| 480 | .cipher = cipher_server, | |
| 481 | }; | |
| 482 | ||
| 483 | // big enough cleartext to produce multiple tls records | |
| 484 | var cleartext_buf: [cipher.max_cleartext_len * 5]u8 = undefined; | |
| 485 | // fill cleartext_buf with random bytes | |
| 486 | var prng = std.Random.DefaultPrng.init(0); | |
| 487 | const random = prng.random(); | |
| 488 | random.bytes(&cleartext_buf); | |
| 489 | ||
| 490 | // cleartext -> client_conn -> ciphertext -> server_conn -> cleartext | |
| 491 | for (0..16) |_| { | |
| 492 | // use random part of clartext_buf | |
| 493 | const n = random.intRangeAtMost(usize, cipher.max_cleartext_len + 1, cleartext_buf.len); | |
| 494 | const client_cleartext = cleartext_buf[0..n]; | |
| 495 | ||
| 496 | // prepare ciphertext buffer | |
| 497 | var ciphertext_buf: [cleartext_buf.len]u8 = undefined; | |
| 498 | var w: Io.Writer = .fixed(&ciphertext_buf); | |
| 499 | client_conn.output = &w; | |
| 500 | ||
| 501 | // write cleartext to the server side | |
| 502 | try client_conn.writeAll(client_cleartext); | |
| 503 | const ciphertext_len = NonBlock.init(cipher_client).encryptedLength(n); | |
| 504 | try testing.expectEqual(ciphertext_len, w.buffered().len); | |
| 505 | ||
| 506 | // feed ciphertext from client to the server | |
| 507 | var r: Io.Reader = .fixed(w.buffered()); | |
| 508 | server_conn.input = &r; | |
| 509 | var server_cleartext_buf: [cleartext_buf.len]u8 = undefined; | |
| 510 | // read cleartext from the server connection | |
| 511 | const nr = try server_conn.readAll(&server_cleartext_buf); | |
| 512 | const server_cleartext = server_cleartext_buf[0..nr]; | |
| 513 | ||
| 514 | try testing.expectEqual(n, nr); | |
| 515 | try testing.expectEqualSlices(u8, client_cleartext, server_cleartext); | |
| 516 | } | |
| 517 | } | |
| 518 | ||
| 519 | pub const NonBlock = struct { | |
| 520 | const Self = @This(); | |
| 521 | ||
| 522 | inner: Connection, | |
| 523 | ||
| 524 | pub fn init(c: Cipher) Self { | |
| 525 | return .{ .inner = .{ .cipher = c, .input = undefined, .output = undefined } }; | |
| 526 | } | |
| 527 | ||
| 528 | /// Required ciphertext buffer length for the given cleartext length. | |
| 529 | pub fn encryptedLength(self: Self, cleartext_len: usize) usize { | |
| 530 | const c = self.inner.cipher; | |
| 531 | const records_count = cleartext_len / cipher.max_cleartext_len; | |
| 532 | if (records_count == 0) return c.recordLen(cleartext_len); | |
| 533 | const last_chunk_len = cleartext_len - cipher.max_cleartext_len * records_count; | |
| 534 | return c.recordLen(cipher.max_cleartext_len) * records_count + | |
| 535 | if (last_chunk_len == 0) 0 else c.recordLen(last_chunk_len); | |
| 536 | } | |
| 537 | ||
| 538 | fn reset(self: *Self) void { | |
| 539 | self.inner.input = undefined; | |
| 540 | self.inner.output = undefined; | |
| 541 | } | |
| 542 | ||
| 543 | /// Encrypts cleartext into ciphertext. | |
| 544 | /// If ciphertext.len is >= encryptedLength(cleartext.len) whole | |
| 545 | /// cleartext will be consumed. | |
| 546 | pub fn encrypt( | |
| 547 | self: *Self, | |
| 548 | /// Cleartext data to encrypt | |
| 549 | cleartext: []const u8, | |
| 550 | /// Write buffer for ciphertext; encrypted data | |
| 551 | ciphertext: []u8, | |
| 552 | ) !struct { | |
| 553 | /// Number of bytes consumed from cleartext | |
| 554 | cleartext_pos: usize = 0, | |
| 555 | /// Unused part of the provided cleartext buffer | |
| 556 | unused_cleartext: []const u8, | |
| 557 | /// Encrypted ciphertext data | |
| 558 | ciphertext: []u8, | |
| 559 | } { | |
| 560 | defer self.reset(); | |
| 561 | var output: Io.Writer = .fixed(ciphertext); | |
| 562 | self.inner.output = &output; | |
| 563 | ||
| 564 | var n: usize = 0; | |
| 565 | while (n < cleartext.len and output.end < output.buffer.len) { | |
| 566 | n += try self.inner.write(cleartext[n..]); | |
| 567 | } | |
| 568 | return .{ | |
| 569 | .cleartext_pos = n, | |
| 570 | .unused_cleartext = cleartext[n..], | |
| 571 | .ciphertext = output.buffered(), | |
| 572 | }; | |
| 573 | } | |
| 574 | ||
| 575 | /// Decrypts ciphertext into cleartext. | |
| 576 | /// NOTE: It is safe to reuses ciphertext buffer for cleartext data. | |
| 577 | pub fn decrypt( | |
| 578 | self: *Self, | |
| 579 | /// Ciphertext data recieved from the other side of the tls connection | |
| 580 | ciphertext: []const u8, | |
| 581 | /// Write buffer for cleartext; decrypted data | |
| 582 | cleartext: []u8, | |
| 583 | ) !struct { | |
| 584 | /// Number of bytes consumed from provided ciphertext buffer | |
| 585 | ciphertext_pos: usize, | |
| 586 | /// Unconsumed part of the provided ciphertext buffer | |
| 587 | unused_ciphertext: []const u8, | |
| 588 | /// Decrypted cleartext data | |
| 589 | cleartext: []u8, | |
| 590 | /// Is clear notify alert received | |
| 591 | closed: bool = false, | |
| 592 | } { | |
| 593 | defer self.reset(); | |
| 594 | var input: Io.Reader = .fixed(ciphertext); | |
| 595 | self.inner.input = &input; | |
| 596 | ||
| 597 | var n: usize = 0; | |
| 598 | while (n < cleartext.len) { | |
| 599 | const nn = self.inner.read(cleartext[n..]) catch |err| switch (err) { | |
| 600 | error.InputBufferUndersize => break, | |
| 601 | else => return err, | |
| 602 | }; | |
| 603 | if (nn == 0) break; | |
| 604 | n += nn; | |
| 605 | } | |
| 606 | ||
| 607 | return .{ | |
| 608 | .ciphertext_pos = input.seek, | |
| 609 | .unused_ciphertext = input.buffered(), | |
| 610 | .cleartext = cleartext[0..n], | |
| 611 | .closed = self.inner.received_close_notify, | |
| 612 | }; | |
| 613 | } | |
| 614 | ||
| 615 | pub fn close(self: *Self, ciphertext: []u8) ![]const u8 { | |
| 616 | return try self.inner.cipher.encrypt(ciphertext, .alert, &proto.Alert.closeNotify()); | |
| 617 | } | |
| 618 | }; | |
| 619 | ||
| 620 | test "nonblock encrypt" { | |
| 621 | const data13 = @import("testdata/tls13.zig"); | |
| 622 | const client_cipher, _ = cipher.testCiphers(); | |
| 623 | var conn = NonBlock.init(client_cipher); | |
| 624 | ||
| 625 | const cleartext = "ping"; | |
| 626 | try testing.expectEqual(26, conn.encryptedLength(cleartext.len)); | |
| 627 | var ciphertext: [32]u8 = undefined; | |
| 628 | ||
| 629 | // with enough big buffer | |
| 630 | { | |
| 631 | const res = try conn.encrypt(cleartext, &ciphertext); | |
| 632 | try testing.expectEqual(cleartext.len, res.cleartext_pos); | |
| 633 | try testing.expectEqual(26, res.ciphertext.len); | |
| 634 | try testing.expectEqualSlices(u8, &data13.client_ping_wrapped, res.ciphertext); | |
| 635 | } | |
| 636 | ||
| 637 | // while ciphertext buffer is not enough for cleartext record | |
| 638 | for (conn.inner.cipher.encryptOverhead() + 1..ciphertext.len) |i| { | |
| 639 | const res = try conn.encrypt(cleartext, ciphertext[0..i]); | |
| 640 | const expected_used_cleartext = @min(cleartext.len, i - conn.inner.cipher.encryptOverhead()); | |
| 641 | try testing.expectEqual(expected_used_cleartext, res.cleartext_pos); | |
| 642 | try testing.expectEqual(expected_used_cleartext + conn.inner.cipher.encryptOverhead(), res.ciphertext.len); | |
| 643 | } | |
| 644 | } | |
| 645 | ||
| 646 | test "nonblock decrypt" { | |
| 647 | const data13 = @import("testdata/tls13.zig"); | |
| 648 | _, const server_cipher = cipher.testCiphers(); | |
| 649 | var conn = NonBlock.init(server_cipher); | |
| 650 | ||
| 651 | const ciphertext = data13.client_ping_wrapped; | |
| 652 | var cleartext_buf: [32]u8 = undefined; | |
| 653 | ||
| 654 | for (1..ciphertext.len - 1) |i| { | |
| 655 | const res = try conn.decrypt(ciphertext[0..i], &cleartext_buf); | |
| 656 | try testing.expectEqual(0, res.ciphertext_pos); | |
| 657 | try testing.expectEqual(0, res.cleartext.len); | |
| 658 | try testing.expectEqual(i, res.unused_ciphertext.len); | |
| 659 | } | |
| 660 | ||
| 661 | const res = try conn.decrypt(&ciphertext, &cleartext_buf); | |
| 662 | try testing.expectEqualSlices(u8, "ping", res.cleartext); | |
| 663 | } | |