Commit graph

685 commits

Author SHA1 Message Date
Frank Denis
ca1fc3827e
crypto.ecdsa: fix EcdsaP384Sha3_384 constant name (#23403)
Spotted by @deatil -- Thanks!
2025-03-29 14:52:34 +00:00
Roman Frołow
37bbe7e930 typo: was issues -> was issued 2025-03-15 12:14:00 +01:00
Linus Groh
f660675467 std: Add support for SerenityOS in various places
Not nearly the entire downstream patchset but these are completely
uncontroversial and known to work.
2025-03-11 14:59:42 +00:00
Jeremy Hertel
801a95035c std.time.epoch: change getDaysInMonth to accept the year as an argument 2025-03-08 14:25:28 -05:00
Frank Denis
d8d2aa9af4
crypto.pcurves.common: generalize invert() (#23039)
The Bernstein-Yang inversion code was meant to be used only with the
fields we currently use for the NIST curves.

But people copied that code and were confused that it didn't work as
expected with other field sizes.

It doesn't cost anything to make it work with other field sizes,
that may support in the future. So let's do it.
This also reduces the diff with the example zig code in fiat crypto.

Suggested by @Rexicon226 -- Thank you!
2025-03-02 11:27:04 +01:00
Linus Groh
4b0f77cc1f std.crypto.tlcsprng: Fix hardcoded use of defaultRandomSeed()
Instead of hardcoding a call to defaultRandomSeed() use the customizable
std.options.cryptoRandomSeed() like in the rest of the function.

Closes #19943.
2025-02-22 22:39:40 -05:00
Andrew Kelley
dd54c48aa2 std.crypto.asn1: fix merge conflicts 2025-02-22 17:44:11 -08:00
Andrew Kelley
ed7004a2ee
Merge pull request #19976 from clickingbuttons/asn1
std.crypto: Add ASN1 module with OIDs and DER
2025-02-22 20:21:09 -05:00
Andrew Kelley
eb3c7f5706 zig build fmt 2025-02-22 17:09:20 -08:00
Frank Denis
65e7ede499 crypto.Ed25519.KeyPair: return an error rather than assert
When runtime safety is turned on, `Ed25519.fromSecretKey()` can
currently hit an assertion if the format of the secret key is
invalid.

Return an error instead, so that applications can recover.
2025-02-21 22:45:38 +01:00
Ryan Liptak
bbd13ab961 rescanMac: Avoid overallocating/overreading by millions of bytes
readAtLeast is greedy and will read the entire length of the buffer if it can. However, reading past the end of the cert in this case is useless, so reading the full length of the buffer just puts an increasingly large (due to the growth algorithm of ArrayList) collection of wasted bytes after each cert in cb.bytes.

In practical terms, this ends up saving potentially millions of bytes of wasted reads/allocations. In my testing, after reading the keychain files on my machine, cb.bytes ends up with these capacities:

- Before: cb.bytes.capacity = 32720747
- After: cb.bytes.capacity = 251937

That's a decrease of 99.2%

Additionally, swaps to readNoEof since it should be an error to hit EOF without reading the full cert size.
2025-02-20 22:16:05 +01:00
Frank Denis
84cdb62159
std.crypto: add the ability to explicitly tag a value as secret (#19907)
* std.crypto: add the ability to explicitly tag a value as secret

It turns out that Valgrind can be a very useful tool to check that secrets
are not leaked via side channels involving lookups or conditional jumps.

Valgrind tracks uninitialized data, and memcheck reports operations
involving uninitialized values. By permanently or temporarily telling
Valgrind that a memory region containing secrets is uninitialized, we can
detect common side-channel vulnerabilities.

For example, the following code snippets would immediately report that the
result is not computed in constant time:

```zig
classify(&key);
const len = std.mem.indexOfScalar(u8, &key, 0);
```

```zig
classify(&key);
const idx = key[0];
x += idx;
```

```zig
var x: [4]u8 = undefined;
std.crypto.random.bytes(&x);
classify(&x);
if (std.mem.eql(u8, "test", &x)) return;
```

This is not fool-proof, but it can help a lot to detect unwanted compiler
optimizations.

Also, right now, this is relying on Valgrind primitives, but these
annotations can be used to do more interesting things later, especially with
our own code generation backends.

* Update for Zig 0.14

* Remove checks for Valgrind enablement
2025-02-20 12:32:37 +01:00
Frank Denis
541d54a37d Clarify that ed25519.generateDeterministic() can be used outside tests
Fixes #22946
2025-02-20 09:01:13 +01:00
Frank Denis
8d824dfdd0
crypto.pwhash.bcrypt: make silently_truncate_password a member of Params (#22792)
* bcrypt: make silently_truncate_password a member of Params

This removes the need for having both `bcrypt()` and
`bcryptWithTruncation()` in the public API.

And whether truncation happens or not becomes even more explicit.

* Update crypto benchmark
2025-02-19 22:37:51 +01:00
Ryan Liptak
0779e847f7 Skip empty/invalid records/certs in MacOS keychain files
In the original PR that implemented this (https://github.com/ziglang/zig/pull/14325), it included a list of references for the keychain format. Multiple of those references include the checks that are added in this commit, and empirically this fixes the loading of a real keychain file that was previously failing (it had both a record with offset 0 and a record with cert_size 0).

Fixes #22870
2025-02-18 09:01:10 +01:00
Frank Denis
55c46870b2
crypto.auth.Aegis128X*Mac: properly absorb tags in the first lane (#22922)
In the MAC finalization function, concatenated tags at odd positions
were not absorbed into the correct lane.

Spotted by a Tigerbeetle regression test and reported by Rafael Batiati
(@batiati) — Thanks!
2025-02-17 17:56:09 +00:00
Don
b3a11018ae Read System.keychain as well as SystemRootCertificates.keychain for MacOS CA Bundle 2025-02-09 04:16:56 +01:00
Andrew Kelley
284de7d957 adjust runtime page size APIs
* fix merge conflicts
* rename the declarations
* reword documentation
* extract FixedBufferAllocator to separate file
* take advantage of locals
* remove the assertion about max alignment in Allocator API, leaving it
  Allocator implementation defined
* fix non-inline function call in start logic

The GeneralPurposeAllocator implementation is totally broken because it
uses global state but I didn't address that in this commit.
2025-02-06 14:23:23 -08:00
Archbirdplus
439667be04 runtime page size detection
heap.zig: define new default page sizes
heap.zig: add min/max_page_size and their options
lib/std/c: add miscellaneous declarations
heap.zig: add pageSize() and its options
switch to new page sizes, especially in GPA/stdlib
mem.zig: remove page_size
2025-02-06 14:23:23 -08:00
Frank Denis
b0ed602d5d
crypto/phc-encoding: forbid parameters named 'v' (#22569)
The spec is ambiguous, and it's too late to change it.

So the most reasonable thing to do in order to avoid generating
strings that could be parsed differently by other implementations
is to forbid parameters named "v" at compile-time.

See https://github.com/P-H-C/phc-string-format/issues/8
2025-02-06 16:37:42 +01:00
Jacob Young
8c8dfb35f3 x86_64: fix crashes compiling the compiler and tests 2025-01-16 20:47:30 -05:00
Jacob Young
7c713251ca x86_64: looped instructions 2025-01-16 20:42:08 -05:00
mlugg
9804cc8bc6
all: update to std.builtin.Type.{Pointer,Array,StructField} field renames 2025-01-16 12:49:58 +00:00
mlugg
d00e05f186
all: update to std.builtin.Type.Pointer.Size field renames
This was done by regex substitution with `sed`. I then manually went
over the entire diff and fixed any incorrect changes.

This diff also changes a lot of `callconv(.C)` to `callconv(.c)`, since
my regex happened to also trigger here. I opted to leave these changes
in, since they *are* a correct migration, even if they're not the one I
was trying to do!
2025-01-16 12:46:29 +00:00
Frank Denis
0fac47cf28
argon2: bail out if m < 8p (#22232)
Fixes #22231
2024-12-14 19:26:55 +00:00
Frank Denis
295c5a64f5
Reinstantiates AEGIS-MAC with the final construction (#22205)
This reverts commit c9d6f8b505.
2024-12-11 18:52:43 +01:00
Frank Denis
c9d6f8b505
Remove parallel variants of AEGIS-MAC (#22146)
The construction is likely to change before standardization
2024-12-04 22:45:07 +00:00
Frank Denis
73dcd19140
std.crypto.bcrypt: implement the actual OpenSSH KDF (#22027)
They way OpenSSH does key derivation to protect keys using a password
is not the standard PBKDF2, but something funky, picking key material
non-linearly.
2024-11-22 10:02:14 +01:00
Frank Denis
636308a17d
std.crypto.aes: introduce AES block vectors (#22023)
* std.crypto.aes: introduce AES block vectors

Modern Intel CPUs with the VAES extension can handle more than a
single AES block per instruction.

So can some ARM and RISC-V CPUs. Software implementations with
bitslicing can also greatly benefit from this.

Implement low-level operations on AES block vectors, and the
parallel AEGIS variants on top of them.

AMD Zen4:

      aegis-128x4:      73225 MiB/s
      aegis-128x2:      51571 MiB/s
       aegis-128l:      25806 MiB/s
      aegis-256x4:      46742 MiB/s
      aegis-256x2:      30227 MiB/s
        aegis-256:       8436 MiB/s
       aes128-gcm:       5926 MiB/s
       aes256-gcm:       5085 MiB/s

AES-GCM, and anything based on AES-CTR are also going to benefit
from this later.

* Make AEGIS-MAC twice a fast
2024-11-22 10:00:49 +01:00
Frank Denis
a5d4ad17b7
crypto.keccak.State: add checks to prevent insecure transitions (#22020)
* crypto.keccak.State: don't unconditionally permute after a squeeze()

Now, squeeze() behaves like absorb()

Namely,

squeeze(x[0..t]);
squeeze(x[t..n)); with t <= n

becomes equivalent to squeeze(x[0..n]).

* keccak: in debug mode, track transitions to prevent insecure ones.

Fixes #22019
2024-11-20 11:16:09 +01:00
Frank Denis
acba2645f7
crypto.aes.soft: use std.atomic.cache_line instead of a harcoded value (#22026) 2024-11-20 03:48:18 +00: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
Frank Denis
05a3ac43e9
crypto.ascon: support up to 16 rounds, and update links (#21953)
Initial public draft NIST SP 800-232 specifies Ascon constants
up to 16 rounds for future extensions. So, add these new constants.
2024-11-10 20:43:09 +00: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
mlugg
d11bbde5f9
compiler: remove anonymous struct types, unify all tuples
This commit reworks how anonymous struct literals and tuples work.

Previously, an untyped anonymous struct literal
(e.g. `const x = .{ .a = 123 }`) was given an "anonymous struct type",
which is a special kind of struct which coerces using structural
equivalence. This mechanism was a holdover from before we used
RLS / result types as the primary mechanism of type inference. This
commit changes the language so that the type assigned here is a "normal"
struct type. It uses a form of equivalence based on the AST node and the
type's structure, much like a reified (`@Type`) type.

Additionally, tuples have been simplified. The distinction between
"simple" and "complex" tuple types is eliminated. All tuples, even those
explicitly declared using `struct { ... }` syntax, use structural
equivalence, and do not undergo staged type resolution. Tuples are very
restricted: they cannot have non-`auto` layouts, cannot have aligned
fields, and cannot have default values with the exception of `comptime`
fields. Tuples currently do not have optimized layout, but this can be
changed in the future.

This change simplifies the language, and fixes some problematic
coercions through pointers which led to unintuitive behavior.

Resolves: #16865
2024-10-31 20:42:53 +00:00
Bruno Franca dos Reis
cdd8e82f0a
closes #21824 (#21832) 2024-10-28 14:54:02 +00:00
mlugg
bc797a97b1
std: update for new CallingConvention
The old `CallingConvention` type is replaced with the new
`NewCallingConvention`. References to `NewCallingConvention` in the
compiler are updated accordingly. In addition, a few parts of the
standard library are updated to use the new type correctly.
2024-10-19 19:15:23 +01: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