#include "includes.h"
RCSID("$OpenBSD: session.c,v 1.108 2001/10/11 13:45:21 markus Exp $");
#include "ssh.h"
#include "ssh1.h"
#include "ssh2.h"
#include "xmalloc.h"
#include "sshpty.h"
#include "packet.h"
#include "buffer.h"
#include "mpaux.h"
#include "uidswap.h"
#include "compat.h"
#include "channels.h"
#include "bufaux.h"
#include "auth.h"
#include "auth-options.h"
#include "pathnames.h"
#include "log.h"
#include "servconf.h"
#include "sshlogin.h"
#include "serverloop.h"
#include "canohost.h"
#include "session.h"
#ifdef WITH_IRIX_PROJECT
#include <proj.h>
#endif
#ifdef WITH_IRIX_JOBS
#include <sys/resource.h>
#endif
#ifdef WITH_IRIX_AUDIT
#include <sat.h>
#endif
#if defined(HAVE_USERSEC_H)
#include <usersec.h>
#endif
#ifdef HAVE_CYGWIN
#include <windows.h>
#include <sys/cygwin.h>
#define is_winnt (GetVersion() < 0x80000000)
#endif
#if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
# define S_UFSIZE_HARD S_UFSIZE "_hard"
# define S_UCPU_HARD S_UCPU "_hard"
# define S_UDATA_HARD S_UDATA "_hard"
# define S_USTACK_HARD S_USTACK "_hard"
# define S_URSS_HARD S_URSS "_hard"
# define S_UCORE_HARD S_UCORE "_hard"
# define S_UNOFILE_HARD S_UNOFILE "_hard"
#endif
#ifdef _AIX
# include <uinfo.h>
#endif
#define TTYSZ 64
typedef struct Session Session;
struct Session {
int used;
int self;
struct passwd *pw;
Authctxt *authctxt;
pid_t pid;
char *term;
int ptyfd, ttyfd, ptymaster;
int row, col, xpixel, ypixel;
char tty[TTYSZ];
char *display;
int screen;
char *auth_proto;
char *auth_data;
int single_connection;
int chanid;
int is_subsystem;
};
Session *session_new(void);
void session_set_fds(Session *, int, int, int);
static void session_pty_cleanup(void *);
void session_proctitle(Session *);
int session_setup_x11fwd(Session *);
void do_exec_pty(Session *, const char *);
void do_exec_no_pty(Session *, const char *);
void do_exec(Session *, const char *);
void do_login(Session *, const char *);
#ifdef LOGIN_NEEDS_UTMPX
static void do_pre_login(Session *s);
#endif
void do_child(Session *, const char *);
void do_motd(void);
int check_quietlogin(Session *, const char *);
static void do_authenticated1(Authctxt *);
static void do_authenticated2(Authctxt *);
static void session_close(Session *);
static int session_pty_req(Session *);
extern ServerOptions options;
extern char *__progname;
extern int log_stderr;
extern int debug_flag;
extern u_int utmp_len;
extern int startup_pipe;
extern void destroy_sensitive_data(void);
const char *original_command = NULL;
#define MAX_SESSIONS 10
Session sessions[MAX_SESSIONS];
#ifdef WITH_AIXAUTHENTICATE
char *aixloginmsg;
#endif
#ifdef HAVE_LOGIN_CAP
static login_cap_t *lc;
#endif
void
do_authenticated(Authctxt *authctxt)
{
alarm(0);
if (startup_pipe != -1) {
close(startup_pipe);
startup_pipe = -1;
}
#if defined(HAVE_LOGIN_CAP) && defined(HAVE_PW_CLASS_IN_PASSWD)
if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
error("unable to get login class");
return;
}
#ifdef BSD_AUTH
if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
packet_disconnect("Approval failure for %s",
authctxt->pw->pw_name);
}
#endif
#endif
#ifdef WITH_AIXAUTHENTICATE
if (loginsuccess(authctxt->user,
get_canonical_hostname(options.reverse_mapping_check),
"ssh", &aixloginmsg) < 0)
aixloginmsg = NULL;
#endif
if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
channel_permit_all_opens();
if (compat20)
do_authenticated2(authctxt);
else
do_authenticated1(authctxt);
if (auth_get_socket_name())
auth_sock_cleanup_proc(authctxt->pw);
#ifdef KRB4
if (options.kerberos_ticket_cleanup)
krb4_cleanup_proc(authctxt);
#endif
#ifdef KRB5
if (options.kerberos_ticket_cleanup)
krb5_cleanup_proc(authctxt);
#endif
}
static void
do_authenticated1(Authctxt *authctxt)
{
Session *s;
char *command;
int success, type, plen, screen_flag;
int compression_level = 0, enable_compression_after_reply = 0;
u_int proto_len, data_len, dlen;
s = session_new();
s->authctxt = authctxt;
s->pw = authctxt->pw;
for (;;) {
success = 0;
type = packet_read(&plen);
switch (type) {
case SSH_CMSG_REQUEST_COMPRESSION:
packet_integrity_check(plen, 4, type);
compression_level = packet_get_int();
if (compression_level < 1 || compression_level > 9) {
packet_send_debug("Received illegal compression level %d.",
compression_level);
break;
}
enable_compression_after_reply = 1;
success = 1;
break;
case SSH_CMSG_REQUEST_PTY:
success = session_pty_req(s);
break;
case SSH_CMSG_X11_REQUEST_FORWARDING:
s->auth_proto = packet_get_string(&proto_len);
s->auth_data = packet_get_string(&data_len);
screen_flag = packet_get_protocol_flags() &
SSH_PROTOFLAG_SCREEN_NUMBER;
debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
if (packet_remaining() == 4) {
if (!screen_flag)
debug2("Buggy client: "
"X11 screen flag missing");
s->screen = packet_get_int();
} else {
s->screen = 0;
}
packet_done();
success = session_setup_x11fwd(s);
if (!success) {
xfree(s->auth_proto);
xfree(s->auth_data);
s->auth_proto = NULL;
s->auth_data = NULL;
}
break;
case SSH_CMSG_AGENT_REQUEST_FORWARDING:
if (no_agent_forwarding_flag || compat13) {
debug("Authentication agent forwarding not permitted for this authentication.");
break;
}
debug("Received authentication agent forwarding request.");
success = auth_input_request_forwarding(s->pw);
break;
case SSH_CMSG_PORT_FORWARD_REQUEST:
if (no_port_forwarding_flag) {
debug("Port forwarding not permitted for this authentication.");
break;
}
if (!options.allow_tcp_forwarding) {
debug("Port forwarding not permitted.");
break;
}
debug("Received TCP/IP port forwarding request.");
channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
success = 1;
break;
case SSH_CMSG_MAX_PACKET_SIZE:
if (packet_set_maxsize(packet_get_int()) > 0)
success = 1;
break;
#if defined(AFS) || defined(KRB5)
case SSH_CMSG_HAVE_KERBEROS_TGT:
if (!options.kerberos_tgt_passing) {
verbose("Kerberos TGT passing disabled.");
} else {
char *kdata = packet_get_string(&dlen);
packet_integrity_check(plen, 4 + dlen, type);
if (kdata[0] != 0x41) {
#ifdef KRB5
krb5_data tgt;
tgt.data = kdata;
tgt.length = dlen;
if (auth_krb5_tgt(s->authctxt, &tgt))
success = 1;
else
verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user);
#endif
} else {
#ifdef AFS
if (auth_krb4_tgt(s->authctxt, kdata))
success = 1;
else
verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user);
#endif
}
xfree(kdata);
}
break;
#endif
#ifdef AFS
case SSH_CMSG_HAVE_AFS_TOKEN:
if (!options.afs_token_passing || !k_hasafs()) {
verbose("AFS token passing disabled.");
} else {
char *token = packet_get_string(&dlen);
packet_integrity_check(plen, 4 + dlen, type);
if (auth_afs_token(s->authctxt, token))
success = 1;
else
verbose("AFS token refused for %.100s",
s->authctxt->user);
xfree(token);
}
break;
#endif
case SSH_CMSG_EXEC_SHELL:
case SSH_CMSG_EXEC_CMD:
if (type == SSH_CMSG_EXEC_CMD) {
command = packet_get_string(&dlen);
debug("Exec command '%.500s'", command);
do_exec(s, command);
xfree(command);
} else {
do_exec(s, NULL);
}
packet_done();
session_close(s);
return;
default:
log("Unknown packet type received after authentication: %d", type);
}
packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
packet_send();
packet_write_wait();
if (enable_compression_after_reply) {
enable_compression_after_reply = 0;
packet_start_compression(compression_level);
}
}
}
void
do_exec_no_pty(Session *s, const char *command)
{
int pid;
#ifdef USE_PIPES
int pin[2], pout[2], perr[2];
if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
packet_disconnect("Could not create pipes: %.100s",
strerror(errno));
#else
int inout[2], err[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
packet_disconnect("Could not create socket pairs: %.100s",
strerror(errno));
#endif
if (s == NULL)
fatal("do_exec_no_pty: no session");
session_proctitle(s);
#if defined(USE_PAM)
do_pam_session(s->pw->pw_name, NULL);
do_pam_setcred(1);
if (is_pam_password_change_required())
packet_disconnect("Password change required but no "
"TTY available");
#endif
if ((pid = fork()) == 0) {
log_init(__progname, options.log_level, options.log_facility, log_stderr);
if (setsid() < 0)
error("setsid failed: %.100s", strerror(errno));
#ifdef USE_PIPES
close(pin[1]);
if (dup2(pin[0], 0) < 0)
perror("dup2 stdin");
close(pin[0]);
close(pout[0]);
if (dup2(pout[1], 1) < 0)
perror("dup2 stdout");
close(pout[1]);
close(perr[0]);
if (dup2(perr[1], 2) < 0)
perror("dup2 stderr");
close(perr[1]);
#else
close(inout[1]);
close(err[1]);
if (dup2(inout[0], 0) < 0)
perror("dup2 stdin");
if (dup2(inout[0], 1) < 0)
perror("dup2 stdout");
if (dup2(err[0], 2) < 0)
perror("dup2 stderr");
#endif
do_child(s, command);
}
#ifdef HAVE_CYGWIN
if (is_winnt)
cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
#endif
if (pid < 0)
packet_disconnect("fork failed: %.100s", strerror(errno));
s->pid = pid;
packet_set_interactive(s->display != NULL);
#ifdef USE_PIPES
close(pin[0]);
close(pout[1]);
close(perr[1]);
if (compat20) {
session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
} else {
server_loop(pid, pin[1], pout[0], perr[0]);
}
#else
close(inout[0]);
close(err[0]);
if (compat20) {
session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
} else {
server_loop(pid, inout[1], inout[1], err[1]);
}
#endif
}
void
do_exec_pty(Session *s, const char *command)
{
int fdout, ptyfd, ttyfd, ptymaster;
pid_t pid;
if (s == NULL)
fatal("do_exec_pty: no session");
ptyfd = s->ptyfd;
ttyfd = s->ttyfd;
#if defined(USE_PAM)
do_pam_session(s->pw->pw_name, s->tty);
do_pam_setcred(1);
#endif
if ((pid = fork()) == 0) {
log_init(__progname, options.log_level, options.log_facility, log_stderr);
close(ptyfd);
pty_make_controlling_tty(&ttyfd, s->tty);
if (dup2(ttyfd, 0) < 0)
error("dup2 stdin: %s", strerror(errno));
if (dup2(ttyfd, 1) < 0)
error("dup2 stdout: %s", strerror(errno));
if (dup2(ttyfd, 2) < 0)
error("dup2 stderr: %s", strerror(errno));
close(ttyfd);
#ifndef HAVE_OSF_SIA
if (!(options.use_login && command == NULL))
do_login(s, command);
# ifdef LOGIN_NEEDS_UTMPX
else
do_pre_login(s);
# endif
#endif
do_child(s, command);
}
#ifdef HAVE_CYGWIN
if (is_winnt)
cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
#endif
if (pid < 0)
packet_disconnect("fork failed: %.100s", strerror(errno));
s->pid = pid;
close(ttyfd);
fdout = dup(ptyfd);
if (fdout < 0)
packet_disconnect("dup #1 failed: %.100s", strerror(errno));
ptymaster = dup(ptyfd);
if (ptymaster < 0)
packet_disconnect("dup #2 failed: %.100s", strerror(errno));
s->ptymaster = ptymaster;
packet_set_interactive(1);
if (compat20) {
session_set_fds(s, ptyfd, fdout, -1);
} else {
server_loop(pid, ptyfd, fdout, -1);
}
}
#ifdef LOGIN_NEEDS_UTMPX
static void
do_pre_login(Session *s)
{
socklen_t fromlen;
struct sockaddr_storage from;
pid_t pid = getpid();
memset(&from, 0, sizeof(from));
if (packet_connection_is_on_socket()) {
fromlen = sizeof(from);
if (getpeername(packet_get_connection_in(),
(struct sockaddr *) & from, &fromlen) < 0) {
debug("getpeername: %.100s", strerror(errno));
fatal_cleanup();
}
}
record_utmp_only(pid, s->tty, s->pw->pw_name,
get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
(struct sockaddr *)&from);
}
#endif
void
do_exec(Session *s, const char *command)
{
if (forced_command) {
original_command = command;
command = forced_command;
debug("Forced command '%.900s'", command);
}
if (s->ttyfd != -1)
do_exec_pty(s, command);
else
do_exec_no_pty(s, command);
original_command = NULL;
}
void
do_login(Session *s, const char *command)
{
char *time_string;
char hostname[MAXHOSTNAMELEN];
socklen_t fromlen;
struct sockaddr_storage from;
time_t last_login_time;
struct passwd * pw = s->pw;
pid_t pid = getpid();
memset(&from, 0, sizeof(from));
if (packet_connection_is_on_socket()) {
fromlen = sizeof(from);
if (getpeername(packet_get_connection_in(),
(struct sockaddr *) & from, &fromlen) < 0) {
debug("getpeername: %.100s", strerror(errno));
fatal_cleanup();
}
}
if (options.print_lastlog) {
hostname[0] = '\0';
last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
hostname, sizeof(hostname));
}
record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
(struct sockaddr *)&from);
#ifdef USE_PAM
if (is_pam_password_change_required()) {
print_pam_messages();
do_pam_chauthtok();
}
#endif
if (check_quietlogin(s, command))
return;
#ifdef USE_PAM
if (!is_pam_password_change_required())
print_pam_messages();
#endif
#ifdef WITH_AIXAUTHENTICATE
if (aixloginmsg && *aixloginmsg)
printf("%s\n", aixloginmsg);
#endif
if (options.print_lastlog && last_login_time != 0) {
time_string = ctime(&last_login_time);
if (strchr(time_string, '\n'))
*strchr(time_string, '\n') = 0;
if (strcmp(hostname, "") == 0)
printf("Last login: %s\r\n", time_string);
else
printf("Last login: %s from %s\r\n", time_string, hostname);
}
do_motd();
}
void
do_motd(void)
{
FILE *f;
char buf[256];
if (options.print_motd) {
#ifdef HAVE_LOGIN_CAP
f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
"/etc/motd"), "r");
#else
f = fopen("/etc/motd", "r");
#endif
if (f) {
while (fgets(buf, sizeof(buf), f))
fputs(buf, stdout);
fclose(f);
}
}
}
int
check_quietlogin(Session *s, const char *command)
{
char buf[256];
struct passwd *pw = s->pw;
struct stat st;
if (command != NULL)
return 1;
snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
return 1;
#else
if (stat(buf, &st) >= 0)
return 1;
#endif
return 0;
}
static void
child_set_env(char ***envp, u_int *envsizep, const char *name,
const char *value)
{
u_int i, namelen;
char **env;
env = *envp;
namelen = strlen(name);
for (i = 0; env[i]; i++)
if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
break;
if (env[i]) {
xfree(env[i]);
} else {
if (i >= (*envsizep) - 1) {
(*envsizep) += 50;
env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
}
env[i + 1] = NULL;
}
env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
}
static void
read_environment_file(char ***env, u_int *envsize,
const char *filename)
{
FILE *f;
char buf[4096];
char *cp, *value;
f = fopen(filename, "r");
if (!f)
return;
while (fgets(buf, sizeof(buf), f)) {
for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
;
if (!*cp || *cp == '#' || *cp == '\n')
continue;
if (strchr(cp, '\n'))
*strchr(cp, '\n') = '\0';
value = strchr(cp, '=');
if (value == NULL) {
fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
continue;
}
*value = '\0';
value++;
child_set_env(env, envsize, cp, value);
}
fclose(f);
}
#ifdef USE_PAM
void do_pam_environment(char ***env, u_int *envsize)
{
char *equals, var_name[512], var_val[512];
char **pam_env;
int i;
if ((pam_env = fetch_pam_environment()) == NULL)
return;
for(i = 0; pam_env[i] != NULL; i++) {
if ((equals = strstr(pam_env[i], "=")) == NULL)
continue;
if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
memset(var_name, '\0', sizeof(var_name));
memset(var_val, '\0', sizeof(var_val));
strncpy(var_name, pam_env[i], equals - pam_env[i]);
strcpy(var_val, equals + 1);
debug3("PAM environment: %s=%s", var_name, var_val);
child_set_env(env, envsize, var_name, var_val);
}
}
}
#endif
#ifdef HAVE_CYGWIN
void copy_environment(char ***env, u_int *envsize)
{
char *equals, var_name[512], var_val[512];
int i;
for(i = 0; environ[i] != NULL; i++) {
if ((equals = strstr(environ[i], "=")) == NULL)
continue;
if (strlen(environ[i]) < (sizeof(var_name) - 1)) {
memset(var_name, '\0', sizeof(var_name));
memset(var_val, '\0', sizeof(var_val));
strncpy(var_name, environ[i], equals - environ[i]);
strcpy(var_val, equals + 1);
debug3("Copy environment: %s=%s", var_name, var_val);
child_set_env(env, envsize, var_name, var_val);
}
}
}
#endif
#if defined(HAVE_GETUSERATTR)
void set_limit(char *user, char *soft, char *hard, int resource, int mult)
{
struct rlimit rlim;
int slim, hlim;
getrlimit(resource, &rlim);
slim = 0;
if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
if (slim < 0) {
rlim.rlim_cur = RLIM_INFINITY;
} else if (slim != 0) {
if (rlim.rlim_cur == slim * mult)
slim = 0;
else
rlim.rlim_cur = slim * mult;
}
}
hlim = 0;
if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
if (hlim < 0) {
rlim.rlim_max = RLIM_INFINITY;
} else if (hlim != 0) {
rlim.rlim_max = hlim * mult;
}
}
if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
&& hlim == 0 && slim != 0)
rlim.rlim_max = rlim.rlim_cur;
else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
rlim.rlim_cur = rlim.rlim_max;
else if (rlim.rlim_cur > rlim.rlim_max)
rlim.rlim_max = rlim.rlim_cur;
if (setrlimit(resource, &rlim) != 0)
error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
}
void set_limits_from_userattr(char *user)
{
int mask;
char buf[16];
set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
#if defined(S_UNOFILE)
set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
#endif
if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
(void) snprintf(buf, sizeof(buf), "%d", mask);
if (sscanf(buf, "%o", &mask) == 1)
umask(mask);
}
}
#endif
void
do_child(Session *s, const char *command)
{
const char *shell, *hostname = NULL, *cp = NULL;
struct passwd *pw = s->pw;
char buf[256];
char cmd[1024];
FILE *f = NULL;
u_int envsize, i;
char **env;
extern char **environ;
struct stat st;
char *argv[10];
int do_xauth;
#ifdef WITH_IRIX_PROJECT
prid_t projid;
#endif
#ifdef WITH_IRIX_JOBS
jid_t jid = 0;
#else
#ifdef WITH_IRIX_ARRAY
int jid = 0;
#endif
#endif
do_xauth =
s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
destroy_sensitive_data();
if (options.use_login && command != NULL)
options.use_login = 0;
#if !defined(HAVE_OSF_SIA)
if (!options.use_login) {
# ifdef HAVE_LOGIN_CAP
if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
_PATH_NOLOGIN), "r");
# else
if (pw->pw_uid)
f = fopen(_PATH_NOLOGIN, "r");
# endif
if (f) {
while (fgets(buf, sizeof(buf), f))
fputs(buf, stderr);
fclose(f);
exit(254);
}
}
#endif
if (!options.use_login) {
#ifdef HAVE_OSF_SIA
session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty);
if (!check_quietlogin(s, command))
do_motd();
#else
#ifdef HAVE_CYGWIN
if (is_winnt) {
#else
if (getuid() == 0 || geteuid() == 0) {
#endif
# ifdef HAVE_GETUSERATTR
set_limits_from_userattr(pw->pw_name);
# endif
# ifdef HAVE_LOGIN_CAP
if (setusercontext(lc, pw, pw->pw_uid,
(LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
perror("unable to set user context");
exit(1);
}
# else
#if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
if (getluid() == -1 && setluid(pw->pw_uid) == -1)
error("setluid: %s", strerror(errno));
#endif
if (setlogin(pw->pw_name) < 0)
error("setlogin failed: %s", strerror(errno));
if (setgid(pw->pw_gid) < 0) {
perror("setgid");
exit(1);
}
if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
perror("initgroups");
exit(1);
}
endgrent();
# ifdef USE_PAM
do_pam_setcred(0);
# endif
# ifdef WITH_IRIX_JOBS
jid = jlimit_startjob(pw->pw_name, pw->pw_uid, "interactive");
if (jid == -1) {
fatal("Failed to create job container: %.100s",
strerror(errno));
}
# endif
# ifdef WITH_IRIX_ARRAY
if (jid == 0) {
if (newarraysess() != 0)
fatal("Failed to set up new array session: %.100s",
strerror(errno));
}
# endif
# ifdef WITH_IRIX_PROJECT
if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
debug("Failed to get project id, using projid 0");
projid = 0;
}
if (setprid(projid))
fatal("Failed to initialize project %d for %s: %.100s",
(int)projid, pw->pw_name, strerror(errno));
# endif
#ifdef WITH_IRIX_AUDIT
if (sysconf(_SC_AUDIT)) {
debug("Setting sat id to %d", (int) pw->pw_uid);
if (satsetid(pw->pw_uid))
debug("error setting satid: %.100s", strerror(errno));
}
#endif
#ifdef _AIX
if (s->ttyfd == -1)
s->tty[0] = '\0';
cp = xmalloc(22 + strlen(s->tty) +
2 * strlen(pw->pw_name));
i = sprintf(cp, "LOGNAME=%s%cNAME=%s%cTTY=%s%c%c",
pw->pw_name, 0, pw->pw_name, 0, s->tty, 0, 0);
if (usrinfo(SETUINFO, cp, i) == -1)
fatal("Couldn't set usrinfo: %s",
strerror(errno));
debug3("AIX/UsrInfo: set len %d", i);
xfree(cp);
#endif
permanently_set_uid(pw);
# endif
}
#endif
#ifdef HAVE_CYGWIN
if (is_winnt)
#endif
if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
}
shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
#ifdef HAVE_LOGIN_CAP
shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
#endif
envsize = 100;
env = xmalloc(envsize * sizeof(char *));
env[0] = NULL;
#ifdef HAVE_CYGWIN
copy_environment(&env, &envsize);
#endif
if (!options.use_login) {
child_set_env(&env, &envsize, "USER", pw->pw_name);
child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
child_set_env(&env, &envsize, "HOME", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
(void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
child_set_env(&env, &envsize, "PATH", getenv("PATH"));
#else
# ifndef HAVE_CYGWIN
child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
# endif
#endif
snprintf(buf, sizeof buf, "%.200s/%.50s",
_PATH_MAILDIR, pw->pw_name);
child_set_env(&env, &envsize, "MAIL", buf);
child_set_env(&env, &envsize, "SHELL", shell);
}
if (getenv("TZ"))
child_set_env(&env, &envsize, "TZ", getenv("TZ"));
if (!options.use_login) {
while (custom_environment) {
struct envstring *ce = custom_environment;
char *s = ce->s;
int i;
for (i = 0; s[i] != '=' && s[i]; i++)
;
if (s[i] == '=') {
s[i] = 0;
child_set_env(&env, &envsize, s, s + i + 1);
}
custom_environment = ce->next;
xfree(ce->s);
xfree(ce);
}
}
snprintf(buf, sizeof buf, "%.50s %d %d",
get_remote_ipaddr(), get_remote_port(), get_local_port());
child_set_env(&env, &envsize, "SSH_CLIENT", buf);
if (s->ttyfd != -1)
child_set_env(&env, &envsize, "SSH_TTY", s->tty);
if (s->term)
child_set_env(&env, &envsize, "TERM", s->term);
if (s->display)
child_set_env(&env, &envsize, "DISPLAY", s->display);
if (original_command)
child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
original_command);
#ifdef _AIX
if ((cp = getenv("AUTHSTATE")) != NULL)
child_set_env(&env, &envsize, "AUTHSTATE", cp);
if ((cp = getenv("KRB5CCNAME")) != NULL)
child_set_env(&env, &envsize, "KRB5CCNAME", cp);
read_environment_file(&env, &envsize, "/etc/environment");
#endif
#ifdef KRB4
if (s->authctxt->krb4_ticket_file)
child_set_env(&env, &envsize, "KRBTKFILE",
s->authctxt->krb4_ticket_file);
#endif
#ifdef KRB5
if (s->authctxt->krb5_ticket_file)
child_set_env(&env, &envsize, "KRB5CCNAME",
s->authctxt->krb5_ticket_file);
#endif
#ifdef USE_PAM
do_pam_environment(&env, &envsize);
#endif
if (auth_get_socket_name() != NULL)
child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
auth_get_socket_name());
if (!options.use_login) {
snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
pw->pw_dir);
read_environment_file(&env, &envsize, buf);
}
if (debug_flag) {
fprintf(stderr, "Environment:\n");
for (i = 0; env[i]; i++)
fprintf(stderr, " %.200s\n", env[i]);
}
if (options.use_login)
hostname = get_remote_name_or_ip(utmp_len,
options.reverse_mapping_check);
if (packet_get_connection_in() == packet_get_connection_out())
close(packet_get_connection_in());
else {
close(packet_get_connection_in());
close(packet_get_connection_out());
}
channel_close_all();
endpwent();
for (i = 3; i < 64; i++)
close(i);
environ = env;
#ifdef AFS
if (k_hasafs()) {
char cell[64];
if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
krb_afslog(cell, 0);
krb_afslog(0, 0);
}
#endif
if (chdir(pw->pw_dir) < 0) {
fprintf(stderr, "Could not chdir to home directory %s: %s\n",
pw->pw_dir, strerror(errno));
#ifdef HAVE_LOGIN_CAP
if (login_getcapbool(lc, "requirehome", 0))
exit(1);
#endif
}
if (!options.use_login) {
if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
if (debug_flag)
fprintf(stderr, "Running %s\n", cmd);
f = popen(cmd, "w");
if (f) {
if (do_xauth)
fprintf(f, "%s %s\n", s->auth_proto,
s->auth_data);
pclose(f);
} else
fprintf(stderr, "Could not run %s\n",
_PATH_SSH_USER_RC);
} else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
if (debug_flag)
fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
_PATH_SSH_SYSTEM_RC);
f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
if (f) {
if (do_xauth)
fprintf(f, "%s %s\n", s->auth_proto,
s->auth_data);
pclose(f);
} else
fprintf(stderr, "Could not run %s\n",
_PATH_SSH_SYSTEM_RC);
} else if (do_xauth && options.xauth_location != NULL) {
char *screen = strchr(s->display, ':');
if (debug_flag) {
fprintf(stderr,
"Running %.100s add "
"%.100s %.100s %.100s\n",
options.xauth_location, s->display,
s->auth_proto, s->auth_data);
if (screen != NULL)
fprintf(stderr,
"Adding %.*s/unix%s %s %s\n",
(int)(screen - s->display),
s->display, screen,
s->auth_proto, s->auth_data);
}
snprintf(cmd, sizeof cmd, "%s -q -",
options.xauth_location);
f = popen(cmd, "w");
if (f) {
fprintf(f, "add %s %s %s\n", s->display,
s->auth_proto, s->auth_data);
if (screen != NULL)
fprintf(f, "add %.*s/unix%s %s %s\n",
(int)(screen - s->display),
s->display, screen,
s->auth_proto,
s->auth_data);
pclose(f);
} else {
fprintf(stderr, "Could not run %s\n",
cmd);
}
}
cp = strrchr(shell, '/');
if (cp)
cp++;
else
cp = shell;
}
signal(SIGPIPE, SIG_DFL);
if (!command) {
if (!options.use_login) {
char buf[256];
buf[0] = '-';
strncpy(buf + 1, cp, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
argv[0] = buf;
argv[1] = NULL;
execve(shell, argv, env);
perror(shell);
exit(1);
} else {
execl(LOGIN_PROGRAM, "login", "-h", hostname,
#ifdef LOGIN_NEEDS_TERM
s->term? s->term : "unknown",
#endif
"-p", "-f", "--", pw->pw_name, (char *)NULL);
perror("login");
exit(1);
}
}
argv[0] = (char *) cp;
argv[1] = "-c";
argv[2] = (char *) command;
argv[3] = NULL;
execve(shell, argv, env);
perror(shell);
exit(1);
}
Session *
session_new(void)
{
int i;
static int did_init = 0;
if (!did_init) {
debug("session_new: init");
for(i = 0; i < MAX_SESSIONS; i++) {
sessions[i].used = 0;
}
did_init = 1;
}
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
if (! s->used) {
memset(s, 0, sizeof(*s));
s->chanid = -1;
s->ptyfd = -1;
s->ttyfd = -1;
s->used = 1;
s->self = i;
debug("session_new: session %d", i);
return s;
}
}
return NULL;
}
static void
session_dump(void)
{
int i;
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
debug("dump: used %d session %d %p channel %d pid %d",
s->used,
s->self,
s,
s->chanid,
s->pid);
}
}
int
session_open(Authctxt *authctxt, int chanid)
{
Session *s = session_new();
debug("session_open: channel %d", chanid);
if (s == NULL) {
error("no more sessions");
return 0;
}
s->authctxt = authctxt;
s->pw = authctxt->pw;
if (s->pw == NULL)
fatal("no user for session %d", s->self);
debug("session_open: session %d: link with channel %d", s->self, chanid);
s->chanid = chanid;
return 1;
}
static Session *
session_by_channel(int id)
{
int i;
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
if (s->used && s->chanid == id) {
debug("session_by_channel: session %d channel %d", i, id);
return s;
}
}
debug("session_by_channel: unknown channel %d", id);
session_dump();
return NULL;
}
static Session *
session_by_pid(pid_t pid)
{
int i;
debug("session_by_pid: pid %d", pid);
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
if (s->used && s->pid == pid)
return s;
}
error("session_by_pid: unknown pid %d", pid);
session_dump();
return NULL;
}
static int
session_window_change_req(Session *s)
{
s->col = packet_get_int();
s->row = packet_get_int();
s->xpixel = packet_get_int();
s->ypixel = packet_get_int();
packet_done();
pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
return 1;
}
static int
session_pty_req(Session *s)
{
u_int len;
int n_bytes;
if (no_pty_flag) {
debug("Allocating a pty not permitted for this authentication.");
return 0;
}
if (s->ttyfd != -1) {
packet_disconnect("Protocol error: you already have a pty.");
return 0;
}
s->term = packet_get_string(&len);
if (compat20) {
s->col = packet_get_int();
s->row = packet_get_int();
} else {
s->row = packet_get_int();
s->col = packet_get_int();
}
s->xpixel = packet_get_int();
s->ypixel = packet_get_int();
if (strcmp(s->term, "") == 0) {
xfree(s->term);
s->term = NULL;
}
debug("Allocating pty.");
if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
if (s->term)
xfree(s->term);
s->term = NULL;
s->ptyfd = -1;
s->ttyfd = -1;
error("session_pty_req: session %d alloc failed", s->self);
return 0;
}
debug("session_pty_req: session %d alloc %s", s->self, s->tty);
if (!compat20)
n_bytes = packet_remaining();
tty_parse_modes(s->ttyfd, &n_bytes);
fatal_add_cleanup(session_pty_cleanup, (void *)s);
pty_setowner(s->pw, s->tty);
pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
packet_done();
session_proctitle(s);
return 1;
}
static int
session_subsystem_req(Session *s)
{
struct stat st;
u_int len;
int success = 0;
char *cmd, *subsys = packet_get_string(&len);
int i;
packet_done();
log("subsystem request for %s", subsys);
for (i = 0; i < options.num_subsystems; i++) {
if (strcmp(subsys, options.subsystem_name[i]) == 0) {
cmd = options.subsystem_command[i];
if (stat(cmd, &st) < 0) {
error("subsystem: cannot stat %s: %s", cmd,
strerror(errno));
break;
}
debug("subsystem: exec() %s", cmd);
s->is_subsystem = 1;
do_exec(s, cmd);
success = 1;
}
}
if (!success)
log("subsystem request for %s failed, subsystem not found",
subsys);
xfree(subsys);
return success;
}
static int
session_x11_req(Session *s)
{
int success;
s->single_connection = packet_get_char();
s->auth_proto = packet_get_string(NULL);
s->auth_data = packet_get_string(NULL);
s->screen = packet_get_int();
packet_done();
success = session_setup_x11fwd(s);
if (!success) {
xfree(s->auth_proto);
xfree(s->auth_data);
s->auth_proto = NULL;
s->auth_data = NULL;
}
return success;
}
static int
session_shell_req(Session *s)
{
packet_done();
do_exec(s, NULL);
return 1;
}
static int
session_exec_req(Session *s)
{
u_int len;
char *command = packet_get_string(&len);
packet_done();
do_exec(s, command);
xfree(command);
return 1;
}
static int
session_auth_agent_req(Session *s)
{
static int called = 0;
packet_done();
if (no_agent_forwarding_flag) {
debug("session_auth_agent_req: no_agent_forwarding_flag");
return 0;
}
if (called) {
return 0;
} else {
called = 1;
return auth_input_request_forwarding(s->pw);
}
}
void
session_input_channel_req(int id, void *arg)
{
u_int len;
int reply;
int success = 0;
char *rtype;
Session *s;
Channel *c;
rtype = packet_get_string(&len);
reply = packet_get_char();
s = session_by_channel(id);
if (s == NULL)
fatal("session_input_channel_req: channel %d: no session", id);
c = channel_lookup(id);
if (c == NULL)
fatal("session_input_channel_req: channel %d: bad channel", id);
debug("session_input_channel_req: session %d channel %d request %s reply %d",
s->self, id, rtype, reply);
if (c->type == SSH_CHANNEL_LARVAL) {
if (strcmp(rtype, "shell") == 0) {
success = session_shell_req(s);
} else if (strcmp(rtype, "exec") == 0) {
success = session_exec_req(s);
} else if (strcmp(rtype, "pty-req") == 0) {
success = session_pty_req(s);
} else if (strcmp(rtype, "x11-req") == 0) {
success = session_x11_req(s);
} else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
success = session_auth_agent_req(s);
} else if (strcmp(rtype, "subsystem") == 0) {
success = session_subsystem_req(s);
}
}
if (strcmp(rtype, "window-change") == 0) {
success = session_window_change_req(s);
}
if (reply) {
packet_start(success ?
SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
packet_put_int(c->remote_id);
packet_send();
}
xfree(rtype);
}
void
session_set_fds(Session *s, int fdin, int fdout, int fderr)
{
if (!compat20)
fatal("session_set_fds: called for proto != 2.0");
if (s->chanid == -1)
fatal("no channel for session %d", s->self);
channel_set_fds(s->chanid,
fdout, fdin, fderr,
fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1);
}
static void
session_pty_cleanup(void *session)
{
Session *s = session;
if (s == NULL) {
error("session_pty_cleanup: no session");
return;
}
if (s->ttyfd == -1)
return;
debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
if (s->pid != 0)
record_logout(s->pid, s->tty);
pty_release(s->tty);
if (close(s->ptymaster) < 0)
error("close(s->ptymaster): %s", strerror(errno));
s->ttyfd = -1;
}
static void
session_exit_message(Session *s, int status)
{
Channel *c;
if (s == NULL)
fatal("session_close: no session");
c = channel_lookup(s->chanid);
if (c == NULL)
fatal("session_exit_message: session %d: no channel %d",
s->self, s->chanid);
debug("session_exit_message: session %d channel %d pid %d",
s->self, s->chanid, s->pid);
if (WIFEXITED(status)) {
channel_request_start(s->chanid,
"exit-status", 0);
packet_put_int(WEXITSTATUS(status));
packet_send();
} else if (WIFSIGNALED(status)) {
channel_request_start(s->chanid,
"exit-signal", 0);
packet_put_int(WTERMSIG(status));
#ifdef WCOREDUMP
packet_put_char(WCOREDUMP(status));
#else
packet_put_char(0);
#endif
packet_put_cstring("");
packet_put_cstring("");
packet_send();
} else {
packet_disconnect("wait returned status %04x.", status);
}
debug("session_exit_message: release channel %d", s->chanid);
channel_cancel_cleanup(s->chanid);
if (c->ostate != CHAN_OUTPUT_CLOSED)
chan_write_failed(c);
s->chanid = -1;
}
static void
session_close(Session *s)
{
debug("session_close: session %d pid %d", s->self, s->pid);
if (s->ttyfd != -1) {
fatal_remove_cleanup(session_pty_cleanup, (void *)s);
session_pty_cleanup(s);
}
if (s->term)
xfree(s->term);
if (s->display)
xfree(s->display);
if (s->auth_data)
xfree(s->auth_data);
if (s->auth_proto)
xfree(s->auth_proto);
s->used = 0;
session_proctitle(s);
}
void
session_close_by_pid(pid_t pid, int status)
{
Session *s = session_by_pid(pid);
if (s == NULL) {
debug("session_close_by_pid: no session for pid %d", pid);
return;
}
if (s->chanid != -1)
session_exit_message(s, status);
session_close(s);
}
void
session_close_by_channel(int id, void *arg)
{
Session *s = session_by_channel(id);
if (s == NULL) {
debug("session_close_by_channel: no session for id %d", id);
return;
}
debug("session_close_by_channel: channel %d child %d", id, s->pid);
if (s->pid != 0) {
debug("session_close_by_channel: channel %d: has child", id);
if (s->ttyfd != -1) {
fatal_remove_cleanup(session_pty_cleanup, (void *)s);
session_pty_cleanup(s);
}
return;
}
channel_cancel_cleanup(s->chanid);
s->chanid = -1;
session_close(s);
}
void
session_destroy_all(void)
{
int i;
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
if (s->used)
session_close(s);
}
}
static char *
session_tty_list(void)
{
static char buf[1024];
int i;
buf[0] = '\0';
for(i = 0; i < MAX_SESSIONS; i++) {
Session *s = &sessions[i];
if (s->used && s->ttyfd != -1) {
if (buf[0] != '\0')
strlcat(buf, ",", sizeof buf);
strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
}
}
if (buf[0] == '\0')
strlcpy(buf, "notty", sizeof buf);
return buf;
}
void
session_proctitle(Session *s)
{
if (s->pw == NULL)
error("no user for session %d", s->self);
else
setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
}
int
session_setup_x11fwd(Session *s)
{
struct stat st;
if (no_x11_forwarding_flag) {
packet_send_debug("X11 forwarding disabled in user configuration file.");
return 0;
}
if (!options.x11_forwarding) {
debug("X11 forwarding disabled in server configuration file.");
return 0;
}
if (!options.xauth_location ||
(stat(options.xauth_location, &st) == -1)) {
packet_send_debug("No xauth program; cannot forward with spoofing.");
return 0;
}
if (options.use_login) {
packet_send_debug("X11 forwarding disabled; "
"not compatible with UseLogin=yes.");
return 0;
}
if (s->display != NULL) {
debug("X11 display already set.");
return 0;
}
s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
if (s->display == NULL) {
debug("x11_create_display_inet failed.");
return 0;
}
return 1;
}
static void
do_authenticated2(Authctxt *authctxt)
{
server_loop2(authctxt);
}