NetBSD/crypto/external/bsd/openssh/dist/chacha.c

217 lines
5.3 KiB
C
Raw Permalink Normal View History

Import OpenSSH 9.5 (Last was OpenSSH 9.3) OpenSSH 9.5/9.5p1 (2023-10-04) OpenSSH 9.5 was released on 2023-10-04. It is available from the mirrors listed at https://www.openssh.com/. OpenSSH is a 100% complete SSH protocol 2.0 implementation and includes sftp client and server support. Once again, we would like to thank the OpenSSH community for their continued support of the project, especially those who contributed code or patches, reported bugs, tested snapshots or donated to the project. More information on donations may be found at: https://www.openssh.com/donations.html Changes since OpenSSH 9.4 ========================= This release fixes a number of bugs and adds some small features. Potentially incompatible changes -------------------------------- * ssh-keygen(1): generate Ed25519 keys by default. Ed25519 public keys are very convenient due to their small size. Ed25519 keys are specified in RFC 8709 and OpenSSH has supported them since version 6.5 (January 2014). * sshd(8): the Subsystem directive now accurately preserves quoting of subsystem commands and arguments. This may change behaviour for exotic configurations, but the most common subsystem configuration (sftp-server) is unlikely to be affected. New features ------------ * ssh(1): add keystroke timing obfuscation to the client. This attempts to hide inter-keystroke timings by sending interactive traffic at fixed intervals (default: every 20ms) when there is only a small amount of data being sent. It also sends fake "chaff" keystrokes for a random interval after the last real keystroke. These are controlled by a new ssh_config ObscureKeystrokeTiming keyword. * ssh(1), sshd(8): Introduce a transport-level ping facility. This adds a pair of SSH transport protocol messages SSH2_MSG_PING/PONG to implement a ping capability. These messages use numbers in the "local extensions" number space and are advertised using a "ping@openssh.com" ext-info message with a string version number of "0". * sshd(8): allow override of Subsystem directives in sshd Match blocks. Bugfixes -------- * scp(1): fix scp in SFTP mode recursive upload and download of directories that contain symlinks to other directories. In scp mode, the links would be followed, but in SFTP mode they were not. bz3611 * ssh-keygen(1): handle cr+lf (instead of just cr) line endings in sshsig signature files. * ssh(1): interactive mode for ControlPersist sessions if they originally requested a tty. * sshd(8): make PerSourceMaxStartups first-match-wins * sshd(8): limit artificial login delay to a reasonable maximum (5s) and don't delay at all for the "none" authentication mechanism.cw bz3602 * sshd(8): Log errors in kex_exchange_identification() with level verbose instead of error to reduce preauth log spam. All of those get logged with a more generic error message by sshpkt_fatal(). * sshd(8): correct math for ClientAliveInterval that caused the probes to be sent less frequently than configured. * ssh(1): fix regression in OpenSSH 9.4 (mux.c r1.99) that caused multiplexed sessions to ignore SIGINT under some circumstances. Portability ----------- * Avoid clang zero-call-used-regs=all bug on Apple compilers, which for some reason have version numbers that do not match the upstream clang version numbers. bz#3584 * Fix configure test for zlib 1.3 and later/development versions. bz3604 Checksums: ========== - SHA1 (openssh-9.5.tar.gz) = 8a0bd3a91fac338d97d91817af58df731f6509a3 - SHA256 (openssh-9.5.tar.gz) = sVMxeM3d6g65qBMktJIofxmK4Ipg9dblKif0VnhPeO0= - SHA1 (openssh-9.5p1.tar.gz) = 35c16dcc6e7d0a9465faa241476ef24f76b196cc - SHA256 (openssh-9.5p1.tar.gz) = 8Cbnt5un+1QPdRgq+W3IqPHbOV+SK7yfbKYDZyaGCGs= Please note that the SHA256 signatures are base64 encoded and not hexadecimal (which is the default for most checksum tools). The PGP key used to sign the releases is available from the mirror sites: https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/RELEASE_KEY.asc Reporting Bugs: =============== - Please read https://www.openssh.com/report.html Security bugs should be reported directly to openssh@openssh.com OpenSSH 9.4/9.4p1 (2023-08-10) OpenSSH 9.4 was released on 2023-08-10. It is available from the mirrors listed at https://www.openssh.com/. OpenSSH is a 100% complete SSH protocol 2.0 implementation and includes sftp client and server support. Once again, we would like to thank the OpenSSH community for their continued support of the project, especially those who contributed code or patches, reported bugs, tested snapshots or donated to the project. More information on donations may be found at: https://www.openssh.com/donations.html Changes since OpenSSH 9.3p2 =========================== This release fixes a number of bugs and adds some small features. Potentially incompatible changes -------------------------------- * This release removes support for older versions of libcrypto. OpenSSH now requires LibreSSL >= 3.1.0 or OpenSSL >= 1.1.1. Note that these versions are already deprecated by their upstream vendors. * ssh-agent(1): PKCS#11 modules must now be specified by their full paths. Previously dlopen(3) could search for them in system library directories. New features ------------ * ssh(1): allow forwarding Unix Domain sockets via ssh -W. * ssh(1): add support for configuration tags to ssh(1). This adds a ssh_config(5) "Tag" directive and corresponding "Match tag" predicate that may be used to select blocks of configuration similar to the pf.conf(5) keywords of the same name. * ssh(1): add a "match localnetwork" predicate. This allows matching on the addresses of available network interfaces and may be used to vary the effective client configuration based on network location. * ssh(1), sshd(8), ssh-keygen(1): infrastructure support for KRL extensions. This defines wire formats for optional KRL extensions and implements parsing of the new submessages. No actual extensions are supported at this point. * sshd(8): AuthorizedPrincipalsCommand and AuthorizedKeysCommand now accept two additional %-expansion sequences: %D which expands to the routing domain of the connected session and %C which expands to the addresses and port numbers for the source and destination of the connection. * ssh-keygen(1): increase the default work factor (rounds) for the bcrypt KDF used to derive symmetric encryption keys for passphrase protected key files by 50%. Bugfixes -------- * ssh-agent(1): improve isolation between loaded PKCS#11 modules by running separate ssh-pkcs11-helpers for each loaded provider. * ssh(1): make -f (fork after authentication) work correctly with multiplexed connections, including ControlPersist. bz3589 bz3589 * ssh(1): make ConnectTimeout apply to multiplexing sockets and not just to network connections. * ssh-agent(1), ssh(1): improve defences against invalid PKCS#11 modules being loaded by checking that the requested module contains the required symbol before loading it. * sshd(8): fix AuthorizedPrincipalsCommand when AuthorizedKeysCommand appears before it in sshd_config. Since OpenSSH 8.7 the AuthorizedPrincipalsCommand directive was incorrectly ignored in this situation. bz3574 * sshd(8), ssh(1), ssh-keygen(1): remove vestigal support for KRL signatures When the KRL format was originally defined, it included support for signing of KRL objects. However, the code to sign KRLs and verify KRL signatues was never completed in OpenSSH. This release removes the partially-implemented code to verify KRLs. All OpenSSH tools now ignore KRL_SECTION_SIGNATURE sections in KRL files. * All: fix a number of memory leaks and unreachable/harmless integer overflows. * ssh-agent(1), ssh(1): don't truncate strings logged from PKCS#11 modules; GHPR406 * sshd(8), ssh(1): better validate CASignatureAlgorithms in ssh_config and sshd_config. Previously this directive would accept certificate algorithm names, but these were unusable in practice as OpenSSH does not support CA chains. bz3577 * ssh(1): make `ssh -Q CASignatureAlgorithms` only list signature algorithms that are valid for CA signing. Previous behaviour was to list all signing algorithms, including certificate algorithms. * ssh-keyscan(1): gracefully handle systems where rlimits or the maximum number of open files is larger than INT_MAX; bz3581 * ssh-keygen(1): fix "no comment" not showing on when running `ssh-keygen -l` on multiple keys where one has a comment and other following keys do not. bz3580 * scp(1), sftp(1): adjust ftruncate() logic to handle servers that reorder requests. Previously, if the server reordered requests then the resultant file would be erroneously truncated. * ssh(1): don't incorrectly disable hostname canonicalization when CanonicalizeHostname=yes and ProxyJump was expicitly set to "none". bz3567 * scp(1): when copying local->remote, check that the source file exists before opening an SFTP connection to the server. Based on GHPR#370 Portability ----------- * All: a number of build fixes for various platforms and configuration combinations. * sshd(8): provide a replacement for the SELinux matchpathcon() function, which is deprecated. * All: relax libcrypto version checks for OpenSSL >=3. Beyond OpenSSL 3.0, the ABI compatibility guarantees are wider (only the library major must match instead of major and minor in earlier versions). bz#3548. * Tests: fix build problems for the sk-dummy.so FIDO provider module used in some tests. Checksums: ========== - SHA1 (openssh-9.4.tar.gz) = d88126d8d7b8e5bf4656587ac4a16055560641cc - SHA256 (openssh-9.4.tar.gz) = 7eqFjx2hAunw+1Jy7f1JQXq//3AMr9B3dKtASDtq8go= - SHA1 (openssh-9.4p1.tar.gz) = 5dea1f3c88f9cfe53a711a3c893ee8b7d3ffecff - SHA256 (openssh-9.4p1.tar.gz) = Ngj9kIjbIWPOs+YAyFq3nQ3j0iHlkZLqGSPiMmOGaoU= Please note that the SHA256 signatures are base64 encoded and not hexadecimal (which is the default for most checksum tools). The PGP key used to sign the releases is available from the mirror sites: https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/RELEASE_KEY.asc Reporting Bugs: =============== - Please read https://www.openssh.com/report.html Security bugs should be reported directly to openssh@openssh.com
2023-10-25 23:14:30 +03:00
/* $OpenBSD: chacha.c,v 1.2 2023/07/17 05:26:38 djm Exp $ */
Changes since OpenSSH 6.6 ========================= Potentially-incompatible changes * sshd(8): The default set of ciphers and MACs has been altered to remove unsafe algorithms. In particular, CBC ciphers and arcfour* are disabled by default. The full set of algorithms remains available if configured explicitly via the Ciphers and MACs sshd_config options. * sshd(8): Support for tcpwrappers/libwrap has been removed. * OpenSSH 6.5 and 6.6 have a bug that causes ~0.2% of connections using the curve25519-sha256@libssh.org KEX exchange method to fail when connecting with something that implements the specification correctly. OpenSSH 6.7 disables this KEX method when speaking to one of the affected versions. New Features * Major internal refactoring to begin to make part of OpenSSH usable as a library. So far the wire parsing, key handling and KRL code has been refactored. Please note that we do not consider the API stable yet, nor do we offer the library in separable form. * ssh(1), sshd(8): Add support for Unix domain socket forwarding. A remote TCP port may be forwarded to a local Unix domain socket and vice versa or both ends may be a Unix domain socket. * ssh(1), ssh-keygen(1): Add support for SSHFP DNS records for ED25519 key types. * sftp(1): Allow resumption of interrupted uploads. * ssh(1): When rekeying, skip file/DNS lookups of the hostkey if it is the same as the one sent during initial key exchange; bz#2154 * sshd(8): Allow explicit ::1 and 127.0.0.1 forwarding bind addresses when GatewayPorts=no; allows client to choose address family; bz#2222 * sshd(8): Add a sshd_config PermitUserRC option to control whether ~/.ssh/rc is executed, mirroring the no-user-rc authorized_keys option; bz#2160 * ssh(1): Add a %C escape sequence for LocalCommand and ControlPath that expands to a unique identifer based on a hash of the tuple of (local host, remote user, hostname, port). Helps avoid exceeding miserly pathname limits for Unix domain sockets in multiplexing control paths; bz#2220 * sshd(8): Make the "Too many authentication failures" message include the user, source address, port and protocol in a format similar to the authentication success / failure messages; bz#2199 * Added unit and fuzz tests for refactored code. These are run automatically in portable OpenSSH via the "make tests" target. Bugfixes * sshd(8): Fix remote forwarding with the same listen port but different listen address. * ssh(1): Fix inverted test that caused PKCS#11 keys that were explicitly listed in ssh_config or on the commandline not to be preferred. * ssh-keygen(1): Fix bug in KRL generation: multiple consecutive revoked certificate serial number ranges could be serialised to an invalid format. Readers of a broken KRL caused by this bug will fail closed, so no should-have-been-revoked key will be accepted. * ssh(1): Reflect stdio-forward ("ssh -W host:port ...") failures in exit status. Previously we were always returning 0; bz#2255 * ssh(1), ssh-keygen(1): Make Ed25519 keys' title fit properly in the randomart border; bz#2247 * ssh-agent(1): Only cleanup agent socket in the main agent process and not in any subprocesses it may have started (e.g. forked askpass). Fixes agent sockets being zapped when askpass processes fatal(); bz#2236 * ssh-add(1): Make stdout line-buffered; saves partial output getting lost when ssh-add fatal()s part-way through (e.g. when listing keys from an agent that supports key types that ssh-add doesn't); bz#2234 * ssh-keygen(1): When hashing or removing hosts, don't choke on @revoked markers and don't remove @cert-authority markers; bz#2241 * ssh(1): Don't fatal when hostname canonicalisation fails and a ProxyCommand is in use; continue and allow the ProxyCommand to connect anyway (e.g. to a host with a name outside the DNS behind a bastion) * scp(1): When copying local->remote fails during read, don't send uninitialised heap to the remote end. * sftp(1): Fix fatal "el_insertstr failed" errors when tab-completing filenames with a single quote char somewhere in the string; bz#2238 * ssh-keyscan(1): Scan for Ed25519 keys by default. * ssh(1): When using VerifyHostKeyDNS with a DNSSEC resolver, down- convert any certificate keys to plain keys and attempt SSHFP resolution. Prevents a server from skipping SSHFP lookup and forcing a new-hostkey dialog by offering only certificate keys. * sshd(8): Avoid crash at exit via NULL pointer reference; bz#2225 * Fix some strict-alignment errors. Portable OpenSSH * Portable OpenSSH now supports building against libressl-portable. * Portable OpenSSH now requires openssl 0.9.8f or greater. Older versions are no longer supported. * In the OpenSSL version check, allow fix version upgrades (but not downgrades. Debian bug #748150. * sshd(8): On Cygwin, determine privilege separation user at runtime, since it may need to be a domain account. * sshd(8): Don't attempt to use vhangup on Linux. It doesn't work for non-root users, and for them it just messes up the tty settings. * Use CLOCK_BOOTTIME in preference to CLOCK_MONOTONIC when it is available. It considers time spent suspended, thereby ensuring timeouts (e.g. for expiring agent keys) fire correctly. bz#2228 * Add support for ed25519 to opensshd.init init script. * sftp-server(8): On platforms that support it, use prctl() to prevent sftp-server from accessing /proc/self/{mem,maps} Changes since OpenSSH 6.5 ========================= This is primarily a bugfix release. Security: * sshd(8): when using environment passing with a sshd_config(5) AcceptEnv pattern with a wildcard. OpenSSH prior to 6.6 could be tricked into accepting any enviornment variable that contains the characters before the wildcard character. New / changed features: * ssh(1), sshd(8): this release removes the J-PAKE authentication code. This code was experimental, never enabled and had been unmaintained for some time. * ssh(1): when processing Match blocks, skip 'exec' clauses other clauses predicates failed to match. * ssh(1): if hostname canonicalisation is enabled and results in the destination hostname being changed, then re-parse ssh_config(5) files using the new destination hostname. This gives 'Host' and 'Match' directives that use the expanded hostname a chance to be applied. Bugfixes: * ssh(1): avoid spurious "getsockname failed: Bad file descriptor" in ssh -W. bz#2200, debian#738692 * sshd(8): allow the shutdown(2) syscall in seccomp-bpf and systrace sandbox modes, as it is reachable if the connection is terminated during the pre-auth phase. * ssh(1), sshd(8): fix unsigned overflow that in SSH protocol 1 bignum parsing. Minimum key length checks render this bug unexploitable to compromise SSH 1 sessions. * sshd_config(5): clarify behaviour of a keyword that appears in multiple matching Match blocks. bz#2184 * ssh(1): avoid unnecessary hostname lookups when canonicalisation is disabled. bz#2205 * sshd(8): avoid sandbox violation crashes in GSSAPI code by caching the supported list of GSSAPI mechanism OIDs before entering the sandbox. bz#2107 * ssh(1): fix possible crashes in SOCKS4 parsing caused by assumption that the SOCKS username is nul-terminated. * ssh(1): fix regression for UsePrivilegedPort=yes when BindAddress is not specified. * ssh(1), sshd(8): fix memory leak in ECDSA signature verification. * ssh(1): fix matching of 'Host' directives in ssh_config(5) files to be case-insensitive again (regression in 6.5). Portable OpenSSH: * sshd(8): don't fatal if the FreeBSD Capsicum is offered by the system headers and libc but is not supported by the kernel. * Fix build using the HP-UX compiler. Changes since OpenSSH 6.4 ========================= This is a feature-focused release. New features: * ssh(1), sshd(8): Add support for key exchange using elliptic-curve Diffie Hellman in Daniel Bernstein's Curve25519. This key exchange method is the default when both the client and server support it. * ssh(1), sshd(8): Add support for Ed25519 as a public key type. Ed25519 is a elliptic curve signature scheme that offers better security than ECDSA and DSA and good performance. It may be used for both user and host keys. * Add a new private key format that uses a bcrypt KDF to better protect keys at rest. This format is used unconditionally for Ed25519 keys, but may be requested when generating or saving existing keys of other types via the -o ssh-keygen(1) option. We intend to make the new format the default in the near future. Details of the new format are in the PROTOCOL.key file. * ssh(1), sshd(8): Add a new transport cipher "chacha20-poly1305@openssh.com" that combines Daniel Bernstein's ChaCha20 stream cipher and Poly1305 MAC to build an authenticated encryption mode. Details are in the PROTOCOL.chacha20poly1305 file. * ssh(1), sshd(8): Refuse RSA keys from old proprietary clients and servers that use the obsolete RSA+MD5 signature scheme. It will still be possible to connect with these clients/servers but only DSA keys will be accepted, and OpenSSH will refuse connection entirely in a future release. * ssh(1), sshd(8): Refuse old proprietary clients and servers that use a weaker key exchange hash calculation. * ssh(1): Increase the size of the Diffie-Hellman groups requested for each symmetric key size. New values from NIST Special Publication 800-57 with the upper limit specified by RFC4419. * ssh(1), ssh-agent(1): Support PKCS#11 tokens that only provide X.509 certs instead of raw public keys (requested as bz#1908). * ssh(1): Add a ssh_config(5) "Match" keyword that allows conditional configuration to be applied by matching on hostname, user and result of arbitrary commands. * ssh(1): Add support for client-side hostname canonicalisation using a set of DNS suffixes and rules in ssh_config(5). This allows unqualified names to be canonicalised to fully-qualified domain names to eliminate ambiguity when looking up keys in known_hosts or checking host certificate names. * sftp-server(8): Add the ability to whitelist and/or blacklist sftp protocol requests by name. * sftp-server(8): Add a sftp "fsync@openssh.com" to support calling fsync(2) on an open file handle. * sshd(8): Add a ssh_config(5) PermitTTY to disallow TTY allocation, mirroring the longstanding no-pty authorized_keys option. * ssh(1): Add a ssh_config ProxyUseFDPass option that supports the use of ProxyCommands that establish a connection and then pass a connected file descriptor back to ssh(1). This allows the ProxyCommand to exit rather than staying around to transfer data. Bugfixes: * ssh(1), sshd(8): Fix potential stack exhaustion caused by nested certificates. * ssh(1): bz#1211: make BindAddress work with UsePrivilegedPort. * sftp(1): bz#2137: fix the progress meter for resumed transfer. * ssh-add(1): bz#2187: do not request smartcard PIN when removing keys from ssh-agent. * sshd(8): bz#2139: fix re-exec fallback when original sshd binary cannot be executed. * ssh-keygen(1): Make relative-specified certificate expiry times relative to current time and not the validity start time. * sshd(8): bz#2161: fix AuthorizedKeysCommand inside a Match block. * sftp(1): bz#2129: symlinking a file would incorrectly canonicalise the target path. * ssh-agent(1): bz#2175: fix a use-after-free in the PKCS#11 agent helper executable. * sshd(8): Improve logging of sessions to include the user name, remote host and port, the session type (shell, command, etc.) and allocated TTY (if any). * sshd(8): bz#1297: tell the client (via a debug message) when their preferred listen address has been overridden by the server's GatewayPorts setting. * sshd(8): bz#2162: include report port in bad protocol banner message. * sftp(1): bz#2163: fix memory leak in error path in do_readdir(). * sftp(1): bz#2171: don't leak file descriptor on error. * sshd(8): Include the local address and port in "Connection from ..." message (only shown at loglevel>=verbose). Portable OpenSSH: * Please note that this is the last version of Portable OpenSSH that will support versions of OpenSSL prior to 0.9.6. Support (i.e. SSH_OLD_EVP) will be removed following the 6.5p1 release. * Portable OpenSSH will attempt compile and link as a Position Independent Executable on Linux, OS X and OpenBSD on recent gcc- like compilers. Other platforms and older/other compilers may request this using the --with-pie configure flag. * A number of other toolchain-related hardening options are used automatically if available, including -ftrapv to abort on signed integer overflow and options to write-protect dynamic linking information. The use of these options may be disabled using the --without-hardening configure flag. * If the toolchain supports it, one of the -fstack-protector-strong, -fstack-protector-all or -fstack-protector compilation flag are used to add guards to mitigate attacks based on stack overflows. The use of these options may be disabled using the --without-stackprotect configure option. * sshd(8): Add support for pre-authentication sandboxing using the Capsicum API introduced in FreeBSD 10. * Switch to a ChaCha20-based arc4random() PRNG for platforms that do not provide their own. * sshd(8): bz#2156: restore Linux oom_adj setting when handling SIGHUP to maintain behaviour over retart. * sshd(8): bz#2032: use local username in krb5_kuserok check rather than full client name which may be of form user@REALM. * ssh(1), sshd(8): Test for both the presence of ECC NID numbers in OpenSSL and that they actually work. Fedora (at least) has NID_secp521r1 that doesn't work. * bz#2173: use pkg-config --libs to include correct -L location for libedit.
2014-10-19 20:28:33 +04:00
/*
chacha-merged.c version 20080118
D. J. Bernstein
Public domain.
*/
#include "chacha.h"
typedef unsigned char u8;
typedef unsigned int u32;
typedef struct chacha_ctx chacha_ctx;
#define U8C(v) (v##U)
#define U32C(v) (v##U)
#define U8V(v) ((u8)(v) & U8C(0xFF))
#define U32V(v) ((u32)(v) & U32C(0xFFFFFFFF))
#define ROTL32(v, n) \
(U32V((v) << (n)) | ((v) >> (32 - (n))))
#define U8TO32_LITTLE(p) \
(((u32)((p)[0]) ) | \
((u32)((p)[1]) << 8) | \
((u32)((p)[2]) << 16) | \
((u32)((p)[3]) << 24))
#define U32TO8_LITTLE(p, v) \
do { \
(p)[0] = U8V((v) ); \
(p)[1] = U8V((v) >> 8); \
(p)[2] = U8V((v) >> 16); \
(p)[3] = U8V((v) >> 24); \
} while (0)
#define ROTATE(v,c) (ROTL32(v,c))
#define XOR(v,w) ((v) ^ (w))
#define PLUS(v,w) (U32V((v) + (w)))
#define PLUSONE(v) (PLUS((v),1))
#define QUARTERROUND(a,b,c,d) \
a = PLUS(a,b); d = ROTATE(XOR(d,a),16); \
c = PLUS(c,d); b = ROTATE(XOR(b,c),12); \
a = PLUS(a,b); d = ROTATE(XOR(d,a), 8); \
c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
static const char sigma[16] = "expand 32-byte k";
static const char tau[16] = "expand 16-byte k";
void
chacha_keysetup(chacha_ctx *x,const u8 *k,u32 kbits)
{
const char *constants;
x->input[4] = U8TO32_LITTLE(k + 0);
x->input[5] = U8TO32_LITTLE(k + 4);
x->input[6] = U8TO32_LITTLE(k + 8);
x->input[7] = U8TO32_LITTLE(k + 12);
if (kbits == 256) { /* recommended */
k += 16;
constants = sigma;
} else { /* kbits == 128 */
constants = tau;
}
x->input[8] = U8TO32_LITTLE(k + 0);
x->input[9] = U8TO32_LITTLE(k + 4);
x->input[10] = U8TO32_LITTLE(k + 8);
x->input[11] = U8TO32_LITTLE(k + 12);
x->input[0] = U8TO32_LITTLE(constants + 0);
x->input[1] = U8TO32_LITTLE(constants + 4);
x->input[2] = U8TO32_LITTLE(constants + 8);
x->input[3] = U8TO32_LITTLE(constants + 12);
}
void
chacha_ivsetup(chacha_ctx *x, const u8 *iv, const u8 *counter)
{
x->input[12] = counter == NULL ? 0 : U8TO32_LITTLE(counter + 0);
x->input[13] = counter == NULL ? 0 : U8TO32_LITTLE(counter + 4);
x->input[14] = U8TO32_LITTLE(iv + 0);
x->input[15] = U8TO32_LITTLE(iv + 4);
}
void
chacha_encrypt_bytes(chacha_ctx *x,const u8 *m,u8 *c,u32 bytes)
{
u32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
u32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
u8 *ctarget = NULL;
u8 tmp[64];
u_int i;
if (!bytes) return;
j0 = x->input[0];
j1 = x->input[1];
j2 = x->input[2];
j3 = x->input[3];
j4 = x->input[4];
j5 = x->input[5];
j6 = x->input[6];
j7 = x->input[7];
j8 = x->input[8];
j9 = x->input[9];
j10 = x->input[10];
j11 = x->input[11];
j12 = x->input[12];
j13 = x->input[13];
j14 = x->input[14];
j15 = x->input[15];
for (;;) {
if (bytes < 64) {
for (i = 0;i < bytes;++i) tmp[i] = m[i];
m = tmp;
ctarget = c;
c = tmp;
}
x0 = j0;
x1 = j1;
x2 = j2;
x3 = j3;
x4 = j4;
x5 = j5;
x6 = j6;
x7 = j7;
x8 = j8;
x9 = j9;
x10 = j10;
x11 = j11;
x12 = j12;
x13 = j13;
x14 = j14;
x15 = j15;
for (i = 20;i > 0;i -= 2) {
QUARTERROUND( x0, x4, x8,x12)
QUARTERROUND( x1, x5, x9,x13)
QUARTERROUND( x2, x6,x10,x14)
QUARTERROUND( x3, x7,x11,x15)
QUARTERROUND( x0, x5,x10,x15)
QUARTERROUND( x1, x6,x11,x12)
QUARTERROUND( x2, x7, x8,x13)
QUARTERROUND( x3, x4, x9,x14)
}
x0 = PLUS(x0,j0);
x1 = PLUS(x1,j1);
x2 = PLUS(x2,j2);
x3 = PLUS(x3,j3);
x4 = PLUS(x4,j4);
x5 = PLUS(x5,j5);
x6 = PLUS(x6,j6);
x7 = PLUS(x7,j7);
x8 = PLUS(x8,j8);
x9 = PLUS(x9,j9);
x10 = PLUS(x10,j10);
x11 = PLUS(x11,j11);
x12 = PLUS(x12,j12);
x13 = PLUS(x13,j13);
x14 = PLUS(x14,j14);
x15 = PLUS(x15,j15);
x0 = XOR(x0,U8TO32_LITTLE(m + 0));
x1 = XOR(x1,U8TO32_LITTLE(m + 4));
x2 = XOR(x2,U8TO32_LITTLE(m + 8));
x3 = XOR(x3,U8TO32_LITTLE(m + 12));
x4 = XOR(x4,U8TO32_LITTLE(m + 16));
x5 = XOR(x5,U8TO32_LITTLE(m + 20));
x6 = XOR(x6,U8TO32_LITTLE(m + 24));
x7 = XOR(x7,U8TO32_LITTLE(m + 28));
x8 = XOR(x8,U8TO32_LITTLE(m + 32));
x9 = XOR(x9,U8TO32_LITTLE(m + 36));
x10 = XOR(x10,U8TO32_LITTLE(m + 40));
x11 = XOR(x11,U8TO32_LITTLE(m + 44));
x12 = XOR(x12,U8TO32_LITTLE(m + 48));
x13 = XOR(x13,U8TO32_LITTLE(m + 52));
x14 = XOR(x14,U8TO32_LITTLE(m + 56));
x15 = XOR(x15,U8TO32_LITTLE(m + 60));
j12 = PLUSONE(j12);
if (!j12) {
j13 = PLUSONE(j13);
/* stopping at 2^70 bytes per nonce is user's responsibility */
}
U32TO8_LITTLE(c + 0,x0);
U32TO8_LITTLE(c + 4,x1);
U32TO8_LITTLE(c + 8,x2);
U32TO8_LITTLE(c + 12,x3);
U32TO8_LITTLE(c + 16,x4);
U32TO8_LITTLE(c + 20,x5);
U32TO8_LITTLE(c + 24,x6);
U32TO8_LITTLE(c + 28,x7);
U32TO8_LITTLE(c + 32,x8);
U32TO8_LITTLE(c + 36,x9);
U32TO8_LITTLE(c + 40,x10);
U32TO8_LITTLE(c + 44,x11);
U32TO8_LITTLE(c + 48,x12);
U32TO8_LITTLE(c + 52,x13);
U32TO8_LITTLE(c + 56,x14);
U32TO8_LITTLE(c + 60,x15);
if (bytes <= 64) {
if (bytes < 64) {
for (i = 0;i < bytes;++i) ctarget[i] = c[i];
}
x->input[12] = j12;
x->input[13] = j13;
return;
}
bytes -= 64;
c += 64;
m += 64;
}
}