Skip to content

Commit

Permalink
updated
Browse files Browse the repository at this point in the history
  • Loading branch information
naoki9911 committed Dec 30, 2023
1 parent ea3e9ed commit db49905
Show file tree
Hide file tree
Showing 42 changed files with 317 additions and 317 deletions.
8 changes: 4 additions & 4 deletions src/alert.zig
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ pub const Alert = struct {
/// @return decoded Alert.
pub fn decode(reader: anytype) !Self {
// Decoding level.
const level = @intToEnum(AlertLevel, try reader.readByte());
const level = @as(AlertLevel, @enumFromInt(try reader.readByte()));

// Decoding description.
const description = @intToEnum(AlertDescription, try reader.readByte());
const description = @as(AlertDescription, @enumFromInt(try reader.readByte()));

return Self{
.level = level,
Expand All @@ -109,11 +109,11 @@ pub const Alert = struct {
var len: usize = 0;

// Encoding level.
try writer.writeByte(@enumToInt(self.level));
try writer.writeByte(@intFromEnum(self.level));
len += @sizeOf(u8);

// Encoding description.
try writer.writeByte(@enumToInt(self.description));
try writer.writeByte(@intFromEnum(self.description));
len += @sizeOf(u8);

return len;
Expand Down
2 changes: 1 addition & 1 deletion src/application_data.zig
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub const ApplicationData = struct {
/// @param allocator allocator to initialize ApplicationData.
/// @return decoded ApplicationData.
pub fn decode(reader: anytype, len: usize, allocator: std.mem.Allocator) !Self {
var res = try Self.init(len, allocator);
const res = try Self.init(len, allocator);

try reader.readNoEof(res.content);

Expand Down
14 changes: 7 additions & 7 deletions src/certificate.zig
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ pub const Certificate = struct {
/// @return decoded Certificate.
pub fn decode(reader: anytype, allocator: std.mem.Allocator) !Self {
// Decoding length of certificate_request_context and initializing Certificate.
const ctx_len = try reader.readIntBig(u16);
const ctx_len = try reader.readInt(u16, .big);
var res = try Self.init(ctx_len, allocator);
errdefer res.deinit();

// Decoding certificate_request_context.
_ = try reader.readAll(res.cert_req_ctx.slice());

// Decoding cert_list.
const cert_len = try reader.readIntBig(u16);
const cert_len = try reader.readInt(u16, .big);
var i: usize = 0;
while (i < cert_len) {
// Decoding CertificateEntry.
Expand All @@ -69,7 +69,7 @@ pub const Certificate = struct {
var len: usize = 0;

// Encoding certificate_request.
try writer.writeIntBig(u16, @intCast(u16, self.cert_req_ctx.slice().len));
try writer.writeInt(u16, @as(u16, @intCast(self.cert_req_ctx.slice().len)), .big);
len += 2;
try writer.writeAll(self.cert_req_ctx.slice());
len += self.cert_req_ctx.slice().len;
Expand All @@ -79,7 +79,7 @@ pub const Certificate = struct {
for (self.cert_list.items) |c| {
cert_len += c.length();
}
try writer.writeIntBig(u16, @intCast(u16, cert_len));
try writer.writeInt(u16, @as(u16, @intCast(cert_len)), .big);
len += 2;
for (self.cert_list.items) |c| {
len += try c.encode(writer);
Expand Down Expand Up @@ -166,14 +166,14 @@ pub const CertificateEntry = struct {
/// @return the result of decoded CertificateEntry.
pub fn decode(reader: anytype, allocator: std.mem.Allocator) !Self {
// Decoding certificate_type.
const cert_type = try reader.readIntBig(u8); // CertificateType
const cert_type = try reader.readInt(u8, .big); // CertificateType
if (cert_type != 0) {
// only X509 certificate is supported.
return Error.UnsupportedCertificate;
}

// Decoding certificate.
const cert_len = try reader.readIntBig(u16);
const cert_len = try reader.readInt(u16, .big);
const cert = try x509.Certificate.decode(reader, allocator);
errdefer cert.deinit();

Expand Down Expand Up @@ -201,7 +201,7 @@ pub const CertificateEntry = struct {
len += 1;

// Encoding certificate.
try writer.writeIntBig(u16, @intCast(u16, self.cert_len));
try writer.writeInt(u16, @as(u16, @intCast(self.cert_len)), .big);
len += 2;
// TODO: directly encode x509.Certificate.
try writer.writeAll(self.cert_data);
Expand Down
10 changes: 5 additions & 5 deletions src/certificate_verify.zig
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ pub const CertificateVerify = struct {
/// @return the result of decoded CertificateVerify.
pub fn decode(reader: anytype, allocator: std.mem.Allocator) !Self {
// Decoding SignatureAlgorithm.
const algorithm = @intToEnum(SignatureScheme, try reader.readIntBig(u16));
const algorithm = @as(SignatureScheme, @enumFromInt(try reader.readInt(u16, .big)));

// Decoding signature.
const sig_len = try reader.readIntBig(u16);
var signature = try allocator.alloc(u8, sig_len);
const sig_len = try reader.readInt(u16, .big);
const signature = try allocator.alloc(u8, sig_len);
errdefer allocator.free(signature);
try reader.readNoEof(signature);

Expand All @@ -64,11 +64,11 @@ pub const CertificateVerify = struct {
var len: usize = 0;

// Encoding algorithm.
try writer.writeIntBig(u16, @enumToInt(self.algorithm));
try writer.writeInt(u16, @intFromEnum(self.algorithm), .big);
len += 2;

// Encoding signature.
try writer.writeIntBig(u16, @intCast(u16, self.signature.len));
try writer.writeInt(u16, @as(u16, @intCast(self.signature.len)), .big);
len += 2;
try writer.writeAll(self.signature);
len += self.signature.len;
Expand Down
42 changes: 21 additions & 21 deletions src/client.zig
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt

pub fn init(allocator: std.mem.Allocator) !Self {
var session_id = try msg.SessionID.init(32);
var msgs_bytes = try allocator.alloc(u8, 1024 * 32);
const msgs_bytes = try allocator.alloc(u8, 1024 * 32);
errdefer allocator.free(msgs_bytes);

var rand: [32]u8 = undefined;
Expand Down Expand Up @@ -200,7 +200,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt

var skey_bytes: [P256.SecretKey.encoded_length]u8 = undefined;
random.bytes(skey_bytes[0..]);
var skey = try P256.SecretKey.fromBytes(skey_bytes);
const skey = try P256.SecretKey.fromBytes(skey_bytes);
res.secp256r1_key = try P256.KeyPair.fromSecretKey(skey);

try res.supported_groups.append(.x25519);
Expand Down Expand Up @@ -261,7 +261,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
}

pub fn configureX25519Keys(self: *Self, priv_key: [32]u8) !void {
std.mem.copy(u8, &self.x25519_priv_key, &priv_key);
@memcpy(&self.x25519_priv_key, &priv_key);
self.x25519_pub_key = try dh.X25519.recoverPublicKey(self.x25519_priv_key);
}

Expand Down Expand Up @@ -290,13 +290,13 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
for (self.key_shares.items) |k| {
switch (k) {
.x25519 => {
var entry_x25519 = try key_share.KeyShareEntry.init(.x25519, 32, self.allocator);
std.mem.copy(u8, entry_x25519.key_exchange, &self.x25519_pub_key);
const entry_x25519 = try key_share.KeyShareEntry.init(.x25519, 32, self.allocator);
@memcpy(entry_x25519.key_exchange, &self.x25519_pub_key);
try ks.entries.append(entry_x25519);
},
.secp256r1 => {
var entry_secp256r1 = try key_share.KeyShareEntry.init(.secp256r1, P256.PublicKey.uncompressed_sec1_encoded_length, self.allocator);
std.mem.copy(u8, entry_secp256r1.key_exchange, &self.secp256r1_key.public_key.toUncompressedSec1());
const entry_secp256r1 = try key_share.KeyShareEntry.init(.secp256r1, P256.PublicKey.uncompressed_sec1_encoded_length, self.allocator);
@memcpy(entry_secp256r1.key_exchange, &self.secp256r1_key.public_key.toUncompressedSec1());
try ks.entries.append(entry_secp256r1);
},
else => unreachable,
Expand Down Expand Up @@ -334,7 +334,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
var opsk = try pre_shared_key.OfferedPsks.init(self.ks.hkdf.digest_length + 1, self.allocator);
errdefer opsk.deinit();
try opsk.identities.append(try psk.copy(self.allocator));
var ext_psk = pre_shared_key.PreSharedKey{
const ext_psk = pre_shared_key.PreSharedKey{
.msg_type = .client_hello,
.offeredPsks = opsk,
};
Expand All @@ -347,7 +347,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
try self.ks.hkdf.hkdfExpandLabel(fin_secret.slice(), prk.slice(), "finished", "", self.ks.hkdf.digest_length);

var hs_ch = Handshake{ .client_hello = client_hello };
var ch_tmp = try self.allocator.alloc(u8, hs_ch.length());
const ch_tmp = try self.allocator.alloc(u8, hs_ch.length());
defer self.allocator.free(ch_tmp);
var ch_stream = io.fixedBufferStream(ch_tmp);
_ = try hs_ch.encode(ch_stream.writer());
Expand All @@ -359,8 +359,8 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
_ = try binder_stream.write(ch_stream.getWritten()[0..last_chb_idx]);

const fin = try Finished.fromMessageBytes(binder_stream.getWritten(), fin_secret.slice(), self.ks.hkdf);
opsk.binders[0] = @intCast(u8, self.ks.hkdf.digest_length);
std.mem.copy(u8, opsk.binders[1..], fin.verify_data.slice());
opsk.binders[0] = @as(u8, @intCast(self.ks.hkdf.digest_length));
@memcpy(opsk.binders[1..], fin.verify_data.slice());
}

return client_hello;
Expand All @@ -377,8 +377,8 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
continue;
}
// TODO: ipv6
const bytes = @ptrCast(*const [4]u8, &addr.in.sa.addr);
var ipv4_addr = std.x.os.IPv4{
const bytes = @as(*const [4]u8, @ptrCast(&addr.in.sa.addr));
const ipv4_addr = std.x.os.IPv4{
.octets = [_]u8{ bytes[0], bytes[1], bytes[2], bytes[3] },
};

Expand Down Expand Up @@ -407,7 +407,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
}

self.host = try self.allocator.alloc(u8, host.len);
std.mem.copy(u8, self.host, host);
@memcpy(self.host, host);

if (!self.io_init) {
return Error.IoNotConfigured;
Expand Down Expand Up @@ -448,7 +448,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt

self.state = .WAIT_SH;
} else {
const t = try self.reader.readEnum(ContentType, .Big);
const t = try self.reader.readEnum(ContentType, .big);
if (t == .change_cipher_spec) {
const recv_record = (try TLSPlainText.decode(self.reader, t, self.allocator, null, null));
defer recv_record.deinit();
Expand Down Expand Up @@ -548,7 +548,7 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt

var close_recv = false;
while (!close_recv) {
const t = self.reader.readEnum(ContentType, .Big) catch |err| {
const t = self.reader.readEnum(ContentType, .big) catch |err| {
switch (err) {
// sometimes the tcp connection is closed after sending close_notify.
error.EndOfStream => return,
Expand Down Expand Up @@ -689,8 +689,8 @@ pub fn TLSClientImpl(comptime ReaderType: type, comptime WriterType: type, compt
},
.secp256r1 => {
const pubkey = try P256.PublicKey.fromSec1(server_pubkey);
const mul = try pubkey.p.mulPublic(self.secp256r1_key.secret_key.bytes, .Big);
const shared_key = mul.affineCoordinates().x.toBytes(.Big);
const mul = try pubkey.p.mulPublic(self.secp256r1_key.secret_key.bytes, .big);
const shared_key = mul.affineCoordinates().x.toBytes(.big);
try self.ks.generateHandshakeSecrets1(&shared_key);
},
else => unreachable,
Expand Down Expand Up @@ -1003,7 +1003,7 @@ test "client test with RFC8448" {
const server_hello_bytes = [_]u8{ 0x16, 0x03, 0x03, 0x00, 0x5a, 0x02, 0x00, 0x00, 0x56, 0x03, 0x03, 0xa6, 0xaf, 0x06, 0xa4, 0x12, 0x18, 0x60, 0xdc, 0x5e, 0x6e, 0x60, 0x24, 0x9c, 0xd3, 0x4c, 0x95, 0x93, 0x0c, 0x8a, 0xc5, 0xcb, 0x14, 0x34, 0xda, 0xc1, 0x55, 0x77, 0x2e, 0xd3, 0xe2, 0x69, 0x28, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0xc9, 0x82, 0x88, 0x76, 0x11, 0x20, 0x95, 0xfe, 0x66, 0x76, 0x2b, 0xdb, 0xf7, 0xc6, 0x72, 0xe1, 0x56, 0xd6, 0xcc, 0x25, 0x3b, 0x83, 0x3d, 0xf1, 0xdd, 0x69, 0xb1, 0xb0, 0x4e, 0x75, 0x1f, 0x0f, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04 };
var stream = io.fixedBufferStream(&server_hello_bytes);
var sh_reader = stream.reader();
var t = try sh_reader.readEnum(ContentType, .Big);
const t = try sh_reader.readEnum(ContentType, .big);
const handshake = (try TLSPlainText.decode(sh_reader, t, std.testing.allocator, null, msgs_stream.writer())).content.handshake;
try expect(handshake == .server_hello);

Expand Down Expand Up @@ -1153,7 +1153,7 @@ test "client test with RFC8448" {
// send application_data
var c_app_data: [50]u8 = undefined;
for (&c_app_data, 0..) |*value, app_i| {
value.* = @intCast(u8, app_i);
value.* = @as(u8, @intCast(app_i));
}

const c_app_record_ans = [_]u8{ 0x17, 0x03, 0x03, 0x00, 0x43, 0xA2, 0x3F, 0x70, 0x54, 0xB6, 0x2C, 0x94, 0xD0, 0xAF, 0xFA, 0xFE, 0x82, 0x28, 0xBA, 0x55, 0xCB, 0xEF, 0xAC, 0xEA, 0x42, 0xF9, 0x14, 0xAA, 0x66, 0xBC, 0xAB, 0x3F, 0x2B, 0x98, 0x19, 0xA8, 0xA5, 0xB4, 0x6B, 0x39, 0x5B, 0xD5, 0x4A, 0x9A, 0x20, 0x44, 0x1E, 0x2B, 0x62, 0x97, 0x4E, 0x1F, 0x5A, 0x62, 0x92, 0xA2, 0x97, 0x70, 0x14, 0xBD, 0x1E, 0x3D, 0xEA, 0xE6, 0x3A, 0xEE, 0xBB, 0x21, 0x69, 0x49, 0x15, 0xE4 };
Expand Down Expand Up @@ -1317,7 +1317,7 @@ test "connect e2e with x25519" {
// zig fmt: on

tls_client.random = dummy;
std.mem.copy(u8, tls_client.session_id.session_id.slice(), &dummy);
@memcpy(tls_client.session_id.session_id.slice(), &dummy);

tls_client.cipher_suites.clearAndFree();
try tls_client.cipher_suites.append(.TLS_AES_128_GCM_SHA256);
Expand Down
8 changes: 4 additions & 4 deletions src/client_hello.zig
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub const ClientHello = struct {
/// @return the result of decoded ClientHello.
pub fn decode(reader: anytype, allocator: std.mem.Allocator) !Self {
// protocol_version must be TLSv1.2(0x0303).
const protocol_version = try reader.readIntBig(u16);
const protocol_version = try reader.readInt(u16, .big);
if (protocol_version != 0x0303) {
return Error.UnsupportedVersion;
}
Expand All @@ -75,11 +75,11 @@ pub const ClientHello = struct {

// Decoding legacy_compression_methods.
// only compression method 'null' is allowed.
const comp_len = try reader.readIntBig(u8);
const comp_len = try reader.readInt(u8, .big);
if (comp_len != 0x01) {
return Error.UnsupportedCompressionMethod;
}
if (try reader.readIntBig(u8) != 0x00) {
if (try reader.readInt(u8, .big) != 0x00) {
return Error.UnsupportedCompressionMethod;
}

Expand Down Expand Up @@ -107,7 +107,7 @@ pub const ClientHello = struct {
var len: usize = 0;

// Encoding protocol_version.
try writer.writeIntBig(u16, self.protocol_version);
try writer.writeInt(u16, self.protocol_version, .big);
len += @sizeOf(u16);

// Encoding random.
Expand Down
2 changes: 1 addition & 1 deletion src/common.zig
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ pub fn ReadEngine(comptime Entity: type, comptime et: EntityType) type {
log.debug("KeyUpdate updated_request has been sent", .{});
}

const t = self.entity.reader.readEnum(ContentType, .Big) catch |err| {
const t = self.entity.reader.readEnum(ContentType, .big) catch |err| {
switch (err) {
error.WouldBlock => return msg_stream.getWritten().len,
else => return err,
Expand Down
26 changes: 13 additions & 13 deletions src/crypto.zig
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub const Hkdf = struct {

fn extract(out: []u8, salt: []const u8, ikm: []const u8) void {
const res = H.extract(salt, ikm);
std.mem.copy(u8, out, &res);
@memcpy(out, &res);
}

fn expand(out: []u8, ctx: []const u8, prk: []const u8) void {
Expand Down Expand Up @@ -74,7 +74,7 @@ pub const Hkdf = struct {

fn extract(out: []u8, salt: []const u8, ikm: []const u8) void {
const res = H.extract(salt, ikm);
std.mem.copy(u8, out, &res);
@memcpy(out, &res);
}

fn expand(out: []u8, ctx: []const u8, prk: []const u8) void {
Expand Down Expand Up @@ -111,21 +111,21 @@ pub const Hkdf = struct {
}

pub fn hkdfExpandLabel(self: Self, out: []u8, prk: []const u8, label: []const u8, ctx: []const u8, len: usize) !void {
const info = try generateHkdfLabel(@intCast(u16, len), label, ctx);
const info = try generateHkdfLabel(@as(u16, @intCast(len)), label, ctx);
self.expand(out, info.slice(), prk);
}

fn generateHkdfLabel(len: u16, label: []const u8, ctx: []const u8) !BoundedArray(u8, MAX_HKDF_LABEL_LENGTH) {
var hkdf_label = try BoundedArray(u8, MAX_HKDF_LABEL_LENGTH).init(0);

var len_buf = [_]u8{0} ** 2;
mem.writeIntBig(u16, &len_buf, len);
mem.writeInt(u16, &len_buf, len, .big);

try hkdf_label.appendSlice(&len_buf);
try hkdf_label.append(@intCast(u8, 6 + label.len)); // "tls13 ".len + label.len
try hkdf_label.append(@as(u8, @intCast(6 + label.len))); // "tls13 ".len + label.len
try hkdf_label.appendSlice("tls13 ");
try hkdf_label.appendSlice(label);
try hkdf_label.append(@intCast(u8, ctx.len));
try hkdf_label.append(@as(u8, @intCast(ctx.len)));
try hkdf_label.appendSlice(ctx);

return hkdf_label;
Expand Down Expand Up @@ -246,8 +246,8 @@ pub const Secret = struct {
.iv = try NonceBoundedArray.init(iv.len),
};

std.mem.copy(u8, res.key.slice(), k);
std.mem.copy(u8, res.iv.slice(), iv);
@memcpy(res.key.slice(), k);
@memcpy(res.iv.slice(), iv);

return res;
}
Expand Down Expand Up @@ -355,15 +355,15 @@ const random = std.crypto.random;
test "ECDHE-P256" {
var a_skey_bytes: [P256.SecretKey.encoded_length]u8 = [_]u8{0} ** P256.SecretKey.encoded_length;
a_skey_bytes[31] = 1;
var a_skey = try P256.SecretKey.fromBytes(a_skey_bytes);
const a_skey = try P256.SecretKey.fromBytes(a_skey_bytes);
const a_key = try P256.KeyPair.fromSecretKey(a_skey);

var b_skey_bytes: [P256.SecretKey.encoded_length]u8 = [_]u8{0} ** P256.SecretKey.encoded_length;
b_skey_bytes[31] = 2;
var b_skey = try P256.SecretKey.fromBytes(b_skey_bytes);
const b_skey = try P256.SecretKey.fromBytes(b_skey_bytes);
const b_key = try P256.KeyPair.fromSecretKey(b_skey);

const shared = try a_key.public_key.p.mul(b_key.secret_key.bytes, .Big);
const shared2 = try b_key.public_key.p.mul(a_key.secret_key.bytes, .Big);
try expect(std.mem.eql(u8, &shared.affineCoordinates().x.toBytes(.Big), &shared2.affineCoordinates().x.toBytes(.Big)));
const shared = try a_key.public_key.p.mul(b_key.secret_key.bytes, .big);
const shared2 = try b_key.public_key.p.mul(a_key.secret_key.bytes, .big);
try expect(std.mem.eql(u8, &shared.affineCoordinates().x.toBytes(.big), &shared2.affineCoordinates().x.toBytes(.big)));
}
Loading

0 comments on commit db49905

Please sign in to comment.