diff options
Diffstat (limited to 'usr/src/cmd/ssh/libssh/common')
57 files changed, 21304 insertions, 0 deletions
diff --git a/usr/src/cmd/ssh/libssh/common/atomicio.c b/usr/src/cmd/ssh/libssh/common/atomicio.c new file mode 100644 index 0000000000..806876e24e --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/atomicio.c @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1995,1999 Theo de Raadt. All rights reserved. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: atomicio.c,v 1.10 2001/05/08 22:48:07 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "atomicio.h" + +/* + * ensure all of data on socket comes through. f==read || f==write + */ +ssize_t +atomicio(f, fd, _s, n) + ssize_t (*f) (); + int fd; + void *_s; + size_t n; +{ + char *s = _s; + ssize_t res, pos = 0; + + while (n > pos) { + res = (f) (fd, s + pos, n - pos); + switch (res) { + case -1: +#ifdef EWOULDBLOCK + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) +#else + if (errno == EINTR || errno == EAGAIN) +#endif + continue; + /* FALLTHROUGH */ + case 0: + return (res); + default: + pos += res; + } + } + return (pos); +} diff --git a/usr/src/cmd/ssh/libssh/common/authfd.c b/usr/src/cmd/ssh/libssh/common/authfd.c new file mode 100644 index 0000000000..71df5cf0e7 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/authfd.c @@ -0,0 +1,653 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Functions for connecting the local authentication agent. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * SSH2 implementation, + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: authfd.c,v 1.57 2002/09/11 18:27:26 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/evp.h> + +#include "ssh.h" +#include "rsa.h" +#include "buffer.h" +#include "bufaux.h" +#include "xmalloc.h" +#include "getput.h" +#include "key.h" +#include "authfd.h" +#include "cipher.h" +#include "kex.h" +#include "compat.h" +#include "log.h" +#include "atomicio.h" + +static int agent_present = 0; + +/* helper */ +int decode_reply(int type); + +/* macro to check for "agent failure" message */ +#define agent_failed(x) \ + ((x == SSH_AGENT_FAILURE) || (x == SSH_COM_AGENT2_FAILURE) || \ + (x == SSH2_AGENT_FAILURE)) + +int +ssh_agent_present(void) +{ + int authfd; + + if (agent_present) + return 1; + if ((authfd = ssh_get_authentication_socket()) == -1) + return 0; + else { + ssh_close_authentication_socket(authfd); + return 1; + } +} + +/* Returns the number of the authentication fd, or -1 if there is none. */ + +int +ssh_get_authentication_socket(void) +{ + const char *authsocket; + int sock; + struct sockaddr_un sunaddr; + + authsocket = getenv(SSH_AUTHSOCKET_ENV_NAME); + if (!authsocket) + return -1; + + sunaddr.sun_family = AF_UNIX; + strlcpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path)); + + sock = socket(AF_UNIX, SOCK_STREAM, 0); + if (sock < 0) + return -1; + + /* close on exec */ + if (fcntl(sock, F_SETFD, 1) == -1) { + close(sock); + return -1; + } + if (connect(sock, (struct sockaddr *) &sunaddr, sizeof sunaddr) < 0) { + close(sock); + return -1; + } + agent_present = 1; + return sock; +} + +static int +ssh_request_reply(AuthenticationConnection *auth, Buffer *request, Buffer *reply) +{ + int l, len; + char buf[1024]; + + /* Get the length of the message, and format it in the buffer. */ + len = buffer_len(request); + PUT_32BIT(buf, len); + + /* Send the length and then the packet to the agent. */ + if (atomicio(write, auth->fd, buf, 4) != 4 || + atomicio(write, auth->fd, buffer_ptr(request), + buffer_len(request)) != buffer_len(request)) { + error("Error writing to authentication socket."); + return 0; + } + /* + * Wait for response from the agent. First read the length of the + * response packet. + */ + len = 4; + while (len > 0) { + l = read(auth->fd, buf + 4 - len, len); + if (l == -1 && (errno == EAGAIN || errno == EINTR)) + continue; + if (l <= 0) { + error("Error reading response length from authentication socket."); + return 0; + } + len -= l; + } + + /* Extract the length, and check it for sanity. */ + len = GET_32BIT(buf); + if (len > 256 * 1024) + fatal("Authentication response too long: %d", len); + + /* Read the rest of the response in to the buffer. */ + buffer_clear(reply); + while (len > 0) { + l = len; + if (l > sizeof(buf)) + l = sizeof(buf); + l = read(auth->fd, buf, l); + if (l == -1 && (errno == EAGAIN || errno == EINTR)) + continue; + if (l <= 0) { + error("Error reading response from authentication socket."); + return 0; + } + buffer_append(reply, buf, l); + len -= l; + } + return 1; +} + +/* + * Closes the agent socket if it should be closed (depends on how it was + * obtained). The argument must have been returned by + * ssh_get_authentication_socket(). + */ + +void +ssh_close_authentication_socket(int sock) +{ + if (getenv(SSH_AUTHSOCKET_ENV_NAME)) + close(sock); +} + +/* + * Opens and connects a private socket for communication with the + * authentication agent. Returns the file descriptor (which must be + * shut down and closed by the caller when no longer needed). + * Returns NULL if an error occurred and the connection could not be + * opened. + */ + +AuthenticationConnection * +ssh_get_authentication_connection(void) +{ + AuthenticationConnection *auth; + int sock; + + sock = ssh_get_authentication_socket(); + + /* + * Fail if we couldn't obtain a connection. This happens if we + * exited due to a timeout. + */ + if (sock < 0) + return NULL; + + auth = xmalloc(sizeof(*auth)); + auth->fd = sock; + buffer_init(&auth->identities); + auth->howmany = 0; + + return auth; +} + +/* + * Closes the connection to the authentication agent and frees any associated + * memory. + */ + +void +ssh_close_authentication_connection(AuthenticationConnection *auth) +{ + buffer_free(&auth->identities); + close(auth->fd); + xfree(auth); +} + +/* Lock/unlock agent */ +int +ssh_lock_agent(AuthenticationConnection *auth, int lock, const char *password) +{ + int type; + Buffer msg; + + buffer_init(&msg); + buffer_put_char(&msg, lock ? SSH_AGENTC_LOCK : SSH_AGENTC_UNLOCK); + buffer_put_cstring(&msg, password); + + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return 0; + } + type = buffer_get_char(&msg); + buffer_free(&msg); + return decode_reply(type); +} + +/* + * Returns the first authentication identity held by the agent. + */ + +int +ssh_get_num_identities(AuthenticationConnection *auth, int version) +{ + int type, code1 = 0, code2 = 0; + Buffer request; + + switch (version) { + case 1: + code1 = SSH_AGENTC_REQUEST_RSA_IDENTITIES; + code2 = SSH_AGENT_RSA_IDENTITIES_ANSWER; + break; + case 2: + code1 = SSH2_AGENTC_REQUEST_IDENTITIES; + code2 = SSH2_AGENT_IDENTITIES_ANSWER; + break; + default: + return 0; + } + + /* + * Send a message to the agent requesting for a list of the + * identities it can represent. + */ + buffer_init(&request); + buffer_put_char(&request, code1); + + buffer_clear(&auth->identities); + if (ssh_request_reply(auth, &request, &auth->identities) == 0) { + buffer_free(&request); + return 0; + } + buffer_free(&request); + + /* Get message type, and verify that we got a proper answer. */ + type = buffer_get_char(&auth->identities); + if (agent_failed(type)) { + return 0; + } else if (type != code2) { + fatal("Bad authentication reply message type: %d", type); + } + + /* Get the number of entries in the response and check it for sanity. */ + auth->howmany = buffer_get_int(&auth->identities); + if (auth->howmany > 1024) + fatal("Too many identities in authentication reply: %d", + auth->howmany); + + return auth->howmany; +} + +Key * +ssh_get_first_identity(AuthenticationConnection *auth, char **comment, int version) +{ + /* get number of identities and return the first entry (if any). */ + if (ssh_get_num_identities(auth, version) > 0) + return ssh_get_next_identity(auth, comment, version); + return NULL; +} + +Key * +ssh_get_next_identity(AuthenticationConnection *auth, char **comment, int version) +{ + u_int bits; + u_char *blob; + u_int blen; + Key *key = NULL; + + /* Return failure if no more entries. */ + if (auth->howmany <= 0) + return NULL; + + /* + * Get the next entry from the packet. These will abort with a fatal + * error if the packet is too short or contains corrupt data. + */ + switch (version) { + case 1: + key = key_new(KEY_RSA1); + bits = buffer_get_int(&auth->identities); + buffer_get_bignum(&auth->identities, key->rsa->e); + buffer_get_bignum(&auth->identities, key->rsa->n); + *comment = buffer_get_string(&auth->identities, NULL); + if (bits != BN_num_bits(key->rsa->n)) + log("Warning: identity keysize mismatch: actual %d, announced %u", + BN_num_bits(key->rsa->n), bits); + break; + case 2: + blob = buffer_get_string(&auth->identities, &blen); + *comment = buffer_get_string(&auth->identities, NULL); + key = key_from_blob(blob, blen); + xfree(blob); + break; + default: + return NULL; + break; + } + /* Decrement the number of remaining entries. */ + auth->howmany--; + return key; +} + +/* + * Generates a random challenge, sends it to the agent, and waits for + * response from the agent. Returns true (non-zero) if the agent gave the + * correct answer, zero otherwise. Response type selects the style of + * response desired, with 0 corresponding to protocol version 1.0 (no longer + * supported) and 1 corresponding to protocol version 1.1. + */ + +int +ssh_decrypt_challenge(AuthenticationConnection *auth, + Key* key, BIGNUM *challenge, + u_char session_id[16], + u_int response_type, + u_char response[16]) +{ + Buffer buffer; + int success = 0; + int i; + int type; + + if (key->type != KEY_RSA1) + return 0; + if (response_type == 0) { + log("Compatibility with ssh protocol version 1.0 no longer supported."); + return 0; + } + buffer_init(&buffer); + buffer_put_char(&buffer, SSH_AGENTC_RSA_CHALLENGE); + buffer_put_int(&buffer, BN_num_bits(key->rsa->n)); + buffer_put_bignum(&buffer, key->rsa->e); + buffer_put_bignum(&buffer, key->rsa->n); + buffer_put_bignum(&buffer, challenge); + buffer_append(&buffer, session_id, 16); + buffer_put_int(&buffer, response_type); + + if (ssh_request_reply(auth, &buffer, &buffer) == 0) { + buffer_free(&buffer); + return 0; + } + type = buffer_get_char(&buffer); + + if (agent_failed(type)) { + log("Agent admitted failure to authenticate using the key."); + } else if (type != SSH_AGENT_RSA_RESPONSE) { + fatal("Bad authentication response: %d", type); + } else { + success = 1; + /* + * Get the response from the packet. This will abort with a + * fatal error if the packet is corrupt. + */ + for (i = 0; i < 16; i++) + response[i] = buffer_get_char(&buffer); + } + buffer_free(&buffer); + return success; +} + +/* ask agent to sign data, returns -1 on error, 0 on success */ +int +ssh_agent_sign(AuthenticationConnection *auth, + Key *key, + u_char **sigp, u_int *lenp, + u_char *data, u_int datalen) +{ + extern int datafellows; + Buffer msg; + u_char *blob; + u_int blen; + int type, flags = 0; + int ret = -1; + + if (key_to_blob(key, &blob, &blen) == 0) + return -1; + + if (datafellows & SSH_BUG_SIGBLOB) + flags = SSH_AGENT_OLD_SIGNATURE; + + buffer_init(&msg); + buffer_put_char(&msg, SSH2_AGENTC_SIGN_REQUEST); + buffer_put_string(&msg, blob, blen); + buffer_put_string(&msg, data, datalen); + buffer_put_int(&msg, flags); + xfree(blob); + + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return -1; + } + type = buffer_get_char(&msg); + if (agent_failed(type)) { + log("Agent admitted failure to sign using the key."); + } else if (type != SSH2_AGENT_SIGN_RESPONSE) { + fatal("Bad authentication response: %d", type); + } else { + ret = 0; + *sigp = buffer_get_string(&msg, lenp); + } + buffer_free(&msg); + return ret; +} + +/* Encode key for a message to the agent. */ + +static void +ssh_encode_identity_rsa1(Buffer *b, RSA *key, const char *comment) +{ + buffer_put_int(b, BN_num_bits(key->n)); + buffer_put_bignum(b, key->n); + buffer_put_bignum(b, key->e); + buffer_put_bignum(b, key->d); + /* To keep within the protocol: p < q for ssh. in SSL p > q */ + buffer_put_bignum(b, key->iqmp); /* ssh key->u */ + buffer_put_bignum(b, key->q); /* ssh key->p, SSL key->q */ + buffer_put_bignum(b, key->p); /* ssh key->q, SSL key->p */ + buffer_put_cstring(b, comment); +} + +static void +ssh_encode_identity_ssh2(Buffer *b, Key *key, const char *comment) +{ + buffer_put_cstring(b, key_ssh_name(key)); + switch (key->type) { + case KEY_RSA: + buffer_put_bignum2(b, key->rsa->n); + buffer_put_bignum2(b, key->rsa->e); + buffer_put_bignum2(b, key->rsa->d); + buffer_put_bignum2(b, key->rsa->iqmp); + buffer_put_bignum2(b, key->rsa->p); + buffer_put_bignum2(b, key->rsa->q); + break; + case KEY_DSA: + buffer_put_bignum2(b, key->dsa->p); + buffer_put_bignum2(b, key->dsa->q); + buffer_put_bignum2(b, key->dsa->g); + buffer_put_bignum2(b, key->dsa->pub_key); + buffer_put_bignum2(b, key->dsa->priv_key); + break; + } + buffer_put_cstring(b, comment); +} + +/* + * Adds an identity to the authentication server. This call is not meant to + * be used by normal applications. + */ + +int +ssh_add_identity_constrained(AuthenticationConnection *auth, Key *key, + const char *comment, u_int life) +{ + Buffer msg; + int type, constrained = (life != 0); + + buffer_init(&msg); + + switch (key->type) { + case KEY_RSA1: + type = constrained ? + SSH_AGENTC_ADD_RSA_ID_CONSTRAINED : + SSH_AGENTC_ADD_RSA_IDENTITY; + buffer_put_char(&msg, type); + ssh_encode_identity_rsa1(&msg, key->rsa, comment); + break; + case KEY_RSA: + case KEY_DSA: + type = constrained ? + SSH2_AGENTC_ADD_ID_CONSTRAINED : + SSH2_AGENTC_ADD_IDENTITY; + buffer_put_char(&msg, type); + ssh_encode_identity_ssh2(&msg, key, comment); + break; + default: + buffer_free(&msg); + return 0; + break; + } + if (constrained) { + if (life != 0) { + buffer_put_char(&msg, SSH_AGENT_CONSTRAIN_LIFETIME); + buffer_put_int(&msg, life); + } + } + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return 0; + } + type = buffer_get_char(&msg); + buffer_free(&msg); + return decode_reply(type); +} + +int +ssh_add_identity(AuthenticationConnection *auth, Key *key, const char *comment) +{ + return ssh_add_identity_constrained(auth, key, comment, 0); +} + +/* + * Removes an identity from the authentication server. This call is not + * meant to be used by normal applications. + */ + +int +ssh_remove_identity(AuthenticationConnection *auth, Key *key) +{ + Buffer msg; + int type; + u_char *blob; + u_int blen; + + buffer_init(&msg); + + if (key->type == KEY_RSA1) { + buffer_put_char(&msg, SSH_AGENTC_REMOVE_RSA_IDENTITY); + buffer_put_int(&msg, BN_num_bits(key->rsa->n)); + buffer_put_bignum(&msg, key->rsa->e); + buffer_put_bignum(&msg, key->rsa->n); + } else if (key->type == KEY_DSA || key->type == KEY_RSA) { + key_to_blob(key, &blob, &blen); + buffer_put_char(&msg, SSH2_AGENTC_REMOVE_IDENTITY); + buffer_put_string(&msg, blob, blen); + xfree(blob); + } else { + buffer_free(&msg); + return 0; + } + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return 0; + } + type = buffer_get_char(&msg); + buffer_free(&msg); + return decode_reply(type); +} + +int +ssh_update_card(AuthenticationConnection *auth, int add, const char *reader_id, const char *pin) +{ + Buffer msg; + int type; + + buffer_init(&msg); + buffer_put_char(&msg, add ? SSH_AGENTC_ADD_SMARTCARD_KEY : + SSH_AGENTC_REMOVE_SMARTCARD_KEY); + buffer_put_cstring(&msg, reader_id); + buffer_put_cstring(&msg, pin); + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return 0; + } + type = buffer_get_char(&msg); + buffer_free(&msg); + return decode_reply(type); +} + +/* + * Removes all identities from the agent. This call is not meant to be used + * by normal applications. + */ + +int +ssh_remove_all_identities(AuthenticationConnection *auth, int version) +{ + Buffer msg; + int type; + int code = (version==1) ? + SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES : + SSH2_AGENTC_REMOVE_ALL_IDENTITIES; + + buffer_init(&msg); + buffer_put_char(&msg, code); + + if (ssh_request_reply(auth, &msg, &msg) == 0) { + buffer_free(&msg); + return 0; + } + type = buffer_get_char(&msg); + buffer_free(&msg); + return decode_reply(type); +} + +int +decode_reply(int type) +{ + switch (type) { + case SSH_AGENT_FAILURE: + case SSH_COM_AGENT2_FAILURE: + case SSH2_AGENT_FAILURE: + log("SSH_AGENT_FAILURE"); + return 0; + case SSH_AGENT_SUCCESS: + return 1; + default: + fatal("Bad response from authentication agent: %d", type); + } + /* NOTREACHED */ + return 0; +} diff --git a/usr/src/cmd/ssh/libssh/common/authfile.c b/usr/src/cmd/ssh/libssh/common/authfile.c new file mode 100644 index 0000000000..29076f390f --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/authfile.c @@ -0,0 +1,624 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * This file contains functions for reading and writing identity files, and + * for reading the passphrase from the user. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: authfile.c,v 1.50 2002/06/24 14:55:38 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/err.h> +#include <openssl/evp.h> +#include <openssl/pem.h> + +#include "cipher.h" +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "ssh.h" +#include "log.h" +#include "authfile.h" +#include "rsa.h" + +/* Version identification string for SSH v1 identity files. */ +static const char authfile_id_string[] = + "SSH PRIVATE KEY FILE FORMAT 1.1\n"; + +/* + * Saves the authentication (private) key in a file, encrypting it with + * passphrase. The identification of the file (lowest 64 bits of n) will + * precede the key to provide identification of the key without needing a + * passphrase. + */ + +static int +key_save_private_rsa1(Key *key, const char *filename, const char *passphrase, + const char *comment) +{ + Buffer buffer, encrypted; + u_char buf[100], *cp; + int fd, i, cipher_num; + CipherContext ciphercontext; + Cipher *cipher; + u_int32_t rand; + + /* + * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting + * to another cipher; otherwise use SSH_AUTHFILE_CIPHER. + */ + cipher_num = (strcmp(passphrase, "") == 0) ? + SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER; + if ((cipher = cipher_by_number(cipher_num)) == NULL) + fatal("save_private_key_rsa: bad cipher"); + + /* This buffer is used to built the secret part of the private key. */ + buffer_init(&buffer); + + /* Put checkbytes for checking passphrase validity. */ + rand = arc4random(); + buf[0] = rand & 0xff; + buf[1] = (rand >> 8) & 0xff; + buf[2] = buf[0]; + buf[3] = buf[1]; + buffer_append(&buffer, buf, 4); + + /* + * Store the private key (n and e will not be stored because they + * will be stored in plain text, and storing them also in encrypted + * format would just give known plaintext). + */ + buffer_put_bignum(&buffer, key->rsa->d); + buffer_put_bignum(&buffer, key->rsa->iqmp); + buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */ + buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */ + + /* Pad the part to be encrypted until its size is a multiple of 8. */ + while (buffer_len(&buffer) % 8 != 0) + buffer_put_char(&buffer, 0); + + /* This buffer will be used to contain the data in the file. */ + buffer_init(&encrypted); + + /* First store keyfile id string. */ + for (i = 0; authfile_id_string[i]; i++) + buffer_put_char(&encrypted, authfile_id_string[i]); + buffer_put_char(&encrypted, 0); + + /* Store cipher type. */ + buffer_put_char(&encrypted, cipher_num); + buffer_put_int(&encrypted, 0); /* For future extension */ + + /* Store public key. This will be in plain text. */ + buffer_put_int(&encrypted, BN_num_bits(key->rsa->n)); + buffer_put_bignum(&encrypted, key->rsa->n); + buffer_put_bignum(&encrypted, key->rsa->e); + buffer_put_cstring(&encrypted, comment); + + /* Allocate space for the private part of the key in the buffer. */ + cp = buffer_append_space(&encrypted, buffer_len(&buffer)); + + cipher_set_key_string(&ciphercontext, cipher, passphrase, + CIPHER_ENCRYPT); + cipher_crypt(&ciphercontext, cp, + buffer_ptr(&buffer), buffer_len(&buffer)); + cipher_cleanup(&ciphercontext); + memset(&ciphercontext, 0, sizeof(ciphercontext)); + + /* Destroy temporary data. */ + memset(buf, 0, sizeof(buf)); + buffer_free(&buffer); + + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) { + error("open %s failed: %s.", filename, strerror(errno)); + return 0; + } + if (write(fd, buffer_ptr(&encrypted), buffer_len(&encrypted)) != + buffer_len(&encrypted)) { + error("write to key file %s failed: %s", filename, + strerror(errno)); + buffer_free(&encrypted); + close(fd); + unlink(filename); + return 0; + } + close(fd); + buffer_free(&encrypted); + return 1; +} + +/* save SSH v2 key in OpenSSL PEM format */ +static int +key_save_private_pem(Key *key, const char *filename, const char *_passphrase, + const char *comment) +{ + FILE *fp; + int fd; + int success = 0; + int len = strlen(_passphrase); + u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL; + const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL; + + if (len > 0 && len <= 4) { + error("passphrase too short: have %d bytes, need > 4", len); + return 0; + } + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) { + error("open %s failed: %s.", filename, strerror(errno)); + return 0; + } + fp = fdopen(fd, "w"); + if (fp == NULL ) { + error("fdopen %s failed: %s.", filename, strerror(errno)); + close(fd); + return 0; + } + switch (key->type) { + case KEY_DSA: + success = PEM_write_DSAPrivateKey(fp, key->dsa, + cipher, passphrase, len, NULL, NULL); + break; + case KEY_RSA: + success = PEM_write_RSAPrivateKey(fp, key->rsa, + cipher, passphrase, len, NULL, NULL); + break; + } + fclose(fp); + return success; +} + +int +key_save_private(Key *key, const char *filename, const char *passphrase, + const char *comment) +{ + switch (key->type) { + case KEY_RSA1: + return key_save_private_rsa1(key, filename, passphrase, + comment); + break; + case KEY_DSA: + case KEY_RSA: + return key_save_private_pem(key, filename, passphrase, + comment); + break; + default: + break; + } + error("key_save_private: cannot save key type %d", key->type); + return 0; +} + +/* + * Loads the public part of the ssh v1 key file. Returns NULL if an error was + * encountered (the file does not exist or is not readable), and the key + * otherwise. + */ + +static Key * +key_load_public_rsa1(int fd, const char *filename, char **commentp) +{ + Buffer buffer; + Key *pub; + char *cp; + int i; + off_t len; + + len = lseek(fd, (off_t) 0, SEEK_END); + lseek(fd, (off_t) 0, SEEK_SET); + + buffer_init(&buffer); + cp = buffer_append_space(&buffer, len); + + if (read(fd, cp, (size_t) len) != (size_t) len) { + debug("Read from key file %.200s failed: %.100s", filename, + strerror(errno)); + buffer_free(&buffer); + return NULL; + } + + /* Check that it is at least big enough to contain the ID string. */ + if (len < sizeof(authfile_id_string)) { + debug3("Not a RSA1 key file %.200s.", filename); + buffer_free(&buffer); + return NULL; + } + /* + * Make sure it begins with the id string. Consume the id string + * from the buffer. + */ + for (i = 0; i < sizeof(authfile_id_string); i++) + if (buffer_get_char(&buffer) != authfile_id_string[i]) { + debug3("Not a RSA1 key file %.200s.", filename); + buffer_free(&buffer); + return NULL; + } + /* Skip cipher type and reserved data. */ + (void) buffer_get_char(&buffer); /* cipher type */ + (void) buffer_get_int(&buffer); /* reserved */ + + /* Read the public key from the buffer. */ + (void) buffer_get_int(&buffer); + pub = key_new(KEY_RSA1); + buffer_get_bignum(&buffer, pub->rsa->n); + buffer_get_bignum(&buffer, pub->rsa->e); + if (commentp) + *commentp = buffer_get_string(&buffer, NULL); + /* The encrypted private part is not parsed by this function. */ + + buffer_free(&buffer); + return pub; +} + +/* load public key from private-key file, works only for SSH v1 */ +Key * +key_load_public_type(int type, const char *filename, char **commentp) +{ + Key *pub; + int fd; + + if (type == KEY_RSA1) { + fd = open(filename, O_RDONLY); + if (fd < 0) + return NULL; + pub = key_load_public_rsa1(fd, filename, commentp); + close(fd); + return pub; + } + return NULL; +} + +/* + * Loads the private key from the file. Returns 0 if an error is encountered + * (file does not exist or is not readable, or passphrase is bad). This + * initializes the private key. + * Assumes we are called under uid of the owner of the file. + */ + +static Key * +key_load_private_rsa1(int fd, const char *filename, const char *passphrase, + char **commentp) +{ + int i, check1, check2, cipher_type; + off_t len; + Buffer buffer, decrypted; + u_char *cp; + CipherContext ciphercontext; + Cipher *cipher; + Key *prv = NULL; + + len = lseek(fd, (off_t) 0, SEEK_END); + lseek(fd, (off_t) 0, SEEK_SET); + + buffer_init(&buffer); + cp = buffer_append_space(&buffer, len); + + if (read(fd, cp, (size_t) len) != (size_t) len) { + debug("Read from key file %.200s failed: %.100s", filename, + strerror(errno)); + buffer_free(&buffer); + close(fd); + return NULL; + } + + /* Check that it is at least big enough to contain the ID string. */ + if (len < sizeof(authfile_id_string)) { + debug3("Not a RSA1 key file %.200s.", filename); + buffer_free(&buffer); + close(fd); + return NULL; + } + /* + * Make sure it begins with the id string. Consume the id string + * from the buffer. + */ + for (i = 0; i < sizeof(authfile_id_string); i++) + if (buffer_get_char(&buffer) != authfile_id_string[i]) { + debug3("Not a RSA1 key file %.200s.", filename); + buffer_free(&buffer); + close(fd); + return NULL; + } + + /* Read cipher type. */ + cipher_type = buffer_get_char(&buffer); + (void) buffer_get_int(&buffer); /* Reserved data. */ + + /* Read the public key from the buffer. */ + (void) buffer_get_int(&buffer); + prv = key_new_private(KEY_RSA1); + + buffer_get_bignum(&buffer, prv->rsa->n); + buffer_get_bignum(&buffer, prv->rsa->e); + if (commentp) + *commentp = buffer_get_string(&buffer, NULL); + else + xfree(buffer_get_string(&buffer, NULL)); + + /* Check that it is a supported cipher. */ + cipher = cipher_by_number(cipher_type); + if (cipher == NULL) { + debug("Unsupported cipher %d used in key file %.200s.", + cipher_type, filename); + buffer_free(&buffer); + goto fail; + } + /* Initialize space for decrypted data. */ + buffer_init(&decrypted); + cp = buffer_append_space(&decrypted, buffer_len(&buffer)); + + /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */ + cipher_set_key_string(&ciphercontext, cipher, passphrase, + CIPHER_DECRYPT); + cipher_crypt(&ciphercontext, cp, + buffer_ptr(&buffer), buffer_len(&buffer)); + cipher_cleanup(&ciphercontext); + memset(&ciphercontext, 0, sizeof(ciphercontext)); + buffer_free(&buffer); + + check1 = buffer_get_char(&decrypted); + check2 = buffer_get_char(&decrypted); + if (check1 != buffer_get_char(&decrypted) || + check2 != buffer_get_char(&decrypted)) { + if (strcmp(passphrase, "") != 0) + debug("Bad passphrase supplied for key file %.200s.", + filename); + /* Bad passphrase. */ + buffer_free(&decrypted); + goto fail; + } + /* Read the rest of the private key. */ + buffer_get_bignum(&decrypted, prv->rsa->d); + buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */ + /* in SSL and SSH v1 p and q are exchanged */ + buffer_get_bignum(&decrypted, prv->rsa->q); /* p */ + buffer_get_bignum(&decrypted, prv->rsa->p); /* q */ + + /* calculate p-1 and q-1 */ + rsa_generate_additional_parameters(prv->rsa); + + buffer_free(&decrypted); + close(fd); + return prv; + +fail: + if (commentp) + xfree(*commentp); + close(fd); + key_free(prv); + return NULL; +} + +Key * +key_load_private_pem(int fd, int type, const char *passphrase, + char **commentp) +{ + FILE *fp; + EVP_PKEY *pk = NULL; + Key *prv = NULL; + char *name = "<no key>"; + + fp = fdopen(fd, "r"); + if (fp == NULL) { + error("fdopen failed: %s", strerror(errno)); + close(fd); + return NULL; + } + pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase); + if (pk == NULL) { + debug("PEM_read_PrivateKey failed"); + (void)ERR_get_error(); + } else if (pk->type == EVP_PKEY_RSA && + (type == KEY_UNSPEC||type==KEY_RSA)) { + prv = key_new(KEY_UNSPEC); + prv->rsa = EVP_PKEY_get1_RSA(pk); + prv->type = KEY_RSA; + name = "rsa w/o comment"; +#ifdef DEBUG_PK + RSA_print_fp(stderr, prv->rsa, 8); +#endif + } else if (pk->type == EVP_PKEY_DSA && + (type == KEY_UNSPEC||type==KEY_DSA)) { + prv = key_new(KEY_UNSPEC); + prv->dsa = EVP_PKEY_get1_DSA(pk); + prv->type = KEY_DSA; + name = "dsa w/o comment"; +#ifdef DEBUG_PK + DSA_print_fp(stderr, prv->dsa, 8); +#endif + } else { + error("PEM_read_PrivateKey: mismatch or " + "unknown EVP_PKEY save_type %d", pk->save_type); + } + fclose(fp); + if (pk != NULL) + EVP_PKEY_free(pk); + if (prv != NULL && commentp) + *commentp = xstrdup(name); + debug("read PEM private key done: type %s", + prv ? key_type(prv) : "<unknown>"); + return prv; +} + +static int +key_perm_ok(int fd, const char *filename) +{ + struct stat st; + + if (fstat(fd, &st) < 0) + return 0; + /* + * if a key owned by the user is accessed, then we check the + * permissions of the file. if the key owned by a different user, + * then we don't care. + */ +#ifdef HAVE_CYGWIN + if (check_ntsec(filename)) +#endif + if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) { + error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @"); + error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); + error("Permissions 0%3.3o for '%s' are too open.", + (int)(st.st_mode & 0777), filename); + error("It is recommended that your private key files are NOT accessible by others."); + error("This private key will be ignored."); + return 0; + } + return 1; +} + +Key * +key_load_private_type(int type, const char *filename, const char *passphrase, + char **commentp) +{ + int fd; + + fd = open(filename, O_RDONLY); + if (fd < 0) + return NULL; + if (!key_perm_ok(fd, filename)) { + error("bad permissions: ignore key: %s", filename); + close(fd); + return NULL; + } + switch (type) { + case KEY_RSA1: + return key_load_private_rsa1(fd, filename, passphrase, + commentp); + /* closes fd */ + break; + case KEY_DSA: + case KEY_RSA: + case KEY_UNSPEC: + return key_load_private_pem(fd, type, passphrase, commentp); + /* closes fd */ + break; + default: + close(fd); + break; + } + return NULL; +} + +Key * +key_load_private(const char *filename, const char *passphrase, + char **commentp) +{ + Key *pub, *prv; + int fd; + + fd = open(filename, O_RDONLY); + if (fd < 0) + return NULL; + if (!key_perm_ok(fd, filename)) { + error("bad permissions: ignore key: %s", filename); + close(fd); + return NULL; + } + pub = key_load_public_rsa1(fd, filename, commentp); + lseek(fd, (off_t) 0, SEEK_SET); /* rewind */ + if (pub == NULL) { + /* closes fd */ + prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL); + /* use the filename as a comment for PEM */ + if (commentp && prv) + *commentp = xstrdup(filename); + } else { + /* it's a SSH v1 key if the public key part is readable */ + key_free(pub); + /* closes fd */ + prv = key_load_private_rsa1(fd, filename, passphrase, NULL); + } + return prv; +} + +static int +key_try_load_public(Key *k, const char *filename, char **commentp) +{ + FILE *f; + char line[4096]; + char *cp; + + f = fopen(filename, "r"); + if (f != NULL) { + while (fgets(line, sizeof(line), f)) { + line[sizeof(line)-1] = '\0'; + cp = line; + switch (*cp) { + case '#': + case '\n': + case '\0': + continue; + } + /* Skip leading whitespace. */ + for (; *cp && (*cp == ' ' || *cp == '\t'); cp++) + ; + if (*cp) { + if (key_read(k, &cp) == 1) { + if (commentp) + *commentp=xstrdup(filename); + fclose(f); + return 1; + } + } + } + fclose(f); + } + return 0; +} + +/* load public key from ssh v1 private or any pubkey file */ +Key * +key_load_public(const char *filename, char **commentp) +{ + Key *pub; + char file[MAXPATHLEN]; + + pub = key_load_public_type(KEY_RSA1, filename, commentp); + if (pub != NULL) + return pub; + pub = key_new(KEY_UNSPEC); + if (key_try_load_public(pub, filename, commentp) == 1) + return pub; + if ((strlcpy(file, filename, sizeof file) < sizeof(file)) && + (strlcat(file, ".pub", sizeof file) < sizeof(file)) && + (key_try_load_public(pub, file, commentp) == 1)) + return pub; + key_free(pub); + return NULL; +} diff --git a/usr/src/cmd/ssh/libssh/common/bufaux.c b/usr/src/cmd/ssh/libssh/common/bufaux.c new file mode 100644 index 0000000000..15ade28076 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/bufaux.c @@ -0,0 +1,409 @@ +/* + * Copyright 2005 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Auxiliary functions for storing and retrieving various data types to/from + * Buffers. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * SSH2 packet format added by Markus Friedl + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: bufaux.c,v 1.27 2002/06/26 08:53:12 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <langinfo.h> +#include <openssl/bn.h> +#include "bufaux.h" +#include "xmalloc.h" +#include "getput.h" +#include "log.h" +#include "g11n.h" + +/* + * Stores an BIGNUM in the buffer with a 2-byte msb first bit count, followed + * by (bits+7)/8 bytes of binary data, msb first. + */ +void +buffer_put_bignum(Buffer *buffer, BIGNUM *value) +{ + int bits = BN_num_bits(value); + int bin_size = (bits + 7) / 8; + u_char *buf = xmalloc(bin_size); + int oi; + char msg[2]; + + /* Get the value of in binary */ + oi = BN_bn2bin(value, buf); + if (oi != bin_size) + fatal("buffer_put_bignum: BN_bn2bin() failed: oi %d != bin_size %d", + oi, bin_size); + + /* Store the number of bits in the buffer in two bytes, msb first. */ + PUT_16BIT(msg, bits); + buffer_append(buffer, msg, 2); + /* Store the binary data. */ + buffer_append(buffer, (char *)buf, oi); + + memset(buf, 0, bin_size); + xfree(buf); +} + +/* + * Retrieves an BIGNUM from the buffer. + */ +void +buffer_get_bignum(Buffer *buffer, BIGNUM *value) +{ + int bits, bytes; + u_char buf[2], *bin; + + /* Get the number for bits. */ + buffer_get(buffer, (char *) buf, 2); + bits = GET_16BIT(buf); + /* Compute the number of binary bytes that follow. */ + bytes = (bits + 7) / 8; + if (bytes > 8 * 1024) + fatal("buffer_get_bignum: cannot handle BN of size %d", bytes); + if (buffer_len(buffer) < bytes) + fatal("buffer_get_bignum: input buffer too small"); + bin = buffer_ptr(buffer); + BN_bin2bn(bin, bytes, value); + buffer_consume(buffer, bytes); +} + +/* + * Stores an BIGNUM in the buffer in SSH2 format. + */ +void +buffer_put_bignum2(Buffer *buffer, BIGNUM *value) +{ + int bytes = BN_num_bytes(value) + 1; + u_char *buf = xmalloc(bytes); + int oi; + int hasnohigh = 0; + + buf[0] = '\0'; + /* Get the value of in binary */ + oi = BN_bn2bin(value, buf+1); + if (oi != bytes-1) + fatal("buffer_put_bignum: BN_bn2bin() failed: oi %d != bin_size %d", + oi, bytes); + hasnohigh = (buf[1] & 0x80) ? 0 : 1; + if (value->neg) { + /**XXX should be two's-complement */ + int i, carry; + u_char *uc = buf; + log("negativ!"); + for (i = bytes-1, carry = 1; i>=0; i--) { + uc[i] ^= 0xff; + if (carry) + carry = !++uc[i]; + } + } + buffer_put_string(buffer, buf+hasnohigh, bytes-hasnohigh); + memset(buf, 0, bytes); + xfree(buf); +} + +/* XXX does not handle negative BNs */ +void +buffer_get_bignum2(Buffer *buffer, BIGNUM *value) +{ + u_int len; + u_char *bin = buffer_get_string(buffer, &len); + + if (len > 8 * 1024) + fatal("buffer_get_bignum2: cannot handle BN of size %d", len); + BN_bin2bn(bin, len, value); + xfree(bin); +} +/* + * Returns integers from the buffer (msb first). + */ + +u_short +buffer_get_short(Buffer *buffer) +{ + u_char buf[2]; + + buffer_get(buffer, (char *) buf, 2); + return GET_16BIT(buf); +} + +u_int +buffer_get_int(Buffer *buffer) +{ + u_char buf[4]; + + buffer_get(buffer, (char *) buf, 4); + return GET_32BIT(buf); +} + +#ifdef HAVE_U_INT64_T +u_int64_t +buffer_get_int64(Buffer *buffer) +{ + u_char buf[8]; + + buffer_get(buffer, (char *) buf, 8); + return GET_64BIT(buf); +} +#endif + +/* + * Stores integers in the buffer, msb first. + */ +void +buffer_put_short(Buffer *buffer, u_short value) +{ + char buf[2]; + + PUT_16BIT(buf, value); + buffer_append(buffer, buf, 2); +} + +void +buffer_put_int(Buffer *buffer, u_int value) +{ + char buf[4]; + + PUT_32BIT(buf, value); + buffer_append(buffer, buf, 4); +} + +#ifdef HAVE_U_INT64_T +void +buffer_put_int64(Buffer *buffer, u_int64_t value) +{ + char buf[8]; + + PUT_64BIT(buf, value); + buffer_append(buffer, buf, 8); +} +#endif + +/* + * Returns an arbitrary binary string from the buffer. The string cannot + * be longer than 256k. The returned value points to memory allocated + * with xmalloc; it is the responsibility of the calling function to free + * the data. If length_ptr is non-NULL, the length of the returned data + * will be stored there. A null character will be automatically appended + * to the returned string, and is not counted in length. + */ +void * +buffer_get_string(Buffer *buffer, u_int *length_ptr) +{ + u_char *value; + u_int len; + + /* Get the length. */ + len = buffer_get_int(buffer); + if (len > 256 * 1024) + fatal("buffer_get_string: bad string length %d", len); + /* Allocate space for the string. Add one byte for a null character. */ + value = xmalloc(len + 1); + /* Get the string. */ + buffer_get(buffer, value, len); + /* Append a null character to make processing easier. */ + value[len] = 0; + /* Optionally return the length of the string. */ + if (length_ptr) + *length_ptr = len; + return value; +} +char * +buffer_get_ascii_cstring(Buffer *buffer) +{ + char *value; + u_char *p; + u_int len; + value = buffer_get_string(buffer, &len); + + /* Look for NULL or high-bit set bytes */ + for (p = (u_char *) value ; + p && *p && (!(*p & 0x80)) && (p - (u_char *) value) < len ; + p++) ; + + /* If there were any, bomb */ + if ((p - (u_char *) value) != len) { + xfree(value); + errno = EILSEQ; + return NULL; + } + return value; +} +u_char * +buffer_get_utf8_cstring(Buffer *buffer) +{ + u_char *value, *converted, *estr; + u_int len; + int err; + + if ((value = buffer_get_string(buffer, &len)) == NULL) { + return value; + } + + converted = g11n_convert_from_utf8(value, &err, &estr); + + if (converted != value) xfree(value); + + if (err) + fatal("invalid UTF-8 sequence; %s", estr); + + return converted; +} + +/* + * Stores and arbitrary binary string in the buffer. + */ +void +buffer_put_string(Buffer *buffer, const void *buf, u_int len) +{ + buffer_put_int(buffer, len); + buffer_append(buffer, buf, len); +} +void +buffer_put_cstring(Buffer *buffer, const char *s) +{ + if (s == NULL) + fatal("buffer_put_cstring: s == NULL"); + buffer_put_string(buffer, s, strlen(s)); +} + +/* + * ASCII versions of the above + */ +#if 0 +void +buffer_put_ascii_string(Buffer *buffer, const void *buf, u_int len) +{ + u_char *p; + for (p = (u_char *) buf ; + p && ((p - (u_char *) buf) < len) && *p && (!(*p & 0x80)) ; + p++) ; + + if ((p - (u_char *) buf) != len) + verbose("buffer_put_ascii_string: storing a non-ASCII string"); + buffer_put_int(buffer, len); + buffer_append(buffer, buf, len); +} +#endif +void +buffer_put_ascii_cstring(Buffer *buffer, const char *s) +{ + u_char *estr; + if (s == NULL) + fatal("buffer_put_cstring: s == NULL"); + + if (!g11n_validate_ascii(s, strlen(s), &estr)) + verbose("buffer_put_ascii_cstring: non-ASCII string; %s", estr); + + buffer_put_cstring(buffer, s); +} + +/* + * UTF-8 versions of the above. + */ + +#if 0 +void +buffer_put_utf8_string(Buffer *buffer, const void *buf, u_int len) +{ + char *converted *estr; + + converted = g11n_convert_to_utf8(buf, &err, &estr); + + if (!converted && err) + fatal("buffer_put_utf8_string: input not a valid UTF-8 encoding; %s", estr); + + if (err) + verbose("buffer_put_utf8_string: input not a valid UTF-8 encoding; %s", estr); + + buffer_put_string(buffer, converted, strlen(converted)); + + if (converted != bug) xfree(converted); + + return; +} +#endif +void +buffer_put_utf8_cstring(Buffer *buffer, const u_char *s) +{ + u_char *converted, *estr; + int err; + + if (s == NULL) + fatal("buffer_put_cstring: s == NULL"); + + converted = g11n_convert_to_utf8(s, &err, &estr); + + if (!converted && err) + fatal("buffer_put_utf8_string: input not a valid UTF-8 encoding; %s", estr); + + if (err) + verbose("buffer_put_utf8_string: input not a valid UTF-8 encoding; %s", estr); + + buffer_put_cstring(buffer, (const char *) converted); + + if (converted != s) xfree(converted); + + return; +} + + +/* + * Returns a character from the buffer (0 - 255). + */ +int +buffer_get_char(Buffer *buffer) +{ + char ch; + + buffer_get(buffer, &ch, 1); + return (u_char) ch; +} + +/* + * Stores a character in the buffer. + */ +void +buffer_put_char(Buffer *buffer, int value) +{ + char ch = value; + + buffer_append(buffer, &ch, 1); +} diff --git a/usr/src/cmd/ssh/libssh/common/buffer.c b/usr/src/cmd/ssh/libssh/common/buffer.c new file mode 100644 index 0000000000..f0168e4ba3 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/buffer.c @@ -0,0 +1,184 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Functions for manipulating fifo buffers (that can grow if needed). + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: buffer.c,v 1.16 2002/06/26 08:54:18 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "buffer.h" +#include "log.h" + +/* Initializes the buffer structure. */ + +void +buffer_init(Buffer *buffer) +{ + const u_int len = 4096; + + buffer->alloc = 0; + buffer->buf = xmalloc(len); + buffer->alloc = len; + buffer->offset = 0; + buffer->end = 0; +} + +/* Frees any memory used for the buffer. */ + +void +buffer_free(Buffer *buffer) +{ + if (buffer->alloc > 0) { + memset(buffer->buf, 0, buffer->alloc); + xfree(buffer->buf); + } +} + +/* + * Clears any data from the buffer, making it empty. This does not actually + * zero the memory. + */ + +void +buffer_clear(Buffer *buffer) +{ + buffer->offset = 0; + buffer->end = 0; +} + +/* Appends data to the buffer, expanding it if necessary. */ + +void +buffer_append(Buffer *buffer, const void *data, u_int len) +{ + void *p; + p = buffer_append_space(buffer, len); + memcpy(p, data, len); +} + +/* + * Appends space to the buffer, expanding the buffer if necessary. This does + * not actually copy the data into the buffer, but instead returns a pointer + * to the allocated region. + */ + +void * +buffer_append_space(Buffer *buffer, u_int len) +{ + u_int newlen; + void *p; + + if (len > 0x100000) + fatal("buffer_append_space: len %u not supported", len); + + /* If the buffer is empty, start using it from the beginning. */ + if (buffer->offset == buffer->end) { + buffer->offset = 0; + buffer->end = 0; + } +restart: + /* If there is enough space to store all data, store it now. */ + if (buffer->end + len < buffer->alloc) { + p = buffer->buf + buffer->end; + buffer->end += len; + return p; + } + /* + * If the buffer is quite empty, but all data is at the end, move the + * data to the beginning and retry. + */ + if (buffer->offset > buffer->alloc / 2) { + memmove(buffer->buf, buffer->buf + buffer->offset, + buffer->end - buffer->offset); + buffer->end -= buffer->offset; + buffer->offset = 0; + goto restart; + } + /* Increase the size of the buffer and retry. */ + + newlen = buffer->alloc + len + 32768; + if (newlen > 0xa00000) + fatal("buffer_append_space: alloc %u not supported", + newlen); + buffer->buf = xrealloc(buffer->buf, newlen); + buffer->alloc = newlen; + goto restart; + /* NOTREACHED */ +} + +/* Returns the number of bytes of data in the buffer. */ + +u_int +buffer_len(Buffer *buffer) +{ + return buffer->end - buffer->offset; +} + +/* Gets data from the beginning of the buffer. */ + +void +buffer_get(Buffer *buffer, void *buf, u_int len) +{ + if (len > buffer->end - buffer->offset) + fatal("buffer_get: trying to get more bytes %d than in buffer %d", + len, buffer->end - buffer->offset); + memcpy(buf, buffer->buf + buffer->offset, len); + buffer->offset += len; +} + +/* Consumes the given number of bytes from the beginning of the buffer. */ + +void +buffer_consume(Buffer *buffer, u_int bytes) +{ + if (bytes > buffer->end - buffer->offset) + fatal("buffer_consume: trying to get more bytes than in buffer"); + buffer->offset += bytes; +} + +/* Consumes the given number of bytes from the end of the buffer. */ + +void +buffer_consume_end(Buffer *buffer, u_int bytes) +{ + if (bytes > buffer->end - buffer->offset) + fatal("buffer_consume_end: trying to get more bytes than in buffer"); + buffer->end -= bytes; +} + +/* Returns a pointer to the first used byte in the buffer. */ + +void * +buffer_ptr(Buffer *buffer) +{ + return buffer->buf + buffer->offset; +} + +/* Dumps the contents of the buffer to stderr. */ + +void +buffer_dump(Buffer *buffer) +{ + int i; + u_char *ucp = buffer->buf; + + for (i = buffer->offset; i < buffer->end; i++) { + fprintf(stderr, "%02x", ucp[i]); + if ((i-buffer->offset)%16==15) + fprintf(stderr, "\r\n"); + else if ((i-buffer->offset)%2==1) + fprintf(stderr, " "); + } + fprintf(stderr, "\r\n"); +} diff --git a/usr/src/cmd/ssh/libssh/common/canohost.c b/usr/src/cmd/ssh/libssh/common/canohost.c new file mode 100644 index 0000000000..84a6d4619a --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/canohost.c @@ -0,0 +1,390 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Functions for returning the canonical host name of the remote site. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ +/* + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: canohost.c,v 1.34 2002/09/23 20:46:27 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "packet.h" +#include "xmalloc.h" +#include "log.h" +#include "canohost.h" + +static const char *inet_ntop_native(int af, const void *src, + char *dst, size_t size); + + +/* + * Return the canonical name of the host at the other end of the socket. The + * caller should free the returned string with xfree. + */ + +static char * +get_remote_hostname(int socket, int verify_reverse_mapping) +{ + struct sockaddr_storage from; + int i, res; + socklen_t fromlen; + struct addrinfo hints, *ai, *aitop; + char name[NI_MAXHOST], ntop[NI_MAXHOST], ntop2[NI_MAXHOST]; + + /* Get IP address of client. */ + fromlen = sizeof(from); + memset(&from, 0, sizeof(from)); + if (getpeername(socket, (struct sockaddr *) &from, &fromlen) < 0) { + debug("getpeername failed: %.100s", strerror(errno)); + fatal_cleanup(); + } + + if ((res = getnameinfo((struct sockaddr *)&from, fromlen, ntop, sizeof(ntop), + NULL, 0, NI_NUMERICHOST)) != 0) + fatal("get_remote_hostname: getnameinfo NI_NUMERICHOST failed: %d", res); + +#ifdef IPV4_IN_IPV6 + if (from.ss_family == AF_INET6) { + struct sockaddr_in6 *from6 = (struct sockaddr_in6 *)&from; + + (void) inet_ntop_native(from.ss_family, + from6->sin6_addr.s6_addr, + ntop, sizeof(ntop)); + } +#endif /* IPV4_IN_IPV6 */ + + debug3("Trying to reverse map address %.100s.", ntop); + /* Map the IP address to a host name. */ + if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), + NULL, 0, NI_NAMEREQD) != 0) { + /* Host name not found. Use ip address. */ +#if 0 + log("Could not reverse map address %.100s.", ntop); +#endif + return xstrdup(ntop); + } + + /* Got host name. */ + name[sizeof(name) - 1] = '\0'; + /* + * Convert it to all lowercase (which is expected by the rest + * of this software). + */ + for (i = 0; name[i]; i++) + if (isupper(name[i])) + name[i] = tolower(name[i]); + + if (!verify_reverse_mapping) + return xstrdup(name); + /* + * Map it back to an IP address and check that the given + * address actually is an address of this host. This is + * necessary because anyone with access to a name server can + * define arbitrary names for an IP address. Mapping from + * name to IP address can be trusted better (but can still be + * fooled if the intruder has access to the name server of + * the domain). + */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = from.ss_family; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { + log("reverse mapping checking getaddrinfo for %.700s " + "failed - POSSIBLE BREAKIN ATTEMPT!", name); + return xstrdup(ntop); + } + /* Look for the address from the list of addresses. */ + for (ai = aitop; ai; ai = ai->ai_next) { + if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, + sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && + (strcmp(ntop, ntop2) == 0)) + break; + } + freeaddrinfo(aitop); + /* If we reached the end of the list, the address was not there. */ + if (!ai) { + /* Address not found for the host name. */ + log("Address %.100s maps to %.600s, but this does not " + "map back to the address - POSSIBLE BREAKIN ATTEMPT!", + ntop, name); + return xstrdup(ntop); + } + return xstrdup(name); +} + +/* + * Return the canonical name of the host in the other side of the current + * connection. The host name is cached, so it is efficient to call this + * several times. + */ + +const char * +get_canonical_hostname(int verify_reverse_mapping) +{ + static char *canonical_host_name = NULL; + static int verify_reverse_mapping_done = 0; + + /* Check if we have previously retrieved name with same option. */ + if (canonical_host_name != NULL) { + if (verify_reverse_mapping_done != verify_reverse_mapping) + xfree(canonical_host_name); + else + return canonical_host_name; + } + + /* Get the real hostname if socket; otherwise return UNKNOWN. */ + if (packet_connection_is_on_socket()) + canonical_host_name = get_remote_hostname( + packet_get_connection_in(), verify_reverse_mapping); + else + canonical_host_name = xstrdup("UNKNOWN"); + + verify_reverse_mapping_done = verify_reverse_mapping; + return canonical_host_name; +} + +/* + * Returns the remote IP-address of socket as a string. The returned + * string must be freed. + */ +char * +get_socket_address(int socket, int remote, int flags) +{ + struct sockaddr_storage addr; + struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr; + socklen_t addrlen; + char ntop[NI_MAXHOST]; + const char *result; + char abuf[INET6_ADDRSTRLEN]; + + /* Get IP address of client. */ + addrlen = sizeof (addr); + memset(&addr, 0, sizeof (addr)); + + if (remote) { + if (getpeername(socket, (struct sockaddr *)&addr, &addrlen) + < 0) { + debug("get_socket_ipaddr: getpeername failed: %.100s", + strerror(errno)); + return (NULL); + } + } else { + if (getsockname(socket, (struct sockaddr *)&addr, &addrlen) + < 0) { + debug("get_socket_ipaddr: getsockname failed: %.100s", + strerror(errno)); + return (NULL); + } + } + + /* Get the address in ascii. */ + if (getnameinfo((struct sockaddr *)&addr, addrlen, ntop, sizeof (ntop), + NULL, 0, flags) != 0) { + error("get_socket_ipaddr: getnameinfo %d failed", flags); + return (NULL); + } + + if (addr.ss_family == AF_INET) { + return (xstrdup(ntop)); + } + + result = inet_ntop_native(addr.ss_family, + addr6->sin6_addr.s6_addr, abuf, sizeof (abuf)); + + return (xstrdup(result)); +} +#if 0 +static char * +get_socket_address(int socket, int remote, int flags) +{ + struct sockaddr_storage addr; + socklen_t addrlen; + char ntop[NI_MAXHOST]; + + /* Get IP address of client. */ + addrlen = sizeof(addr); + memset(&addr, 0, sizeof(addr)); + + if (remote) { + if (getpeername(socket, (struct sockaddr *)&addr, &addrlen) + < 0) + return NULL; + } else { + if (getsockname(socket, (struct sockaddr *)&addr, &addrlen) + < 0) + return NULL; + } + /* Get the address in ascii. */ + if (getnameinfo((struct sockaddr *)&addr, addrlen, ntop, sizeof(ntop), + NULL, 0, flags) != 0) { + error("get_socket_ipaddr: getnameinfo %d failed", flags); + return NULL; + } + return xstrdup(ntop); +} +#endif + +char * +get_peer_ipaddr(int socket) +{ + char *p; + + if ((p = get_socket_address(socket, 1, NI_NUMERICHOST)) != NULL) + return p; + return xstrdup("UNKNOWN"); +} + +char * +get_local_ipaddr(int socket) +{ + char *p; + + if ((p = get_socket_address(socket, 0, NI_NUMERICHOST)) != NULL) + return p; + return xstrdup("UNKNOWN"); +} + +char * +get_local_name(int socket) +{ + return get_socket_address(socket, 0, NI_NAMEREQD); +} + +/* + * Returns the IP-address of the remote host as a string. The returned + * string must not be freed. + */ + +const char * +get_remote_ipaddr(void) +{ + static char *canonical_host_ip = NULL; + + /* Check whether we have cached the ipaddr. */ + if (canonical_host_ip == NULL) { + if (packet_connection_is_on_socket()) { + canonical_host_ip = + get_peer_ipaddr(packet_get_connection_in()); + if (canonical_host_ip == NULL) + fatal_cleanup(); + } else { + /* If not on socket, return UNKNOWN. */ + canonical_host_ip = xstrdup("UNKNOWN"); + } + } + return canonical_host_ip; +} + +const char * +get_remote_name_or_ip(u_int utmp_len, int verify_reverse_mapping) +{ + static const char *remote = ""; + if (utmp_len > 0) + remote = get_canonical_hostname(verify_reverse_mapping); + if (utmp_len == 0 || strlen(remote) > utmp_len) + remote = get_remote_ipaddr(); + return remote; +} + +/* Returns the local/remote port for the socket. */ + +static int +get_sock_port(int sock, int local) +{ + struct sockaddr_storage from; + socklen_t fromlen; + char strport[NI_MAXSERV]; + + /* Get IP address of client. */ + fromlen = sizeof(from); + memset(&from, 0, sizeof(from)); + if (local) { + if (getsockname(sock, (struct sockaddr *)&from, &fromlen) < 0) { + error("getsockname failed: %.100s", strerror(errno)); + return 0; + } + } else { + if (getpeername(sock, (struct sockaddr *) & from, &fromlen) < 0) { + debug("getpeername failed: %.100s", strerror(errno)); + fatal_cleanup(); + } + } + /* Return port number. */ + if (getnameinfo((struct sockaddr *)&from, fromlen, NULL, 0, + strport, sizeof(strport), NI_NUMERICSERV) != 0) + fatal("get_sock_port: getnameinfo NI_NUMERICSERV failed"); + return atoi(strport); +} + +/* Returns remote/local port number for the current connection. */ + +static int +get_port(int local) +{ + /* + * If the connection is not a socket, return 65535. This is + * intentionally chosen to be an unprivileged port number. + */ + if (!packet_connection_is_on_socket()) + return 65535; + + /* Get socket and return the port number. */ + return get_sock_port(packet_get_connection_in(), local); +} + +int +get_peer_port(int sock) +{ + return get_sock_port(sock, 0); +} + +int +get_remote_port(void) +{ + return get_port(0); +} + +int +get_local_port(void) +{ + return get_port(1); +} + +/* + * Taken from inetd.c + * This is a wrapper function for inet_ntop(). In case the af is AF_INET6 + * and the address pointed by src is a IPv4-mapped IPv6 address, it + * returns printable IPv4 address, not IPv4-mapped IPv6 address. In other cases + * it behaves just like inet_ntop(). + */ +static const char * +inet_ntop_native(int af, const void *src, char *dst, size_t size) +{ + struct in_addr src4; + const char *result; + + if (af == AF_INET6) { + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)src)) { + IN6_V4MAPPED_TO_INADDR((struct in6_addr *)src, &src4); + result = inet_ntop(AF_INET, &src4, dst, size); + } else { + result = inet_ntop(AF_INET6, src, dst, size); + } + } else { + result = inet_ntop(af, src, dst, size); + } + + return (result); +} diff --git a/usr/src/cmd/ssh/libssh/common/channels.c b/usr/src/cmd/ssh/libssh/common/channels.c new file mode 100644 index 0000000000..61febdd9e4 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/channels.c @@ -0,0 +1,2785 @@ +/* + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * This file contains functions for generic socket connection forwarding. + * There is also code for initiating connection forwarding for X11 connections, + * arbitrary tcp/ip connections, and the authentication agent connection. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * SSH2 support added by Markus Friedl. + * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved. + * Copyright (c) 1999 Dug Song. All rights reserved. + * Copyright (c) 1999 Theo de Raadt. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: channels.c,v 1.183 2002/09/17 07:47:02 itojun Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ssh.h" +#include "ssh1.h" +#include "ssh2.h" +#include "packet.h" +#include "xmalloc.h" +#include "log.h" +#include "misc.h" +#include "channels.h" +#include "compat.h" +#include "canohost.h" +#include "key.h" +#include "authfd.h" +#include "pathnames.h" + + +/* -- channel core */ + +/* + * Pointer to an array containing all allocated channels. The array is + * dynamically extended as needed. + */ +static Channel **channels = NULL; + +/* + * Size of the channel array. All slots of the array must always be + * initialized (at least the type field); unused slots set to NULL + */ +static int channels_alloc = 0; + +/* + * Maximum file descriptor value used in any of the channels. This is + * updated in channel_new. + */ +static int channel_max_fd = 0; + + +/* -- tcp forwarding */ + +/* + * Data structure for storing which hosts are permitted for forward requests. + * The local sides of any remote forwards are stored in this array to prevent + * a corrupt remote server from accessing arbitrary TCP/IP ports on our local + * network (which might be behind a firewall). + */ +typedef struct { + char *host_to_connect; /* Connect to 'host'. */ + u_short port_to_connect; /* Connect to 'port'. */ + u_short listen_port; /* Remote side should listen port number. */ +} ForwardPermission; + +/* List of all permitted host/port pairs to connect. */ +static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION]; + +/* Number of permitted host/port pairs in the array. */ +static int num_permitted_opens = 0; +/* + * If this is true, all opens are permitted. This is the case on the server + * on which we have to trust the client anyway, and the user could do + * anything after logging in anyway. + */ +static int all_opens_permitted = 0; + + +/* -- X11 forwarding */ + +/* Maximum number of fake X11 displays to try. */ +#define MAX_DISPLAYS 1000 + +/* Saved X11 authentication protocol name. */ +static char *x11_saved_proto = NULL; + +/* Saved X11 authentication data. This is the real data. */ +static char *x11_saved_data = NULL; +static u_int x11_saved_data_len = 0; + +/* + * Fake X11 authentication data. This is what the server will be sending us; + * we should replace any occurrences of this by the real data. + */ +static char *x11_fake_data = NULL; +static u_int x11_fake_data_len; + + +/* -- agent forwarding */ + +#define NUM_SOCKS 10 + +/* AF_UNSPEC or AF_INET or AF_INET6 */ +static int IPv4or6 = AF_UNSPEC; + +/* helper */ +static void port_open_helper(Channel *c, char *rtype); + +/* -- channel core */ + +Channel * +channel_lookup(int id) +{ + Channel *c; + + if (id < 0 || id >= channels_alloc) { + log("channel_lookup: %d: bad id", id); + return NULL; + } + c = channels[id]; + if (c == NULL) { + log("channel_lookup: %d: bad id: channel free", id); + return NULL; + } + return c; +} + +/* + * Register filedescriptors for a channel, used when allocating a channel or + * when the channel consumer/producer is ready, e.g. shell exec'd + */ + +static void +channel_register_fds(Channel *c, int rfd, int wfd, int efd, + int extusage, int nonblock) +{ + /* Update the maximum file descriptor value. */ + channel_max_fd = MAX(channel_max_fd, rfd); + channel_max_fd = MAX(channel_max_fd, wfd); + channel_max_fd = MAX(channel_max_fd, efd); + + /* XXX set close-on-exec -markus */ + + c->rfd = rfd; + c->wfd = wfd; + c->sock = (rfd == wfd) ? rfd : -1; + c->efd = efd; + c->extended_usage = extusage; + + /* XXX ugly hack: nonblock is only set by the server */ + if (nonblock && isatty(c->rfd)) { + debug("channel %d: rfd %d isatty", c->self, c->rfd); + c->isatty = 1; + if (!isatty(c->wfd)) { + error("channel %d: wfd %d is not a tty?", + c->self, c->wfd); + } + } else { + c->isatty = 0; + } + c->wfd_isatty = isatty(c->wfd); + + /* enable nonblocking mode */ + if (nonblock) { + if (rfd != -1) + set_nonblock(rfd); + if (wfd != -1) + set_nonblock(wfd); + if (efd != -1) + set_nonblock(efd); + } +} + +/* + * Allocate a new channel object and set its type and socket. This will cause + * remote_name to be freed. + */ + +Channel * +channel_new(char *ctype, int type, int rfd, int wfd, int efd, + u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock) +{ + int i, found; + Channel *c; + + /* Do initial allocation if this is the first call. */ + if (channels_alloc == 0) { + channels_alloc = 10; + channels = xmalloc(channels_alloc * sizeof(Channel *)); + for (i = 0; i < channels_alloc; i++) + channels[i] = NULL; + fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL); + } + /* Try to find a free slot where to put the new channel. */ + for (found = -1, i = 0; i < channels_alloc; i++) + if (channels[i] == NULL) { + /* Found a free slot. */ + found = i; + break; + } + if (found == -1) { + /* There are no free slots. Take last+1 slot and expand the array. */ + found = channels_alloc; + if (channels_alloc > 10000) + fatal("channel_new: internal error: channels_alloc %d " + "too big.", channels_alloc); + channels = xrealloc(channels, + (channels_alloc + 10) * sizeof(Channel *)); + channels_alloc += 10; + debug2("channel: expanding %d", channels_alloc); + for (i = found; i < channels_alloc; i++) + channels[i] = NULL; + } + /* Initialize and return new channel. */ + c = channels[found] = xmalloc(sizeof(Channel)); + memset(c, 0, sizeof(Channel)); + buffer_init(&c->input); + buffer_init(&c->output); + buffer_init(&c->extended); + c->ostate = CHAN_OUTPUT_OPEN; + c->istate = CHAN_INPUT_OPEN; + c->flags = 0; + channel_register_fds(c, rfd, wfd, efd, extusage, nonblock); + c->self = found; + c->type = type; + c->ctype = ctype; + c->local_window = window; + c->local_window_max = window; + c->local_consumed = 0; + c->local_maxpacket = maxpack; + c->remote_id = -1; + c->remote_name = remote_name; + c->remote_window = 0; + c->remote_maxpacket = 0; + c->force_drain = 0; + c->single_connection = 0; + c->detach_user = NULL; + c->confirm = NULL; + c->input_filter = NULL; + debug("channel %d: new [%s]", found, remote_name); + return c; +} + +static int +channel_find_maxfd(void) +{ + int i, max = 0; + Channel *c; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c != NULL) { + max = MAX(max, c->rfd); + max = MAX(max, c->wfd); + max = MAX(max, c->efd); + } + } + return max; +} + +int +channel_close_fd(int *fdp) +{ + int ret = 0, fd = *fdp; + + if (fd != -1) { + ret = close(fd); + *fdp = -1; + if (fd == channel_max_fd) + channel_max_fd = channel_find_maxfd(); + } + return ret; +} + +/* Close all channel fd/socket. */ + +static void +channel_close_fds(Channel *c) +{ + debug3("channel_close_fds: channel %d: r %d w %d e %d", + c->self, c->rfd, c->wfd, c->efd); + + channel_close_fd(&c->sock); + channel_close_fd(&c->rfd); + channel_close_fd(&c->wfd); + channel_close_fd(&c->efd); +} + +/* Free the channel and close its fd/socket. */ + +void +channel_free(Channel *c) +{ + char *s; + int i, n; + + for (n = 0, i = 0; i < channels_alloc; i++) + if (channels[i]) + n++; + debug("channel_free: channel %d: %s, nchannels %d", c->self, + c->remote_name ? c->remote_name : "???", n); + + s = channel_open_message(); + debug3("channel_free: status: %s", s); + xfree(s); + + if (c->sock != -1) + shutdown(c->sock, SHUT_RDWR); + channel_close_fds(c); + buffer_free(&c->input); + buffer_free(&c->output); + buffer_free(&c->extended); + if (c->remote_name) { + xfree(c->remote_name); + c->remote_name = NULL; + } + channels[c->self] = NULL; + xfree(c); +} + +void +channel_free_all(void) +{ + int i; + + for (i = 0; i < channels_alloc; i++) + if (channels[i] != NULL) + channel_free(channels[i]); +} + +/* + * Closes the sockets/fds of all channels. This is used to close extra file + * descriptors after a fork. + */ + +void +channel_close_all(void) +{ + int i; + + for (i = 0; i < channels_alloc; i++) + if (channels[i] != NULL) + channel_close_fds(channels[i]); +} + +/* + * Stop listening to channels. + */ + +void +channel_stop_listening(void) +{ + int i; + Channel *c; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c != NULL) { + switch (c->type) { + case SSH_CHANNEL_AUTH_SOCKET: + case SSH_CHANNEL_PORT_LISTENER: + case SSH_CHANNEL_RPORT_LISTENER: + case SSH_CHANNEL_X11_LISTENER: + channel_close_fd(&c->sock); + channel_free(c); + break; + } + } + } +} + +/* + * Returns true if no channel has too much buffered data, and false if one or + * more channel is overfull. + */ + +int +channel_not_very_much_buffered_data(void) +{ + u_int i; + Channel *c; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c != NULL && c->type == SSH_CHANNEL_OPEN) { +#if 0 + if (!compat20 && + buffer_len(&c->input) > packet_get_maxsize()) { + debug("channel %d: big input buffer %d", + c->self, buffer_len(&c->input)); + return 0; + } +#endif + if (buffer_len(&c->output) > packet_get_maxsize()) { + debug("channel %d: big output buffer %d > %d", + c->self, buffer_len(&c->output), + packet_get_maxsize()); + return 0; + } + } + } + return 1; +} + +/* Returns true if any channel is still open. */ + +int +channel_still_open(void) +{ + int i; + Channel *c; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c == NULL) + continue; + switch (c->type) { + case SSH_CHANNEL_X11_LISTENER: + case SSH_CHANNEL_PORT_LISTENER: + case SSH_CHANNEL_RPORT_LISTENER: + case SSH_CHANNEL_CLOSED: + case SSH_CHANNEL_AUTH_SOCKET: + case SSH_CHANNEL_DYNAMIC: + case SSH_CHANNEL_CONNECTING: + case SSH_CHANNEL_ZOMBIE: + continue; + case SSH_CHANNEL_LARVAL: + if (!compat20) + fatal("cannot happen: SSH_CHANNEL_LARVAL"); + continue; + case SSH_CHANNEL_OPENING: + case SSH_CHANNEL_OPEN: + case SSH_CHANNEL_X11_OPEN: + return 1; + case SSH_CHANNEL_INPUT_DRAINING: + case SSH_CHANNEL_OUTPUT_DRAINING: + if (!compat13) + fatal("cannot happen: OUT_DRAIN"); + return 1; + default: + fatal("channel_still_open: bad channel type %d", c->type); + /* NOTREACHED */ + } + } + return 0; +} + +/* Returns the id of an open channel suitable for keepaliving */ + +int +channel_find_open(void) +{ + int i; + Channel *c; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c == NULL) + continue; + switch (c->type) { + case SSH_CHANNEL_CLOSED: + case SSH_CHANNEL_DYNAMIC: + case SSH_CHANNEL_X11_LISTENER: + case SSH_CHANNEL_PORT_LISTENER: + case SSH_CHANNEL_RPORT_LISTENER: + case SSH_CHANNEL_OPENING: + case SSH_CHANNEL_CONNECTING: + case SSH_CHANNEL_ZOMBIE: + continue; + case SSH_CHANNEL_LARVAL: + case SSH_CHANNEL_AUTH_SOCKET: + case SSH_CHANNEL_OPEN: + case SSH_CHANNEL_X11_OPEN: + return i; + case SSH_CHANNEL_INPUT_DRAINING: + case SSH_CHANNEL_OUTPUT_DRAINING: + if (!compat13) + fatal("cannot happen: OUT_DRAIN"); + return i; + default: + fatal("channel_find_open: bad channel type %d", c->type); + /* NOTREACHED */ + } + } + return -1; +} + + +/* + * Returns a message describing the currently open forwarded connections, + * suitable for sending to the client. The message contains crlf pairs for + * newlines. + */ + +char * +channel_open_message(void) +{ + Buffer buffer; + Channel *c; + char buf[1024], *cp; + int i; + + buffer_init(&buffer); + snprintf(buf, sizeof buf, "The following connections are open:\r\n"); + buffer_append(&buffer, buf, strlen(buf)); + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c == NULL) + continue; + switch (c->type) { + case SSH_CHANNEL_X11_LISTENER: + case SSH_CHANNEL_PORT_LISTENER: + case SSH_CHANNEL_RPORT_LISTENER: + case SSH_CHANNEL_CLOSED: + case SSH_CHANNEL_AUTH_SOCKET: + case SSH_CHANNEL_ZOMBIE: + continue; + case SSH_CHANNEL_LARVAL: + case SSH_CHANNEL_OPENING: + case SSH_CHANNEL_CONNECTING: + case SSH_CHANNEL_DYNAMIC: + case SSH_CHANNEL_OPEN: + case SSH_CHANNEL_X11_OPEN: + case SSH_CHANNEL_INPUT_DRAINING: + case SSH_CHANNEL_OUTPUT_DRAINING: + snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n", + c->self, c->remote_name, + c->type, c->remote_id, + c->istate, buffer_len(&c->input), + c->ostate, buffer_len(&c->output), + c->rfd, c->wfd); + buffer_append(&buffer, buf, strlen(buf)); + continue; + default: + fatal("channel_open_message: bad channel type %d", c->type); + /* NOTREACHED */ + } + } + buffer_append(&buffer, "\0", 1); + cp = xstrdup(buffer_ptr(&buffer)); + buffer_free(&buffer); + return cp; +} + +void +channel_send_open(int id) +{ + Channel *c = channel_lookup(id); + + if (c == NULL) { + log("channel_send_open: %d: bad id", id); + return; + } + debug("send channel open %d", id); + packet_start(SSH2_MSG_CHANNEL_OPEN); + packet_put_cstring(c->ctype); + packet_put_int(c->self); + packet_put_int(c->local_window); + packet_put_int(c->local_maxpacket); + packet_send(); +} + +void +channel_request_start(int local_id, char *service, int wantconfirm) +{ + Channel *c = channel_lookup(local_id); + + if (c == NULL) { + log("channel_request_start: %d: unknown channel id", local_id); + return; + } + debug("channel request %d: %s", local_id, service) ; + packet_start(SSH2_MSG_CHANNEL_REQUEST); + packet_put_int(c->remote_id); + packet_put_cstring(service); + packet_put_char(wantconfirm); +} +void +channel_register_confirm(int id, channel_callback_fn *fn) +{ + Channel *c = channel_lookup(id); + + if (c == NULL) { + log("channel_register_comfirm: %d: bad id", id); + return; + } + c->confirm = fn; +} +void +channel_register_cleanup(int id, channel_callback_fn *fn) +{ + Channel *c = channel_lookup(id); + + if (c == NULL) { + log("channel_register_cleanup: %d: bad id", id); + return; + } + c->detach_user = fn; +} +void +channel_cancel_cleanup(int id) +{ + Channel *c = channel_lookup(id); + + if (c == NULL) { + log("channel_cancel_cleanup: %d: bad id", id); + return; + } + c->detach_user = NULL; +} +void +channel_register_filter(int id, channel_filter_fn *fn) +{ + Channel *c = channel_lookup(id); + + if (c == NULL) { + log("channel_register_filter: %d: bad id", id); + return; + } + c->input_filter = fn; +} + +void +channel_set_fds(int id, int rfd, int wfd, int efd, + int extusage, int nonblock, u_int window_max) +{ + Channel *c = channel_lookup(id); + + if (c == NULL || c->type != SSH_CHANNEL_LARVAL) + fatal("channel_activate for non-larval channel %d.", id); + channel_register_fds(c, rfd, wfd, efd, extusage, nonblock); + c->type = SSH_CHANNEL_OPEN; + c->local_window = c->local_window_max = window_max; + packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST); + packet_put_int(c->remote_id); + packet_put_int(c->local_window); + packet_send(); +} + +void +channel_set_wait_for_exit(int id, int wait_for_exit) +{ + Channel *c = channel_lookup(id); + + if (c == NULL || c->type != SSH_CHANNEL_OPEN) + fatal("channel_set_wait_for_exit for non-open channel %d.", id); + + debug3("channel_set_wait_for_exit %d, %d (type: %d)", id, wait_for_exit, c->type); + c->wait_for_exit = wait_for_exit; +} + +/* + * 'channel_pre*' are called just before select() to add any bits relevant to + * channels in the select bitmasks. + */ +/* + * 'channel_post*': perform any appropriate operations for channels which + * have events pending. + */ +typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset); +chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE]; +chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE]; + +static void +channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset) +{ + FD_SET(c->sock, readset); +} + +static void +channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset) +{ + debug3("channel %d: waiting for connection", c->self); + FD_SET(c->sock, writeset); +} + +static void +channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset) +{ + if (buffer_len(&c->input) < packet_get_maxsize()) + FD_SET(c->sock, readset); + if (buffer_len(&c->output) > 0) + FD_SET(c->sock, writeset); +} + +static void +channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset) +{ + u_int limit = compat20 ? c->remote_window : packet_get_maxsize(); + + if (c->istate == CHAN_INPUT_OPEN && + limit > 0 && + buffer_len(&c->input) < limit) + FD_SET(c->rfd, readset); + if (c->ostate == CHAN_OUTPUT_OPEN || + c->ostate == CHAN_OUTPUT_WAIT_DRAIN) { + if (buffer_len(&c->output) > 0) { + FD_SET(c->wfd, writeset); + } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) { + if (CHANNEL_EFD_OUTPUT_ACTIVE(c)) + debug2("channel %d: obuf_empty delayed efd %d/(%d)", + c->self, c->efd, buffer_len(&c->extended)); + else + chan_obuf_empty(c); + } + } + /** XXX check close conditions, too */ + if (compat20 && c->efd != -1) { + if (c->extended_usage == CHAN_EXTENDED_WRITE && + buffer_len(&c->extended) > 0) + FD_SET(c->efd, writeset); + else if (!(c->flags & CHAN_EOF_SENT) && + c->extended_usage == CHAN_EXTENDED_READ && + buffer_len(&c->extended) < c->remote_window) + FD_SET(c->efd, readset); + } +} + +static void +channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset) +{ + if (buffer_len(&c->input) == 0) { + packet_start(SSH_MSG_CHANNEL_CLOSE); + packet_put_int(c->remote_id); + packet_send(); + c->type = SSH_CHANNEL_CLOSED; + debug("channel %d: closing after input drain.", c->self); + } +} + +static void +channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset) +{ + if (buffer_len(&c->output) == 0) + chan_mark_dead(c); + else + FD_SET(c->sock, writeset); +} + +/* + * This is a special state for X11 authentication spoofing. An opened X11 + * connection (when authentication spoofing is being done) remains in this + * state until the first packet has been completely read. The authentication + * data in that packet is then substituted by the real data if it matches the + * fake data, and the channel is put into normal mode. + * XXX All this happens at the client side. + * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok + */ +static int +x11_open_helper(Buffer *b) +{ + u_char *ucp; + u_int proto_len, data_len; + + /* Check if the fixed size part of the packet is in buffer. */ + if (buffer_len(b) < 12) + return 0; + + /* Parse the lengths of variable-length fields. */ + ucp = buffer_ptr(b); + if (ucp[0] == 0x42) { /* Byte order MSB first. */ + proto_len = 256 * ucp[6] + ucp[7]; + data_len = 256 * ucp[8] + ucp[9]; + } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */ + proto_len = ucp[6] + 256 * ucp[7]; + data_len = ucp[8] + 256 * ucp[9]; + } else { + debug("Initial X11 packet contains bad byte order byte: 0x%x", + ucp[0]); + return -1; + } + + /* Check if the whole packet is in buffer. */ + if (buffer_len(b) < + 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3)) + return 0; + + /* Check if authentication protocol matches. */ + if (proto_len != strlen(x11_saved_proto) || + memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) { + debug("X11 connection uses different authentication protocol."); + return -1; + } + /* Check if authentication data matches our fake data. */ + if (data_len != x11_fake_data_len || + memcmp(ucp + 12 + ((proto_len + 3) & ~3), + x11_fake_data, x11_fake_data_len) != 0) { + debug("X11 auth data does not match fake data."); + return -1; + } + /* Check fake data length */ + if (x11_fake_data_len != x11_saved_data_len) { + error("X11 fake_data_len %d != saved_data_len %d", + x11_fake_data_len, x11_saved_data_len); + return -1; + } + /* + * Received authentication protocol and data match + * our fake data. Substitute the fake data with real + * data. + */ + memcpy(ucp + 12 + ((proto_len + 3) & ~3), + x11_saved_data, x11_saved_data_len); + return 1; +} + +static void +channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset) +{ + int ret = x11_open_helper(&c->output); + + if (ret == 1) { + /* Start normal processing for the channel. */ + c->type = SSH_CHANNEL_OPEN; + channel_pre_open_13(c, readset, writeset); + } else if (ret == -1) { + /* + * We have received an X11 connection that has bad + * authentication information. + */ + log("X11 connection rejected because of wrong authentication."); + buffer_clear(&c->input); + buffer_clear(&c->output); + channel_close_fd(&c->sock); + c->sock = -1; + c->type = SSH_CHANNEL_CLOSED; + packet_start(SSH_MSG_CHANNEL_CLOSE); + packet_put_int(c->remote_id); + packet_send(); + } +} + +static void +channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset) +{ + int ret = x11_open_helper(&c->output); + + /* c->force_drain = 1; */ + + if (ret == 1) { + c->type = SSH_CHANNEL_OPEN; + channel_pre_open(c, readset, writeset); + } else if (ret == -1) { + log("X11 connection rejected because of wrong authentication."); + debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate); + chan_read_failed(c); + buffer_clear(&c->input); + chan_ibuf_empty(c); + buffer_clear(&c->output); + /* for proto v1, the peer will send an IEOF */ + if (compat20) + chan_write_failed(c); + else + c->type = SSH_CHANNEL_OPEN; + debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate); + } +} + +/* try to decode a socks4 header */ +static int +channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset) +{ + char *p, *host; + int len, have, i, found; + char username[256]; + struct { + u_int8_t version; + u_int8_t command; + u_int16_t dest_port; + struct in_addr dest_addr; + } s4_req, s4_rsp; + + debug2("channel %d: decode socks4", c->self); + + have = buffer_len(&c->input); + len = sizeof(s4_req); + if (have < len) + return 0; + p = buffer_ptr(&c->input); + for (found = 0, i = len; i < have; i++) { + if (p[i] == '\0') { + found = 1; + break; + } + if (i > 1024) { + /* the peer is probably sending garbage */ + debug("channel %d: decode socks4: too long", + c->self); + return -1; + } + } + if (!found) + return 0; + buffer_get(&c->input, (char *)&s4_req.version, 1); + buffer_get(&c->input, (char *)&s4_req.command, 1); + buffer_get(&c->input, (char *)&s4_req.dest_port, 2); + buffer_get(&c->input, (char *)&s4_req.dest_addr, 4); + have = buffer_len(&c->input); + p = buffer_ptr(&c->input); + len = strlen(p); + debug2("channel %d: decode socks4: user %s/%d", c->self, p, len); + if (len > have) + fatal("channel %d: decode socks4: len %d > have %d", + c->self, len, have); + strlcpy(username, p, sizeof(username)); + buffer_consume(&c->input, len); + buffer_consume(&c->input, 1); /* trailing '\0' */ + + host = inet_ntoa(s4_req.dest_addr); + strlcpy(c->path, host, sizeof(c->path)); + c->host_port = ntohs(s4_req.dest_port); + + debug("channel %d: dynamic request: socks4 host %s port %u command %u", + c->self, host, c->host_port, s4_req.command); + + if (s4_req.command != 1) { + debug("channel %d: cannot handle: socks4 cn %d", + c->self, s4_req.command); + return -1; + } + s4_rsp.version = 0; /* vn: 0 for reply */ + s4_rsp.command = 90; /* cd: req granted */ + s4_rsp.dest_port = 0; /* ignored */ + s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */ + buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp)); + return 1; +} + +/* dynamic port forwarding */ +static void +channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset) +{ + u_char *p; + int have, ret; + + have = buffer_len(&c->input); + c->delayed = 0; + debug2("channel %d: pre_dynamic: have %d", c->self, have); + /* buffer_dump(&c->input); */ + /* check if the fixed size part of the packet is in buffer. */ + if (have < 4) { + /* need more */ + FD_SET(c->sock, readset); + return; + } + /* try to guess the protocol */ + p = buffer_ptr(&c->input); + switch (p[0]) { + case 0x04: + ret = channel_decode_socks4(c, readset, writeset); + break; + default: + ret = -1; + break; + } + if (ret < 0) { + chan_mark_dead(c); + } else if (ret == 0) { + debug2("channel %d: pre_dynamic: need more", c->self); + /* need more */ + FD_SET(c->sock, readset); + } else { + /* switch to the next state */ + c->type = SSH_CHANNEL_OPENING; + port_open_helper(c, "direct-tcpip"); + } +} + +/* This is our fake X11 server socket. */ +static void +channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset) +{ + Channel *nc; + struct sockaddr addr; + int newsock; + socklen_t addrlen; + char buf[16384], *remote_ipaddr; + int remote_port; + + if (FD_ISSET(c->sock, readset)) { + debug("X11 connection requested."); + addrlen = sizeof(addr); + newsock = accept(c->sock, &addr, &addrlen); + if (c->single_connection) { + debug("single_connection: closing X11 listener."); + channel_close_fd(&c->sock); + chan_mark_dead(c); + } + if (newsock < 0) { + error("accept: %.100s", strerror(errno)); + return; + } + set_nodelay(newsock); + remote_ipaddr = get_peer_ipaddr(newsock); + remote_port = get_peer_port(newsock); + snprintf(buf, sizeof buf, "X11 connection from %.200s port %d", + remote_ipaddr, remote_port); + + nc = channel_new("accepted x11 socket", + SSH_CHANNEL_OPENING, newsock, newsock, -1, + c->local_window_max, c->local_maxpacket, + 0, xstrdup(buf), 1); + if (compat20) { + packet_start(SSH2_MSG_CHANNEL_OPEN); + packet_put_cstring("x11"); + packet_put_int(nc->self); + packet_put_int(nc->local_window_max); + packet_put_int(nc->local_maxpacket); + /* originator ipaddr and port */ + packet_put_cstring(remote_ipaddr); + if (datafellows & SSH_BUG_X11FWD) { + debug("ssh2 x11 bug compat mode"); + } else { + packet_put_int(remote_port); + } + packet_send(); + } else { + packet_start(SSH_SMSG_X11_OPEN); + packet_put_int(nc->self); + if (packet_get_protocol_flags() & + SSH_PROTOFLAG_HOST_IN_FWD_OPEN) + packet_put_cstring(buf); + packet_send(); + } + xfree(remote_ipaddr); + } +} + +static void +port_open_helper(Channel *c, char *rtype) +{ + int direct; + char buf[1024]; + char *remote_ipaddr = get_peer_ipaddr(c->sock); + u_short remote_port = get_peer_port(c->sock); + + direct = (strcmp(rtype, "direct-tcpip") == 0); + + snprintf(buf, sizeof buf, + "%s: listening port %d for %.100s port %d, " + "connect from %.200s port %d", + rtype, c->listening_port, c->path, c->host_port, + remote_ipaddr, remote_port); + + xfree(c->remote_name); + c->remote_name = xstrdup(buf); + + if (compat20) { + packet_start(SSH2_MSG_CHANNEL_OPEN); + packet_put_cstring(rtype); + packet_put_int(c->self); + packet_put_int(c->local_window_max); + packet_put_int(c->local_maxpacket); + if (direct) { + /* target host, port */ + packet_put_cstring(c->path); + packet_put_int(c->host_port); + } else { + /* listen address, port */ + packet_put_cstring(c->path); + packet_put_int(c->listening_port); + } + /* originator host and port */ + packet_put_cstring(remote_ipaddr); + packet_put_int(remote_port); + packet_send(); + } else { + packet_start(SSH_MSG_PORT_OPEN); + packet_put_int(c->self); + packet_put_cstring(c->path); + packet_put_int(c->host_port); + if (packet_get_protocol_flags() & + SSH_PROTOFLAG_HOST_IN_FWD_OPEN) + packet_put_cstring(c->remote_name); + packet_send(); + } + xfree(remote_ipaddr); +} + +/* + * This socket is listening for connections to a forwarded TCP/IP port. + */ +static void +channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset) +{ + Channel *nc; + struct sockaddr addr; + int newsock, nextstate; + socklen_t addrlen; + char *rtype; + + if (FD_ISSET(c->sock, readset)) { + debug("Connection to port %d forwarding " + "to %.100s port %d requested.", + c->listening_port, c->path, c->host_port); + + if (c->type == SSH_CHANNEL_RPORT_LISTENER) { + nextstate = SSH_CHANNEL_OPENING; + rtype = "forwarded-tcpip"; + } else { + if (c->host_port == 0) { + nextstate = SSH_CHANNEL_DYNAMIC; + rtype = "dynamic-tcpip"; + } else { + nextstate = SSH_CHANNEL_OPENING; + rtype = "direct-tcpip"; + } + } + + addrlen = sizeof(addr); + newsock = accept(c->sock, &addr, &addrlen); + if (newsock < 0) { + error("accept: %.100s", strerror(errno)); + return; + } + set_nodelay(newsock); + nc = channel_new(rtype, + nextstate, newsock, newsock, -1, + c->local_window_max, c->local_maxpacket, + 0, xstrdup(rtype), 1); + nc->listening_port = c->listening_port; + nc->host_port = c->host_port; + strlcpy(nc->path, c->path, sizeof(nc->path)); + + if (nextstate == SSH_CHANNEL_DYNAMIC) { + /* + * do not call the channel_post handler until + * this flag has been reset by a pre-handler. + * otherwise the FD_ISSET calls might overflow + */ + nc->delayed = 1; + } else { + port_open_helper(nc, rtype); + } + } +} + +/* + * This is the authentication agent socket listening for connections from + * clients. + */ +static void +channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset) +{ + Channel *nc; + char *name; + int newsock; + struct sockaddr addr; + socklen_t addrlen; + + if (FD_ISSET(c->sock, readset)) { + addrlen = sizeof(addr); + newsock = accept(c->sock, &addr, &addrlen); + if (newsock < 0) { + error("accept from auth socket: %.100s", strerror(errno)); + return; + } + name = xstrdup("accepted auth socket"); + nc = channel_new("accepted auth socket", + SSH_CHANNEL_OPENING, newsock, newsock, -1, + c->local_window_max, c->local_maxpacket, + 0, name, 1); + if (compat20) { + packet_start(SSH2_MSG_CHANNEL_OPEN); + packet_put_cstring("auth-agent@openssh.com"); + packet_put_int(nc->self); + packet_put_int(c->local_window_max); + packet_put_int(c->local_maxpacket); + } else { + packet_start(SSH_SMSG_AGENT_OPEN); + packet_put_int(nc->self); + } + packet_send(); + } +} + +static void +channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset) +{ + int err = 0; + socklen_t sz = sizeof(err); + + if (FD_ISSET(c->sock, writeset)) { + if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) { + err = errno; + error("getsockopt SO_ERROR failed"); + } + if (err == 0) { + debug("channel %d: connected", c->self); + c->type = SSH_CHANNEL_OPEN; + if (compat20) { + packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION); + packet_put_int(c->remote_id); + packet_put_int(c->self); + packet_put_int(c->local_window); + packet_put_int(c->local_maxpacket); + } else { + packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION); + packet_put_int(c->remote_id); + packet_put_int(c->self); + } + } else { + debug("channel %d: not connected: %s", + c->self, strerror(err)); + if (compat20) { + packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(c->remote_id); + packet_put_int(SSH2_OPEN_CONNECT_FAILED); + if (!(datafellows & SSH_BUG_OPENFAILURE)) { + packet_put_cstring(strerror(err)); + packet_put_cstring(""); + } + } else { + packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(c->remote_id); + } + chan_mark_dead(c); + } + packet_send(); + } +} + +static int +channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset) +{ + char buf[16*1024]; + int len; + + if (c->rfd != -1 && + FD_ISSET(c->rfd, readset)) { + len = read(c->rfd, buf, sizeof(buf)); + if (len < 0 && (errno == EINTR || errno == EAGAIN)) + return 1; + if (len <= 0) { + debug("channel %d: read<=0 rfd %d len %d", + c->self, c->rfd, len); + if (c->type != SSH_CHANNEL_OPEN) { + debug("channel %d: not open", c->self); + chan_mark_dead(c); + return -1; + } else if (compat13) { + buffer_clear(&c->output); + c->type = SSH_CHANNEL_INPUT_DRAINING; + debug("channel %d: input draining.", c->self); + } else { + chan_read_failed(c); + } + return -1; + } + if (c->input_filter != NULL) { + if (c->input_filter(c, buf, len) == -1) { + debug("channel %d: filter stops", c->self); + chan_read_failed(c); + } + } else { + buffer_append(&c->input, buf, len); + } + } + return 1; +} +static int +channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset) +{ + struct termios tio; + u_char *data; + u_int dlen; + int len; + + /* Send buffered output data to the socket. */ + if (c->wfd != -1 && + FD_ISSET(c->wfd, writeset) && + buffer_len(&c->output) > 0) { + data = buffer_ptr(&c->output); + dlen = buffer_len(&c->output); +#ifdef _AIX + /* XXX: Later AIX versions can't push as much data to tty */ + if (compat20 && c->wfd_isatty && dlen > 8*1024) + dlen = 8*1024; +#endif + len = write(c->wfd, data, dlen); + if (len < 0 && (errno == EINTR || errno == EAGAIN)) + return 1; + if (len <= 0) { + if (c->type != SSH_CHANNEL_OPEN) { + debug("channel %d: not open", c->self); + chan_mark_dead(c); + return -1; + } else if (compat13) { + buffer_clear(&c->output); + debug("channel %d: input draining.", c->self); + c->type = SSH_CHANNEL_INPUT_DRAINING; + } else { + chan_write_failed(c); + } + return -1; + } + if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') { + if (tcgetattr(c->wfd, &tio) == 0 && + !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) { + /* + * Simulate echo to reduce the impact of + * traffic analysis. We need to match the + * size of a SSH2_MSG_CHANNEL_DATA message + * (4 byte channel id + data) + */ + packet_send_ignore(4 + len); + packet_send(); + } + } + buffer_consume(&c->output, len); + if (compat20 && len > 0) { + c->local_consumed += len; + } + } + return 1; +} +static int +channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset) +{ + char buf[16*1024]; + int len; + +/** XXX handle drain efd, too */ + if (c->efd != -1) { + if (c->extended_usage == CHAN_EXTENDED_WRITE && + FD_ISSET(c->efd, writeset) && + buffer_len(&c->extended) > 0) { + len = write(c->efd, buffer_ptr(&c->extended), + buffer_len(&c->extended)); + debug2("channel %d: written %d to efd %d", + c->self, len, c->efd); + if (len < 0 && (errno == EINTR || errno == EAGAIN)) + return 1; + if (len <= 0) { + debug2("channel %d: closing write-efd %d", + c->self, c->efd); + channel_close_fd(&c->efd); + } else { + buffer_consume(&c->extended, len); + c->local_consumed += len; + } + } else if (c->extended_usage == CHAN_EXTENDED_READ && + FD_ISSET(c->efd, readset)) { + len = read(c->efd, buf, sizeof(buf)); + debug2("channel %d: read %d from efd %d", + c->self, len, c->efd); + if (len < 0 && (errno == EINTR || errno == EAGAIN)) + return 1; + if (len <= 0) { + debug2("channel %d: closing read-efd %d", + c->self, c->efd); + channel_close_fd(&c->efd); + } else { + buffer_append(&c->extended, buf, len); + } + } + } + return 1; +} +static int +channel_check_window(Channel *c) +{ + if (c->type == SSH_CHANNEL_OPEN && + !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) && + c->local_window < c->local_window_max/2 && + c->local_consumed > 0) { + packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST); + packet_put_int(c->remote_id); + packet_put_int(c->local_consumed); + packet_send(); + debug2("channel %d: window %d sent adjust %d", + c->self, c->local_window, + c->local_consumed); + c->local_window += c->local_consumed; + c->local_consumed = 0; + } + return 1; +} + +static void +channel_post_open(Channel *c, fd_set * readset, fd_set * writeset) +{ + if (c->delayed) + return; + channel_handle_rfd(c, readset, writeset); + channel_handle_wfd(c, readset, writeset); + if (!compat20) + return; + channel_handle_efd(c, readset, writeset); + channel_check_window(c); +} + +static void +channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset) +{ + int len; + + /* Send buffered output data to the socket. */ + if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) { + len = write(c->sock, buffer_ptr(&c->output), + buffer_len(&c->output)); + if (len <= 0) + buffer_clear(&c->output); + else + buffer_consume(&c->output, len); + } +} + +static void +channel_handler_init_20(void) +{ + channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open; + channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open; + channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting; + channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic; + + channel_post[SSH_CHANNEL_OPEN] = &channel_post_open; + channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener; + channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener; + channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener; + channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener; + channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting; + channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open; +} + +static void +channel_handler_init_13(void) +{ + channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13; + channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13; + channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining; + channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining; + channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting; + channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic; + + channel_post[SSH_CHANNEL_OPEN] = &channel_post_open; + channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener; + channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener; + channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener; + channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13; + channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting; + channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open; +} + +static void +channel_handler_init_15(void) +{ + channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open; + channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open; + channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener; + channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting; + channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic; + + channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener; + channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener; + channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener; + channel_post[SSH_CHANNEL_OPEN] = &channel_post_open; + channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting; + channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open; +} + +static void +channel_handler_init(void) +{ + int i; + + for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) { + channel_pre[i] = NULL; + channel_post[i] = NULL; + } + if (compat20) + channel_handler_init_20(); + else if (compat13) + channel_handler_init_13(); + else + channel_handler_init_15(); +} + +/* gc dead channels */ +static void +channel_garbage_collect(Channel *c) +{ + if (c == NULL) + return; + if (c->detach_user != NULL) { + if (!chan_is_dead(c, 0)) + return; + debug("channel %d: gc: notify user", c->self); + c->detach_user(c->self, NULL); + /* if we still have a callback */ + if (c->detach_user != NULL) + return; + debug("channel %d: gc: user detached", c->self); + } + if (!c->wait_for_exit && !chan_is_dead(c, 1)) + return; + debug("channel %d: garbage collecting", c->self); + channel_free(c); +} + +static void +channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset) +{ + static int did_init = 0; + int i; + Channel *c; + + if (!did_init) { + channel_handler_init(); + did_init = 1; + } + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c == NULL) + continue; + if (ftab[c->type] != NULL) + (*ftab[c->type])(c, readset, writeset); + channel_garbage_collect(c); + } +} + +/* + * Allocate/update select bitmasks and add any bits relevant to channels in + * select bitmasks. + */ +void +channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp, + int *nallocp, int rekeying) +{ + int n; + u_int sz; + + n = MAX(*maxfdp, channel_max_fd); + + sz = howmany(n+1, NFDBITS) * sizeof(fd_mask); + /* perhaps check sz < nalloc/2 and shrink? */ + if (*readsetp == NULL || sz > *nallocp) { + *readsetp = xrealloc(*readsetp, sz); + *writesetp = xrealloc(*writesetp, sz); + *nallocp = sz; + } + *maxfdp = n; + memset(*readsetp, 0, sz); + memset(*writesetp, 0, sz); + + if (!rekeying) + channel_handler(channel_pre, *readsetp, *writesetp); +} + +/* + * After select, perform any appropriate operations for channels which have + * events pending. + */ +void +channel_after_select(fd_set * readset, fd_set * writeset) +{ + channel_handler(channel_post, readset, writeset); +} + + +/* If there is data to send to the connection, enqueue some of it now. */ + +void +channel_output_poll(void) +{ + Channel *c; + int i; + u_int len; + + for (i = 0; i < channels_alloc; i++) { + c = channels[i]; + if (c == NULL) + continue; + + /* + * We are only interested in channels that can have buffered + * incoming data. + */ + if (compat13) { + if (c->type != SSH_CHANNEL_OPEN && + c->type != SSH_CHANNEL_INPUT_DRAINING) + continue; + } else { + if (c->type != SSH_CHANNEL_OPEN) + continue; + } + if (compat20 && + (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) { + /* XXX is this true? */ + debug3("channel %d: will not send data after close", c->self); + continue; + } + + /* Get the amount of buffered data for this channel. */ + if ((c->istate == CHAN_INPUT_OPEN || + c->istate == CHAN_INPUT_WAIT_DRAIN) && + (len = buffer_len(&c->input)) > 0) { + /* + * Send some data for the other side over the secure + * connection. + */ + if (compat20) { + if (len > c->remote_window) + len = c->remote_window; + if (len > c->remote_maxpacket) + len = c->remote_maxpacket; + } else { + if (packet_is_interactive()) { + if (len > 1024) + len = 512; + } else { + /* Keep the packets at reasonable size. */ + if (len > packet_get_maxsize()/2) + len = packet_get_maxsize()/2; + } + } + if (len > 0) { + packet_start(compat20 ? + SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA); + packet_put_int(c->remote_id); + packet_put_string(buffer_ptr(&c->input), len); + packet_send(); + buffer_consume(&c->input, len); + c->remote_window -= len; + } + } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) { + if (compat13) + fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3"); + /* + * input-buffer is empty and read-socket shutdown: + * tell peer, that we will not send more data: send IEOF. + * hack for extended data: delay EOF if EFD still in use. + */ + if (CHANNEL_EFD_INPUT_ACTIVE(c)) + debug2("channel %d: ibuf_empty delayed efd %d/(%d)", + c->self, c->efd, buffer_len(&c->extended)); + else + chan_ibuf_empty(c); + } + /* Send extended data, i.e. stderr */ + if (compat20 && + !(c->flags & CHAN_EOF_SENT) && + c->remote_window > 0 && + (len = buffer_len(&c->extended)) > 0 && + c->extended_usage == CHAN_EXTENDED_READ) { + debug2("channel %d: rwin %u elen %u euse %d", + c->self, c->remote_window, buffer_len(&c->extended), + c->extended_usage); + if (len > c->remote_window) + len = c->remote_window; + if (len > c->remote_maxpacket) + len = c->remote_maxpacket; + packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA); + packet_put_int(c->remote_id); + packet_put_int(SSH2_EXTENDED_DATA_STDERR); + packet_put_string(buffer_ptr(&c->extended), len); + packet_send(); + buffer_consume(&c->extended, len); + c->remote_window -= len; + debug2("channel %d: sent ext data %d", c->self, len); + } + } +} + + +/* -- protocol input */ + +void +channel_input_data(int type, u_int32_t seq, void *ctxt) +{ + int id; + char *data; + u_int data_len; + Channel *c; + + /* Get the channel number and verify it. */ + id = packet_get_int(); + c = channel_lookup(id); + if (c == NULL) + packet_disconnect("Received data for nonexistent channel %d.", id); + + /* Ignore any data for non-open channels (might happen on close) */ + if (c->type != SSH_CHANNEL_OPEN && + c->type != SSH_CHANNEL_X11_OPEN) + return; + + /* same for protocol 1.5 if output end is no longer open */ + if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) + return; + + /* Get the data. */ + data = packet_get_string(&data_len); + + if (compat20) { + if (data_len > c->local_maxpacket) { + log("channel %d: rcvd big packet %d, maxpack %d", + c->self, data_len, c->local_maxpacket); + } + if (data_len > c->local_window) { + log("channel %d: rcvd too much data %d, win %d", + c->self, data_len, c->local_window); + xfree(data); + return; + } + c->local_window -= data_len; + } + packet_check_eom(); + buffer_append(&c->output, data, data_len); + xfree(data); +} + +void +channel_input_extended_data(int type, u_int32_t seq, void *ctxt) +{ + int id; + char *data; + u_int data_len, tcode; + Channel *c; + + /* Get the channel number and verify it. */ + id = packet_get_int(); + c = channel_lookup(id); + + if (c == NULL) + packet_disconnect("Received extended_data for bad channel %d.", id); + if (c->type != SSH_CHANNEL_OPEN) { + log("channel %d: ext data for non open", id); + return; + } + if (c->flags & CHAN_EOF_RCVD) { + if (datafellows & SSH_BUG_EXTEOF) + debug("channel %d: accepting ext data after eof", id); + else + packet_disconnect("Received extended_data after EOF " + "on channel %d.", id); + } + tcode = packet_get_int(); + if (c->efd == -1 || + c->extended_usage != CHAN_EXTENDED_WRITE || + tcode != SSH2_EXTENDED_DATA_STDERR) { + log("channel %d: bad ext data", c->self); + return; + } + data = packet_get_string(&data_len); + packet_check_eom(); + if (data_len > c->local_window) { + log("channel %d: rcvd too much extended_data %d, win %d", + c->self, data_len, c->local_window); + xfree(data); + return; + } + debug2("channel %d: rcvd ext data %d", c->self, data_len); + c->local_window -= data_len; + buffer_append(&c->extended, data, data_len); + xfree(data); +} + +void +channel_input_ieof(int type, u_int32_t seq, void *ctxt) +{ + int id; + Channel *c; + + id = packet_get_int(); + packet_check_eom(); + c = channel_lookup(id); + if (c == NULL) + packet_disconnect("Received ieof for nonexistent channel %d.", id); + chan_rcvd_ieof(c); + + /* XXX force input close */ + if (c->force_drain && c->istate == CHAN_INPUT_OPEN) { + debug("channel %d: FORCE input drain", c->self); + c->istate = CHAN_INPUT_WAIT_DRAIN; + if (buffer_len(&c->input) == 0) + chan_ibuf_empty(c); + } + +} + +void +channel_input_close(int type, u_int32_t seq, void *ctxt) +{ + int id; + Channel *c; + + id = packet_get_int(); + packet_check_eom(); + c = channel_lookup(id); + if (c == NULL) + packet_disconnect("Received close for nonexistent channel %d.", id); + + /* + * Send a confirmation that we have closed the channel and no more + * data is coming for it. + */ + packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION); + packet_put_int(c->remote_id); + packet_send(); + + /* + * If the channel is in closed state, we have sent a close request, + * and the other side will eventually respond with a confirmation. + * Thus, we cannot free the channel here, because then there would be + * no-one to receive the confirmation. The channel gets freed when + * the confirmation arrives. + */ + if (c->type != SSH_CHANNEL_CLOSED) { + /* + * Not a closed channel - mark it as draining, which will + * cause it to be freed later. + */ + buffer_clear(&c->input); + c->type = SSH_CHANNEL_OUTPUT_DRAINING; + } +} + +/* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */ +void +channel_input_oclose(int type, u_int32_t seq, void *ctxt) +{ + int id = packet_get_int(); + Channel *c = channel_lookup(id); + + packet_check_eom(); + if (c == NULL) + packet_disconnect("Received oclose for nonexistent channel %d.", id); + chan_rcvd_oclose(c); +} + +void +channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt) +{ + int id = packet_get_int(); + Channel *c = channel_lookup(id); + + packet_check_eom(); + if (c == NULL) + packet_disconnect("Received close confirmation for " + "out-of-range channel %d.", id); + if (c->type != SSH_CHANNEL_CLOSED) + packet_disconnect("Received close confirmation for " + "non-closed channel %d (type %d).", id, c->type); + channel_free(c); +} + +void +channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt) +{ + int id, remote_id; + Channel *c; + + id = packet_get_int(); + c = channel_lookup(id); + + if (c==NULL || c->type != SSH_CHANNEL_OPENING) + packet_disconnect("Received open confirmation for " + "non-opening channel %d.", id); + remote_id = packet_get_int(); + /* Record the remote channel number and mark that the channel is now open. */ + c->remote_id = remote_id; + c->type = SSH_CHANNEL_OPEN; + + if (compat20) { + c->remote_window = packet_get_int(); + c->remote_maxpacket = packet_get_int(); + if (c->confirm) { + debug2("callback start"); + c->confirm(c->self, NULL); + debug2("callback done"); + } + debug("channel %d: open confirm rwindow %u rmax %u", c->self, + c->remote_window, c->remote_maxpacket); + } + packet_check_eom(); +} + +static char * +reason2txt(int reason) +{ + switch (reason) { + case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED: + return "administratively prohibited"; + case SSH2_OPEN_CONNECT_FAILED: + return "connect failed"; + case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE: + return "unknown channel type"; + case SSH2_OPEN_RESOURCE_SHORTAGE: + return "resource shortage"; + } + return "unknown reason"; +} + +void +channel_input_open_failure(int type, u_int32_t seq, void *ctxt) +{ + int id, reason; + char *msg = NULL, *lang = NULL; + Channel *c; + + id = packet_get_int(); + c = channel_lookup(id); + + if (c==NULL || c->type != SSH_CHANNEL_OPENING) + packet_disconnect("Received open failure for " + "non-opening channel %d.", id); + if (compat20) { + reason = packet_get_int(); + if (!(datafellows & SSH_BUG_OPENFAILURE)) { + msg = packet_get_string(NULL); + lang = packet_get_string(NULL); + } + log("channel %d: open failed: %s%s%s", id, + reason2txt(reason), msg ? ": ": "", msg ? msg : ""); + if (msg != NULL) + xfree(msg); + if (lang != NULL) + xfree(lang); + } + packet_check_eom(); + /* Free the channel. This will also close the socket. */ + channel_free(c); +} + +void +channel_input_window_adjust(int type, u_int32_t seq, void *ctxt) +{ + Channel *c; + int id; + u_int adjust; + + if (!compat20) + return; + + /* Get the channel number and verify it. */ + id = packet_get_int(); + c = channel_lookup(id); + + if (c == NULL || c->type != SSH_CHANNEL_OPEN) { + log("Received window adjust for " + "non-open channel %d.", id); + return; + } + adjust = packet_get_int(); + packet_check_eom(); + debug2("channel %d: rcvd adjust %u", id, adjust); + c->remote_window += adjust; +} + +void +channel_input_port_open(int type, u_int32_t seq, void *ctxt) +{ + Channel *c = NULL; + u_short host_port; + char *host, *originator_string; + int remote_id, sock = -1; + + remote_id = packet_get_int(); + host = packet_get_string(NULL); + host_port = packet_get_int(); + + if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) { + originator_string = packet_get_string(NULL); + } else { + originator_string = xstrdup("unknown (remote did not supply name)"); + } + packet_check_eom(); + sock = channel_connect_to(host, host_port); + if (sock != -1) { + c = channel_new("connected socket", + SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0, + originator_string, 1); + c->remote_id = remote_id; + } + if (c == NULL) { + packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(remote_id); + packet_send(); + } + xfree(host); +} + + +/* -- tcp forwarding */ + +void +channel_set_af(int af) +{ + IPv4or6 = af; +} + +static int +channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port, + const char *host_to_connect, u_short port_to_connect, int gateway_ports) +{ + Channel *c; + int success, sock, on = 1; + struct addrinfo hints, *ai, *aitop; + const char *host; + char ntop[NI_MAXHOST], strport[NI_MAXSERV]; + + success = 0; + host = (type == SSH_CHANNEL_RPORT_LISTENER) ? + listen_addr : host_to_connect; + + if (host == NULL) { + error("No forward host name."); + return success; + } + if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) { + error("Forward host name too long."); + return success; + } + + /* + * getaddrinfo returns a loopback address if the hostname is + * set to NULL and hints.ai_flags is not AI_PASSIVE + */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = IPv4or6; + hints.ai_flags = gateway_ports ? AI_PASSIVE : 0; + hints.ai_socktype = SOCK_STREAM; + snprintf(strport, sizeof strport, "%d", listen_port); + if (getaddrinfo(NULL, strport, &hints, &aitop) != 0) + packet_disconnect("getaddrinfo: fatal error"); + + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) + continue; + if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop), + strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) { + error("channel_setup_fwd_listener: getnameinfo failed"); + continue; + } + /* Create a port to listen for the host. */ + sock = socket(ai->ai_family, SOCK_STREAM, 0); + if (sock < 0) { + /* this is no error since kernel may not support ipv6 */ + verbose("socket: %.100s", strerror(errno)); + continue; + } + /* + * Set socket options. + * Allow local port reuse in TIME_WAIT. + */ + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, + sizeof(on)) == -1) + error("setsockopt SO_REUSEADDR: %s", strerror(errno)); + + debug("Local forwarding listening on %s port %s.", ntop, strport); + + /* Bind the socket to the address. */ + if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) { + /* address can be in use ipv6 address is already bound */ + if (!ai->ai_next) + error("bind: %.100s", strerror(errno)); + else + verbose("bind: %.100s", strerror(errno)); + + close(sock); + continue; + } + /* Start listening for connections on the socket. */ + if (listen(sock, 5) < 0) { + error("listen: %.100s", strerror(errno)); + close(sock); + continue; + } + /* Allocate a channel number for the socket. */ + c = channel_new("port listener", type, sock, sock, -1, + CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, + 0, xstrdup("port listener"), 1); + strlcpy(c->path, host, sizeof(c->path)); + c->host_port = port_to_connect; + c->listening_port = listen_port; + success = 1; + } + if (success == 0) + error("channel_setup_fwd_listener: cannot listen to port: %d", + listen_port); + freeaddrinfo(aitop); + return success; +} + +/* protocol local port fwd, used by ssh (and sshd in v1) */ +int +channel_setup_local_fwd_listener(u_short listen_port, + const char *host_to_connect, u_short port_to_connect, int gateway_ports) +{ + return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER, + NULL, listen_port, host_to_connect, port_to_connect, gateway_ports); +} + +/* protocol v2 remote port fwd, used by sshd */ +int +channel_setup_remote_fwd_listener(const char *listen_address, + u_short listen_port, int gateway_ports) +{ + return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER, + listen_address, listen_port, NULL, 0, gateway_ports); +} + +/* + * Initiate forwarding of connections to port "port" on remote host through + * the secure channel to host:port from local side. + */ + +void +channel_request_remote_forwarding(u_short listen_port, + const char *host_to_connect, u_short port_to_connect) +{ + int type, success = 0; + + /* Record locally that connection to this host/port is permitted. */ + if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION) + fatal("channel_request_remote_forwarding: too many forwards"); + + /* Send the forward request to the remote side. */ + if (compat20) { + const char *address_to_bind = "0.0.0.0"; + packet_start(SSH2_MSG_GLOBAL_REQUEST); + packet_put_cstring("tcpip-forward"); + packet_put_char(1); /* boolean: want reply */ + packet_put_cstring(address_to_bind); + packet_put_int(listen_port); + packet_send(); + packet_write_wait(); + /* Assume that server accepts the request */ + success = 1; + } else { + packet_start(SSH_CMSG_PORT_FORWARD_REQUEST); + packet_put_int(listen_port); + packet_put_cstring(host_to_connect); + packet_put_int(port_to_connect); + packet_send(); + packet_write_wait(); + + /* Wait for response from the remote side. */ + type = packet_read(); + switch (type) { + case SSH_SMSG_SUCCESS: + success = 1; + break; + case SSH_SMSG_FAILURE: + log("Warning: Server denied remote port forwarding."); + break; + default: + /* Unknown packet */ + packet_disconnect("Protocol error for port forward request:" + "received packet type %d.", type); + } + } + if (success) { + permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect); + permitted_opens[num_permitted_opens].port_to_connect = port_to_connect; + permitted_opens[num_permitted_opens].listen_port = listen_port; + num_permitted_opens++; + } +} + +/* + * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates + * listening for the port, and sends back a success reply (or disconnect + * message if there was an error). This never returns if there was an error. + */ + +void +channel_input_port_forward_request(int is_root, int gateway_ports) +{ + u_short port, host_port; + char *hostname; + + /* Get arguments from the packet. */ + port = packet_get_int(); + hostname = packet_get_string(NULL); + host_port = packet_get_int(); + +#ifndef HAVE_CYGWIN + /* + * Check that an unprivileged user is not trying to forward a + * privileged port. + */ + if (port < IPPORT_RESERVED && !is_root) + packet_disconnect("Requested forwarding of port %d but user is not root.", + port); +#endif + /* Initiate forwarding */ + channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports); + + /* Free the argument string. */ + xfree(hostname); +} + +/* + * Permits opening to any host/port if permitted_opens[] is empty. This is + * usually called by the server, because the user could connect to any port + * anyway, and the server has no way to know but to trust the client anyway. + */ +void +channel_permit_all_opens(void) +{ + if (num_permitted_opens == 0) + all_opens_permitted = 1; +} + +void +channel_add_permitted_opens(char *host, int port) +{ + if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION) + fatal("channel_request_remote_forwarding: too many forwards"); + debug("allow port forwarding to host %s port %d", host, port); + + permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host); + permitted_opens[num_permitted_opens].port_to_connect = port; + num_permitted_opens++; + + all_opens_permitted = 0; +} + +void +channel_clear_permitted_opens(void) +{ + int i; + + for (i = 0; i < num_permitted_opens; i++) + xfree(permitted_opens[i].host_to_connect); + num_permitted_opens = 0; + +} + + +/* return socket to remote host, port */ +static int +connect_to(const char *host, u_short port) +{ + struct addrinfo hints, *ai, *aitop; + char ntop[NI_MAXHOST], strport[NI_MAXSERV]; + int gaierr; + int sock = -1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = IPv4or6; + hints.ai_socktype = SOCK_STREAM; + snprintf(strport, sizeof strport, "%d", port); + if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) { + error("connect_to %.100s: unknown host (%s)", host, + gai_strerror(gaierr)); + return -1; + } + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) + continue; + if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop), + strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) { + error("connect_to: getnameinfo failed"); + continue; + } + sock = socket(ai->ai_family, SOCK_STREAM, 0); + if (sock < 0) { + error("socket: %.100s", strerror(errno)); + continue; + } + if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) + fatal("connect_to: F_SETFL: %s", strerror(errno)); + if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 && + errno != EINPROGRESS) { + error("connect_to %.100s port %s: %.100s", ntop, strport, + strerror(errno)); + close(sock); + continue; /* fail -- try next */ + } + break; /* success */ + + } + freeaddrinfo(aitop); + if (!ai) { + error("connect_to %.100s port %d: failed.", host, port); + return -1; + } + /* success */ + set_nodelay(sock); + return sock; +} + +int +channel_connect_by_listen_address(u_short listen_port) +{ + int i; + + for (i = 0; i < num_permitted_opens; i++) + if (permitted_opens[i].listen_port == listen_port) + return connect_to( + permitted_opens[i].host_to_connect, + permitted_opens[i].port_to_connect); + error("WARNING: Server requests forwarding for unknown listen_port %d", + listen_port); + return -1; +} + +/* Check if connecting to that port is permitted and connect. */ +int +channel_connect_to(const char *host, u_short port) +{ + int i, permit; + + permit = all_opens_permitted; + if (!permit) { + for (i = 0; i < num_permitted_opens; i++) + if (permitted_opens[i].port_to_connect == port && + strcmp(permitted_opens[i].host_to_connect, host) == 0) + permit = 1; + + } + if (!permit) { + log("Received request to connect to host %.100s port %d, " + "but the request was denied.", host, port); + return -1; + } + return connect_to(host, port); +} + +/* -- X11 forwarding */ + +/* + * Creates an internet domain socket for listening for X11 connections. + * Returns 0 and a suitable display number for the DISPLAY variable + * stored in display_numberp , or -1 if an error occurs. + */ +int +x11_create_display_inet(int x11_display_offset, int x11_use_localhost, + int single_connection, u_int *display_numberp) +{ + Channel *nc = NULL; + int display_number, sock; + u_short port; + struct addrinfo hints, *ai, *aitop; + char strport[NI_MAXSERV]; + int gaierr, n, num_socks = 0, socks[NUM_SOCKS]; + + for (display_number = x11_display_offset; + display_number < MAX_DISPLAYS; + display_number++) { + port = 6000 + display_number; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = IPv4or6; + hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE; + hints.ai_socktype = SOCK_STREAM; + snprintf(strport, sizeof strport, "%d", port); + if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) { + error("getaddrinfo: %.100s", gai_strerror(gaierr)); + return -1; + } + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) + continue; + sock = socket(ai->ai_family, SOCK_STREAM, 0); + if (sock < 0) { + if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) { + error("socket: %.100s", strerror(errno)); + return -1; + } else { + debug("x11_create_display_inet: Socket family %d not supported", + ai->ai_family); + continue; + } + } +#ifdef IPV6_V6ONLY + if (ai->ai_family == AF_INET6) { + int on = 1; + if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) + error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno)); + } +#endif + if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) { + debug("bind port %d: %.100s", port, strerror(errno)); + close(sock); + + if (ai->ai_next) + continue; + + for (n = 0; n < num_socks; n++) { + close(socks[n]); + } + num_socks = 0; + break; + } + socks[num_socks++] = sock; +#ifndef DONT_TRY_OTHER_AF + if (num_socks == NUM_SOCKS) + break; +#else + if (x11_use_localhost) { + if (num_socks == NUM_SOCKS) + break; + } else { + break; + } +#endif + } + freeaddrinfo(aitop); + if (num_socks > 0) + break; + } + if (display_number >= MAX_DISPLAYS) { + error("Failed to allocate internet-domain X11 display socket."); + return -1; + } + /* Start listening for connections on the socket. */ + for (n = 0; n < num_socks; n++) { + sock = socks[n]; + if (listen(sock, 5) < 0) { + error("listen: %.100s", strerror(errno)); + close(sock); + return -1; + } + } + + /* Allocate a channel for each socket. */ + for (n = 0; n < num_socks; n++) { + sock = socks[n]; + nc = channel_new("x11 listener", + SSH_CHANNEL_X11_LISTENER, sock, sock, -1, + CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, + 0, xstrdup("X11 inet listener"), 1); + nc->single_connection = single_connection; + } + + /* Return the display number for the DISPLAY environment variable. */ + *display_numberp = display_number; + return (0); +} + +static int +connect_local_xsocket(u_int dnr) +{ + int sock; + struct sockaddr_un addr; + + sock = socket(AF_UNIX, SOCK_STREAM, 0); + if (sock < 0) + error("socket: %.100s", strerror(errno)); + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr); + if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0) + return sock; + close(sock); + error("connect %.100s: %.100s", addr.sun_path, strerror(errno)); + return -1; +} + +int +x11_connect_display(void) +{ + int display_number, sock = 0; + const char *display; + char buf[1024], *cp; + struct addrinfo hints, *ai, *aitop; + char strport[NI_MAXSERV]; + int gaierr; + + /* Try to open a socket for the local X server. */ + display = getenv("DISPLAY"); + if (!display) { + error("DISPLAY not set."); + return -1; + } + /* + * Now we decode the value of the DISPLAY variable and make a + * connection to the real X server. + */ + + /* + * Check if it is a unix domain socket. Unix domain displays are in + * one of the following formats: unix:d[.s], :d[.s], ::d[.s] + */ + if (strncmp(display, "unix:", 5) == 0 || + display[0] == ':') { + /* Connect to the unix domain socket. */ + if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) { + error("Could not parse display number from DISPLAY: %.100s", + display); + return -1; + } + /* Create a socket. */ + sock = connect_local_xsocket(display_number); + if (sock < 0) + return -1; + + /* OK, we now have a connection to the display. */ + return sock; + } + /* + * Connect to an inet socket. The DISPLAY value is supposedly + * hostname:d[.s], where hostname may also be numeric IP address. + */ + strlcpy(buf, display, sizeof(buf)); + cp = strchr(buf, ':'); + if (!cp) { + error("Could not find ':' in DISPLAY: %.100s", display); + return -1; + } + *cp = 0; + /* buf now contains the host name. But first we parse the display number. */ + if (sscanf(cp + 1, "%d", &display_number) != 1) { + error("Could not parse display number from DISPLAY: %.100s", + display); + return -1; + } + + /* Look up the host address */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = IPv4or6; + hints.ai_socktype = SOCK_STREAM; + snprintf(strport, sizeof strport, "%d", 6000 + display_number); + if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) { + error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr)); + return -1; + } + for (ai = aitop; ai; ai = ai->ai_next) { + /* Create a socket. */ + sock = socket(ai->ai_family, SOCK_STREAM, 0); + if (sock < 0) { + debug("socket: %.100s", strerror(errno)); + continue; + } + /* Connect it to the display. */ + if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) { + debug("connect %.100s port %d: %.100s", buf, + 6000 + display_number, strerror(errno)); + close(sock); + continue; + } + /* Success */ + break; + } + freeaddrinfo(aitop); + if (!ai) { + error("connect %.100s port %d: %.100s", buf, 6000 + display_number, + strerror(errno)); + return -1; + } + set_nodelay(sock); + return sock; +} + +/* + * This is called when SSH_SMSG_X11_OPEN is received. The packet contains + * the remote channel number. We should do whatever we want, and respond + * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE. + */ + +void +x11_input_open(int type, u_int32_t seq, void *ctxt) +{ + Channel *c = NULL; + int remote_id, sock = 0; + char *remote_host; + + debug("Received X11 open request."); + + remote_id = packet_get_int(); + + if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) { + remote_host = packet_get_string(NULL); + } else { + remote_host = xstrdup("unknown (remote did not supply name)"); + } + packet_check_eom(); + + /* Obtain a connection to the real X display. */ + sock = x11_connect_display(); + if (sock != -1) { + /* Allocate a channel for this connection. */ + c = channel_new("connected x11 socket", + SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0, + remote_host, 1); + c->remote_id = remote_id; + c->force_drain = 1; + } + if (c == NULL) { + /* Send refusal to the remote host. */ + packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(remote_id); + } else { + /* Send a confirmation to the remote host. */ + packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION); + packet_put_int(remote_id); + packet_put_int(c->self); + } + packet_send(); +} + +/* dummy protocol handler that denies SSH-1 requests (agent/x11) */ +void +deny_input_open(int type, u_int32_t seq, void *ctxt) +{ + int rchan = packet_get_int(); + + switch (type) { + case SSH_SMSG_AGENT_OPEN: + error("Warning: ssh server tried agent forwarding."); + break; + case SSH_SMSG_X11_OPEN: + error("Warning: ssh server tried X11 forwarding."); + break; + default: + error("deny_input_open: type %d", type); + break; + } + error("Warning: this is probably a break in attempt by a malicious server."); + packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(rchan); + packet_send(); +} + +/* + * Requests forwarding of X11 connections, generates fake authentication + * data, and enables authentication spoofing. + * This should be called in the client only. + */ +void +x11_request_forwarding_with_spoofing(int client_session_id, + const char *proto, const char *data) +{ + u_int data_len = (u_int) strlen(data) / 2; + u_int i, value, len; + char *new_data; + int screen_number; + const char *cp; + u_int32_t rand = 0; + + cp = getenv("DISPLAY"); + if (cp) + cp = strchr(cp, ':'); + if (cp) + cp = strchr(cp, '.'); + if (cp) + screen_number = atoi(cp + 1); + else + screen_number = 0; + + /* Save protocol name. */ + x11_saved_proto = xstrdup(proto); + + /* + * Extract real authentication data and generate fake data of the + * same length. + */ + x11_saved_data = xmalloc(data_len); + x11_fake_data = xmalloc(data_len); + for (i = 0; i < data_len; i++) { + if (sscanf(data + 2 * i, "%2x", &value) != 1) + fatal("x11_request_forwarding: bad authentication data: %.100s", data); + if (i % 4 == 0) + rand = arc4random(); + x11_saved_data[i] = value; + x11_fake_data[i] = rand & 0xff; + rand >>= 8; + } + x11_saved_data_len = data_len; + x11_fake_data_len = data_len; + + /* Convert the fake data into hex. */ + len = 2 * data_len + 1; + new_data = xmalloc(len); + for (i = 0; i < data_len; i++) + snprintf(new_data + 2 * i, len - 2 * i, + "%02x", (u_char) x11_fake_data[i]); + + /* Send the request packet. */ + if (compat20) { + channel_request_start(client_session_id, "x11-req", 0); + packet_put_char(0); /* XXX bool single connection */ + } else { + packet_start(SSH_CMSG_X11_REQUEST_FORWARDING); + } + packet_put_cstring(proto); + packet_put_cstring(new_data); + packet_put_int(screen_number); + packet_send(); + packet_write_wait(); + xfree(new_data); +} + + +/* -- agent forwarding */ + +/* Sends a message to the server to request authentication fd forwarding. */ + +void +auth_request_forwarding(void) +{ + packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING); + packet_send(); + packet_write_wait(); +} + +/* This is called to process an SSH_SMSG_AGENT_OPEN message. */ + +void +auth_input_open_request(int type, u_int32_t seq, void *ctxt) +{ + Channel *c = NULL; + int remote_id, sock; + char *name; + + /* Read the remote channel number from the message. */ + remote_id = packet_get_int(); + packet_check_eom(); + + /* + * Get a connection to the local authentication agent (this may again + * get forwarded). + */ + sock = ssh_get_authentication_socket(); + + /* + * If we could not connect the agent, send an error message back to + * the server. This should never happen unless the agent dies, + * because authentication forwarding is only enabled if we have an + * agent. + */ + if (sock >= 0) { + name = xstrdup("authentication agent connection"); + c = channel_new("", SSH_CHANNEL_OPEN, sock, sock, + -1, 0, 0, 0, name, 1); + c->remote_id = remote_id; + c->force_drain = 1; + } + if (c == NULL) { + packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); + packet_put_int(remote_id); + } else { + /* Send a confirmation to the remote host. */ + debug("Forwarding authentication connection."); + packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION); + packet_put_int(remote_id); + packet_put_int(c->self); + } + packet_send(); +} diff --git a/usr/src/cmd/ssh/libssh/common/cipher-ctr.c b/usr/src/cmd/ssh/libssh/common/cipher-ctr.c new file mode 100644 index 0000000000..a5e95f6caa --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/cipher-ctr.c @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2003 Markus Friedl <markus@openbsd.org> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +#include "includes.h" +RCSID("$OpenBSD: cipher-ctr.c,v 1.4 2004/02/06 23:41:13 dtucker Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/evp.h> + +#include "log.h" +#include "xmalloc.h" + +#if OPENSSL_VERSION_NUMBER < 0x00906000L +#define SSH_OLD_EVP +#endif + +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) +#include "rijndael.h" +#define AES_KEY rijndael_ctx +#define AES_BLOCK_SIZE 16 +#define AES_encrypt(a, b, c) rijndael_encrypt(c, a, b) +#define AES_set_encrypt_key(a, b, c) rijndael_set_key(c, (u_char *)a, b, 1) +#else +#include <openssl/aes.h> +#endif + +const EVP_CIPHER *evp_aes_128_ctr(void); +void ssh_aes_ctr_iv(EVP_CIPHER_CTX *, int, u_char *, u_int); + +struct ssh_aes_ctr_ctx +{ + AES_KEY aes_ctx; + u_char aes_counter[AES_BLOCK_SIZE]; +}; + +/* + * increment counter 'ctr', + * the counter is of size 'len' bytes and stored in network-byte-order. + * (LSB at ctr[len-1], MSB at ctr[0]) + */ +static void +ssh_ctr_inc(u_char *ctr, u_int len) +{ + int i; + + for (i = len - 1; i >= 0; i--) + if (++ctr[i]) /* continue on overflow */ + return; +} + +static int +ssh_aes_ctr(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src, + u_int len) +{ + struct ssh_aes_ctr_ctx *c; + u_int n = 0; + u_char buf[AES_BLOCK_SIZE]; + + if (len == 0) + return (1); + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) + return (0); + + while ((len--) > 0) { + if (n == 0) { + AES_encrypt(c->aes_counter, buf, &c->aes_ctx); + ssh_ctr_inc(c->aes_counter, AES_BLOCK_SIZE); + } + *(dest++) = *(src++) ^ buf[n]; + n = (n + 1) % AES_BLOCK_SIZE; + } + return (1); +} + +static int +ssh_aes_ctr_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv, + int enc) +{ + struct ssh_aes_ctr_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) { + c = xmalloc(sizeof(*c)); + EVP_CIPHER_CTX_set_app_data(ctx, c); + } + if (key != NULL) + AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, + &c->aes_ctx); + if (iv != NULL) + memcpy(c->aes_counter, iv, AES_BLOCK_SIZE); + return (1); +} + +static int +ssh_aes_ctr_cleanup(EVP_CIPHER_CTX *ctx) +{ + struct ssh_aes_ctr_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) { + memset(c, 0, sizeof(*c)); + xfree(c); + EVP_CIPHER_CTX_set_app_data(ctx, NULL); + } + return (1); +} + +void +ssh_aes_ctr_iv(EVP_CIPHER_CTX *evp, int doset, u_char * iv, u_int len) +{ + struct ssh_aes_ctr_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(evp)) == NULL) + fatal("ssh_aes_ctr_iv: no context"); + if (doset) + memcpy(c->aes_counter, iv, len); + else + memcpy(iv, c->aes_counter, len); +} + +const EVP_CIPHER * +evp_aes_128_ctr(void) +{ + static EVP_CIPHER aes_ctr; + + memset(&aes_ctr, 0, sizeof(EVP_CIPHER)); + aes_ctr.nid = NID_undef; + aes_ctr.block_size = AES_BLOCK_SIZE; + aes_ctr.iv_len = AES_BLOCK_SIZE; + aes_ctr.key_len = 16; + aes_ctr.init = ssh_aes_ctr_init; + aes_ctr.cleanup = ssh_aes_ctr_cleanup; + aes_ctr.do_cipher = ssh_aes_ctr; +#ifndef SSH_OLD_EVP + aes_ctr.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | + EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CUSTOM_IV; +#endif + return (&aes_ctr); +} diff --git a/usr/src/cmd/ssh/libssh/common/cipher.c b/usr/src/cmd/ssh/libssh/common/cipher.c new file mode 100644 index 0000000000..9d6e792849 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/cipher.c @@ -0,0 +1,772 @@ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * Copyright (c) 1999 Niels Provos. All rights reserved. + * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: cipher.c,v 1.61 2002/07/12 15:50:17 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "log.h" +#include "cipher.h" + +#include <openssl/md5.h> + +#if OPENSSL_VERSION_NUMBER < 0x00906000L +#define SSH_OLD_EVP +#define EVP_CIPHER_CTX_get_app_data(e) ((e)->app_data) +#endif + +extern const EVP_CIPHER *evp_aes_128_ctr(void); +extern void ssh_aes_ctr_iv(EVP_CIPHER_CTX *, int, u_char *, u_int); + +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) +#include "rijndael.h" +static const EVP_CIPHER *evp_rijndael(void); +#endif +static const EVP_CIPHER *evp_ssh1_3des(void); +static const EVP_CIPHER *evp_ssh1_bf(void); + +struct Cipher { + char *name; + int number; /* for ssh1 only */ + u_int block_size; + u_int key_len; + const EVP_CIPHER *(*evptype)(void); +} ciphers[] = { + { "none", SSH_CIPHER_NONE, 8, 0, EVP_enc_null }, + { "des", SSH_CIPHER_DES, 8, 8, EVP_des_cbc }, + { "3des", SSH_CIPHER_3DES, 8, 16, evp_ssh1_3des }, + { "blowfish", SSH_CIPHER_BLOWFISH, 8, 32, evp_ssh1_bf }, + { "3des-cbc", SSH_CIPHER_SSH2, 8, 24, EVP_des_ede3_cbc }, + { "blowfish-cbc", SSH_CIPHER_SSH2, 8, 16, EVP_bf_cbc }, +#ifdef SOLARIS_SSH_ENABLE_CAST5_128 + { "cast128-cbc", SSH_CIPHER_SSH2, 8, 16, EVP_cast5_cbc }, +#endif /* SOLARIS_SSH_ENABLE_CAST5_128 */ + { "arcfour", SSH_CIPHER_SSH2, 8, 16, EVP_rc4 }, +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) + { "aes128-cbc", SSH_CIPHER_SSH2, 16, 16, evp_rijndael }, +#ifdef SOLARIS_SSH_ENABLE_AES192 + { "aes192-cbc", SSH_CIPHER_SSH2, 16, 24, evp_rijndael }, +#endif /* SOLARIS_SSH_ENABLE_AES192 */ +#ifdef SOLARIS_SSH_ENABLE_AES256 + { "aes256-cbc", SSH_CIPHER_SSH2, 16, 32, evp_rijndael }, + { "rijndael-cbc@lysator.liu.se", + SSH_CIPHER_SSH2, 16, 32, evp_rijndael }, +#endif /* SOLARIS_SSH_ENABLE_AES256 */ +#else + { "aes128-cbc", SSH_CIPHER_SSH2, 16, 16, EVP_aes_128_cbc }, +#ifdef SOLARIS_SSH_ENABLE_AES192 + { "aes192-cbc", SSH_CIPHER_SSH2, 16, 24, EVP_aes_192_cbc }, +#endif /* SOLARIS_SSH_ENABLE_AES192 */ +#ifdef SOLARIS_SSH_ENABLE_AES256 + { "aes256-cbc", SSH_CIPHER_SSH2, 16, 32, EVP_aes_256_cbc }, + { "rijndael-cbc@lysator.liu.se", + SSH_CIPHER_SSH2, 16, 32, EVP_aes_256_cbc }, +#endif /* SOLARIS_SSH_ENABLE_AES256 */ +#endif +#if OPENSSL_VERSION_NUMBER >= 0x00905000L + { "aes128-ctr", SSH_CIPHER_SSH2, 16, 16, evp_aes_128_ctr }, +#ifdef SOLARIS_SSH_ENABLE_AES192 + { "aes192-ctr", SSH_CIPHER_SSH2, 16, 24, evp_aes_128_ctr }, +#endif /* SOLARIS_SSH_ENABLE_AES192 */ +#ifdef SOLARIS_SSH_ENABLE_AES192 + { "aes256-ctr", SSH_CIPHER_SSH2, 16, 32, evp_aes_128_ctr }, +#endif /* SOLARIS_SSH_ENABLE_AES192 */ +#endif + { NULL, SSH_CIPHER_ILLEGAL, 0, 0, NULL } +}; + +/*--*/ + +u_int +cipher_blocksize(Cipher *c) +{ + return (c->block_size); +} + +u_int +cipher_keylen(Cipher *c) +{ + return (c->key_len); +} + +u_int +cipher_get_number(Cipher *c) +{ + return (c->number); +} + +u_int +cipher_mask_ssh1(int client) +{ + u_int mask = 0; + mask |= 1 << SSH_CIPHER_3DES; /* Mandatory */ + mask |= 1 << SSH_CIPHER_BLOWFISH; + if (client) { + mask |= 1 << SSH_CIPHER_DES; + } + return mask; +} + +Cipher * +cipher_by_name(const char *name) +{ + Cipher *c; + for (c = ciphers; c->name != NULL; c++) + if (strcasecmp(c->name, name) == 0) + return c; + return NULL; +} + +Cipher * +cipher_by_number(int id) +{ + Cipher *c; + for (c = ciphers; c->name != NULL; c++) + if (c->number == id) + return c; + return NULL; +} + +#define CIPHER_SEP "," +int +ciphers_valid(const char *names) +{ + Cipher *c; + char *ciphers, *cp; + char *p; + + if (names == NULL || strcmp(names, "") == 0) + return 0; + ciphers = cp = xstrdup(names); + for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0'; + (p = strsep(&cp, CIPHER_SEP))) { + c = cipher_by_name(p); + if (c == NULL || c->number != SSH_CIPHER_SSH2) { + debug("bad cipher %s [%s]", p, names); + xfree(ciphers); + return 0; + } else { + debug3("cipher ok: %s [%s]", p, names); + } + } + debug3("ciphers ok: [%s]", names); + xfree(ciphers); + return 1; +} + +/* + * Parses the name of the cipher. Returns the number of the corresponding + * cipher, or -1 on error. + */ + +int +cipher_number(const char *name) +{ + Cipher *c; + if (name == NULL) + return -1; + c = cipher_by_name(name); + return (c==NULL) ? -1 : c->number; +} + +char * +cipher_name(int id) +{ + Cipher *c = cipher_by_number(id); + return (c==NULL) ? "<unknown>" : c->name; +} + +void +cipher_init(CipherContext *cc, Cipher *cipher, + const u_char *key, u_int keylen, const u_char *iv, u_int ivlen, + int encrypt) +{ + static int dowarn = 1; +#ifdef SSH_OLD_EVP + EVP_CIPHER *type; +#else + const EVP_CIPHER *type; +#endif + int klen; + + if (cipher->number == SSH_CIPHER_DES) { + if (dowarn) { + error("Warning: use of DES is strongly discouraged " + "due to cryptographic weaknesses"); + dowarn = 0; + } + if (keylen > 8) + keylen = 8; + } + cc->plaintext = (cipher->number == SSH_CIPHER_NONE); + + if (keylen < cipher->key_len) + fatal("cipher_init: key length %d is insufficient for %s.", + keylen, cipher->name); + if (iv != NULL && ivlen < cipher->block_size) + fatal("cipher_init: iv length %d is insufficient for %s.", + ivlen, cipher->name); + cc->cipher = cipher; + + type = (*cipher->evptype)(); + + EVP_CIPHER_CTX_init(&cc->evp); +#ifdef SSH_OLD_EVP + if (type->key_len > 0 && type->key_len != keylen) { + debug("cipher_init: set keylen (%d -> %d)", + type->key_len, keylen); + type->key_len = keylen; + } + EVP_CipherInit(&cc->evp, type, (u_char *)key, (u_char *)iv, + (encrypt == CIPHER_ENCRYPT)); +#else + if (EVP_CipherInit(&cc->evp, type, NULL, (u_char *)iv, + (encrypt == CIPHER_ENCRYPT)) == 0) + fatal("cipher_init: EVP_CipherInit failed for %s", + cipher->name); + klen = EVP_CIPHER_CTX_key_length(&cc->evp); + if (klen > 0 && keylen != klen) { + debug("cipher_init: set keylen (%d -> %d)", klen, keylen); + if (EVP_CIPHER_CTX_set_key_length(&cc->evp, keylen) == 0) + fatal("cipher_init: set keylen failed (%d -> %d)", + klen, keylen); + } + if (EVP_CipherInit(&cc->evp, NULL, (u_char *)key, NULL, -1) == 0) + fatal("cipher_init: EVP_CipherInit: set key failed for %s", + cipher->name); +#endif +} + +void +cipher_crypt(CipherContext *cc, u_char *dest, const u_char *src, u_int len) +{ + if (len % cc->cipher->block_size) + fatal("cipher_encrypt: bad plaintext length %d", len); +#ifdef SSH_OLD_EVP + EVP_Cipher(&cc->evp, dest, (u_char *)src, len); +#else + if (EVP_Cipher(&cc->evp, dest, (u_char *)src, len) == 0) + fatal("evp_crypt: EVP_Cipher failed"); +#endif +} + +void +cipher_cleanup(CipherContext *cc) +{ +#ifdef SSH_OLD_EVP + EVP_CIPHER_CTX_cleanup(&cc->evp); +#else + if (EVP_CIPHER_CTX_cleanup(&cc->evp) == 0) + error("cipher_cleanup: EVP_CIPHER_CTX_cleanup failed"); +#endif +} + +/* + * Selects the cipher, and keys if by computing the MD5 checksum of the + * passphrase and using the resulting 16 bytes as the key. + */ + +void +cipher_set_key_string(CipherContext *cc, Cipher *cipher, + const char *passphrase, int encrypt) +{ + MD5_CTX md; + u_char digest[16]; + + MD5_Init(&md); + MD5_Update(&md, (const u_char *)passphrase, strlen(passphrase)); + MD5_Final(digest, &md); + + cipher_init(cc, cipher, digest, 16, NULL, 0, encrypt); + + memset(digest, 0, sizeof(digest)); + memset(&md, 0, sizeof(md)); +} + +/* Implementations for other non-EVP ciphers */ + +/* + * This is used by SSH1: + * + * What kind of triple DES are these 2 routines? + * + * Why is there a redundant initialization vector? + * + * If only iv3 was used, then, this would till effect have been + * outer-cbc. However, there is also a private iv1 == iv2 which + * perhaps makes differential analysis easier. On the other hand, the + * private iv1 probably makes the CRC-32 attack ineffective. This is a + * result of that there is no longer any known iv1 to use when + * choosing the X block. + */ +struct ssh1_3des_ctx +{ + EVP_CIPHER_CTX k1, k2, k3; +}; + +static int +ssh1_3des_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv, + int enc) +{ + struct ssh1_3des_ctx *c; + u_char *k1, *k2, *k3; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) { + c = xmalloc(sizeof(*c)); + EVP_CIPHER_CTX_set_app_data(ctx, c); + } + if (key == NULL) + return (1); + if (enc == -1) + enc = ctx->encrypt; + k1 = k2 = k3 = (u_char *) key; + k2 += 8; + if (EVP_CIPHER_CTX_key_length(ctx) >= 16+8) { + if (enc) + k3 += 16; + else + k1 += 16; + } + EVP_CIPHER_CTX_init(&c->k1); + EVP_CIPHER_CTX_init(&c->k2); + EVP_CIPHER_CTX_init(&c->k3); +#ifdef SSH_OLD_EVP + EVP_CipherInit(&c->k1, EVP_des_cbc(), k1, NULL, enc); + EVP_CipherInit(&c->k2, EVP_des_cbc(), k2, NULL, !enc); + EVP_CipherInit(&c->k3, EVP_des_cbc(), k3, NULL, enc); +#else + if (EVP_CipherInit(&c->k1, EVP_des_cbc(), k1, NULL, enc) == 0 || + EVP_CipherInit(&c->k2, EVP_des_cbc(), k2, NULL, !enc) == 0 || + EVP_CipherInit(&c->k3, EVP_des_cbc(), k3, NULL, enc) == 0) { + memset(c, 0, sizeof(*c)); + xfree(c); + EVP_CIPHER_CTX_set_app_data(ctx, NULL); + return (0); + } +#endif + return (1); +} + +static int +ssh1_3des_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src, u_int len) +{ + struct ssh1_3des_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) { + error("ssh1_3des_cbc: no context"); + return (0); + } +#ifdef SSH_OLD_EVP + EVP_Cipher(&c->k1, dest, (u_char *)src, len); + EVP_Cipher(&c->k2, dest, dest, len); + EVP_Cipher(&c->k3, dest, dest, len); +#else + if (EVP_Cipher(&c->k1, dest, (u_char *)src, len) == 0 || + EVP_Cipher(&c->k2, dest, dest, len) == 0 || + EVP_Cipher(&c->k3, dest, dest, len) == 0) + return (0); +#endif + return (1); +} + +static int +ssh1_3des_cleanup(EVP_CIPHER_CTX *ctx) +{ + struct ssh1_3des_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) { + memset(c, 0, sizeof(*c)); + xfree(c); + EVP_CIPHER_CTX_set_app_data(ctx, NULL); + } + return (1); +} + +static const EVP_CIPHER * +evp_ssh1_3des(void) +{ + static EVP_CIPHER ssh1_3des; + + memset(&ssh1_3des, 0, sizeof(EVP_CIPHER)); + ssh1_3des.nid = NID_undef; + ssh1_3des.block_size = 8; + ssh1_3des.iv_len = 0; + ssh1_3des.key_len = 16; + ssh1_3des.init = ssh1_3des_init; + ssh1_3des.cleanup = ssh1_3des_cleanup; + ssh1_3des.do_cipher = ssh1_3des_cbc; +#ifndef SSH_OLD_EVP + ssh1_3des.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH; +#endif + return (&ssh1_3des); +} + +/* + * SSH1 uses a variation on Blowfish, all bytes must be swapped before + * and after encryption/decryption. Thus the swap_bytes stuff (yuk). + */ +static void +swap_bytes(const u_char *src, u_char *dst, int n) +{ + u_char c[4]; + + /* Process 4 bytes every lap. */ + for (n = n / 4; n > 0; n--) { + c[3] = *src++; + c[2] = *src++; + c[1] = *src++; + c[0] = *src++; + + *dst++ = c[0]; + *dst++ = c[1]; + *dst++ = c[2]; + *dst++ = c[3]; + } +} + +#ifdef SSH_OLD_EVP +static void bf_ssh1_init (EVP_CIPHER_CTX * ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + if (iv != NULL) + memcpy (&(ctx->oiv[0]), iv, 8); + memcpy (&(ctx->iv[0]), &(ctx->oiv[0]), 8); + if (key != NULL) + BF_set_key (&(ctx->c.bf_ks), EVP_CIPHER_CTX_key_length (ctx), + key); +} +#endif +static int (*orig_bf)(EVP_CIPHER_CTX *, u_char *, const u_char *, u_int) = NULL; + +static int +bf_ssh1_cipher(EVP_CIPHER_CTX *ctx, u_char *out, const u_char *in, u_int len) +{ + int ret; + + swap_bytes(in, out, len); + ret = (*orig_bf)(ctx, out, out, len); + swap_bytes(out, out, len); + return (ret); +} + +static const EVP_CIPHER * +evp_ssh1_bf(void) +{ + static EVP_CIPHER ssh1_bf; + + memcpy(&ssh1_bf, EVP_bf_cbc(), sizeof(EVP_CIPHER)); + orig_bf = ssh1_bf.do_cipher; + ssh1_bf.nid = NID_undef; +#ifdef SSH_OLD_EVP + ssh1_bf.init = bf_ssh1_init; +#endif + ssh1_bf.do_cipher = bf_ssh1_cipher; + ssh1_bf.key_len = 32; + return (&ssh1_bf); +} + +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) +/* RIJNDAEL */ +#define RIJNDAEL_BLOCKSIZE 16 +struct ssh_rijndael_ctx +{ + rijndael_ctx r_ctx; + u_char r_iv[RIJNDAEL_BLOCKSIZE]; +}; + +static int +ssh_rijndael_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv, + int enc) +{ + struct ssh_rijndael_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) { + c = xmalloc(sizeof(*c)); + EVP_CIPHER_CTX_set_app_data(ctx, c); + } + if (key != NULL) { + if (enc == -1) + enc = ctx->encrypt; + rijndael_set_key(&c->r_ctx, (u_char *)key, + 8*EVP_CIPHER_CTX_key_length(ctx), enc); + } + if (iv != NULL) + memcpy(c->r_iv, iv, RIJNDAEL_BLOCKSIZE); + return (1); +} + +static int +ssh_rijndael_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src, + u_int len) +{ + struct ssh_rijndael_ctx *c; + u_char buf[RIJNDAEL_BLOCKSIZE]; + u_char *cprev, *cnow, *plain, *ivp; + int i, j, blocks = len / RIJNDAEL_BLOCKSIZE; + + if (len == 0) + return (1); + if (len % RIJNDAEL_BLOCKSIZE) + fatal("ssh_rijndael_cbc: bad len %d", len); + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) { + error("ssh_rijndael_cbc: no context"); + return (0); + } + if (ctx->encrypt) { + cnow = dest; + plain = (u_char *)src; + cprev = c->r_iv; + for (i = 0; i < blocks; i++, plain+=RIJNDAEL_BLOCKSIZE, + cnow+=RIJNDAEL_BLOCKSIZE) { + for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++) + buf[j] = plain[j] ^ cprev[j]; + rijndael_encrypt(&c->r_ctx, buf, cnow); + cprev = cnow; + } + memcpy(c->r_iv, cprev, RIJNDAEL_BLOCKSIZE); + } else { + cnow = (u_char *) (src+len-RIJNDAEL_BLOCKSIZE); + plain = dest+len-RIJNDAEL_BLOCKSIZE; + + memcpy(buf, cnow, RIJNDAEL_BLOCKSIZE); + for (i = blocks; i > 0; i--, cnow-=RIJNDAEL_BLOCKSIZE, + plain-=RIJNDAEL_BLOCKSIZE) { + rijndael_decrypt(&c->r_ctx, cnow, plain); + ivp = (i == 1) ? c->r_iv : cnow-RIJNDAEL_BLOCKSIZE; + for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++) + plain[j] ^= ivp[j]; + } + memcpy(c->r_iv, buf, RIJNDAEL_BLOCKSIZE); + } + return (1); +} + +static int +ssh_rijndael_cleanup(EVP_CIPHER_CTX *ctx) +{ + struct ssh_rijndael_ctx *c; + + if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) { + memset(c, 0, sizeof(*c)); + xfree(c); + EVP_CIPHER_CTX_set_app_data(ctx, NULL); + } + return (1); +} + +static const EVP_CIPHER * +evp_rijndael(void) +{ + static EVP_CIPHER rijndal_cbc; + + memset(&rijndal_cbc, 0, sizeof(EVP_CIPHER)); + rijndal_cbc.nid = NID_undef; + rijndal_cbc.block_size = RIJNDAEL_BLOCKSIZE; + rijndal_cbc.iv_len = RIJNDAEL_BLOCKSIZE; + rijndal_cbc.key_len = 16; + rijndal_cbc.init = ssh_rijndael_init; + rijndal_cbc.cleanup = ssh_rijndael_cleanup; + rijndal_cbc.do_cipher = ssh_rijndael_cbc; +#ifndef SSH_OLD_EVP + rijndal_cbc.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH | + EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CUSTOM_IV; +#endif + return (&rijndal_cbc); +} +#endif + +/* + * Exports an IV from the CipherContext required to export the key + * state back from the unprivileged child to the privileged parent + * process. + */ + +int +cipher_get_keyiv_len(CipherContext *cc) +{ + Cipher *c = cc->cipher; + int ivlen; + + if (c->number == SSH_CIPHER_3DES) + ivlen = 24; + else + ivlen = EVP_CIPHER_CTX_iv_length(&cc->evp); + return (ivlen); +} + +void +cipher_get_keyiv(CipherContext *cc, u_char *iv, u_int len) +{ + Cipher *c = cc->cipher; + u_char *civ = NULL; + int evplen; + + switch (c->number) { + case SSH_CIPHER_SSH2: + case SSH_CIPHER_DES: + case SSH_CIPHER_BLOWFISH: + evplen = EVP_CIPHER_CTX_iv_length(&cc->evp); + if (evplen == 0) + return; + if (evplen != len) + fatal("%s: wrong iv length %d != %d", __func__, + evplen, len); + +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) + if (c->evptype == evp_rijndael) { + struct ssh_rijndael_ctx *aesc; + + aesc = EVP_CIPHER_CTX_get_app_data(&cc->evp); + if (aesc == NULL) + fatal("%s: no rijndael context", __func__); + civ = aesc->r_iv; + } else +#endif + if (c->evptype == evp_aes_128_ctr) { + ssh_aes_ctr_iv(&cc->evp, 0, iv, len); + return; + } else { + civ = cc->evp.iv; + } + break; + case SSH_CIPHER_3DES: { + struct ssh1_3des_ctx *desc; + if (len != 24) + fatal("%s: bad 3des iv length: %d", __func__, len); + desc = EVP_CIPHER_CTX_get_app_data(&cc->evp); + if (desc == NULL) + fatal("%s: no 3des context", __func__); + debug3("%s: Copying 3DES IV", __func__); + memcpy(iv, desc->k1.iv, 8); + memcpy(iv + 8, desc->k2.iv, 8); + memcpy(iv + 16, desc->k3.iv, 8); + return; + } + default: + fatal("%s: bad cipher %d", __func__, c->number); + } + memcpy(iv, civ, len); +} + +void +cipher_set_keyiv(CipherContext *cc, u_char *iv) +{ + Cipher *c = cc->cipher; + u_char *div = NULL; + int evplen = 0; + + switch (c->number) { + case SSH_CIPHER_SSH2: + case SSH_CIPHER_DES: + case SSH_CIPHER_BLOWFISH: + evplen = EVP_CIPHER_CTX_iv_length(&cc->evp); + if (evplen == 0) + return; + +#if (OPENSSL_VERSION_NUMBER < 0x00907000L) + if (c->evptype == evp_rijndael) { + struct ssh_rijndael_ctx *aesc; + + aesc = EVP_CIPHER_CTX_get_app_data(&cc->evp); + if (aesc == NULL) + fatal("%s: no rijndael context", __func__); + div = aesc->r_iv; + } else +#endif + if (c->evptype == evp_aes_128_ctr) { + ssh_aes_ctr_iv(&cc->evp, 1, iv, evplen); + return; + } else { + div = cc->evp.iv; + } + break; + case SSH_CIPHER_3DES: { + struct ssh1_3des_ctx *desc; + desc = EVP_CIPHER_CTX_get_app_data(&cc->evp); + if (desc == NULL) + fatal("%s: no 3des context", __func__); + debug3("%s: Installed 3DES IV", __func__); + memcpy(desc->k1.iv, iv, 8); + memcpy(desc->k2.iv, iv + 8, 8); + memcpy(desc->k3.iv, iv + 16, 8); + return; + } + default: + fatal("%s: bad cipher %d", __func__, c->number); + } + memcpy(div, iv, evplen); +} + +#if OPENSSL_VERSION_NUMBER < 0x00907000L +#define EVP_X_STATE(evp) &(evp).c +#define EVP_X_STATE_LEN(evp) sizeof((evp).c) +#else +#define EVP_X_STATE(evp) (evp).cipher_data +#define EVP_X_STATE_LEN(evp) (evp).cipher->ctx_size +#endif + +int +cipher_get_keycontext(CipherContext *cc, u_char *dat) +{ + int plen = 0; + Cipher *c = cc->cipher; + + if (c->evptype == EVP_rc4) { + plen = EVP_X_STATE_LEN(cc->evp); + if (dat == NULL) + return (plen); + memcpy(dat, EVP_X_STATE(cc->evp), plen); + } + return (plen); +} + +void +cipher_set_keycontext(CipherContext *cc, u_char *dat) +{ + Cipher *c = cc->cipher; + int plen; + + if (c->evptype == EVP_rc4) { + plen = EVP_X_STATE_LEN(cc->evp); + memcpy(EVP_X_STATE(cc->evp), dat, plen); + } +} diff --git a/usr/src/cmd/ssh/libssh/common/compat.c b/usr/src/cmd/ssh/libssh/common/compat.c new file mode 100644 index 0000000000..a631b346ae --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/compat.c @@ -0,0 +1,252 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: compat.c,v 1.65 2002/09/27 10:42:09 mickey Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "buffer.h" +#include "packet.h" +#include "xmalloc.h" +#include "compat.h" +#include "log.h" +#include "match.h" + +int compat13 = 0; +int compat20 = 0; +int datafellows = 0; + +void +enable_compat20(void) +{ + debug("Enabling compatibility mode for protocol 2.0"); + compat20 = 1; +} +void +enable_compat13(void) +{ + debug("Enabling compatibility mode for protocol 1.3"); + compat13 = 1; +} +/* datafellows bug compatibility */ +void +compat_datafellows(const char *version) +{ + int i; + static struct { + char *pat; + int bugs; + } check[] = { + { "OpenSSH-2.0*," + "OpenSSH-2.1*," + "OpenSSH_2.1*," + "OpenSSH_2.2*", SSH_OLD_SESSIONID|SSH_BUG_BANNER| + SSH_OLD_DHGEX|SSH_BUG_NOREKEY| + SSH_BUG_EXTEOF}, + { "OpenSSH_2.3.0*", SSH_BUG_BANNER|SSH_BUG_BIGENDIANAES| + SSH_OLD_DHGEX|SSH_BUG_NOREKEY| + SSH_BUG_EXTEOF}, + { "OpenSSH_2.3.*", SSH_BUG_BIGENDIANAES|SSH_OLD_DHGEX| + SSH_BUG_NOREKEY|SSH_BUG_EXTEOF}, + { "OpenSSH_2.5.0p1*," + "OpenSSH_2.5.1p1*", + SSH_BUG_BIGENDIANAES|SSH_OLD_DHGEX| + SSH_BUG_NOREKEY|SSH_BUG_EXTEOF| + SSH_OLD_GSSAPI}, + { "OpenSSH_2.5.0*," + "OpenSSH_2.5.1*," + "OpenSSH_2.5.2*", SSH_OLD_DHGEX|SSH_BUG_NOREKEY| + SSH_BUG_EXTEOF}, + { "OpenSSH_2.5.3*", SSH_BUG_NOREKEY|SSH_BUG_EXTEOF}, + { "OpenSSH_2.9p*", SSH_BUG_EXTEOF|SSH_OLD_GSSAPI| + SSH_BUG_GSSKEX_HOSTKEY}, + { "OpenSSH_2.*," + "OpenSSH_3.0*," + "OpenSSH_3.1*", SSH_BUG_EXTEOF|SSH_OLD_GSSAPI| + SSH_BUG_GSSAPI_BER| + SSH_BUG_GSSKEX_HOSTKEY}, + { "OpenSSH_3.2*," + "OpenSSH_3.3*," + "OpenSSH_3.4*," + "OpenSSH_3.5*", SSH_BUG_GSSAPI_BER|SSH_OLD_GSSAPI| + SSH_BUG_GSSKEX_HOSTKEY}, + { "OpenSSH_3.6*," + "OpenSSH_3.7*," + "OpenSSH_3.8*", SSH_BUG_GSSKEX_HOSTKEY}, + { "OpenSSH*", 0 }, + { "Sun_SSH_1.0.*", SSH_BUG_NOREKEY| + SSH_BUG_DFLT_CLNT_EXIT_0| + SSH_BUG_LOCALES_NOT_LANGTAGS}, + { "Sun_SSH_1.0*", SSH_BUG_NOREKEY|SSH_BUG_EXTEOF| + SSH_BUG_DFLT_CLNT_EXIT_0| + SSH_BUG_LOCALES_NOT_LANGTAGS}, + { "*MindTerm*", 0 }, + { "2.1.0*", SSH_BUG_SIGBLOB|SSH_BUG_HMAC| + SSH_OLD_SESSIONID|SSH_BUG_DEBUG| + SSH_BUG_RSASIGMD5|SSH_BUG_HBSERVICE| + SSH_BUG_FIRSTKEX }, + { "2.1 *", SSH_BUG_SIGBLOB|SSH_BUG_HMAC| + SSH_OLD_SESSIONID|SSH_BUG_DEBUG| + SSH_BUG_RSASIGMD5|SSH_BUG_HBSERVICE| + SSH_BUG_FIRSTKEX }, + { "2.0.13*," + "2.0.14*," + "2.0.15*," + "2.0.16*," + "2.0.17*," + "2.0.18*," + "2.0.19*", SSH_BUG_SIGBLOB|SSH_BUG_HMAC| + SSH_OLD_SESSIONID|SSH_BUG_DEBUG| + SSH_BUG_PKSERVICE|SSH_BUG_X11FWD| + SSH_BUG_PKOK|SSH_BUG_RSASIGMD5| + SSH_BUG_HBSERVICE|SSH_BUG_OPENFAILURE| + SSH_BUG_DUMMYCHAN|SSH_BUG_FIRSTKEX }, + { "2.0.11*," + "2.0.12*", SSH_BUG_SIGBLOB|SSH_BUG_HMAC| + SSH_OLD_SESSIONID|SSH_BUG_DEBUG| + SSH_BUG_PKSERVICE|SSH_BUG_X11FWD| + SSH_BUG_PKAUTH|SSH_BUG_PKOK| + SSH_BUG_RSASIGMD5|SSH_BUG_OPENFAILURE| + SSH_BUG_DUMMYCHAN|SSH_BUG_FIRSTKEX }, + { "2.0.*", SSH_BUG_SIGBLOB|SSH_BUG_HMAC| + SSH_OLD_SESSIONID|SSH_BUG_DEBUG| + SSH_BUG_PKSERVICE|SSH_BUG_X11FWD| + SSH_BUG_PKAUTH|SSH_BUG_PKOK| + SSH_BUG_RSASIGMD5|SSH_BUG_OPENFAILURE| + SSH_BUG_DERIVEKEY|SSH_BUG_DUMMYCHAN| + SSH_BUG_FIRSTKEX }, + { "2.2.0*," + "2.3.0*", SSH_BUG_HMAC|SSH_BUG_DEBUG| + SSH_BUG_RSASIGMD5|SSH_BUG_FIRSTKEX }, + { "2.3.*", SSH_BUG_DEBUG|SSH_BUG_RSASIGMD5| + SSH_BUG_FIRSTKEX }, + { "2.4", SSH_OLD_SESSIONID }, /* Van Dyke */ + { "2.*", SSH_BUG_DEBUG|SSH_BUG_FIRSTKEX }, + { "3.0.*", SSH_BUG_DEBUG }, + { "3.0 SecureCRT*", SSH_OLD_SESSIONID }, + { "1.7 SecureFX*", SSH_OLD_SESSIONID }, + { "1.2.18*," + "1.2.19*," + "1.2.20*," + "1.2.21*," + "1.2.22*", SSH_BUG_IGNOREMSG|SSH_BUG_K5USER }, + { "1.3.2*", /* F-Secure */ + SSH_BUG_IGNOREMSG|SSH_BUG_K5USER }, + { "1.2.1*," + "1.2.2*," + "1.2.3*", SSH_BUG_K5USER }, + { "*SSH Compatible Server*", /* Netscreen */ + SSH_BUG_PASSWORDPAD }, + { "*OSU_0*," + "OSU_1.0*," + "OSU_1.1*," + "OSU_1.2*," + "OSU_1.3*," + "OSU_1.4*," + "OSU_1.5alpha1*," + "OSU_1.5alpha2*," + "OSU_1.5alpha3*", SSH_BUG_PASSWORDPAD }, + { "*SSH_Version_Mapper*", + SSH_BUG_SCANNER }, + { "Probe-*", + SSH_BUG_PROBE }, + { NULL, 0 } + }; + + /* process table, return first match */ + for (i = 0; check[i].pat; i++) { + if (match_pattern_list(version, check[i].pat, + strlen(check[i].pat), 0) == 1) { + debug("match: %s pat %s", version, check[i].pat); + datafellows = check[i].bugs; + return; + } + } + debug("no match: %s", version); +} + +#define SEP "," +int +proto_spec(const char *spec) +{ + char *s, *p, *q; + int ret = SSH_PROTO_UNKNOWN; + + if (spec == NULL) + return ret; + q = s = xstrdup(spec); + for ((p = strsep(&q, SEP)); p && *p != '\0'; (p = strsep(&q, SEP))) { + switch (atoi(p)) { + case 1: + if (ret == SSH_PROTO_UNKNOWN) + ret |= SSH_PROTO_1_PREFERRED; + ret |= SSH_PROTO_1; + break; + case 2: + ret |= SSH_PROTO_2; + break; + default: + log("ignoring bad proto spec: '%s'.", p); + break; + } + } + xfree(s); + return ret; +} + +char * +compat_cipher_proposal(char *cipher_prop) +{ + Buffer b; + char *orig_prop, *fix_ciphers; + char *cp, *tmp; + + if (!(datafellows & SSH_BUG_BIGENDIANAES)) + return(cipher_prop); + + buffer_init(&b); + tmp = orig_prop = xstrdup(cipher_prop); + while ((cp = strsep(&tmp, ",")) != NULL) { + if (strncmp(cp, "aes", 3) != 0) { + if (buffer_len(&b) > 0) + buffer_append(&b, ",", 1); + buffer_append(&b, cp, strlen(cp)); + } + } + buffer_append(&b, "\0", 1); + fix_ciphers = xstrdup(buffer_ptr(&b)); + buffer_free(&b); + xfree(orig_prop); + debug2("Original cipher proposal: %s", cipher_prop); + debug2("Compat cipher proposal: %s", fix_ciphers); + if (!*fix_ciphers) + fatal("No available ciphers found."); + + return(fix_ciphers); +} diff --git a/usr/src/cmd/ssh/libssh/common/compress.c b/usr/src/cmd/ssh/libssh/common/compress.c new file mode 100644 index 0000000000..6a4965c461 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/compress.c @@ -0,0 +1,162 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Interface to packet compression for ssh. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: compress.c,v 1.19 2002/03/18 17:31:54 provos Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "log.h" +#include "buffer.h" +#include "zlib.h" +#include "compress.h" + +z_stream incoming_stream; +z_stream outgoing_stream; +static int compress_init_send_called = 0; +static int compress_init_recv_called = 0; +static int inflate_failed = 0; +static int deflate_failed = 0; + +/* + * Initializes compression; level is compression level from 1 to 9 + * (as in gzip). + */ + +void +buffer_compress_init_send(int level) +{ + if (compress_init_send_called == 1) + deflateEnd(&outgoing_stream); + compress_init_send_called = 1; + debug("Enabling compression at level %d.", level); + if (level < 1 || level > 9) + fatal("Bad compression level %d.", level); + deflateInit(&outgoing_stream, level); +} +void +buffer_compress_init_recv(void) +{ + if (compress_init_recv_called == 1) + inflateEnd(&incoming_stream); + compress_init_recv_called = 1; + inflateInit(&incoming_stream); +} + +/* Frees any data structures allocated for compression. */ + +void +buffer_compress_uninit(void) +{ + debug("compress outgoing: raw data %lu, compressed %lu, factor %.2f", + outgoing_stream.total_in, outgoing_stream.total_out, + outgoing_stream.total_in == 0 ? 0.0 : + (double) outgoing_stream.total_out / outgoing_stream.total_in); + debug("compress incoming: raw data %lu, compressed %lu, factor %.2f", + incoming_stream.total_out, incoming_stream.total_in, + incoming_stream.total_out == 0 ? 0.0 : + (double) incoming_stream.total_in / incoming_stream.total_out); + if (compress_init_recv_called == 1 && inflate_failed == 0) + inflateEnd(&incoming_stream); + if (compress_init_send_called == 1 && deflate_failed == 0) + deflateEnd(&outgoing_stream); +} + +/* + * Compresses the contents of input_buffer into output_buffer. All packets + * compressed using this function will form a single compressed data stream; + * however, data will be flushed at the end of every call so that each + * output_buffer can be decompressed independently (but in the appropriate + * order since they together form a single compression stream) by the + * receiver. This appends the compressed data to the output buffer. + */ + +void +buffer_compress(Buffer * input_buffer, Buffer * output_buffer) +{ + u_char buf[4096]; + int status; + + /* This case is not handled below. */ + if (buffer_len(input_buffer) == 0) + return; + + /* Input is the contents of the input buffer. */ + outgoing_stream.next_in = buffer_ptr(input_buffer); + outgoing_stream.avail_in = buffer_len(input_buffer); + + /* Loop compressing until deflate() returns with avail_out != 0. */ + do { + /* Set up fixed-size output buffer. */ + outgoing_stream.next_out = buf; + outgoing_stream.avail_out = sizeof(buf); + + /* Compress as much data into the buffer as possible. */ + status = deflate(&outgoing_stream, Z_PARTIAL_FLUSH); + switch (status) { + case Z_OK: + /* Append compressed data to output_buffer. */ + buffer_append(output_buffer, buf, + sizeof(buf) - outgoing_stream.avail_out); + break; + default: + deflate_failed = 1; + fatal("buffer_compress: deflate returned %d", status); + /* NOTREACHED */ + } + } while (outgoing_stream.avail_out == 0); +} + +/* + * Uncompresses the contents of input_buffer into output_buffer. All packets + * uncompressed using this function will form a single compressed data + * stream; however, data will be flushed at the end of every call so that + * each output_buffer. This must be called for the same size units that the + * buffer_compress was called, and in the same order that buffers compressed + * with that. This appends the uncompressed data to the output buffer. + */ + +void +buffer_uncompress(Buffer * input_buffer, Buffer * output_buffer) +{ + u_char buf[4096]; + int status; + + incoming_stream.next_in = buffer_ptr(input_buffer); + incoming_stream.avail_in = buffer_len(input_buffer); + + for (;;) { + /* Set up fixed-size output buffer. */ + incoming_stream.next_out = buf; + incoming_stream.avail_out = sizeof(buf); + + status = inflate(&incoming_stream, Z_PARTIAL_FLUSH); + switch (status) { + case Z_OK: + buffer_append(output_buffer, buf, + sizeof(buf) - incoming_stream.avail_out); + break; + case Z_BUF_ERROR: + /* + * Comments in zlib.h say that we should keep calling + * inflate() until we get an error. This appears to + * be the error that we get. + */ + return; + default: + inflate_failed = 1; + fatal("buffer_uncompress: inflate returned %d", status); + /* NOTREACHED */ + } + } +} diff --git a/usr/src/cmd/ssh/libssh/common/crc32.c b/usr/src/cmd/ssh/libssh/common/crc32.c new file mode 100644 index 0000000000..213b7b8aa8 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/crc32.c @@ -0,0 +1,116 @@ +/* + * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or + * code or tables extracted from it, as desired without restriction. + * + * First, the polynomial itself and its table of feedback terms. The + * polynomial is + * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 + * + * Note that we take it "backwards" and put the highest-order term in + * the lowest-order bit. The X^32 term is "implied"; the LSB is the + * X^31 term, etc. The X^0 term (usually shown as "+1") results in + * the MSB being 1 + * + * Note that the usual hardware shift register implementation, which + * is what we're using (we're merely optimizing it by doing eight-bit + * chunks at a time) shifts bits into the lowest-order term. In our + * implementation, that means shifting towards the right. Why do we + * do it this way? Because the calculated CRC must be transmitted in + * order from highest-order term to lowest-order term. UARTs transmit + * characters in order from LSB to MSB. By storing the CRC this way + * we hand it to the UART in the order low-byte to high-byte; the UART + * sends each low-bit to hight-bit; and the result is transmission bit + * by bit from highest- to lowest-order term without requiring any bit + * shuffling on our part. Reception works similarly + * + * The feedback terms table consists of 256, 32-bit entries. Notes + * + * The table can be generated at runtime if desired; code to do so + * is shown later. It might not be obvious, but the feedback + * terms simply represent the results of eight shift/xor opera + * tions for all combinations of data and CRC register values + * + * The values must be right-shifted by eight bits by the "updcrc + * logic; the shift must be u_(bring in zeroes). On some + * hardware you could probably optimize the shift in assembler by + * using byte-swap instructions + * polynomial $edb88320 + */ + + +#include "includes.h" +RCSID("$OpenBSD: crc32.c,v 1.8 2000/12/19 23:17:56 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "crc32.h" + +static u_int crc32_tab[] = { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, + 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, + 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, + 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, + 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, + 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, + 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, + 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, + 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, + 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, + 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, + 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, + 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, + 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, + 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, + 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, + 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, + 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, + 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, + 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, + 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, + 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, + 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, + 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, + 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, + 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, + 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, + 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, + 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, + 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, + 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, + 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, + 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, + 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, + 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, + 0x2d02ef8d +}; + +/* Return a 32-bit CRC of the contents of the buffer. */ + +u_int +ssh_crc32(const u_char *s, u_int len) +{ + u_int i; + u_int crc32val; + + crc32val = 0; + for (i = 0; i < len; i ++) { + crc32val = crc32_tab[(crc32val ^ s[i]) & 0xff] ^ (crc32val >> 8); + } + return crc32val; +} diff --git a/usr/src/cmd/ssh/libssh/common/deattack.c b/usr/src/cmd/ssh/libssh/common/deattack.c new file mode 100644 index 0000000000..a5e5fde167 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/deattack.c @@ -0,0 +1,158 @@ +/* + * Cryptographic attack detector for ssh - source code + * + * Copyright (c) 1998 CORE SDI S.A., Buenos Aires, Argentina. + * + * All rights reserved. Redistribution and use in source and binary + * forms, with or without modification, are permitted provided that + * this copyright notice is retained. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES ARE DISCLAIMED. IN NO EVENT SHALL CORE SDI S.A. BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR + * CONSEQUENTIAL DAMAGES RESULTING FROM THE USE OR MISUSE OF THIS + * SOFTWARE. + * + * Ariel Futoransky <futo@core-sdi.com> + * <http://www.core-sdi.com> + */ + +#include "includes.h" +RCSID("$OpenBSD: deattack.c,v 1.18 2002/03/04 17:27:39 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "deattack.h" +#include "log.h" +#include "crc32.h" +#include "getput.h" +#include "xmalloc.h" +#include "deattack.h" + +/* SSH Constants */ +#define SSH_MAXBLOCKS (32 * 1024) +#define SSH_BLOCKSIZE (8) + +/* Hashing constants */ +#define HASH_MINSIZE (8 * 1024) +#define HASH_ENTRYSIZE (2) +#define HASH_FACTOR(x) ((x)*3/2) +#define HASH_UNUSEDCHAR (0xff) +#define HASH_UNUSED (0xffff) +#define HASH_IV (0xfffe) + +#define HASH_MINBLOCKS (7*SSH_BLOCKSIZE) + + +/* Hash function (Input keys are cipher results) */ +#define HASH(x) GET_32BIT(x) + +#define CMP(a, b) (memcmp(a, b, SSH_BLOCKSIZE)) + +static void +crc_update(u_int32_t *a, u_int32_t b) +{ + b ^= *a; + *a = ssh_crc32((u_char *) &b, sizeof(b)); +} + +/* detect if a block is used in a particular pattern */ +static int +check_crc(u_char *S, u_char *buf, u_int32_t len, + u_char *IV) +{ + u_int32_t crc; + u_char *c; + + crc = 0; + if (IV && !CMP(S, IV)) { + crc_update(&crc, 1); + crc_update(&crc, 0); + } + for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) { + if (!CMP(S, c)) { + crc_update(&crc, 1); + crc_update(&crc, 0); + } else { + crc_update(&crc, 0); + crc_update(&crc, 0); + } + } + return (crc == 0); +} + + +/* Detect a crc32 compensation attack on a packet */ +int +detect_attack(u_char *buf, u_int32_t len, u_char *IV) +{ + static u_int16_t *h = (u_int16_t *) NULL; + static u_int32_t n = HASH_MINSIZE / HASH_ENTRYSIZE; + u_int32_t i, j; + u_int32_t l; + u_char *c; + u_char *d; + + if (len > (SSH_MAXBLOCKS * SSH_BLOCKSIZE) || + len % SSH_BLOCKSIZE != 0) { + fatal("detect_attack: bad length %d", len); + } + for (l = n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2) + ; + + if (h == NULL) { + debug("Installing crc compensation attack detector."); + n = l; + h = (u_int16_t *) xmalloc(n * HASH_ENTRYSIZE); + } else { + if (l > n) { + n = l; + h = (u_int16_t *) xrealloc(h, n * HASH_ENTRYSIZE); + } + } + + if (len <= HASH_MINBLOCKS) { + for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) { + if (IV && (!CMP(c, IV))) { + if ((check_crc(c, buf, len, IV))) + return (DEATTACK_DETECTED); + else + break; + } + for (d = buf; d < c; d += SSH_BLOCKSIZE) { + if (!CMP(c, d)) { + if ((check_crc(c, buf, len, IV))) + return (DEATTACK_DETECTED); + else + break; + } + } + } + return (DEATTACK_OK); + } + memset(h, HASH_UNUSEDCHAR, n * HASH_ENTRYSIZE); + + if (IV) + h[HASH(IV) & (n - 1)] = HASH_IV; + + for (c = buf, j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) { + for (i = HASH(c) & (n - 1); h[i] != HASH_UNUSED; + i = (i + 1) & (n - 1)) { + if (h[i] == HASH_IV) { + if (!CMP(c, IV)) { + if (check_crc(c, buf, len, IV)) + return (DEATTACK_DETECTED); + else + break; + } + } else if (!CMP(c, buf + h[i] * SSH_BLOCKSIZE)) { + if (check_crc(c, buf, len, IV)) + return (DEATTACK_DETECTED); + else + break; + } + } + h[i] = j; + } + return (DEATTACK_OK); +} diff --git a/usr/src/cmd/ssh/libssh/common/dh.c b/usr/src/cmd/ssh/libssh/common/dh.c new file mode 100644 index 0000000000..f6643a09af --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/dh.c @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2000 Niels Provos. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: dh.c,v 1.22 2002/06/27 08:49:44 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" + +#include <openssl/bn.h> +#include <openssl/dh.h> +#include <openssl/evp.h> + +#include "buffer.h" +#include "cipher.h" +#include "kex.h" +#include "dh.h" +#include "pathnames.h" +#include "log.h" +#include "misc.h" + +static int +parse_prime(int linenum, char *line, struct dhgroup *dhg) +{ + char *cp, *arg; + char *strsize, *gen, *prime; + + cp = line; + arg = strdelim(&cp); + /* Ignore leading whitespace */ + if (*arg == '\0') + arg = strdelim(&cp); + if (!arg || !*arg || *arg == '#') + return 0; + + /* time */ + if (cp == NULL || *arg == '\0') + goto fail; + arg = strsep(&cp, " "); /* type */ + if (cp == NULL || *arg == '\0') + goto fail; + arg = strsep(&cp, " "); /* tests */ + if (cp == NULL || *arg == '\0') + goto fail; + arg = strsep(&cp, " "); /* tries */ + if (cp == NULL || *arg == '\0') + goto fail; + strsize = strsep(&cp, " "); /* size */ + if (cp == NULL || *strsize == '\0' || + (dhg->size = atoi(strsize)) == 0) + goto fail; + /* The whole group is one bit larger */ + dhg->size++; + gen = strsep(&cp, " "); /* gen */ + if (cp == NULL || *gen == '\0') + goto fail; + prime = strsep(&cp, " "); /* prime */ + if (cp != NULL || *prime == '\0') + goto fail; + + if ((dhg->g = BN_new()) == NULL) + fatal("parse_prime: BN_new failed"); + if ((dhg->p = BN_new()) == NULL) + fatal("parse_prime: BN_new failed"); + if (BN_hex2bn(&dhg->g, gen) == 0) + goto failclean; + + if (BN_hex2bn(&dhg->p, prime) == 0) + goto failclean; + + if (BN_num_bits(dhg->p) != dhg->size) + goto failclean; + + return (1); + + failclean: + BN_clear_free(dhg->g); + BN_clear_free(dhg->p); + fail: + error("Bad prime description in line %d", linenum); + return (0); +} + +DH * +choose_dh(int min, int wantbits, int max) +{ + FILE *f; + char line[2048]; + int best, bestcount, which; + int linenum; + struct dhgroup dhg; + + if ((f = fopen(_PATH_DH_MODULI, "r")) == NULL && + (f = fopen(_PATH_DH_PRIMES, "r")) == NULL) { + log("WARNING: %s does not exist, using old modulus", _PATH_DH_MODULI); + return (dh_new_group1()); + } + + linenum = 0; + best = bestcount = 0; + while (fgets(line, sizeof(line), f)) { + linenum++; + if (!parse_prime(linenum, line, &dhg)) + continue; + BN_clear_free(dhg.g); + BN_clear_free(dhg.p); + + if (dhg.size > max || dhg.size < min) + continue; + + if ((dhg.size > wantbits && dhg.size < best) || + (dhg.size > best && best < wantbits)) { + best = dhg.size; + bestcount = 0; + } + if (dhg.size == best) + bestcount++; + } + rewind(f); + + if (bestcount == 0) { + fclose(f); + log("WARNING: no suitable primes in %s", _PATH_DH_PRIMES); + return (NULL); + } + + linenum = 0; + which = arc4random() % bestcount; + while (fgets(line, sizeof(line), f)) { + if (!parse_prime(linenum, line, &dhg)) + continue; + if ((dhg.size > max || dhg.size < min) || + dhg.size != best || + linenum++ != which) { + BN_clear_free(dhg.g); + BN_clear_free(dhg.p); + continue; + } + break; + } + fclose(f); + if (linenum != which+1) + fatal("WARNING: line %d disappeared in %s, giving up", + which, _PATH_DH_PRIMES); + + return (dh_new_group(dhg.g, dhg.p)); +} + +/* diffie-hellman-group1-sha1 */ + +int +dh_pub_is_valid(DH *dh, BIGNUM *dh_pub) +{ + int i; + int n = BN_num_bits(dh_pub); + int bits_set = 0; + + if (dh_pub->neg) { + log("invalid public DH value: negativ"); + return 0; + } + for (i = 0; i <= n; i++) + if (BN_is_bit_set(dh_pub, i)) + bits_set++; + debug("bits set: %d/%d", bits_set, BN_num_bits(dh->p)); + + /* if g==2 and bits_set==1 then computing log_g(dh_pub) is trivial */ + if (bits_set > 1 && (BN_cmp(dh_pub, dh->p) == -1)) + return 1; + log("invalid public DH value (%d/%d)", bits_set, BN_num_bits(dh->p)); + return 0; +} + +void +dh_gen_key(DH *dh, int need) +{ + int i, bits_set = 0, tries = 0; + + if (dh->p == NULL) + fatal("dh_gen_key: dh->p == NULL"); + if (2*need >= BN_num_bits(dh->p)) + fatal("dh_gen_key: group too small: %d (2*need %d)", + BN_num_bits(dh->p), 2*need); + do { + if (dh->priv_key != NULL) + BN_clear_free(dh->priv_key); + if ((dh->priv_key = BN_new()) == NULL) + fatal("dh_gen_key: BN_new failed"); + /* generate a 2*need bits random private exponent */ + if (!BN_rand(dh->priv_key, 2*need, 0, 0)) + fatal("dh_gen_key: BN_rand failed"); + if (DH_generate_key(dh) == 0) + fatal("DH_generate_key"); + for (i = 0; i <= BN_num_bits(dh->priv_key); i++) + if (BN_is_bit_set(dh->priv_key, i)) + bits_set++; + debug("dh_gen_key: priv key bits set: %d/%d", + bits_set, BN_num_bits(dh->priv_key)); + if (tries++ > 10) + fatal("dh_gen_key: too many bad keys: giving up"); + } while (!dh_pub_is_valid(dh, dh->pub_key)); +} + +DH * +dh_new_group_asc(const char *gen, const char *modulus) +{ + DH *dh; + + if ((dh = DH_new()) == NULL) + fatal("dh_new_group_asc: DH_new"); + + if (BN_hex2bn(&dh->p, modulus) == 0) + fatal("BN_hex2bn p"); + if (BN_hex2bn(&dh->g, gen) == 0) + fatal("BN_hex2bn g"); + + return (dh); +} + +/* + * This just returns the group, we still need to generate the exchange + * value. + */ + +DH * +dh_new_group(BIGNUM *gen, BIGNUM *modulus) +{ + DH *dh; + + if ((dh = DH_new()) == NULL) + fatal("dh_new_group: DH_new"); + dh->p = modulus; + dh->g = gen; + + return (dh); +} + +DH * +dh_new_group1(void) +{ + static char *gen = "2", *group1 = + "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" + "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" + "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" + "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" + "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381" + "FFFFFFFF" "FFFFFFFF"; + + return (dh_new_group_asc(gen, group1)); +} + +/* + * Estimates the group order for a Diffie-Hellman group that has an + * attack complexity approximately the same as O(2**bits). Estimate + * with: O(exp(1.9223 * (ln q)^(1/3) (ln ln q)^(2/3))) + */ + +int +dh_estimate(int bits) +{ + + if (bits < 64) + return (512); /* O(2**63) */ + if (bits < 128) + return (1024); /* O(2**86) */ + if (bits < 192) + return (2048); /* O(2**116) */ + return (4096); /* O(2**156) */ +} diff --git a/usr/src/cmd/ssh/libssh/common/dispatch.c b/usr/src/cmd/ssh/libssh/common/dispatch.c new file mode 100644 index 0000000000..f2bf9b6847 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/dispatch.c @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "includes.h" +RCSID("$OpenBSD: dispatch.c,v 1.15 2002/01/11 13:39:36 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ssh1.h" +#include "ssh2.h" +#include "log.h" +#include "dispatch.h" +#include "packet.h" +#include "compat.h" + +#define DISPATCH_MIN 0 +#define DISPATCH_MAX 255 + +dispatch_fn *dispatch[DISPATCH_MAX]; + +void +dispatch_protocol_error(int type, u_int32_t seq, void *ctxt) +{ + log("dispatch_protocol_error: type %d seq %u", type, seq); + if (!compat20) + fatal("protocol error"); + packet_start(SSH2_MSG_UNIMPLEMENTED); + packet_put_int(seq); + packet_send(); + packet_write_wait(); +} +void +dispatch_protocol_ignore(int type, u_int32_t seq, void *ctxt) +{ + log("dispatch_protocol_ignore: type %d seq %u", type, seq); +} +void +dispatch_init(dispatch_fn *dflt) +{ + u_int i; + for (i = 0; i < DISPATCH_MAX; i++) + dispatch[i] = dflt; +} +void +dispatch_range(u_int from, u_int to, dispatch_fn *fn) +{ + u_int i; + + for (i = from; i <= to; i++) { + if (i >= DISPATCH_MAX) + break; + dispatch[i] = fn; + } +} +void +dispatch_set(int type, dispatch_fn *fn) +{ + dispatch[type] = fn; +} +void +dispatch_run(int mode, int *done, void *ctxt) +{ + for (;;) { + int type; + u_int32_t seqnr; + + if (mode == DISPATCH_BLOCK) { + type = packet_read_seqnr(&seqnr); + } else { + type = packet_read_poll_seqnr(&seqnr); + if (type == SSH_MSG_NONE) + return; + } + if (type > 0 && type < DISPATCH_MAX && dispatch[type] != NULL) + (*dispatch[type])(type, seqnr, ctxt); + else + packet_disconnect("protocol error: rcvd type %d", type); + if (done != NULL && *done) + return; + } +} diff --git a/usr/src/cmd/ssh/libssh/common/entropy.c b/usr/src/cmd/ssh/libssh/common/entropy.c new file mode 100644 index 0000000000..c661b74496 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/entropy.c @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2001 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" + +#include <openssl/rand.h> +#include <openssl/crypto.h> + +#include "ssh.h" +#include "misc.h" +#include "xmalloc.h" +#include "atomicio.h" +#include "pathnames.h" +#include "log.h" + +/* + * Portable OpenSSH PRNG seeding: + * If OpenSSL has not "internally seeded" itself (e.g. pulled data from + * /dev/random), then we execute a "ssh-rand-helper" program which + * collects entropy and writes it to stdout. The child program must + * write at least RANDOM_SEED_SIZE bytes. The child is run with stderr + * attached, so error/debugging output should be visible. + * + * XXX: we should tell the child how many bytes we need. + */ + +RCSID("$Id: entropy.c,v 1.44 2002/06/09 19:41:48 mouring Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#ifndef OPENSSL_PRNG_ONLY +#define RANDOM_SEED_SIZE 48 +static uid_t original_uid, original_euid; +#endif + +void +seed_rng(void) +{ +#ifndef OPENSSL_PRNG_ONLY + int devnull; + int p[2]; + pid_t pid; + int ret; + unsigned char buf[RANDOM_SEED_SIZE]; + mysig_t old_sigchld; + + if (RAND_status() == 1) { + debug3("RNG is ready, skipping seeding"); + return; + } + + debug3("Seeding PRNG from %s", SSH_RAND_HELPER); + + if ((devnull = open("/dev/null", O_RDWR)) == -1) + fatal("Couldn't open /dev/null: %s", strerror(errno)); + if (pipe(p) == -1) + fatal("pipe: %s", strerror(errno)); + + old_sigchld = mysignal(SIGCHLD, SIG_DFL); + if ((pid = fork()) == -1) + fatal("Couldn't fork: %s", strerror(errno)); + if (pid == 0) { + dup2(devnull, STDIN_FILENO); + dup2(p[1], STDOUT_FILENO); + /* Keep stderr open for errors */ + close(p[0]); + close(p[1]); + close(devnull); + + if (original_uid != original_euid && + ( seteuid(getuid()) == -1 || + setuid(original_uid) == -1) ) { + fprintf(stderr, "(rand child) setuid(%d): %s\n", + original_uid, strerror(errno)); + _exit(1); + } + + execl(SSH_RAND_HELPER, "ssh-rand-helper", NULL); + fprintf(stderr, "(rand child) Couldn't exec '%s': %s\n", + SSH_RAND_HELPER, strerror(errno)); + _exit(1); + } + + close(devnull); + close(p[1]); + + memset(buf, '\0', sizeof(buf)); + ret = atomicio(read, p[0], buf, sizeof(buf)); + if (ret == -1) + fatal("Couldn't read from ssh-rand-helper: %s", + strerror(errno)); + if (ret != sizeof(buf)) + fatal("ssh-rand-helper child produced insufficient data"); + + close(p[0]); + + if (waitpid(pid, &ret, 0) == -1) + fatal("Couldn't wait for ssh-rand-helper completion: %s", + strerror(errno)); + mysignal(SIGCHLD, old_sigchld); + + /* We don't mind if the child exits upon a SIGPIPE */ + if (!WIFEXITED(ret) && + (!WIFSIGNALED(ret) || WTERMSIG(ret) != SIGPIPE)) + fatal("ssh-rand-helper terminated abnormally"); + if (WEXITSTATUS(ret) != 0) + fatal("ssh-rand-helper exit with exit status %d", ret); + + RAND_add(buf, sizeof(buf), sizeof(buf)); + memset(buf, '\0', sizeof(buf)); + +#endif /* OPENSSL_PRNG_ONLY */ + if (RAND_status() != 1) + fatal("PRNG is not seeded"); +} + +void +init_rng(void) +{ + /* + * OpenSSL version numbers: MNNFFPPS: major minor fix patch status + * We match major, minor, fix and status (not patch) + */ + if ((SSLeay() ^ OPENSSL_VERSION_NUMBER) & ~0xff0L) + fatal("OpenSSL version mismatch. Built against %lx, you " + "have %lx", OPENSSL_VERSION_NUMBER, SSLeay()); + +#ifndef OPENSSL_PRNG_ONLY + if ((original_uid = getuid()) == -1) + fatal("getuid: %s", strerror(errno)); + if ((original_euid = geteuid()) == -1) + fatal("geteuid: %s", strerror(errno)); +#endif +} + diff --git a/usr/src/cmd/ssh/libssh/common/fatal.c b/usr/src/cmd/ssh/libssh/common/fatal.c new file mode 100644 index 0000000000..0b5038f365 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/fatal.c @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2002 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: fatal.c,v 1.1 2002/02/22 12:20:34 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "log.h" + +/* Fatal messages. This function never returns. */ + +void +fatal(const char *fmt,...) +{ + va_list args; + va_start(args, fmt); + do_log(SYSLOG_LEVEL_FATAL, fmt, args); + va_end(args); + fatal_cleanup(); +} diff --git a/usr/src/cmd/ssh/libssh/common/g11n.c b/usr/src/cmd/ssh/libssh/common/g11n.c new file mode 100644 index 0000000000..52e5ddf4d7 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/g11n.c @@ -0,0 +1,1024 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2005 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <errno.h> +#include <locale.h> +#include <langinfo.h> +#include <iconv.h> +#include <ctype.h> +#include <strings.h> +#include <string.h> +#include <stdio.h> +#include <stdlib.h> +#include "includes.h" +#include "xmalloc.h" +#include "xlist.h" + +#ifdef MIN +#undef MIN +#endif /* MIN */ + +#define MIN(x, y) ((x) < (y) ? (x) : (y)) + +#define LOCALE_PATH "/usr/bin/locale" + +#define LANGTAG_MAX 5 /* two-char country code, '-' and two-char region code */ + +static u_char * do_iconv(iconv_t cd, u_int *mul_ptr, + const void *buf, u_int len, + u_int *outlen, int *err, + u_char **err_str); + +static int locale_cmp(const void *d1, const void *d2); +static char *g11n_locale2langtag(char *locale); + +u_int +g11n_validate_ascii(const char *str, u_int len, u_char **error_str); + +u_int +g11n_validate_utf8(const u_char *str, u_int len, u_char **error_str); + +static +char * +g11n_locale2langtag(char *locale) +{ + char *langtag; + + /* base cases */ + if (!locale || !*locale) return NULL; + + if (strcmp(locale, "POSIX") == 0 || + strcmp(locale, "C") == 0) return "i-default"; + + /* Punt for language codes which are not exactly 2 letters */ + if (strlen(locale) < 2 || + !isalpha(locale[0]) || + !isalpha(locale[1]) || + (locale[2] != '\0' && + locale[2] != '_' && + locale[2] != '.' && + locale[2] != '@')) + return NULL; + + + /* We have a primary language sub-tag */ + langtag = (char *) xmalloc(LANGTAG_MAX + 1); + + strncpy(langtag, locale, 2); + langtag[2] = '\0'; + + /* Do we have country sub-tag? */ + if (locale[2] == '_') { + if (strlen(locale) < 5 || + !isalpha(locale[3]) || + !isalpha(locale[4]) || + (locale[5] != '\0' && (locale[5] != '.' && locale[5] != '@'))) { + return langtag; + } + + /* yes, we do */ + /* if (snprintf(langtag, 6, "%s-%s,%s", lang_subtag, + country_subtag, langtag) == 8) */ + if (snprintf(langtag, 6, "%.*s-%.*s", 2, locale, + 2, locale+3) == 5) + return langtag; + } + + /* In all other cases we just use the primary language sub-tag */ + return langtag; +} + +u_int +g11n_langtag_is_default(char *langtag) +{ + return (strcmp(langtag, "i-default") == 0); +} + +/* + * This lang tag / locale matching function works only for two-character + * language primary sub-tags and two-character country sub-tags. + */ +u_int +g11n_langtag_matches_locale(char *langtag, char *locale) +{ + /* Match "i-default" to the process' current locale if possible */ + if (g11n_langtag_is_default(langtag)) { + if (strcasecmp(locale, "POSIX") == 0 || + strcasecmp(locale, "C") == 0) + return 1; + else + return 0; + } + + /* locale must be at least 2 chars long and the lang part must be + * exactly two characters */ + if (strlen(locale) < 2 || + (!isalpha(locale[0]) || !isalpha(locale[1]) || + (locale[2] != '\0' && locale[2] != '_' && locale[2] != '.' && locale[2] != '@'))) + return 0; + + /* same thing with the langtag */ + if (strlen(langtag) < 2 || + (!isalpha(langtag[0]) || !isalpha(langtag[1]) || + (langtag[2] != '\0' && langtag[2] != '-'))) + return 0; + + /* primary language sub-tag and the locale's language part must match */ + if (strncasecmp(langtag, locale, 2) != 0) + return 0; + + /* primary language sub-tag and the locale's language match, now + * fuzzy check country part */ + + /* neither langtag nor locale have more than one component */ + if (langtag[2] == '\0' && + (locale[2] == '\0' || locale[2] == '.' || locale[2] == '@')) + return 2; + + /* langtag has only one sub-tag... */ + if (langtag[2] == '\0') + return 1; + + /* locale has no country code... */ + if (locale[2] == '\0' || locale[2] == '.' || locale[2] == '@') + return 1; + + /* langtag has more than one subtag and the locale has a country code */ + + /* ignore second subtag if not two chars */ + if (strlen(langtag) < 5) + return 1; + + if (!isalpha(langtag[3]) || !isalpha(langtag[4]) || + (langtag[5] != '\0' && langtag[5] != '-')) + return 1; + + /* ignore rest of locale if there is no two-character country part */ + if (strlen(locale) < 5) + return 1; + + if (locale[2] != '_' || !isalpha(locale[3]) || !isalpha(locale[4]) || + (locale[5] != '\0' && locale[5] != '.' && locale[5] != '@')) + return 1; + + /* if the country part matches, return 2 */ + if (strncasecmp(&langtag[3], &locale[3], 2) == 0) + return 2; + + return 1; +} + +char * +g11n_getlocale() +{ + /* We have one text domain - always set it */ + (void) textdomain(TEXT_DOMAIN); + + /* If the locale is not set, set it from the env vars */ + if (!setlocale(LC_CTYPE, NULL)) + (void) setlocale(LC_CTYPE, ""); + + return setlocale(LC_CTYPE, NULL); +} + +void +g11n_setlocale(int category, const char *locale) +{ + char *curr; + + /* We have one text domain - always set it */ + (void) textdomain(TEXT_DOMAIN); + + if (!locale) + return; + + if (*locale && ((curr = setlocale(category, NULL))) && + strcmp(curr, locale) == 0) + return; + + /* + * If <category> is bogus, setlocale() will do nothing and will + * return NULL. + */ + if (!setlocale(category, locale)) + return; + + /* If setting the locale from the environment, then we're done */ + if (!*locale) + return; + + /* + * If setting a locale from the <locale> argument, then set the + * related env vars. + */ + switch (category) { + case LC_ALL: + setenv("LANG", locale, 1); + setenv("LC_ALL", locale, 1); + break; + case LC_CTYPE: + setenv("LC_CTYPE", locale, 1); + break; + case LC_NUMERIC: + setenv("LC_NUMERIC", locale, 1); + break; + case LC_TIME: + setenv("LC_TIME", locale, 1); + break; + case LC_COLLATE: + setenv("LC_COLLATE", locale, 1); + break; + case LC_MONETARY: + setenv("LC_MONETARY", locale, 1); + break; + case LC_MESSAGES: + setenv("LC_MESSAGES", locale, 1); + break; + } + return; +} + +char ** +g11n_getlocales() +{ + FILE *locale_out; + u_int n_elems, list_size, long_line = 0; + char **list; + char locale[64]; /* 64 bytes is plenty for locale names */ + + if ((locale_out = popen(LOCALE_PATH " -a", "r")) == NULL) { + return NULL; + } + + /* + * Start with enough room for 65 locales - that's a lot fewer than + * all the locales available for installation, but a lot more than + * what most users will need and install + */ + n_elems=0; + list_size=192; + list = (char **) xmalloc(sizeof(char *) * (list_size + 1)); + memset(list, 0, sizeof(char *) * (list_size + 1)); + + while (fgets(locale, sizeof(locale), locale_out)) { + /* skip long locale names (if any) */ + if (!strchr(locale, '\n')) { + long_line = 1; + continue; + } + else if (long_line) { + long_line = 0; + continue; + } + if (strncmp(locale, "iso_8859", 8) == 0) + continue; /* ignore locale names like "iso_8859-1" */ + + if (n_elems == list_size) { + list_size *= 2; + list = (char **) xrealloc((void *) list, (list_size + 1) * sizeof(char *)); + memset(&list[n_elems+1], 0, sizeof(char *) * (list_size - n_elems + 1)); + } + + *(strchr(locale, '\n')) = '\0'; /* remove the trailing \n */ + + list[n_elems++] = xstrdup(locale); + } + list[n_elems] = NULL; + (void) pclose(locale_out); + + qsort(list, n_elems - 1, sizeof(char *), locale_cmp); + return list; +} + +char * +g11n_getlangs() +{ + char *locale; + + if (getenv("SSH_LANGS")) + return xstrdup(getenv("SSH_LANGS")); + + locale = g11n_getlocale(); + + if (!locale || !*locale) + return xstrdup("i-default"); + + return g11n_locale2langtag(locale); +} + +char * +g11n_locales2langs(char **locale_set) +{ + char **p, **r, **q; + char *langtag; + int locales, skip; + + for (locales = 0, p = locale_set ; p && *p ; p++) + locales++; + + r = (char **) xmalloc((locales + 1) * sizeof(char *)); + memset(r, 0, (locales + 1) * sizeof(char *)); + + for (p = locale_set ; p && *p && ((p - locale_set) <= locales); p++) { + skip = 0; + if ((langtag = g11n_locale2langtag(*p)) == NULL) + continue; + for (q = r ; (q - r) < locales ; q++) { + if (!*q) break; + if (*q && strcmp(*q, langtag) == 0) + skip = 1; + } + if (!skip) + *(q++) = langtag; + *q = NULL; + } + return xjoin(r, ','); +} + +static +int +sortcmp(const void *d1, const void *d2) +{ + char *s1 = *(char **)d1; + char *s2 = *(char **)d2; + + return strcmp(s1, s2); +} + +int +g11n_langtag_match(char *langtag1, char *langtag2) +{ + int len1, len2; + char c1, c2; + + len1 = (strchr(langtag1, '-')) ? + (strchr(langtag1, '-') - langtag1) + : strlen(langtag1); + + len2 = (strchr(langtag2, '-')) ? + (strchr(langtag2, '-') - langtag2) + : strlen(langtag2); + + /* no match */ + if (len1 != len2 || + strncmp(langtag1, langtag2, len1) != 0) + return 0; + + c1 = *(langtag1 + len1); + c2 = *(langtag2 + len2); + + /* no country sub-tags - exact match */ + if (c1 == '\0' && c2 == '\0') + return 2; + + /* one langtag has a country sub-tag, the other doesn't */ + if (c1 == '\0' || c2 == '\0') + return 1; + + /* can't happen - both langtags have a country sub-tag */ + if (c1 != '-' || c2 != '-') + return 1; + + /* compare country subtags */ + langtag1 = langtag1 + len1 + 1; + langtag2 = langtag2 + len2 + 1; + + len1 = (strchr(langtag1, '-')) ? + (strchr(langtag1, '-') - langtag1) + : strlen(langtag1); + + len2 = (strchr(langtag2, '-')) ? + (strchr(langtag2, '-') - langtag2) + : strlen(langtag2); + + if (len1 != len2 || + strncmp(langtag1, langtag2, len1) != 0) + return 1; + + /* country tags matched - exact match */ + return 2; +} + +char * +g11n_langtag_set_intersect(char *set1, char *set2) +{ + char **list1, **list2, **list3, **p, **q, **r; + char *set3, *lang_subtag; + u_int n1, n2, n3; + u_int do_append; + + list1 = xsplit(set1, ','); + list2 = xsplit(set2, ','); + for (n1 = 0, p = list1 ; p && *p ; p++, n1++) ; + for (n2 = 0, p = list2 ; p && *p ; p++, n2++) ; + + list3 = (char **) xmalloc(sizeof(char *) * (n1 + n2 + 1)); + *list3 = NULL; + + /* we must not sort the user langtags - sorting or not the server's + * should not affect the outcome + */ + qsort(list2, n2, sizeof(char *), sortcmp); + + for (n3 = 0, p = list1 ; p && *p ; p++) { + do_append = 0; + for (q = list2 ; q && *q ; q++) { + if (g11n_langtag_match(*p, *q) != 2) continue; + /* append element */ + for (r = list3; (r - list3) <= (n1 + n2) ; r++) { + do_append = 1; + if (!*r) break; + if (strcmp(*p, *r) == 0) { + do_append = 0; + break; + } + } + if (do_append && n3 <= (n1 + n2)) { + list3[n3++] = xstrdup(*p); + list3[n3] = NULL; + } + } + } + + for (p = list1 ; p && *p ; p++) { + do_append = 0; + for (q = list2 ; q && *q ; q++) { + if (g11n_langtag_match(*p, *q) != 1) continue; + /* append element */ + lang_subtag = xstrdup(*p); + if (strchr(lang_subtag, '-')) + *(strchr(lang_subtag, '-')) = '\0'; + for (r = list3; (r - list3) <= (n1 + n2) ; r++) { + do_append = 1; + if (!*r) break; + if (strcmp(lang_subtag, *r) == 0) { + do_append = 0; + break; + } + } + if (do_append && n3 <= (n1 + n2)) { + list3[n3++] = lang_subtag; + list3[n3] = NULL; + } + else + xfree(lang_subtag); + } + } + + set3 = xjoin(list3, ','); + xfree_split_list(list1); + xfree_split_list(list2); + xfree_split_list(list3); + + return set3; +} + +char * +g11n_clnt_langtag_negotiate(char *clnt_langtags, char *srvr_langtags) +{ + char *list, *result; + char **xlist; + + /* g11n_langtag_set_intersect uses xmalloc - should not return NULL */ + list = g11n_langtag_set_intersect(clnt_langtags, srvr_langtags); + + if (!list) + return NULL; + + xlist = xsplit(list, ','); + + xfree(list); + + if (!xlist || !*xlist) + return NULL; + + result = xstrdup(*xlist); + + xfree_split_list(xlist); + + return result; +} + +/* + * Compare locales, preferring UTF-8 codesets to others, otherwise doing + * a stright strcmp() + */ +static +int +locale_cmp(const void *d1, const void *d2) +{ + char *dot_ptr; + char *s1 = *(char **)d1; + char *s2 = *(char **)d2; + int s1_is_utf8 = 0; + int s2_is_utf8 = 0; + + /* check if s1 is a UTF-8 locale */ + if (((dot_ptr = strchr((char *) s1, '.')) != NULL) && (*dot_ptr != '\0') && + (strncmp(dot_ptr+1, "UTF-8", 5) == 0) && + (*(dot_ptr+6) == '\0' || *(dot_ptr+6) == '@')) { + s1_is_utf8++; + } + /* check if s2 is a UTF-8 locale */ + if (((dot_ptr = strchr((char *) s2, '.')) != NULL) && (*dot_ptr != '\0') && + (strncmp(dot_ptr+1, "UTF-8", 5) == 0) && + (*(dot_ptr+6) == '\0' || *(dot_ptr+6) == '@')) { + s2_is_utf8++; + } + + /* prefer UTF-8 locales */ + if (s1_is_utf8 && !s2_is_utf8) + return -1; + + if (s2_is_utf8 && !s1_is_utf8) + return 1; + + /* prefer any locale over the default locales */ + if (strcmp(s1, "C") == 0 || + strcmp(s1, "POSIX") == 0 || + strcmp(s1, "common") == 0) + if (strcmp(s2, "C") != 0 && + strcmp(s2, "POSIX") != 0 && + strcmp(s2, "common") != 0) + return 1; + + if (strcmp(s2, "C") == 0 || + strcmp(s2, "POSIX") == 0 || + strcmp(s2, "common") == 0) + if (strcmp(s1, "C") != 0 && + strcmp(s1, "POSIX") != 0 && + strcmp(s1, "common") != 0) + return -1; + + return strcmp(s1, s2); +} + + +char ** +g11n_langtag_set_locale_set_intersect(char *langtag_set, + char **locale_set) +{ + char **langtag_list, **result, **p, **q, **r; + char *s; + u_int do_append, n_langtags, n_locales, n_results, max_results; + + /* Count lang tags and locales */ + for (n_locales = 0, p = locale_set ; p && *p ; p++) n_locales++; + n_langtags = ((s = langtag_set) != NULL && *s && *s != ',') ? 1 : 0; + for ( ; s = strchr(s, ',') ; s++, n_langtags++) ; + /* + while ((s = strchr(s, ','))) { + n_langtags++; + s++; + } + */ + + qsort(locale_set, n_locales, sizeof(char *), locale_cmp); + + langtag_list = xsplit(langtag_set, ','); + for ( n_langtags = 0, p = langtag_list ; p && *p ; p++, n_langtags++); + + max_results = MIN(n_locales, n_langtags) * 2; + result = (char **) xmalloc(sizeof(char *) * (max_results + 1)); + *result = NULL; + n_results = 0; + + /* More specific matches first */ + for (p = langtag_list ; p && *p ; p++) { + do_append = 0; + for (q = locale_set ; q && *q ; q++) { + if (g11n_langtag_matches_locale(*p, *q) == 2) { + do_append = 1; + for (r = result ; (r - result) <= MIN(n_locales, n_langtags) ; r++) { + if (!*r) break; + if (strcmp(*q, *r) == 0) { + do_append = 0; + break; + } + } + if (do_append && n_results < max_results) { + result[n_results++] = xstrdup(*q); + result[n_results] = NULL; + } + break; + } + } + } + + for (p = langtag_list ; p && *p ; p++) { + do_append = 0; + for (q = locale_set ; q && *q ; q++) { + if (g11n_langtag_matches_locale(*p, *q) == 1) { + do_append = 1; + for (r = result ; (r - result) <= MIN(n_locales, n_langtags) ; r++) { + if (!*r) break; + if (strcmp(*q, *r) == 0) { + do_append = 0; + break; + } + } + if (do_append && n_results < max_results) { + result[n_results++] = xstrdup(*q); + result[n_results] = NULL; + } + break; + } + } + } + xfree_split_list(langtag_list); + + return result; +} + +char * +g11n_srvr_locale_negotiate(char *clnt_langtags, char **srvr_locales) +{ + char **results, *result = NULL; + + if ((results = g11n_langtag_set_locale_set_intersect(clnt_langtags, + srvr_locales ? srvr_locales : g11n_getlocales())) == NULL) + return NULL; + + if (*results != NULL) + result = xstrdup(*results); + + xfree_split_list(results); + + return result; +} + + +/* + * Functions for validating ASCII and UTF-8 strings + * + * The error_str parameter is an optional pointer to a char variable + * where to store a string suitable for use with error() or fatal() or + * friends. + * + * The return value is 0 if success, EILSEQ or EINVAL. + * + */ + +u_int +g11n_validate_ascii(const char *str, u_int len, u_char **error_str) +{ + u_char *p; + + for (p = (u_char *) str ; p && *p && (!(*p & 0x80)) ; p++) ; + + if (len && ((p - (u_char *) str) != len)) { + return EILSEQ; + } + return 0; +} + +u_int +g11n_validate_utf8(const u_char *str, u_int len, u_char **error_str) +{ + u_char *p; + u_int c, l; + + if (len == 0) len = strlen((const char *)str); + + for (p = (u_char *) str ; p && (p - str < len) && *p ; ) { + /* 8-bit chars begin a UTF-8 sequence */ + if (*p & 0x80) { + /* Get sequence length and sanity check first byte */ + if (*p < 0xc0) + return EILSEQ; + else if (*p < 0xe0) + l=2; + else if (*p < 0xf0) + l=3; + else if (*p < 0xf8) + l=4; + else if (*p < 0xfc) + l=5; + else if (*p < 0xfe) + l=6; + else + return EILSEQ; + + if ((p + l - str) >= len) + return EILSEQ; + + /* overlong detection - build codepoint */ + c = *p & 0x3f; + c = c << (6 * (l-1)); /* shift c bits from first byte */ + + if (l > 1) { + if (*(p+1) && ((*(p+1) & 0xc0) == 0x80)) + c = c | ((*(p+1) & 0x3f) << (6 * (l-2))); + else + return EILSEQ; + if (c < 0x80) + return EILSEQ; + } + if (l > 2) { + if (*(p+2) && ((*(p+2) & 0xc0) == 0x80)) + c = c | ((*(p+2) & 0x3f) << (6 * (l-3))); + else + return EILSEQ; + if (c < 0x800) + return EILSEQ; + } + if (l > 3) { + if (*(p+3) && ((*(p+3) & 0xc0) == 0x80)) + c = c | ((*(p+3) & 0x3f) << (6 * (l-4))); + else + return EILSEQ; + if (c < 0x10000) + return EILSEQ; + } + if (l > 4) { + if (*(p+4) && ((*(p+4) & 0xc0) == 0x80)) + c = c | ((*(p+4) & 0x3f) << (6 * (l-5))); + else + return EILSEQ; + if (c < 0x200000) + return EILSEQ; + } + if (l > 5) { + if (*(p+5) && ((*(p+5) & 0xc0) == 0x80)) + c = c | (*(p+5) & 0x3f) ; + else + return EILSEQ; + if (c < 0x4000000) + return EILSEQ; + } + + /* Check for UTF-16 surrogates ifs other illegal UTF-8 * points */ + if (((c <= 0xdfff) && (c >= 0xd800)) || + (c == 0xfffe) || (c == 0xffff)) + return EILSEQ; + p += l; + } + /* 7-bit chars are fine */ + else + p++; + } + return 0; +} + +/* + * Functions for converting to ASCII or UTF-8 from the local codeset + * Functions for converting from ASCII or UTF-8 to the local codeset + * + * The error_str parameter is an optional pointer to a char variable + * where to store a string suitable for use with error() or fatal() or + * friends. + * + * The err parameter is an optional pointer to an integer where 0 + * (success) or EILSEQ or EINVAL will be stored (failure). + * + * These functions return NULL if the conversion fails. + * + */ + +u_char * +g11n_convert_from_ascii(const char *str, int *err_ptr, u_char **error_str) +{ + static u_int initialized = 0; + static u_int do_convert = 0; + iconv_t cd; + int err; + + if (!initialized) { + /* + * iconv_open() fails if the to/from codesets are the + * same, and there are aliases of codesets to boot... + */ + if (strcmp("646", nl_langinfo(CODESET)) == 0 || + strcmp("ASCII", nl_langinfo(CODESET)) == 0 || + strcmp("US-ASCII", nl_langinfo(CODESET)) == 0) { + initialized = 1; + do_convert = 0; + } + else { + cd = iconv_open(nl_langinfo(CODESET), "646"); + if (cd == (iconv_t) -1) { + if (err_ptr) *err_ptr = errno; + if (error_str) *error_str = (u_char *) + "Cannot convert ASCII strings to the local codeset"; + } + initialized = 1; + do_convert = 1; + } + } + + if (!do_convert) { + if ((err = g11n_validate_ascii(str, 0, error_str))) { + if (err_ptr) *err_ptr = err; + return NULL; + } + else + return (u_char *) xstrdup(str); + } + return do_iconv(cd, NULL, str, 0, NULL, err_ptr, error_str); +} + +u_char * +g11n_convert_from_utf8(const u_char *str, int *err_ptr, u_char **error_str) +{ + static u_int initialized = 0; + static u_int do_convert = 0; + iconv_t cd; + int err; + + if (!initialized) { + /* + * iconv_open() fails if the to/from codesets are the + * same, and there are aliases of codesets to boot... + */ + if (strcmp("UTF-8", nl_langinfo(CODESET)) == 0 || + strcmp("UTF8", nl_langinfo(CODESET)) == 0) { + initialized = 1; + do_convert = 0; + } + else { + cd = iconv_open(nl_langinfo(CODESET), "UTF-8"); + if (cd == (iconv_t) -1) { + if (err_ptr) *err_ptr = errno; + if (error_str) *error_str = (u_char *) + "Cannot convert UTF-8 strings to the local codeset"; + } + initialized = 1; + do_convert = 1; + } + } + + if (!do_convert) { + if ((err = g11n_validate_utf8(str, 0, error_str))) { + if (err_ptr) *err_ptr = err; + return NULL; + } + else + return (u_char *) xstrdup((char *) str); + } + return do_iconv(cd, NULL, str, 0, NULL, err_ptr, error_str); +} + +char * +g11n_convert_to_ascii(const u_char *str, int *err_ptr, u_char **error_str) +{ + static u_int initialized = 0; + static u_int do_convert = 0; + iconv_t cd; + + if (!initialized) { + /* + * iconv_open() fails if the to/from codesets are the + * same, and there are aliases of codesets to boot... + */ + if (strcmp("646", nl_langinfo(CODESET)) == 0 || + strcmp("ASCII", nl_langinfo(CODESET)) == 0 || + strcmp("US-ASCII", nl_langinfo(CODESET)) == 0) { + initialized = 1; + do_convert = 0; + } + else { + cd = iconv_open("646", nl_langinfo(CODESET)); + if (cd == (iconv_t) -1) { + if (err_ptr) *err_ptr = errno; + if (error_str) *error_str = (u_char *) + "Cannot convert UTF-8 strings to the local codeset"; + } + initialized = 1; + do_convert = 1; + } + } + + if (!do_convert) + return xstrdup((char *) str); + return (char *) do_iconv(cd, NULL, str, 0, NULL, err_ptr, error_str); +} + +u_char * +g11n_convert_to_utf8(const u_char *str, int *err_ptr, u_char **error_str) +{ + static u_int initialized = 0; + static u_int do_convert = 0; + iconv_t cd; + + if (!initialized) { + /* + * iconv_open() fails if the to/from codesets are the + * same, and there are aliases of codesets to boot... + */ + if (strcmp("UTF-8", nl_langinfo(CODESET)) == 0 || + strcmp("UTF8", nl_langinfo(CODESET)) == 0) { + initialized = 1; + do_convert = 0; + } + else { + cd = iconv_open("UTF-8", nl_langinfo(CODESET)); + if (cd == (iconv_t) -1) { + if (err_ptr) *err_ptr = errno; + if (error_str) *error_str = (u_char *) + "Cannot convert UTF-8 strings to the local codeset"; + } + initialized = 1; + do_convert = 1; + } + } + + if (!do_convert) + return (u_char *) xstrdup((char *) str); + return do_iconv(cd, NULL, str, 0, NULL, err_ptr, error_str); +} + + +/* + * Wrapper around iconv() + * + * The caller is responsible for freeing the result and for handling + * (errno && errno != E2BIG) (i.e., EILSEQ, EINVAL, EBADF). + */ + +static +u_char * +do_iconv(iconv_t cd, u_int *mul_ptr, + const void *buf, u_int len, + u_int *outlen, int *err, + u_char **err_str) +{ + size_t inbytesleft, outbytesleft, converted_size; + char *outbuf; + u_char *converted; + const char *inbuf; + u_int mul = 0; + + if (!buf || !(*(char *)buf)) return NULL; + if (len == 0) len = strlen(buf); + /* reset conversion descriptor */ + /* XXX Do we need initial shift sequences for UTF-8??? */ + (void) iconv(cd, NULL, &inbytesleft, &outbuf, &outbytesleft); + inbuf = (const char *) buf; + if (mul_ptr) mul = *mul_ptr; + converted_size = (len << mul); + outbuf = (char *) xmalloc(converted_size + 1); /* for null */ + converted = (u_char *) outbuf; + outbytesleft = len; + do { + if (iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft) == + (size_t) -1) { + if (errno == E2BIG) { + /* UTF-8 codepoints are at most 8 bytes long. */ + if (mul > 2) { + if (err_str) + *err_str = (u_char *) "Conversion to UTF-8 failed due to" + "preposterous space requirements"; + if (err) + *err = EILSEQ; + return NULL; + } + + /* + * Re-alloc output and ensure that the outbuf + * and outbytesleft values are adjusted. + */ + converted = xrealloc(converted, converted_size << 1 + 1); + outbuf = (char *) converted + converted_size - outbytesleft; + converted_size = (len << ++(mul)); + outbytesleft = converted_size - outbytesleft; + } + else { + /* + * Let the caller deal with iconv() errors, probably by + * calling fatal(); xfree() does not set errno. + */ + if (err) *err = errno; + xfree(converted); + return NULL; + } + } + } while (inbytesleft); + *outbuf = '\0'; /* ensure null-termination */ + if (outlen) *outlen = converted_size - outbytesleft; + if (mul_ptr) *mul_ptr = mul; + return converted; +} diff --git a/usr/src/cmd/ssh/libssh/common/hostfile.c b/usr/src/cmd/ssh/libssh/common/hostfile.c new file mode 100644 index 0000000000..129030b9ea --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/hostfile.c @@ -0,0 +1,234 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Functions for manipulating the known hosts files. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * Copyright (c) 1999, 2000 Markus Friedl. All rights reserved. + * Copyright (c) 1999 Niels Provos. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: hostfile.c,v 1.30 2002/07/24 16:11:18 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "packet.h" +#include "match.h" +#include "key.h" +#include "hostfile.h" +#include "log.h" + +/* + * Parses an RSA (number of bits, e, n) or DSA key from a string. Moves the + * pointer over the key. Skips any whitespace at the beginning and at end. + */ + +int +hostfile_read_key(char **cpp, u_int *bitsp, Key *ret) +{ + char *cp; + + /* Skip leading whitespace. */ + for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++) + ; + + if (key_read(ret, &cp) != 1) + return 0; + + /* Skip trailing whitespace. */ + for (; *cp == ' ' || *cp == '\t'; cp++) + ; + + /* Return results. */ + *cpp = cp; + *bitsp = key_size(ret); + return 1; +} + +static int +hostfile_check_key(int bits, Key *key, const char *host, const char *filename, int linenum) +{ + if (key == NULL || key->type != KEY_RSA1 || key->rsa == NULL) + return 1; + if (bits != BN_num_bits(key->rsa->n)) { + log("Warning: %s, line %d: keysize mismatch for host %s: " + "actual %d vs. announced %d.", + filename, linenum, host, BN_num_bits(key->rsa->n), bits); + log("Warning: replace %d with %d in %s, line %d.", + bits, BN_num_bits(key->rsa->n), filename, linenum); + } + return 1; +} + +/* + * Checks whether the given host (which must be in all lowercase) is already + * in the list of our known hosts. Returns HOST_OK if the host is known and + * has the specified key, HOST_NEW if the host is not known, and HOST_CHANGED + * if the host is known but used to have a different host key. + * + * If no 'key' has been specified and a key of type 'keytype' is known + * for the specified host, then HOST_FOUND is returned. + */ + +static HostStatus +check_host_in_hostfile_by_key_or_type(const char *filename, + const char *host, Key *key, int keytype, Key *found, int *numret) +{ + FILE *f; + char line[8192]; + int linenum = 0; + u_int kbits; + char *cp, *cp2; + HostStatus end_return; + + debug3("check_host_in_hostfile: filename %s", filename); + + /* Open the file containing the list of known hosts. */ + f = fopen(filename, "r"); + if (!f) + return HOST_NEW; + + /* + * Return value when the loop terminates. This is set to + * HOST_CHANGED if we have seen a different key for the host and have + * not found the proper one. + */ + end_return = HOST_NEW; + + /* Go through the file. */ + while (fgets(line, sizeof(line), f)) { + cp = line; + linenum++; + + /* Skip any leading whitespace, comments and empty lines. */ + for (; *cp == ' ' || *cp == '\t'; cp++) + ; + if (!*cp || *cp == '#' || *cp == '\n') + continue; + + /* Find the end of the host name portion. */ + for (cp2 = cp; *cp2 && *cp2 != ' ' && *cp2 != '\t'; cp2++) + ; + + /* Check if the host name matches. */ + if (match_hostname(host, cp, (u_int) (cp2 - cp)) != 1) + continue; + + /* Got a match. Skip host name. */ + cp = cp2; + + /* + * Extract the key from the line. This will skip any leading + * whitespace. Ignore badly formatted lines. + */ + if (!hostfile_read_key(&cp, &kbits, found)) + continue; + + if (numret != NULL) + *numret = linenum; + + if (key == NULL) { + /* we found a key of the requested type */ + if (found->type == keytype) + return HOST_FOUND; + continue; + } + + if (!hostfile_check_key(kbits, found, host, filename, linenum)) + continue; + + /* Check if the current key is the same as the given key. */ + if (key_equal(key, found)) { + /* Ok, they match. */ + debug3("check_host_in_hostfile: match line %d", linenum); + fclose(f); + return HOST_OK; + } + /* + * They do not match. We will continue to go through the + * file; however, we note that we will not return that it is + * new. + */ + end_return = HOST_CHANGED; + } + /* Clear variables and close the file. */ + fclose(f); + + /* + * Return either HOST_NEW or HOST_CHANGED, depending on whether we + * saw a different key for the host. + */ + return end_return; +} + +HostStatus +check_host_in_hostfile(const char *filename, const char *host, Key *key, + Key *found, int *numret) +{ + if (key == NULL) + fatal("no key to look up"); + return (check_host_in_hostfile_by_key_or_type(filename, host, key, 0, + found, numret)); +} + +int +lookup_key_in_hostfile_by_type(const char *filename, const char *host, + int keytype, Key *found, int *numret) +{ + return (check_host_in_hostfile_by_key_or_type(filename, host, NULL, + keytype, found, numret) == HOST_FOUND); +} + +/* + * Appends an entry to the host file. Returns false if the entry could not + * be appended. + */ + +int +add_host_to_hostfile(const char *filename, const char *host, Key *key) +{ + FILE *f; + int success = 0; + if (key == NULL) + return 1; /* XXX ? */ + f = fopen(filename, "a"); + if (!f) + return 0; + fprintf(f, "%s ", host); + if (key_write(key, f)) { + success = 1; + } else { + error("add_host_to_hostfile: saving key in %s failed", filename); + } + fprintf(f, "\n"); + fclose(f); + return success; +} diff --git a/usr/src/cmd/ssh/libssh/common/kex.c b/usr/src/cmd/ssh/libssh/common/kex.c new file mode 100644 index 0000000000..0e3b8d9365 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kex.c @@ -0,0 +1,673 @@ +/* + * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: kex.c,v 1.51 2002/06/24 14:55:38 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <locale.h> + +#include <openssl/crypto.h> + +#include "ssh2.h" +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "packet.h" +#include "compat.h" +#include "cipher.h" +#include "kex.h" +#include "key.h" +#include "log.h" +#include "mac.h" +#include "match.h" +#include "dispatch.h" +#include "monitor.h" +#include "g11n.h" + +#ifdef GSSAPI +#include "ssh-gss.h" +#endif + +#define KEX_COOKIE_LEN 16 + +/* Use privilege separation for sshd */ +int use_privsep; +struct monitor *pmonitor; + +char *session_lang = NULL; + + +/* prototype */ +static void kex_do_hook(Kex *kex); +static void kex_kexinit_finish(Kex *); +static void kex_choose_conf(Kex *); + +/* put algorithm proposal into buffer */ +static +void +kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX]) +{ + int i; + + buffer_clear(b); + /* + * add a dummy cookie, the cookie will be overwritten by + * kex_send_kexinit(), each time a kexinit is set + */ + for (i = 0; i < KEX_COOKIE_LEN; i++) + buffer_put_char(b, 0); + for (i = 0; i < PROPOSAL_MAX; i++) + buffer_put_cstring(b, proposal[i]); + buffer_put_char(b, 0); /* first_kex_packet_follows */ + buffer_put_int(b, 0); /* uint32 reserved */ +} + +/* parse buffer and return algorithm proposal */ +static +char ** +kex_buf2prop(Buffer *raw, int *first_kex_follows) +{ + Buffer b; + int i; + char **proposal; + + proposal = xmalloc(PROPOSAL_MAX * sizeof(char *)); + + buffer_init(&b); + buffer_append(&b, buffer_ptr(raw), buffer_len(raw)); + /* skip cookie */ + for (i = 0; i < KEX_COOKIE_LEN; i++) + buffer_get_char(&b); + /* extract kex init proposal strings */ + for (i = 0; i < PROPOSAL_MAX; i++) { + proposal[i] = buffer_get_string(&b,NULL); + debug2("kex_parse_kexinit: %s", proposal[i]); + } + /* first kex follows / reserved */ + i = buffer_get_char(&b); + if (first_kex_follows != NULL) + *first_kex_follows = i; + debug2("kex_parse_kexinit: first_kex_follows %d ", i); + i = buffer_get_int(&b); + debug2("kex_parse_kexinit: reserved %d ", i); + buffer_free(&b); + return proposal; +} + +static +void +kex_prop_free(char **proposal) +{ + int i; + + for (i = 0; i < PROPOSAL_MAX; i++) + xfree(proposal[i]); + xfree(proposal); +} + +static void +kex_protocol_error(int type, u_int32_t seq, void *ctxt) +{ + error("Hm, kex protocol error: type %d seq %u", type, seq); +} + +static void +kex_reset_dispatch(void) +{ +#ifdef ALTPRIVSEP + /* unprivileged sshd has a kex packet handler that must not be reset */ + debug3("kex_reset_dispatch -- should we dispatch_set(KEXINIT) here? %d && !%d", + packet_is_server(), packet_is_monitor()); + if (packet_is_server() && !packet_is_monitor()) { + debug3("kex_reset_dispatch -- skipping dispatch_set(KEXINIT) in unpriv proc"); + return; + } +#endif /* ALTPRIVSEP */ + + dispatch_range(SSH2_MSG_TRANSPORT_MIN, + SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error); + dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); +} + +void +kex_finish(Kex *kex) +{ + kex_reset_dispatch(); + + packet_start(SSH2_MSG_NEWKEYS); + packet_send(); + /* packet_write_wait(); */ + debug("SSH2_MSG_NEWKEYS sent"); + +#ifdef ALTPRIVSEP + if (packet_is_monitor()) + goto skip_newkeys; +#endif /* ALTPRIVSEP */ + debug("expecting SSH2_MSG_NEWKEYS"); + packet_read_expect(SSH2_MSG_NEWKEYS); + packet_check_eom(); + debug("SSH2_MSG_NEWKEYS received"); +#ifdef ALTPRIVSEP +skip_newkeys: +#endif /* ALTPRIVSEP */ + + kex->done = 1; + kex->initial_kex_done = 1; /* never to be cleared once set */ + buffer_clear(&kex->peer); + /* buffer_clear(&kex->my); */ + kex->flags &= ~KEX_INIT_SENT; +#if 0 + /* Must have this name for use in sshd (audit_save_kex())... */ + xfree(kex->name); + kex->name = NULL; +#endif +} + +void +kex_send_kexinit(Kex *kex) +{ + u_int32_t rand = 0; + u_char *cookie; + int i; + + if (kex == NULL) { + error("kex_send_kexinit: no kex, cannot rekey"); + return; + } + if (kex->flags & KEX_INIT_SENT) { + debug("KEX_INIT_SENT"); + return; + } + kex->done = 0; + + /* update my proposal -- e.g., add/remove GSS kexalgs */ + kex_do_hook(kex); + + /* generate a random cookie */ + if (buffer_len(&kex->my) < KEX_COOKIE_LEN) + fatal("kex_send_kexinit: kex proposal too short"); + cookie = buffer_ptr(&kex->my); + for (i = 0; i < KEX_COOKIE_LEN; i++) { + if (i % 4 == 0) + rand = arc4random(); + cookie[i] = rand; + rand >>= 8; + } + packet_start(SSH2_MSG_KEXINIT); + packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my)); + packet_send(); + debug("SSH2_MSG_KEXINIT sent"); + kex->flags |= KEX_INIT_SENT; +} + +void +kex_input_kexinit(int type, u_int32_t seq, void *ctxt) +{ + char *ptr; + u_int dlen; + int i; + Kex *kex = (Kex *)ctxt; + + debug("SSH2_MSG_KEXINIT received"); + if (kex == NULL) + fatal("kex_input_kexinit: no kex, cannot rekey"); + + ptr = packet_get_raw(&dlen); + buffer_append(&kex->peer, ptr, dlen); + + /* discard packet */ + for (i = 0; i < KEX_COOKIE_LEN; i++) + packet_get_char(); + for (i = 0; i < PROPOSAL_MAX; i++) + xfree(packet_get_string(NULL)); + (void) packet_get_char(); + (void) packet_get_int(); + packet_check_eom(); + + kex_kexinit_finish(kex); +} + +/* + * This is for GSS keyex, where actual KEX offer can change at rekey + * time due to credential expiration/renewal... + */ +static +void +kex_do_hook(Kex *kex) +{ + char **prop; + + if (kex->kex_hook == NULL) + return; + + /* Unmarshall my proposal, let the hook modify it, remarshall it */ + prop = kex_buf2prop(&kex->my, NULL); + buffer_clear(&kex->my); + (kex->kex_hook)(kex, prop); + kex_prop2buf(&kex->my, prop); + kex_prop_free(prop); +} + +Kex * +kex_setup(const char *host, char *proposal[PROPOSAL_MAX], Kex_hook_func hook) +{ + Kex *kex; + + kex = xmalloc(sizeof(*kex)); + memset(kex, 0, sizeof(*kex)); + buffer_init(&kex->peer); + buffer_init(&kex->my); + + kex->kex_hook = hook; /* called by kex_send_kexinit() */ + + if (host != NULL && *host != '\0') + kex->serverhost = xstrdup(host); + else + kex->server = 1; + + kex_prop2buf(&kex->my, proposal); + + kex_send_kexinit(kex); + kex_reset_dispatch(); + + return kex; +} + +static void +kex_kexinit_finish(Kex *kex) +{ + if (!(kex->flags & KEX_INIT_SENT)) + kex_send_kexinit(kex); + + kex_choose_conf(kex); + + if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX && + kex->kex[kex->kex_type] != NULL) + (kex->kex[kex->kex_type])(kex); + else + fatal("Unsupported key exchange %d", kex->kex_type); +} + +static void +choose_lang(char **lang, char *client, char *server) +{ + if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS) + *lang = match_list(client, server, NULL); + else + *lang = g11n_srvr_locale_negotiate(client, NULL); +} +static void +choose_enc(Enc *enc, char *client, char *server) +{ + char *name = match_list(client, server, NULL); + if (name == NULL) + fatal("no matching cipher found: client %s server %s", client, server); + if ((enc->cipher = cipher_by_name(name)) == NULL) + fatal("matching cipher is not supported: %s", name); + enc->name = name; + enc->enabled = 0; + enc->iv = NULL; + enc->key = NULL; + enc->key_len = cipher_keylen(enc->cipher); + enc->block_size = cipher_blocksize(enc->cipher); +} +static void +choose_mac(Mac *mac, char *client, char *server) +{ + char *name = match_list(client, server, NULL); + if (name == NULL) + fatal("no matching mac found: client %s server %s", client, server); + if (mac_init(mac, name) < 0) + fatal("unsupported mac %s", name); + /* truncate the key */ + if (datafellows & SSH_BUG_HMAC) + mac->key_len = 16; + mac->name = name; + mac->key = NULL; + mac->enabled = 0; +} +static void +choose_comp(Comp *comp, char *client, char *server) +{ + char *name = match_list(client, server, NULL); + if (name == NULL) + fatal("no matching comp found: client %s server %s", client, server); + if (strcmp(name, "zlib") == 0) { + comp->type = 1; + } else if (strcmp(name, "none") == 0) { + comp->type = 0; + } else { + fatal("unsupported comp %s", name); + } + comp->name = name; +} +static void +choose_kex(Kex *k, char *client, char *server) +{ + k->name = match_list(client, server, NULL); + if (k->name == NULL) + fatal("no kex alg"); + /* XXX Finish 3.6/7 merge of kex stuff -- choose_kex() done */ + if (strcmp(k->name, KEX_DH1) == 0) { + k->kex_type = KEX_DH_GRP1_SHA1; + } else if (strcmp(k->name, KEX_DHGEX) == 0) { + k->kex_type = KEX_DH_GEX_SHA1; +#ifdef GSSAPI + } else if (strncmp(k->name, KEX_GSS_SHA1, sizeof(KEX_GSS_SHA1)-1) == 0) { + k->kex_type = KEX_GSS_GRP1_SHA1; +#endif + } else + fatal("bad kex alg %s", k->name); +} +static void +choose_hostkeyalg(Kex *k, char *client, char *server) +{ + char *hostkeyalg = match_list(client, server, NULL); + if (hostkeyalg == NULL) + fatal("no hostkey alg"); + k->hostkey_type = key_type_from_name(hostkeyalg); + if (k->hostkey_type == KEY_UNSPEC) + fatal("bad hostkey alg '%s'", hostkeyalg); + xfree(hostkeyalg); +} + +static int +proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX]) +{ + static int check[] = { + PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1 + }; + int *idx; + char *p; + + for (idx = &check[0]; *idx != -1; idx++) { + if ((p = strchr(my[*idx], ',')) != NULL) + *p = '\0'; + if ((p = strchr(peer[*idx], ',')) != NULL) + *p = '\0'; + if (strcmp(my[*idx], peer[*idx]) != 0) { + debug2("proposal mismatch: my %s peer %s", + my[*idx], peer[*idx]); + return (0); + } + } + debug2("proposals match"); + return (1); +} + +static void +kex_choose_conf(Kex *kex) +{ + Newkeys *newkeys; + char **my, **peer; + char **cprop, **sprop; + char *p_langs_c2s, *p_langs_s2c; /* peer's langs */ + char *plangs = NULL; /* peer's langs*/ + char *mlangs = NULL; /* my langs */ + int nenc, nmac, ncomp; + int mode; + int ctos; /* direction: if true client-to-server */ + int need; + int first_kex_follows, type; + + my = kex_buf2prop(&kex->my, NULL); + peer = kex_buf2prop(&kex->peer, &first_kex_follows); + + if (kex->server) { + cprop=peer; + sprop=my; + } else { + cprop=my; + sprop=peer; + } + + /* Algorithm Negotiation */ + for (mode = 0; mode < MODE_MAX; mode++) { + newkeys = xmalloc(sizeof(*newkeys)); + memset(newkeys, 0, sizeof(*newkeys)); + kex->newkeys[mode] = newkeys; + ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN); + nenc = ctos ? PROPOSAL_ENC_ALGS_CTOS : PROPOSAL_ENC_ALGS_STOC; + nmac = ctos ? PROPOSAL_MAC_ALGS_CTOS : PROPOSAL_MAC_ALGS_STOC; + ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC; + choose_enc (&newkeys->enc, cprop[nenc], sprop[nenc]); + choose_mac (&newkeys->mac, cprop[nmac], sprop[nmac]); + choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]); + debug("kex: %s %s %s %s", + ctos ? "client->server" : "server->client", + newkeys->enc.name, + newkeys->mac.name, + newkeys->comp.name); + } + choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]); + choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS], + sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]); + need = 0; + for (mode = 0; mode < MODE_MAX; mode++) { + newkeys = kex->newkeys[mode]; + if (need < newkeys->enc.key_len) + need = newkeys->enc.key_len; + if (need < newkeys->enc.block_size) + need = newkeys->enc.block_size; + if (need < newkeys->mac.key_len) + need = newkeys->mac.key_len; + } + /* XXX need runden? */ + kex->we_need = need; + + /* ignore the next message if the proposals do not match */ + if (first_kex_follows && !proposals_match(my, peer) && + !(datafellows & SSH_BUG_FIRSTKEX)) { + type = packet_read(); + debug2("skipping next packet (type %u)", type); + } + + /* Language/locale negotiation -- not worth doing on re-key */ + + if (!kex->initial_kex_done) { + p_langs_c2s = peer[PROPOSAL_LANG_CTOS]; + p_langs_s2c = peer[PROPOSAL_LANG_STOC]; + debug("Peer sent proposed langtags, ctos: %s", p_langs_c2s); + debug("Peer sent proposed langtags, stoc: %s", p_langs_s2c); + plangs = NULL; + + /* We propose the same langs for each protocol direction */ + mlangs = my[PROPOSAL_LANG_STOC]; + debug("We proposed langtags, ctos: %s", my[PROPOSAL_LANG_CTOS]); + debug("We proposed langtags, stoc: %s", mlangs); + + /* + * Why oh why did they bother with negotiating langs for + * each protocol direction?! + * + * The semantics of this are vaguely specified, but one can + * imagine using one language (locale) for the whole session and + * a different one for message localization (e.g., 'en_US.UTF-8' + * overall and 'fr' for messages). Weird? Maybe. But lang + * tags don't include codeset info, like locales do... + * + * So, server-side we want: + * - setlocale(LC_ALL, c2s_locale); + * and + * - setlocale(LC_MESSAGES, s2c_locale); + * + * Client-side we don't really care. But we could do: + * + * - when very verbose, tell the use what lang the server's + * messages are in, if left out in the protocol + * - when sending messages to the server, and if applicable, we + * can localize them according to the language negotiated for + * that direction. + * + * But for now we do nothing on the client side. + */ + if ((p_langs_c2s && *p_langs_c2s) && !(p_langs_s2c && *p_langs_s2c)) + plangs = p_langs_c2s; + else if ((p_langs_s2c && *p_langs_s2c) && !(p_langs_c2s && *p_langs_c2s)) + plangs = p_langs_s2c; + else + plangs = p_langs_c2s; + + if (kex->server) { + if (plangs && mlangs && *plangs && *mlangs) { + char *locale; + + choose_lang(&locale, plangs, mlangs); + if (locale) { + g11n_setlocale(LC_ALL, locale); + debug("Negotiated main locale: %s", locale); + packet_send_debug("Negotiated main locale: %s", locale); + } + if (plangs != p_langs_s2c && + p_langs_s2c && *p_langs_s2c) { + choose_lang(&locale, p_langs_s2c, mlangs); + if (locale) { + g11n_setlocale(LC_MESSAGES, locale); + debug("Negotiated messages locale: %s", locale); + packet_send_debug("Negotiated messages locale: %s", locale); + } + } + /* + * Should we free locale? Or does setlocale + * retain a reference? + */ + /*xfree(locale);*/ + } + } + else { + if (plangs && mlangs && *plangs && *mlangs && + !(datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)) { + char *lang; + lang = g11n_clnt_langtag_negotiate(mlangs, plangs); + if (lang) { + session_lang = lang; + debug("Negotiated lang: %s", lang); + } + } + } + } + + kex_prop_free(my); + kex_prop_free(peer); +} + +static u_char * +derive_key(Kex *kex, int id, int need, u_char *hash, BIGNUM *shared_secret) +{ + Buffer b; + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + char c = id; + int have; + int mdsz = EVP_MD_size(evp_md); + u_char *digest = xmalloc(roundup(need, mdsz)); + + buffer_init(&b); + buffer_put_bignum2(&b, shared_secret); + + /* K1 = HASH(K || H || "A" || session_id) */ + EVP_DigestInit(&md, evp_md); + if (!(datafellows & SSH_BUG_DERIVEKEY)) + EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b)); + EVP_DigestUpdate(&md, hash, mdsz); + EVP_DigestUpdate(&md, &c, 1); + EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len); + EVP_DigestFinal(&md, digest, NULL); + + /* + * expand key: + * Kn = HASH(K || H || K1 || K2 || ... || Kn-1) + * Key = K1 || K2 || ... || Kn + */ + for (have = mdsz; need > have; have += mdsz) { + EVP_DigestInit(&md, evp_md); + if (!(datafellows & SSH_BUG_DERIVEKEY)) + EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b)); + EVP_DigestUpdate(&md, hash, mdsz); + EVP_DigestUpdate(&md, digest, have); + EVP_DigestFinal(&md, digest + have, NULL); + } + buffer_free(&b); +#ifdef DEBUG_KEX + fprintf(stderr, "key '%c'== ", c); + dump_digest("key", digest, need); +#endif + return digest; +} + +Newkeys *current_keys[MODE_MAX]; + +#define NKEYS 6 +void +kex_derive_keys(Kex *kex, u_char *hash, BIGNUM *shared_secret) +{ + u_char *keys[NKEYS]; + int i, mode, ctos; + + for (i = 0; i < NKEYS; i++) + keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, shared_secret); + + debug2("kex_derive_keys"); + for (mode = 0; mode < MODE_MAX; mode++) { + current_keys[mode] = kex->newkeys[mode]; + kex->newkeys[mode] = NULL; + ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN); + current_keys[mode]->enc.iv = keys[ctos ? 0 : 1]; + current_keys[mode]->enc.key = keys[ctos ? 2 : 3]; + current_keys[mode]->mac.key = keys[ctos ? 4 : 5]; + } +} + +Newkeys * +kex_get_newkeys(int mode) +{ + Newkeys *ret; + + ret = current_keys[mode]; + current_keys[mode] = NULL; + return ret; +} + +#if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) +void +dump_digest(char *msg, u_char *digest, int len) +{ + int i; + + fprintf(stderr, "%s\n", msg); + for (i = 0; i< len; i++) { + fprintf(stderr, "%02x", digest[i]); + if (i%32 == 31) + fprintf(stderr, "\n"); + else if (i%8 == 7) + fprintf(stderr, " "); + } + fprintf(stderr, "\n"); +} +#endif diff --git a/usr/src/cmd/ssh/libssh/common/kexdh.c b/usr/src/cmd/ssh/libssh/common/kexdh.c new file mode 100644 index 0000000000..7af19994fb --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexdh.c @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexdh.c,v 1.18 2002/03/18 17:50:31 provos Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/crypto.h> +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "monitor_wrap.h" + +u_char * +kex_dh_hash( + char *client_version_string, + char *server_version_string, + char *ckexinit, int ckexinitlen, + char *skexinit, int skexinitlen, + u_char *serverhostkeyblob, int sbloblen, + BIGNUM *client_dh_pub, + BIGNUM *server_dh_pub, + BIGNUM *shared_secret) +{ + Buffer b; + static u_char digest[EVP_MAX_MD_SIZE]; + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + + buffer_init(&b); + buffer_put_cstring(&b, client_version_string); + buffer_put_cstring(&b, server_version_string); + + /* kexinit messages: fake header: len+SSH2_MSG_KEXINIT */ + buffer_put_int(&b, ckexinitlen+1); + buffer_put_char(&b, SSH2_MSG_KEXINIT); + buffer_append(&b, ckexinit, ckexinitlen); + buffer_put_int(&b, skexinitlen+1); + buffer_put_char(&b, SSH2_MSG_KEXINIT); + buffer_append(&b, skexinit, skexinitlen); + + buffer_put_string(&b, serverhostkeyblob, sbloblen); + buffer_put_bignum2(&b, client_dh_pub); + buffer_put_bignum2(&b, server_dh_pub); + buffer_put_bignum2(&b, shared_secret); + +#ifdef DEBUG_KEX + buffer_dump(&b); +#endif + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b)); + EVP_DigestFinal(&md, digest, NULL); + + buffer_free(&b); + +#ifdef DEBUG_KEX + dump_digest("hash", digest, EVP_MD_size(evp_md)); +#endif + return digest; +} diff --git a/usr/src/cmd/ssh/libssh/common/kexdhc.c b/usr/src/cmd/ssh/libssh/common/kexdhc.c new file mode 100644 index 0000000000..6e7e7d7dc5 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexdhc.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexdh.c,v 1.18 2002/03/18 17:50:31 provos Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/crypto.h> +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "monitor_wrap.h" + +void +kexdh_client(Kex *kex) +{ + BIGNUM *dh_server_pub = NULL, *shared_secret = NULL; + DH *dh; + Key *server_host_key; + u_char *server_host_key_blob = NULL, *signature = NULL; + u_char *kbuf, *hash; + u_int klen, kout, slen, sbloblen; + + /* generate and send 'e', client DH public key */ + dh = dh_new_group1(); + dh_gen_key(dh, kex->we_need * 8); + packet_start(SSH2_MSG_KEXDH_INIT); + packet_put_bignum2(dh->pub_key); + packet_send(); + + debug("sending SSH2_MSG_KEXDH_INIT"); +#ifdef DEBUG_KEXDH + DHparams_print_fp(stderr, dh); + fprintf(stderr, "pub= "); + BN_print_fp(stderr, dh->pub_key); + fprintf(stderr, "\n"); +#endif + + debug("expecting SSH2_MSG_KEXDH_REPLY"); + packet_read_expect(SSH2_MSG_KEXDH_REPLY); + + /* key, cert */ + server_host_key_blob = packet_get_string(&sbloblen); + server_host_key = key_from_blob(server_host_key_blob, sbloblen); + if (server_host_key == NULL) + fatal("cannot decode server_host_key_blob"); + if (server_host_key->type != kex->hostkey_type) + fatal("type mismatch for decoded server_host_key_blob"); + if (kex->verify_host_key == NULL) + fatal("cannot verify server_host_key"); + if (kex->verify_host_key(server_host_key) == -1) + fatal("server_host_key verification failed"); + + /* DH paramter f, server public DH key */ + if ((dh_server_pub = BN_new()) == NULL) + fatal("dh_server_pub == NULL"); + packet_get_bignum2(dh_server_pub); + +#ifdef DEBUG_KEXDH + fprintf(stderr, "dh_server_pub= "); + BN_print_fp(stderr, dh_server_pub); + fprintf(stderr, "\n"); + debug("bits %d", BN_num_bits(dh_server_pub)); +#endif + + /* signed H */ + signature = packet_get_string(&slen); + packet_check_eom(); + + if (!dh_pub_is_valid(dh, dh_server_pub)) + packet_disconnect("bad server public DH value"); + + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_server_pub, dh); +#ifdef DEBUG_KEXDH + dump_digest("shared secret", kbuf, kout); +#endif + if ((shared_secret = BN_new()) == NULL) + fatal("kexdh_client: BN_new failed"); + BN_bin2bn(kbuf, kout, shared_secret); + memset(kbuf, 0, klen); + xfree(kbuf); + + /* calc and verify H */ + hash = kex_dh_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->my), buffer_len(&kex->my), + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + server_host_key_blob, sbloblen, + dh->pub_key, + dh_server_pub, + shared_secret + ); + xfree(server_host_key_blob); + BN_clear_free(dh_server_pub); + DH_free(dh); + + if (key_verify(server_host_key, signature, slen, hash, 20) != 1) + fatal("key_verify failed for server_host_key"); + key_free(server_host_key); + xfree(signature); + + /* save session id */ + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + memcpy(kex->session_id, hash, kex->session_id_len); + } + + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + kex_finish(kex); +} diff --git a/usr/src/cmd/ssh/libssh/common/kexdhs.c b/usr/src/cmd/ssh/libssh/common/kexdhs.c new file mode 100644 index 0000000000..1fc9f4c2ee --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexdhs.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexdh.c,v 1.18 2002/03/18 17:50:31 provos Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/crypto.h> +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "monitor_wrap.h" + +void +kexdh_server(Kex *kex) +{ + BIGNUM *shared_secret = NULL, *dh_client_pub = NULL; + DH *dh; + Key *server_host_key; + u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL; + u_int sbloblen, klen, kout; + u_int slen; + + /* generate server DH public key */ + dh = dh_new_group1(); + dh_gen_key(dh, kex->we_need * 8); + + debug("expecting SSH2_MSG_KEXDH_INIT"); + packet_read_expect(SSH2_MSG_KEXDH_INIT); + + if (kex->load_host_key == NULL) + fatal("Cannot load hostkey"); + server_host_key = kex->load_host_key(kex->hostkey_type); + if (server_host_key == NULL) + fatal("Unsupported hostkey type %d", kex->hostkey_type); + + /* key, cert */ + if ((dh_client_pub = BN_new()) == NULL) + fatal("dh_client_pub == NULL"); + packet_get_bignum2(dh_client_pub); + packet_check_eom(); + +#ifdef DEBUG_KEXDH + fprintf(stderr, "dh_client_pub= "); + BN_print_fp(stderr, dh_client_pub); + fprintf(stderr, "\n"); + debug("bits %d", BN_num_bits(dh_client_pub)); +#endif + +#ifdef DEBUG_KEXDH + DHparams_print_fp(stderr, dh); + fprintf(stderr, "pub= "); + BN_print_fp(stderr, dh->pub_key); + fprintf(stderr, "\n"); +#endif + if (!dh_pub_is_valid(dh, dh_client_pub)) + packet_disconnect("bad client public DH value"); + + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_client_pub, dh); +#ifdef DEBUG_KEXDH + dump_digest("shared secret", kbuf, kout); +#endif + if ((shared_secret = BN_new()) == NULL) + fatal("kexdh_server: BN_new failed"); + BN_bin2bn(kbuf, kout, shared_secret); + memset(kbuf, 0, klen); + xfree(kbuf); + + key_to_blob(server_host_key, &server_host_key_blob, &sbloblen); + + /* calc H */ + hash = kex_dh_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + buffer_ptr(&kex->my), buffer_len(&kex->my), + server_host_key_blob, sbloblen, + dh_client_pub, + dh->pub_key, + shared_secret + ); + BN_clear_free(dh_client_pub); + + /* save session id := H */ + /* XXX hashlen depends on KEX */ + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + memcpy(kex->session_id, hash, kex->session_id_len); + } + + /* sign H */ + /* XXX hashlen depends on KEX */ + PRIVSEP(key_sign(server_host_key, &signature, &slen, hash, 20)); + + /* destroy_sensitive_data(); */ + + /* send server hostkey, DH pubkey 'f' and singed H */ + packet_start(SSH2_MSG_KEXDH_REPLY); + packet_put_string(server_host_key_blob, sbloblen); + packet_put_bignum2(dh->pub_key); /* f */ + packet_put_string(signature, slen); + packet_send(); + + xfree(signature); + xfree(server_host_key_blob); + /* have keys, free DH */ + DH_free(dh); + + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + kex_finish(kex); +} diff --git a/usr/src/cmd/ssh/libssh/common/kexgex.c b/usr/src/cmd/ssh/libssh/common/kexgex.c new file mode 100644 index 0000000000..3553bb130f --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexgex.c @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2000 Niels Provos. All rights reserved. + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexgex.c,v 1.22 2002/03/24 17:27:03 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "compat.h" +#include "monitor_wrap.h" + +u_char * +kexgex_hash( + char *client_version_string, + char *server_version_string, + char *ckexinit, int ckexinitlen, + char *skexinit, int skexinitlen, + u_char *serverhostkeyblob, int sbloblen, + int min, int wantbits, int max, BIGNUM *prime, BIGNUM *gen, + BIGNUM *client_dh_pub, + BIGNUM *server_dh_pub, + BIGNUM *shared_secret) +{ + Buffer b; + static u_char digest[EVP_MAX_MD_SIZE]; + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + + buffer_init(&b); + buffer_put_cstring(&b, client_version_string); + buffer_put_cstring(&b, server_version_string); + + /* kexinit messages: fake header: len+SSH2_MSG_KEXINIT */ + buffer_put_int(&b, ckexinitlen+1); + buffer_put_char(&b, SSH2_MSG_KEXINIT); + buffer_append(&b, ckexinit, ckexinitlen); + buffer_put_int(&b, skexinitlen+1); + buffer_put_char(&b, SSH2_MSG_KEXINIT); + buffer_append(&b, skexinit, skexinitlen); + + buffer_put_string(&b, serverhostkeyblob, sbloblen); + if (min == -1 || max == -1) + buffer_put_int(&b, wantbits); + else { + buffer_put_int(&b, min); + buffer_put_int(&b, wantbits); + buffer_put_int(&b, max); + } + buffer_put_bignum2(&b, prime); + buffer_put_bignum2(&b, gen); + buffer_put_bignum2(&b, client_dh_pub); + buffer_put_bignum2(&b, server_dh_pub); + buffer_put_bignum2(&b, shared_secret); + +#ifdef DEBUG_KEXDH + buffer_dump(&b); +#endif + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b)); + EVP_DigestFinal(&md, digest, NULL); + + buffer_free(&b); + +#ifdef DEBUG_KEXDH + dump_digest("hash", digest, EVP_MD_size(evp_md)); +#endif + return digest; +} diff --git a/usr/src/cmd/ssh/libssh/common/kexgexc.c b/usr/src/cmd/ssh/libssh/common/kexgexc.c new file mode 100644 index 0000000000..5f6ac3d283 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexgexc.c @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2000 Niels Provos. All rights reserved. + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexgex.c,v 1.22 2002/03/24 17:27:03 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "compat.h" +#include "monitor_wrap.h" + +void +kexgex_client(Kex *kex) +{ + BIGNUM *dh_server_pub = NULL, *shared_secret = NULL; + BIGNUM *p = NULL, *g = NULL; + Key *server_host_key; + u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL; + u_int klen, kout, slen, sbloblen; + int min, max, nbits; + DH *dh; + + nbits = dh_estimate(kex->we_need * 8); + + if (datafellows & SSH_OLD_DHGEX) { + debug("SSH2_MSG_KEX_DH_GEX_REQUEST_OLD sent"); + + /* Old GEX request */ + packet_start(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD); + packet_put_int(nbits); + min = DH_GRP_MIN; + max = DH_GRP_MAX; + } else { + debug("SSH2_MSG_KEX_DH_GEX_REQUEST sent"); + + /* New GEX request */ + min = DH_GRP_MIN; + max = DH_GRP_MAX; + packet_start(SSH2_MSG_KEX_DH_GEX_REQUEST); + packet_put_int(min); + packet_put_int(nbits); + packet_put_int(max); + } +#ifdef DEBUG_KEXDH + fprintf(stderr, "\nmin = %d, nbits = %d, max = %d\n", + min, nbits, max); +#endif + packet_send(); + + debug("expecting SSH2_MSG_KEX_DH_GEX_GROUP"); + packet_read_expect(SSH2_MSG_KEX_DH_GEX_GROUP); + + if ((p = BN_new()) == NULL) + fatal("BN_new"); + packet_get_bignum2(p); + if ((g = BN_new()) == NULL) + fatal("BN_new"); + packet_get_bignum2(g); + packet_check_eom(); + + if (BN_num_bits(p) < min || BN_num_bits(p) > max) + fatal("DH_GEX group out of range: %d !< %d !< %d", + min, BN_num_bits(p), max); + + dh = dh_new_group(g, p); + dh_gen_key(dh, kex->we_need * 8); + +#ifdef DEBUG_KEXDH + DHparams_print_fp(stderr, dh); + fprintf(stderr, "pub= "); + BN_print_fp(stderr, dh->pub_key); + fprintf(stderr, "\n"); +#endif + + debug("SSH2_MSG_KEX_DH_GEX_INIT sent"); + /* generate and send 'e', client DH public key */ + packet_start(SSH2_MSG_KEX_DH_GEX_INIT); + packet_put_bignum2(dh->pub_key); + packet_send(); + + debug("expecting SSH2_MSG_KEX_DH_GEX_REPLY"); + packet_read_expect(SSH2_MSG_KEX_DH_GEX_REPLY); + + /* key, cert */ + server_host_key_blob = packet_get_string(&sbloblen); + server_host_key = key_from_blob(server_host_key_blob, sbloblen); + if (server_host_key == NULL) + fatal("cannot decode server_host_key_blob"); + if (server_host_key->type != kex->hostkey_type) + fatal("type mismatch for decoded server_host_key_blob"); + if (kex->verify_host_key == NULL) + fatal("cannot verify server_host_key"); + if (kex->verify_host_key(server_host_key) == -1) + fatal("server_host_key verification failed"); + + /* DH paramter f, server public DH key */ + if ((dh_server_pub = BN_new()) == NULL) + fatal("dh_server_pub == NULL"); + packet_get_bignum2(dh_server_pub); + +#ifdef DEBUG_KEXDH + fprintf(stderr, "dh_server_pub= "); + BN_print_fp(stderr, dh_server_pub); + fprintf(stderr, "\n"); + debug("bits %d", BN_num_bits(dh_server_pub)); +#endif + + /* signed H */ + signature = packet_get_string(&slen); + packet_check_eom(); + + if (!dh_pub_is_valid(dh, dh_server_pub)) + packet_disconnect("bad server public DH value"); + + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_server_pub, dh); +#ifdef DEBUG_KEXDH + dump_digest("shared secret", kbuf, kout); +#endif + if ((shared_secret = BN_new()) == NULL) + fatal("kexgex_client: BN_new failed"); + BN_bin2bn(kbuf, kout, shared_secret); + memset(kbuf, 0, klen); + xfree(kbuf); + + if (datafellows & SSH_OLD_DHGEX) + min = max = -1; + + /* calc and verify H */ + hash = kexgex_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->my), buffer_len(&kex->my), + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + server_host_key_blob, sbloblen, + min, nbits, max, + dh->p, dh->g, + dh->pub_key, + dh_server_pub, + shared_secret + ); + /* have keys, free DH */ + DH_free(dh); + xfree(server_host_key_blob); + BN_clear_free(dh_server_pub); + + if (key_verify(server_host_key, signature, slen, hash, 20) != 1) + fatal("key_verify failed for server_host_key"); + key_free(server_host_key); + xfree(signature); + + /* save session id */ + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + memcpy(kex->session_id, hash, kex->session_id_len); + } + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + + kex_finish(kex); +} diff --git a/usr/src/cmd/ssh/libssh/common/kexgexs.c b/usr/src/cmd/ssh/libssh/common/kexgexs.c new file mode 100644 index 0000000000..60608d2a65 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexgexs.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2000 Niels Provos. All rights reserved. + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: kexgex.c,v 1.22 2002/03/24 17:27:03 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "compat.h" +#include "monitor_wrap.h" + +void +kexgex_server(Kex *kex) +{ + BIGNUM *shared_secret = NULL, *dh_client_pub = NULL; + Key *server_host_key; + DH *dh; + u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL; + u_int sbloblen, klen, kout, slen; + int min = -1, max = -1, nbits = -1, type; + + if (kex->load_host_key == NULL) + fatal("Cannot load hostkey"); + server_host_key = kex->load_host_key(kex->hostkey_type); + if (server_host_key == NULL) + fatal("Unsupported hostkey type %d", kex->hostkey_type); + + type = packet_read(); + switch (type) { + case SSH2_MSG_KEX_DH_GEX_REQUEST: + debug("SSH2_MSG_KEX_DH_GEX_REQUEST received"); + min = packet_get_int(); + nbits = packet_get_int(); + max = packet_get_int(); + min = MAX(DH_GRP_MIN, min); + max = MIN(DH_GRP_MAX, max); + break; + case SSH2_MSG_KEX_DH_GEX_REQUEST_OLD: + debug("SSH2_MSG_KEX_DH_GEX_REQUEST_OLD received"); + nbits = packet_get_int(); + min = DH_GRP_MIN; + max = DH_GRP_MAX; + /* unused for old GEX */ + break; + default: + fatal("protocol error during kex, no DH_GEX_REQUEST: %d", type); + } + packet_check_eom(); + + if (max < min || nbits < min || max < nbits) + fatal("DH_GEX_REQUEST, bad parameters: %d !< %d !< %d", + min, nbits, max); + + /* Contact privileged parent */ + dh = PRIVSEP(choose_dh(min, nbits, max)); + if (dh == NULL) + packet_disconnect("Protocol error: no matching DH grp found"); + + debug("SSH2_MSG_KEX_DH_GEX_GROUP sent"); + packet_start(SSH2_MSG_KEX_DH_GEX_GROUP); + packet_put_bignum2(dh->p); + packet_put_bignum2(dh->g); + packet_send(); + + /* flush */ + packet_write_wait(); + + /* Compute our exchange value in parallel with the client */ + dh_gen_key(dh, kex->we_need * 8); + + debug("expecting SSH2_MSG_KEX_DH_GEX_INIT"); + packet_read_expect(SSH2_MSG_KEX_DH_GEX_INIT); + + /* key, cert */ + if ((dh_client_pub = BN_new()) == NULL) + fatal("dh_client_pub == NULL"); + packet_get_bignum2(dh_client_pub); + packet_check_eom(); + +#ifdef DEBUG_KEXDH + fprintf(stderr, "dh_client_pub= "); + BN_print_fp(stderr, dh_client_pub); + fprintf(stderr, "\n"); + debug("bits %d", BN_num_bits(dh_client_pub)); +#endif + +#ifdef DEBUG_KEXDH + DHparams_print_fp(stderr, dh); + fprintf(stderr, "pub= "); + BN_print_fp(stderr, dh->pub_key); + fprintf(stderr, "\n"); +#endif + if (!dh_pub_is_valid(dh, dh_client_pub)) + packet_disconnect("bad client public DH value"); + + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_client_pub, dh); +#ifdef DEBUG_KEXDH + dump_digest("shared secret", kbuf, kout); +#endif + if ((shared_secret = BN_new()) == NULL) + fatal("kexgex_server: BN_new failed"); + BN_bin2bn(kbuf, kout, shared_secret); + memset(kbuf, 0, klen); + xfree(kbuf); + + key_to_blob(server_host_key, &server_host_key_blob, &sbloblen); + + if (type == SSH2_MSG_KEX_DH_GEX_REQUEST_OLD) + min = max = -1; + + /* calc H */ /* XXX depends on 'kex' */ + hash = kexgex_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + buffer_ptr(&kex->my), buffer_len(&kex->my), + server_host_key_blob, sbloblen, + min, nbits, max, + dh->p, dh->g, + dh_client_pub, + dh->pub_key, + shared_secret + ); + BN_clear_free(dh_client_pub); + + /* save session id := H */ + /* XXX hashlen depends on KEX */ + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + memcpy(kex->session_id, hash, kex->session_id_len); + } + + /* sign H */ + /* XXX hashlen depends on KEX */ + PRIVSEP(key_sign(server_host_key, &signature, &slen, hash, 20)); + + /* destroy_sensitive_data(); */ + + /* send server hostkey, DH pubkey 'f' and singed H */ + debug("SSH2_MSG_KEX_DH_GEX_REPLY sent"); + packet_start(SSH2_MSG_KEX_DH_GEX_REPLY); + packet_put_string(server_host_key_blob, sbloblen); + packet_put_bignum2(dh->pub_key); /* f */ + packet_put_string(signature, slen); + packet_send(); + + xfree(signature); + xfree(server_host_key_blob); + /* have keys, free DH */ + DH_free(dh); + + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + + kex_finish(kex); +} diff --git a/usr/src/cmd/ssh/libssh/common/kexgssc.c b/usr/src/cmd/ssh/libssh/common/kexgssc.c new file mode 100644 index 0000000000..815044733d --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexgssc.c @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + + +#include "includes.h" + +#ifdef GSSAPI + +#include <openssl/crypto.h> +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "canohost.h" +#include "ssh2.h" +#include "ssh-gss.h" + +extern char *xxx_host; + +Gssctxt *xxx_gssctxt; + +static void kexgss_verbose_cleanup(void *arg); + +void +kexgss_client(Kex *kex) +{ + gss_buffer_desc gssbuf,send_tok,recv_tok, msg_tok; + gss_buffer_t token_ptr; + gss_OID mech = GSS_C_NULL_OID; + Gssctxt *ctxt = NULL; + OM_uint32 maj_status, min_status, smaj_status, smin_status; + unsigned int klen, kout; + DH *dh; + BIGNUM *dh_server_pub = 0; + BIGNUM *shared_secret = 0; + Key *server_host_key = NULL; + unsigned char *kbuf; + unsigned char *hash; + unsigned char *server_host_key_blob = NULL; + char *msg, *lang; + int type = 0; + int first = 1; + u_int sbloblen = 0; + u_int strlen; + + /* Map the negotiated kex name to a mech OID*/ + ssh_gssapi_oid_of_kexname(kex->name, &mech); + if (mech == GSS_C_NULL_OID) + fatal("Couldn't match the negotiated GSS key exchange"); + + ssh_gssapi_build_ctx(&ctxt, 1, mech); + + /* This code should match that in ssh_dh1_client */ + + /* Step 1 - e is dh->pub_key */ + dh = dh_new_group1(); + dh_gen_key(dh, kex->we_need * 8); + + /* This is f, we initialise it now to make life easier */ + dh_server_pub = BN_new(); + if (dh_server_pub == NULL) { + fatal("dh_server_pub == NULL"); + } + + token_ptr = GSS_C_NO_BUFFER; + + recv_tok.value=NULL; + recv_tok.length=0; + + do { + debug("Calling gss_init_sec_context"); + + maj_status=ssh_gssapi_init_ctx(ctxt, + xxx_host, + kex->options.gss_deleg_creds, + token_ptr, + &send_tok); + + if (GSS_ERROR(maj_status)) { + ssh_gssapi_error(ctxt, "performing GSS-API protected " + "SSHv2 key exchange"); + (void) gss_release_buffer(&min_status, &send_tok); + packet_disconnect("A GSS-API error occurred during " + "GSS-API protected SSHv2 key exchange\n"); + } + + /* If we've got an old receive buffer get rid of it */ + if (token_ptr != GSS_C_NO_BUFFER) { + /* We allocated recv_tok */ + xfree(recv_tok.value); + recv_tok.value = NULL; + recv_tok.length = 0; + token_ptr = GSS_C_NO_BUFFER; + } + + if (maj_status == GSS_S_COMPLETE) { + /* If mutual state flag is not true, kex fails */ + if (!(ctxt->flags & GSS_C_MUTUAL_FLAG)) { + fatal("Mutual authentication failed"); + } + /* If integ avail flag is not true kex fails */ + if (!(ctxt->flags & GSS_C_INTEG_FLAG)) { + fatal("Integrity check failed"); + } + } + + /* If we have data to send, then the last message that we + * received cannot have been a 'complete'. */ + if (send_tok.length !=0) { + if (first) { + packet_start(SSH2_MSG_KEXGSS_INIT); + packet_put_string(send_tok.value, + send_tok.length); + packet_put_bignum2(dh->pub_key); + first=0; + } else { + packet_start(SSH2_MSG_KEXGSS_CONTINUE); + packet_put_string(send_tok.value, + send_tok.length); + } + (void) gss_release_buffer(&min_status, &send_tok); + packet_send(); + packet_write_wait(); + + + /* If we've sent them data, they'd better be polite + * and reply. */ + +next_packet: + /* + * We need to catch connection closing w/o error + * tokens or messages so we can tell the user + * _something_ more useful than "Connection + * closed by ..." + * + * We use a fatal cleanup function as that's + * all, really, that we can do for now. + */ + fatal_add_cleanup(kexgss_verbose_cleanup, NULL); + type = packet_read(); + fatal_remove_cleanup(kexgss_verbose_cleanup, NULL); + switch (type) { + case SSH2_MSG_KEXGSS_HOSTKEY: + debug("Received KEXGSS_HOSTKEY"); + server_host_key_blob = + packet_get_string(&sbloblen); + server_host_key = + key_from_blob(server_host_key_blob, + sbloblen); + goto next_packet; /* there MUSt be another */ + break; + case SSH2_MSG_KEXGSS_CONTINUE: + debug("Received GSSAPI_CONTINUE"); + if (maj_status == GSS_S_COMPLETE) + packet_disconnect("Protocol error: " + "received GSS-API context token" + " though the context was already" + " established"); + recv_tok.value=packet_get_string(&strlen); + recv_tok.length=strlen; /* u_int vs. size_t */ + break; + case SSH2_MSG_KEXGSS_COMPLETE: + debug("Received GSSAPI_COMPLETE"); + packet_get_bignum2(dh_server_pub); + msg_tok.value=packet_get_string(&strlen); + msg_tok.length=strlen; /* u_int vs. size_t */ + + /* Is there a token included? */ + if (packet_get_char()) { + recv_tok.value= + packet_get_string(&strlen); + recv_tok.length=strlen; /*u_int/size_t*/ + } + if (recv_tok.length > 0 && + maj_status == GSS_S_COMPLETE) { + packet_disconnect("Protocol error: " + "received GSS-API context token" + " though the context was already" + " established"); + } else if (recv_tok.length == 0 && + maj_status == GSS_S_CONTINUE_NEEDED) { + /* No token included */ + packet_disconnect("Protocol error: " + "did not receive expected " + "GSS-API context token"); + } + break; + case SSH2_MSG_KEXGSS_ERROR: + smaj_status=packet_get_int(); + smin_status=packet_get_int(); + msg = packet_get_string(NULL); + lang = packet_get_string(NULL); + xfree(lang); + error("Server had a GSS-API error; the " + "connection will close (%d/%d):\n%s", + smaj_status, smin_status, msg); + error("Use the GssKeyEx option to disable " + "GSS-API key exchange and try again."); + packet_disconnect("The server had a GSS-API " + "error during GSS-API protected SSHv2 " + "key exchange\n"); + break; + default: + packet_disconnect("Protocol error: " + "didn't expect packet type %d", type); + } + if (recv_tok.value) + token_ptr=&recv_tok; + } else { + /* No data, and not complete */ + if (maj_status != GSS_S_COMPLETE) { + fatal("Not complete, and no token output"); + } + } + } while (maj_status == GSS_S_CONTINUE_NEEDED); + + /* We _must_ have received a COMPLETE message in reply from the + * server, which will have set dh_server_pub and msg_tok */ + + if (type != SSH2_MSG_KEXGSS_COMPLETE) + fatal("Expected SSH2_MSG_KEXGSS_COMPLETE never arrived"); + if (maj_status != GSS_S_COMPLETE) + fatal("Internal error in GSS-API protected SSHv2 key exchange"); + + /* Check f in range [1, p-1] */ + if (!dh_pub_is_valid(dh, dh_server_pub)) + packet_disconnect("bad server public DH value"); + + /* compute K=f^x mod p */ + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_server_pub, dh); + + shared_secret = BN_new(); + BN_bin2bn(kbuf,kout, shared_secret); + (void) memset(kbuf, 0, klen); + xfree(kbuf); + + /* The GSS hash is identical to the DH one */ + hash = kex_dh_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->my), buffer_len(&kex->my), + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + server_host_key_blob, sbloblen, /* server host key */ + dh->pub_key, /* e */ + dh_server_pub, /* f */ + shared_secret /* K */ + ); + + gssbuf.value=hash; + gssbuf.length=20; + + /* Verify that H matches the token we just got. */ + if ((maj_status = gss_verify_mic(&min_status, + ctxt->context, + &gssbuf, + &msg_tok, + NULL))) { + + packet_disconnect("Hash's MIC didn't verify"); + } + + if (server_host_key && kex->accept_host_key != NULL) + (void) kex->accept_host_key(server_host_key); + + DH_free(dh); + + xxx_gssctxt = ctxt; /* for gss keyex w/ mic userauth */ + + /* save session id */ + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + (void) memcpy(kex->session_id, hash, kex->session_id_len); + } + + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + kex_finish(kex); +} + +/* ARGSUSED */ +static +void +kexgss_verbose_cleanup(void *arg) +{ + error("The GSS-API protected key exchange has failed without " + "indication\nfrom the server, possibly due to misconfiguration " + "of the server."); + error("Use the GssKeyEx option to disable GSS-API key exchange " + "and try again."); +} + +#endif /* GSSAPI */ diff --git a/usr/src/cmd/ssh/libssh/common/kexgsss.c b/usr/src/cmd/ssh/libssh/common/kexgsss.c new file mode 100644 index 0000000000..d777874feb --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/kexgsss.c @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "includes.h" + +#ifdef GSSAPI + +#include <openssl/crypto.h> +#include <openssl/bn.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "compat.h" +#include "kex.h" +#include "log.h" +#include "packet.h" +#include "dh.h" +#include "ssh2.h" +#include "ssh-gss.h" +#include "monitor_wrap.h" + +Gssctxt *xxx_gssctxt; + +static void kex_gss_send_error(Gssctxt *ctxt); + +void +kexgss_server(Kex *kex) +{ + OM_uint32 maj_status, min_status; + gss_buffer_desc gssbuf, send_tok, recv_tok, msg_tok; + Gssctxt *ctxt = NULL; + unsigned int klen, kout; + unsigned int sbloblen = 0; + unsigned char *kbuf, *hash; + unsigned char *server_host_key_blob = NULL; + DH *dh; + Key *server_host_key = NULL; + BIGNUM *shared_secret = NULL; + BIGNUM *dh_client_pub = NULL; + int type =0; + u_int slen; + gss_OID oid; + + /* + * Load host key to advertise in a SSH_MSG_KEXGSS_HOSTKEY packet + * -- unlike KEX_DH/KEX_GEX no host key, no problem since it's + * the GSS-API that provides for server host authentication. + */ + if (kex->load_host_key != NULL && + !(datafellows & SSH_BUG_GSSKEX_HOSTKEY)) + server_host_key = kex->load_host_key(kex->hostkey_type); + if (server_host_key != NULL) + key_to_blob(server_host_key, &server_host_key_blob, &sbloblen); + + + /* Initialise GSSAPI */ + + ssh_gssapi_oid_of_kexname(kex->name, &oid); + if (oid == GSS_C_NULL_OID) { + fatal("Couldn't match the negotiated GSS key exchange"); + } + + ssh_gssapi_build_ctx(&ctxt, 0, oid); + + xxx_gssctxt = ctxt; + + do { + debug("Wait SSH2_MSG_GSSAPI_INIT"); + type = packet_read(); + switch(type) { + case SSH2_MSG_KEXGSS_INIT: + if (dh_client_pub!=NULL) + fatal("Received KEXGSS_INIT after initialising"); + recv_tok.value=packet_get_string(&slen); + recv_tok.length=slen; /* int vs. size_t */ + + dh_client_pub = BN_new(); + + if (dh_client_pub == NULL) + fatal("dh_client_pub == NULL"); + packet_get_bignum2(dh_client_pub); + + /* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */ + if (sbloblen) { + packet_start(SSH2_MSG_KEXGSS_HOSTKEY); + packet_put_string(server_host_key_blob, sbloblen); + packet_send(); + packet_write_wait(); + } + break; + case SSH2_MSG_KEXGSS_CONTINUE: + recv_tok.value=packet_get_string(&slen); + recv_tok.length=slen; /* int vs. size_t */ + break; + default: + packet_disconnect("Protocol error: didn't expect packet type %d", + type); + } + + maj_status=PRIVSEP(ssh_gssapi_accept_ctx(ctxt,&recv_tok, + &send_tok)); + + xfree(recv_tok.value); /* We allocated this, not gss */ + + if (dh_client_pub == NULL) + fatal("No client public key"); + + if (maj_status == GSS_S_CONTINUE_NEEDED) { + debug("Sending GSSAPI_CONTINUE"); + packet_start(SSH2_MSG_KEXGSS_CONTINUE); + packet_put_string(send_tok.value,send_tok.length); + packet_send(); + packet_write_wait(); + (void) gss_release_buffer(&min_status, &send_tok); + } + } while (maj_status == GSS_S_CONTINUE_NEEDED); + + if (GSS_ERROR(maj_status)) { + kex_gss_send_error(ctxt); + if (send_tok.length>0) { + packet_start(SSH2_MSG_KEXGSS_CONTINUE); + packet_put_string(send_tok.value,send_tok.length); + packet_send(); + packet_write_wait(); + (void) gss_release_buffer(&min_status, &send_tok); + } + fatal("accept_ctx died"); + } + + debug("gss_complete"); + if (!(ctxt->flags & GSS_C_MUTUAL_FLAG)) + fatal("Mutual authentication flag wasn't set"); + + if (!(ctxt->flags & GSS_C_INTEG_FLAG)) + fatal("Integrity flag wasn't set"); + + dh = dh_new_group1(); + dh_gen_key(dh, kex->we_need * 8); + + if (!dh_pub_is_valid(dh, dh_client_pub)) + packet_disconnect("bad client public DH value"); + + klen = DH_size(dh); + kbuf = xmalloc(klen); + kout = DH_compute_key(kbuf, dh_client_pub, dh); + + shared_secret = BN_new(); + BN_bin2bn(kbuf, kout, shared_secret); + (void) memset(kbuf, 0, klen); + xfree(kbuf); + + /* The GSSAPI hash is identical to the Diffie Helman one */ + hash = kex_dh_hash( + kex->client_version_string, + kex->server_version_string, + buffer_ptr(&kex->peer), buffer_len(&kex->peer), + buffer_ptr(&kex->my), buffer_len(&kex->my), + server_host_key_blob, sbloblen, + dh_client_pub, + dh->pub_key, + shared_secret + ); + BN_free(dh_client_pub); + + if (kex->session_id == NULL) { + kex->session_id_len = 20; + kex->session_id = xmalloc(kex->session_id_len); + (void) memcpy(kex->session_id, hash, kex->session_id_len); + } + + /* Should fix kex_dh_hash to output hash length */ + gssbuf.length = 20; /* yes, it's always 20 (SHA-1) */ + gssbuf.value = hash; /* and it's static constant storage */ + + if (GSS_ERROR(ssh_gssapi_get_mic(ctxt,&gssbuf,&msg_tok))) { + kex_gss_send_error(ctxt); + fatal("Couldn't get MIC"); + } + + packet_start(SSH2_MSG_KEXGSS_COMPLETE); + packet_put_bignum2(dh->pub_key); + packet_put_string((char *)msg_tok.value,msg_tok.length); + (void) gss_release_buffer(&min_status, &msg_tok); + + if (send_tok.length != 0) { + packet_put_char(1); /* true */ + packet_put_string((char *)send_tok.value,send_tok.length); + (void) gss_release_buffer(&min_status, &send_tok); + } else { + packet_put_char(0); /* false */ + } + packet_send(); + packet_write_wait(); + + DH_free(dh); + + kex_derive_keys(kex, hash, shared_secret); + BN_clear_free(shared_secret); + kex_finish(kex); +} + +static void +kex_gss_send_error(Gssctxt *ctxt) { + char *errstr; + OM_uint32 maj,min; + + errstr = ssh_gssapi_last_error(ctxt,&maj,&min); + if (errstr) { + packet_start(SSH2_MSG_KEXGSS_ERROR); + packet_put_int(maj); + packet_put_int(min); + packet_put_cstring(errstr); + packet_put_cstring(""); + packet_send(); + packet_write_wait(); + /* XXX - We should probably log the error locally here */ + xfree(errstr); + } +} +#endif /* GSSAPI */ diff --git a/usr/src/cmd/ssh/libssh/common/key.c b/usr/src/cmd/ssh/libssh/common/key.c new file mode 100644 index 0000000000..8f2f488912 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/key.c @@ -0,0 +1,860 @@ +/* + * read_bignum(): + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "includes.h" +RCSID("$OpenBSD: key.c,v 1.49 2002/09/09 14:54:14 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/evp.h> + +#include "xmalloc.h" +#include "key.h" +#include "rsa.h" +#include "ssh-dss.h" +#include "ssh-rsa.h" +#include "uuencode.h" +#include "buffer.h" +#include "bufaux.h" +#include "log.h" + +Key * +key_new(int type) +{ + Key *k; + RSA *rsa; + DSA *dsa; + k = xmalloc(sizeof(*k)); + k->type = type; + k->flags = 0; + k->dsa = NULL; + k->rsa = NULL; + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + if ((rsa = RSA_new()) == NULL) + fatal("key_new: RSA_new failed"); + if ((rsa->n = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + if ((rsa->e = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + k->rsa = rsa; + break; + case KEY_DSA: + if ((dsa = DSA_new()) == NULL) + fatal("key_new: DSA_new failed"); + if ((dsa->p = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + if ((dsa->q = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + if ((dsa->g = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + if ((dsa->pub_key = BN_new()) == NULL) + fatal("key_new: BN_new failed"); + k->dsa = dsa; + break; + case KEY_UNSPEC: + break; + default: + fatal("key_new: bad key type %d", k->type); + break; + } + return k; +} + +Key * +key_new_private(int type) +{ + Key *k = key_new(type); + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + if ((k->rsa->d = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + if ((k->rsa->iqmp = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + if ((k->rsa->q = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + if ((k->rsa->p = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + if ((k->rsa->dmq1 = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + if ((k->rsa->dmp1 = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + break; + case KEY_DSA: + if ((k->dsa->priv_key = BN_new()) == NULL) + fatal("key_new_private: BN_new failed"); + break; + case KEY_UNSPEC: + break; + default: + break; + } + return k; +} + +void +key_free(Key *k) +{ + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + if (k->rsa != NULL) + RSA_free(k->rsa); + k->rsa = NULL; + break; + case KEY_DSA: + if (k->dsa != NULL) + DSA_free(k->dsa); + k->dsa = NULL; + break; + case KEY_UNSPEC: + break; + default: + fatal("key_free: bad key type %d", k->type); + break; + } + xfree(k); +} +int +key_equal(Key *a, Key *b) +{ + if (a == NULL || b == NULL || a->type != b->type) + return 0; + switch (a->type) { + case KEY_RSA1: + case KEY_RSA: + return a->rsa != NULL && b->rsa != NULL && + BN_cmp(a->rsa->e, b->rsa->e) == 0 && + BN_cmp(a->rsa->n, b->rsa->n) == 0; + break; + case KEY_DSA: + return a->dsa != NULL && b->dsa != NULL && + BN_cmp(a->dsa->p, b->dsa->p) == 0 && + BN_cmp(a->dsa->q, b->dsa->q) == 0 && + BN_cmp(a->dsa->g, b->dsa->g) == 0 && + BN_cmp(a->dsa->pub_key, b->dsa->pub_key) == 0; + break; + default: + fatal("key_equal: bad key type %d", a->type); + break; + } + return 0; +} + +static u_char * +key_fingerprint_raw(Key *k, enum fp_type dgst_type, u_int *dgst_raw_length) +{ + const EVP_MD *md = NULL; + EVP_MD_CTX ctx; + u_char *blob = NULL; + u_char *retval = NULL; + u_int len = 0; + int nlen, elen; + + *dgst_raw_length = 0; + + switch (dgst_type) { + case SSH_FP_MD5: + md = EVP_md5(); + break; + case SSH_FP_SHA1: + md = EVP_sha1(); + break; + default: + fatal("key_fingerprint_raw: bad digest type %d", + dgst_type); + } + switch (k->type) { + case KEY_RSA1: + nlen = BN_num_bytes(k->rsa->n); + elen = BN_num_bytes(k->rsa->e); + len = nlen + elen; + blob = xmalloc(len); + BN_bn2bin(k->rsa->n, blob); + BN_bn2bin(k->rsa->e, blob + nlen); + break; + case KEY_DSA: + case KEY_RSA: + key_to_blob(k, &blob, &len); + break; + case KEY_UNSPEC: + return retval; + break; + default: + fatal("key_fingerprint_raw: bad key type %d", k->type); + break; + } + if (blob != NULL) { + retval = xmalloc(EVP_MAX_MD_SIZE); + EVP_DigestInit(&ctx, md); + EVP_DigestUpdate(&ctx, blob, len); + EVP_DigestFinal(&ctx, retval, dgst_raw_length); + memset(blob, 0, len); + xfree(blob); + } else { + fatal("key_fingerprint_raw: blob is null"); + } + return retval; +} + +static char * +key_fingerprint_hex(u_char *dgst_raw, u_int dgst_raw_len) +{ + char *retval; + int i; + + retval = xmalloc(dgst_raw_len * 3 + 1); + retval[0] = '\0'; + for (i = 0; i < dgst_raw_len; i++) { + char hex[4]; + snprintf(hex, sizeof(hex), "%02x:", dgst_raw[i]); + strlcat(retval, hex, dgst_raw_len * 3); + } + retval[(dgst_raw_len * 3) - 1] = '\0'; + return retval; +} + +static char * +key_fingerprint_bubblebabble(u_char *dgst_raw, u_int dgst_raw_len) +{ + char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' }; + char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm', + 'n', 'p', 'r', 's', 't', 'v', 'z', 'x' }; + u_int i, j = 0, rounds, seed = 1; + char *retval; + + rounds = (dgst_raw_len / 2) + 1; + retval = xmalloc(sizeof(char) * (rounds*6)); + retval[j++] = 'x'; + for (i = 0; i < rounds; i++) { + u_int idx0, idx1, idx2, idx3, idx4; + if ((i + 1 < rounds) || (dgst_raw_len % 2 != 0)) { + idx0 = (((((u_int)(dgst_raw[2 * i])) >> 6) & 3) + + seed) % 6; + idx1 = (((u_int)(dgst_raw[2 * i])) >> 2) & 15; + idx2 = ((((u_int)(dgst_raw[2 * i])) & 3) + + (seed / 6)) % 6; + retval[j++] = vowels[idx0]; + retval[j++] = consonants[idx1]; + retval[j++] = vowels[idx2]; + if ((i + 1) < rounds) { + idx3 = (((u_int)(dgst_raw[(2 * i) + 1])) >> 4) & 15; + idx4 = (((u_int)(dgst_raw[(2 * i) + 1]))) & 15; + retval[j++] = consonants[idx3]; + retval[j++] = '-'; + retval[j++] = consonants[idx4]; + seed = ((seed * 5) + + ((((u_int)(dgst_raw[2 * i])) * 7) + + ((u_int)(dgst_raw[(2 * i) + 1])))) % 36; + } + } else { + idx0 = seed % 6; + idx1 = 16; + idx2 = seed / 6; + retval[j++] = vowels[idx0]; + retval[j++] = consonants[idx1]; + retval[j++] = vowels[idx2]; + } + } + retval[j++] = 'x'; + retval[j++] = '\0'; + return retval; +} + +char * +key_fingerprint(Key *k, enum fp_type dgst_type, enum fp_rep dgst_rep) +{ + char *retval = NULL; + u_char *dgst_raw; + u_int dgst_raw_len; + + dgst_raw = key_fingerprint_raw(k, dgst_type, &dgst_raw_len); + if (!dgst_raw) + fatal("key_fingerprint: null from key_fingerprint_raw()"); + switch (dgst_rep) { + case SSH_FP_HEX: + retval = key_fingerprint_hex(dgst_raw, dgst_raw_len); + break; + case SSH_FP_BUBBLEBABBLE: + retval = key_fingerprint_bubblebabble(dgst_raw, dgst_raw_len); + break; + default: + fatal("key_fingerprint_ex: bad digest representation %d", + dgst_rep); + break; + } + memset(dgst_raw, 0, dgst_raw_len); + xfree(dgst_raw); + return retval; +} + +/* + * Reads a multiple-precision integer in decimal from the buffer, and advances + * the pointer. The integer must already be initialized. This function is + * permitted to modify the buffer. This leaves *cpp to point just beyond the + * last processed (and maybe modified) character. Note that this may modify + * the buffer containing the number. + */ +static int +read_bignum(char **cpp, BIGNUM * value) +{ + char *cp = *cpp; + int old; + + /* Skip any leading whitespace. */ + for (; *cp == ' ' || *cp == '\t'; cp++) + ; + + /* Check that it begins with a decimal digit. */ + if (*cp < '0' || *cp > '9') + return 0; + + /* Save starting position. */ + *cpp = cp; + + /* Move forward until all decimal digits skipped. */ + for (; *cp >= '0' && *cp <= '9'; cp++) + ; + + /* Save the old terminating character, and replace it by \0. */ + old = *cp; + *cp = 0; + + /* Parse the number. */ + if (BN_dec2bn(&value, *cpp) == 0) + return 0; + + /* Restore old terminating character. */ + *cp = old; + + /* Move beyond the number and return success. */ + *cpp = cp; + return 1; +} + +static int +write_bignum(FILE *f, BIGNUM *num) +{ + char *buf = BN_bn2dec(num); + if (buf == NULL) { + error("write_bignum: BN_bn2dec() failed"); + return 0; + } + fprintf(f, " %s", buf); + OPENSSL_free(buf); + return 1; +} + +/* returns 1 ok, -1 error */ +int +key_read(Key *ret, char **cpp) +{ + Key *k; + int success = -1; + char *cp, *space; + int len, n, type; + u_int bits; + u_char *blob; + + cp = *cpp; + + switch (ret->type) { + case KEY_RSA1: + /* Get number of bits. */ + if (*cp < '0' || *cp > '9') + return -1; /* Bad bit count... */ + for (bits = 0; *cp >= '0' && *cp <= '9'; cp++) + bits = 10 * bits + *cp - '0'; + if (bits == 0) + return -1; + *cpp = cp; + /* Get public exponent, public modulus. */ + if (!read_bignum(cpp, ret->rsa->e)) + return -1; + if (!read_bignum(cpp, ret->rsa->n)) + return -1; + success = 1; + break; + case KEY_UNSPEC: + case KEY_RSA: + case KEY_DSA: + space = strchr(cp, ' '); + if (space == NULL) { + debug3("key_read: no space"); + return -1; + } + *space = '\0'; + type = key_type_from_name(cp); + *space = ' '; + if (type == KEY_UNSPEC) { + debug3("key_read: no key found"); + return -1; + } + cp = space+1; + if (*cp == '\0') { + debug3("key_read: short string"); + return -1; + } + if (ret->type == KEY_UNSPEC) { + ret->type = type; + } else if (ret->type != type) { + /* is a key, but different type */ + debug3("key_read: type mismatch"); + return -1; + } + len = 2*strlen(cp); + blob = xmalloc(len); + n = uudecode(cp, blob, len); + if (n < 0) { + error("key_read: uudecode %s failed", cp); + xfree(blob); + return -1; + } + k = key_from_blob(blob, n); + xfree(blob); + if (k == NULL) { + error("key_read: key_from_blob %s failed", cp); + return -1; + } + if (k->type != type) { + error("key_read: type mismatch: encoding error"); + key_free(k); + return -1; + } +/*XXXX*/ + if (ret->type == KEY_RSA) { + if (ret->rsa != NULL) + RSA_free(ret->rsa); + ret->rsa = k->rsa; + k->rsa = NULL; + success = 1; +#ifdef DEBUG_PK + RSA_print_fp(stderr, ret->rsa, 8); +#endif + } else { + if (ret->dsa != NULL) + DSA_free(ret->dsa); + ret->dsa = k->dsa; + k->dsa = NULL; + success = 1; +#ifdef DEBUG_PK + DSA_print_fp(stderr, ret->dsa, 8); +#endif + } +/*XXXX*/ + key_free(k); + if (success != 1) + break; + /* advance cp: skip whitespace and data */ + while (*cp == ' ' || *cp == '\t') + cp++; + while (*cp != '\0' && *cp != ' ' && *cp != '\t') + cp++; + *cpp = cp; + break; + default: + fatal("key_read: bad key type: %d", ret->type); + break; + } + return success; +} + +int +key_write(Key *key, FILE *f) +{ + int n, success = 0; + u_int len, bits = 0; + u_char *blob; + char *uu; + + if (key->type == KEY_RSA1 && key->rsa != NULL) { + /* size of modulus 'n' */ + bits = BN_num_bits(key->rsa->n); + fprintf(f, "%u", bits); + if (write_bignum(f, key->rsa->e) && + write_bignum(f, key->rsa->n)) { + success = 1; + } else { + error("key_write: failed for RSA key"); + } + } else if ((key->type == KEY_DSA && key->dsa != NULL) || + (key->type == KEY_RSA && key->rsa != NULL)) { + key_to_blob(key, &blob, &len); + uu = xmalloc(2*len); + n = uuencode(blob, len, uu, 2*len); + if (n > 0) { + fprintf(f, "%s %s", key_ssh_name(key), uu); + success = 1; + } + xfree(blob); + xfree(uu); + } + return success; +} + +char * +key_type(Key *k) +{ + switch (k->type) { + case KEY_RSA1: + return "RSA1"; + break; + case KEY_RSA: + return "RSA"; + break; + case KEY_DSA: + return "DSA"; + break; + } + return "unknown"; +} + +char * +key_ssh_name(Key *k) +{ + switch (k->type) { + case KEY_RSA: + return "ssh-rsa"; + break; + case KEY_DSA: + return "ssh-dss"; + break; + } + return "ssh-unknown"; +} + +u_int +key_size(Key *k) +{ + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + return BN_num_bits(k->rsa->n); + break; + case KEY_DSA: + return BN_num_bits(k->dsa->p); + break; + } + return 0; +} + +static RSA * +rsa_generate_private_key(u_int bits) +{ + RSA *private; + private = RSA_generate_key(bits, 35, NULL, NULL); + if (private == NULL) + fatal("rsa_generate_private_key: key generation failed."); + return private; +} + +static DSA* +dsa_generate_private_key(u_int bits) +{ + DSA *private = DSA_generate_parameters(bits, NULL, 0, NULL, NULL, NULL, NULL); + if (private == NULL) + fatal("dsa_generate_private_key: DSA_generate_parameters failed"); + if (!DSA_generate_key(private)) + fatal("dsa_generate_private_key: DSA_generate_key failed."); + if (private == NULL) + fatal("dsa_generate_private_key: NULL."); + return private; +} + +Key * +key_generate(int type, u_int bits) +{ + Key *k = key_new(KEY_UNSPEC); + switch (type) { + case KEY_DSA: + k->dsa = dsa_generate_private_key(bits); + break; + case KEY_RSA: + case KEY_RSA1: + k->rsa = rsa_generate_private_key(bits); + break; + default: + fatal("key_generate: unknown type %d", type); + } + k->type = type; + return k; +} + +Key * +key_from_private(Key *k) +{ + Key *n = NULL; + switch (k->type) { + case KEY_DSA: + n = key_new(k->type); + BN_copy(n->dsa->p, k->dsa->p); + BN_copy(n->dsa->q, k->dsa->q); + BN_copy(n->dsa->g, k->dsa->g); + BN_copy(n->dsa->pub_key, k->dsa->pub_key); + break; + case KEY_RSA: + case KEY_RSA1: + n = key_new(k->type); + BN_copy(n->rsa->n, k->rsa->n); + BN_copy(n->rsa->e, k->rsa->e); + break; + default: + fatal("key_from_private: unknown type %d", k->type); + break; + } + return n; +} + +int +key_type_from_name(char *name) +{ + if (strcmp(name, "rsa1") == 0) { + return KEY_RSA1; + } else if (strcmp(name, "rsa") == 0) { + return KEY_RSA; + } else if (strcmp(name, "dsa") == 0) { + return KEY_DSA; + } else if (strcmp(name, "ssh-rsa") == 0) { + return KEY_RSA; + } else if (strcmp(name, "ssh-dss") == 0) { + return KEY_DSA; + } else if (strcmp(name, "null") == 0){ + return KEY_NULL; + } + debug2("key_type_from_name: unknown key type '%s'", name); + return KEY_UNSPEC; +} + +int +key_names_valid2(const char *names) +{ + char *s, *cp, *p; + + if (names == NULL || strcmp(names, "") == 0) + return 0; + s = cp = xstrdup(names); + for ((p = strsep(&cp, ",")); p && *p != '\0'; + (p = strsep(&cp, ","))) { + switch (key_type_from_name(p)) { + case KEY_RSA1: + case KEY_UNSPEC: + xfree(s); + return 0; + } + } + debug3("key names ok: [%s]", names); + xfree(s); + return 1; +} + +Key * +key_from_blob(u_char *blob, int blen) +{ + Buffer b; + char *ktype; + int rlen, type; + Key *key = NULL; + +#ifdef DEBUG_PK + dump_base64(stderr, blob, blen); +#endif + buffer_init(&b); + buffer_append(&b, blob, blen); + ktype = buffer_get_string(&b, NULL); + type = key_type_from_name(ktype); + + switch (type) { + case KEY_RSA: + key = key_new(type); + buffer_get_bignum2(&b, key->rsa->e); + buffer_get_bignum2(&b, key->rsa->n); +#ifdef DEBUG_PK + RSA_print_fp(stderr, key->rsa, 8); +#endif + break; + case KEY_DSA: + key = key_new(type); + buffer_get_bignum2(&b, key->dsa->p); + buffer_get_bignum2(&b, key->dsa->q); + buffer_get_bignum2(&b, key->dsa->g); + buffer_get_bignum2(&b, key->dsa->pub_key); +#ifdef DEBUG_PK + DSA_print_fp(stderr, key->dsa, 8); +#endif + break; + case KEY_UNSPEC: + key = key_new(type); + break; + default: + error("key_from_blob: cannot handle type %s", ktype); + break; + } + rlen = buffer_len(&b); + if (key != NULL && rlen != 0) + error("key_from_blob: remaining bytes in key blob %d", rlen); + xfree(ktype); + buffer_free(&b); + return key; +} + +int +key_to_blob(Key *key, u_char **blobp, u_int *lenp) +{ + Buffer b; + int len; + + if (key == NULL) { + error("key_to_blob: key == NULL"); + return 0; + } + buffer_init(&b); + switch (key->type) { + case KEY_DSA: + buffer_put_cstring(&b, key_ssh_name(key)); + buffer_put_bignum2(&b, key->dsa->p); + buffer_put_bignum2(&b, key->dsa->q); + buffer_put_bignum2(&b, key->dsa->g); + buffer_put_bignum2(&b, key->dsa->pub_key); + break; + case KEY_RSA: + buffer_put_cstring(&b, key_ssh_name(key)); + buffer_put_bignum2(&b, key->rsa->e); + buffer_put_bignum2(&b, key->rsa->n); + break; + default: + error("key_to_blob: unsupported key type %d", key->type); + buffer_free(&b); + return 0; + } + len = buffer_len(&b); + if (lenp != NULL) + *lenp = len; + if (blobp != NULL) { + *blobp = xmalloc(len); + memcpy(*blobp, buffer_ptr(&b), len); + } + memset(buffer_ptr(&b), 0, len); + buffer_free(&b); + return len; +} + +int +key_sign( + Key *key, + u_char **sigp, u_int *lenp, + u_char *data, u_int datalen) +{ + switch (key->type) { + case KEY_DSA: + return ssh_dss_sign(key, sigp, lenp, data, datalen); + break; + case KEY_RSA: + return ssh_rsa_sign(key, sigp, lenp, data, datalen); + break; + default: + error("key_sign: illegal key type %d", key->type); + return -1; + break; + } +} + +/* + * key_verify returns 1 for a correct signature, 0 for an incorrect signature + * and -1 on error. + */ +int +key_verify( + Key *key, + u_char *signature, u_int signaturelen, + u_char *data, u_int datalen) +{ + if (signaturelen == 0) + return -1; + + switch (key->type) { + case KEY_DSA: + return ssh_dss_verify(key, signature, signaturelen, data, datalen); + break; + case KEY_RSA: + return ssh_rsa_verify(key, signature, signaturelen, data, datalen); + break; + default: + error("key_verify: illegal key type %d", key->type); + return -1; + break; + } +} + +/* Converts a private to a public key */ +Key * +key_demote(Key *k) +{ + Key *pk; + + pk = xmalloc(sizeof(*pk)); + pk->type = k->type; + pk->flags = k->flags; + pk->dsa = NULL; + pk->rsa = NULL; + + switch (k->type) { + case KEY_RSA1: + case KEY_RSA: + if ((pk->rsa = RSA_new()) == NULL) + fatal("key_demote: RSA_new failed"); + if ((pk->rsa->e = BN_dup(k->rsa->e)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->rsa->n = BN_dup(k->rsa->n)) == NULL) + fatal("key_demote: BN_dup failed"); + break; + case KEY_DSA: + if ((pk->dsa = DSA_new()) == NULL) + fatal("key_demote: DSA_new failed"); + if ((pk->dsa->p = BN_dup(k->dsa->p)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->q = BN_dup(k->dsa->q)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->g = BN_dup(k->dsa->g)) == NULL) + fatal("key_demote: BN_dup failed"); + if ((pk->dsa->pub_key = BN_dup(k->dsa->pub_key)) == NULL) + fatal("key_demote: BN_dup failed"); + break; + default: + fatal("key_free: bad key type %d", k->type); + break; + } + + return (pk); +} diff --git a/usr/src/cmd/ssh/libssh/common/llib-lssh b/usr/src/cmd/ssh/libssh/common/llib-lssh new file mode 100644 index 0000000000..321ed7d2e3 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/llib-lssh @@ -0,0 +1,141 @@ +/* LINTLIBRARY */ +/* PROTOLIB1 */ + +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <includes.h> +#include <ssh.h> +#include <atomicio.h> +#include <auth.h> +#include <auth-pam.h> +#include <auth2-pam.h> +#include <authfd.h> +#include <authfile.h> +#include <auth-options.h> +#include <base64.h> +#include <bindresvport.h> +#include <bsd-arc4random.h> +#include <bsd-cray.h> +#include <bsd-cygwin_util.h> +#include <bsd-getpeereid.h> +#include <bsd-misc.h> +#include <bsd-nextstep.h> +#include <bsd-snprintf.h> +#include <bsd-waitpid.h> +#include <bufaux.h> +#include <buffer.h> +#include <canohost.h> +#include <channels.h> +#include <cipher.h> +#include <clientloop.h> +#include <compat.h> +#include <compress.h> +#include <config.h> +#include <crc32.h> +#include <daemon.h> +#include <deattack.h> +#include <defines.h> +#include <dh.h> +#include <dirname.h> +#include <dispatch.h> +#include <entropy.h> +#include <fake-gai-errnos.h> +#include <fake-getaddrinfo.h> +#include <fake-getnameinfo.h> +#include <fake-socket.h> +#include <g11n.h> +#include <getcwd.h> +#include <getgrouplist.h> +#include <getopt.h> +#include <getput.h> +#include <glob.h> +#include <groupaccess.h> +#include <hostfile.h> +#include <inet_ntoa.h> +#include <inet_ntop.h> +#include <kex.h> +#include <key.h> +#include <log.h> +#include <loginrec.h> +#include <mac.h> +#include <match.h> +#include <misc.h> +#include <mktemp.h> +#include <monitor_fdpass.h> +#include <monitor.h> +#include <monitor_mm.h> +#include <monitor_wrap.h> +#include <mpaux.h> +#include <msg.h> +#include <myproposal.h> +#include <openbsd-compat.h> +#include <packet.h> +#include <pathnames.h> +#include <port-aix.h> +#include <port-irix.h> +#include <proxy-io.h> +#include <readconf.h> +#include <readpass.h> +#include <readpassphrase.h> +#include <realpath.h> +#include <rresvport.h> +#include <rsa.h> +#include <servconf.h> +#include <serverloop.h> +#include <session.h> +#include <setproctitle.h> +#include <sftp-common.h> +#include <sftp.h> +#include <sftp-int.h> +#include <sftp-glob.h> +#include <sftp-client.h> +#include <sigact.h> +#include <ssh1.h> +#include <ssh2.h> +#include <sshconnect.h> +#include <ssh-dss.h> +#include <sshlogin.h> +#include <sshpty.h> +#include <ssh-rsa.h> +#include <sshtty.h> +#include <strlcat.h> +#include <strlcpy.h> +#include <strmode.h> +#include <strsep.h> +#include <sys-queue.h> +#include <sys-tree.h> +#include <tildexpand.h> +#include <uidswap.h> +#include <uuencode.h> +#include <version.h> +#include <xlist.h> +#include <xmalloc.h> +#include <xmmap.h> + +extern uid_t original_real_uid; +extern char *__progname; + diff --git a/usr/src/cmd/ssh/libssh/common/log.c b/usr/src/cmd/ssh/libssh/common/log.c new file mode 100644 index 0000000000..4042d2ffd9 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/log.c @@ -0,0 +1,445 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: log.c,v 1.24 2002/07/19 15:43:33 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "log.h" +#include "xmalloc.h" + +#include <syslog.h> + +static LogLevel log_level = SYSLOG_LEVEL_INFO; +static int log_on_stderr = 1; +static int log_facility = LOG_AUTH; +static char *argv0; + +extern char *__progname; + +static const char *log_txt_prefix = ""; + +/* textual representation of log-facilities/levels */ + +static struct { + const char *name; + SyslogFacility val; +} log_facilities[] = { + { "DAEMON", SYSLOG_FACILITY_DAEMON }, + { "USER", SYSLOG_FACILITY_USER }, + { "AUTH", SYSLOG_FACILITY_AUTH }, +#ifdef LOG_AUTHPRIV + { "AUTHPRIV", SYSLOG_FACILITY_AUTHPRIV }, +#endif + { "LOCAL0", SYSLOG_FACILITY_LOCAL0 }, + { "LOCAL1", SYSLOG_FACILITY_LOCAL1 }, + { "LOCAL2", SYSLOG_FACILITY_LOCAL2 }, + { "LOCAL3", SYSLOG_FACILITY_LOCAL3 }, + { "LOCAL4", SYSLOG_FACILITY_LOCAL4 }, + { "LOCAL5", SYSLOG_FACILITY_LOCAL5 }, + { "LOCAL6", SYSLOG_FACILITY_LOCAL6 }, + { "LOCAL7", SYSLOG_FACILITY_LOCAL7 }, + { NULL, SYSLOG_FACILITY_NOT_SET } +}; + +static struct { + const char *name; + LogLevel val; +} log_levels[] = +{ + { "QUIET", SYSLOG_LEVEL_QUIET }, + { "FATAL", SYSLOG_LEVEL_FATAL }, + { "ERROR", SYSLOG_LEVEL_ERROR }, + { "NOTICE", SYSLOG_LEVEL_NOTICE }, + { "INFO", SYSLOG_LEVEL_INFO }, + { "VERBOSE", SYSLOG_LEVEL_VERBOSE }, + { "DEBUG", SYSLOG_LEVEL_DEBUG1 }, + { "DEBUG1", SYSLOG_LEVEL_DEBUG1 }, + { "DEBUG2", SYSLOG_LEVEL_DEBUG2 }, + { "DEBUG3", SYSLOG_LEVEL_DEBUG3 }, + { NULL, SYSLOG_LEVEL_NOT_SET } +}; + +SyslogFacility +log_facility_number(char *name) +{ + int i; + + if (name != NULL) + for (i = 0; log_facilities[i].name; i++) + if (strcasecmp(log_facilities[i].name, name) == 0) + return log_facilities[i].val; + return SYSLOG_FACILITY_NOT_SET; +} + +LogLevel +log_level_number(char *name) +{ + int i; + + if (name != NULL) + for (i = 0; log_levels[i].name; i++) + if (strcasecmp(log_levels[i].name, name) == 0) + return log_levels[i].val; + return SYSLOG_LEVEL_NOT_SET; +} + +void +set_log_txt_prefix(const char *txt) +{ + log_txt_prefix = txt; +} + +/* Error messages that should be logged. */ + +void +error(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_ERROR, fmt, args); + va_end(args); +} + +void +notice(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_NOTICE, fmt, args); + va_end(args); +} + +/* Log this message (information that usually should go to the log). */ + +void +log(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_INFO, fmt, args); + va_end(args); +} + +/* More detailed messages (information that does not need to go to the log). */ + +void +verbose(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_VERBOSE, fmt, args); + va_end(args); +} + +/* Debugging messages that should not be logged during normal operation. */ + +void +debug(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_DEBUG1, fmt, args); + va_end(args); +} + +void +debug2(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_DEBUG2, fmt, args); + va_end(args); +} + +void +debug3(const char *fmt,...) +{ + va_list args; + + va_start(args, fmt); + do_log(SYSLOG_LEVEL_DEBUG3, fmt, args); + va_end(args); +} + +/* Fatal cleanup */ + +struct fatal_cleanup { + struct fatal_cleanup *next; + void (*proc) (void *); + void *context; +}; + +static struct fatal_cleanup *fatal_cleanups = NULL; + +/* Registers a cleanup function to be called by fatal() before exiting. */ + +void +fatal_add_cleanup(void (*proc) (void *), void *context) +{ + struct fatal_cleanup *cu; + + cu = xmalloc(sizeof(*cu)); + cu->proc = proc; + cu->context = context; + cu->next = fatal_cleanups; + fatal_cleanups = cu; +} + +/* Removes a cleanup frunction to be called at fatal(). */ + +void +fatal_remove_cleanup(void (*proc) (void *context), void *context) +{ + struct fatal_cleanup **cup, *cu; + + for (cup = &fatal_cleanups; *cup; cup = &cu->next) { + cu = *cup; + if (cu->proc == proc && cu->context == context) { + *cup = cu->next; + xfree(cu); + return; + } + } + debug3("fatal_remove_cleanup: no such cleanup function: 0x%lx 0x%lx", + (u_long) proc, (u_long) context); +} + +/* Remove all cleanups, to be called after fork() */ +void +fatal_remove_all_cleanups(void) +{ + struct fatal_cleanup *cu, *next_cu; + + for (cu = fatal_cleanups; cu; cu = next_cu) { + next_cu = cu->next; + xfree(cu); + } + + fatal_cleanups = NULL; +} + +/* Cleanup and exit */ +void +fatal_cleanup(void) +{ + struct fatal_cleanup *cu, *next_cu; + static int called = 0; + + if (called) + exit(255); + called = 1; + /* Call cleanup functions. */ + for (cu = fatal_cleanups; cu; cu = next_cu) { + next_cu = cu->next; + debug("Calling cleanup 0x%lx(0x%lx)", + (u_long) cu->proc, (u_long) cu->context); + (*cu->proc) (cu->context); + } + exit(255); +} + + +/* + * Initialize the log. + */ + +void +log_init(char *av0, LogLevel level, SyslogFacility facility, int on_stderr) +{ + argv0 = av0; + + switch (level) { + case SYSLOG_LEVEL_QUIET: + case SYSLOG_LEVEL_FATAL: + case SYSLOG_LEVEL_ERROR: + case SYSLOG_LEVEL_NOTICE: + case SYSLOG_LEVEL_INFO: + case SYSLOG_LEVEL_VERBOSE: + case SYSLOG_LEVEL_DEBUG1: + case SYSLOG_LEVEL_DEBUG2: + case SYSLOG_LEVEL_DEBUG3: + log_level = level; + break; + default: + fprintf(stderr, "Unrecognized internal syslog level code %d\n", + (int) level); + exit(1); + } + + log_on_stderr = on_stderr; + if (on_stderr) + return; + + switch (facility) { + case SYSLOG_FACILITY_DAEMON: + log_facility = LOG_DAEMON; + break; + case SYSLOG_FACILITY_USER: + log_facility = LOG_USER; + break; + case SYSLOG_FACILITY_AUTH: + log_facility = LOG_AUTH; + break; +#ifdef LOG_AUTHPRIV + case SYSLOG_FACILITY_AUTHPRIV: + log_facility = LOG_AUTHPRIV; + break; +#endif + case SYSLOG_FACILITY_LOCAL0: + log_facility = LOG_LOCAL0; + break; + case SYSLOG_FACILITY_LOCAL1: + log_facility = LOG_LOCAL1; + break; + case SYSLOG_FACILITY_LOCAL2: + log_facility = LOG_LOCAL2; + break; + case SYSLOG_FACILITY_LOCAL3: + log_facility = LOG_LOCAL3; + break; + case SYSLOG_FACILITY_LOCAL4: + log_facility = LOG_LOCAL4; + break; + case SYSLOG_FACILITY_LOCAL5: + log_facility = LOG_LOCAL5; + break; + case SYSLOG_FACILITY_LOCAL6: + log_facility = LOG_LOCAL6; + break; + case SYSLOG_FACILITY_LOCAL7: + log_facility = LOG_LOCAL7; + break; + default: + fprintf(stderr, + "Unrecognized internal syslog facility code %d\n", + (int) facility); + exit(1); + } +} + +#define MSGBUFSIZ 1024 + +/* PRINTFLIKE2 */ +void +do_log(LogLevel level, const char *fmt, va_list args) +{ + char msgbuf[MSGBUFSIZ]; + char fmtbuf[MSGBUFSIZ]; + char *txt = NULL; + int pri = LOG_INFO; + int do_gettext = log_on_stderr; /* + * Localize user messages - not + * syslog()ed messages. + */ + + if (level > log_level) + return; + + switch (level) { + case SYSLOG_LEVEL_FATAL: + if (!log_on_stderr) + txt = "fatal"; + pri = LOG_CRIT; + break; + case SYSLOG_LEVEL_ERROR: + if (!log_on_stderr) + txt = "error"; + pri = LOG_ERR; + break; + case SYSLOG_LEVEL_NOTICE: + pri = LOG_NOTICE; + break; + case SYSLOG_LEVEL_INFO: + pri = LOG_INFO; + break; + case SYSLOG_LEVEL_VERBOSE: + pri = LOG_INFO; + break; + case SYSLOG_LEVEL_DEBUG1: + txt = "debug1"; + pri = LOG_DEBUG; + /* + * Don't localize debug messages - such are not intended + * for users but for support staff whose preferred + * language is unknown, therefore we default to the + * language used in the source code: English. + */ + do_gettext = 0; + break; + case SYSLOG_LEVEL_DEBUG2: + txt = "debug2"; + pri = LOG_DEBUG; + do_gettext = 0; /* Don't localize debug messages. */ + break; + case SYSLOG_LEVEL_DEBUG3: + txt = "debug3"; + pri = LOG_DEBUG; + do_gettext = 0; /* Don't localize debug messages. */ + break; + default: + txt = "internal error"; + pri = LOG_ERR; + break; + } + if (txt != NULL) { + snprintf(fmtbuf, sizeof(fmtbuf), "%s%s: %s", log_txt_prefix, + do_gettext ? gettext(txt) : txt, + do_gettext ? gettext(fmt) : fmt); + vsnprintf(msgbuf, sizeof(msgbuf), fmtbuf, args); + } else { + vsnprintf(msgbuf, sizeof(msgbuf), + do_gettext ? gettext(fmt) : fmt, + args); + } + if (log_on_stderr) { + fprintf(stderr, "%s\r\n", msgbuf); + } else { + openlog(argv0 ? argv0 : __progname, LOG_PID, log_facility); + syslog(pri, "%.500s", msgbuf); + closelog(); + } +} diff --git a/usr/src/cmd/ssh/libssh/common/mac.c b/usr/src/cmd/ssh/libssh/common/mac.c new file mode 100644 index 0000000000..c04a2746f1 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/mac.c @@ -0,0 +1,122 @@ +/* + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: mac.c,v 1.5 2002/05/16 22:02:50 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/hmac.h> + +#include "xmalloc.h" +#include "getput.h" +#include "log.h" +#include "cipher.h" +#include "kex.h" +#include "mac.h" + +struct { + char *name; + const EVP_MD * (*mdfunc)(void); + int truncatebits; /* truncate digest if != 0 */ +} macs[] = { + { "hmac-sha1", EVP_sha1, 0 }, + { "hmac-sha1-96", EVP_sha1, 96 }, + { "hmac-md5", EVP_md5, 0 }, + { "hmac-md5-96", EVP_md5, 96 }, +#ifdef SOLARIS_SSH_ENABLE_RIPEMD160 + { "hmac-ripemd160", EVP_ripemd160, 0 }, + { "hmac-ripemd160@openssh.com", EVP_ripemd160, 0 }, +#endif /* SOLARIS_SSH_ENABLE_RIPEMD160 */ + { NULL, NULL, 0 } +}; + +int +mac_init(Mac *mac, char *name) +{ + int i; + for (i = 0; macs[i].name; i++) { + if (strcmp(name, macs[i].name) == 0) { + if (mac != NULL) { + mac->md = (*macs[i].mdfunc)(); + mac->key_len = mac->mac_len = EVP_MD_size(mac->md); + if (macs[i].truncatebits != 0) + mac->mac_len = macs[i].truncatebits/8; + } + debug2("mac_init: found %s", name); + return (0); + } + } + debug2("mac_init: unknown %s", name); + return (-1); +} + +u_char * +mac_compute(Mac *mac, u_int32_t seqno, u_char *data, int datalen) +{ + HMAC_CTX c; + static u_char m[EVP_MAX_MD_SIZE]; + u_char b[4]; + + if (mac->key == NULL) + fatal("mac_compute: no key"); + if (mac->mac_len > sizeof(m)) + fatal("mac_compute: mac too long"); + HMAC_Init(&c, mac->key, mac->key_len, mac->md); + PUT_32BIT(b, seqno); + HMAC_Update(&c, b, sizeof(b)); + HMAC_Update(&c, data, datalen); + HMAC_Final(&c, m, NULL); + HMAC_cleanup(&c); + return (m); +} + +/* XXX copied from ciphers_valid */ +#define MAC_SEP "," +int +mac_valid(const char *names) +{ + char *maclist, *cp, *p; + + if (names == NULL || strcmp(names, "") == 0) + return (0); + maclist = cp = xstrdup(names); + for ((p = strsep(&cp, MAC_SEP)); p && *p != '\0'; + (p = strsep(&cp, MAC_SEP))) { + if (mac_init(NULL, p) < 0) { + debug("bad mac %s [%s]", p, names); + xfree(maclist); + return (0); + } else { + debug3("mac ok: %s [%s]", p, names); + } + } + debug3("macs ok: [%s]", names); + xfree(maclist); + return (1); +} diff --git a/usr/src/cmd/ssh/libssh/common/match.c b/usr/src/cmd/ssh/libssh/common/match.c new file mode 100644 index 0000000000..4724d435e7 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/match.c @@ -0,0 +1,271 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Simple pattern matching, with '*' and '?' as wildcards. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: match.c,v 1.19 2002/03/01 13:12:10 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "match.h" +#include "xmalloc.h" + +/* + * Returns true if the given string matches the pattern (which may contain ? + * and * as wildcards), and zero if it does not match. + */ + +int +match_pattern(const char *s, const char *pattern) +{ + for (;;) { + /* If at end of pattern, accept if also at end of string. */ + if (!*pattern) + return !*s; + + if (*pattern == '*') { + /* Skip the asterisk. */ + pattern++; + + /* If at end of pattern, accept immediately. */ + if (!*pattern) + return 1; + + /* If next character in pattern is known, optimize. */ + if (*pattern != '?' && *pattern != '*') { + /* + * Look instances of the next character in + * pattern, and try to match starting from + * those. + */ + for (; *s; s++) + if (*s == *pattern && + match_pattern(s + 1, pattern + 1)) + return 1; + /* Failed. */ + return 0; + } + /* + * Move ahead one character at a time and try to + * match at each position. + */ + for (; *s; s++) + if (match_pattern(s, pattern)) + return 1; + /* Failed. */ + return 0; + } + /* + * There must be at least one more character in the string. + * If we are at the end, fail. + */ + if (!*s) + return 0; + + /* Check if the next character of the string is acceptable. */ + if (*pattern != '?' && *pattern != *s) + return 0; + + /* Move to the next character, both in string and in pattern. */ + s++; + pattern++; + } + /* NOTREACHED */ +} + +/* + * Tries to match the string against the + * comma-separated sequence of subpatterns (each possibly preceded by ! to + * indicate negation). Returns -1 if negation matches, 1 if there is + * a positive match, 0 if there is no match at all. + */ + +int +match_pattern_list(const char *string, const char *pattern, u_int len, + int dolower) +{ + char sub[1024]; + int negated; + int got_positive; + u_int i, subi; + + got_positive = 0; + for (i = 0; i < len;) { + /* Check if the subpattern is negated. */ + if (pattern[i] == '!') { + negated = 1; + i++; + } else + negated = 0; + + /* + * Extract the subpattern up to a comma or end. Convert the + * subpattern to lowercase. + */ + for (subi = 0; + i < len && subi < sizeof(sub) - 1 && pattern[i] != ','; + subi++, i++) + sub[subi] = dolower && isupper(pattern[i]) ? + tolower(pattern[i]) : pattern[i]; + /* If subpattern too long, return failure (no match). */ + if (subi >= sizeof(sub) - 1) + return 0; + + /* If the subpattern was terminated by a comma, skip the comma. */ + if (i < len && pattern[i] == ',') + i++; + + /* Null-terminate the subpattern. */ + sub[subi] = '\0'; + + /* Try to match the subpattern against the string. */ + if (match_pattern(string, sub)) { + if (negated) + return -1; /* Negative */ + else + got_positive = 1; /* Positive */ + } + } + + /* + * Return success if got a positive match. If there was a negative + * match, we have already returned -1 and never get here. + */ + return got_positive; +} + +/* + * Tries to match the host name (which must be in all lowercase) against the + * comma-separated sequence of subpatterns (each possibly preceded by ! to + * indicate negation). Returns -1 if negation matches, 1 if there is + * a positive match, 0 if there is no match at all. + */ +int +match_hostname(const char *host, const char *pattern, u_int len) +{ + return match_pattern_list(host, pattern, len, 1); +} + +/* + * returns 0 if we get a negative match for the hostname or the ip + * or if we get no match at all. returns 1 otherwise. + */ +int +match_host_and_ip(const char *host, const char *ipaddr, + const char *patterns) +{ + int mhost, mip; + + /* negative ipaddr match */ + if ((mip = match_hostname(ipaddr, patterns, strlen(patterns))) == -1) + return 0; + /* negative hostname match */ + if ((mhost = match_hostname(host, patterns, strlen(patterns))) == -1) + return 0; + /* no match at all */ + if (mhost == 0 && mip == 0) + return 0; + return 1; +} + +/* + * match user, user@host_or_ip, user@host_or_ip_list against pattern + */ +int +match_user(const char *user, const char *host, const char *ipaddr, + const char *pattern) +{ + char *p, *pat; + int ret; + + if ((p = strchr(pattern,'@')) == NULL) + return match_pattern(user, pattern); + + pat = xstrdup(pattern); + p = strchr(pat, '@'); + *p++ = '\0'; + + if ((ret = match_pattern(user, pat)) == 1) + ret = match_host_and_ip(host, ipaddr, p); + xfree(pat); + + return ret; +} + +/* + * Returns first item from client-list that is also supported by server-list, + * caller must xfree() returned string. + */ +#define MAX_PROP 40 +#define SEP "," +char * +match_list(const char *client, const char *server, u_int *next) +{ + char *sproposals[MAX_PROP]; + char *c, *s, *p, *ret, *cp, *sp; + int i, j, nproposals; + + c = cp = xstrdup(client); + s = sp = xstrdup(server); + + for ((p = strsep(&sp, SEP)), i=0; p && *p != '\0'; + (p = strsep(&sp, SEP)), i++) { + if (i < MAX_PROP) + sproposals[i] = p; + else + break; + } + nproposals = i; + + for ((p = strsep(&cp, SEP)), i=0; p && *p != '\0'; + (p = strsep(&cp, SEP)), i++) { + for (j = 0; j < nproposals; j++) { + if (strcmp(p, sproposals[j]) == 0) { + ret = xstrdup(p); + if (next != NULL) + *next = (cp == NULL) ? + strlen(c) : cp - c; + xfree(c); + xfree(s); + return ret; + } + } + } + if (next != NULL) + *next = strlen(c); + xfree(c); + xfree(s); + return NULL; +} diff --git a/usr/src/cmd/ssh/libssh/common/misc.c b/usr/src/cmd/ssh/libssh/common/misc.c new file mode 100644 index 0000000000..5c4de6102d --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/misc.c @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: misc.c,v 1.19 2002/03/04 17:27:39 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "misc.h" +#include "log.h" +#include "xmalloc.h" + +/* remove newline at end of string */ +char * +chop(char *s) +{ + char *t = s; + while (*t) { + if (*t == '\n' || *t == '\r') { + *t = '\0'; + return s; + } + t++; + } + return s; + +} + +/* set/unset filedescriptor to non-blocking */ +void +set_nonblock(int fd) +{ + int val; + + val = fcntl(fd, F_GETFL, 0); + if (val < 0) { + error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno)); + return; + } + if (val & O_NONBLOCK) { + debug2("fd %d is O_NONBLOCK", fd); + return; + } + debug("fd %d setting O_NONBLOCK", fd); + val |= O_NONBLOCK; + if (fcntl(fd, F_SETFL, val) == -1) + debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", + fd, strerror(errno)); +} + +void +unset_nonblock(int fd) +{ + int val; + + val = fcntl(fd, F_GETFL, 0); + if (val < 0) { + error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno)); + return; + } + if (!(val & O_NONBLOCK)) { + debug2("fd %d is not O_NONBLOCK", fd); + return; + } + debug("fd %d clearing O_NONBLOCK", fd); + val &= ~O_NONBLOCK; + if (fcntl(fd, F_SETFL, val) == -1) + debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", + fd, strerror(errno)); +} + +/* disable nagle on socket */ +void +set_nodelay(int fd) +{ + int opt; + socklen_t optlen; + + optlen = sizeof opt; + if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) { + error("getsockopt TCP_NODELAY: %.100s", strerror(errno)); + return; + } + if (opt == 1) { + debug2("fd %d is TCP_NODELAY", fd); + return; + } + opt = 1; + debug("fd %d setting TCP_NODELAY", fd); + if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1) + error("setsockopt TCP_NODELAY: %.100s", strerror(errno)); +} + +/* Characters considered whitespace in strsep calls. */ +#define WHITESPACE " \t\r\n" + +/* return next token in configuration line */ +char * +strdelim(char **s) +{ + char *old; + int wspace = 0; + + if (*s == NULL) + return NULL; + + old = *s; + + *s = strpbrk(*s, WHITESPACE "="); + if (*s == NULL) + return (old); + + /* Allow only one '=' to be skipped */ + if (*s[0] == '=') + wspace = 1; + *s[0] = '\0'; + + *s += strspn(*s + 1, WHITESPACE) + 1; + if (*s[0] == '=' && !wspace) + *s += strspn(*s + 1, WHITESPACE) + 1; + + return (old); +} + +struct passwd * +pwcopy(struct passwd *pw) +{ + struct passwd *copy = xmalloc(sizeof(*copy)); + + memset(copy, 0, sizeof(*copy)); + copy->pw_name = xstrdup(pw->pw_name); + copy->pw_passwd = xstrdup(pw->pw_passwd); + copy->pw_gecos = xstrdup(pw->pw_gecos); + copy->pw_uid = pw->pw_uid; + copy->pw_gid = pw->pw_gid; +#ifdef HAVE_PW_EXPIRE_IN_PASSWD + copy->pw_expire = pw->pw_expire; +#endif +#ifdef HAVE_PW_CHANGE_IN_PASSWD + copy->pw_change = pw->pw_change; +#endif +#ifdef HAVE_PW_CLASS_IN_PASSWD + copy->pw_class = xstrdup(pw->pw_class); +#endif + copy->pw_dir = xstrdup(pw->pw_dir); + copy->pw_shell = xstrdup(pw->pw_shell); + return copy; +} + +void +pwfree(struct passwd **pw) +{ + struct passwd *p; + + if (pw == NULL || *pw == NULL) + return; + + p = *pw; + *pw = NULL; + + xfree(p->pw_name); + xfree(p->pw_passwd); + xfree(p->pw_gecos); +#ifdef HAVE_PW_CLASS_IN_PASSWD + xfree(p->pw_class); +#endif + xfree(p->pw_dir); + xfree(p->pw_shell); + xfree(p); +} + +/* + * Convert ASCII string to TCP/IP port number. + * Port must be >0 and <=65535. + * Return 0 if invalid. + */ +int +a2port(const char *s) +{ + long port; + char *endp; + + errno = 0; + port = strtol(s, &endp, 0); + if (s == endp || *endp != '\0' || + (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) || + port <= 0 || port > 65535) + return 0; + + return port; +} + +#define SECONDS 1 +#define MINUTES (SECONDS * 60) +#define HOURS (MINUTES * 60) +#define DAYS (HOURS * 24) +#define WEEKS (DAYS * 7) + +/* + * Convert a time string into seconds; format is + * a sequence of: + * time[qualifier] + * + * Valid time qualifiers are: + * <none> seconds + * s|S seconds + * m|M minutes + * h|H hours + * d|D days + * w|W weeks + * + * Examples: + * 90m 90 minutes + * 1h30m 90 minutes + * 2d 2 days + * 1w 1 week + * + * Return -1 if time string is invalid. + */ +long +convtime(const char *s) +{ + long total, secs; + const char *p; + char *endp; + + errno = 0; + total = 0; + p = s; + + if (p == NULL || *p == '\0') + return -1; + + while (*p) { + secs = strtol(p, &endp, 10); + if (p == endp || + (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) || + secs < 0) + return -1; + + switch (*endp++) { + case '\0': + endp--; + break; + case 's': + case 'S': + break; + case 'm': + case 'M': + secs *= MINUTES; + break; + case 'h': + case 'H': + secs *= HOURS; + break; + case 'd': + case 'D': + secs *= DAYS; + break; + case 'w': + case 'W': + secs *= WEEKS; + break; + default: + return -1; + } + total += secs; + if (total < 0) + return -1; + p = endp; + } + + return total; +} + +char * +cleanhostname(char *host) +{ + if (*host == '[' && host[strlen(host) - 1] == ']') { + host[strlen(host) - 1] = '\0'; + return (host + 1); + } else + return host; +} + +char * +colon(char *cp) +{ + int flag = 0; + + if (*cp == ':') /* Leading colon is part of file name. */ + return (0); + if (*cp == '[') + flag = 1; + + for (; *cp; ++cp) { + if (*cp == '@' && *(cp+1) == '[') + flag = 1; + if (*cp == ']' && *(cp+1) == ':' && flag) + return (cp+1); + if (*cp == ':' && !flag) + return (cp); + if (*cp == '/') + return (0); + } + return (0); +} + +/* function to assist building execv() arguments */ +/* PRINTFLIKE2 */ +void +addargs(arglist *args, char *fmt, ...) +{ + va_list ap; + char buf[1024]; + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + + if (args->list == NULL) { + args->nalloc = 32; + args->num = 0; + } else if (args->num+2 >= args->nalloc) + args->nalloc *= 2; + + args->list = xrealloc(args->list, args->nalloc * sizeof(char *)); + args->list[args->num++] = xstrdup(buf); + args->list[args->num] = NULL; +} + +mysig_t +mysignal(int sig, mysig_t act) +{ +#ifdef HAVE_SIGACTION + struct sigaction sa, osa; + + if (sigaction(sig, NULL, &osa) == -1) + return (mysig_t) -1; + if (osa.sa_handler != act) { + memset(&sa, 0, sizeof(sa)); + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; +#if defined(SA_INTERRUPT) + if (sig == SIGALRM) + sa.sa_flags |= SA_INTERRUPT; +#endif + sa.sa_handler = act; + if (sigaction(sig, &sa, NULL) == -1) + return (mysig_t) -1; + } + return (osa.sa_handler); +#else + return (signal(sig, act)); +#endif +} diff --git a/usr/src/cmd/ssh/libssh/common/monitor_fdpass.c b/usr/src/cmd/ssh/libssh/common/monitor_fdpass.c new file mode 100644 index 0000000000..305e45e4cc --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/monitor_fdpass.c @@ -0,0 +1,128 @@ +/* + * Copyright 2001 Niels Provos <provos@citi.umich.edu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: monitor_fdpass.c,v 1.4 2002/06/26 14:50:04 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <sys/uio.h> + +#include "log.h" +#include "monitor_fdpass.h" + +void +mm_send_fd(int socket, int fd) +{ +#if defined(HAVE_SENDMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR)) + struct msghdr msg; + struct iovec vec; + char ch = '\0'; + ssize_t n; +#ifndef HAVE_ACCRIGHTS_IN_MSGHDR + char tmp[CMSG_SPACE(sizeof(int))]; + struct cmsghdr *cmsg; +#endif + + memset(&msg, 0, sizeof(msg)); +#ifdef HAVE_ACCRIGHTS_IN_MSGHDR + msg.msg_accrights = (caddr_t)&fd; + msg.msg_accrightslen = sizeof(fd); +#else + msg.msg_control = (caddr_t)tmp; + msg.msg_controllen = CMSG_LEN(sizeof(int)); + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + *(int *)CMSG_DATA(cmsg) = fd; +#endif + + vec.iov_base = &ch; + vec.iov_len = 1; + msg.msg_iov = &vec; + msg.msg_iovlen = 1; + + if ((n = sendmsg(socket, &msg, 0)) == -1) + fatal("%s: sendmsg(%d): %s", __func__, fd, + strerror(errno)); + if (n != 1) + fatal("%s: sendmsg: expected sent 1 got %ld", + __func__, (long)n); +#else + fatal("%s: UsePrivilegeSeparation=yes not supported", + __func__); +#endif +} + +int +mm_receive_fd(int socket) +{ +#if defined(HAVE_RECVMSG) && (defined(HAVE_ACCRIGHTS_IN_MSGHDR) || defined(HAVE_CONTROL_IN_MSGHDR)) + struct msghdr msg; + struct iovec vec; + ssize_t n; + char ch; + int fd; +#ifndef HAVE_ACCRIGHTS_IN_MSGHDR + char tmp[CMSG_SPACE(sizeof(int))]; + struct cmsghdr *cmsg; +#endif + + memset(&msg, 0, sizeof(msg)); + vec.iov_base = &ch; + vec.iov_len = 1; + msg.msg_iov = &vec; + msg.msg_iovlen = 1; +#ifdef HAVE_ACCRIGHTS_IN_MSGHDR + msg.msg_accrights = (caddr_t)&fd; + msg.msg_accrightslen = sizeof(fd); +#else + msg.msg_control = tmp; + msg.msg_controllen = sizeof(tmp); +#endif + + if ((n = recvmsg(socket, &msg, 0)) == -1) + fatal("%s: recvmsg: %s", __func__, strerror(errno)); + if (n != 1) + fatal("%s: recvmsg: expected received 1 got %ld", + __func__, (long)n); + +#ifdef HAVE_ACCRIGHTS_IN_MSGHDR + if (msg.msg_accrightslen != sizeof(fd)) + fatal("%s: no fd", __func__); +#else + cmsg = CMSG_FIRSTHDR(&msg); + if (cmsg->cmsg_type != SCM_RIGHTS) + fatal("%s: expected type %d got %d", __func__, + SCM_RIGHTS, cmsg->cmsg_type); + fd = (*(int *)CMSG_DATA(cmsg)); +#endif + return fd; +#else + fatal("%s: UsePrivilegeSeparation=yes not supported", + __func__); +#endif +} diff --git a/usr/src/cmd/ssh/libssh/common/monitor_wrap.c b/usr/src/cmd/ssh/libssh/common/monitor_wrap.c new file mode 100644 index 0000000000..4882c3d967 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/monitor_wrap.c @@ -0,0 +1,1174 @@ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Copyright 2002 Niels Provos <provos@citi.umich.edu> + * Copyright 2002 Markus Friedl <markus@openbsd.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: monitor_wrap.c,v 1.19 2002/09/26 11:38:43 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> +#include <openssl/dh.h> + +#include "ssh.h" +#include "dh.h" +#include "kex.h" +#include "auth.h" +#include "buffer.h" +#include "bufaux.h" +#include "packet.h" +#include "mac.h" +#include "log.h" +#include "zlib.h" +#include "monitor.h" +#include "monitor_wrap.h" +#include "xmalloc.h" +#include "atomicio.h" +#include "monitor_fdpass.h" +#include "getput.h" + +#include "auth.h" +#include "channels.h" +#include "session.h" + +#ifdef GSSAPI +#include "ssh-gss.h" +#endif + +/* Imports */ +extern int compat20; +extern Newkeys *newkeys[]; +extern z_stream incoming_stream; +extern z_stream outgoing_stream; +extern struct monitor *pmonitor; +extern Buffer input, output; + +void +mm_request_send(int socket, enum monitor_reqtype type, Buffer *m) +{ + u_int mlen = buffer_len(m); + u_char buf[5]; + + debug3("%s entering: type %d", __func__, type); + + PUT_32BIT(buf, mlen + 1); + buf[4] = (u_char) type; /* 1st byte of payload is mesg-type */ + if (atomicio(write, socket, buf, sizeof(buf)) != sizeof(buf)) + fatal("%s: write", __func__); + if (atomicio(write, socket, buffer_ptr(m), mlen) != mlen) + fatal("%s: write", __func__); +} + +void +mm_request_receive(int socket, Buffer *m) +{ + u_char buf[4]; + u_int msg_len; + ssize_t res; + + debug3("%s entering", __func__); + + res = atomicio(read, socket, buf, sizeof(buf)); + if (res != sizeof(buf)) { + if (res == 0) + fatal_cleanup(); + fatal("%s: read: %ld", __func__, (long)res); + } + msg_len = GET_32BIT(buf); + if (msg_len > 256 * 1024) + fatal("%s: read: bad msg_len %d", __func__, msg_len); + buffer_clear(m); + buffer_append_space(m, msg_len); + res = atomicio(read, socket, buffer_ptr(m), msg_len); + if (res != msg_len) + fatal("%s: read: %ld != msg_len", __func__, (long)res); +} + +void +mm_request_receive_expect(int socket, enum monitor_reqtype type, Buffer *m) +{ + u_char rtype; + + debug3("%s entering: type %d", __func__, type); + + mm_request_receive(socket, m); + rtype = buffer_get_char(m); + if (rtype != type) + fatal("%s: read: rtype %d != type %d", __func__, + rtype, type); +} + +DH * +mm_choose_dh(int min, int nbits, int max) +{ + BIGNUM *p, *g; + int success = 0; + Buffer m; + + buffer_init(&m); + buffer_put_int(&m, min); + buffer_put_int(&m, nbits); + buffer_put_int(&m, max); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_MODULI, &m); + + debug3("%s: waiting for MONITOR_ANS_MODULI", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_MODULI, &m); + + success = buffer_get_char(&m); + if (success == 0) + fatal("%s: MONITOR_ANS_MODULI failed", __func__); + + if ((p = BN_new()) == NULL) + fatal("%s: BN_new failed", __func__); + if ((g = BN_new()) == NULL) + fatal("%s: BN_new failed", __func__); + buffer_get_bignum2(&m, p); + buffer_get_bignum2(&m, g); + + debug3("%s: remaining %d", __func__, buffer_len(&m)); + buffer_free(&m); + + return (dh_new_group(g, p)); +} + +int +mm_key_sign(Key *key, u_char **sigp, u_int *lenp, u_char *data, u_int datalen) +{ + Kex *kex = *pmonitor->m_pkex; + Buffer m; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_int(&m, kex->host_key_index(key)); + buffer_put_string(&m, data, datalen); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SIGN, &m); + + debug3("%s: waiting for MONITOR_ANS_SIGN", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SIGN, &m); + *sigp = buffer_get_string(&m, lenp); + buffer_free(&m); + + return (0); +} + +struct passwd * +mm_getpwnamallow(const char *login) +{ + Buffer m; + struct passwd *pw; + u_int pwlen; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_cstring(&m, login); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PWNAM, &m); + + debug3("%s: waiting for MONITOR_ANS_PWNAM", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PWNAM, &m); + + if (buffer_get_char(&m) == 0) { + buffer_free(&m); + return (NULL); + } + pw = buffer_get_string(&m, &pwlen); + if (pwlen != sizeof(struct passwd)) + fatal("%s: struct passwd size mismatch", __func__); + pw->pw_name = buffer_get_string(&m, NULL); + pw->pw_passwd = buffer_get_string(&m, NULL); + pw->pw_gecos = buffer_get_string(&m, NULL); +#ifdef HAVE_PW_CLASS_IN_PASSWD + pw->pw_class = buffer_get_string(&m, NULL); +#endif + pw->pw_dir = buffer_get_string(&m, NULL); + pw->pw_shell = buffer_get_string(&m, NULL); + buffer_free(&m); + + return (pw); +} + +char *mm_auth2_read_banner(void) +{ + Buffer m; + char *banner; + + debug3("%s entering", __func__); + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTH2_READ_BANNER, &m); + buffer_clear(&m); + + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTH2_READ_BANNER, &m); + banner = buffer_get_string(&m, NULL); + buffer_free(&m); + + return (banner); +} + +/* Inform the privileged process about service and style */ + +void +mm_inform_authserv(char *service, char *style) +{ + Buffer m; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_cstring(&m, service); + buffer_put_cstring(&m, style ? style : ""); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHSERV, &m); + + buffer_free(&m); +} + +/* Do the password authentication */ +int +mm_auth_password(Authctxt *authctxt, char *password) +{ + Buffer m; + int authenticated = 0; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_cstring(&m, password); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHPASSWORD, &m); + + debug3("%s: waiting for MONITOR_ANS_AUTHPASSWORD", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTHPASSWORD, &m); + + authenticated = buffer_get_int(&m); + + buffer_free(&m); + + debug3("%s: user %sauthenticated", + __func__, authenticated ? "" : "not "); + return (authenticated); +} + +int +mm_user_key_allowed(struct passwd *pw, Key *key) +{ + return (mm_key_allowed(MM_USERKEY, NULL, NULL, key)); +} + +int +mm_hostbased_key_allowed(struct passwd *pw, char *user, char *host, + Key *key) +{ + return (mm_key_allowed(MM_HOSTKEY, user, host, key)); +} + +int +mm_auth_rhosts_rsa_key_allowed(struct passwd *pw, char *user, + char *host, Key *key) +{ + int ret; + + key->type = KEY_RSA; /* XXX hack for key_to_blob */ + ret = mm_key_allowed(MM_RSAHOSTKEY, user, host, key); + key->type = KEY_RSA1; + return (ret); +} + +static void +mm_send_debug(Buffer *m) +{ + char *msg; + + while (buffer_len(m)) { + msg = buffer_get_string(m, NULL); + debug3("%s: Sending debug: %s", __func__, msg); + packet_send_debug("%s", msg); + xfree(msg); + } +} + +int +mm_key_allowed(enum mm_keytype type, char *user, char *host, Key *key) +{ + Buffer m; + u_char *blob; + u_int len; + int allowed = 0; + + debug3("%s entering", __func__); + + /* Convert the key to a blob and the pass it over */ + if (!key_to_blob(key, &blob, &len)) + return (0); + + buffer_init(&m); + buffer_put_int(&m, type); + buffer_put_cstring(&m, user ? user : ""); + buffer_put_cstring(&m, host ? host : ""); + buffer_put_string(&m, blob, len); + xfree(blob); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYALLOWED, &m); + + debug3("%s: waiting for MONITOR_ANS_KEYALLOWED", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYALLOWED, &m); + + allowed = buffer_get_int(&m); + + /* Send potential debug messages */ + mm_send_debug(&m); + + buffer_free(&m); + + return (allowed); +} + +/* + * This key verify needs to send the key type along, because the + * privileged parent makes the decision if the key is allowed + * for authentication. + */ + +int +mm_key_verify(Key *key, u_char *sig, u_int siglen, u_char *data, u_int datalen) +{ + Buffer m; + u_char *blob; + u_int len; + int verified = 0; + + debug3("%s entering", __func__); + + /* Convert the key to a blob and the pass it over */ + if (!key_to_blob(key, &blob, &len)) + return (0); + + buffer_init(&m); + buffer_put_string(&m, blob, len); + buffer_put_string(&m, sig, siglen); + buffer_put_string(&m, data, datalen); + xfree(blob); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYVERIFY, &m); + + debug3("%s: waiting for MONITOR_ANS_KEYVERIFY", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYVERIFY, &m); + + verified = buffer_get_int(&m); + + buffer_free(&m); + + return (verified); +} + +/* Export key state after authentication */ +Newkeys * +mm_newkeys_from_blob(u_char *blob, int blen) +{ + Buffer b; + u_int len; + Newkeys *newkey = NULL; + Enc *enc; + Mac *mac; + Comp *comp; + + debug3("%s: %p(%d)", __func__, blob, blen); +#ifdef DEBUG_PK + dump_base64(stderr, blob, blen); +#endif + buffer_init(&b); + buffer_append(&b, blob, blen); + + newkey = xmalloc(sizeof(*newkey)); + enc = &newkey->enc; + mac = &newkey->mac; + comp = &newkey->comp; + + /* Enc structure */ + enc->name = buffer_get_string(&b, NULL); + buffer_get(&b, &enc->cipher, sizeof(enc->cipher)); + enc->enabled = buffer_get_int(&b); + enc->block_size = buffer_get_int(&b); + enc->key = buffer_get_string(&b, &enc->key_len); + enc->iv = buffer_get_string(&b, &len); + if (len != enc->block_size) + fatal("%s: bad ivlen: expected %u != %u", __func__, + enc->block_size, len); + + if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) + fatal("%s: bad cipher name %s or pointer %p", __func__, + enc->name, enc->cipher); + + /* Mac structure */ + mac->name = buffer_get_string(&b, NULL); + if (mac->name == NULL || mac_init(mac, mac->name) == -1) + fatal("%s: can not init mac %s", __func__, mac->name); + mac->enabled = buffer_get_int(&b); + mac->key = buffer_get_string(&b, &len); + if (len > mac->key_len) + fatal("%s: bad mac key length: %u > %d", __func__, len, + mac->key_len); + mac->key_len = len; + + /* Comp structure */ + comp->type = buffer_get_int(&b); + comp->enabled = buffer_get_int(&b); + comp->name = buffer_get_string(&b, NULL); + + len = buffer_len(&b); + if (len != 0) + error("newkeys_from_blob: remaining bytes in blob %u", len); + buffer_free(&b); + return (newkey); +} + +int +mm_newkeys_to_blob(int mode, u_char **blobp, u_int *lenp) +{ + Buffer b; + int len; + Enc *enc; + Mac *mac; + Comp *comp; + Newkeys *newkey = newkeys[mode]; + + debug3("%s: converting %p", __func__, newkey); + + if (newkey == NULL) { + error("%s: newkey == NULL", __func__); + return 0; + } + enc = &newkey->enc; + mac = &newkey->mac; + comp = &newkey->comp; + + buffer_init(&b); + /* Enc structure */ + buffer_put_cstring(&b, enc->name); + /* The cipher struct is constant and shared, you export pointer */ + buffer_append(&b, &enc->cipher, sizeof(enc->cipher)); + buffer_put_int(&b, enc->enabled); + buffer_put_int(&b, enc->block_size); + buffer_put_string(&b, enc->key, enc->key_len); + packet_get_keyiv(mode, enc->iv, enc->block_size); + buffer_put_string(&b, enc->iv, enc->block_size); + + /* Mac structure */ + buffer_put_cstring(&b, mac->name); + buffer_put_int(&b, mac->enabled); + buffer_put_string(&b, mac->key, mac->key_len); + + /* Comp structure */ + buffer_put_int(&b, comp->type); + buffer_put_int(&b, comp->enabled); + buffer_put_cstring(&b, comp->name); + + len = buffer_len(&b); + if (lenp != NULL) + *lenp = len; + if (blobp != NULL) { + *blobp = xmalloc(len); + memcpy(*blobp, buffer_ptr(&b), len); + } + memset(buffer_ptr(&b), 0, len); + buffer_free(&b); + return len; +} + +static void +mm_send_kex(Buffer *m, Kex *kex) +{ + buffer_put_string(m, kex->session_id, kex->session_id_len); + buffer_put_int(m, kex->we_need); + buffer_put_int(m, kex->hostkey_type); + buffer_put_int(m, kex->kex_type); + buffer_put_string(m, buffer_ptr(&kex->my), buffer_len(&kex->my)); + buffer_put_string(m, buffer_ptr(&kex->peer), buffer_len(&kex->peer)); + buffer_put_int(m, kex->flags); + buffer_put_cstring(m, kex->client_version_string); + buffer_put_cstring(m, kex->server_version_string); +} + +void +mm_send_keystate(struct monitor *pmonitor) +{ + Buffer m; + u_char *blob, *p; + u_int bloblen, plen; + + buffer_init(&m); + + if (!compat20) { + u_char iv[24]; + u_char *key; + u_int ivlen, keylen; + + buffer_put_int(&m, packet_get_protocol_flags()); + + buffer_put_int(&m, packet_get_ssh1_cipher()); + + debug3("%s: Sending ssh1 KEY+IV", __func__); + keylen = packet_get_encryption_key(NULL); + key = xmalloc(keylen+1); /* add 1 if keylen == 0 */ + keylen = packet_get_encryption_key(key); + buffer_put_string(&m, key, keylen); + memset(key, 0, keylen); + xfree(key); + + ivlen = packet_get_keyiv_len(MODE_OUT); + packet_get_keyiv(MODE_OUT, iv, ivlen); + buffer_put_string(&m, iv, ivlen); + ivlen = packet_get_keyiv_len(MODE_OUT); + packet_get_keyiv(MODE_IN, iv, ivlen); + buffer_put_string(&m, iv, ivlen); + goto skip; + } else { + /* Kex for rekeying */ + mm_send_kex(&m, *pmonitor->m_pkex); + } + + debug3("%s: Sending new keys: %p %p", + __func__, newkeys[MODE_OUT], newkeys[MODE_IN]); + + /* Keys from Kex */ + if (!mm_newkeys_to_blob(MODE_OUT, &blob, &bloblen)) + fatal("%s: conversion of newkeys failed", __func__); + + buffer_put_string(&m, blob, bloblen); + xfree(blob); + + if (!mm_newkeys_to_blob(MODE_IN, &blob, &bloblen)) + fatal("%s: conversion of newkeys failed", __func__); + + buffer_put_string(&m, blob, bloblen); + xfree(blob); + + buffer_put_int(&m, packet_get_seqnr(MODE_OUT)); + buffer_put_int(&m, packet_get_seqnr(MODE_IN)); + + debug3("%s: New keys have been sent", __func__); + skip: + /* More key context */ + plen = packet_get_keycontext(MODE_OUT, NULL); + p = xmalloc(plen+1); + packet_get_keycontext(MODE_OUT, p); + buffer_put_string(&m, p, plen); + xfree(p); + + plen = packet_get_keycontext(MODE_IN, NULL); + p = xmalloc(plen+1); + packet_get_keycontext(MODE_IN, p); + buffer_put_string(&m, p, plen); + xfree(p); + + /* Compression state */ + debug3("%s: Sending compression state", __func__); + buffer_put_string(&m, &outgoing_stream, sizeof(outgoing_stream)); + buffer_put_string(&m, &incoming_stream, sizeof(incoming_stream)); + + /* Network I/O buffers */ + buffer_put_string(&m, buffer_ptr(&input), buffer_len(&input)); + buffer_put_string(&m, buffer_ptr(&output), buffer_len(&output)); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYEXPORT, &m); + debug3("%s: Finished sending state", __func__); + + buffer_free(&m); +} + +int +mm_pty_allocate(int *ptyfd, int *ttyfd, char *namebuf, int namebuflen) +{ + Buffer m; + char *p; + int success = 0; + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTY, &m); + + debug3("%s: waiting for MONITOR_ANS_PTY", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PTY, &m); + + success = buffer_get_int(&m); + if (success == 0) { + debug3("%s: pty alloc failed", __func__); + buffer_free(&m); + return (0); + } + p = buffer_get_string(&m, NULL); + buffer_free(&m); + + strlcpy(namebuf, p, namebuflen); /* Possible truncation */ + xfree(p); + + *ptyfd = mm_receive_fd(pmonitor->m_recvfd); + *ttyfd = mm_receive_fd(pmonitor->m_recvfd); + + /* Success */ + return (1); +} + +void +mm_session_pty_cleanup2(void *session) +{ + Session *s = session; + Buffer m; + + if (s->ttyfd == -1) + return; + buffer_init(&m); + buffer_put_cstring(&m, s->tty); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTYCLEANUP, &m); + buffer_free(&m); + + /* closed dup'ed master */ + if (close(s->ptymaster) < 0) + error("close(s->ptymaster): %s", strerror(errno)); + + /* unlink pty from session */ + s->ttyfd = -1; +} + +#ifdef USE_PAM +void +mm_start_pam(char *user) +{ + Buffer m; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_cstring(&m, user); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_START, &m); + + buffer_free(&m); +} +#endif /* USE_PAM */ + +/* Request process termination */ + +void +mm_terminate(void) +{ + Buffer m; + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_TERM, &m); + buffer_free(&m); +} + +int +mm_ssh1_session_key(BIGNUM *num) +{ + int rsafail; + Buffer m; + + buffer_init(&m); + buffer_put_bignum2(&m, num); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSKEY, &m); + + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SESSKEY, &m); + + rsafail = buffer_get_int(&m); + buffer_get_bignum2(&m, num); + + buffer_free(&m); + + return (rsafail); +} + +static void +mm_chall_setup(char **name, char **infotxt, u_int *numprompts, + char ***prompts, u_int **echo_on) +{ + *name = xstrdup(""); + *infotxt = xstrdup(""); + *numprompts = 1; + *prompts = xmalloc(*numprompts * sizeof(char *)); + *echo_on = xmalloc(*numprompts * sizeof(u_int)); + (*echo_on)[0] = 0; +} + +int +mm_bsdauth_query(void *ctx, char **name, char **infotxt, + u_int *numprompts, char ***prompts, u_int **echo_on) +{ + Buffer m; + int res; + char *challenge; + + debug3("%s: entering", __func__); + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHQUERY, &m); + + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_BSDAUTHQUERY, + &m); + res = buffer_get_int(&m); + if (res == -1) { + debug3("%s: no challenge", __func__); + buffer_free(&m); + return (-1); + } + + /* Get the challenge, and format the response */ + challenge = buffer_get_string(&m, NULL); + buffer_free(&m); + + mm_chall_setup(name, infotxt, numprompts, prompts, echo_on); + (*prompts)[0] = challenge; + + debug3("%s: received challenge: %s", __func__, challenge); + + return (0); +} + +int +mm_bsdauth_respond(void *ctx, u_int numresponses, char **responses) +{ + Buffer m; + int authok; + + debug3("%s: entering", __func__); + if (numresponses != 1) + return (-1); + + buffer_init(&m); + buffer_put_cstring(&m, responses[0]); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHRESPOND, &m); + + mm_request_receive_expect(pmonitor->m_recvfd, + MONITOR_ANS_BSDAUTHRESPOND, &m); + + authok = buffer_get_int(&m); + buffer_free(&m); + + return ((authok == 0) ? -1 : 0); +} + +int +mm_skey_query(void *ctx, char **name, char **infotxt, + u_int *numprompts, char ***prompts, u_int **echo_on) +{ + Buffer m; + int len, res; + char *p, *challenge; + + debug3("%s: entering", __func__); + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYQUERY, &m); + + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SKEYQUERY, + &m); + res = buffer_get_int(&m); + if (res == -1) { + debug3("%s: no challenge", __func__); + buffer_free(&m); + return (-1); + } + + /* Get the challenge, and format the response */ + challenge = buffer_get_string(&m, NULL); + buffer_free(&m); + + debug3("%s: received challenge: %s", __func__, challenge); + + mm_chall_setup(name, infotxt, numprompts, prompts, echo_on); + + len = strlen(challenge) + strlen(SKEY_PROMPT) + 1; + p = xmalloc(len); + strlcpy(p, challenge, len); + strlcat(p, SKEY_PROMPT, len); + (*prompts)[0] = p; + xfree(challenge); + + return (0); +} + +int +mm_skey_respond(void *ctx, u_int numresponses, char **responses) +{ + Buffer m; + int authok; + + debug3("%s: entering", __func__); + if (numresponses != 1) + return (-1); + + buffer_init(&m); + buffer_put_cstring(&m, responses[0]); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYRESPOND, &m); + + mm_request_receive_expect(pmonitor->m_recvfd, + MONITOR_ANS_SKEYRESPOND, &m); + + authok = buffer_get_int(&m); + buffer_free(&m); + + return ((authok == 0) ? -1 : 0); +} + +void +mm_ssh1_session_id(u_char session_id[16]) +{ + Buffer m; + int i; + + debug3("%s entering", __func__); + + buffer_init(&m); + for (i = 0; i < 16; i++) + buffer_put_char(&m, session_id[i]); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSID, &m); + buffer_free(&m); +} + +int +mm_auth_rsa_key_allowed(struct passwd *pw, BIGNUM *client_n, Key **rkey) +{ + Buffer m; + Key *key; + u_char *blob; + u_int blen; + int allowed = 0; + + debug3("%s entering", __func__); + + buffer_init(&m); + buffer_put_bignum2(&m, client_n); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSAKEYALLOWED, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSAKEYALLOWED, &m); + + allowed = buffer_get_int(&m); + + if (allowed && rkey != NULL) { + blob = buffer_get_string(&m, &blen); + if ((key = key_from_blob(blob, blen)) == NULL) + fatal("%s: key_from_blob failed", __func__); + *rkey = key; + xfree(blob); + } + mm_send_debug(&m); + buffer_free(&m); + + return (allowed); +} + +BIGNUM * +mm_auth_rsa_generate_challenge(Key *key) +{ + Buffer m; + BIGNUM *challenge; + u_char *blob; + u_int blen; + + debug3("%s entering", __func__); + + if ((challenge = BN_new()) == NULL) + fatal("%s: BN_new failed", __func__); + + key->type = KEY_RSA; /* XXX cheat for key_to_blob */ + if (key_to_blob(key, &blob, &blen) == 0) + fatal("%s: key_to_blob failed", __func__); + key->type = KEY_RSA1; + + buffer_init(&m); + buffer_put_string(&m, blob, blen); + xfree(blob); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSACHALLENGE, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSACHALLENGE, &m); + + buffer_get_bignum2(&m, challenge); + buffer_free(&m); + + return (challenge); +} + +int +mm_auth_rsa_verify_response(Key *key, BIGNUM *p, u_char response[16]) +{ + Buffer m; + u_char *blob; + u_int blen; + int success = 0; + + debug3("%s entering", __func__); + + key->type = KEY_RSA; /* XXX cheat for key_to_blob */ + if (key_to_blob(key, &blob, &blen) == 0) + fatal("%s: key_to_blob failed", __func__); + key->type = KEY_RSA1; + + buffer_init(&m); + buffer_put_string(&m, blob, blen); + buffer_put_string(&m, response, 16); + xfree(blob); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSARESPONSE, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSARESPONSE, &m); + + success = buffer_get_int(&m); + buffer_free(&m); + + return (success); +} + +#ifdef KRB4 +int +mm_auth_krb4(Authctxt *authctxt, void *_auth, char **client, void *_reply) +{ + KTEXT auth, reply; + Buffer m; + u_int rlen; + int success = 0; + char *p; + + debug3("%s entering", __func__); + auth = _auth; + reply = _reply; + + buffer_init(&m); + buffer_put_string(&m, auth->dat, auth->length); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KRB4, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KRB4, &m); + + success = buffer_get_int(&m); + if (success) { + *client = buffer_get_string(&m, NULL); + p = buffer_get_string(&m, &rlen); + if (rlen >= MAX_KTXT_LEN) + fatal("%s: reply from monitor too large", __func__); + reply->length = rlen; + memcpy(reply->dat, p, rlen); + memset(p, 0, rlen); + xfree(p); + } + buffer_free(&m); + return (success); +} +#endif + +#ifdef KRB5 +int +mm_auth_krb5(void *ctx, void *argp, char **userp, void *resp) +{ + krb5_data *tkt, *reply; + Buffer m; + int success; + + debug3("%s entering", __func__); + tkt = (krb5_data *) argp; + reply = (krb5_data *) resp; + + buffer_init(&m); + buffer_put_string(&m, tkt->data, tkt->length); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KRB5, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KRB5, &m); + + success = buffer_get_int(&m); + if (success) { + u_int len; + + *userp = buffer_get_string(&m, NULL); + reply->data = buffer_get_string(&m, &len); + reply->length = len; + } else { + memset(reply, 0, sizeof(*reply)); + *userp = NULL; + } + + buffer_free(&m); + return (success); +} +#endif +#ifdef GSSAPI +OM_uint32 +mm_ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID oid) { + Buffer m; + OM_uint32 major; + + /* Client doesn't get to see the context */ + *ctx=NULL; + + buffer_init(&m); + buffer_put_string(&m,oid->elements,oid->length); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSETUP, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSETUP, &m); + + major=buffer_get_int(&m); + + buffer_free(&m); + return(major); +} + +OM_uint32 +mm_ssh_gssapi_accept_ctx(Gssctxt *ctx, gss_buffer_t in, + gss_buffer_t out) { + + Buffer m; + OM_uint32 major; + + buffer_init(&m); + buffer_put_string(&m, in->value, in->length); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSTEP, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSTEP, &m); + + major=buffer_get_int(&m); + out->value=buffer_get_string(&m,&out->length); + buffer_free(&m); + + return(major); +} + +int +mm_ssh_gssapi_userok(Gssctxt *ctx, char *user) { + Buffer m; + int authenticated = 0; + + buffer_init(&m); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUSEROK, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUSEROK, + &m); + + authenticated = buffer_get_int(&m); + + buffer_free(&m); + debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not "); + return(authenticated); +} + +OM_uint32 +mm_ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_desc *data, gss_buffer_desc *hash) { + Buffer m; + OM_uint32 major; + + buffer_init(&m); + buffer_put_string(&m, data->value, data->length); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSIGN, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSIGN, &m); + + major=buffer_get_int(&m); + hash->value = buffer_get_string(&m, &hash->length); + + buffer_free(&m); + + return(major); +} + +char * +mm_ssh_gssapi_last_error(Gssctxt *ctx, OM_uint32 *major, OM_uint32 *minor) { + Buffer m; + OM_uint32 maj,min; + char *errstr; + + buffer_init(&m); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSERR, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSERR, &m); + + maj = buffer_get_int(&m); + min = buffer_get_int(&m); + + if (major) *major=maj; + if (minor) *minor=min; + + errstr=buffer_get_string(&m,NULL); + + buffer_free(&m); + + return(errstr); +} + +OM_uint32 +mm_gss_indicate_mechs(OM_uint32 *minor_status, gss_OID_set *mech_set) +{ + Buffer m; + OM_uint32 major,minor; + int count; + gss_OID_desc oid; + u_int length; + + buffer_init(&m); + + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSMECHS, &m); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSMECHS, + &m); + major=buffer_get_int(&m); + count=buffer_get_int(&m); + + gss_create_empty_oid_set(&minor,mech_set); + while(count-->0) { + oid.elements=buffer_get_string(&m,&length); + oid.length=length; + gss_add_oid_set_member(&minor,&oid,mech_set); + } + + buffer_free(&m); + + return(major); +} + +int +mm_ssh_gssapi_localname(char **lname) +{ + Buffer m; + + buffer_init(&m); + mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSLOCALNAME, &m); + + debug3("%s: waiting for MONITOR_ANS_GSSLOCALNAME", __func__); + mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSLOCALNAME, + &m); + + *lname = buffer_get_string(&m, NULL); + + buffer_free(&m); + if (lname[0] == '\0') { + debug3("%s: gssapi identity mapping failed", __func__); + } else { + debug3("%s: gssapi identity mapped to %s", __func__, *lname); + } + + return(0); +} +#endif /* GSSAPI */ diff --git a/usr/src/cmd/ssh/libssh/common/mpaux.c b/usr/src/cmd/ssh/libssh/common/mpaux.c new file mode 100644 index 0000000000..1b77961b62 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/mpaux.c @@ -0,0 +1,48 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * This file contains various auxiliary functions related to multiple + * precision integers. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: mpaux.c,v 1.16 2001/02/08 19:30:52 itojun Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> +#include "getput.h" +#include "xmalloc.h" + +#include <openssl/md5.h> + +#include "mpaux.h" + +void +compute_session_id(u_char session_id[16], + u_char cookie[8], + BIGNUM* host_key_n, + BIGNUM* session_key_n) +{ + u_int host_key_bytes = BN_num_bytes(host_key_n); + u_int session_key_bytes = BN_num_bytes(session_key_n); + u_int bytes = host_key_bytes + session_key_bytes; + u_char *buf = xmalloc(bytes); + MD5_CTX md; + + BN_bn2bin(host_key_n, buf); + BN_bn2bin(session_key_n, buf + host_key_bytes); + MD5_Init(&md); + MD5_Update(&md, buf, bytes); + MD5_Update(&md, cookie, 8); + MD5_Final(session_id, &md); + memset(buf, 0, bytes); + xfree(buf); +} diff --git a/usr/src/cmd/ssh/libssh/common/msg.c b/usr/src/cmd/ssh/libssh/common/msg.c new file mode 100644 index 0000000000..26c5eeec61 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/msg.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2002 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "includes.h" +RCSID("$OpenBSD: msg.c,v 1.4 2002/07/01 16:15:25 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "buffer.h" +#include "getput.h" +#include "log.h" +#include "atomicio.h" +#include "msg.h" + +void +ssh_msg_send(int fd, u_char type, Buffer *m) +{ + u_char buf[5]; + u_int mlen = buffer_len(m); + + debug3("ssh_msg_send: type %u", (unsigned int)type & 0xff); + + PUT_32BIT(buf, mlen + 1); + buf[4] = type; /* 1st byte of payload is mesg-type */ + if (atomicio(write, fd, buf, sizeof(buf)) != sizeof(buf)) + fatal("ssh_msg_send: write"); + if (atomicio(write, fd, buffer_ptr(m), mlen) != mlen) + fatal("ssh_msg_send: write"); +} + +int +ssh_msg_recv(int fd, Buffer *m) +{ + u_char buf[4]; + ssize_t res; + u_int msg_len; + + debug3("ssh_msg_recv entering"); + + res = atomicio(read, fd, buf, sizeof(buf)); + if (res != sizeof(buf)) { + if (res == 0) + return -1; + fatal("ssh_msg_recv: read: header %ld", (long)res); + } + msg_len = GET_32BIT(buf); + if (msg_len > 256 * 1024) + fatal("ssh_msg_recv: read: bad msg_len %u", msg_len); + buffer_clear(m); + buffer_append_space(m, msg_len); + res = atomicio(read, fd, buffer_ptr(m), msg_len); + if (res != msg_len) + fatal("ssh_msg_recv: read: %ld != msg_len", (long)res); + return 0; +} diff --git a/usr/src/cmd/ssh/libssh/common/nchan.c b/usr/src/cmd/ssh/libssh/common/nchan.c new file mode 100644 index 0000000000..97c51fcda8 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/nchan.c @@ -0,0 +1,485 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: nchan.c,v 1.47 2002/06/19 00:27:55 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ssh1.h" +#include "ssh2.h" +#include "buffer.h" +#include "packet.h" +#include "channels.h" +#include "compat.h" +#include "log.h" + +/* + * SSH Protocol 1.5 aka New Channel Protocol + * Thanks to Martina, Axel and everyone who left Erlangen, leaving me bored. + * Written by Markus Friedl in October 1999 + * + * Protocol versions 1.3 and 1.5 differ in the handshake protocol used for the + * tear down of channels: + * + * 1.3: strict request-ack-protocol: + * CLOSE -> + * <- CLOSE_CONFIRM + * + * 1.5: uses variations of: + * IEOF -> + * <- OCLOSE + * <- IEOF + * OCLOSE -> + * i.e. both sides have to close the channel + * + * 2.0: the EOF messages are optional + * + * See the debugging output from 'ssh -v' and 'sshd -d' of + * ssh-1.2.27 as an example. + * + */ + +/* functions manipulating channel states */ +/* + * EVENTS update channel input/output states execute ACTIONS + */ +/* + * ACTIONS: should never update the channel states + */ +static void chan_send_ieof1(Channel *); +static void chan_send_oclose1(Channel *); +static void chan_send_close2(Channel *); +static void chan_send_eof2(Channel *); + +/* helper */ +static void chan_shutdown_write(Channel *); +static void chan_shutdown_read(Channel *); + +static char *ostates[] = { "open", "drain", "wait_ieof", "closed" }; +static char *istates[] = { "open", "drain", "wait_oclose", "closed" }; + +static void +chan_set_istate(Channel *c, u_int next) +{ + if (c->istate > CHAN_INPUT_CLOSED || next > CHAN_INPUT_CLOSED) + fatal("chan_set_istate: bad state %d -> %d", c->istate, next); + debug("channel %d: input %s -> %s", c->self, istates[c->istate], + istates[next]); + c->istate = next; +} +static void +chan_set_ostate(Channel *c, u_int next) +{ + if (c->ostate > CHAN_OUTPUT_CLOSED || next > CHAN_OUTPUT_CLOSED) + fatal("chan_set_ostate: bad state %d -> %d", c->ostate, next); + debug("channel %d: output %s -> %s", c->self, ostates[c->ostate], + ostates[next]); + c->ostate = next; +} + +/* + * SSH1 specific implementation of event functions + */ + +static void +chan_rcvd_oclose1(Channel *c) +{ + debug("channel %d: rcvd oclose", c->self); + switch (c->istate) { + case CHAN_INPUT_WAIT_OCLOSE: + chan_set_istate(c, CHAN_INPUT_CLOSED); + break; + case CHAN_INPUT_OPEN: + chan_shutdown_read(c); + chan_send_ieof1(c); + chan_set_istate(c, CHAN_INPUT_CLOSED); + break; + case CHAN_INPUT_WAIT_DRAIN: + /* both local read_failed and remote write_failed */ + chan_send_ieof1(c); + chan_set_istate(c, CHAN_INPUT_CLOSED); + break; + default: + error("channel %d: protocol error: rcvd_oclose for istate %d", + c->self, c->istate); + return; + } +} +void +chan_read_failed(Channel *c) +{ + debug("channel %d: read failed", c->self); + switch (c->istate) { + case CHAN_INPUT_OPEN: + chan_shutdown_read(c); + chan_set_istate(c, CHAN_INPUT_WAIT_DRAIN); + break; + default: + error("channel %d: chan_read_failed for istate %d", + c->self, c->istate); + break; + } +} +void +chan_ibuf_empty(Channel *c) +{ + debug("channel %d: ibuf empty", c->self); + if (buffer_len(&c->input)) { + error("channel %d: chan_ibuf_empty for non empty buffer", + c->self); + return; + } + switch (c->istate) { + case CHAN_INPUT_WAIT_DRAIN: + if (compat20) { + if (!(c->flags & CHAN_CLOSE_SENT)) + chan_send_eof2(c); + chan_set_istate(c, CHAN_INPUT_CLOSED); + } else { + chan_send_ieof1(c); + chan_set_istate(c, CHAN_INPUT_WAIT_OCLOSE); + } + break; + default: + error("channel %d: chan_ibuf_empty for istate %d", + c->self, c->istate); + break; + } +} +static void +chan_rcvd_ieof1(Channel *c) +{ + debug("channel %d: rcvd ieof", c->self); + switch (c->ostate) { + case CHAN_OUTPUT_OPEN: + chan_set_ostate(c, CHAN_OUTPUT_WAIT_DRAIN); + break; + case CHAN_OUTPUT_WAIT_IEOF: + chan_set_ostate(c, CHAN_OUTPUT_CLOSED); + break; + default: + error("channel %d: protocol error: rcvd_ieof for ostate %d", + c->self, c->ostate); + break; + } +} +static void +chan_write_failed1(Channel *c) +{ + debug("channel %d: write failed", c->self); + switch (c->ostate) { + case CHAN_OUTPUT_OPEN: + chan_shutdown_write(c); + chan_send_oclose1(c); + chan_set_ostate(c, CHAN_OUTPUT_WAIT_IEOF); + break; + case CHAN_OUTPUT_WAIT_DRAIN: + chan_shutdown_write(c); + chan_send_oclose1(c); + chan_set_ostate(c, CHAN_OUTPUT_CLOSED); + break; + default: + error("channel %d: chan_write_failed for ostate %d", + c->self, c->ostate); + break; + } +} +void +chan_obuf_empty(Channel *c) +{ + debug("channel %d: obuf empty", c->self); + if (buffer_len(&c->output)) { + error("channel %d: chan_obuf_empty for non empty buffer", + c->self); + return; + } + switch (c->ostate) { + case CHAN_OUTPUT_WAIT_DRAIN: + chan_shutdown_write(c); + if (!compat20) + chan_send_oclose1(c); + chan_set_ostate(c, CHAN_OUTPUT_CLOSED); + break; + default: + error("channel %d: internal error: obuf_empty for ostate %d", + c->self, c->ostate); + break; + } +} +static void +chan_send_ieof1(Channel *c) +{ + debug("channel %d: send ieof", c->self); + switch (c->istate) { + case CHAN_INPUT_OPEN: + case CHAN_INPUT_WAIT_DRAIN: + packet_start(SSH_MSG_CHANNEL_INPUT_EOF); + packet_put_int(c->remote_id); + packet_send(); + break; + default: + error("channel %d: cannot send ieof for istate %d", + c->self, c->istate); + break; + } +} +static void +chan_send_oclose1(Channel *c) +{ + debug("channel %d: send oclose", c->self); + switch (c->ostate) { + case CHAN_OUTPUT_OPEN: + case CHAN_OUTPUT_WAIT_DRAIN: + buffer_clear(&c->output); + packet_start(SSH_MSG_CHANNEL_OUTPUT_CLOSE); + packet_put_int(c->remote_id); + packet_send(); + break; + default: + error("channel %d: cannot send oclose for ostate %d", + c->self, c->ostate); + break; + } +} + +/* + * the same for SSH2 + */ +static void +chan_rcvd_close2(Channel *c) +{ + debug("channel %d: rcvd close", c->self); + if (c->flags & CHAN_CLOSE_RCVD) + error("channel %d: protocol error: close rcvd twice", c->self); + c->flags |= CHAN_CLOSE_RCVD; + if (c->type == SSH_CHANNEL_LARVAL) { + /* tear down larval channels immediately */ + chan_set_ostate(c, CHAN_OUTPUT_CLOSED); + chan_set_istate(c, CHAN_INPUT_CLOSED); + return; + } + switch (c->ostate) { + case CHAN_OUTPUT_OPEN: + /* + * wait until a data from the channel is consumed if a CLOSE + * is received + */ + chan_set_ostate(c, CHAN_OUTPUT_WAIT_DRAIN); + break; + } + switch (c->istate) { + case CHAN_INPUT_OPEN: + chan_shutdown_read(c); + chan_set_istate(c, CHAN_INPUT_CLOSED); + break; + case CHAN_INPUT_WAIT_DRAIN: + chan_send_eof2(c); + chan_set_istate(c, CHAN_INPUT_CLOSED); + break; + } +} +static void +chan_rcvd_eof2(Channel *c) +{ + debug("channel %d: rcvd eof", c->self); + c->flags |= CHAN_EOF_RCVD; + if (c->ostate == CHAN_OUTPUT_OPEN) + chan_set_ostate(c, CHAN_OUTPUT_WAIT_DRAIN); +} +static void +chan_write_failed2(Channel *c) +{ + debug("channel %d: write failed", c->self); + switch (c->ostate) { + case CHAN_OUTPUT_OPEN: + case CHAN_OUTPUT_WAIT_DRAIN: + chan_shutdown_write(c); + chan_set_ostate(c, CHAN_OUTPUT_CLOSED); + break; + default: + error("channel %d: chan_write_failed for ostate %d", + c->self, c->ostate); + break; + } +} +static void +chan_send_eof2(Channel *c) +{ + debug("channel %d: send eof", c->self); + switch (c->istate) { + case CHAN_INPUT_WAIT_DRAIN: + packet_start(SSH2_MSG_CHANNEL_EOF); + packet_put_int(c->remote_id); + packet_send(); + c->flags |= CHAN_EOF_SENT; + break; + default: + error("channel %d: cannot send eof for istate %d", + c->self, c->istate); + break; + } +} +static void +chan_send_close2(Channel *c) +{ + debug("channel %d: send close", c->self); + if (c->ostate != CHAN_OUTPUT_CLOSED || + c->istate != CHAN_INPUT_CLOSED) { + error("channel %d: cannot send close for istate/ostate %d/%d", + c->self, c->istate, c->ostate); + } else if (c->flags & CHAN_CLOSE_SENT) { + error("channel %d: already sent close", c->self); + } else { + packet_start(SSH2_MSG_CHANNEL_CLOSE); + packet_put_int(c->remote_id); + packet_send(); + c->flags |= CHAN_CLOSE_SENT; + } +} + +/* shared */ + +void +chan_rcvd_ieof(Channel *c) +{ + if (compat20) + chan_rcvd_eof2(c); + else + chan_rcvd_ieof1(c); + if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN && + buffer_len(&c->output) == 0 && + !CHANNEL_EFD_OUTPUT_ACTIVE(c)) + chan_obuf_empty(c); +} +void +chan_rcvd_oclose(Channel *c) +{ + if (compat20) + chan_rcvd_close2(c); + else + chan_rcvd_oclose1(c); +} +void +chan_write_failed(Channel *c) +{ + if (compat20) + chan_write_failed2(c); + else + chan_write_failed1(c); +} + +void +chan_mark_dead(Channel *c) +{ + c->type = SSH_CHANNEL_ZOMBIE; +} + +int +chan_is_dead(Channel *c, int send) +{ + if (c->type == SSH_CHANNEL_ZOMBIE) { + debug("channel %d: zombie", c->self); + return 1; + } + if (c->istate != CHAN_INPUT_CLOSED || c->ostate != CHAN_OUTPUT_CLOSED) + return 0; + if (!compat20) { + debug("channel %d: is dead", c->self); + return 1; + } + if ((datafellows & SSH_BUG_EXTEOF) && + c->extended_usage == CHAN_EXTENDED_WRITE && + c->efd != -1 && + buffer_len(&c->extended) > 0) { + debug2("channel %d: active efd: %d len %d", + c->self, c->efd, buffer_len(&c->extended)); + return 0; + } + if (!(c->flags & CHAN_CLOSE_SENT)) { + if (send) { + chan_send_close2(c); + } else { + /* channel would be dead if we sent a close */ + if (c->flags & CHAN_CLOSE_RCVD) { + debug("channel %d: almost dead", + c->self); + return 1; + } + } + } + if ((c->flags & CHAN_CLOSE_SENT) && + (c->flags & CHAN_CLOSE_RCVD)) { + debug("channel %d: is dead", c->self); + return 1; + } + return 0; +} + +/* helper */ +static void +chan_shutdown_write(Channel *c) +{ + buffer_clear(&c->output); + if (compat20 && c->type == SSH_CHANNEL_LARVAL) + return; + /* shutdown failure is allowed if write failed already */ + debug("channel %d: close_write", c->self); + if (c->sock != -1) { + if (shutdown(c->sock, SHUT_WR) < 0) + debug("channel %d: chan_shutdown_write: " + "shutdown() failed for fd%d: %.100s", + c->self, c->sock, strerror(errno)); + } else { + if (channel_close_fd(&c->wfd) < 0) + log("channel %d: chan_shutdown_write: " + "close() failed for fd%d: %.100s", + c->self, c->wfd, strerror(errno)); + } +} +static void +chan_shutdown_read(Channel *c) +{ + if (compat20 && c->type == SSH_CHANNEL_LARVAL) + return; + debug("channel %d: close_read", c->self); + if (c->sock != -1) { + /* + * shutdown(sock, SHUT_READ) may return ENOTCONN if the + * write side has been closed already. (bug on Linux) + * HP-UX may return ENOTCONN also. + */ + if (shutdown(c->sock, SHUT_RD) < 0 + && errno != ENOTCONN) + error("channel %d: chan_shutdown_read: " + "shutdown() failed for fd%d [i%d o%d]: %.100s", + c->self, c->sock, c->istate, c->ostate, + strerror(errno)); + } else { + if (channel_close_fd(&c->rfd) < 0) + log("channel %d: chan_shutdown_read: " + "close() failed for fd%d: %.100s", + c->self, c->rfd, strerror(errno)); + } +} diff --git a/usr/src/cmd/ssh/libssh/common/packet.c b/usr/src/cmd/ssh/libssh/common/packet.c new file mode 100644 index 0000000000..10cf9bdc1b --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/packet.c @@ -0,0 +1,1608 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * This file contains code implementing the packet protocol and communication + * with the other side. This same code is used both on client and server side. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * SSH2 packet format added by Markus Friedl. + * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: packet.c,v 1.97 2002/07/04 08:12:15 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "buffer.h" +#include "packet.h" +#include "bufaux.h" +#include "crc32.h" +#include "getput.h" + +#include "compress.h" +#include "deattack.h" +#include "channels.h" + +#include "compat.h" +#include "ssh1.h" +#include "ssh2.h" + +#include "cipher.h" +#include "kex.h" +#include "mac.h" +#include "log.h" +#include "canohost.h" +#include "misc.h" +#include "ssh.h" + +#ifdef ALTPRIVSEP +static int packet_server = 0; +static int packet_monitor = 0; +#endif /* ALTPRIVSEP */ + +#ifdef PACKET_DEBUG +#define DBG(x) x +#else +#define DBG(x) +#endif + +/* + * This variable contains the file descriptors used for communicating with + * the other side. connection_in is used for reading; connection_out for + * writing. These can be the same descriptor, in which case it is assumed to + * be a socket. + */ +static int connection_in = -1; +static int connection_out = -1; + +/* Protocol flags for the remote side. */ +static u_int remote_protocol_flags = 0; + +/* Encryption context for receiving data. This is only used for decryption. */ +static CipherContext receive_context; + +/* Encryption context for sending data. This is only used for encryption. */ +static CipherContext send_context; + +/* Buffer for raw input data from the socket. */ +Buffer input; + +/* Buffer for raw output data going to the socket. */ +Buffer output; + +/* Buffer for the partial outgoing packet being constructed. */ +static Buffer outgoing_packet; + +/* Buffer for the incoming packet currently being processed. */ +static Buffer incoming_packet; + +/* Scratch buffer for packet compression/decompression. */ +static Buffer compression_buffer; +static int compression_buffer_ready = 0; + +/* Flag indicating whether packet compression/decompression is enabled. */ +static int packet_compression = 0; + +/* default maximum packet size */ +int max_packet_size = 32768; + +/* Flag indicating whether this module has been initialized. */ +static int initialized = 0; + +/* Set to true if the connection is interactive. */ +static int interactive_mode = 0; + +/* Session key information for Encryption and MAC */ +Newkeys *newkeys[MODE_MAX]; +static u_int32_t read_seqnr = 0; +static u_int32_t send_seqnr = 0; + +/* Session key for protocol v1 */ +static u_char ssh1_key[SSH_SESSION_KEY_LENGTH]; +static u_int ssh1_keylen; + +/* roundup current message to extra_pad bytes */ +static u_char extra_pad = 0; + +/* + * Sets the descriptors used for communication. Disables encryption until + * packet_set_encryption_key is called. + */ +void +packet_set_connection(int fd_in, int fd_out) +{ + Cipher *none = cipher_by_name("none"); + + if (none == NULL) + fatal("packet_set_connection: cannot load cipher 'none'"); + connection_in = fd_in; + connection_out = fd_out; + cipher_init(&send_context, none, (unsigned char *) "", 0, NULL, 0, CIPHER_ENCRYPT); + cipher_init(&receive_context, none, (unsigned char *) "", 0, NULL, 0, CIPHER_DECRYPT); + newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL; + if (!initialized) { + initialized = 1; + buffer_init(&input); + buffer_init(&output); + buffer_init(&outgoing_packet); + buffer_init(&incoming_packet); + } else { + buffer_clear(&input); + buffer_clear(&output); + buffer_clear(&outgoing_packet); + buffer_clear(&incoming_packet); + } + + /* + * Prime the cache for get_remote_ipaddr() while we have a + * socket on which to do a getpeername(). + */ + (void) get_remote_ipaddr(); + + /* Kludge: arrange the close function to be called from fatal(). */ + fatal_add_cleanup((void (*) (void *)) packet_close, NULL); +} + +/* Returns 1 if remote host is connected via socket, 0 if not. */ + +int +packet_connection_is_on_socket(void) +{ + struct sockaddr_storage from, to; + socklen_t fromlen, tolen; + + /* filedescriptors in and out are the same, so it's a socket */ + if (connection_in != -1 && connection_in == connection_out) + return 1; + fromlen = sizeof(from); + memset(&from, 0, sizeof(from)); + if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0) + return 0; + tolen = sizeof(to); + memset(&to, 0, sizeof(to)); + if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0) + return 0; + if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0) + return 0; + if (from.ss_family != AF_INET && from.ss_family != AF_INET6) + return 0; + return 1; +} + +/* + * Exports an IV from the CipherContext required to export the key + * state back from the unprivileged child to the privileged parent + * process. + */ + +void +packet_get_keyiv(int mode, u_char *iv, u_int len) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + cipher_get_keyiv(cc, iv, len); +} + +int +packet_get_keycontext(int mode, u_char *dat) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + return (cipher_get_keycontext(cc, dat)); +} + +void +packet_set_keycontext(int mode, u_char *dat) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + cipher_set_keycontext(cc, dat); +} + +int +packet_get_keyiv_len(int mode) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + return (cipher_get_keyiv_len(cc)); +} +void +packet_set_iv(int mode, u_char *dat) +{ + CipherContext *cc; + + if (mode == MODE_OUT) + cc = &send_context; + else + cc = &receive_context; + + cipher_set_keyiv(cc, dat); +} +int +packet_get_ssh1_cipher() +{ + return (cipher_get_number(receive_context.cipher)); +} + + +u_int32_t +packet_get_seqnr(int mode) +{ + return (mode == MODE_IN ? read_seqnr : send_seqnr); +} + +void +packet_set_seqnr(int mode, u_int32_t seqnr) +{ + if (mode == MODE_IN) + read_seqnr = seqnr; + else if (mode == MODE_OUT) + send_seqnr = seqnr; + else + fatal("packet_set_seqnr: bad mode %d", mode); +} + +/* returns 1 if connection is via ipv4 */ + +int +packet_connection_is_ipv4(void) +{ + struct sockaddr_storage to; + socklen_t tolen = sizeof(to); + + memset(&to, 0, sizeof(to)); + if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0) + return 0; + if (to.ss_family == AF_INET) + return 1; +#ifdef IPV4_IN_IPV6 + if (to.ss_family == AF_INET6 && + IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr)) + return 1; +#endif + return 0; +} + +/* Sets the connection into non-blocking mode. */ + +void +packet_set_nonblocking(void) +{ + /* Set the socket into non-blocking mode. */ + if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0) + error("fcntl O_NONBLOCK: %.100s", strerror(errno)); + + if (connection_out != connection_in) { + if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0) + error("fcntl O_NONBLOCK: %.100s", strerror(errno)); + } +} + +/* Returns the socket used for reading. */ + +int +packet_get_connection_in(void) +{ + return connection_in; +} + +/* Returns the descriptor used for writing. */ + +int +packet_get_connection_out(void) +{ + return connection_out; +} + +/* Closes the connection and clears and frees internal data structures. */ + +void +packet_close(void) +{ + if (!initialized) + return; + initialized = 0; + if (connection_in == connection_out) { + shutdown(connection_out, SHUT_RDWR); + close(connection_out); + } else { + close(connection_in); + close(connection_out); + } + buffer_free(&input); + buffer_free(&output); + buffer_free(&outgoing_packet); + buffer_free(&incoming_packet); + if (compression_buffer_ready) { + buffer_free(&compression_buffer); + buffer_compress_uninit(); + compression_buffer_ready = 0; + } + cipher_cleanup(&send_context); + cipher_cleanup(&receive_context); +} + +/* Sets remote side protocol flags. */ + +void +packet_set_protocol_flags(u_int protocol_flags) +{ + remote_protocol_flags = protocol_flags; +} + +/* Returns the remote protocol flags set earlier by the above function. */ + +u_int +packet_get_protocol_flags(void) +{ + return remote_protocol_flags; +} + +/* + * Starts packet compression from the next packet on in both directions. + * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip. + */ + +static void +packet_init_compression(void) +{ + if (compression_buffer_ready == 1) + return; + compression_buffer_ready = 1; + buffer_init(&compression_buffer); +} + +void +packet_start_compression(int level) +{ +#ifdef ALTPRIVSEP + /* shouldn't happen! */ + if (packet_monitor) + fatal("INTERNAL ERROR: The monitor cannot compress."); +#endif /* ALTPRIVSEP */ + + if (packet_compression && !compat20) + fatal("Compression already enabled."); + packet_compression = 1; + packet_init_compression(); + buffer_compress_init_send(level); + buffer_compress_init_recv(); +} + +/* + * Causes any further packets to be encrypted using the given key. The same + * key is used for both sending and reception. However, both directions are + * encrypted independently of each other. + */ + +void +packet_set_encryption_key(const u_char *key, u_int keylen, + int number) +{ + Cipher *cipher = cipher_by_number(number); + + if (cipher == NULL) + fatal("packet_set_encryption_key: unknown cipher number %d", number); + if (keylen < 20) + fatal("packet_set_encryption_key: keylen too small: %d", keylen); + if (keylen > SSH_SESSION_KEY_LENGTH) + fatal("packet_set_encryption_key: keylen too big: %d", keylen); + memcpy(ssh1_key, key, keylen); + ssh1_keylen = keylen; + cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT); + cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT); +} + +u_int +packet_get_encryption_key(u_char *key) +{ + if (key == NULL) + return (ssh1_keylen); + memcpy(key, ssh1_key, ssh1_keylen); + return (ssh1_keylen); +} + +/* Start constructing a packet to send. */ +void +packet_start(u_char type) +{ + u_char buf[9]; + int len; + + DBG(debug("packet_start[%d]", type)); + len = compat20 ? 6 : 9; + memset(buf, 0, len - 1); + buf[len - 1] = type; + buffer_clear(&outgoing_packet); + buffer_append(&outgoing_packet, buf, len); +} + +/* Append payload. */ +void +packet_put_char(int value) +{ + char ch = value; + + buffer_append(&outgoing_packet, &ch, 1); +} +void +packet_put_int(u_int value) +{ + buffer_put_int(&outgoing_packet, value); +} +void +packet_put_string(const void *buf, u_int len) +{ + buffer_put_string(&outgoing_packet, buf, len); +} +void +packet_put_cstring(const char *str) +{ + buffer_put_cstring(&outgoing_packet, str); +} +void +packet_put_ascii_cstring(const char *str) +{ + buffer_put_ascii_cstring(&outgoing_packet, str); +} +void +packet_put_utf8_cstring(const u_char *str) +{ + buffer_put_utf8_cstring(&outgoing_packet, str); +} +#if 0 +void +packet_put_ascii_string(const void *buf, u_int len) +{ + buffer_put_ascii_string(&outgoing_packet, buf, len); +} +void +packet_put_utf8_string(const void *buf, u_int len) +{ + buffer_put_utf8_string(&outgoing_packet, buf, len); +} +#endif +void +packet_put_raw(const void *buf, u_int len) +{ + buffer_append(&outgoing_packet, buf, len); +} +void +packet_put_bignum(BIGNUM * value) +{ + buffer_put_bignum(&outgoing_packet, value); +} +void +packet_put_bignum2(BIGNUM * value) +{ + buffer_put_bignum2(&outgoing_packet, value); +} + +/* + * Finalizes and sends the packet. If the encryption key has been set, + * encrypts the packet before sending. + */ + +static void +packet_send1(void) +{ + u_char buf[8], *cp; + int i, padding, len; + u_int checksum; + u_int32_t rand = 0; + + /* + * If using packet compression, compress the payload of the outgoing + * packet. + */ + if (packet_compression) { + buffer_clear(&compression_buffer); + /* Skip padding. */ + buffer_consume(&outgoing_packet, 8); + /* padding */ + buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8); + buffer_compress(&outgoing_packet, &compression_buffer); + buffer_clear(&outgoing_packet); + buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer), + buffer_len(&compression_buffer)); + } + /* Compute packet length without padding (add checksum, remove padding). */ + len = buffer_len(&outgoing_packet) + 4 - 8; + + /* Insert padding. Initialized to zero in packet_start1() */ + padding = 8 - len % 8; + if (!send_context.plaintext) { + cp = buffer_ptr(&outgoing_packet); + for (i = 0; i < padding; i++) { + if (i % 4 == 0) + rand = arc4random(); + cp[7 - i] = rand & 0xff; + rand >>= 8; + } + } + buffer_consume(&outgoing_packet, 8 - padding); + + /* Add check bytes. */ + checksum = ssh_crc32(buffer_ptr(&outgoing_packet), + buffer_len(&outgoing_packet)); + PUT_32BIT(buf, checksum); + buffer_append(&outgoing_packet, buf, 4); + +#ifdef PACKET_DEBUG + fprintf(stderr, "packet_send plain: "); + buffer_dump(&outgoing_packet); +#endif + + /* Append to output. */ + PUT_32BIT(buf, len); + buffer_append(&output, buf, 4); + cp = buffer_append_space(&output, buffer_len(&outgoing_packet)); + cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet), + buffer_len(&outgoing_packet)); + +#ifdef PACKET_DEBUG + fprintf(stderr, "encrypted: "); + buffer_dump(&output); +#endif + + buffer_clear(&outgoing_packet); + + /* + * Note that the packet is now only buffered in output. It won\'t be + * actually sent until packet_write_wait or packet_write_poll is + * called. + */ +} + +void +set_newkeys(int mode) +{ + Enc *enc; + Mac *mac; + Comp *comp; + CipherContext *cc; + int encrypt; + + debug("newkeys: mode %d", mode); + + if (mode == MODE_OUT) { + cc = &send_context; + encrypt = CIPHER_ENCRYPT; + } else { + cc = &receive_context; + encrypt = CIPHER_DECRYPT; + } + if (newkeys[mode] != NULL) { + debug("newkeys: rekeying"); + cipher_cleanup(cc); + enc = &newkeys[mode]->enc; + mac = &newkeys[mode]->mac; + comp = &newkeys[mode]->comp; + memset(mac->key, 0, mac->key_len); + xfree(enc->name); + xfree(enc->iv); + xfree(enc->key); + xfree(mac->name); + xfree(mac->key); + xfree(comp->name); + xfree(newkeys[mode]); + } + newkeys[mode] = kex_get_newkeys(mode); + if (newkeys[mode] == NULL) + fatal("newkeys: no keys for mode %d", mode); + enc = &newkeys[mode]->enc; + mac = &newkeys[mode]->mac; + comp = &newkeys[mode]->comp; + if (mac->md != NULL) + mac->enabled = 1; + DBG(debug("cipher_init_context: %d", mode)); + cipher_init(cc, enc->cipher, enc->key, enc->key_len, + enc->iv, enc->block_size, encrypt); + /* Deleting the keys does not gain extra security */ + /* memset(enc->iv, 0, enc->block_size); + memset(enc->key, 0, enc->key_len); */ + if (comp->type != 0 && comp->enabled == 0) { + packet_init_compression(); + if (mode == MODE_OUT) + buffer_compress_init_send(6); + else + buffer_compress_init_recv(); + comp->enabled = 1; + } +} + +/* + * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue) + */ +static void +packet_send2(void) +{ + u_char type, *cp, *macbuf = NULL; + u_char padlen, pad; + u_int packet_length = 0; + u_int i, len; + u_int32_t rand = 0; + Enc *enc = NULL; + Mac *mac = NULL; + Comp *comp = NULL; + int block_size; + + if (newkeys[MODE_OUT] != NULL) { + enc = &newkeys[MODE_OUT]->enc; + mac = &newkeys[MODE_OUT]->mac; + comp = &newkeys[MODE_OUT]->comp; + } + block_size = enc ? enc->block_size : 8; + + cp = buffer_ptr(&outgoing_packet); + type = cp[5]; + +#ifdef PACKET_DEBUG + fprintf(stderr, "plain: "); + buffer_dump(&outgoing_packet); +#endif + + if (comp && comp->enabled) { + len = buffer_len(&outgoing_packet); + /* skip header, compress only payload */ + buffer_consume(&outgoing_packet, 5); + buffer_clear(&compression_buffer); + buffer_compress(&outgoing_packet, &compression_buffer); + buffer_clear(&outgoing_packet); + buffer_append(&outgoing_packet, "\0\0\0\0\0", 5); + buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer), + buffer_len(&compression_buffer)); + DBG(debug("compression: raw %d compressed %d", len, + buffer_len(&outgoing_packet))); + } + + /* sizeof (packet_len + pad_len + payload) */ + len = buffer_len(&outgoing_packet); + + /* + * calc size of padding, alloc space, get random data, + * minimum padding is 4 bytes + */ + padlen = block_size - (len % block_size); + if (padlen < 4) + padlen += block_size; + if (extra_pad) { + /* will wrap if extra_pad+padlen > 255 */ + extra_pad = roundup(extra_pad, block_size); + pad = extra_pad - ((len + padlen) % extra_pad); + debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)", + pad, len, padlen, extra_pad); + padlen += pad; + extra_pad = 0; + } + cp = buffer_append_space(&outgoing_packet, padlen); + if (enc && !send_context.plaintext) { + /* random padding */ + for (i = 0; i < padlen; i++) { + if (i % 4 == 0) + rand = arc4random(); + cp[i] = rand & 0xff; + rand >>= 8; + } + } else { + /* clear padding */ + memset(cp, 0, padlen); + } + /* packet_length includes payload, padding and padding length field */ + packet_length = buffer_len(&outgoing_packet) - 4; + cp = buffer_ptr(&outgoing_packet); + PUT_32BIT(cp, packet_length); + cp[4] = padlen; + DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen)); + + /* compute MAC over seqnr and packet(length fields, payload, padding) */ + if (mac && mac->enabled) { + macbuf = mac_compute(mac, send_seqnr, + buffer_ptr(&outgoing_packet), + buffer_len(&outgoing_packet)); + DBG(debug("done calc MAC out #%d", send_seqnr)); + } + /* encrypt packet and append to output buffer. */ + cp = buffer_append_space(&output, buffer_len(&outgoing_packet)); + cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet), + buffer_len(&outgoing_packet)); + /* append unencrypted MAC */ + if (mac && mac->enabled) + buffer_append(&output, (char *)macbuf, mac->mac_len); +#ifdef PACKET_DEBUG + fprintf(stderr, "encrypted: "); + buffer_dump(&output); +#endif + /* increment sequence number for outgoing packets */ + if (++send_seqnr == 0) + log("outgoing seqnr wraps around"); + buffer_clear(&outgoing_packet); + + if (type == SSH2_MSG_NEWKEYS) +#ifdef ALTPRIVSEP + /* set_newkeys(MODE_OUT) in client, server, but not monitor */ + if (!packet_is_server() && !packet_is_monitor()) +#endif /* ALTPRIVSEP */ + set_newkeys(MODE_OUT); +} + +void +packet_send(void) +{ + if (compat20) + packet_send2(); + else + packet_send1(); + DBG(debug("packet_send done")); +} + +/* + * Waits until a packet has been received, and returns its type. Note that + * no other data is processed until this returns, so this function should not + * be used during the interactive session. + */ + +int +packet_read_seqnr(u_int32_t *seqnr_p) +{ + int type, len; + fd_set *setp; + char buf[8192]; + DBG(debug("packet_read()")); + + setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) * + sizeof(fd_mask)); + + /* Since we are blocking, ensure that all written packets have been sent. */ + packet_write_wait(); + + /* Stay in the loop until we have received a complete packet. */ + for (;;) { + /* Try to read a packet from the buffer. */ + type = packet_read_poll_seqnr(seqnr_p); + if (!compat20 && ( + type == SSH_SMSG_SUCCESS + || type == SSH_SMSG_FAILURE + || type == SSH_CMSG_EOF + || type == SSH_CMSG_EXIT_CONFIRMATION)) + packet_check_eom(); + /* If we got a packet, return it. */ + if (type != SSH_MSG_NONE) { + xfree(setp); + return type; + } + /* + * Otherwise, wait for some data to arrive, add it to the + * buffer, and try again. + */ + memset(setp, 0, howmany(connection_in + 1, NFDBITS) * + sizeof(fd_mask)); + FD_SET(connection_in, setp); + + /* Wait for some data to arrive. */ + while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 && + (errno == EAGAIN || errno == EINTR)) + ; + + /* Read data from the socket. */ + len = read(connection_in, buf, sizeof(buf)); + if (len == 0) { + log("Connection closed by %.200s", get_remote_ipaddr()); + fatal_cleanup(); + } + if (len < 0) + fatal("Read from socket failed: %.100s", strerror(errno)); + /* Append it to the buffer. */ + packet_process_incoming(buf, len); + } + /* NOTREACHED */ +} + +int +packet_read(void) +{ + return packet_read_seqnr(NULL); +} + +/* + * Waits until a packet has been received, verifies that its type matches + * that given, and gives a fatal error and exits if there is a mismatch. + */ + +void +packet_read_expect(int expected_type) +{ + int type; + + type = packet_read(); + if (type != expected_type) + packet_disconnect("Protocol error: expected packet type %d, got %d", + expected_type, type); +} + +/* Checks if a full packet is available in the data received so far via + * packet_process_incoming. If so, reads the packet; otherwise returns + * SSH_MSG_NONE. This does not wait for data from the connection. + * + * SSH_MSG_DISCONNECT is handled specially here. Also, + * SSH_MSG_IGNORE messages are skipped by this function and are never returned + * to higher levels. + */ + +static int +packet_read_poll1(void) +{ + u_int len, padded_len; + u_char *cp, type; + u_int checksum, stored_checksum; + + /* Check if input size is less than minimum packet size. */ + if (buffer_len(&input) < 4 + 8) + return SSH_MSG_NONE; + /* Get length of incoming packet. */ + cp = buffer_ptr(&input); + len = GET_32BIT(cp); + if (len < 1 + 2 + 2 || len > 256 * 1024) + packet_disconnect("Bad packet length %d.", len); + padded_len = (len + 8) & ~7; + + /* Check if the packet has been entirely received. */ + if (buffer_len(&input) < 4 + padded_len) + return SSH_MSG_NONE; + + /* The entire packet is in buffer. */ + + /* Consume packet length. */ + buffer_consume(&input, 4); + + /* + * Cryptographic attack detector for ssh + * (C)1998 CORE-SDI, Buenos Aires Argentina + * Ariel Futoransky(futo@core-sdi.com) + */ + if (!receive_context.plaintext && + detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED) + packet_disconnect("crc32 compensation attack: network attack detected"); + + /* Decrypt data to incoming_packet. */ + buffer_clear(&incoming_packet); + cp = buffer_append_space(&incoming_packet, padded_len); + cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len); + + buffer_consume(&input, padded_len); + +#ifdef PACKET_DEBUG + fprintf(stderr, "read_poll plain: "); + buffer_dump(&incoming_packet); +#endif + + /* Compute packet checksum. */ + checksum = ssh_crc32(buffer_ptr(&incoming_packet), + buffer_len(&incoming_packet) - 4); + + /* Skip padding. */ + buffer_consume(&incoming_packet, 8 - len % 8); + + /* Test check bytes. */ + if (len != buffer_len(&incoming_packet)) + packet_disconnect("packet_read_poll1: len %d != buffer_len %d.", + len, buffer_len(&incoming_packet)); + + cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4; + stored_checksum = GET_32BIT(cp); + if (checksum != stored_checksum) + packet_disconnect("Corrupted check bytes on input."); + buffer_consume_end(&incoming_packet, 4); + + if (packet_compression) { + buffer_clear(&compression_buffer); + buffer_uncompress(&incoming_packet, &compression_buffer); + buffer_clear(&incoming_packet); + buffer_append(&incoming_packet, buffer_ptr(&compression_buffer), + buffer_len(&compression_buffer)); + } + type = buffer_get_char(&incoming_packet); + return type; +} + +static int +packet_read_poll2(u_int32_t *seqnr_p) +{ + static u_int packet_length = 0; + u_int padlen, need; + u_char *macbuf, *cp, type; + int maclen, block_size; + Enc *enc = NULL; + Mac *mac = NULL; + Comp *comp = NULL; + + if (newkeys[MODE_IN] != NULL) { + enc = &newkeys[MODE_IN]->enc; + mac = &newkeys[MODE_IN]->mac; + comp = &newkeys[MODE_IN]->comp; + } + maclen = mac && mac->enabled ? mac->mac_len : 0; + block_size = enc ? enc->block_size : 8; + + if (packet_length == 0) { + /* + * check if input size is less than the cipher block size, + * decrypt first block and extract length of incoming packet + */ + if (buffer_len(&input) < block_size) + return SSH_MSG_NONE; + buffer_clear(&incoming_packet); + cp = buffer_append_space(&incoming_packet, block_size); + cipher_crypt(&receive_context, cp, buffer_ptr(&input), + block_size); + cp = buffer_ptr(&incoming_packet); + packet_length = GET_32BIT(cp); + if (packet_length < 1 + 4 || packet_length > 256 * 1024) { + buffer_dump(&incoming_packet); + packet_disconnect("Bad packet length %d.", packet_length); + } + DBG(debug("input: packet len %d", packet_length+4)); + buffer_consume(&input, block_size); + } + /* we have a partial packet of block_size bytes */ + need = 4 + packet_length - block_size; + DBG(debug("partial packet %d, need %d, maclen %d", block_size, + need, maclen)); + if (need % block_size != 0) + fatal("padding error: need %d block %d mod %d", + need, block_size, need % block_size); + /* + * check if the entire packet has been received and + * decrypt into incoming_packet + */ + if (buffer_len(&input) < need + maclen) + return SSH_MSG_NONE; +#ifdef PACKET_DEBUG + fprintf(stderr, "read_poll enc/full: "); + buffer_dump(&input); +#endif + cp = buffer_append_space(&incoming_packet, need); + cipher_crypt(&receive_context, cp, buffer_ptr(&input), need); + buffer_consume(&input, need); + /* + * compute MAC over seqnr and packet, + * increment sequence number for incoming packet + */ + if (mac && mac->enabled) { + macbuf = mac_compute(mac, read_seqnr, + buffer_ptr(&incoming_packet), + buffer_len(&incoming_packet)); + if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0) + packet_disconnect("Corrupted MAC on input."); + DBG(debug("MAC #%d ok", read_seqnr)); + buffer_consume(&input, mac->mac_len); + } + if (seqnr_p != NULL) + *seqnr_p = read_seqnr; + if (++read_seqnr == 0) + log("incoming seqnr wraps around"); + + /* get padlen */ + cp = buffer_ptr(&incoming_packet); + padlen = cp[4]; + DBG(debug("input: padlen %d", padlen)); + if (padlen < 4) + packet_disconnect("Corrupted padlen %d on input.", padlen); + + /* skip packet size + padlen, discard padding */ + buffer_consume(&incoming_packet, 4 + 1); + buffer_consume_end(&incoming_packet, padlen); + + DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet))); + if (comp && comp->enabled) { + buffer_clear(&compression_buffer); + buffer_uncompress(&incoming_packet, &compression_buffer); + buffer_clear(&incoming_packet); + buffer_append(&incoming_packet, buffer_ptr(&compression_buffer), + buffer_len(&compression_buffer)); + DBG(debug("input: len after de-compress %d", + buffer_len(&incoming_packet))); + } + /* + * get packet type, implies consume. + * return length of payload (without type field) + */ + type = buffer_get_char(&incoming_packet); +#ifdef ALTPRIVSEP + if (type == SSH2_MSG_NEWKEYS) + /* set_newkeys(MODE_OUT) in client, server, but not monitor */ + if (!packet_is_server() && !packet_is_monitor()) + set_newkeys(MODE_IN); +#else /* ALTPRIVSEP */ + if (type == SSH2_MSG_NEWKEYS) + set_newkeys(MODE_IN); +#endif /* ALTPRIVSEP */ +#ifdef PACKET_DEBUG + fprintf(stderr, "read/plain[%d]:\r\n", type); + buffer_dump(&incoming_packet); +#endif + /* reset for next packet */ + packet_length = 0; + return type; +} + +int +packet_read_poll_seqnr(u_int32_t *seqnr_p) +{ + u_int reason, seqnr; + u_char type; + char *msg; + + for (;;) { + if (compat20) { + type = packet_read_poll2(seqnr_p); + DBG(debug("received packet type %d", type)); + switch (type) { + case SSH2_MSG_IGNORE: + break; + case SSH2_MSG_DEBUG: + packet_get_char(); + msg = packet_get_string(NULL); + debug("Remote: %.900s", msg); + xfree(msg); + msg = packet_get_string(NULL); + xfree(msg); + break; + case SSH2_MSG_DISCONNECT: + reason = packet_get_int(); + msg = packet_get_string(NULL); + log("Received disconnect from %s: %u: %.400s", + get_remote_ipaddr(), reason, msg); + xfree(msg); + fatal_cleanup(); + break; + case SSH2_MSG_UNIMPLEMENTED: + seqnr = packet_get_int(); + debug("Received SSH2_MSG_UNIMPLEMENTED for %u", + seqnr); + break; + default: + return type; + break; + } + } else { + type = packet_read_poll1(); + DBG(debug("received packet type %d", type)); + switch (type) { + case SSH_MSG_IGNORE: + break; + case SSH_MSG_DEBUG: + msg = packet_get_string(NULL); + debug("Remote: %.900s", msg); + xfree(msg); + break; + case SSH_MSG_DISCONNECT: + msg = packet_get_string(NULL); + log("Received disconnect from %s: %.400s", + get_remote_ipaddr(), msg); + fatal_cleanup(); + xfree(msg); + break; + default: + return type; + break; + } + } + } +} + +int +packet_read_poll(void) +{ + return packet_read_poll_seqnr(NULL); +} + +/* + * Buffers the given amount of input characters. This is intended to be used + * together with packet_read_poll. + */ + +void +packet_process_incoming(const char *buf, u_int len) +{ + buffer_append(&input, buf, len); +} + +/* Returns a character from the packet. */ + +u_int +packet_get_char(void) +{ + char ch; + + buffer_get(&incoming_packet, &ch, 1); + return (u_char) ch; +} + +/* Returns an integer from the packet data. */ + +u_int +packet_get_int(void) +{ + return buffer_get_int(&incoming_packet); +} + +/* + * Returns an arbitrary precision integer from the packet data. The integer + * must have been initialized before this call. + */ + +void +packet_get_bignum(BIGNUM * value) +{ + buffer_get_bignum(&incoming_packet, value); +} + +void +packet_get_bignum2(BIGNUM * value) +{ + buffer_get_bignum2(&incoming_packet, value); +} + +void * +packet_get_raw(u_int *length_ptr) +{ + u_int bytes = buffer_len(&incoming_packet); + + if (length_ptr != NULL) + *length_ptr = bytes; + return buffer_ptr(&incoming_packet); +} + +int +packet_remaining(void) +{ + return buffer_len(&incoming_packet); +} + +/* + * Returns a string from the packet data. The string is allocated using + * xmalloc; it is the responsibility of the calling program to free it when + * no longer needed. The length_ptr argument may be NULL, or point to an + * integer into which the length of the string is stored. + */ + +void * +packet_get_string(u_int *length_ptr) +{ + return buffer_get_string(&incoming_packet, length_ptr); +} +char * +packet_get_ascii_cstring() +{ + return buffer_get_ascii_cstring(&incoming_packet); +} +u_char * +packet_get_utf8_cstring() +{ + return buffer_get_utf8_cstring(&incoming_packet); +} + +/* + * Sends a diagnostic message from the server to the client. This message + * can be sent at any time (but not while constructing another message). The + * message is printed immediately, but only if the client is being executed + * in verbose mode. These messages are primarily intended to ease debugging + * authentication problems. The length of the formatted message must not + * exceed 1024 bytes. This will automatically call packet_write_wait. + */ + +void +packet_send_debug(const char *fmt,...) +{ + char buf[1024]; + va_list args; + + if (compat20 && (datafellows & SSH_BUG_DEBUG)) + return; + + va_start(args, fmt); + vsnprintf(buf, sizeof(buf), gettext(fmt), args); + va_end(args); + +#ifdef ALTPRIVSEP + /* shouldn't happen */ + if (packet_monitor) { + debug("packet_send_debug: %s", buf); + return; + } +#endif /* ALTPRIVSEP */ + + if (compat20) { + packet_start(SSH2_MSG_DEBUG); + packet_put_char(0); /* bool: always display */ + packet_put_cstring(buf); + packet_put_cstring(""); + } else { + packet_start(SSH_MSG_DEBUG); + packet_put_cstring(buf); + } + packet_send(); + packet_write_wait(); +} + +/* + * Logs the error plus constructs and sends a disconnect packet, closes the + * connection, and exits. This function never returns. The error message + * should not contain a newline. The length of the formatted message must + * not exceed 1024 bytes. + */ + +void +packet_disconnect(const char *fmt,...) +{ + char buf[1024]; + va_list args; + static int disconnecting = 0; + + if (disconnecting) /* Guard against recursive invocations. */ + fatal("packet_disconnect called recursively."); + disconnecting = 1; + + /* + * Format the message. Note that the caller must make sure the + * message is of limited size. + */ + va_start(args, fmt); + vsnprintf(buf, sizeof(buf), fmt, args); + va_end(args); + +#ifdef ALTPRIVSEP + /* + * If we packet_disconnect() in the monitor the fatal cleanups will take + * care of the child. See main() in sshd.c. We don't send the packet + * disconnect message here because: a) the child might not be looking + * for it and b) because we don't really know if the child is compat20 + * or not as we lost that information when packet_set_monitor() was + * called. + */ + if (packet_monitor) + goto close_stuff; +#endif /* ALTPRIVSEP */ + + /* Send the disconnect message to the other side, and wait for it to get sent. */ + if (compat20) { + packet_start(SSH2_MSG_DISCONNECT); + packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR); + packet_put_cstring(buf); + packet_put_cstring(""); + } else { + packet_start(SSH_MSG_DISCONNECT); + packet_put_cstring(buf); + } + packet_send(); + packet_write_wait(); + +#ifdef ALTPRIVSEP +close_stuff: +#endif /* ALTPRIVSEP */ + /* Stop listening for connections. */ + channel_close_all(); + + /* Close the connection. */ + packet_close(); + + /* Display the error locally and exit. */ + log("Disconnecting: %.100s", buf); + fatal_cleanup(); +} + +/* Checks if there is any buffered output, and tries to write some of the output. */ + +void +packet_write_poll(void) +{ + int len = buffer_len(&output); + + if (len > 0) { + len = write(connection_out, buffer_ptr(&output), len); + if (len <= 0) { + if (errno == EAGAIN) + return; + else + fatal("Write failed: %.100s", strerror(errno)); + } + buffer_consume(&output, len); + } +} + +/* + * Calls packet_write_poll repeatedly until all pending output data has been + * written. + */ + +void +packet_write_wait(void) +{ + fd_set *setp; + + setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) * + sizeof(fd_mask)); + packet_write_poll(); + while (packet_have_data_to_write()) { + memset(setp, 0, howmany(connection_out + 1, NFDBITS) * + sizeof(fd_mask)); + FD_SET(connection_out, setp); + while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 && + (errno == EAGAIN || errno == EINTR)) + ; + packet_write_poll(); + } + xfree(setp); +} + +/* Returns true if there is buffered data to write to the connection. */ + +int +packet_have_data_to_write(void) +{ + return buffer_len(&output) != 0; +} + +/* Returns true if there is not too much data to write to the connection. */ + +int +packet_not_very_much_data_to_write(void) +{ + if (interactive_mode) + return buffer_len(&output) < 16384; + else + return buffer_len(&output) < 128 * 1024; +} + +/* Informs that the current session is interactive. Sets IP flags for that. */ + +void +packet_set_interactive(int interactive) +{ + static int called = 0; +#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN) + int lowdelay = IPTOS_LOWDELAY; + int throughput = IPTOS_THROUGHPUT; +#endif + + if (called) + return; + called = 1; + + /* Record that we are in interactive mode. */ + interactive_mode = interactive; + + /* Only set socket options if using a socket. */ + if (!packet_connection_is_on_socket()) + return; + /* + * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only + */ + if (interactive) { + /* + * Set IP options for an interactive connection. Use + * IPTOS_LOWDELAY and TCP_NODELAY. + */ +#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN) + if (packet_connection_is_ipv4()) { + if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, + &lowdelay, sizeof(lowdelay)) < 0) + error("setsockopt IPTOS_LOWDELAY: %.100s", + strerror(errno)); + } +#endif + set_nodelay(connection_in); + } +#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN) + else if (packet_connection_is_ipv4()) { + /* + * Set IP options for a non-interactive connection. Use + * IPTOS_THROUGHPUT. + */ + if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput, + sizeof(throughput)) < 0) + error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno)); + } +#endif +} + +/* Returns true if the current connection is interactive. */ + +int +packet_is_interactive(void) +{ + return interactive_mode; +} + +int +packet_set_maxsize(int s) +{ + static int called = 0; + + if (called) { + log("packet_set_maxsize: called twice: old %d new %d", + max_packet_size, s); + return -1; + } + if (s < 4 * 1024 || s > 1024 * 1024) { + log("packet_set_maxsize: bad size %d", s); + return -1; + } + called = 1; + debug("packet_set_maxsize: setting to %d", s); + max_packet_size = s; + return s; +} + +/* roundup current message to pad bytes */ +void +packet_add_padding(u_char pad) +{ + extra_pad = pad; +} + +/* + * 9.2. Ignored Data Message + * + * byte SSH_MSG_IGNORE + * string data + * + * All implementations MUST understand (and ignore) this message at any + * time (after receiving the protocol version). No implementation is + * required to send them. This message can be used as an additional + * protection measure against advanced traffic analysis techniques. + */ +void +packet_send_ignore(int nbytes) +{ + u_int32_t rand = 0; + int i; + +#ifdef ALTPRIVSEP + /* shouldn't happen -- see packet_set_monitor() */ + if (packet_monitor) + return; +#endif /* ALTPRIVSEP */ + + packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE); + packet_put_int(nbytes); + for (i = 0; i < nbytes; i++) { + if (i % 4 == 0) + rand = arc4random(); + packet_put_char(rand & 0xff); + rand >>= 8; + } +} + +#ifdef ALTPRIVSEP +void +packet_set_server(void) +{ + packet_server = 1; +} + +void +packet_set_no_monitor(void) +{ + packet_server = 0; +} + +int +packet_is_server(void) +{ + return (packet_server); +} + +void +packet_set_monitor(int pipe) +{ + int dup_fd; + + packet_server = 1; + packet_monitor = 1; + + /* + * Awful hack follows. + * + * For SSHv1 the monitor does not process any SSHv1 packets, only + * ALTPRIVSEP packets. We take advantage of that here to keep changes + * to packet.c to a minimum by using the SSHv2 binary packet protocol, + * with cipher "none," mac "none" and compression alg "none," as the + * basis for the monitor protocol. And so to force packet.c to treat + * packets as SSHv2 we force compat20 == 1 here. + * + * For completeness and to help future developers catch this we also + * force compat20 == 1 in the monitor loop, in serverloop.c. + */ + compat20 = 1; + + /* + * NOTE: Assumptions below! + * + * - lots of packet.c code assumes that (connection_in == + * connection_out) -> connection is socket + * + * - packet_close() does not shutdown() the connection fildes + * if connection_in != connection_out + * + * - other code assumes the connection is a socket if + * connection_in == connection_out + */ + + if ((dup_fd = dup(pipe)) < 0) + fatal("Monitor failed to start: %s", strerror(errno)); + + /* + * make sure that the monitor's child's socket is not shutdown(3SOCKET) + * when we packet_close() + */ + if (packet_connection_is_on_socket()) + connection_out = -1; + + /* now cleanup state related to ssh socket */ + packet_close(); + + /* now make the monitor pipe look like the ssh connection */ + packet_set_connection(pipe, dup_fd); +} + +int +packet_is_monitor(void) +{ + return (packet_monitor); +} +#endif /* ALTPRIVSEP */ diff --git a/usr/src/cmd/ssh/libssh/common/proxy-io.c b/usr/src/cmd/ssh/libssh/common/proxy-io.c new file mode 100644 index 0000000000..c025f28f0a --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/proxy-io.c @@ -0,0 +1,38 @@ +/* + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <stdio.h> +#include <unistd.h> +#include "proxy-io.h" + +int +proxy_read_write_loop(int readfd, int writefd) +{ + int rbytes, bytes_to_write, bytes_written; + char readbuf[BUFFER_SIZ]; + char *ptr; + + rbytes = read(readfd, readbuf, sizeof (readbuf)); + + if (rbytes > 0) { + bytes_to_write = rbytes; + ptr = readbuf; + while (bytes_to_write > 0) { + if ((bytes_written = + write(writefd, ptr, bytes_to_write)) < 0) { + perror("write"); + return (0); + } + bytes_to_write -= bytes_written; + ptr += bytes_written; + } + } else if (rbytes <= 0) { + return (0); + } + /* Read and write successful */ + return (1); +} diff --git a/usr/src/cmd/ssh/libssh/common/radix.c b/usr/src/cmd/ssh/libssh/common/radix.c new file mode 100644 index 0000000000..4200f71b3b --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/radix.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1999 Dug Song. All rights reserved. + * Copyright (c) 2002 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +#include "uuencode.h" + +RCSID("$OpenBSD: radix.c,v 1.22 2002/09/09 14:54:15 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#ifdef AFS +#include <krb.h> + +#include <radix.h> +#include "bufaux.h" + +int +creds_to_radix(CREDENTIALS *creds, u_char *buf, size_t buflen) +{ + Buffer b; + int ret; + + buffer_init(&b); + + buffer_put_char(&b, 1); /* version */ + + buffer_append(&b, creds->service, strlen(creds->service)); + buffer_put_char(&b, '\0'); + buffer_append(&b, creds->instance, strlen(creds->instance)); + buffer_put_char(&b, '\0'); + buffer_append(&b, creds->realm, strlen(creds->realm)); + buffer_put_char(&b, '\0'); + buffer_append(&b, creds->pname, strlen(creds->pname)); + buffer_put_char(&b, '\0'); + buffer_append(&b, creds->pinst, strlen(creds->pinst)); + buffer_put_char(&b, '\0'); + + /* Null string to repeat the realm. */ + buffer_put_char(&b, '\0'); + + buffer_put_int(&b, creds->issue_date); + buffer_put_int(&b, krb_life_to_time(creds->issue_date, + creds->lifetime)); + buffer_append(&b, creds->session, sizeof(creds->session)); + buffer_put_short(&b, creds->kvno); + + /* 32 bit size + data */ + buffer_put_string(&b, creds->ticket_st.dat, creds->ticket_st.length); + + ret = uuencode(buffer_ptr(&b), buffer_len(&b), (char *)buf, buflen); + + buffer_free(&b); + return ret; +} + +#define GETSTRING(b, t, tlen) \ + do { \ + int i, found = 0; \ + for (i = 0; i < tlen; i++) { \ + if (buffer_len(b) == 0) \ + goto done; \ + t[i] = buffer_get_char(b); \ + if (t[i] == '\0') { \ + found = 1; \ + break; \ + } \ + } \ + if (!found) \ + goto done; \ + } while(0) + +int +radix_to_creds(const char *buf, CREDENTIALS *creds) +{ + Buffer b; + u_char *space; + char c, version, *p; + u_int endTime, len; + int blen, ret; + + ret = 0; + blen = strlen(buf); + + /* sanity check for size */ + if (blen > 8192) + return 0; + + buffer_init(&b); + space = buffer_append_space(&b, blen); + + /* check version and length! */ + len = uudecode(buf, space, blen); + if (len < 1) + goto done; + + version = buffer_get_char(&b); + + GETSTRING(&b, creds->service, sizeof creds->service); + GETSTRING(&b, creds->instance, sizeof creds->instance); + GETSTRING(&b, creds->realm, sizeof creds->realm); + GETSTRING(&b, creds->pname, sizeof creds->pname); + GETSTRING(&b, creds->pinst, sizeof creds->pinst); + + if (buffer_len(&b) == 0) + goto done; + + /* Ignore possibly different realm. */ + while (buffer_len(&b) > 0 && (c = buffer_get_char(&b)) != '\0') + ; + + if (buffer_len(&b) == 0) + goto done; + + creds->issue_date = buffer_get_int(&b); + + endTime = buffer_get_int(&b); + creds->lifetime = krb_time_to_life(creds->issue_date, endTime); + + len = buffer_len(&b); + if (len < sizeof(creds->session)) + goto done; + memcpy(&creds->session, buffer_ptr(&b), sizeof(creds->session)); + buffer_consume(&b, sizeof(creds->session)); + + creds->kvno = buffer_get_short(&b); + + p = buffer_get_string(&b, &len); + if (len < 0 || len > sizeof(creds->ticket_st.dat)) + goto done; + memcpy(&creds->ticket_st.dat, p, len); + creds->ticket_st.length = len; + + ret = 1; +done: + buffer_free(&b); + return ret; +} +#endif /* AFS */ diff --git a/usr/src/cmd/ssh/libssh/common/readconf.c b/usr/src/cmd/ssh/libssh/common/readconf.c new file mode 100644 index 0000000000..516cad749e --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/readconf.c @@ -0,0 +1,997 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Functions for reading the configuration files. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" +RCSID("$OpenBSD: readconf.c,v 1.100 2002/06/19 00:27:55 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ssh.h" +#include "xmalloc.h" +#include "compat.h" +#include "cipher.h" +#include "pathnames.h" +#include "log.h" +#include "readconf.h" +#include "match.h" +#include "misc.h" +#include "kex.h" +#include "mac.h" + +/* Format of the configuration file: + + # Configuration data is parsed as follows: + # 1. command line options + # 2. user-specific file + # 3. system-wide file + # Any configuration value is only changed the first time it is set. + # Thus, host-specific definitions should be at the beginning of the + # configuration file, and defaults at the end. + + # Host-specific declarations. These may override anything above. A single + # host may match multiple declarations; these are processed in the order + # that they are given in. + + Host *.ngs.fi ngs.fi + User foo + + Host fake.com + HostName another.host.name.real.org + User blaah + Port 34289 + ForwardX11 no + ForwardAgent no + + Host books.com + RemoteForward 9999 shadows.cs.hut.fi:9999 + Cipher 3des + + Host fascist.blob.com + Port 23123 + User tylonen + RhostsAuthentication no + PasswordAuthentication no + + Host puukko.hut.fi + User t35124p + ProxyCommand ssh-proxy %h %p + + Host *.fr + PublicKeyAuthentication no + + Host *.su + Cipher none + PasswordAuthentication no + + # Defaults for various options + Host * + ForwardAgent no + ForwardX11 no + RhostsAuthentication yes + PasswordAuthentication yes + RSAAuthentication yes + RhostsRSAAuthentication yes + StrictHostKeyChecking yes + KeepAlives no + IdentityFile ~/.ssh/identity + Port 22 + EscapeChar ~ + +*/ + +/* Keyword tokens. */ + +typedef enum { + oBadOption, + oForwardAgent, oForwardX11, oGatewayPorts, oRhostsAuthentication, + oPasswordAuthentication, oRSAAuthentication, + oChallengeResponseAuthentication, oXAuthLocation, +#if defined(KRB4) || defined(KRB5) + oKerberosAuthentication, +#endif +#ifdef GSSAPI + oGssKeyEx, oGssAuthentication, oGssDelegateCreds, +#ifdef GSI + oGssGlobusDelegateLimitedCreds, +#endif /* GSI */ +#endif /* GSSAPI */ +#if defined(AFS) || defined(KRB5) + oKerberosTgtPassing, +#endif +#ifdef AFS + oAFSTokenPassing, +#endif + oIdentityFile, oHostName, oPort, oCipher, oRemoteForward, oLocalForward, + oUser, oHost, oEscapeChar, oRhostsRSAAuthentication, oProxyCommand, + oGlobalKnownHostsFile, oUserKnownHostsFile, oConnectionAttempts, + oBatchMode, oCheckHostIP, oStrictHostKeyChecking, oCompression, + oCompressionLevel, oKeepAlives, oNumberOfPasswordPrompts, + oUsePrivilegedPort, oLogLevel, oCiphers, oProtocol, oMacs, + oGlobalKnownHostsFile2, oUserKnownHostsFile2, oPubkeyAuthentication, + oKbdInteractiveAuthentication, oKbdInteractiveDevices, oHostKeyAlias, + oDynamicForward, oPreferredAuthentications, oHostbasedAuthentication, + oHostKeyAlgorithms, oBindAddress, oSmartcardDevice, + oClearAllForwardings, oNoHostAuthenticationForLocalhost, + oFallBackToRsh, oUseRsh, + oDeprecated +} OpCodes; + +/* Textual representations of the tokens. */ + +static struct { + const char *name; + OpCodes opcode; +} keywords[] = { + { "forwardagent", oForwardAgent }, + { "forwardx11", oForwardX11 }, + { "xauthlocation", oXAuthLocation }, + { "gatewayports", oGatewayPorts }, + { "useprivilegedport", oUsePrivilegedPort }, + { "rhostsauthentication", oRhostsAuthentication }, + { "passwordauthentication", oPasswordAuthentication }, + { "kbdinteractiveauthentication", oKbdInteractiveAuthentication }, + { "kbdinteractivedevices", oKbdInteractiveDevices }, + { "rsaauthentication", oRSAAuthentication }, + { "pubkeyauthentication", oPubkeyAuthentication }, + { "dsaauthentication", oPubkeyAuthentication }, /* alias */ + { "rhostsrsaauthentication", oRhostsRSAAuthentication }, + { "hostbasedauthentication", oHostbasedAuthentication }, + { "challengeresponseauthentication", oChallengeResponseAuthentication }, + { "skeyauthentication", oChallengeResponseAuthentication }, /* alias */ + { "tisauthentication", oChallengeResponseAuthentication }, /* alias */ +#if defined(KRB4) || defined(KRB5) + { "kerberosauthentication", oKerberosAuthentication }, +#endif +#ifdef GSSAPI + { "gssapikeyexchange", oGssKeyEx }, + { "gssapiauthentication", oGssAuthentication }, + { "gssapidelegatecredentials", oGssDelegateCreds }, + { "gsskeyex", oGssKeyEx }, /* alias */ + { "gssauthentication", oGssAuthentication }, /* alias */ + { "gssdelegatecreds", oGssDelegateCreds }, /* alias */ +#ifdef GSI + /* For backwards compatability with old 1.2.27 client code */ + { "forwardgssapiglobusproxy", oGssDelegateCreds }, /* alias */ + { "forwardgssapiglobuslimitedproxy", oGssGlobusDelegateLimitedCreds }, +#endif /* GSI */ +#endif /* GSSAPI */ +#if defined(AFS) || defined(KRB5) + { "kerberostgtpassing", oKerberosTgtPassing }, +#endif +#ifdef AFS + { "afstokenpassing", oAFSTokenPassing }, +#endif + { "fallbacktorsh", oFallBackToRsh }, + { "usersh", oUseRsh }, + { "identityfile", oIdentityFile }, + { "identityfile2", oIdentityFile }, /* alias */ + { "hostname", oHostName }, + { "hostkeyalias", oHostKeyAlias }, + { "proxycommand", oProxyCommand }, + { "port", oPort }, + { "cipher", oCipher }, + { "ciphers", oCiphers }, + { "macs", oMacs }, + { "protocol", oProtocol }, + { "remoteforward", oRemoteForward }, + { "localforward", oLocalForward }, + { "user", oUser }, + { "host", oHost }, + { "escapechar", oEscapeChar }, + { "globalknownhostsfile", oGlobalKnownHostsFile }, + { "userknownhostsfile", oUserKnownHostsFile }, /* obsolete */ + { "globalknownhostsfile2", oGlobalKnownHostsFile2 }, + { "userknownhostsfile2", oUserKnownHostsFile2 }, /* obsolete */ + { "connectionattempts", oConnectionAttempts }, + { "batchmode", oBatchMode }, + { "checkhostip", oCheckHostIP }, + { "stricthostkeychecking", oStrictHostKeyChecking }, + { "compression", oCompression }, + { "compressionlevel", oCompressionLevel }, + { "keepalive", oKeepAlives }, + { "numberofpasswordprompts", oNumberOfPasswordPrompts }, + { "loglevel", oLogLevel }, + { "dynamicforward", oDynamicForward }, + { "preferredauthentications", oPreferredAuthentications }, + { "hostkeyalgorithms", oHostKeyAlgorithms }, + { "bindaddress", oBindAddress }, + { "smartcarddevice", oSmartcardDevice }, + { "clearallforwardings", oClearAllForwardings }, + { "nohostauthenticationforlocalhost", oNoHostAuthenticationForLocalhost }, + { NULL, oBadOption } +}; + +/* + * Adds a local TCP/IP port forward to options. Never returns if there is an + * error. + */ + +void +add_local_forward(Options *options, u_short port, const char *host, + u_short host_port) +{ + Forward *fwd; +#ifndef NO_IPPORT_RESERVED_CONCEPT + extern uid_t original_real_uid; + if (port < IPPORT_RESERVED && original_real_uid != 0) + fatal("Privileged ports can only be forwarded by root."); +#endif + if (options->num_local_forwards >= SSH_MAX_FORWARDS_PER_DIRECTION) + fatal("Too many local forwards (max %d).", SSH_MAX_FORWARDS_PER_DIRECTION); + fwd = &options->local_forwards[options->num_local_forwards++]; + fwd->port = port; + fwd->host = xstrdup(host); + fwd->host_port = host_port; +} + +/* + * Adds a remote TCP/IP port forward to options. Never returns if there is + * an error. + */ + +void +add_remote_forward(Options *options, u_short port, const char *host, + u_short host_port) +{ + Forward *fwd; + if (options->num_remote_forwards >= SSH_MAX_FORWARDS_PER_DIRECTION) + fatal("Too many remote forwards (max %d).", + SSH_MAX_FORWARDS_PER_DIRECTION); + fwd = &options->remote_forwards[options->num_remote_forwards++]; + fwd->port = port; + fwd->host = xstrdup(host); + fwd->host_port = host_port; +} + +static void +clear_forwardings(Options *options) +{ + int i; + + for (i = 0; i < options->num_local_forwards; i++) + xfree(options->local_forwards[i].host); + options->num_local_forwards = 0; + for (i = 0; i < options->num_remote_forwards; i++) + xfree(options->remote_forwards[i].host); + options->num_remote_forwards = 0; +} + +/* + * Returns the number of the token pointed to by cp or oBadOption. + */ + +static OpCodes +parse_token(const char *cp, const char *filename, int linenum) +{ + u_int i; + + for (i = 0; keywords[i].name; i++) + if (strcasecmp(cp, keywords[i].name) == 0) + return keywords[i].opcode; + + error("%s: line %d: Bad configuration option: %s", + filename, linenum, cp); + return oBadOption; +} + +/* + * Processes a single option line as used in the configuration files. This + * only sets those values that have not already been set. + */ + +int +process_config_line(Options *options, const char *host, + char *line, const char *filename, int linenum, + int *activep) +{ + char buf[256], *s, *string, **charptr, *endofnumber, *keyword, *arg; + int opcode, *intptr, value; + u_short fwd_port, fwd_host_port; + char sfwd_host_port[6]; + + s = line; + /* Get the keyword. (Each line is supposed to begin with a keyword). */ + keyword = strdelim(&s); + /* Ignore leading whitespace. */ + if (*keyword == '\0') + keyword = strdelim(&s); + if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#') + return 0; + + opcode = parse_token(keyword, filename, linenum); + + switch (opcode) { + case oBadOption: + /* don't panic, but count bad options */ + return -1; + /* NOTREACHED */ + case oForwardAgent: + intptr = &options->forward_agent; +parse_flag: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing yes/no argument.", filename, linenum); + value = 0; /* To avoid compiler warning... */ + if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0) + value = 1; + else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0) + value = 0; + else + fatal("%.200s line %d: Bad yes/no argument.", filename, linenum); + if (*activep && *intptr == -1) + *intptr = value; + break; + + case oForwardX11: + intptr = &options->forward_x11; + goto parse_flag; + + case oGatewayPorts: + intptr = &options->gateway_ports; + goto parse_flag; + + case oUsePrivilegedPort: + intptr = &options->use_privileged_port; + goto parse_flag; + + case oRhostsAuthentication: + intptr = &options->rhosts_authentication; + goto parse_flag; + + case oPasswordAuthentication: + intptr = &options->password_authentication; + goto parse_flag; + + case oKbdInteractiveAuthentication: + intptr = &options->kbd_interactive_authentication; + goto parse_flag; + + case oKbdInteractiveDevices: + charptr = &options->kbd_interactive_devices; + goto parse_string; + + case oPubkeyAuthentication: + intptr = &options->pubkey_authentication; + goto parse_flag; + + case oRSAAuthentication: + intptr = &options->rsa_authentication; + goto parse_flag; + + case oRhostsRSAAuthentication: + intptr = &options->rhosts_rsa_authentication; + goto parse_flag; + + case oHostbasedAuthentication: + intptr = &options->hostbased_authentication; + goto parse_flag; + + case oChallengeResponseAuthentication: + intptr = &options->challenge_response_authentication; + goto parse_flag; +#if defined(KRB4) || defined(KRB5) + case oKerberosAuthentication: + intptr = &options->kerberos_authentication; + goto parse_flag; +#endif +#ifdef GSSAPI + case oGssKeyEx: + intptr = &options->gss_keyex; + goto parse_flag; + + case oGssAuthentication: + intptr = &options->gss_authentication; + goto parse_flag; + + case oGssDelegateCreds: + intptr = &options->gss_deleg_creds; + goto parse_flag; + +#ifdef GSI + case oGssGlobusDelegateLimitedCreds: + intptr = &options->gss_globus_deleg_limited_proxy; + goto parse_flag; +#endif /* GSI */ + +#endif /* GSSAPI */ + +#if defined(AFS) || defined(KRB5) + case oKerberosTgtPassing: + intptr = &options->kerberos_tgt_passing; + goto parse_flag; +#endif +#ifdef AFS + case oAFSTokenPassing: + intptr = &options->afs_token_passing; + goto parse_flag; +#endif + case oFallBackToRsh: + intptr = &options->fallback_to_rsh; + goto parse_flag; + + case oUseRsh: + intptr = &options->use_rsh; + goto parse_flag; + + case oBatchMode: + intptr = &options->batch_mode; + goto parse_flag; + + case oCheckHostIP: + intptr = &options->check_host_ip; + goto parse_flag; + + case oStrictHostKeyChecking: + intptr = &options->strict_host_key_checking; + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing yes/no/ask argument.", + filename, linenum); + value = 0; /* To avoid compiler warning... */ + if (strcmp(arg, "yes") == 0 || strcmp(arg, "true") == 0) + value = 1; + else if (strcmp(arg, "no") == 0 || strcmp(arg, "false") == 0) + value = 0; + else if (strcmp(arg, "ask") == 0) + value = 2; + else + fatal("%.200s line %d: Bad yes/no/ask argument.", filename, linenum); + if (*activep && *intptr == -1) + *intptr = value; + break; + + case oCompression: + intptr = &options->compression; + goto parse_flag; + + case oKeepAlives: + intptr = &options->keepalives; + goto parse_flag; + + case oNoHostAuthenticationForLocalhost: + intptr = &options->no_host_authentication_for_localhost; + goto parse_flag; + + case oNumberOfPasswordPrompts: + intptr = &options->number_of_password_prompts; + goto parse_int; + + case oCompressionLevel: + intptr = &options->compression_level; + goto parse_int; + + case oIdentityFile: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (*activep) { + intptr = &options->num_identity_files; + if (*intptr >= SSH_MAX_IDENTITY_FILES) + fatal("%.200s line %d: Too many identity files specified (max %d).", + filename, linenum, SSH_MAX_IDENTITY_FILES); + charptr = &options->identity_files[*intptr]; + *charptr = xstrdup(arg); + *intptr = *intptr + 1; + } + break; + + case oXAuthLocation: + charptr=&options->xauth_location; + goto parse_string; + + case oUser: + charptr = &options->user; +parse_string: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (*activep && *charptr == NULL) + *charptr = xstrdup(arg); + break; + + case oGlobalKnownHostsFile: + charptr = &options->system_hostfile; + goto parse_string; + + case oUserKnownHostsFile: + charptr = &options->user_hostfile; + goto parse_string; + + case oGlobalKnownHostsFile2: + charptr = &options->system_hostfile2; + goto parse_string; + + case oUserKnownHostsFile2: + charptr = &options->user_hostfile2; + goto parse_string; + + case oHostName: + charptr = &options->hostname; + goto parse_string; + + case oHostKeyAlias: + charptr = &options->host_key_alias; + goto parse_string; + + case oPreferredAuthentications: + charptr = &options->preferred_authentications; + goto parse_string; + + case oBindAddress: + charptr = &options->bind_address; + goto parse_string; + + case oSmartcardDevice: + charptr = &options->smartcard_device; + goto parse_string; + + case oProxyCommand: + charptr = &options->proxy_command; + string = xstrdup(""); + while ((arg = strdelim(&s)) != NULL && *arg != '\0') { + string = xrealloc(string, strlen(string) + strlen(arg) + 2); + strcat(string, " "); + strcat(string, arg); + } + if (*activep && *charptr == NULL) + *charptr = string; + else + xfree(string); + return 0; + + case oPort: + intptr = &options->port; +parse_int: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (arg[0] < '0' || arg[0] > '9') + fatal("%.200s line %d: Bad number.", filename, linenum); + + /* Octal, decimal, or hex format? */ + value = strtol(arg, &endofnumber, 0); + if (arg == endofnumber) + fatal("%.200s line %d: Bad number.", filename, linenum); + if (*activep && *intptr == -1) + *intptr = value; + break; + + case oConnectionAttempts: + intptr = &options->connection_attempts; + goto parse_int; + + case oCipher: + intptr = &options->cipher; + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + value = cipher_number(arg); + if (value == -1) + fatal("%.200s line %d: Bad cipher '%s'.", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && *intptr == -1) + *intptr = value; + break; + + case oCiphers: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (!ciphers_valid(arg)) + fatal("%.200s line %d: Bad SSH2 cipher spec '%s'.", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && options->ciphers == NULL) + options->ciphers = xstrdup(arg); + break; + + case oMacs: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (!mac_valid(arg)) + fatal("%.200s line %d: Bad SSH2 Mac spec '%s'.", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && options->macs == NULL) + options->macs = xstrdup(arg); + break; + + case oHostKeyAlgorithms: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (!key_names_valid2(arg)) + fatal("%.200s line %d: Bad protocol 2 host key algorithms '%s'.", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && options->hostkeyalgorithms == NULL) + options->hostkeyalgorithms = xstrdup(arg); + break; + + case oProtocol: + intptr = &options->protocol; + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + value = proto_spec(arg); + if (value == SSH_PROTO_UNKNOWN) + fatal("%.200s line %d: Bad protocol spec '%s'.", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && *intptr == SSH_PROTO_UNKNOWN) + *intptr = value; + break; + + case oLogLevel: + intptr = (int *) &options->log_level; + arg = strdelim(&s); + value = log_level_number(arg); + if (value == SYSLOG_LEVEL_NOT_SET) + fatal("%.200s line %d: unsupported log level '%s'", + filename, linenum, arg ? arg : "<NONE>"); + if (*activep && (LogLevel) *intptr == SYSLOG_LEVEL_NOT_SET) + *intptr = (LogLevel) value; + break; + + case oLocalForward: + case oRemoteForward: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing port argument.", + filename, linenum); + if ((fwd_port = a2port(arg)) == 0) + fatal("%.200s line %d: Bad listen port.", + filename, linenum); + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing second argument.", + filename, linenum); + if (sscanf(arg, "%255[^:]:%5[0-9]", buf, sfwd_host_port) != 2 && + sscanf(arg, "%255[^/]/%5[0-9]", buf, sfwd_host_port) != 2) + fatal("%.200s line %d: Bad forwarding specification.", + filename, linenum); + if ((fwd_host_port = a2port(sfwd_host_port)) == 0) + fatal("%.200s line %d: Bad forwarding port.", + filename, linenum); + if (*activep) { + if (opcode == oLocalForward) + add_local_forward(options, fwd_port, buf, + fwd_host_port); + else if (opcode == oRemoteForward) + add_remote_forward(options, fwd_port, buf, + fwd_host_port); + } + break; + + case oDynamicForward: + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing port argument.", + filename, linenum); + fwd_port = a2port(arg); + if (fwd_port == 0) + fatal("%.200s line %d: Badly formatted port number.", + filename, linenum); + if (*activep) + add_local_forward(options, fwd_port, "socks4", 0); + break; + + case oClearAllForwardings: + intptr = &options->clear_forwardings; + goto parse_flag; + + case oHost: + *activep = 0; + while ((arg = strdelim(&s)) != NULL && *arg != '\0') + if (match_pattern(host, arg)) { + debug("Applying options for %.100s", arg); + *activep = 1; + break; + } + /* Avoid garbage check below, as strdelim is done. */ + return 0; + + case oEscapeChar: + intptr = &options->escape_char; + arg = strdelim(&s); + if (!arg || *arg == '\0') + fatal("%.200s line %d: Missing argument.", filename, linenum); + if (arg[0] == '^' && arg[2] == 0 && + (u_char) arg[1] >= 64 && (u_char) arg[1] < 128) + value = (u_char) arg[1] & 31; + else if (strlen(arg) == 1) + value = (u_char) arg[0]; + else if (strcmp(arg, "none") == 0) + value = SSH_ESCAPECHAR_NONE; + else { + fatal("%.200s line %d: Bad escape character.", + filename, linenum); + /* NOTREACHED */ + value = 0; /* Avoid compiler warning. */ + } + if (*activep && *intptr == -1) + *intptr = value; + break; + + case oDeprecated: + debug("%s line %d: Deprecated option \"%s\"", + filename, linenum, keyword); + return 0; + + default: + fatal("process_config_line: Unimplemented opcode %d", opcode); + } + + /* Check that there is no garbage at end of line. */ + if ((arg = strdelim(&s)) != NULL && *arg != '\0') { + fatal("%.200s line %d: garbage at end of line; \"%.200s\".", + filename, linenum, arg); + } + return 0; +} + + +/* + * Reads the config file and modifies the options accordingly. Options + * should already be initialized before this call. This never returns if + * there is an error. If the file does not exist, this returns 0. + */ + +int +read_config_file(const char *filename, const char *host, Options *options) +{ + FILE *f; + char line[1024]; + int active, linenum; + int bad_options = 0; + + /* Open the file. */ + f = fopen(filename, "r"); + if (!f) + return 0; + + debug("Reading configuration data %.200s", filename); + + /* + * Mark that we are now processing the options. This flag is turned + * on/off by Host specifications. + */ + active = 1; + linenum = 0; + while (fgets(line, sizeof(line), f)) { + /* Update line number counter. */ + linenum++; + if (process_config_line(options, host, line, filename, linenum, &active) != 0) + bad_options++; + } + fclose(f); + if (bad_options > 0) + fatal("%s: terminating, %d bad configuration options", + filename, bad_options); + return 1; +} + +/* + * Initializes options to special values that indicate that they have not yet + * been set. Read_config_file will only set options with this value. Options + * are processed in the following order: command line, user config file, + * system config file. Last, fill_default_options is called. + */ + +void +initialize_options(Options * options) +{ + memset(options, 'X', sizeof(*options)); + options->forward_agent = -1; + options->forward_x11 = -1; + options->xauth_location = NULL; + options->gateway_ports = -1; + options->use_privileged_port = -1; + options->rhosts_authentication = -1; + options->rsa_authentication = -1; + options->pubkey_authentication = -1; + options->challenge_response_authentication = -1; +#ifdef GSSAPI + options->gss_keyex = -1; + options->gss_authentication = -1; + options->gss_deleg_creds = -1; +#ifdef GSI + options->gss_globus_deleg_limited_proxy = -1; +#endif /* GSI */ +#endif /* GSSAPI */ + +#if defined(KRB4) || defined(KRB5) + options->kerberos_authentication = -1; +#endif +#if defined(AFS) || defined(KRB5) + options->kerberos_tgt_passing = -1; +#endif +#ifdef AFS + options->afs_token_passing = -1; +#endif + options->password_authentication = -1; + options->kbd_interactive_authentication = -1; + options->kbd_interactive_devices = NULL; + options->rhosts_rsa_authentication = -1; + options->hostbased_authentication = -1; + options->batch_mode = -1; + options->check_host_ip = -1; + options->strict_host_key_checking = -1; + options->compression = -1; + options->keepalives = -1; + options->compression_level = -1; + options->port = -1; + options->connection_attempts = -1; + options->number_of_password_prompts = -1; + options->cipher = -1; + options->ciphers = NULL; + options->macs = NULL; + options->hostkeyalgorithms = NULL; + options->protocol = SSH_PROTO_UNKNOWN; + options->num_identity_files = 0; + options->hostname = NULL; + options->host_key_alias = NULL; + options->proxy_command = NULL; + options->user = NULL; + options->escape_char = -1; + options->system_hostfile = NULL; + options->user_hostfile = NULL; + options->system_hostfile2 = NULL; + options->user_hostfile2 = NULL; + options->num_local_forwards = 0; + options->num_remote_forwards = 0; + options->clear_forwardings = -1; + options->log_level = SYSLOG_LEVEL_NOT_SET; + options->preferred_authentications = NULL; + options->bind_address = NULL; + options->smartcard_device = NULL; + options->no_host_authentication_for_localhost = - 1; + options->fallback_to_rsh = -1; + options->use_rsh = -1; +} + +/* + * Called after processing other sources of option data, this fills those + * options for which no value has been specified with their default values. + */ + +void +fill_default_options(Options * options) +{ + int len; + + if (options->forward_agent == -1) + options->forward_agent = 0; + if (options->forward_x11 == -1) + options->forward_x11 = 0; + if (options->xauth_location == NULL) + options->xauth_location = _PATH_XAUTH; + if (options->gateway_ports == -1) + options->gateway_ports = 0; + if (options->use_privileged_port == -1) + options->use_privileged_port = 0; + if (options->rhosts_authentication == -1) + options->rhosts_authentication = 0; + if (options->rsa_authentication == -1) + options->rsa_authentication = 1; + if (options->pubkey_authentication == -1) + options->pubkey_authentication = 1; + if (options->challenge_response_authentication == -1) + options->challenge_response_authentication = 1; +#ifdef GSSAPI + if (options->gss_keyex == -1) + options->gss_keyex = 1; + if (options->gss_authentication == -1) + options->gss_authentication = 1; + if (options->gss_deleg_creds == -1) + options->gss_deleg_creds = 0; +#ifdef GSI + if (options->gss_globus_deleg_limited_proxy == -1) + options->gss_globus_deleg_limited_proxy = 0; +#endif /* GSI */ +#endif /* GSSAPI */ +#if defined(KRB4) || defined(KRB5) + if (options->kerberos_authentication == -1) + options->kerberos_authentication = 1; +#endif +#if defined(AFS) || defined(KRB5) + if (options->kerberos_tgt_passing == -1) + options->kerberos_tgt_passing = 1; +#endif +#ifdef AFS + if (options->afs_token_passing == -1) + options->afs_token_passing = 1; +#endif + if (options->password_authentication == -1) + options->password_authentication = 1; + if (options->kbd_interactive_authentication == -1) + options->kbd_interactive_authentication = 1; + if (options->rhosts_rsa_authentication == -1) + options->rhosts_rsa_authentication = 0; + if (options->hostbased_authentication == -1) + options->hostbased_authentication = 0; + if (options->batch_mode == -1) + options->batch_mode = 0; + if (options->check_host_ip == -1) + options->check_host_ip = 1; + if (options->strict_host_key_checking == -1) + options->strict_host_key_checking = 2; /* 2 is default */ + if (options->compression == -1) + options->compression = 0; + if (options->keepalives == -1) + options->keepalives = 1; + if (options->compression_level == -1) + options->compression_level = 6; + if (options->port == -1) + options->port = 0; /* Filled in ssh_connect. */ + if (options->connection_attempts == -1) + options->connection_attempts = 1; + if (options->number_of_password_prompts == -1) + options->number_of_password_prompts = 3; + /* Selected in ssh_login(). */ + if (options->cipher == -1) + options->cipher = SSH_CIPHER_NOT_SET; + /* options->ciphers, default set in myproposals.h */ + /* options->macs, default set in myproposals.h */ + /* options->hostkeyalgorithms, default set in myproposals.h */ + if (options->protocol == SSH_PROTO_UNKNOWN) + options->protocol = SSH_PROTO_1|SSH_PROTO_2; + if (options->num_identity_files == 0) { + if (options->protocol & SSH_PROTO_1) { + len = 2 + strlen(_PATH_SSH_CLIENT_IDENTITY) + 1; + options->identity_files[options->num_identity_files] = + xmalloc(len); + snprintf(options->identity_files[options->num_identity_files++], + len, "~/%.100s", _PATH_SSH_CLIENT_IDENTITY); + } + if (options->protocol & SSH_PROTO_2) { + len = 2 + strlen(_PATH_SSH_CLIENT_ID_RSA) + 1; + options->identity_files[options->num_identity_files] = + xmalloc(len); + snprintf(options->identity_files[options->num_identity_files++], + len, "~/%.100s", _PATH_SSH_CLIENT_ID_RSA); + + len = 2 + strlen(_PATH_SSH_CLIENT_ID_DSA) + 1; + options->identity_files[options->num_identity_files] = + xmalloc(len); + snprintf(options->identity_files[options->num_identity_files++], + len, "~/%.100s", _PATH_SSH_CLIENT_ID_DSA); + } + } + if (options->escape_char == -1) + options->escape_char = '~'; + if (options->system_hostfile == NULL) + options->system_hostfile = _PATH_SSH_SYSTEM_HOSTFILE; + if (options->user_hostfile == NULL) + options->user_hostfile = _PATH_SSH_USER_HOSTFILE; + if (options->system_hostfile2 == NULL) + options->system_hostfile2 = _PATH_SSH_SYSTEM_HOSTFILE2; + if (options->user_hostfile2 == NULL) + options->user_hostfile2 = _PATH_SSH_USER_HOSTFILE2; + if (options->log_level == SYSLOG_LEVEL_NOT_SET) + options->log_level = SYSLOG_LEVEL_INFO; + if (options->clear_forwardings == 1) + clear_forwardings(options); + if (options->no_host_authentication_for_localhost == - 1) + options->no_host_authentication_for_localhost = 0; + if (options->fallback_to_rsh == - 1) + options->fallback_to_rsh = 0; + if (options->use_rsh == - 1) + options->use_rsh = 0; + /* options->proxy_command should not be set by default */ + /* options->user will be set in the main program if appropriate */ + /* options->hostname will be set in the main program if appropriate */ + /* options->host_key_alias should not be set by default */ + /* options->preferred_authentications will be set in ssh */ +} diff --git a/usr/src/cmd/ssh/libssh/common/readpass.c b/usr/src/cmd/ssh/libssh/common/readpass.c new file mode 100644 index 0000000000..8e7fd9e239 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/readpass.c @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: readpass.c,v 1.27 2002/03/26 15:58:46 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "readpass.h" +#include "pathnames.h" +#include "log.h" +#include "ssh.h" + +static char * +ssh_askpass(char *askpass, const char *msg) +{ + pid_t pid; + size_t len; + char *pass; + int p[2], status, ret; + char buf[1024]; + + if (fflush(stdout) != 0) + error("ssh_askpass: fflush: %s", strerror(errno)); + if (askpass == NULL) + fatal("internal error: askpass undefined"); + if (pipe(p) < 0) { + error("ssh_askpass: pipe: %s", strerror(errno)); + return xstrdup(""); + } + if ((pid = fork()) < 0) { + error("ssh_askpass: fork: %s", strerror(errno)); + return xstrdup(""); + } + if (pid == 0) { + seteuid(getuid()); + setuid(getuid()); + close(p[0]); + if (dup2(p[1], STDOUT_FILENO) < 0) + fatal("ssh_askpass: dup2: %s", strerror(errno)); + execlp(askpass, askpass, msg, (char *) 0); + fatal("ssh_askpass: exec(%s): %s", askpass, strerror(errno)); + } + close(p[1]); + + len = ret = 0; + do { + ret = read(p[0], buf + len, sizeof(buf) - 1 - len); + if (ret == -1 && errno == EINTR) + continue; + if (ret <= 0) + break; + len += ret; + } while (sizeof(buf) - 1 - len > 0); + buf[len] = '\0'; + + close(p[0]); + while (waitpid(pid, &status, 0) < 0) + if (errno != EINTR) + break; + + buf[strcspn(buf, "\r\n")] = '\0'; + pass = xstrdup(buf); + memset(buf, 0, sizeof(buf)); + return pass; +} + +/* + * Reads a passphrase from /dev/tty with echo turned off/on. Returns the + * passphrase (allocated with xmalloc). Exits if EOF is encountered. If + * RP_ALLOW_STDIN is set, the passphrase will be read from stdin if no + * tty is available + */ +char * +read_passphrase(const char *prompt, int flags) +{ + char *askpass = NULL, *ret, buf[1024]; + int rppflags, use_askpass = 0, ttyfd; + + rppflags = (flags & RP_ECHO) ? RPP_ECHO_ON : RPP_ECHO_OFF; + if (flags & RP_ALLOW_STDIN) { + if (!isatty(STDIN_FILENO)) + use_askpass = 1; + } else { + rppflags |= RPP_REQUIRE_TTY; + ttyfd = open(_PATH_TTY, O_RDWR); + if (ttyfd >= 0) + close(ttyfd); + else + use_askpass = 1; + } + + if (use_askpass && getenv("DISPLAY")) { + if (getenv(SSH_ASKPASS_ENV)) + askpass = getenv(SSH_ASKPASS_ENV); + else + askpass = _PATH_SSH_ASKPASS_DEFAULT; + return ssh_askpass(askpass, prompt); + } + + if (readpassphrase(prompt, buf, sizeof buf, rppflags) == NULL) { + if (flags & RP_ALLOW_EOF) + return NULL; + return xstrdup(""); + } + + ret = xstrdup(buf); + memset(buf, 'x', sizeof buf); + return ret; +} diff --git a/usr/src/cmd/ssh/libssh/common/rsa.c b/usr/src/cmd/ssh/libssh/common/rsa.c new file mode 100644 index 0000000000..f24a44a770 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/rsa.c @@ -0,0 +1,146 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + * + * + * Copyright (c) 1999 Niels Provos. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * Description of the RSA algorithm can be found e.g. from the following + * sources: + * + * Bruce Schneier: Applied Cryptography. John Wiley & Sons, 1994. + * + * Jennifer Seberry and Josed Pieprzyk: Cryptography: An Introduction to + * Computer Security. Prentice-Hall, 1989. + * + * Man Young Rhee: Cryptography and Secure Data Communications. McGraw-Hill, + * 1994. + * + * R. Rivest, A. Shamir, and L. M. Adleman: Cryptographic Communications + * System and Method. US Patent 4,405,829, 1983. + * + * Hans Riesel: Prime Numbers and Computer Methods for Factorization. + * Birkhauser, 1994. + * + * The RSA Frequently Asked Questions document by RSA Data Security, + * Inc., 1995. + * + * RSA in 3 lines of perl by Adam Back <aba@atlax.ex.ac.uk>, 1995, as + * included below: + * + * [gone - had to be deleted - what a pity] + */ + +#include "includes.h" +RCSID("$OpenBSD: rsa.c,v 1.24 2001/12/27 18:22:16 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "rsa.h" +#include "log.h" +#include "xmalloc.h" + +void +rsa_public_encrypt(BIGNUM *out, BIGNUM *in, RSA *key) +{ + u_char *inbuf, *outbuf; + int len, ilen, olen; + + if (BN_num_bits(key->e) < 2 || !BN_is_odd(key->e)) + fatal("rsa_public_encrypt() exponent too small or not odd"); + + olen = BN_num_bytes(key->n); + outbuf = xmalloc(olen); + + ilen = BN_num_bytes(in); + inbuf = xmalloc(ilen); + BN_bn2bin(in, inbuf); + + if ((len = RSA_public_encrypt(ilen, inbuf, outbuf, key, + RSA_PKCS1_PADDING)) <= 0) + fatal("rsa_public_encrypt() failed"); + + BN_bin2bn(outbuf, len, out); + + memset(outbuf, 0, olen); + memset(inbuf, 0, ilen); + xfree(outbuf); + xfree(inbuf); +} + +int +rsa_private_decrypt(BIGNUM *out, BIGNUM *in, RSA *key) +{ + u_char *inbuf, *outbuf; + int len, ilen, olen; + + olen = BN_num_bytes(key->n); + outbuf = xmalloc(olen); + + ilen = BN_num_bytes(in); + inbuf = xmalloc(ilen); + BN_bn2bin(in, inbuf); + + if ((len = RSA_private_decrypt(ilen, inbuf, outbuf, key, + RSA_PKCS1_PADDING)) <= 0) { + error("rsa_private_decrypt() failed"); + } else { + BN_bin2bn(outbuf, len, out); + } + memset(outbuf, 0, olen); + memset(inbuf, 0, ilen); + xfree(outbuf); + xfree(inbuf); + return len; +} + +/* calculate p-1 and q-1 */ +void +rsa_generate_additional_parameters(RSA *rsa) +{ + BIGNUM *aux; + BN_CTX *ctx; + + if ((aux = BN_new()) == NULL) + fatal("rsa_generate_additional_parameters: BN_new failed"); + if ((ctx = BN_CTX_new()) == NULL) + fatal("rsa_generate_additional_parameters: BN_CTX_new failed"); + + BN_sub(aux, rsa->q, BN_value_one()); + BN_mod(rsa->dmq1, rsa->d, aux, ctx); + + BN_sub(aux, rsa->p, BN_value_one()); + BN_mod(rsa->dmp1, rsa->d, aux, ctx); + + BN_clear_free(aux); + BN_CTX_free(ctx); +} + diff --git a/usr/src/cmd/ssh/libssh/common/scard-opensc.c b/usr/src/cmd/ssh/libssh/common/scard-opensc.c new file mode 100644 index 0000000000..2aa04e126f --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/scard-opensc.c @@ -0,0 +1,464 @@ +/* + * Copyright (c) 2002 Juha Yrjölä. All rights reserved. + * Copyright (c) 2001 Markus Friedl. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +#if defined(SMARTCARD) && defined(USE_OPENSC) + +#include <openssl/evp.h> +#include <openssl/x509.h> + +#include <opensc/opensc.h> +#include <opensc/pkcs15.h> + +#include "key.h" +#include "log.h" +#include "xmalloc.h" +#include "readpass.h" +#include "scard.h" + +#if OPENSSL_VERSION_NUMBER < 0x00907000L && defined(CRYPTO_LOCK_ENGINE) +#define USE_ENGINE +#define RSA_get_default_method RSA_get_default_openssl_method +#else +#endif + +#ifdef USE_ENGINE +#include <openssl/engine.h> +#define sc_get_rsa sc_get_engine +#else +#define sc_get_rsa sc_get_rsa_method +#endif + +static int sc_reader_id; +static sc_context_t *ctx = NULL; +static sc_card_t *card = NULL; +static sc_pkcs15_card_t *p15card = NULL; + +static char *sc_pin = NULL; + +struct sc_priv_data +{ + struct sc_pkcs15_id cert_id; + int ref_count; +}; + +void +sc_close(void) +{ + if (p15card) { + sc_pkcs15_unbind(p15card); + p15card = NULL; + } + if (card) { + sc_disconnect_card(card, 0); + card = NULL; + } + if (ctx) { + sc_release_context(ctx); + ctx = NULL; + } +} + +static int +sc_init(void) +{ + int r; + + r = sc_establish_context(&ctx, "openssh"); + if (r) + goto err; + r = sc_connect_card(ctx->reader[sc_reader_id], 0, &card); + if (r) + goto err; + r = sc_pkcs15_bind(card, &p15card); + if (r) + goto err; + return 0; +err: + sc_close(); + return r; +} + +/* private key operations */ + +static int +sc_prkey_op_init(RSA *rsa, struct sc_pkcs15_object **key_obj_out) +{ + int r; + struct sc_priv_data *priv; + struct sc_pkcs15_object *key_obj; + struct sc_pkcs15_prkey_info *key; + struct sc_pkcs15_object *pin_obj; + struct sc_pkcs15_pin_info *pin; + + priv = (struct sc_priv_data *) RSA_get_app_data(rsa); + if (priv == NULL) + return -1; + if (p15card == NULL) { + sc_close(); + r = sc_init(); + if (r) { + error("SmartCard init failed: %s", sc_strerror(r)); + goto err; + } + } + r = sc_pkcs15_find_prkey_by_id(p15card, &priv->cert_id, &key_obj); + if (r) { + error("Unable to find private key from SmartCard: %s", + sc_strerror(r)); + goto err; + } + key = key_obj->data; + r = sc_pkcs15_find_pin_by_auth_id(p15card, &key_obj->auth_id, + &pin_obj); + if (r) { + error("Unable to find PIN object from SmartCard: %s", + sc_strerror(r)); + goto err; + } + pin = pin_obj->data; + r = sc_lock(card); + if (r) { + error("Unable to lock smartcard: %s", sc_strerror(r)); + goto err; + } + if (sc_pin != NULL) { + r = sc_pkcs15_verify_pin(p15card, pin, sc_pin, + strlen(sc_pin)); + if (r) { + sc_unlock(card); + error("PIN code verification failed: %s", + sc_strerror(r)); + goto err; + } + } + *key_obj_out = key_obj; + return 0; +err: + sc_close(); + return -1; +} + +static int +sc_private_decrypt(int flen, u_char *from, u_char *to, RSA *rsa, + int padding) +{ + struct sc_pkcs15_object *key_obj; + int r; + + if (padding != RSA_PKCS1_PADDING) + return -1; + r = sc_prkey_op_init(rsa, &key_obj); + if (r) + return -1; + r = sc_pkcs15_decipher(p15card, key_obj, 0, from, flen, to, flen); + sc_unlock(card); + if (r < 0) { + error("sc_pkcs15_decipher() failed: %s", sc_strerror(r)); + goto err; + } + return r; +err: + sc_close(); + return -1; +} + +static int +sc_sign(int type, u_char *m, unsigned int m_len, + unsigned char *sigret, unsigned int *siglen, RSA *rsa) +{ + struct sc_pkcs15_object *key_obj; + int r; + unsigned long flags = 0; + + r = sc_prkey_op_init(rsa, &key_obj); + if (r) + return -1; + /* FIXME: length of sigret correct? */ + /* FIXME: check 'type' and modify flags accordingly */ + flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA1; + r = sc_pkcs15_compute_signature(p15card, key_obj, flags, + m, m_len, sigret, RSA_size(rsa)); + sc_unlock(card); + if (r < 0) { + error("sc_pkcs15_compute_signature() failed: %s", + sc_strerror(r)); + goto err; + } + *siglen = r; + return 1; +err: + sc_close(); + return 0; +} + +static int +sc_private_encrypt(int flen, u_char *from, u_char *to, RSA *rsa, + int padding) +{ + error("Private key encryption not supported"); + return -1; +} + +/* called on free */ + +static int (*orig_finish)(RSA *rsa) = NULL; + +static int +sc_finish(RSA *rsa) +{ + struct sc_priv_data *priv; + + priv = RSA_get_app_data(rsa); + priv->ref_count--; + if (priv->ref_count == 0) { + free(priv); + sc_close(); + } + if (orig_finish) + orig_finish(rsa); + return 1; +} + +/* engine for overloading private key operations */ + +static RSA_METHOD * +sc_get_rsa_method(void) +{ + static RSA_METHOD smart_rsa; + const RSA_METHOD *def = RSA_get_default_method(); + + /* use the OpenSSL version */ + memcpy(&smart_rsa, def, sizeof(smart_rsa)); + + smart_rsa.name = "opensc"; + + /* overload */ + smart_rsa.rsa_priv_enc = sc_private_encrypt; + smart_rsa.rsa_priv_dec = sc_private_decrypt; + smart_rsa.rsa_sign = sc_sign; + + /* save original */ + orig_finish = def->finish; + smart_rsa.finish = sc_finish; + + return &smart_rsa; +} + +#ifdef USE_ENGINE +static ENGINE * +sc_get_engine(void) +{ + static ENGINE *smart_engine = NULL; + + if ((smart_engine = ENGINE_new()) == NULL) + fatal("ENGINE_new failed"); + + ENGINE_set_id(smart_engine, "opensc"); + ENGINE_set_name(smart_engine, "OpenSC"); + + ENGINE_set_RSA(smart_engine, sc_get_rsa_method()); + ENGINE_set_DSA(smart_engine, DSA_get_default_openssl_method()); + ENGINE_set_DH(smart_engine, DH_get_default_openssl_method()); + ENGINE_set_RAND(smart_engine, RAND_SSLeay()); + ENGINE_set_BN_mod_exp(smart_engine, BN_mod_exp); + + return smart_engine; +} +#endif + +static void +convert_rsa_to_rsa1(Key * in, Key * out) +{ + struct sc_priv_data *priv; + + out->rsa->flags = in->rsa->flags; + out->flags = in->flags; + RSA_set_method(out->rsa, RSA_get_method(in->rsa)); + BN_copy(out->rsa->n, in->rsa->n); + BN_copy(out->rsa->e, in->rsa->e); + priv = RSA_get_app_data(in->rsa); + priv->ref_count++; + RSA_set_app_data(out->rsa, priv); + return; +} + +static int +sc_read_pubkey(Key * k, const struct sc_pkcs15_object *cert_obj) +{ + int r; + sc_pkcs15_cert_t *cert = NULL; + struct sc_priv_data *priv = NULL; + sc_pkcs15_cert_info_t *cinfo = cert_obj->data; + + X509 *x509 = NULL; + EVP_PKEY *pubkey = NULL; + u8 *p; + char *tmp; + + debug("sc_read_pubkey() with cert id %02X", cinfo->id.value[0]); + r = sc_pkcs15_read_certificate(p15card, cinfo, &cert); + if (r) { + log("Certificate read failed: %s", sc_strerror(r)); + goto err; + } + x509 = X509_new(); + if (x509 == NULL) { + r = -1; + goto err; + } + p = cert->data; + if (!d2i_X509(&x509, &p, cert->data_len)) { + log("Unable to parse X.509 certificate"); + r = -1; + goto err; + } + sc_pkcs15_free_certificate(cert); + cert = NULL; + pubkey = X509_get_pubkey(x509); + X509_free(x509); + x509 = NULL; + if (pubkey->type != EVP_PKEY_RSA) { + log("Public key is of unknown type"); + r = -1; + goto err; + } + k->rsa = EVP_PKEY_get1_RSA(pubkey); + EVP_PKEY_free(pubkey); + + k->rsa->flags |= RSA_FLAG_SIGN_VER; + RSA_set_method(k->rsa, sc_get_rsa_method()); + priv = xmalloc(sizeof(struct sc_priv_data)); + priv->cert_id = cinfo->id; + priv->ref_count = 1; + RSA_set_app_data(k->rsa, priv); + + k->flags = KEY_FLAG_EXT; + tmp = key_fingerprint(k, SSH_FP_MD5, SSH_FP_HEX); + debug("fingerprint %d %s", key_size(k), tmp); + xfree(tmp); + + return 0; +err: + if (cert) + sc_pkcs15_free_certificate(cert); + if (pubkey) + EVP_PKEY_free(pubkey); + if (x509) + X509_free(x509); + return r; +} + +Key ** +sc_get_keys(const char *id, const char *pin) +{ + Key *k, **keys; + int i, r, real_count = 0, key_count; + sc_pkcs15_id_t cert_id; + sc_pkcs15_object_t *certs[32]; + char *buf = xstrdup(id), *p; + + debug("sc_get_keys called: id = %s", id); + + if (sc_pin != NULL) + xfree(sc_pin); + sc_pin = (pin == NULL) ? NULL : xstrdup(pin); + + cert_id.len = 0; + if ((p = strchr(buf, ':')) != NULL) { + *p = 0; + p++; + sc_pkcs15_hex_string_to_id(p, &cert_id); + } + r = sscanf(buf, "%d", &sc_reader_id); + xfree(buf); + if (r != 1) + goto err; + if (p15card == NULL) { + sc_close(); + r = sc_init(); + if (r) { + error("Smartcard init failed: %s", sc_strerror(r)); + goto err; + } + } + if (cert_id.len) { + r = sc_pkcs15_find_cert_by_id(p15card, &cert_id, &certs[0]); + if (r < 0) + goto err; + key_count = 1; + } else { + r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_CERT_X509, + certs, 32); + if (r == 0) { + log("No certificates found on smartcard"); + r = -1; + goto err; + } else if (r < 0) { + error("Certificate enumeration failed: %s", + sc_strerror(r)); + goto err; + } + key_count = r; + } + /* FIXME: only keep entries with a corresponding private key */ + keys = xmalloc(sizeof(Key *) * (key_count*2+1)); + for (i = 0; i < key_count; i++) { + k = key_new(KEY_RSA); + if (k == NULL) + break; + r = sc_read_pubkey(k, certs[i]); + if (r) { + error("sc_read_pubkey failed: %s", sc_strerror(r)); + key_free(k); + continue; + } + keys[real_count] = k; + real_count++; + k = key_new(KEY_RSA1); + if (k == NULL) + break; + convert_rsa_to_rsa1(keys[real_count-1], k); + keys[real_count] = k; + real_count++; + } + keys[real_count] = NULL; + + return keys; +err: + sc_close(); + return NULL; +} + +int +sc_put_key(Key *prv, const char *id) +{ + error("key uploading not yet supported"); + return -1; +} + +#endif /* SMARTCARD */ + +#pragma ident "%Z%%M% %I% %E% SMI" diff --git a/usr/src/cmd/ssh/libssh/common/scard.c b/usr/src/cmd/ssh/libssh/common/scard.c new file mode 100644 index 0000000000..fbce861733 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/scard.c @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +#if defined(SMARTCARD) && defined(USE_SECTOK) +RCSID("$OpenBSD: scard.c,v 1.26 2002/06/23 03:30:17 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/evp.h> +#include <sectok.h> + +#include "key.h" +#include "log.h" +#include "xmalloc.h" +#include "readpass.h" +#include "scard.h" + +#if OPENSSL_VERSION_NUMBER < 0x00907000L +#define USE_ENGINE +#define RSA_get_default_method RSA_get_default_openssl_method +#else +#endif + +#ifdef USE_ENGINE +#include <openssl/engine.h> +#define sc_get_rsa sc_get_engine +#else +#define sc_get_rsa sc_get_rsa_method +#endif + +#define CLA_SSH 0x05 +#define INS_DECRYPT 0x10 +#define INS_GET_KEYLENGTH 0x20 +#define INS_GET_PUBKEY 0x30 +#define INS_GET_RESPONSE 0xc0 + +#define MAX_BUF_SIZE 256 + +u_char DEFAUT0[] = {0xad, 0x9f, 0x61, 0xfe, 0xfa, 0x20, 0xce, 0x63}; + +static int sc_fd = -1; +static char *sc_reader_id = NULL; +static char *sc_pin = NULL; +static int cla = 0x00; /* class */ + +static void sc_mk_digest(const char *pin, u_char *digest); +static int get_AUT0(u_char *aut0); +static int try_AUT0(void); + +/* interface to libsectok */ + +static int +sc_open(void) +{ + int sw; + + if (sc_fd >= 0) + return sc_fd; + + sc_fd = sectok_friendly_open(sc_reader_id, STONOWAIT, &sw); + if (sc_fd < 0) { + error("sectok_open failed: %s", sectok_get_sw(sw)); + return SCARD_ERROR_FAIL; + } + if (! sectok_cardpresent(sc_fd)) { + debug("smartcard in reader %s not present, skipping", + sc_reader_id); + sc_close(); + return SCARD_ERROR_NOCARD; + } + if (sectok_reset(sc_fd, 0, NULL, &sw) <= 0) { + error("sectok_reset failed: %s", sectok_get_sw(sw)); + sc_fd = -1; + return SCARD_ERROR_FAIL; + } + if ((cla = cyberflex_inq_class(sc_fd)) < 0) + cla = 0; + + debug("sc_open ok %d", sc_fd); + return sc_fd; +} + +static int +sc_enable_applet(void) +{ + static u_char aid[] = {0xfc, 0x53, 0x73, 0x68, 0x2e, 0x62, 0x69, 0x6e}; + int sw = 0; + + /* select applet id */ + sectok_apdu(sc_fd, cla, 0xa4, 0x04, 0, sizeof aid, aid, 0, NULL, &sw); + if (!sectok_swOK(sw)) { + error("sectok_apdu failed: %s", sectok_get_sw(sw)); + sc_close(); + return -1; + } + return 0; +} + +static int +sc_init(void) +{ + int status; + + status = sc_open(); + if (status == SCARD_ERROR_NOCARD) { + return SCARD_ERROR_NOCARD; + } + if (status < 0 ) { + error("sc_open failed"); + return status; + } + if (sc_enable_applet() < 0) { + error("sc_enable_applet failed"); + return SCARD_ERROR_APPLET; + } + return 0; +} + +static int +sc_read_pubkey(Key * k) +{ + u_char buf[2], *n; + char *p; + int len, sw, status = -1; + + len = sw = 0; + n = NULL; + + if (sc_fd < 0) { + if (sc_init() < 0) + goto err; + } + + /* get key size */ + sectok_apdu(sc_fd, CLA_SSH, INS_GET_KEYLENGTH, 0, 0, 0, NULL, + sizeof(buf), buf, &sw); + if (!sectok_swOK(sw)) { + error("could not obtain key length: %s", sectok_get_sw(sw)); + goto err; + } + len = (buf[0] << 8) | buf[1]; + len /= 8; + debug("INS_GET_KEYLENGTH: len %d sw %s", len, sectok_get_sw(sw)); + + n = xmalloc(len); + /* get n */ + sectok_apdu(sc_fd, CLA_SSH, INS_GET_PUBKEY, 0, 0, 0, NULL, len, n, &sw); + + if (sw == 0x6982) { + if (try_AUT0() < 0) + goto err; + sectok_apdu(sc_fd, CLA_SSH, INS_GET_PUBKEY, 0, 0, 0, NULL, len, n, &sw); + } + if (!sectok_swOK(sw)) { + error("could not obtain public key: %s", sectok_get_sw(sw)); + goto err; + } + + debug("INS_GET_KEYLENGTH: sw %s", sectok_get_sw(sw)); + + if (BN_bin2bn(n, len, k->rsa->n) == NULL) { + error("c_read_pubkey: BN_bin2bn failed"); + goto err; + } + + /* currently the java applet just stores 'n' */ + if (!BN_set_word(k->rsa->e, 35)) { + error("c_read_pubkey: BN_set_word(e, 35) failed"); + goto err; + } + + status = 0; + p = key_fingerprint(k, SSH_FP_MD5, SSH_FP_HEX); + debug("fingerprint %u %s", key_size(k), p); + xfree(p); + +err: + if (n != NULL) + xfree(n); + sc_close(); + return status; +} + +/* private key operations */ + +static int +sc_private_decrypt(int flen, u_char *from, u_char *to, RSA *rsa, + int padding) +{ + u_char *padded = NULL; + int sw, len, olen, status = -1; + + debug("sc_private_decrypt called"); + + olen = len = sw = 0; + if (sc_fd < 0) { + status = sc_init(); + if (status < 0 ) + goto err; + } + if (padding != RSA_PKCS1_PADDING) + goto err; + + len = BN_num_bytes(rsa->n); + padded = xmalloc(len); + + sectok_apdu(sc_fd, CLA_SSH, INS_DECRYPT, 0, 0, len, from, len, padded, &sw); + + if (sw == 0x6982) { + if (try_AUT0() < 0) + goto err; + sectok_apdu(sc_fd, CLA_SSH, INS_DECRYPT, 0, 0, len, from, len, padded, &sw); + } + if (!sectok_swOK(sw)) { + error("sc_private_decrypt: INS_DECRYPT failed: %s", + sectok_get_sw(sw)); + goto err; + } + olen = RSA_padding_check_PKCS1_type_2(to, len, padded + 1, len - 1, + len); +err: + if (padded) + xfree(padded); + sc_close(); + return (olen >= 0 ? olen : status); +} + +static int +sc_private_encrypt(int flen, u_char *from, u_char *to, RSA *rsa, + int padding) +{ + u_char *padded = NULL; + int sw, len, status = -1; + + len = sw = 0; + if (sc_fd < 0) { + status = sc_init(); + if (status < 0 ) + goto err; + } + if (padding != RSA_PKCS1_PADDING) + goto err; + + debug("sc_private_encrypt called"); + len = BN_num_bytes(rsa->n); + padded = xmalloc(len); + + if (RSA_padding_add_PKCS1_type_1(padded, len, (u_char *)from, flen) <= 0) { + error("RSA_padding_add_PKCS1_type_1 failed"); + goto err; + } + sectok_apdu(sc_fd, CLA_SSH, INS_DECRYPT, 0, 0, len, padded, len, to, &sw); + if (sw == 0x6982) { + if (try_AUT0() < 0) + goto err; + sectok_apdu(sc_fd, CLA_SSH, INS_DECRYPT, 0, 0, len, padded, len, to, &sw); + } + if (!sectok_swOK(sw)) { + error("sc_private_encrypt: INS_DECRYPT failed: %s", + sectok_get_sw(sw)); + goto err; + } +err: + if (padded) + xfree(padded); + sc_close(); + return (len >= 0 ? len : status); +} + +/* called on free */ + +static int (*orig_finish)(RSA *rsa) = NULL; + +static int +sc_finish(RSA *rsa) +{ + if (orig_finish) + orig_finish(rsa); + sc_close(); + return 1; +} + +/* engine for overloading private key operations */ + +static RSA_METHOD * +sc_get_rsa_method(void) +{ + static RSA_METHOD smart_rsa; + const RSA_METHOD *def = RSA_get_default_method(); + + /* use the OpenSSL version */ + memcpy(&smart_rsa, def, sizeof(smart_rsa)); + + smart_rsa.name = "sectok"; + + /* overload */ + smart_rsa.rsa_priv_enc = sc_private_encrypt; + smart_rsa.rsa_priv_dec = sc_private_decrypt; + + /* save original */ + orig_finish = def->finish; + smart_rsa.finish = sc_finish; + + return &smart_rsa; +} + +#ifdef USE_ENGINE +static ENGINE * +sc_get_engine(void) +{ + static ENGINE *smart_engine = NULL; + + if ((smart_engine = ENGINE_new()) == NULL) + fatal("ENGINE_new failed"); + + ENGINE_set_id(smart_engine, "sectok"); + ENGINE_set_name(smart_engine, "libsectok"); + + ENGINE_set_RSA(smart_engine, sc_get_rsa_method()); + ENGINE_set_DSA(smart_engine, DSA_get_default_openssl_method()); + ENGINE_set_DH(smart_engine, DH_get_default_openssl_method()); + ENGINE_set_RAND(smart_engine, RAND_SSLeay()); + ENGINE_set_BN_mod_exp(smart_engine, BN_mod_exp); + + return smart_engine; +} +#endif + +void +sc_close(void) +{ + if (sc_fd >= 0) { + sectok_close(sc_fd); + sc_fd = -1; + } +} + +Key ** +sc_get_keys(const char *id, const char *pin) +{ + Key *k, *n, **keys; + int status, nkeys = 2; + + if (sc_reader_id != NULL) + xfree(sc_reader_id); + sc_reader_id = xstrdup(id); + + if (sc_pin != NULL) + xfree(sc_pin); + sc_pin = (pin == NULL) ? NULL : xstrdup(pin); + + k = key_new(KEY_RSA); + if (k == NULL) { + return NULL; + } + status = sc_read_pubkey(k); + if (status == SCARD_ERROR_NOCARD) { + key_free(k); + return NULL; + } + if (status < 0 ) { + error("sc_read_pubkey failed"); + key_free(k); + return NULL; + } + keys = xmalloc((nkeys+1) * sizeof(Key *)); + + n = key_new(KEY_RSA1); + BN_copy(n->rsa->n, k->rsa->n); + BN_copy(n->rsa->e, k->rsa->e); + RSA_set_method(n->rsa, sc_get_rsa()); + n->flags |= KEY_FLAG_EXT; + keys[0] = n; + + n = key_new(KEY_RSA); + BN_copy(n->rsa->n, k->rsa->n); + BN_copy(n->rsa->e, k->rsa->e); + RSA_set_method(n->rsa, sc_get_rsa()); + n->flags |= KEY_FLAG_EXT; + keys[1] = n; + + keys[2] = NULL; + + key_free(k); + return keys; +} + +#define NUM_RSA_KEY_ELEMENTS 5+1 +#define COPY_RSA_KEY(x, i) \ + do { \ + len = BN_num_bytes(prv->rsa->x); \ + elements[i] = xmalloc(len); \ + debug("#bytes %d", len); \ + if (BN_bn2bin(prv->rsa->x, elements[i]) < 0) \ + goto done; \ + } while (0) + +static void +sc_mk_digest(const char *pin, u_char *digest) +{ + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, pin, strlen(pin)); + EVP_DigestFinal(&md, digest, NULL); +} + +static int +get_AUT0(u_char *aut0) +{ + char *pass; + + pass = read_passphrase("Enter passphrase for smartcard: ", RP_ALLOW_STDIN); + if (pass == NULL) + return -1; + if (!strcmp(pass, "-")) { + memcpy(aut0, DEFAUT0, sizeof DEFAUT0); + return 0; + } + sc_mk_digest(pass, aut0); + memset(pass, 0, strlen(pass)); + xfree(pass); + return 0; +} + +static int +try_AUT0(void) +{ + u_char aut0[EVP_MAX_MD_SIZE]; + + /* permission denied; try PIN if provided */ + if (sc_pin && strlen(sc_pin) > 0) { + sc_mk_digest(sc_pin, aut0); + if (cyberflex_verify_AUT0(sc_fd, cla, aut0, 8) < 0) { + error("smartcard passphrase incorrect"); + return (-1); + } + } else { + /* try default AUT0 key */ + if (cyberflex_verify_AUT0(sc_fd, cla, DEFAUT0, 8) < 0) { + /* default AUT0 key failed; prompt for passphrase */ + if (get_AUT0(aut0) < 0 || + cyberflex_verify_AUT0(sc_fd, cla, aut0, 8) < 0) { + error("smartcard passphrase incorrect"); + return (-1); + } + } + } + return (0); +} + +int +sc_put_key(Key *prv, const char *id) +{ + u_char *elements[NUM_RSA_KEY_ELEMENTS]; + u_char key_fid[2]; + u_char AUT0[EVP_MAX_MD_SIZE]; + int len, status = -1, i, fd = -1, ret; + int sw = 0, cla = 0x00; + + for (i = 0; i < NUM_RSA_KEY_ELEMENTS; i++) + elements[i] = NULL; + + COPY_RSA_KEY(q, 0); + COPY_RSA_KEY(p, 1); + COPY_RSA_KEY(iqmp, 2); + COPY_RSA_KEY(dmq1, 3); + COPY_RSA_KEY(dmp1, 4); + COPY_RSA_KEY(n, 5); + len = BN_num_bytes(prv->rsa->n); + fd = sectok_friendly_open(id, STONOWAIT, &sw); + if (fd < 0) { + error("sectok_open failed: %s", sectok_get_sw(sw)); + goto done; + } + if (! sectok_cardpresent(fd)) { + error("smartcard in reader %s not present", id); + goto done; + } + ret = sectok_reset(fd, 0, NULL, &sw); + if (ret <= 0) { + error("sectok_reset failed: %s", sectok_get_sw(sw)); + goto done; + } + if ((cla = cyberflex_inq_class(fd)) < 0) { + error("cyberflex_inq_class failed"); + goto done; + } + memcpy(AUT0, DEFAUT0, sizeof(DEFAUT0)); + if (cyberflex_verify_AUT0(fd, cla, AUT0, sizeof(DEFAUT0)) < 0) { + if (get_AUT0(AUT0) < 0 || + cyberflex_verify_AUT0(fd, cla, AUT0, sizeof(DEFAUT0)) < 0) { + memset(AUT0, 0, sizeof(DEFAUT0)); + error("smartcard passphrase incorrect"); + goto done; + } + } + memset(AUT0, 0, sizeof(DEFAUT0)); + key_fid[0] = 0x00; + key_fid[1] = 0x12; + if (cyberflex_load_rsa_priv(fd, cla, key_fid, 5, 8*len, elements, + &sw) < 0) { + error("cyberflex_load_rsa_priv failed: %s", sectok_get_sw(sw)); + goto done; + } + if (!sectok_swOK(sw)) + goto done; + log("cyberflex_load_rsa_priv done"); + key_fid[0] = 0x73; + key_fid[1] = 0x68; + if (cyberflex_load_rsa_pub(fd, cla, key_fid, len, elements[5], + &sw) < 0) { + error("cyberflex_load_rsa_pub failed: %s", sectok_get_sw(sw)); + goto done; + } + if (!sectok_swOK(sw)) + goto done; + log("cyberflex_load_rsa_pub done"); + status = 0; + +done: + memset(elements[0], '\0', BN_num_bytes(prv->rsa->q)); + memset(elements[1], '\0', BN_num_bytes(prv->rsa->p)); + memset(elements[2], '\0', BN_num_bytes(prv->rsa->iqmp)); + memset(elements[3], '\0', BN_num_bytes(prv->rsa->dmq1)); + memset(elements[4], '\0', BN_num_bytes(prv->rsa->dmp1)); + memset(elements[5], '\0', BN_num_bytes(prv->rsa->n)); + + for (i = 0; i < NUM_RSA_KEY_ELEMENTS; i++) + if (elements[i]) + xfree(elements[i]); + if (fd != -1) + sectok_close(fd); + return (status); +} +#endif /* SMARTCARD && USE_SECTOK */ diff --git a/usr/src/cmd/ssh/libssh/common/sftp-common.c b/usr/src/cmd/ssh/libssh/common/sftp-common.c new file mode 100644 index 0000000000..7cbe72c44c --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/sftp-common.c @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * Copyright (c) 2001 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: sftp-common.c,v 1.7 2002/09/11 22:41:50 djm Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "buffer.h" +#include "bufaux.h" +#include "log.h" +#include "xmalloc.h" + +#include "sftp.h" +#include "sftp-common.h" + +/* Clear contents of attributes structure */ +void +attrib_clear(Attrib *a) +{ + a->flags = 0; + a->size = 0; + a->uid = 0; + a->gid = 0; + a->perm = 0; + a->atime = 0; + a->mtime = 0; +} + +/* Convert from struct stat to filexfer attribs */ +void +stat_to_attrib(struct stat *st, Attrib *a) +{ + attrib_clear(a); + a->flags = 0; + a->flags |= SSH2_FILEXFER_ATTR_SIZE; + a->size = st->st_size; + a->flags |= SSH2_FILEXFER_ATTR_UIDGID; + a->uid = st->st_uid; + a->gid = st->st_gid; + a->flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; + a->perm = st->st_mode; + a->flags |= SSH2_FILEXFER_ATTR_ACMODTIME; + a->atime = st->st_atime; + a->mtime = st->st_mtime; +} + +/* Convert from filexfer attribs to struct stat */ +void +attrib_to_stat(Attrib *a, struct stat *st) +{ + memset(st, 0, sizeof(*st)); + + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) + st->st_size = a->size; + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + st->st_uid = a->uid; + st->st_gid = a->gid; + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + st->st_mode = a->perm; + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + st->st_atime = a->atime; + st->st_mtime = a->mtime; + } +} + +/* Decode attributes in buffer */ +Attrib * +decode_attrib(Buffer *b) +{ + static Attrib a; + + attrib_clear(&a); + a.flags = buffer_get_int(b); + if (a.flags & SSH2_FILEXFER_ATTR_SIZE) + a.size = buffer_get_int64(b); + if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) { + a.uid = buffer_get_int(b); + a.gid = buffer_get_int(b); + } + if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + a.perm = buffer_get_int(b); + if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + a.atime = buffer_get_int(b); + a.mtime = buffer_get_int(b); + } + /* vendor-specific extensions */ + if (a.flags & SSH2_FILEXFER_ATTR_EXTENDED) { + char *type, *data; + int i, count; + + count = buffer_get_int(b); + for (i = 0; i < count; i++) { + type = buffer_get_string(b, NULL); + data = buffer_get_string(b, NULL); + debug3("Got file attribute \"%s\"", type); + xfree(type); + xfree(data); + } + } + return &a; +} + +/* Encode attributes to buffer */ +void +encode_attrib(Buffer *b, Attrib *a) +{ + buffer_put_int(b, a->flags); + if (a->flags & SSH2_FILEXFER_ATTR_SIZE) + buffer_put_int64(b, a->size); + if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { + buffer_put_int(b, a->uid); + buffer_put_int(b, a->gid); + } + if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) + buffer_put_int(b, a->perm); + if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { + buffer_put_int(b, a->atime); + buffer_put_int(b, a->mtime); + } +} + +/* Convert from SSH2_FX_ status to text error message */ +const char * +fx2txt(int status) +{ + switch (status) { + case SSH2_FX_OK: + return("No error"); + case SSH2_FX_EOF: + return("End of file"); + case SSH2_FX_NO_SUCH_FILE: + return("No such file or directory"); + case SSH2_FX_PERMISSION_DENIED: + return("Permission denied"); + case SSH2_FX_FAILURE: + return("Failure"); + case SSH2_FX_BAD_MESSAGE: + return("Bad message"); + case SSH2_FX_NO_CONNECTION: + return("No connection"); + case SSH2_FX_CONNECTION_LOST: + return("Connection lost"); + case SSH2_FX_OP_UNSUPPORTED: + return("Operation unsupported"); + default: + return("Unknown status"); + } + /* NOTREACHED */ +} + +/* + * drwxr-xr-x 5 markus markus 1024 Jan 13 18:39 .ssh + */ +char * +ls_file(char *name, struct stat *st, int remote) +{ + int ulen, glen, sz = 0; + struct passwd *pw; + struct group *gr; + struct tm *ltime = localtime(&st->st_mtime); + char *user, *group; + char buf[1024], mode[11+1], tbuf[12+1], ubuf[11+1], gbuf[11+1]; + + strmode(st->st_mode, mode); + if (!remote && (pw = getpwuid(st->st_uid)) != NULL) { + user = pw->pw_name; + } else { + snprintf(ubuf, sizeof ubuf, "%u", (u_int)st->st_uid); + user = ubuf; + } + if (!remote && (gr = getgrgid(st->st_gid)) != NULL) { + group = gr->gr_name; + } else { + snprintf(gbuf, sizeof gbuf, "%u", (u_int)st->st_gid); + group = gbuf; + } + if (ltime != NULL) { + if (time(NULL) - st->st_mtime < (365*24*60*60)/2) + sz = strftime(tbuf, sizeof tbuf, "%b %e %H:%M", ltime); + else + sz = strftime(tbuf, sizeof tbuf, "%b %e %Y", ltime); + } + if (sz == 0) + tbuf[0] = '\0'; + ulen = MAX(strlen(user), 8); + glen = MAX(strlen(group), 8); + snprintf(buf, sizeof buf, "%s %3d %-*s %-*s %8llu %s %s", mode, + st->st_nlink, ulen, user, glen, group, + (u_int64_t)st->st_size, tbuf, name); + return xstrdup(buf); +} diff --git a/usr/src/cmd/ssh/libssh/common/ssh-dss.c b/usr/src/cmd/ssh/libssh/common/ssh-dss.c new file mode 100644 index 0000000000..f73a91672f --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/ssh-dss.c @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: ssh-dss.c,v 1.17 2002/07/04 10:41:47 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/bn.h> +#include <openssl/evp.h> + +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "compat.h" +#include "log.h" +#include "key.h" +#include "ssh-dss.h" + +#define INTBLOB_LEN 20 +#define SIGBLOB_LEN (2*INTBLOB_LEN) + +int +ssh_dss_sign(Key *key, u_char **sigp, u_int *lenp, + u_char *data, u_int datalen) +{ + DSA_SIG *sig; + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + u_char digest[EVP_MAX_MD_SIZE], sigblob[SIGBLOB_LEN]; + u_int rlen, slen, len, dlen; + Buffer b; + + if (key == NULL || key->type != KEY_DSA || key->dsa == NULL) { + error("ssh_dss_sign: no DSA key"); + return -1; + } + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, data, datalen); + EVP_DigestFinal(&md, digest, &dlen); + + sig = DSA_do_sign(digest, dlen, key->dsa); + memset(digest, 'd', sizeof(digest)); + + if (sig == NULL) { + error("ssh_dss_sign: sign failed"); + return -1; + } + + rlen = BN_num_bytes(sig->r); + slen = BN_num_bytes(sig->s); + if (rlen > INTBLOB_LEN || slen > INTBLOB_LEN) { + error("bad sig size %u %u", rlen, slen); + DSA_SIG_free(sig); + return -1; + } + memset(sigblob, 0, SIGBLOB_LEN); + BN_bn2bin(sig->r, sigblob+ SIGBLOB_LEN - INTBLOB_LEN - rlen); + BN_bn2bin(sig->s, sigblob+ SIGBLOB_LEN - slen); + DSA_SIG_free(sig); + + if (datafellows & SSH_BUG_SIGBLOB) { + if (lenp != NULL) + *lenp = SIGBLOB_LEN; + if (sigp != NULL) { + *sigp = xmalloc(SIGBLOB_LEN); + memcpy(*sigp, sigblob, SIGBLOB_LEN); + } + } else { + /* ietf-drafts */ + buffer_init(&b); + buffer_put_cstring(&b, "ssh-dss"); + buffer_put_string(&b, sigblob, SIGBLOB_LEN); + len = buffer_len(&b); + if (lenp != NULL) + *lenp = len; + if (sigp != NULL) { + *sigp = xmalloc(len); + memcpy(*sigp, buffer_ptr(&b), len); + } + buffer_free(&b); + } + return 0; +} +int +ssh_dss_verify(Key *key, u_char *signature, u_int signaturelen, + u_char *data, u_int datalen) +{ + DSA_SIG *sig; + const EVP_MD *evp_md = EVP_sha1(); + EVP_MD_CTX md; + u_char digest[EVP_MAX_MD_SIZE], *sigblob; + u_int len, dlen; + int rlen, ret; + Buffer b; + + if (key == NULL || key->type != KEY_DSA || key->dsa == NULL) { + error("ssh_dss_verify: no DSA key"); + return -1; + } + + /* fetch signature */ + if (datafellows & SSH_BUG_SIGBLOB) { + sigblob = signature; + len = signaturelen; + } else { + /* ietf-drafts */ + char *ktype; + buffer_init(&b); + buffer_append(&b, signature, signaturelen); + ktype = buffer_get_string(&b, NULL); + if (strcmp("ssh-dss", ktype) != 0) { + error("ssh_dss_verify: cannot handle type %s", ktype); + buffer_free(&b); + xfree(ktype); + return -1; + } + xfree(ktype); + sigblob = buffer_get_string(&b, &len); + rlen = buffer_len(&b); + buffer_free(&b); + if (rlen != 0) { + error("ssh_dss_verify: " + "remaining bytes in signature %d", rlen); + xfree(sigblob); + return -1; + } + } + + if (len != SIGBLOB_LEN) { + fatal("bad sigbloblen %u != SIGBLOB_LEN", len); + } + + /* parse signature */ + if ((sig = DSA_SIG_new()) == NULL) + fatal("ssh_dss_verify: DSA_SIG_new failed"); + if ((sig->r = BN_new()) == NULL) + fatal("ssh_dss_verify: BN_new failed"); + if ((sig->s = BN_new()) == NULL) + fatal("ssh_dss_verify: BN_new failed"); + BN_bin2bn(sigblob, INTBLOB_LEN, sig->r); + BN_bin2bn(sigblob+ INTBLOB_LEN, INTBLOB_LEN, sig->s); + + if (!(datafellows & SSH_BUG_SIGBLOB)) { + memset(sigblob, 0, len); + xfree(sigblob); + } + + /* sha1 the data */ + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, data, datalen); + EVP_DigestFinal(&md, digest, &dlen); + + ret = DSA_do_verify(digest, dlen, sig, key->dsa); + memset(digest, 'd', sizeof(digest)); + + DSA_SIG_free(sig); + + debug("ssh_dss_verify: signature %s", + ret == 1 ? "correct" : ret == 0 ? "incorrect" : "error"); + return ret; +} diff --git a/usr/src/cmd/ssh/libssh/common/ssh-gss.c b/usr/src/cmd/ssh/libssh/common/ssh-gss.c new file mode 100644 index 0000000000..d03aad381d --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/ssh-gss.c @@ -0,0 +1,767 @@ +/* + * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved. * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#include "includes.h" + +#ifdef GSSAPI + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ssh.h" +#include "ssh2.h" +#include "xmalloc.h" +#include "buffer.h" +#include "bufaux.h" +#include "packet.h" +#include "compat.h" +#include <openssl/evp.h> +#include "cipher.h" +#include "kex.h" +#include "log.h" +#include "compat.h" +#include "xlist.h" +#include "monitor_wrap.h" + +#include <netdb.h> + +#include "ssh-gss.h" + +#ifdef HAVE_GSS_OID_TO_MECH +#include <gssapi/gssapi_ext.h> +#endif /* HAVE_GSS_OID_TO_MECH */ + +typedef struct { + char *encoded; + gss_OID oid; +} ssh_gss_kex_mapping; + +static ssh_gss_kex_mapping **gss_enc2oid = NULL; + +static void ssh_gssapi_encode_oid_for_kex(const gss_OID oid, char **enc_name); +static char *ssh_gssapi_make_kexalgs_list(gss_OID_set mechs, + const char *old_kexalgs); + +/* + * Populate gss_enc2oid table and return list of kexnames. + * + * If called with both mechs == GSS_C_NULL_OID_SET and kexname_list == NULL + * then cached gss_enc2oid table is cleaned up. + */ +void +ssh_gssapi_mech_oids_to_kexnames(const gss_OID_set mechs, char **kexname_list) +{ + ssh_gss_kex_mapping **new_gss_enc2oid, **p; + Buffer buf; + char *enc_name; + int i; + + if (kexname_list != NULL) + *kexname_list = NULL; /* default to failed */ + + if (mechs != GSS_C_NULL_OID_SET || kexname_list == NULL) { + /* Cleanup gss_enc2oid table */ + for (p = gss_enc2oid ; p != NULL && *p != NULL ; p++) { + if ((*p)->encoded) + xfree((*p)->encoded); + ssh_gssapi_release_oid(&(*p)->oid); + xfree(*p); + } + if (gss_enc2oid) + xfree(gss_enc2oid); + } + + if (mechs == GSS_C_NULL_OID_SET && kexname_list == NULL) + return; /* nothing left to do */ + + if (mechs) { + gss_OID mech; + /* Populate gss_enc2oid table */ + new_gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping *) * + (mechs->count + 1)); + memset(new_gss_enc2oid, 0, + sizeof(ssh_gss_kex_mapping *) * (mechs->count + 1)); + + for (i = 0 ; i < mechs->count ; i++) { + mech = &mechs->elements[i]; + ssh_gssapi_encode_oid_for_kex((const gss_OID)mech, + &enc_name); + + if (!enc_name) + continue; + + new_gss_enc2oid[i] = + xmalloc(sizeof(ssh_gss_kex_mapping)); + (new_gss_enc2oid[i])->encoded = enc_name; + (new_gss_enc2oid[i])->oid = + ssh_gssapi_dup_oid(&mechs->elements[i]); + } + + /* Do this last to avoid run-ins with fatal_cleanups */ + gss_enc2oid = new_gss_enc2oid; + } + + if (!kexname_list) + return; /* nothing left to do */ + + /* Make kex name list */ + buffer_init(&buf); + for (p = gss_enc2oid ; p && *p ; p++) { + buffer_put_char(&buf,','); + buffer_append(&buf, (*p)->encoded, strlen((*p)->encoded)); + } + + if (buffer_len(&buf) == 0) { + buffer_free(&buf); + return; + } + + buffer_consume(&buf, 1); /* consume leading ',' */ + buffer_put_char(&buf,'\0'); + + *kexname_list = xstrdup(buffer_ptr(&buf)); + buffer_free(&buf); +} + +void +ssh_gssapi_mech_oid_to_kexname(const gss_OID mech, char **kexname) +{ + ssh_gss_kex_mapping **p; + + if (mech == GSS_C_NULL_OID || !kexname) + return; + + *kexname = NULL; /* default to not found */ + if (gss_enc2oid) { + for (p = gss_enc2oid ; p && *p ; p++) { + if (mech->length == (*p)->oid->length && + memcmp(mech->elements, (*p)->oid->elements, + mech->length) == 0) + *kexname = xstrdup((*p)->encoded); + } + } + + if (*kexname) + return; /* found */ + + ssh_gssapi_encode_oid_for_kex(mech, kexname); +} + +void +ssh_gssapi_oid_of_kexname(const char *kexname, gss_OID *mech) +{ + ssh_gss_kex_mapping **p; + + if (!mech || !kexname || !*kexname) + return; + + *mech = GSS_C_NULL_OID; /* default to not found */ + + if (!gss_enc2oid) + return; + + for (p = gss_enc2oid ; p && *p ; p++) { + if (strcmp(kexname, (*p)->encoded) == 0) { + *mech = (*p)->oid; + return; + } + } +} + +static +void +ssh_gssapi_encode_oid_for_kex(const gss_OID oid, char **enc_name) +{ + Buffer buf; + OM_uint32 oidlen; + u_int enclen; + const EVP_MD *evp_md = EVP_md5(); + EVP_MD_CTX md; + u_char digest[EVP_MAX_MD_SIZE]; + char *encoded; + + if (oid == GSS_C_NULL_OID || !enc_name) + return; + + *enc_name = NULL; + + oidlen = oid->length; + + /* No GSS mechs have OIDs as long as 128 -- simplify DER encoding */ + if (oidlen > 128) + return; /* fail gracefully */ + + /* + * NOTE: If we need to support SSH_BUG_GSSAPI_BER this is where + * we'd do it. + * + * That means using "Se3H81ismmOC3OE+FwYCiQ==" for the Kerberos + * V mech and "N3+k7/4wGxHyuP8Yxi4RhA==" for the GSI mech. Ick. + */ + + buffer_init(&buf); + + /* UNIVERSAL class tag for OBJECT IDENTIFIER */ + buffer_put_char(&buf, 0x06); + buffer_put_char(&buf, oidlen); /* one octet DER length -- see above */ + + /* OID elements */ + buffer_append(&buf, oid->elements, oidlen); + + /* Make digest */ + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, buffer_ptr(&buf), buffer_len(&buf)); + EVP_DigestFinal(&md, digest, NULL); + buffer_free(&buf); + + /* Base 64 encoding */ + encoded=xmalloc(EVP_MD_size(evp_md)*2); + enclen=__b64_ntop(digest, EVP_MD_size(evp_md), + encoded,EVP_MD_size(evp_md)*2); + buffer_init(&buf); + buffer_append(&buf, KEX_GSS_SHA1, sizeof(KEX_GSS_SHA1)-1); + buffer_append(&buf, encoded, enclen); + buffer_put_char(&buf, '\0'); + + debug2("GSS-API Mechanism encoded as %s",encoded); + + *enc_name = xstrdup(buffer_ptr(&buf)); + buffer_free(&buf); +} + +static +char * +ssh_gssapi_make_kexalgs_list(gss_OID_set mechs, const char *old_kexalgs) +{ + char *gss_kexalgs, *new_kexalgs; + int len; + + if (mechs == GSS_C_NULL_OID_SET) + return (xstrdup(old_kexalgs)); /* never null */ + + ssh_gssapi_mech_oids_to_kexnames(mechs, &gss_kexalgs); + + if (gss_kexalgs == NULL || *gss_kexalgs == '\0') + return (xstrdup(old_kexalgs)); /* never null */ + + if (old_kexalgs == NULL || *old_kexalgs == '\0') + return (gss_kexalgs); + + len = strlen(old_kexalgs) + strlen(gss_kexalgs) + 2; + new_kexalgs = xmalloc(len); + (void) snprintf(new_kexalgs, len, "%s,%s", gss_kexalgs, old_kexalgs); + + return (new_kexalgs); +} + +void +ssh_gssapi_modify_kex(Kex *kex, gss_OID_set mechs, char **proposal) +{ + char *kexalgs, *orig_kexalgs, *p; + char **hostalg, *orig_hostalgs, *new_hostalgs; + char **hostalgs; + gss_OID_set dup_mechs; + OM_uint32 maj, min; + int i; + + if (kex == NULL || proposal == NULL || + (orig_kexalgs = proposal[PROPOSAL_KEX_ALGS]) == NULL) { + fatal("INTERNAL ERROR (%s)", __func__); + } + + orig_hostalgs = proposal[PROPOSAL_SERVER_HOST_KEY_ALGS]; + + if (kex->mechs == GSS_C_NULL_OID_SET && mechs == GSS_C_NULL_OID_SET) + return; /* didn't offer GSS last time, not offering now */ + + if (kex->mechs == GSS_C_NULL_OID_SET || mechs == GSS_C_NULL_OID_SET) + goto mod_offer; /* didn't offer last time or not offering now */ + + /* Check if mechs is congruent to kex->mechs (last offered) */ + if (kex->mechs->count == mechs->count) { + int present, matches = 0; + + for ( i = 0 ; i < mechs->count ; i++ ) { + maj = gss_test_oid_set_member(&min, + &kex->mechs->elements[i], mechs, + &present); + + if (GSS_ERROR(maj)) { + mechs = GSS_C_NULL_OID_SET; + break; + } + + matches += (present) ? 1 : 0; + } + + if (matches == kex->mechs->count) + return; /* no change in offer from last time */ + } + +mod_offer: + /* + * Remove previously offered mechs from PROPOSAL_KEX_ALGS proposal + * + * ASSUMPTION: GSS-API kex algs always go in front, so removing + * them is a matter of skipping them. + */ + p = kexalgs = orig_kexalgs = proposal[PROPOSAL_KEX_ALGS]; + while (p != NULL && *p != '\0' && + strncmp(p, KEX_GSS_SHA1, strlen(KEX_GSS_SHA1)) == 0) { + + if ((p = strchr(p, ',')) == NULL) + break; + p++; + kexalgs = p; + + } + kexalgs = proposal[PROPOSAL_KEX_ALGS] = xstrdup(kexalgs); + xfree(orig_kexalgs); + + (void) gss_release_oid_set(&min, &kex->mechs); /* ok if !kex->mechs */ + + /* Not offering GSS kexalgs now -> all done */ + if (mechs == GSS_C_NULL_OID_SET) + return; + + /* Remember mechs we're offering */ + maj = gss_create_empty_oid_set(&min, &dup_mechs); + if (GSS_ERROR(maj)) + return; + for ( i = 0 ; i < mechs->count ; i++ ) { + maj = gss_add_oid_set_member(&min, &mechs->elements[i], + &dup_mechs); + + if (GSS_ERROR(maj)) { + (void) gss_release_oid_set(&min, &dup_mechs); + return; + } + } + + /* Add mechs to kexalgs ... */ + proposal[PROPOSAL_KEX_ALGS] = ssh_gssapi_make_kexalgs_list(mechs, kexalgs); + kex->mechs = dup_mechs; /* remember what we offer now */ + + /* + * ... and add null host key alg, if it wasn't there before, but + * not if we're the server and we have other host key algs to + * offer. + * + * NOTE: Never remove "null" host key alg once added. + */ + if (orig_hostalgs == NULL || *orig_hostalgs == '\0') { + proposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = xstrdup("null"); + } else if (!kex->server) { + hostalgs = xsplit(orig_hostalgs, ','); + for ( hostalg = hostalgs ; *hostalg != NULL ; hostalg++ ) { + if (strcmp(*hostalg, "null") == 0) { + xfree_split_list(hostalgs); + return; + } + } + xfree_split_list(hostalgs); + + if (kex->mechs != GSS_C_NULL_OID_SET) { + int len; + + len = strlen(orig_hostalgs) + sizeof(",null"); + new_hostalgs = xmalloc(len); + (void) snprintf(new_hostalgs, len, "%s,null", + orig_hostalgs); + proposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = new_hostalgs; + } + + xfree(orig_hostalgs); + } +} + +/* + * Yes, we harcode OIDs for some things, for now it's all we can do. + * + * We have to reference particular mechanisms due to lack of generality + * in the GSS-API in several areas: authorization, mapping principal + * names to usernames, "storing" delegated credentials, and discovering + * whether a mechanism is a pseudo-mechanism that negotiates mechanisms. + * + * Even if they were in some header file or if __gss_mech_to_oid() + * and/or __gss_oid_to_mech() were standard we'd still have to hardcode + * the mechanism names, and since the mechanisms have no standard names + * other than their OIDs it's actually worse [less portable] to hardcode + * names than OIDs, so we hardcode OIDs. + * + * SPNEGO is a difficult problem though -- it MUST NOT be used in SSHv2, + * but that's true of all possible pseudo-mechanisms that can perform + * mechanism negotiation, and SPNEGO could have new OIDs in the future. + * Ideally we could query each mechanism for its feature set and then + * ignore any mechanisms that negotiate mechanisms, but, alas, there's + * no interface to do that. + * + * In the future, if the necessary generic GSS interfaces for the issues + * listed above are made available (even if they differ by platform, as + * we can expect authorization interfaces will), then we can stop + * referencing specific mechanism OIDs here. + */ +int +ssh_gssapi_is_spnego(gss_OID oid) +{ + return (oid->length == 6 && + memcmp("\053\006\001\005\005\002", + oid->elements, 6) == 0); +} + +int +ssh_gssapi_is_krb5(gss_OID oid) +{ + return (oid->length == 9 && + memcmp("\x2A\x86\x48\x86\xF7\x12\x01\x02\x02", + oid->elements, 9) == 0); +} + +int +ssh_gssapi_is_dh(gss_OID oid) +{ + return (oid->length == 9 && + memcmp("\053\006\004\001\052\002\032\002\005", + oid->elements, 9) == 0); +} + +int +ssh_gssapi_is_gsi(gss_OID oid) +{ + return (oid->length == 9 && + memcmp("\x2B\x06\x01\x04\x01\x9B\x50\x01\x01", + oid->elements, 9) == 0); +} + +const +char * +ssh_gssapi_oid_to_name(gss_OID oid) +{ +#ifdef HAVE_GSS_OID_TO_MECH + return __gss_oid_to_mech(oid); +#else + if (ssh_gssapi_is_krb5(oid)) + return "Kerberos"; + if (ssh_gssapi_is_gsi(oid)) + return "GSI"; + return "(unknown)"; +#endif /* HAVE_GSS_OID_TO_MECH */ +} + +char * +ssh_gssapi_oid_to_str(gss_OID oid) +{ +#ifdef HAVE_GSS_OID_TO_STR + gss_buffer_desc str_buf; + char *str; + OM_uint32 maj, min; + + maj = gss_oid_to_str(&min, oid, &str_buf); + + if (GSS_ERROR(maj)) + return xstrdup("<gss_oid_to_str() failed>"); + + str = xmalloc(str_buf.length + 1); + memset(str, 0, str_buf.length + 1); + strlcpy(str, str_buf.value, str_buf.length + 1); + (void) gss_release_buffer(&min, &str_buf); + + return str; +#else + return xstrdup("<gss_oid_to_str() unsupported>"); +#endif /* HAVE_GSS_OID_TO_STR */ +} + +/* Check that the OID in a data stream matches that in the context */ +int ssh_gssapi_check_mech_oid(Gssctxt *ctx, void *data, size_t len) { + + return (ctx!=NULL && ctx->desired_mech != GSS_C_NULL_OID && + ctx->desired_mech->length == len && + memcmp(ctx->desired_mech->elements,data,len)==0); +} + +/* Set the contexts OID from a data stream */ +void ssh_gssapi_set_oid_data(Gssctxt *ctx, void *data, size_t len) { + if (ctx->actual_mech != GSS_C_NULL_OID) { + xfree(ctx->actual_mech->elements); + xfree(ctx->actual_mech); + } + ctx->actual_mech=xmalloc(sizeof(gss_OID_desc)); + ctx->actual_mech->length=len; + ctx->actual_mech->elements=xmalloc(len); + memcpy(ctx->actual_mech->elements,data,len); +} + +/* Set the contexts OID */ +void ssh_gssapi_set_oid(Gssctxt *ctx, gss_OID oid) { + ssh_gssapi_set_oid_data(ctx,oid->elements,oid->length); +} + +/* All this effort to report an error ... */ + +void +ssh_gssapi_error(Gssctxt *ctxt, const char *where) { + if (where) + debug("GSS-API error while %s: %s", where, + ssh_gssapi_last_error(ctxt,NULL,NULL)); + else + debug("GSS-API error: %s", + ssh_gssapi_last_error(ctxt,NULL,NULL)); +} + +char * +ssh_gssapi_last_error(Gssctxt *ctxt, + OM_uint32 *major_status, OM_uint32 *minor_status) { + OM_uint32 lmin, more; + OM_uint32 maj, min; + gss_OID mech = GSS_C_NULL_OID; + gss_buffer_desc msg; + Buffer b; + char *ret; + + buffer_init(&b); + + if (ctxt) { + /* Get status codes from the Gssctxt */ + maj = ctxt->major; + min = ctxt->minor; + /* Output them if desired */ + if (major_status) + *major_status = maj; + if (minor_status) + *minor_status = min; + /* Get mechanism for minor status display */ + mech = (ctxt->actual_mech != GSS_C_NULL_OID) ? + ctxt->actual_mech : ctxt->desired_mech; + } else if (major_status && minor_status) { + maj = *major_status; + min = *major_status; + } else { + maj = GSS_S_COMPLETE; + min = 0; + } + + more = 0; + /* The GSSAPI error */ + do { + gss_display_status(&lmin, maj, + GSS_C_GSS_CODE, GSS_C_NULL_OID, + &more, &msg); + + buffer_append(&b,msg.value,msg.length); + buffer_put_char(&b,'\n'); + gss_release_buffer(&lmin, &msg); + } while (more!=0); + + /* The mechanism specific error */ + do { + /* + * If mech == GSS_C_NULL_OID we may get the default + * mechanism, whatever that is, and that may not be + * useful. + */ + gss_display_status(&lmin, min, + GSS_C_MECH_CODE, mech, + &more, &msg); + + buffer_append(&b,msg.value,msg.length); + buffer_put_char(&b,'\n'); + + gss_release_buffer(&lmin, &msg); + } while (more!=0); + + buffer_put_char(&b,'\0'); + ret=xstrdup(buffer_ptr(&b)); + buffer_free(&b); + + return (ret); +} + +/* Initialise our GSSAPI context. We use this opaque structure to contain all + * of the data which both the client and server need to persist across + * {accept,init}_sec_context calls, so that when we do it from the userauth + * stuff life is a little easier + */ +void +ssh_gssapi_build_ctx(Gssctxt **ctx, int client, gss_OID mech) +{ + Gssctxt *newctx; + + ssh_gssapi_delete_ctx(ctx); + + newctx = (Gssctxt*)xmalloc(sizeof (Gssctxt)); + memset(newctx, 0, sizeof(Gssctxt)); + + newctx->local = client; + newctx->desired_mech = ssh_gssapi_dup_oid(mech); + + /* This happens to be redundant given the memset() above */ + newctx->major = GSS_S_COMPLETE; + newctx->context = GSS_C_NO_CONTEXT; + newctx->actual_mech = GSS_C_NULL_OID; + newctx->desired_name = GSS_C_NO_NAME; + newctx->src_name = GSS_C_NO_NAME; + newctx->dst_name = GSS_C_NO_NAME; + newctx->creds = GSS_C_NO_CREDENTIAL; + newctx->deleg_creds = GSS_C_NO_CREDENTIAL; + + *ctx = newctx; +} + +gss_OID +ssh_gssapi_dup_oid(gss_OID oid) +{ + gss_OID new_oid; + + new_oid = xmalloc(sizeof(gss_OID_desc)); + + new_oid->elements = xmalloc(oid->length); + new_oid->length = oid->length; + memcpy(new_oid->elements, oid->elements, oid->length); + + return (new_oid); +} + +gss_OID +ssh_gssapi_make_oid(size_t length, void *elements) +{ + gss_OID_desc oid; + + oid.length = length; + oid.elements = elements; + + return (ssh_gssapi_dup_oid(&oid)); +} + +void +ssh_gssapi_release_oid(gss_OID *oid) +{ + OM_uint32 min; + + if (oid && *oid == GSS_C_NULL_OID) + return; + (void) gss_release_oid(&min, oid); + + if (*oid == GSS_C_NULL_OID) + return; /* libgss did own this gss_OID and released it */ + + xfree((*oid)->elements); + xfree(*oid); + *oid = GSS_C_NULL_OID; +} + +struct gss_name { + gss_OID name_type; + gss_buffer_t external_name; + gss_OID mech_type; + void *mech_name; +}; + +/* Delete our context, providing it has been built correctly */ +void +ssh_gssapi_delete_ctx(Gssctxt **ctx) +{ + OM_uint32 ms; + + if ((*ctx) == NULL) + return; + + if ((*ctx)->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&ms,&(*ctx)->context,GSS_C_NO_BUFFER); + /* XXX if ((*ctx)->desired_mech != GSS_C_NULL_OID) + ssh_gssapi_release_oid(&(*ctx)->desired_mech);*/ + if ((*ctx)->actual_mech != GSS_C_NULL_OID) + (void) ssh_gssapi_release_oid(&(*ctx)->actual_mech); + if ((*ctx)->desired_name != GSS_C_NO_NAME) + gss_release_name(&ms,&(*ctx)->desired_name); + /* if ((*ctx)->src_name != GSS_C_NO_NAME) + gss_release_name(&ms,&(*ctx)->src_name); */ + if ((*ctx)->dst_name != GSS_C_NO_NAME) + gss_release_name(&ms,&(*ctx)->dst_name); + if ((*ctx)->creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&ms,&(*ctx)->creds); + if ((*ctx)->deleg_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&ms,&(*ctx)->deleg_creds); + + xfree(*ctx); + *ctx=NULL; +} + +/* Create a GSS hostbased service principal name for a given server hostname */ +int +ssh_gssapi_import_name(Gssctxt *ctx, const char *server_host) +{ + gss_buffer_desc name_buf; + int ret; + + /* Build target principal */ + + /* Non-portable but very neat code relying on SUSv3: + name_buf.length = snprintf(NULL, 0, "%s@%S", + SSH_GSS_HOSTBASED_SERVICE, server_host); + */ + + name_buf.length = strlen(SSH_GSS_HOSTBASED_SERVICE) + + strlen(server_host) + 1; /* +1 for '@' */ + name_buf.value = xmalloc(name_buf.length + 1); /* +1 for NUL */ + ret = snprintf(name_buf.value, name_buf.length + 1, "%s@%s", + SSH_GSS_HOSTBASED_SERVICE, server_host); + + debug3("%s: snprintf() returned %d, expected %d", __func__, ret, name_buf.length + 1); + + ctx->major = gss_import_name(&ctx->minor, &name_buf, + GSS_C_NT_HOSTBASED_SERVICE, &ctx->desired_name); + + if (GSS_ERROR(ctx->major)) { + ssh_gssapi_error(ctx, "calling GSS_Import_name()"); + return 0; + } + + xfree(name_buf.value); + + return 1; +} + +OM_uint32 +ssh_gssapi_get_mic(Gssctxt *ctx, gss_buffer_desc *buffer, gss_buffer_desc *hash) { + + ctx->major=gss_get_mic(&ctx->minor,ctx->context, + GSS_C_QOP_DEFAULT, buffer, hash); + if (GSS_ERROR(ctx->major)) + ssh_gssapi_error(ctx, "while getting MIC"); + return(ctx->major); +} + +OM_uint32 +ssh_gssapi_verify_mic(Gssctxt *ctx, gss_buffer_desc *buffer, gss_buffer_desc *hash) { + gss_qop_t qop; + + ctx->major=gss_verify_mic(&ctx->minor,ctx->context, buffer, hash, &qop); + if (GSS_ERROR(ctx->major)) + ssh_gssapi_error(ctx, "while verifying MIC"); + return(ctx->major); +} +#endif /* GSSAPI */ diff --git a/usr/src/cmd/ssh/libssh/common/ssh-rsa.c b/usr/src/cmd/ssh/libssh/common/ssh-rsa.c new file mode 100644 index 0000000000..bc89d41da1 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/ssh-rsa.c @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: ssh-rsa.c,v 1.26 2002/08/27 17:13:56 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <openssl/evp.h> +#include <openssl/err.h> + +#include "xmalloc.h" +#include "log.h" +#include "buffer.h" +#include "bufaux.h" +#include "key.h" +#include "ssh-rsa.h" +#include "compat.h" +#include "ssh.h" + +static int openssh_RSA_verify(int, u_char *, u_int, u_char *, u_int , RSA *); + +/* RSASSA-PKCS1-v1_5 (PKCS #1 v2.0 signature) with SHA1 */ +int +ssh_rsa_sign(Key *key, u_char **sigp, u_int *lenp, + u_char *data, u_int datalen) +{ + const EVP_MD *evp_md; + EVP_MD_CTX md; + u_char digest[EVP_MAX_MD_SIZE], *sig; + u_int slen, dlen, len; + int ok, nid; + Buffer b; + + if (key == NULL || key->type != KEY_RSA || key->rsa == NULL) { + error("ssh_rsa_sign: no RSA key"); + return -1; + } + nid = (datafellows & SSH_BUG_RSASIGMD5) ? NID_md5 : NID_sha1; + if ((evp_md = EVP_get_digestbynid(nid)) == NULL) { + error("ssh_rsa_sign: EVP_get_digestbynid %d failed", nid); + return -1; + } + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, data, datalen); + EVP_DigestFinal(&md, digest, &dlen); + + slen = RSA_size(key->rsa); + sig = xmalloc(slen); + + ok = RSA_sign(nid, digest, dlen, sig, &len, key->rsa); + memset(digest, 'd', sizeof(digest)); + + if (ok != 1) { + int ecode = ERR_get_error(); + error("ssh_rsa_sign: RSA_sign failed: %s", + ERR_error_string(ecode, NULL)); + xfree(sig); + return -1; + } + if (len < slen) { + u_int diff = slen - len; + debug("slen %u > len %u", slen, len); + memmove(sig + diff, sig, len); + memset(sig, 0, diff); + } else if (len > slen) { + error("ssh_rsa_sign: slen %u slen2 %u", slen, len); + xfree(sig); + return -1; + } + /* encode signature */ + buffer_init(&b); + buffer_put_cstring(&b, "ssh-rsa"); + buffer_put_string(&b, sig, slen); + len = buffer_len(&b); + if (lenp != NULL) + *lenp = len; + if (sigp != NULL) { + *sigp = xmalloc(len); + memcpy(*sigp, buffer_ptr(&b), len); + } + buffer_free(&b); + memset(sig, 's', slen); + xfree(sig); + + return 0; +} + +int +ssh_rsa_verify(Key *key, u_char *signature, u_int signaturelen, + u_char *data, u_int datalen) +{ + Buffer b; + const EVP_MD *evp_md; + EVP_MD_CTX md; + char *ktype; + u_char digest[EVP_MAX_MD_SIZE], *sigblob; + u_int len, dlen, modlen; + int rlen, ret, nid; + + if (key == NULL || key->type != KEY_RSA || key->rsa == NULL) { + error("ssh_rsa_verify: no RSA key"); + return -1; + } + if (BN_num_bits(key->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) { + error("ssh_rsa_verify: RSA modulus too small: %d < minimum %d bits", + BN_num_bits(key->rsa->n), SSH_RSA_MINIMUM_MODULUS_SIZE); + return -1; + } + buffer_init(&b); + buffer_append(&b, signature, signaturelen); + ktype = buffer_get_string(&b, NULL); + if (strcmp("ssh-rsa", ktype) != 0) { + error("ssh_rsa_verify: cannot handle type %s", ktype); + buffer_free(&b); + xfree(ktype); + return -1; + } + xfree(ktype); + sigblob = buffer_get_string(&b, &len); + rlen = buffer_len(&b); + buffer_free(&b); + if (rlen != 0) { + error("ssh_rsa_verify: remaining bytes in signature %d", rlen); + xfree(sigblob); + return -1; + } + /* RSA_verify expects a signature of RSA_size */ + modlen = RSA_size(key->rsa); + if (len > modlen) { + error("ssh_rsa_verify: len %u > modlen %u", len, modlen); + xfree(sigblob); + return -1; + } else if (len < modlen) { + u_int diff = modlen - len; + debug("ssh_rsa_verify: add padding: modlen %u > len %u", + modlen, len); + sigblob = xrealloc(sigblob, modlen); + memmove(sigblob + diff, sigblob, len); + memset(sigblob, 0, diff); + len = modlen; + } + nid = (datafellows & SSH_BUG_RSASIGMD5) ? NID_md5 : NID_sha1; + if ((evp_md = EVP_get_digestbynid(nid)) == NULL) { + error("ssh_rsa_verify: EVP_get_digestbynid %d failed", nid); + xfree(sigblob); + return -1; + } + EVP_DigestInit(&md, evp_md); + EVP_DigestUpdate(&md, data, datalen); + EVP_DigestFinal(&md, digest, &dlen); + + ret = openssh_RSA_verify(nid, digest, dlen, sigblob, len, key->rsa); + memset(digest, 'd', sizeof(digest)); + memset(sigblob, 's', len); + xfree(sigblob); + debug("ssh_rsa_verify: signature %scorrect", (ret==0) ? "in" : ""); + return ret; +} + +/* + * See: + * http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/ + * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.asn + */ +/* + * id-sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) + * oiw(14) secsig(3) algorithms(2) 26 } + */ +static const u_char id_sha1[] = { + 0x30, 0x21, /* type Sequence, length 0x21 (33) */ + 0x30, 0x09, /* type Sequence, length 0x09 */ + 0x06, 0x05, /* type OID, length 0x05 */ + 0x2b, 0x0e, 0x03, 0x02, 0x1a, /* id-sha1 OID */ + 0x05, 0x00, /* NULL */ + 0x04, 0x14 /* Octet string, length 0x14 (20), followed by sha1 hash */ +}; +/* + * id-md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) + * rsadsi(113549) digestAlgorithm(2) 5 } + */ +static const u_char id_md5[] = { + 0x30, 0x20, /* type Sequence, length 0x20 (32) */ + 0x30, 0x0c, /* type Sequence, length 0x09 */ + 0x06, 0x08, /* type OID, length 0x05 */ + 0x2a, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, /* id-md5 */ + 0x05, 0x00, /* NULL */ + 0x04, 0x10 /* Octet string, length 0x10 (16), followed by md5 hash */ +}; + +static int +openssh_RSA_verify(int type, u_char *hash, u_int hashlen, + u_char *sigbuf, u_int siglen, RSA *rsa) +{ + u_int ret, rsasize, oidlen = 0, hlen = 0; + int len; + const u_char *oid = NULL; + u_char *decrypted = NULL; + + ret = 0; + switch (type) { + case NID_sha1: + oid = id_sha1; + oidlen = sizeof(id_sha1); + hlen = 20; + break; + case NID_md5: + oid = id_md5; + oidlen = sizeof(id_md5); + hlen = 16; + break; + default: + goto done; + break; + } + if (hashlen != hlen) { + error("bad hashlen"); + goto done; + } + rsasize = RSA_size(rsa); + if (siglen == 0 || siglen > rsasize) { + error("bad siglen"); + goto done; + } + decrypted = xmalloc(rsasize); + if ((len = RSA_public_decrypt(siglen, sigbuf, decrypted, rsa, + RSA_PKCS1_PADDING)) < 0) { + error("RSA_public_decrypt failed: %s", + ERR_error_string(ERR_get_error(), NULL)); + goto done; + } + if (len != hlen + oidlen) { + error("bad decrypted len: %d != %d + %d", len, hlen, oidlen); + goto done; + } + if (memcmp(decrypted, oid, oidlen) != 0) { + error("oid mismatch"); + goto done; + } + if (memcmp(decrypted + oidlen, hash, hlen) != 0) { + error("hash mismatch"); + goto done; + } + ret = 1; +done: + if (decrypted) + xfree(decrypted); + return ret; +} diff --git a/usr/src/cmd/ssh/libssh/common/tildexpand.c b/usr/src/cmd/ssh/libssh/common/tildexpand.c new file mode 100644 index 0000000000..6d3850a9ea --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/tildexpand.c @@ -0,0 +1,75 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: tildexpand.c,v 1.13 2002/06/23 03:25:50 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "log.h" +#include "tildexpand.h" + +/* + * Expands tildes in the file name. Returns data allocated by xmalloc. + * Warning: this calls getpw*. + */ +char * +tilde_expand_filename(const char *filename, uid_t my_uid) +{ + const char *cp; + u_int userlen; + char *expanded; + struct passwd *pw; + char user[100]; + int len; + + /* Return immediately if no tilde. */ + if (filename[0] != '~') + return xstrdup(filename); + + /* Skip the tilde. */ + filename++; + + /* Find where the username ends. */ + cp = strchr(filename, '/'); + if (cp) + userlen = cp - filename; /* Something after username. */ + else + userlen = strlen(filename); /* Nothing after username. */ + if (userlen == 0) + pw = getpwuid(my_uid); /* Own home directory. */ + else { + /* Tilde refers to someone elses home directory. */ + if (userlen > sizeof(user) - 1) + fatal("User name after tilde too long."); + memcpy(user, filename, userlen); + user[userlen] = 0; + pw = getpwnam(user); + } + if (!pw) + fatal("Unknown user %100s.", user); + + /* If referring to someones home directory, return it now. */ + if (!cp) { + /* Only home directory specified */ + return xstrdup(pw->pw_dir); + } + /* Build a path combining the specified directory and path. */ + len = strlen(pw->pw_dir) + strlen(cp + 1) + 2; + if (len > MAXPATHLEN) + fatal("Home directory too long (%d > %d", len-1, MAXPATHLEN-1); + expanded = xmalloc(len); + snprintf(expanded, len, "%s%s%s", pw->pw_dir, + strcmp(pw->pw_dir, "/") ? "/" : "", cp + 1); + return expanded; +} diff --git a/usr/src/cmd/ssh/libssh/common/ttymodes.c b/usr/src/cmd/ssh/libssh/common/ttymodes.c new file mode 100644 index 0000000000..1c27120481 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/ttymodes.c @@ -0,0 +1,465 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +/* + * SSH2 tty modes support by Kevin Steves. + * Copyright (c) 2001 Kevin Steves. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +/* + * Encoding and decoding of terminal modes in a portable way. + * Much of the format is defined in ttymodes.h; it is included multiple times + * into this file with the appropriate macro definitions to generate the + * suitable code. + */ + +#include "includes.h" +RCSID("$OpenBSD: ttymodes.c,v 1.18 2002/06/19 00:27:55 deraadt Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "packet.h" +#include "log.h" +#include "ssh1.h" +#include "compat.h" +#include "buffer.h" +#include "bufaux.h" + +#define TTY_OP_END 0 +/* + * uint32 (u_int) follows speed in SSH1 and SSH2 + */ +#define TTY_OP_ISPEED_PROTO1 192 +#define TTY_OP_OSPEED_PROTO1 193 +#define TTY_OP_ISPEED_PROTO2 128 +#define TTY_OP_OSPEED_PROTO2 129 + +/* + * Converts POSIX speed_t to a baud rate. The values of the + * constants for speed_t are not themselves portable. + */ +static int +speed_to_baud(speed_t speed) +{ + switch (speed) { + case B0: + return 0; + case B50: + return 50; + case B75: + return 75; + case B110: + return 110; + case B134: + return 134; + case B150: + return 150; + case B200: + return 200; + case B300: + return 300; + case B600: + return 600; + case B1200: + return 1200; + case B1800: + return 1800; + case B2400: + return 2400; + case B4800: + return 4800; + case B9600: + return 9600; + +#ifdef B19200 + case B19200: + return 19200; +#else /* B19200 */ +#ifdef EXTA + case EXTA: + return 19200; +#endif /* EXTA */ +#endif /* B19200 */ + +#ifdef B38400 + case B38400: + return 38400; +#else /* B38400 */ +#ifdef EXTB + case EXTB: + return 38400; +#endif /* EXTB */ +#endif /* B38400 */ + +#ifdef B7200 + case B7200: + return 7200; +#endif /* B7200 */ +#ifdef B14400 + case B14400: + return 14400; +#endif /* B14400 */ +#ifdef B28800 + case B28800: + return 28800; +#endif /* B28800 */ +#ifdef B57600 + case B57600: + return 57600; +#endif /* B57600 */ +#ifdef B76800 + case B76800: + return 76800; +#endif /* B76800 */ +#ifdef B115200 + case B115200: + return 115200; +#endif /* B115200 */ +#ifdef B230400 + case B230400: + return 230400; +#endif /* B230400 */ + default: + return 9600; + } +} + +/* + * Converts a numeric baud rate to a POSIX speed_t. + */ +static speed_t +baud_to_speed(int baud) +{ + switch (baud) { + case 0: + return B0; + case 50: + return B50; + case 75: + return B75; + case 110: + return B110; + case 134: + return B134; + case 150: + return B150; + case 200: + return B200; + case 300: + return B300; + case 600: + return B600; + case 1200: + return B1200; + case 1800: + return B1800; + case 2400: + return B2400; + case 4800: + return B4800; + case 9600: + return B9600; + +#ifdef B19200 + case 19200: + return B19200; +#else /* B19200 */ +#ifdef EXTA + case 19200: + return EXTA; +#endif /* EXTA */ +#endif /* B19200 */ + +#ifdef B38400 + case 38400: + return B38400; +#else /* B38400 */ +#ifdef EXTB + case 38400: + return EXTB; +#endif /* EXTB */ +#endif /* B38400 */ + +#ifdef B7200 + case 7200: + return B7200; +#endif /* B7200 */ +#ifdef B14400 + case 14400: + return B14400; +#endif /* B14400 */ +#ifdef B28800 + case 28800: + return B28800; +#endif /* B28800 */ +#ifdef B57600 + case 57600: + return B57600; +#endif /* B57600 */ +#ifdef B76800 + case 76800: + return B76800; +#endif /* B76800 */ +#ifdef B115200 + case 115200: + return B115200; +#endif /* B115200 */ +#ifdef B230400 + case 230400: + return B230400; +#endif /* B230400 */ + default: + return B9600; + } +} + +/* + * Encodes terminal modes for the terminal referenced by fd + * or tiop in a portable manner, and appends the modes to a packet + * being constructed. + */ +void +tty_make_modes(int fd, struct termios *tiop) +{ + struct termios tio; + int baud; + Buffer buf; + int tty_op_ospeed, tty_op_ispeed; + void (*put_arg)(Buffer *, u_int); + + buffer_init(&buf); + if (compat20) { + tty_op_ospeed = TTY_OP_OSPEED_PROTO2; + tty_op_ispeed = TTY_OP_ISPEED_PROTO2; + put_arg = buffer_put_int; + } else { + tty_op_ospeed = TTY_OP_OSPEED_PROTO1; + tty_op_ispeed = TTY_OP_ISPEED_PROTO1; + put_arg = (void (*)(Buffer *, u_int)) buffer_put_char; + } + + if (tiop == NULL) { + if (tcgetattr(fd, &tio) == -1) { + log("tcgetattr: %.100s", strerror(errno)); + goto end; + } + } else + tio = *tiop; + + /* Store input and output baud rates. */ + baud = speed_to_baud(cfgetospeed(&tio)); + debug3("tty_make_modes: ospeed %d", baud); + buffer_put_char(&buf, tty_op_ospeed); + buffer_put_int(&buf, baud); + baud = speed_to_baud(cfgetispeed(&tio)); + debug3("tty_make_modes: ispeed %d", baud); + buffer_put_char(&buf, tty_op_ispeed); + buffer_put_int(&buf, baud); + + /* Store values of mode flags. */ +#define TTYCHAR(NAME, OP) \ + debug3("tty_make_modes: %d %d", OP, tio.c_cc[NAME]); \ + buffer_put_char(&buf, OP); \ + put_arg(&buf, tio.c_cc[NAME]); + +#define TTYMODE(NAME, FIELD, OP) \ + debug3("tty_make_modes: %d %d", OP, ((tio.FIELD & NAME) != 0)); \ + buffer_put_char(&buf, OP); \ + put_arg(&buf, ((tio.FIELD & NAME) != 0)); + +#include "ttymodes.h" + +#undef TTYCHAR +#undef TTYMODE + +end: + /* Mark end of mode data. */ + buffer_put_char(&buf, TTY_OP_END); + if (compat20) + packet_put_string(buffer_ptr(&buf), buffer_len(&buf)); + else + packet_put_raw(buffer_ptr(&buf), buffer_len(&buf)); + buffer_free(&buf); +} + +/* + * Decodes terminal modes for the terminal referenced by fd in a portable + * manner from a packet being read. + */ +void +tty_parse_modes(int fd, int *n_bytes_ptr) +{ + struct termios tio; + int opcode, baud; + int n_bytes = 0; + int failure = 0; + u_int (*get_arg)(void); + int arg, arg_size; + + if (compat20) { + *n_bytes_ptr = packet_get_int(); + debug3("tty_parse_modes: SSH2 n_bytes %d", *n_bytes_ptr); + if (*n_bytes_ptr == 0) + return; + get_arg = packet_get_int; + arg_size = 4; + } else { + get_arg = packet_get_char; + arg_size = 1; + } + + /* + * Get old attributes for the terminal. We will modify these + * flags. I am hoping that if there are any machine-specific + * modes, they will initially have reasonable values. + */ + if (tcgetattr(fd, &tio) == -1) { + log("tcgetattr: %.100s", strerror(errno)); + failure = -1; + } + + for (;;) { + n_bytes += 1; + opcode = packet_get_char(); + switch (opcode) { + case TTY_OP_END: + goto set; + + /* XXX: future conflict possible */ + case TTY_OP_ISPEED_PROTO1: + case TTY_OP_ISPEED_PROTO2: + n_bytes += 4; + baud = packet_get_int(); + debug3("tty_parse_modes: ispeed %d", baud); + if (failure != -1 && cfsetispeed(&tio, baud_to_speed(baud)) == -1) + error("cfsetispeed failed for %d", baud); + break; + + /* XXX: future conflict possible */ + case TTY_OP_OSPEED_PROTO1: + case TTY_OP_OSPEED_PROTO2: + n_bytes += 4; + baud = packet_get_int(); + debug3("tty_parse_modes: ospeed %d", baud); + if (failure != -1 && cfsetospeed(&tio, baud_to_speed(baud)) == -1) + error("cfsetospeed failed for %d", baud); + break; + +#define TTYCHAR(NAME, OP) \ + case OP: \ + n_bytes += arg_size; \ + tio.c_cc[NAME] = get_arg(); \ + debug3("tty_parse_modes: %d %d", OP, tio.c_cc[NAME]); \ + break; +#define TTYMODE(NAME, FIELD, OP) \ + case OP: \ + n_bytes += arg_size; \ + if ((arg = get_arg())) \ + tio.FIELD |= NAME; \ + else \ + tio.FIELD &= ~NAME; \ + debug3("tty_parse_modes: %d %d", OP, arg); \ + break; + +#include "ttymodes.h" + +#undef TTYCHAR +#undef TTYMODE + + default: + debug("Ignoring unsupported tty mode opcode %d (0x%x)", + opcode, opcode); + if (!compat20) { + /* + * SSH1: + * Opcodes 1 to 127 are defined to have + * a one-byte argument. + * Opcodes 128 to 159 are defined to have + * an integer argument. + */ + if (opcode > 0 && opcode < 128) { + n_bytes += 1; + (void) packet_get_char(); + break; + } else if (opcode >= 128 && opcode < 160) { + n_bytes += 4; + (void) packet_get_int(); + break; + } else { + /* + * It is a truly undefined opcode (160 to 255). + * We have no idea about its arguments. So we + * must stop parsing. Note that some data may be + * left in the packet; hopefully there is nothing + * more coming after the mode data. + */ + log("parse_tty_modes: unknown opcode %d", opcode); + goto set; + } + } else { + /* + * SSH2: + * Opcodes 1 to 159 are defined to have + * a uint32 argument. + * Opcodes 160 to 255 are undefined and + * cause parsing to stop. + */ + if (opcode > 0 && opcode < 160) { + n_bytes += 4; + (void) packet_get_int(); + break; + } else { + log("parse_tty_modes: unknown opcode %d", opcode); + goto set; + } + } + } + } + +set: + if (*n_bytes_ptr != n_bytes) { + *n_bytes_ptr = n_bytes; + log("parse_tty_modes: n_bytes_ptr != n_bytes: %d %d", + *n_bytes_ptr, n_bytes); + return; /* Don't process bytes passed */ + } + if (failure == -1) + return; /* Packet parsed ok but tcgetattr() failed */ + + /* Set the new modes for the terminal. */ + if (tcsetattr(fd, TCSANOW, &tio) == -1) + log("Setting tty modes failed: %.100s", strerror(errno)); +} diff --git a/usr/src/cmd/ssh/libssh/common/uidswap.c b/usr/src/cmd/ssh/libssh/common/uidswap.c new file mode 100644 index 0000000000..42868df057 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/uidswap.c @@ -0,0 +1,184 @@ +/* + * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Code for uid-swapping. + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: uidswap.c,v 1.23 2002/07/15 17:15:31 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "log.h" +#include "uidswap.h" + +/* + * Note: all these functions must work in all of the following cases: + * 1. euid=0, ruid=0 + * 2. euid=0, ruid!=0 + * 3. euid!=0, ruid!=0 + * Additionally, they must work regardless of whether the system has + * POSIX saved uids or not. + */ + +#if defined(_POSIX_SAVED_IDS) && !defined(BROKEN_SAVED_UIDS) +/* Lets assume that posix saved ids also work with seteuid, even though that + is not part of the posix specification. */ +#define SAVED_IDS_WORK +/* Saved effective uid. */ +static uid_t saved_euid = 0; +static gid_t saved_egid = 0; +#endif + +/* Saved effective uid. */ +static int privileged = 0; +static int temporarily_use_uid_effective = 0; +static gid_t saved_egroups[NGROUPS_MAX], user_groups[NGROUPS_MAX]; +static int saved_egroupslen = -1, user_groupslen = -1; + +/* + * Temporarily changes to the given uid. If the effective user + * id is not root, this does nothing. This call cannot be nested. + */ +void +temporarily_use_uid(struct passwd *pw) +{ + /* Save the current euid, and egroups. */ +#ifdef SAVED_IDS_WORK + saved_euid = geteuid(); + saved_egid = getegid(); + debug("temporarily_use_uid: %u/%u (e=%u/%u)", + (u_int)pw->pw_uid, (u_int)pw->pw_gid, + (u_int)saved_euid, (u_int)saved_egid); + if (saved_euid != 0) { + privileged = 0; + return; + } +#else + if (geteuid() != 0) { + privileged = 0; + return; + } +#endif /* SAVED_IDS_WORK */ + + privileged = 1; + temporarily_use_uid_effective = 1; + saved_egroupslen = getgroups(NGROUPS_MAX, saved_egroups); + if (saved_egroupslen < 0) + fatal("getgroups: %.100s", strerror(errno)); + + /* set and save the user's groups */ + if (user_groupslen == -1) { + if (initgroups(pw->pw_name, pw->pw_gid) < 0) + fatal("initgroups: %s: %.100s", pw->pw_name, + strerror(errno)); + user_groupslen = getgroups(NGROUPS_MAX, user_groups); + if (user_groupslen < 0) + fatal("getgroups: %.100s", strerror(errno)); + } + /* Set the effective uid to the given (unprivileged) uid. */ + if (setgroups(user_groupslen, user_groups) < 0) + fatal("setgroups: %.100s", strerror(errno)); +#ifdef SAVED_IDS_WORK + /* Set saved gid and set real gid */ + if (setregid(pw->pw_gid, -1) == -1) + debug("setregid(%u, -1): %.100s", (uint_t)pw->pw_gid, strerror(errno)); + /* Set saved uid and set real uid */ + if (setreuid(pw->pw_uid, -1) == -1) + debug("setreuid(%u, -1): %.100s", (uint_t)pw->pw_uid, strerror(errno)); +#else + /* Propagate the privileged gid to all of our gids. */ + if (setgid(getegid()) < 0) + debug("setgid %u: %.100s", (u_int) getegid(), strerror(errno)); + /* Propagate the privileged uid to all of our uids. */ + if (setuid(geteuid()) < 0) + debug("setuid %u: %.100s", (u_int) geteuid(), strerror(errno)); +#endif /* SAVED_IDS_WORK */ + /* Set effective gid */ + if (setegid(pw->pw_gid) == -1) + fatal("setegid %u: %.100s", (u_int)pw->pw_uid, + strerror(errno)); + /* Set effective uid */ + if (seteuid(pw->pw_uid) == -1) + fatal("seteuid %u: %.100s", (u_int)pw->pw_uid, + strerror(errno)); + /* + * If saved set ids work then + * + * ruid == euid == pw->pw_uid + * saved uid = previous euid + * rgid == egid == pw->pw_gid + * saved gid = previous egid + */ +} + +/* + * Restores to the original (privileged) uid. + */ +void +restore_uid(void) +{ + /* it's a no-op unless privileged */ + if (!privileged) { + debug("restore_uid: (unprivileged)"); + return; + } + if (!temporarily_use_uid_effective) + fatal("restore_uid: temporarily_use_uid not effective"); + +#ifdef SAVED_IDS_WORK + debug("restore_uid: %u/%u", (u_int)saved_euid, (u_int)saved_egid); + /* Set the effective uid back to the saved privileged uid. */ + if (seteuid(saved_euid) < 0) + fatal("seteuid %u: %.100s", (u_int)saved_euid, strerror(errno)); + if (setuid(saved_euid) < 0) + fatal("setuid %u: %.100s", (u_int)saved_euid, strerror(errno)); + if (setegid(saved_egid) < 0) + fatal("setegid %u: %.100s", (u_int)saved_egid, strerror(errno)); + if (setgid(saved_egid) < 0) + fatal("setgid %u: %.100s", (u_int)saved_egid, strerror(errno)); +#else /* SAVED_IDS_WORK */ + /* + * We are unable to restore the real uid to its unprivileged value. + * Propagate the real uid (usually more privileged) to effective uid + * as well. + */ + setuid(getuid()); + setgid(getgid()); +#endif /* SAVED_IDS_WORK */ + + if (setgroups(saved_egroupslen, saved_egroups) < 0) + fatal("setgroups: %.100s", strerror(errno)); + temporarily_use_uid_effective = 0; +} + +/* + * Permanently sets all uids to the given uid. This cannot be + * called while temporarily_use_uid is effective. + */ +void +permanently_set_uid(struct passwd *pw) +{ + if (temporarily_use_uid_effective) + fatal("permanently_set_uid: temporarily_use_uid effective"); + debug("permanently_set_uid: %u/%u", (u_int)pw->pw_uid, + (u_int)pw->pw_gid); + if (initgroups(pw->pw_name, pw->pw_gid) < 0) + fatal("initgroups: %s: %.100s", pw->pw_name, + strerror(errno)); + if (setgid(pw->pw_gid) < 0) + fatal("setgid %u: %.100s", (u_int)pw->pw_gid, strerror(errno)); + if (setuid(pw->pw_uid) < 0) + fatal("setuid %u: %.100s", (u_int)pw->pw_uid, strerror(errno)); +} diff --git a/usr/src/cmd/ssh/libssh/common/uuencode.c b/usr/src/cmd/ssh/libssh/common/uuencode.c new file mode 100644 index 0000000000..30547a0c3a --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/uuencode.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "includes.h" +RCSID("$OpenBSD: uuencode.c,v 1.16 2002/09/09 14:54:15 markus Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "uuencode.h" + +int +uuencode(u_char *src, u_int srclength, + char *target, size_t targsize) +{ + return __b64_ntop(src, srclength, target, targsize); +} + +int +uudecode(const char *src, u_char *target, size_t targsize) +{ + int len; + char *encoded, *p; + + /* copy the 'readonly' source */ + encoded = xstrdup(src); + /* skip whitespace and data */ + for (p = encoded; *p == ' ' || *p == '\t'; p++) + ; + for (; *p != '\0' && *p != ' ' && *p != '\t'; p++) + ; + /* and remove trailing whitespace because __b64_pton needs this */ + *p = '\0'; + len = __b64_pton(encoded, target, targsize); + xfree(encoded); + return len; +} + +void +dump_base64(FILE *fp, u_char *data, u_int len) +{ + char *buf = xmalloc(2*len); + int i, n; + + n = uuencode(data, len, buf, 2*len); + for (i = 0; i < n; i++) { + fprintf(fp, "%c", buf[i]); + if (i % 70 == 69) + fprintf(fp, "\n"); + } + if (i % 70 != 69) + fprintf(fp, "\n"); + xfree(buf); +} diff --git a/usr/src/cmd/ssh/libssh/common/xlist.c b/usr/src/cmd/ssh/libssh/common/xlist.c new file mode 100644 index 0000000000..45a5611510 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/xlist.c @@ -0,0 +1,78 @@ + /* + * Copyright 2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include <stdio.h> +#include <strings.h> +#include "xmalloc.h" +#include "xlist.h" + +char ** +xsplit(char *list, char sep) +{ + char **a; + char *p, *q; + u_int n = 0; + + for (n = 0, p = list ; p && *p ; ) { + while (p && *p && *p == sep) p++; + if (!*p) break; + n++; + p = strchr(p, sep); + } + a = (char **) xmalloc(sizeof(char *) * (n + 2)); + for (n = 0, p = list ; p && *p ; ) { + while (*p == sep) p++; + if (!*p) break; + q = strchr(p, sep); + if (!q) + q = p + strlen(p); + a[n] = (char *) xmalloc((q - p + 2)); + (void) strncpy(a[n], p, q - p); + a[n][q - p] = '\0'; + n++; + if (!*q) break; + p = q+1; + } + a[n] = NULL; + return a; +} + +void +xfree_split_list(char **list) +{ + char **p; + for (p = list ; p && *p ; p++) { + xfree(*p); + } + xfree(list); +} + +char * +xjoin(char **alist, char sep) +{ + char **p; + char *list; + char sep_str[2]; + u_int n; + + for (n = 1, p = alist ; p && *p ; p++) { + if (!*p || !**p) continue; + n += strlen(*p) + 1; + } + list = (char *) xmalloc(n); + *list = '\0'; + + sep_str[0] = sep; + sep_str[1] = '\0'; + for (p = alist ; p && *p ; p++) { + if (!*p || !**p) continue; + if (*list != '\0') + (void) strlcat(list, sep_str, n); + (void) strlcat(list, *p, n); + } + return list; +} diff --git a/usr/src/cmd/ssh/libssh/common/xmalloc.c b/usr/src/cmd/ssh/libssh/common/xmalloc.c new file mode 100644 index 0000000000..ef11fce812 --- /dev/null +++ b/usr/src/cmd/ssh/libssh/common/xmalloc.c @@ -0,0 +1,70 @@ +/* + * Author: Tatu Ylonen <ylo@cs.hut.fi> + * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland + * All rights reserved + * Versions of malloc and friends that check their results, and never return + * failure (they call fatal if they encounter an error). + * + * As far as I am concerned, the code I have written for this software + * can be used freely for any purpose. Any derived versions of this + * software must be clearly marked as such, and if the derived work is + * incompatible with the protocol description in the RFC file, it must be + * called by a name other than "ssh" or "Secure Shell". + */ + +#include "includes.h" +RCSID("$OpenBSD: xmalloc.c,v 1.16 2001/07/23 18:21:46 stevesk Exp $"); + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "xmalloc.h" +#include "log.h" + +void * +xmalloc(size_t size) +{ + void *ptr; + + if (size == 0) + fatal("xmalloc: zero size"); + ptr = malloc(size); + if (ptr == NULL) + fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size); + return ptr; +} + +void * +xrealloc(void *ptr, size_t new_size) +{ + void *new_ptr; + + if (new_size == 0) + fatal("xrealloc: zero size"); + if (ptr == NULL) + new_ptr = malloc(new_size); + else + new_ptr = realloc(ptr, new_size); + if (new_ptr == NULL) + fatal("xrealloc: out of memory (new_size %lu bytes)", (u_long) new_size); + return new_ptr; +} + +void +xfree(void *ptr) +{ + if (ptr == NULL) + fatal("xfree: NULL pointer given as argument"); + free(ptr); +} + +char * +xstrdup(const char *str) +{ + size_t len; + char *cp; + + len = strlen(str) + 1; + cp = xmalloc(len); + strlcpy(cp, str, len); + return cp; +} |