48 Commits

Author SHA1 Message Date
Frank Denis
96e4825fbb
Validate wildcard TLS certificates correctly (#24829)
Validate wildcard certificates as specified in RFC 6125.

In particular, `*.example.com` should match `foo.example.com` but
NOT `bar.foo.example.com` as it previously did.
2025-08-14 13:57:00 +00:00
Jacob Young
1f6f8b0ffe x86_64: implement integer @reduce(.Add) 2025-05-28 15:10:22 -04:00
HydroH
cc1475c91d
std: remove std.crypto.Certificate.Parsed.pubKeySigAlgo method (#23811) 2025-05-16 00:21:25 +02:00
Jeremy Hertel
801a95035c std.time.epoch: change getDaysInMonth to accept the year as an argument 2025-03-08 14:25:28 -05:00
Jacob Young
c2a779ae79 std.crypto.tls: implement TLSv1.2 2024-11-07 20:25:26 -05:00
Jora Troosh
13070448f5
std: fix typos (#20560) 2024-07-09 14:25:42 -07:00
Igor Anić
c1e7eb7389 crypto.Certificate: case insensitive host name check
This makes comparing host name with dns name from certificate case
insensitive.

I found a few domains (from the
[cloudflare](https://radar.cloudflare.com/domains) list of top domains)
for which tls.Client fails to connect. Error is:

```zig
error: TlsInitializationFailed
Code/zig/lib/std/crypto/Certificate.zig:336:9: 0x1177b1f in verifyHostName (http_get_std)
        return error.CertificateHostMismatch;
Code/zig/lib/std/crypto/tls23/handshake_client.zig:461:25: 0x11752bd in parseServerCertificate (http_get_std)
                        try subject.verifyHostName(opt.host);
```
In its certificate this domains have host names which are not strictly
lower case. This is what checkHostName is comparing:

 |host_name            |  dns_name                |
 |------------------------------------------------|
 |ey.com               | EY.COM                   |
 |truist.com           | Truist.com               |
 |wscampanhas.bradesco | WSCAMPANHAS.BRADESCO     |
 |dell.com             | Dell.com                 |

From
[RFC2818](https://datatracker.ietf.org/doc/html/rfc2818#section-2.4):
>  Matching is performed using the matching rules specified by
   [RFC2459].
From [RFC2459](https://datatracker.ietf.org/doc/html/rfc2459#section-4.2.1.7):
> When comparing URIs, conforming implementations
> MUST compare the scheme and host without regard to case, but assume
> the remainder of the scheme-specific-part is case sensitive.

Testing with:

```
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();
    }
}
```
`$ zig run example/main.zig -- truist.com `
2024-07-09 16:35:41 -04:00
Travis Staloch
8af59d1f98 ComptimeStringMap: return a regular struct and optimize
this patch renames ComptimeStringMap to StaticStringMap, makes it
accept only a single type parameter, and return a known struct type
instead of an anonymous struct.  initial motivation for these changes
was to reduce the 'very long type names' issue described here
https://github.com/ziglang/zig/pull/19682.

this breaks the previous API.  users will now need to write:
`const map = std.StaticStringMap(T).initComptime(kvs_list);`

* move `kvs_list` param from type param to an `initComptime()` param
* new public methods
  * `keys()`, `values()` helpers
  * `init(allocator)`, `deinit(allocator)` for runtime data
  * `getLongestPrefix(str)`, `getLongestPrefixIndex(str)` - i'm not sure
     these belong but have left in for now incase they are deemed useful
* performance notes:
  * i posted some benchmarking results here:
    https://github.com/travisstaloch/comptime-string-map-revised/issues/1
  * i noticed a speedup reducing the size of the struct from 48 to 32
    bytes and thus use u32s instead of usize for all length fields
  * i noticed speedup storing KVs as a struct of arrays
  * latest benchmark shows these wall_time improvements for
    debug/safe/small/fast builds: -6.6% / -10.2% / -19.1% / -8.9%. full
    output in link above.
2024-04-22 15:31:41 -07:00
Andrew Kelley
fc17402919
std.crypto.Certificate: support 3072 bits RSA certificate (#19591)
Used by musicbrainz.org API.
2024-04-09 12:16:45 -07: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
mlugg
51595d6b75
lib: correct unnecessary uses of 'var' 2023-11-19 09:55:07 +00:00
Jacob Young
509be7cf1f x86_64: fix std test failures 2023-11-03 23:18:21 -04: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
27fe945a00 Revert "Revert "Merge pull request #17637 from jacobly0/x86_64-test-std""
This reverts commit 6f0198cadbe29294f2bf3153a27beebd64377566.
2023-10-22 15:46:43 -04:00
Andrew Kelley
6f0198cadb Revert "Merge pull request #17637 from jacobly0/x86_64-test-std"
This reverts commit 0c99ba1eab63865592bb084feb271cd4e4b0357e, reversing
changes made to 5f92b070bf284f1493b1b5d433dd3adde2f46727.

This caused a CI failure when it landed in master branch due to a
128-bit `@byteSwap` in std.mem.
2023-10-22 12:16:35 -07:00
Jacob Young
2e6e39a700 x86_64: fix bugs and disable erroring tests 2023-10-21 10:55:41 -04:00
Luis Cáceres
df5f6836c4 std.crypto.Certificate: consistent param types for parseTimeDigits
This commit changes the type of the first parameter of parseTimeDigits
to *const [2]u8 for consistency with parseYear4 which uses *const [4]u8
as its first parameter. This is also more ergonomic for the caller since
they don't need to dereference the array.
2023-07-23 21:02:59 +00:00
Luis Cáceres
05bad1f42d std.crypto.Certificate: fix timedate parsing
This commit fixes parsing in parseYear4 and parseTimeDigits by using a
wider vector data type such that the intermediate result cannot overflow
and the error check remains correct.
2023-07-23 20:48:45 +00: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
Andrew Kelley
629f0d23b5
Merge pull request #15579 from squeek502/mem-delimiters
Split `std.mem.split` and `tokenize` into `sequence`, `any`, and `scalar` versions
2023-06-03 13:51:02 -07: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
Ryan Liptak
2129f28953 Update all std.mem.split calls to their appropriate function
Everywhere that can now use `splitScalar` should get a nice little performance boost.
2023-05-13 13:45:05 -07:00
Linus Groh
94e30a756e std: fix a bunch of typos
The majority of these are in comments, some in doc comments which might
affect the generated documentation, and a few in parameter names -
nothing that should be breaking, however.
2023-04-30 18:16:04 -07:00
Andrew Kelley
6261c13731 update codebase to use @memset and @memcpy 2023-04-28 13:24:43 -07:00
Nameless
038ed32cff
add explicit error union for Bundle.rescan and associated functions 2023-04-17 19:14:48 -05:00
Andrew Kelley
aeaef8c0ff update std lib and compiler sources to new for loop syntax 2023-02-18 19:17:21 -07:00
Mateusz Poliwczak
bbbc4ebf03 support P256 in x509 2023-01-22 17:24:45 -05:00
山下
6c98c8d891
Wildcard certs should only validate one level of sub domain 2023-01-19 19:13:42 +00:00
Andrew Kelley
d35d086ae6 std.crypto.Certificate: add more object id 2023-01-17 00:09:38 -07:00
Andrew Kelley
7623f3fad0 std.crypto.Certificate: skip unknown attributes 2023-01-17 00:09:34 -07:00
Andrew Kelley
62e3fdcf4f std.crypto.Certificate: add more object ids 2023-01-17 00:08:42 -07:00
Andrew Kelley
9a0e1704ae std.crypto.Certificate: support v1
closes #14304
2023-01-15 14:59:49 -07:00
Andrew Kelley
9ca6d67345 std.crypto.tls.Certificate: make the current time a parameter 2023-01-02 16:57:16 -07:00
Andrew Kelley
97acdeeca8 std.crypto.tls: verify via Subject Alt Name
Previously, the code only checked Common Name, leading to unable to
validate valid certificates which relied on the subject_alt_name
extension for host name verification.

This commit also adds rsa_pss_rsae_* back to the signature algorithms
list in the ClientHello.
2023-01-02 16:57:16 -07:00
Andrew Kelley
66b07fd672 std.crypto.Certificate: bump RSA needed memory 2023-01-02 16:57:16 -07:00
Andrew Kelley
341e68ff8f std.crypto.tls.Client: remove debug prints 2023-01-02 16:57:16 -07:00
Andrew Kelley
79b41dbdbf std.crypto.tls: avoid heap allocation
The code we are borrowing from https://github.com/shiguredo/tls13-zig
requires an Allocator for doing RSA certificate verification. As a
stopgap measure, this commit uses a FixedBufferAllocator to avoid heap
allocation for these functions.

Thank you to @naoki9911 for providing this great resource which has been
extremely helpful for me when working on this standard library TLS
implementation. Until Zig has std.crypto.rsa officially, we will borrow
this implementation of RSA. 🙏
2023-01-02 16:57:16 -07:00
Andrew Kelley
22e2aaa283 crypto.tls: support rsa_pss_rsae_sha256 and fixes
* fix eof logic
 * fix read logic
 * fix VecPut logic
 * add some debug prints to remove later
2023-01-02 16:57:16 -07:00
Andrew Kelley
5bbedb63cf std.crypto.Certificate: support verifying secp384r1 pub keys 2023-01-02 16:57:15 -07:00
Andrew Kelley
b1cbfa0ec6 std.crypto.Certificate: remove subject_alt_name parsing
I believe this is provided as an extension, not in this location.
2023-01-02 16:57:15 -07:00
Andrew Kelley
b24f178029 std.crypto.tls.Certificate: fix parsing missing subsequent fields
Instead of seeing all the attributed types and values, the code was only
seeing the first one.
2023-01-02 16:57:15 -07:00
Andrew Kelley
c71c562486 remove std.crypto.der
Only a little bit of generalized logic for DER encoding is needed and so
it can live inside the Certificate namespace.

This commit removes the generic "parse object id" function which is no
longer used in favor of more specific, smaller sets of object ids used
with ComptimeStringMap.
2023-01-02 16:57:15 -07:00
Andrew Kelley
642a8b05c3 std.crypto.tls.Certificate: explicit error set for verify 2023-01-02 16:57:15 -07:00
Andrew Kelley
7cb535d4b5 std.crypto.tls.Certificate: verify time validity
When scanning the file system for root certificates, expired
certificates are skipped and therefore not used for verification in TLS
sessions. There is only this one check, however, so a long-running
server will need to periodically rescan for a new Certificate.Bundle
and strategically start using it for new sessions. In this commit I made
the judgement call that applications would like to opt-in to root
certificate rescanning at a point in time that makes sense for that
application, as opposed to having the system clock potentially start
causing connections to fail.

Certificate verification checks the subject only, as opposed to both the
subject and the issuer. The idea is that the trust chain analysis will
always check the subject, leading to every certificate in the chain's
validity being checked exactly once, with the root certificate's
validity checked upon scanning.

Furthermore, this commit adjusts the scanning logic to fully parse
certificates, even though only the subject is technically needed. This
allows relying on parsing to succeed later on.
2023-01-02 16:57:15 -07:00
Andrew Kelley
16f936b420 std.crypto.tls: handle the certificate_verify message 2023-01-02 16:57:15 -07:00
Andrew Kelley
29475b4518 std.crypto.tls: validate previous certificate 2023-01-02 16:57:15 -07:00