Commit graph

89 commits

Author SHA1 Message Date
Roman Frołow
37bbe7e930 typo: was issues -> was issued 2025-03-15 12:14:00 +01:00
Andrew Kelley
eb3c7f5706 zig build fmt 2025-02-22 17:09:20 -08:00
Jacob Young
7c713251ca x86_64: looped instructions 2025-01-16 20:42:08 -05:00
Frank Denis
8a00bd4ce6
std.crypto: make the key pair API creation consistent (#21955)
Our key pair creation API was ugly and inconsistent between ecdsa
keys and other keys.

The same `generate()` function can now be used to generate key pairs,
and that function cannot fail.

For deterministic keys, a `generateDeterministic()` function is
available for all key types.

Fix comments and compilation of the benchmark by the way.

Fixes #21002
2024-11-19 18:05:09 +01:00
Jacob Young
75adba7cb9 std.crypto.tls: add support for secp384r1 key share 2024-11-07 20:25:26 -05:00
Jacob Young
a4e88abf04 std.crypto.tls: advertise all supported signature algorithms 2024-11-07 20:25:26 -05:00
Jacob Young
fbaefcaa94 std.crypto.tls: support the same key sizes as certificate verification 2024-11-07 20:25:26 -05:00
Jacob Young
a6ede7ba86 std.crypto.tls: support handshake fragments 2024-11-07 20:25:26 -05:00
Jacob Young
de53e6e4f2 std.crypto.tls: improve debuggability of encrypted connections
By default, programs built in debug mode that open a https connection
will append secrets to the file specified in the SSLKEYLOGFILE
environment variable to allow protocol debugging by external programs.
2024-11-07 20:25:26 -05:00
Jacob Young
d86a8aedd5 std.crypto.tls: increase handshake buffer sizes 2024-11-07 20:25:26 -05:00
Jacob Young
485f20a10a std.crypto.tls: remove hardcoded initial loop
This was preventing TLSv1.2 from working in some cases, because servers
are allowed to send multiple handshake messages in the first handshake
record, whereas this inital loop was assuming that it only contained a
server hello.
2024-11-07 20:25:26 -05:00
Jacob Young
90a761c186 std.crypto.tls: make verify data checks timing safe 2024-11-07 20:25:26 -05:00
Jacob Young
7afb277725 std.crypto.tls: fix x25519_ml_kem768 key share
This is mostly nfc cleanup as I was bisecting the client hello to find
the problematic part, and the only bug fix ended up being

    key_share.x25519_kp.public_key ++
    key_share.ml_kem768_kp.public_key.toBytes()

to

    key_share.ml_kem768_kp.public_key.toBytes() ++
    key_share.x25519_kp.public_key)

and the same swap in `KeyShare.exchange` as per some random blog that
says "a hybrid keyshare, constructed by concatenating the public KEM key
with the public X25519 key".  I also note that based on the same blog
post, there was a draft version of this method that indeed had these
values swapped, and that used to be supported by this code, but it was
not properly fixed up when this code was updated from the draft spec.

Closes #21747
2024-11-07 20:25:26 -05:00
Jacob Young
7f20c78c95 std.crypto: delete new functions that are only used once 2024-11-07 20:25:26 -05:00
Jacob Young
4466f145d6 std.crypto.tls: support more key share params
This condition is already checked less restrictively in
`KeyShare.exchange`.
2024-11-07 20:25:26 -05:00
Jacob Young
e184b15a66 std.crypto.tls: fix fetching https://nginx.org
Note that the removed `error.TlsIllegalParameter` case is still caught
below when it is compared to a fixed-length string, but after checking
the proper protocol version requirement first.
2024-11-07 20:25:26 -05:00
Jacob Young
c2a779ae79 std.crypto.tls: implement TLSv1.2 2024-11-07 20:25:26 -05:00
Frank Denis
c062c532d7 Add post-quantum key agreement X25519MLKEM768
X25519MLKEM768 replaces X25519Kyber768Draft00 now that NIST has
released ML-KEM.

IANA has assigned the codepoint 0x11ec:
https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8
2024-09-24 13:18:32 -07:00
Igor Anić
aa73bb6bc9
tls.Client: implement record padding (#20558)
On decryption tls client should remove zero byte padding after the
content type field. This padding is rarely used, the only site (from the
list of top domains) that I found using it is `tutanota.com`.

From [RFC](https://datatracker.ietf.org/doc/html/rfc8446#section-5.4):
> All encrypted TLS records can be padded.
> Padding is a string of zero-valued bytes appended to the ContentType
field before encryption.
> the receiving implementation scans the field from the end toward the
beginning until it finds a non-zero octet. This non-zero octet is the
content type of the message.

Currently we can't connect to that site:
```
$ zig run main.zig -- tutanota.com
error: TlsInitializationFailed
/usr/local/zig/zig-linux-x86_64-0.14.0-dev.208+854e86c56/lib/std/crypto/tls/Client.zig:476:45: 0x121fbed in init__anon_10331 (http_get_std)
                if (inner_ct != .handshake) return error.TlsUnexpectedMessage;
                                            ^
/usr/local/zig/zig-linux-x86_64-0.14.0-dev.208+854e86c56/lib/std/http/Client.zig:1357:99: 0x1161f0b in connectTcp (http_get_std)
        conn.data.tls_client.* = std.crypto.tls.Client.init(stream, client.ca_bundle, host) catch return error.TlsInitializationFailed;
                                                                                                  ^
/usr/local/zig/zig-linux-x86_64-0.14.0-dev.208+854e86c56/lib/std/http/Client.zig:1492:14: 0x11271e1 in connect (http_get_std)
    } orelse return client.connectTcp(host, port, protocol);
             ^
/usr/local/zig/zig-linux-x86_64-0.14.0-dev.208+854e86c56/lib/std/http/Client.zig:1640:9: 0x111a24e in open (http_get_std)
        try client.connect(valid_uri.host.?.raw, uriPort(valid_uri, protocol), protocol);
        ^
/home/ianic/Code/tls.zig/example/http_get_std.zig:28:19: 0x1118f8c in main (http_get_std)
        var req = try client.open(.GET, uri, .{ .server_header_buffer = &server_header_buffer });
                  ^
```
using this example:

```zig
const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    if (args.len > 1) {
        const domain = args[1];

        var client: std.http.Client = .{ .allocator = allocator };
        defer client.deinit();

        // Add https:// prefix if needed
        const url = brk: {
            const scheme = "https://";
            if (domain.len >= scheme.len and std.mem.eql(u8, domain[0..scheme.len], scheme))
                break :brk domain;

            var url_buf: [128]u8 = undefined;
            break :brk try std.fmt.bufPrint(&url_buf, "https://{s}", .{domain});
        };

        const uri = try std.Uri.parse(url);
        var server_header_buffer: [16 * 1024]u8 = undefined;
        var req = try client.open(.GET, uri, .{ .server_header_buffer = &server_header_buffer });
        defer req.deinit();

        try req.send();
        try req.wait();
    }
}
```
2024-07-21 01:19:36 -07:00
Igor Anić
ca752c61c0 tls.Client: fix out of bounds panic
When calculating how much ciphertext from the stream can fit into
user and internal buffers we should also take into account ciphertext
data which are already in internal buffer.

Fixes: 15226

Tested with
[this](https://github.com/ziglang/zig/issues/15226#issuecomment-2218809140).
Using client with different read buffers until I, hopefully, understood
what is happening.

Not relevant to this fix, but this
[part](95d9292a7a/lib/std/crypto/tls/Client.zig (L988-L991))
is still mystery to me. Why we don't use free_size in buf_cap
calculation. Seems like rudiment from previous implementation without iovec.
2024-07-12 03:07:15 -04:00
Jora Troosh
13070448f5
std: fix typos (#20560) 2024-07-09 14:25:42 -07:00
Nameless
aecd9cc6d1 std.posix.iovec: use .base and .len instead of .iov_base and .iov_len 2024-04-28 00:20:30 -07:00
Andrew Kelley
cd62005f19 extract std.posix from std.os
closes #5019
2024-03-19 11:45:09 -07:00
Jacob Young
eaa6218f09 x86_64: fix errors compiling the compiler
This fixes issues targetting both `x86_64-linux` and `x86_64-macos` with
the self-hosted backend.
2024-02-04 22:58:38 -05:00
Jacob Young
5e791e8e07 tls: support ed25519 signatures
Which were claimed to be supported during the handshake but were not
actually implemented.
2024-02-02 17:27:26 -08:00
melonedo
9b0da5ccef Fix TLS record overflow by limiting inner record length to 2^14
Per last paragraph of RFC 8446, Section 5.2, the length of the inner content of an encrypted record must not exceed 2^14 + 1, while that of the whole encrypted record must not exceed 2^14 + 256.
2024-01-16 14:58:56 -08:00
Purrie
c4a1b54ebe tls client interface consistency fix
Client for tls was using a function that wasn't declared on the
interface for it. The issue wasn't apparent because net stream
implemented that function.

I changed it to keep the interface promise of what's required to be
compatible with the tls client functionality.
2024-01-16 13:02:00 -08:00
Frank Denis
f276bb107e verify_buffer is not expected to be sentinel-terminated 2023-12-01 20:04:52 +01:00
Frank Denis
9831dc9e0c TLS: The 0x1306 TLS identifier was updated to TLS_AEGIS_256_SHA512
Following the recommendations from [1], the AEGIS specification
and the TLS registry [2] were updated to recommend SHA512 for the
traffic secrets.

[1] https://eprint.iacr.org/2023/913.pdf
[2] https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4
2023-12-01 18:00:15 +01:00
mlugg
51595d6b75
lib: correct unnecessary uses of 'var' 2023-11-19 09:55:07 +00:00
Andrew Kelley
3fc6fc6812 std.builtin.Endian: make the tags lower case
Let's take this breaking change opportunity to fix the style of this
enum.
2023-10-31 21:37:35 -04:00
Jacob Young
d890e81761 mem: fix ub in writeInt
Use inline to vastly simplify the exposed API.  This allows a
comptime-known endian parameter to be propogated, making extra functions
for a specific endianness completely unnecessary.
2023-10-31 21:37:35 -04:00
Nameless
e1c37f70d4
std.http.Client: store *Connection instead of a pool node, buffer writes 2023-10-21 20:52:58 -05:00
dec05eba
2e424e019f Client.zig: support rsa_pss_rsae_sha384 and rsa_pss_rsae_sha512
This fixes HTTP GET to https://www.iana.org/domains/reserved
for example
2023-07-06 18:36:15 -07:00
Jacob Young
8239d3b358 crypto: recoup storage in tls.Client.partially_read_buffer 2023-06-26 21:05:08 -04:00
Jacob Young
eb8881a538 crypto: cleanup unneeded uses of @as in tls.Client 2023-06-26 21:05:08 -04:00
mlugg
f26dda2117 all: migrate code to new cast builtin syntax
Most of this migration was performed automatically with `zig fmt`. There
were a few exceptions which I had to manually fix:

* `@alignCast` and `@addrSpaceCast` cannot be automatically rewritten
* `@truncate`'s fixup is incorrect for vectors
* Test cases are not formatted, and their error locations change
2023-06-24 16:56:39 -07:00
Eric Joldasov
50339f595a all: zig fmt and rename "@XToY" to "@YFromX"
Signed-off-by: Eric Joldasov <bratishkaerik@getgoogleoff.me>
2023-06-19 12:34:42 -07:00
mlugg
9e61ba19e9 std.crypto.tls.Client: fix @memcpy crash in limitedOverlapCopy
Resolves: #15928
2023-06-12 14:22:09 -07:00
Nameless
0e5e6cb10c
std.http: add TlsAlert descriptions so that they can at least be viewed in err return traces 2023-06-01 13:43:55 -05:00
Frank Denis
1ab008d89d
RSA: remove usage of allocators (#15901)
Individual max buffer sizes are well known, now that arithmetic doesn't
require allocations any more.

Also bump `main_cert_pub_key_buf`, so that e.g. `nodejs.org` public
keys can fit.
2023-05-30 10:06:44 +00:00
Frank Denis
89f622fc68
std.crypto.ff - Alloc-free, constant-time field arithmetic for crypto (#15795)
A minimal set of simple, safe functions for Montgomery arithmetic,
designed for cryptographic primitives.

Also update the current RSA cert validation to use it, getting rid
of the FixedBuffer hack and the previous limitations.

Make the check of the RSA public key a little bit more strict by
the way.
2023-05-22 16:11:06 +02:00
Andrew Kelley
7cf2cbb33e std.crypto.tls.Client.readvAdvanced: fix bugs
* When there is buffered cleartext, return it without calling the
   underlying read function. This prevents buffer overflow due to space
   used up by cleartext.
 * Avoid clearing the buffer when the buffered cleartext could not be
   completely given to the result read buffer, and there is some
   buffered ciphertext left.
 * Instead of rounding up the amount of bytes to ask for to the nearest
   TLS record size, round down, with a minimum of 1. This prevents the
   code path from being taken which requires extra memory copies.
 * Avoid calling `@memcpy` with overlapping arguments.

closes #15590
2023-05-18 03:26:16 -07:00
Pyry Kovanen
ffccd70671 tls: update finishRead2 for new @memcpy semantics 2023-05-09 14:47:04 -07:00
Jonathan Marler
5def162391 fix bug and simplify std.crypto.tls.Client.limitVecs 2023-05-03 20:52:18 -07:00
Andrew Kelley
6261c13731 update codebase to use @memset and @memcpy 2023-04-28 13:24:43 -07:00
Andrew Kelley
a5c910adb6 change semantics of @memcpy and @memset
Now they use slices or array pointers with any element type instead of
requiring byte pointers.

This is a breaking enhancement to the language.

The safety check for overlapping pointers will be implemented in a
future commit.

closes #14040
2023-04-25 11:23:40 -07:00
Nameless
fde05b10b3 tls.Client: don't read if we don't need more data 2023-04-08 03:37:05 -04:00
Frank Denis
d61ac0db8c
TLS: Favor ChaCha over AES-based ciphers on CPUs without AES support (#15034)
On CPUs without AES support, ChaCha is always faster and safer than
software AES.

Add `crypto.core.aes.has_hardware_support` to represent whether
AES acceleration is available or not, and in `tls.Client`, favor
AES-based ciphers only if hardware support is available.

This matches what BoringSSL is doing.
2023-03-22 17:58:24 +01:00
Bas Westerbaan
2089b3f193
tls: use post-quantum secure key exchange (#14920) 2023-03-17 17:51:24 +01:00