Commit graph

660 commits

Author SHA1 Message Date
clickingbuttons
3cc17b93a9 std.crypto.asn1: add short comments and der tests 2024-05-16 13:11:58 -04:00
clickingbuttons
330d353d6e std.crypto: Add ASN1 module with OIDs and DER
Add module for mapping ASN1 types to Zig types. See
`asn1.Tag.fromZig` for the mapping. Add DER encoder and decoder.

See `asn1/test.zig` for example usage of every ASN1 type.

This implementation allows ASN1 tags to be overriden with `asn1_tag`
and `asn1_tags`:
```zig
const MyContainer = (enum | union | struct) {
    field: u32,

    pub const asn1_tag = asn1.Tag.init(...);

    // This specifies a tag's class, and if explicit, additional encoding
    // rules.
    pub const asn1_tags = .{
        .field = asn1.FieldTag.explicit(0, .context_specific),
    };
};
```

Despite having an enum tag type, ASN1 frequently uses OIDs as enum
values. This is supported via an `pub const oids` field.
```zig
const MyEnum = enum {
    a,

    pub const oids = asn1.Oid.StaticMap(MyEnum).initComptime(.{
        .a = "1.2.3.4",
    });
};
```

Futhermore, a container may choose to implement encoding and decoding
however it deems fit. This allows for derived fields since Zig has a far
more powerful type system than ASN1.
```zig
// ASN1 has no standard way of tagging unions.
const MyContainer = union(enum) {
    derived: PowerfulZigType,

    const WeakAsn1Type = ...;

    pub fn encodeDer(self: MyContainer, encoder: *der.Encoder) !void {
        try encoder.any(WeakAsn1Type{...});
    }

    pub fn decodeDer(decoder: *der.Decoder) !MyContainer {
        const weak_asn1_type = try decoder.any(WeakAsn1Type);
        return .{ .derived = PowerfulZigType{...} };
    }
};
```
An unfortunate side-effect is that decoding and encoding cannot have
complete complete error sets unless we limit what errors users may
return. Luckily, PKI ASN1 types are NOT recursive so the inferred
error set should be sufficient.

Finally, other encodings are possible, but this patch only implements
a buffered DER encoder and decoder.

In an effort to keep the changeset minimal this PR does not actually
use the DER parser for stdlib PKI, but a tested example of how it may
be used for Certificate is available
[here.](https://github.com/clickingbuttons/asn1/blob/69c5709d/src/Certificate.zig)

Closes #19775.
2024-05-15 15:59:24 -04:00
Jakub Konka
2e1fc0dd14 handle visionos target OS tag in the compiler
* rename .xros to .visionos as agreed in the tracking issue
* add support for VisionOS platform in the MachO linker
2024-05-09 15:04:15 +02:00
Ryan Liptak
a52f12afc9 Delete compile errors for deprecated decls 2024-05-03 13:27:30 -07:00
clickingbuttons
8a36a1f913
std.crypto.hash.sha2: cleanup add add more docs (#19744)
* std.crypto.hash.sha2: generalize sha512 truncation

Replace `Sha512224`, `Sha512256`, and `Sha512T224` with
`fn Sha512Truncated(digest_bits: comptime_int)`.

This required refactoring `Sha2x64(comptime params)` to
`Sha2x64(comptime iv: [8]u64, digest_bits: comptime_int)`
for user-specified `digest_bits`.

I left #19697 alone but added a compile-time check that digest_bits is
divisible by 8.

Remove docs which restate type name. Add module docs and reference where
IVs come from.

* std.crypto.sha2: make Sha512_224 and Sha512_256 pub

* make generic type implementation detail, add comments

* fix iv

* address @jedisct1 feedback

* fix typo

* renaming

* add truncation clarifying comment and Sha259T192 tests
2024-04-28 22:22:09 +02: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
clickingbuttons
7cf3167e98
std.crypto: make ff.ct_unprotected.limbsCmpLt compile (#19741)
* std.crypto: make ff.ct_unprotected.limbsCmpLt compile

* std.crypto: add ff.ct test

* fix testCt to work on x86

* disable test on stage2-c

---------

Co-authored-by: Frank Denis <124872+jedisct1@users.noreply.github.com>
2024-04-23 20:29:36 +00: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
Frank Denis
d8764ec770 Rename der_encoded_max_length to der_encoded_length_max
The `length_min`/`length_max` convention is used everywhere else in
`std.crypto.*` so be consistent.
2024-04-20 16:27:56 -07:00
Meghan Denny
f03829a2da
define std.crypto.sha2.Sha512224 (#19697)
* define std.crypto.sha2.Sha512224

* rename blunder

* add sha512-224 and sha512-256 tests

* fix Sha2x64 for variations that aren't a multiple of 64 bits
2024-04-19 14:50:46 +00:00
Frank Denis
e45bdc6bd6
std.crypto.pcurves.*: simpler, smaller, faster u64 addition with carry (#19644)
signature/s:

Algorithm        Before     After
---------------+---------+-------
ecdsa-p256        3707       4396
ecdsa-p384        1067       1332
ecdsa-secp256k1   4490       5147

Add ECDSA to the benchmark by the way.
2024-04-14 01:13:22 +02: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
Frank Denis
9d27f34d04
crypto.sha3: implement constructions from NIST SP 800-185 (#19533)
https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf

This adds useful standard SHA3-based constructions from the
NIST SP 800-185 document:

- cSHAKE: similar to the SHAKE extensible hash function, but
with the addition of a context parameter.
- KMAC: SHAKE-based authentication / keyed XOF
- TupleHash: unambiguous hashing of tuples

These are required by recent protocols and specifications.

They also offer properties that none of the currently available
constructions in the stdlib offer, especially the ability to safely
hash tuples.

Other keyed hash functions/XOFs will fall back to using HMAC, which
is suboptimal from a performance perspective, but fine from a
security perspective.
2024-04-09 12:16:19 -07:00
regeliv
13a9d94a80 Change std.os.exit to std.process.exit 2024-03-22 15:01:02 +02:00
Andrew Kelley
12191c8a22 std: promote tests to doctests
Now these show up as "example usage" in generated documentation.
2024-03-21 14:11:46 -07:00
Andrew Kelley
cd62005f19 extract std.posix from std.os
closes #5019
2024-03-19 11:45:09 -07:00
Frank Denis
153ba46a5b
{aegis,aes_gcm}: fix overflow with large inputs on 32-bit systems (#19270)
These systems write the number of *bits* of their inputs as a u64.

However if `@sizeOf(usize) == 4`, an input message or associated data
whose size is > 512 MiB could overflow.

On 64-bit systems, it is safe to assume that no machine has more than
2 EiB of memory.
2024-03-12 22:56:28 +00:00
Frank Denis
b8920bceb7
ml_kem.zig: inLen -> in_len (#19269)
Don't use camelCase for variable names, especially just for that one.
2024-03-12 19:52:06 +00:00
Andrew Kelley
cb4e087fda
Merge pull request #19239 from jedisct1/ml-kem
std.crypto: add support for ML-KEM
2024-03-11 18:48:08 -07:00
Frank Denis
eaca8626b2
std.crypto.pcurves fixes (#19245)
Fixes compilation errors in functions that are syntaxic sugar
to operate on serialized scalars.

Also make it explicit that square roots in fields whose size is
not congruent to 3 modulo 4 are not an error, they are just
not implemented yet.

Reported by @vitalonodo - Thanks!
2024-03-11 09:00:15 +01:00
Frank Denis
2dba5eaa64 Fix typo in an old comment, and avoid useless hash 2024-03-10 19:54:38 +01:00
Frank Denis
1ca3a48b87 std.crypto: add support for ML-KEM
ML-KEM is the Kyber post-quantum secure key encapsulation mechanism,
as being standardized by NIST.

Too bad, they decided to rename it; the "Kyber" name was so much
better!

This implements the current draft (NIST FIPS-203), which is already
being deployed even though the specification is not finalized.
2024-03-10 15:48:38 +01:00
Ryan Liptak
16b3d1004e Remove redundant test name prefixes now that test names are fully qualified
Follow up to #19079, which made test names fully qualified.

This fixes tests that now-redundant information in their test names. For example here's a fully qualified test name before the changes in this commit:

"priority_queue.test.std.PriorityQueue: shrinkAndFree"

and the same test's name after the changes in this commit:

"priority_queue.test.shrinkAndFree"
2024-02-26 15:18:31 -08:00
Jacob Young
4fcc750ba5 x86_64: implement more shuffles 2024-02-25 11:22:10 +01:00
Jacob Young
2fdc9e6ae8 x86_64: implement @shuffle 2024-02-25 11:22:10 +01:00
Jacob Young
ab6f9e3d10 x86_64: fix incorrect mnemonic selection 2024-02-25 11:22:10 +01:00
Jacob Young
d894727873 x86_64: implement @byteSwap of big integers 2024-02-12 05:25:07 +01:00
Jacob Young
bcbd49b2a6 x86_64: implement shifts of big integers 2024-02-12 05:25:07 +01:00
e4m2
8d56e472c9 Replace std.rand references with std.Random 2024-02-08 15:21:35 +01:00
Andrew Kelley
9f3165540e std.os.linux.MAP: use a packed struct
Introduces type safety to this constant. Eliminates one use of
`usingnamespace`.
2024-02-06 21:12:11 -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
Veikka Tuominen
c085c6ecdd std: remove meta.globalOption 2024-01-27 13:56:32 -08:00
Tristan Ross
d0da3d731e std.io: replace readStructBig with readStructEndian 2024-01-22 10:53:27 -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
Carl Åstholm
59ac0d1eed Deprecate suggestVectorSize in favor of suggestVectorLength
The function returns the vector length, not the byte size of the vector or the bit size of individual elements. This distinction is very important and some usages of this function in the stdlib operated under these incorrect assumptions.
2024-01-01 16:18:57 +01:00
Frank Denis
21ae64852a
std.crypto.kem.kyber: mitigate KyberSlash (#18316)
On some architectures, including AMD Zen CPUs, dividing a secret
by a constant denominator may not be a constant-time operation.

And most Kyber implementations, including ours, could leak the
hamming weight of the shared secret because of this. See:

https://kyberslash.cr.yp.to

Multiplications aren't guaranteed to be constant-time either, but
at least on the CPUs we currently support, it is.
2023-12-22 15:57:16 +00: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
Andrew Kelley
e357550610 update for the std.fs.Dir changes 2023-11-22 15:24:57 -07:00
Andrew Kelley
49d6dd3ecb std.crypto.ff: simplify implementation
* Take advantage of multi-object for loops.
* Remove use of BoundedArray since it had no meaningful impact on safety
  or readability.
* Simplify some complex expressions, such as using `!` to invert a
  boolean value.
2023-11-22 11:32:14 -07:00
mlugg
51595d6b75
lib: correct unnecessary uses of 'var' 2023-11-19 09:55:07 +00:00
Frank Denis
a70d8d29d5
Curve25519.fromEdwards25519(): don't assume normalized coordinates (#17920)
The low-level `Curve25519.fromEdwards25519()` function assumed
that the X/Y coordinates were not scaled (Z=1).

But this is not guaranteed to be the case.

In most real-world applications, the coordinates are freshly decoded,
either directly or via the `X25519.fromEd25519()` function, so this
is not an issue.

However, since we offer the ability to do that conversion after
arbitrary computations, the assertion was not correct.
2023-11-08 11:56:56 +01: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
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
Jacob Young
f6f2708d82 x86_64: fix compiler rt test failures 2023-10-29 07:20:36 -04:00
Jacob Young
b0cf620fe3 x86_64: fix cond_br 2023-10-27 03:33:49 -04:00
Jacob Young
6ad22cd964 x86_64: add missing spills 2023-10-26 22:35:38 -04:00