diff options
Diffstat (limited to 'crypto/kerberosIV/appl/ftp/ftpd')
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/Makefile.in | 84 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/auth.c | 249 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/auth.h | 109 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/extern.h | 141 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/ftpcmd.y | 1408 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/ftpd.c | 2076 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/kauth.c | 325 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/krb4.c | 372 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/krb4.h | 61 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/logwtmp.c | 136 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/pathnames.h | 55 | ||||
-rw-r--r-- | crypto/kerberosIV/appl/ftp/ftpd/popen.c | 224 |
12 files changed, 5240 insertions, 0 deletions
diff --git a/crypto/kerberosIV/appl/ftp/ftpd/Makefile.in b/crypto/kerberosIV/appl/ftp/ftpd/Makefile.in new file mode 100644 index 0000000..55981de --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/Makefile.in @@ -0,0 +1,84 @@ +# +# $Id: Makefile.in,v 1.31 1997/05/02 17:49:27 assar Exp $ +# + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ + +topdir = ../../.. + +SHELL = /bin/sh + +CC = @CC@ +YACC = @YACC@ +RANLIB = @RANLIB@ +DEFS = @DEFS@ +CFLAGS = @CFLAGS@ +LD_FLAGS = @LD_FLAGS@ +LIBS = @LIBS@ +LIB_DBM = @LIB_DBM@ +MKINSTALLDIRS = $(top_srcdir)/mkinstalldirs + +INSTALL = @INSTALL@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ + +prefix = @prefix@ +exec_prefix = @exec_prefix@ +libdir = @libdir@ +libexecdir = @libexecdir@ +transform=@program_transform_name@ +EXECSUFFIX=@EXECSUFFIX@ + +ATHENA = ../../.. + +INCTOP = $(ATHENA)/include + +LIBTOP = $(ATHENA)/lib + +LIBKAFS = @KRB_KAFS_LIB@ +LIBKRB = -L$(LIBTOP)/krb -lkrb +LIBDES = -L$(LIBTOP)/des -ldes +LIBOTP = -L$(LIBTOP)/otp -lotp +LIBROKEN= -L$(LIBTOP)/roken -lroken + +PROGS = ftpd$(EXECSUFFIX) + +ftpd_SOURCES = ftpd.c ftpcmd.c logwtmp.c popen.c auth.c krb4.c kauth.c +ftpd_OBJS = ftpd.o ftpcmd.o logwtmp.o popen.o auth.o krb4.o kauth.o + +SOURCES = $(ftpd_SOURCES) +OBJECTS = $(ftpd_OBJS) + +all: $(PROGS) + +.c.o: + $(CC) -c $(CFLAGS) -I$(srcdir) -I$(srcdir)/../common -I$(INCTOP) $(DEFS) $< + +install: all + $(MKINSTALLDIRS) $(libexecdir) + for x in $(PROGS); do \ + $(INSTALL_PROGRAM) $$x $(libexecdir)/`echo $$x | sed '$(transform)'`; \ + done + +uninstall: + for x in $(PROGS); do \ + rm -f $(libexecdir)/`echo $$x | sed '$(transform)'`; \ + done + +ftpd$(EXECSUFFIX): $(ftpd_OBJS) + $(CC) $(LD_FLAGS) $(LDFLAGS) -o $@ $(ftpd_OBJS) -L../common -lcommon $(LIBKAFS) $(LIBKRB) $(LIBOTP) $(LIBDES) $(LIBROKEN) $(LIB_DBM) $(LIBS) $(LIBROKEN) + +ftpcmd.c: ftpcmd.y + $(YACC) $(YFLAGS) $< + chmod a-w y.tab.c + mv -f y.tab.c ftpcmd.c + +TAGS: $(SOURCES) + etags $(SOURCES) + +clean cleandir: + rm -f *~ *.o core ftpd ftpcmd.c \#* + +distclean: + rm -f Makefile diff --git a/crypto/kerberosIV/appl/ftp/ftpd/auth.c b/crypto/kerberosIV/appl/ftp/ftpd/auth.c new file mode 100644 index 0000000..862eb6d --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/auth.c @@ -0,0 +1,249 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +RCSID("$Id: auth.c,v 1.11 1997/05/04 23:09:00 assar Exp $"); +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#if defined(HAVE_SYS_IOCTL_H) && SunOS != 4 +#include <sys/ioctl.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#include "extern.h" +#include "krb4.h" +#include "auth.h" + +static struct at auth_types [] = { + { "KERBEROS_V4", krb4_auth, krb4_adat, krb4_pbsz, krb4_prot, krb4_ccc, + krb4_mic, krb4_conf, krb4_enc, krb4_read, krb4_write, krb4_userok, + krb4_vprintf }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0 } +}; + +struct at *ct; + +int data_protection; +int buffer_size; +unsigned char *data_buffer; +int auth_complete; + + +char *protection_names[] = { + "clear", "safe", + "confidential", "private" +}; + + +void auth_init(void) +{ +} + +char *ftp_command; +int prot_level; + +void new_ftp_command(char *command) +{ + ftp_command = command; +} + +void delete_ftp_command(void) +{ + if(ftp_command){ + free(ftp_command); + ftp_command = NULL; + } +} + +int auth_ok(void) +{ + return ct && auth_complete; +} + +void auth(char *auth) +{ + for(ct=auth_types; ct->name; ct++){ + if(!strcasecmp(auth, ct->name)){ + ct->auth(auth); + return; + } + } + reply(504, "%s is not a known security mechanism", auth); +} + +void adat(char *auth) +{ + if(ct && !auth_complete) + ct->adat(auth); + else + reply(503, "You must (re)issue an AUTH first."); +} + +void pbsz(int size) +{ + int old = buffer_size; + if(auth_ok()) + ct->pbsz(size); + else + reply(503, "Incomplete security data exchange."); + if(buffer_size != old){ + if(data_buffer) + free(data_buffer); + data_buffer = malloc(buffer_size + 4); + } +} + +void prot(char *pl) +{ + int p = -1; + + if(buffer_size == 0){ + reply(503, "No protection buffer size negotiated."); + return; + } + + if(!strcasecmp(pl, "C")) + p = prot_clear; + + if(!strcasecmp(pl, "S")) + p = prot_safe; + + if(!strcasecmp(pl, "E")) + p = prot_confidential; + + if(!strcasecmp(pl, "P")) + p = prot_private; + + if(p == -1){ + reply(504, "Unrecognized protection level."); + return; + } + + if(auth_ok()){ + if(ct->prot(p)){ + reply(536, "%s does not support %s protection.", + ct->name, protection_names[p]); + }else{ + data_protection = p; + reply(200, "Data protection is %s.", + protection_names[data_protection]); + } + }else{ + reply(503, "Incomplete security data exchange."); + } +} + +void ccc(void) +{ + if(auth_ok()){ + if(!ct->ccc()) + prot_level = prot_clear; + }else + reply(503, "Incomplete security data exchange."); +} + +void mic(char *msg) +{ + if(auth_ok()){ + if(!ct->mic(msg)) + prot_level = prot_safe; + }else + reply(503, "Incomplete security data exchange."); +} + +void conf(char *msg) +{ + if(auth_ok()){ + if(!ct->conf(msg)) + prot_level = prot_confidential; + }else + reply(503, "Incomplete security data exchange."); +} + +void enc(char *msg) +{ + if(auth_ok()){ + if(!ct->enc(msg)) + prot_level = prot_private; + }else + reply(503, "Incomplete security data exchange."); +} + +int auth_read(int fd, void *data, int length) +{ + if(auth_ok() && data_protection) + return ct->read(fd, data, length); + else + return read(fd, data, length); +} + +int auth_write(int fd, void *data, int length) +{ + if(auth_ok() && data_protection) + return ct->write(fd, data, length); + else + return write(fd, data, length); +} + +void auth_vprintf(const char *fmt, va_list ap) +{ + if(auth_ok() && prot_level){ + ct->vprintf(fmt, ap); + }else + vprintf(fmt, ap); +} + +void auth_printf(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + auth_vprintf(fmt, ap); + va_end(ap); +} diff --git a/crypto/kerberosIV/appl/ftp/ftpd/auth.h b/crypto/kerberosIV/appl/ftp/ftpd/auth.h new file mode 100644 index 0000000..17d9a13 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/auth.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +/* $Id: auth.h,v 1.9 1997/05/11 11:04:28 assar Exp $ */ + +#ifndef __AUTH_H__ +#define __AUTH_H__ + +#include <stdarg.h> + +struct at { + char *name; + int (*auth)(char*); + int (*adat)(char*); + int (*pbsz)(int); + int (*prot)(int); + int (*ccc)(void); + int (*mic)(char*); + int (*conf)(char*); + int (*enc)(char*); + int (*read)(int, void*, int); + int (*write)(int, void*, int); + int (*userok)(char*); + int (*vprintf)(const char*, va_list); +}; + +extern struct at *ct; + +enum protection_levels { + prot_clear, prot_safe, prot_confidential, prot_private +}; + +extern char *protection_names[]; + +extern char *ftp_command; +extern int prot_level; + +void delete_ftp_command(void); + +extern int data_protection; +extern int buffer_size; +extern unsigned char *data_buffer; +extern int auth_complete; + +void auth_init(void); + +int auth_ok(void); + +void auth(char*); +void adat(char*); +void pbsz(int); +void prot(char*); +void ccc(void); +void mic(char*); +void conf(char*); +void enc(char*); + +int auth_read(int, void*, int); +int auth_write(int, void*, int); + +void auth_vprintf(const char *fmt, va_list ap) +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 0))) +#endif +; +void auth_printf(const char *fmt, ...) +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +; + +void new_ftp_command(char *command); + +#endif /* __AUTH_H__ */ diff --git a/crypto/kerberosIV/appl/ftp/ftpd/extern.h b/crypto/kerberosIV/appl/ftp/ftpd/extern.h new file mode 100644 index 0000000..f9b800f --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/extern.h @@ -0,0 +1,141 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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. + * + * @(#)extern.h 8.2 (Berkeley) 4/4/94 + */ + +#ifndef _EXTERN_H_ +#define _EXTERN_H_ + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif + +#include <stdio.h> +#include <stdarg.h> +#include <setjmp.h> +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +void abor(void); +void blkfree(char **); +char **copyblk(char **); +void cwd(char *); +void do_delete(char *); +void dologout(int); +void fatal(char *); +int filename_check(char *); +int ftpd_pclose(FILE *); +FILE *ftpd_popen(char *, char *, int, int); +char *getline(char *, int); +void logwtmp(char *, char *, char *); +void lreply(int, const char *, ...) +#ifdef __GNUC__ +__attribute__ ((format (printf, 2, 3))) +#endif +; +void makedir(char *); +void nack(char *); +void nreply(const char *, ...) +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +; +void pass(char *); +void passive(void); +void perror_reply(int, char *); +void pwd(void); +void removedir(char *); +void renamecmd(char *, char *); +char *renamefrom(char *); +void reply(int, const char *, ...) +#ifdef __GNUC__ +__attribute__ ((format (printf, 2, 3))) +#endif +; +void retrieve(char *, char *); +void send_file_list(char *); +void setproctitle(const char *, ...) +#ifdef __GNUC__ +__attribute__ ((format (printf, 1, 2))) +#endif +; +void statcmd(void); +void statfilecmd(char *); +void do_store(char *, char *, int); +void upper(char *); +void user(char *); +void yyerror(char *); + +void kauth(char *, char*); +void klist(void); + +int find(char *); + +int do_login(int code, char *passwd); +int klogin(char *name, char *password); + +const char *ftp_rooted(const char *path); + +extern struct sockaddr_in ctrl_addr, his_addr; +extern char hostname[]; + +extern struct sockaddr_in data_dest; +extern int logged_in; +extern struct passwd *pw; +extern int guest; +extern int logging; +extern int type; +extern int oobflag; +extern off_t file_size; +extern off_t byte_count; +extern jmp_buf urgcatch; + +extern int form; +extern int debug; +extern int ftpd_timeout; +extern int maxtimeout; +extern int pdata; +extern char hostname[], remotehost[]; +extern char proctitle[]; +extern int usedefault; +extern int transflag; +extern char tmpline[]; + +#endif /* _EXTERN_H_ */ diff --git a/crypto/kerberosIV/appl/ftp/ftpd/ftpcmd.y b/crypto/kerberosIV/appl/ftp/ftpd/ftpcmd.y new file mode 100644 index 0000000..9368cdb --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/ftpcmd.y @@ -0,0 +1,1408 @@ +/* $NetBSD: ftpcmd.y,v 1.6 1995/06/03 22:46:45 mycroft Exp $ */ + +/* + * Copyright (c) 1985, 1988, 1993, 1994 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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. + * + * @(#)ftpcmd.y 8.3 (Berkeley) 4/6/94 + */ + +/* + * Grammar for FTP commands. + * See RFC 959. + */ + +%{ + + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +RCSID("$Id: ftpcmd.y,v 1.35 1997/05/25 14:38:49 assar Exp $"); + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_ARPA_FTP_H +#include <arpa/ftp.h> +#endif + +#include <ctype.h> +#include <errno.h> +#include <glob.h> +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#include <setjmp.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#ifdef HAVE_SYSLOG_H +#include <syslog.h> +#endif +#include <time.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#ifdef HAVE_BSD_BSD_H +#include <bsd/bsd.h> +#endif + +#include <roken.h> + +#ifdef SOCKS +#include <socks.h> +extern int LIBPREFIX(fclose) __P((FILE *)); +#endif + +#include "extern.h" +#include "auth.h" + +off_t restart_point; + +static int cmd_type; +static int cmd_form; +static int cmd_bytesz; +char cbuf[512]; +char *fromname; + +struct tab { + char *name; + short token; + short state; + short implemented; /* 1 if command is implemented */ + char *help; +}; + +extern struct tab cmdtab[]; +extern struct tab sitetab[]; + +static char *copy (char *); +static void help (struct tab *, char *); +static struct tab * + lookup (struct tab *, char *); +static void sizecmd (char *); +static void toolong (int); +static int yylex (void); + +/* This is for bison */ + +#if !defined(alloca) && !defined(HAVE_ALLOCA) +#define alloca(x) malloc(x) +#endif + +%} + +%union { + int i; + char *s; +} + +%token + A B C E F I + L N P R S T + + SP CRLF COMMA + + USER PASS ACCT REIN QUIT PORT + PASV TYPE STRU MODE RETR STOR + APPE MLFL MAIL MSND MSOM MSAM + MRSQ MRCP ALLO REST RNFR RNTO + ABOR DELE CWD LIST NLST SITE + STAT HELP NOOP MKD RMD PWD + CDUP STOU SMNT SYST SIZE MDTM + + UMASK IDLE CHMOD + + AUTH ADAT PROT PBSZ CCC MIC + CONF ENC + + KAUTH KLIST FIND URL + + LEXERR + +%token <s> STRING +%token <i> NUMBER + +%type <i> check_login check_login_no_guest octal_number byte_size +%type <i> struct_code mode_code type_code form_code +%type <s> pathstring pathname password username + +%start cmd_list + +%% + +cmd_list + : /* empty */ + | cmd_list cmd + { + fromname = (char *) 0; + restart_point = (off_t) 0; + } + | cmd_list rcmd + ; + +cmd + : USER SP username CRLF + { + user($3); + free($3); + } + | AUTH SP STRING CRLF + { + auth($3); + free($3); + } + | ADAT SP STRING CRLF + { + adat($3); + free($3); + } + | PBSZ SP NUMBER CRLF + { + pbsz($3); + } + | PROT SP STRING CRLF + { + prot($3); + } + | CCC CRLF + { + ccc(); + } + | MIC SP STRING CRLF + { + mic($3); + free($3); + } + | CONF SP STRING CRLF + { + conf($3); + free($3); + } + | PASS SP password CRLF + { + pass($3); + memset ($3, 0, strlen($3)); + free($3); + } + | PORT SP host_port CRLF + { + usedefault = 0; + if (pdata >= 0) { + close(pdata); + pdata = -1; + } + reply(200, "PORT command successful."); + } + | PASV CRLF + { + passive(); + } + | TYPE SP type_code CRLF + { + switch (cmd_type) { + + case TYPE_A: + if (cmd_form == FORM_N) { + reply(200, "Type set to A."); + type = cmd_type; + form = cmd_form; + } else + reply(504, "Form must be N."); + break; + + case TYPE_E: + reply(504, "Type E not implemented."); + break; + + case TYPE_I: + reply(200, "Type set to I."); + type = cmd_type; + break; + + case TYPE_L: +#if NBBY == 8 + if (cmd_bytesz == 8) { + reply(200, + "Type set to L (byte size 8)."); + type = cmd_type; + } else + reply(504, "Byte size must be 8."); +#else /* NBBY == 8 */ + UNIMPLEMENTED for NBBY != 8 +#endif /* NBBY == 8 */ + } + } + | STRU SP struct_code CRLF + { + switch ($3) { + + case STRU_F: + reply(200, "STRU F ok."); + break; + + default: + reply(504, "Unimplemented STRU type."); + } + } + | MODE SP mode_code CRLF + { + switch ($3) { + + case MODE_S: + reply(200, "MODE S ok."); + break; + + default: + reply(502, "Unimplemented MODE type."); + } + } + | ALLO SP NUMBER CRLF + { + reply(202, "ALLO command ignored."); + } + | ALLO SP NUMBER SP R SP NUMBER CRLF + { + reply(202, "ALLO command ignored."); + } + | RETR check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + retrieve((char *) 0, $4); + if ($4 != NULL) + free($4); + } + | STOR check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + do_store($4, "w", 0); + if ($4 != NULL) + free($4); + } + | APPE check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + do_store($4, "a", 0); + if ($4 != NULL) + free($4); + } + | NLST check_login CRLF + { + if ($2) + send_file_list("."); + } + | NLST check_login SP STRING CRLF + { + if ($2 && $4 != NULL) + send_file_list($4); + if ($4 != NULL) + free($4); + } + | LIST check_login CRLF + { +#ifdef HAVE_LS_A + char *cmd = "/bin/ls -lA"; +#else + char *cmd = "/bin/ls -la"; +#endif + if ($2) + retrieve(cmd, ""); + + } + | LIST check_login SP pathname CRLF + { +#ifdef HAVE_LS_A + char *cmd = "/bin/ls -lA %s"; +#else + char *cmd = "/bin/ls -la %s"; +#endif + if ($2 && $4 != NULL) + retrieve(cmd, $4); + if ($4 != NULL) + free($4); + } + | STAT check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + statfilecmd($4); + if ($4 != NULL) + free($4); + } + | STAT CRLF + { + if(oobflag){ + if (file_size != (off_t) -1) + reply(213, "Status: %ld of %ld bytes transferred", + byte_count, file_size); + else + reply(213, "Status: %ld bytes transferred", byte_count); + }else + statcmd(); + } + | DELE check_login_no_guest SP pathname CRLF + { + if ($2 && $4 != NULL) + do_delete($4); + if ($4 != NULL) + free($4); + } + | RNTO check_login_no_guest SP pathname CRLF + { + if($2){ + if (fromname) { + renamecmd(fromname, $4); + free(fromname); + fromname = (char *) 0; + } else { + reply(503, "Bad sequence of commands."); + } + } + if ($4 != NULL) + free($4); + } + | ABOR CRLF + { + if(oobflag){ + reply(426, "Transfer aborted. Data connection closed."); + reply(226, "Abort successful"); + oobflag = 0; + longjmp(urgcatch, 1); + }else + reply(225, "ABOR command successful."); + } + | CWD check_login CRLF + { + if ($2) + cwd(pw->pw_dir); + } + | CWD check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + cwd($4); + if ($4 != NULL) + free($4); + } + | HELP CRLF + { + help(cmdtab, (char *) 0); + } + | HELP SP STRING CRLF + { + char *cp = $3; + + if (strncasecmp(cp, "SITE", 4) == 0) { + cp = $3 + 4; + if (*cp == ' ') + cp++; + if (*cp) + help(sitetab, cp); + else + help(sitetab, (char *) 0); + } else + help(cmdtab, $3); + } + | NOOP CRLF + { + reply(200, "NOOP command successful."); + } + | MKD check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + makedir($4); + if ($4 != NULL) + free($4); + } + | RMD check_login_no_guest SP pathname CRLF + { + if ($2 && $4 != NULL) + removedir($4); + if ($4 != NULL) + free($4); + } + | PWD check_login CRLF + { + if ($2) + pwd(); + } + | CDUP check_login CRLF + { + if ($2) + cwd(".."); + } + | SITE SP HELP CRLF + { + help(sitetab, (char *) 0); + } + | SITE SP HELP SP STRING CRLF + { + help(sitetab, $5); + } + | SITE SP UMASK check_login CRLF + { + int oldmask; + + if ($4) { + oldmask = umask(0); + umask(oldmask); + reply(200, "Current UMASK is %03o", oldmask); + } + } + | SITE SP UMASK check_login_no_guest SP octal_number CRLF + { + int oldmask; + + if ($4) { + if (($6 == -1) || ($6 > 0777)) { + reply(501, "Bad UMASK value"); + } else { + oldmask = umask($6); + reply(200, + "UMASK set to %03o (was %03o)", + $6, oldmask); + } + } + } + | SITE SP CHMOD check_login_no_guest SP octal_number SP pathname CRLF + { + if ($4 && $8 != NULL) { + if ($6 > 0777) + reply(501, + "CHMOD: Mode value must be between 0 and 0777"); + else if (chmod($8, $6) < 0) + perror_reply(550, $8); + else + reply(200, "CHMOD command successful."); + } + if ($8 != NULL) + free($8); + } + | SITE SP IDLE CRLF + { + reply(200, + "Current IDLE time limit is %d seconds; max %d", + ftpd_timeout, maxtimeout); + } + | SITE SP IDLE SP NUMBER CRLF + { + if ($5 < 30 || $5 > maxtimeout) { + reply(501, + "Maximum IDLE time must be between 30 and %d seconds", + maxtimeout); + } else { + ftpd_timeout = $5; + alarm((unsigned) ftpd_timeout); + reply(200, + "Maximum IDLE time set to %d seconds", + ftpd_timeout); + } + } + + | SITE SP KAUTH check_login SP STRING CRLF + { + char *p; + + if(guest) + reply(500, "Can't be done as guest."); + else{ + if($4 && $6 != NULL){ + p = strpbrk($6, " \t"); + if(p){ + *p++ = 0; + kauth($6, p + strspn(p, " \t")); + }else + kauth($6, NULL); + } + } + if($6 != NULL) + free($6); + } + | SITE SP KLIST check_login CRLF + { + if($4) + klist(); + } + | SITE SP FIND check_login SP STRING CRLF + { + if($4 && $6 != NULL) + find($6); + if($6 != NULL) + free($6); + } + | SITE SP URL CRLF + { + reply(200, "http://www.pdc.kth.se/kth-krb/"); + } + | STOU check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + do_store($4, "w", 1); + if ($4 != NULL) + free($4); + } + | SYST CRLF + { +#if defined(unix) || defined(__unix__) || defined(__unix) || defined(_AIX) || defined(_CRAY) + reply(215, "UNIX Type: L%d", NBBY); +#else + reply(215, "UNKNOWN Type: L%d", NBBY); +#endif + } + + /* + * SIZE is not in RFC959, but Postel has blessed it and + * it will be in the updated RFC. + * + * Return size of file in a format suitable for + * using with RESTART (we just count bytes). + */ + | SIZE check_login SP pathname CRLF + { + if ($2 && $4 != NULL) + sizecmd($4); + if ($4 != NULL) + free($4); + } + + /* + * MDTM is not in RFC959, but Postel has blessed it and + * it will be in the updated RFC. + * + * Return modification time of file as an ISO 3307 + * style time. E.g. YYYYMMDDHHMMSS or YYYYMMDDHHMMSS.xxx + * where xxx is the fractional second (of any precision, + * not necessarily 3 digits) + */ + | MDTM check_login SP pathname CRLF + { + if ($2 && $4 != NULL) { + struct stat stbuf; + if (stat($4, &stbuf) < 0) + reply(550, "%s: %s", + $4, strerror(errno)); + else if (!S_ISREG(stbuf.st_mode)) { + reply(550, "%s: not a plain file.", $4); + } else { + struct tm *t; + t = gmtime(&stbuf.st_mtime); + reply(213, + "%04d%02d%02d%02d%02d%02d", + t->tm_year + 1900, + t->tm_mon + 1, + t->tm_mday, + t->tm_hour, + t->tm_min, + t->tm_sec); + } + } + if ($4 != NULL) + free($4); + } + | QUIT CRLF + { + reply(221, "Goodbye."); + dologout(0); + } + | error CRLF + { + yyerrok; + } + ; +rcmd + : RNFR check_login_no_guest SP pathname CRLF + { + restart_point = (off_t) 0; + if ($2 && $4) { + fromname = renamefrom($4); + if (fromname == (char *) 0 && $4) { + free($4); + } + } + } + | REST SP byte_size CRLF + { + fromname = (char *) 0; + restart_point = $3; /* XXX $3 is only "int" */ + reply(350, "Restarting at %ld. %s", + (long)restart_point, + "Send STORE or RETRIEVE to initiate transfer."); + } + | ENC SP STRING CRLF + { + enc($3); + free($3); + } + ; + +username + : STRING + ; + +password + : /* empty */ + { + $$ = (char *)calloc(1, sizeof(char)); + } + | STRING + ; + +byte_size + : NUMBER + ; + +host_port + : NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA + NUMBER COMMA NUMBER + { + data_dest.sin_family = AF_INET; + data_dest.sin_port = htons($9 * 256 + $11); + data_dest.sin_addr.s_addr = + htonl(($1 << 24) | ($3 << 16) | ($5 << 8) | $7); + } + ; + +form_code + : N + { + $$ = FORM_N; + } + | T + { + $$ = FORM_T; + } + | C + { + $$ = FORM_C; + } + ; + +type_code + : A + { + cmd_type = TYPE_A; + cmd_form = FORM_N; + } + | A SP form_code + { + cmd_type = TYPE_A; + cmd_form = $3; + } + | E + { + cmd_type = TYPE_E; + cmd_form = FORM_N; + } + | E SP form_code + { + cmd_type = TYPE_E; + cmd_form = $3; + } + | I + { + cmd_type = TYPE_I; + } + | L + { + cmd_type = TYPE_L; + cmd_bytesz = NBBY; + } + | L SP byte_size + { + cmd_type = TYPE_L; + cmd_bytesz = $3; + } + /* this is for a bug in the BBN ftp */ + | L byte_size + { + cmd_type = TYPE_L; + cmd_bytesz = $2; + } + ; + +struct_code + : F + { + $$ = STRU_F; + } + | R + { + $$ = STRU_R; + } + | P + { + $$ = STRU_P; + } + ; + +mode_code + : S + { + $$ = MODE_S; + } + | B + { + $$ = MODE_B; + } + | C + { + $$ = MODE_C; + } + ; + +pathname + : pathstring + { + /* + * Problem: this production is used for all pathname + * processing, but only gives a 550 error reply. + * This is a valid reply in some cases but not in others. + */ + if (logged_in && $1 && *$1 == '~') { + glob_t gl; + int flags = + GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE; + + memset(&gl, 0, sizeof(gl)); + if (glob($1, flags, NULL, &gl) || + gl.gl_pathc == 0) { + reply(550, "not found"); + $$ = NULL; + } else { + $$ = strdup(gl.gl_pathv[0]); + } + globfree(&gl); + free($1); + } else + $$ = $1; + } + ; + +pathstring + : STRING + ; + +octal_number + : NUMBER + { + int ret, dec, multby, digit; + + /* + * Convert a number that was read as decimal number + * to what it would be if it had been read as octal. + */ + dec = $1; + multby = 1; + ret = 0; + while (dec) { + digit = dec%10; + if (digit > 7) { + ret = -1; + break; + } + ret += digit * multby; + multby *= 8; + dec /= 10; + } + $$ = ret; + } + ; + + +check_login_no_guest : check_login + { + $$ = $1 && !guest; + if($1 && !$$) + reply(550, "Permission denied"); + } + ; + +check_login + : /* empty */ + { + if(auth_complete && prot_level == prot_clear){ + reply(533, "Command protection level denied for paranoid reasons."); + $$ = 0; + }else + if (logged_in) + $$ = 1; + else { + reply(530, "Please login with USER and PASS."); + $$ = 0; + } + } + ; + +%% + +extern jmp_buf errcatch; + +#define CMD 0 /* beginning of command */ +#define ARGS 1 /* expect miscellaneous arguments */ +#define STR1 2 /* expect SP followed by STRING */ +#define STR2 3 /* expect STRING */ +#define OSTR 4 /* optional SP then STRING */ +#define ZSTR1 5 /* SP then optional STRING */ +#define ZSTR2 6 /* optional STRING after SP */ +#define SITECMD 7 /* SITE command */ +#define NSTR 8 /* Number followed by a string */ + +struct tab cmdtab[] = { /* In order defined in RFC 765 */ + { "USER", USER, STR1, 1, "<sp> username" }, + { "PASS", PASS, ZSTR1, 1, "<sp> password" }, + { "ACCT", ACCT, STR1, 0, "(specify account)" }, + { "SMNT", SMNT, ARGS, 0, "(structure mount)" }, + { "REIN", REIN, ARGS, 0, "(reinitialize server state)" }, + { "QUIT", QUIT, ARGS, 1, "(terminate service)", }, + { "PORT", PORT, ARGS, 1, "<sp> b0, b1, b2, b3, b4" }, + { "PASV", PASV, ARGS, 1, "(set server in passive mode)" }, + { "TYPE", TYPE, ARGS, 1, "<sp> [ A | E | I | L ]" }, + { "STRU", STRU, ARGS, 1, "(specify file structure)" }, + { "MODE", MODE, ARGS, 1, "(specify transfer mode)" }, + { "RETR", RETR, STR1, 1, "<sp> file-name" }, + { "STOR", STOR, STR1, 1, "<sp> file-name" }, + { "APPE", APPE, STR1, 1, "<sp> file-name" }, + { "MLFL", MLFL, OSTR, 0, "(mail file)" }, + { "MAIL", MAIL, OSTR, 0, "(mail to user)" }, + { "MSND", MSND, OSTR, 0, "(mail send to terminal)" }, + { "MSOM", MSOM, OSTR, 0, "(mail send to terminal or mailbox)" }, + { "MSAM", MSAM, OSTR, 0, "(mail send to terminal and mailbox)" }, + { "MRSQ", MRSQ, OSTR, 0, "(mail recipient scheme question)" }, + { "MRCP", MRCP, STR1, 0, "(mail recipient)" }, + { "ALLO", ALLO, ARGS, 1, "allocate storage (vacuously)" }, + { "REST", REST, ARGS, 1, "<sp> offset (restart command)" }, + { "RNFR", RNFR, STR1, 1, "<sp> file-name" }, + { "RNTO", RNTO, STR1, 1, "<sp> file-name" }, + { "ABOR", ABOR, ARGS, 1, "(abort operation)" }, + { "DELE", DELE, STR1, 1, "<sp> file-name" }, + { "CWD", CWD, OSTR, 1, "[ <sp> directory-name ]" }, + { "XCWD", CWD, OSTR, 1, "[ <sp> directory-name ]" }, + { "LIST", LIST, OSTR, 1, "[ <sp> path-name ]" }, + { "NLST", NLST, OSTR, 1, "[ <sp> path-name ]" }, + { "SITE", SITE, SITECMD, 1, "site-cmd [ <sp> arguments ]" }, + { "SYST", SYST, ARGS, 1, "(get type of operating system)" }, + { "STAT", STAT, OSTR, 1, "[ <sp> path-name ]" }, + { "HELP", HELP, OSTR, 1, "[ <sp> <string> ]" }, + { "NOOP", NOOP, ARGS, 1, "" }, + { "MKD", MKD, STR1, 1, "<sp> path-name" }, + { "XMKD", MKD, STR1, 1, "<sp> path-name" }, + { "RMD", RMD, STR1, 1, "<sp> path-name" }, + { "XRMD", RMD, STR1, 1, "<sp> path-name" }, + { "PWD", PWD, ARGS, 1, "(return current directory)" }, + { "XPWD", PWD, ARGS, 1, "(return current directory)" }, + { "CDUP", CDUP, ARGS, 1, "(change to parent directory)" }, + { "XCUP", CDUP, ARGS, 1, "(change to parent directory)" }, + { "STOU", STOU, STR1, 1, "<sp> file-name" }, + { "SIZE", SIZE, OSTR, 1, "<sp> path-name" }, + { "MDTM", MDTM, OSTR, 1, "<sp> path-name" }, + + /* extensions from draft-ietf-cat-ftpsec-08 */ + { "AUTH", AUTH, STR1, 1, "<sp> auth-type" }, + { "ADAT", ADAT, STR1, 1, "<sp> auth-data" }, + { "PBSZ", PBSZ, ARGS, 1, "<sp> buffer-size" }, + { "PROT", PROT, STR1, 1, "<sp> prot-level" }, + { "CCC", CCC, ARGS, 1, "" }, + { "MIC", MIC, STR1, 1, "<sp> integrity command" }, + { "CONF", CONF, STR1, 1, "<sp> confidentiality command" }, + { "ENC", ENC, STR1, 1, "<sp> privacy command" }, + + { NULL, 0, 0, 0, 0 } +}; + +struct tab sitetab[] = { + { "UMASK", UMASK, ARGS, 1, "[ <sp> umask ]" }, + { "IDLE", IDLE, ARGS, 1, "[ <sp> maximum-idle-time ]" }, + { "CHMOD", CHMOD, NSTR, 1, "<sp> mode <sp> file-name" }, + { "HELP", HELP, OSTR, 1, "[ <sp> <string> ]" }, + + { "KAUTH", KAUTH, STR1, 1, "<sp> principal [ <sp> ticket ]" }, + { "KLIST", KLIST, ARGS, 1, "(show ticket file)" }, + + { "FIND", FIND, STR1, 1, "<sp> globexpr" }, + + { "URL", URL, ARGS, 1, "?" }, + + { NULL, 0, 0, 0, 0 } +}; + +static struct tab * +lookup(struct tab *p, char *cmd) +{ + + for (; p->name != NULL; p++) + if (strcmp(cmd, p->name) == 0) + return (p); + return (0); +} + +#include <arpa/telnet.h> + +/* + * getline - a hacked up version of fgets to ignore TELNET escape codes. + */ +char * +getline(char *s, int n) +{ + int c; + char *cs; + + cs = s; +/* tmpline may contain saved command from urgent mode interruption */ + if(ftp_command){ + strncpy(s, ftp_command, n); + if (debug) + syslog(LOG_DEBUG, "command: %s", s); +#ifdef XXX + fprintf(stderr, "%s\n", s); +#endif + return s; + } + prot_level = prot_clear; + while ((c = getc(stdin)) != EOF) { + c &= 0377; + if (c == IAC) { + if ((c = getc(stdin)) != EOF) { + c &= 0377; + switch (c) { + case WILL: + case WONT: + c = getc(stdin); + printf("%c%c%c", IAC, DONT, 0377&c); + fflush(stdout); + continue; + case DO: + case DONT: + c = getc(stdin); + printf("%c%c%c", IAC, WONT, 0377&c); + fflush(stdout); + continue; + case IAC: + break; + default: + continue; /* ignore command */ + } + } + } + *cs++ = c; + if (--n <= 0 || c == '\n') + break; + } + if (c == EOF && cs == s) + return (NULL); + *cs++ = '\0'; + if (debug) { + if (!guest && strncasecmp("pass ", s, 5) == 0) { + /* Don't syslog passwords */ + syslog(LOG_DEBUG, "command: %.5s ???", s); + } else { + char *cp; + int len; + + /* Don't syslog trailing CR-LF */ + len = strlen(s); + cp = s + len - 1; + while (cp >= s && (*cp == '\n' || *cp == '\r')) { + --cp; + --len; + } + syslog(LOG_DEBUG, "command: %.*s", len, s); + } + } +#ifdef XXX + fprintf(stderr, "%s\n", s); +#endif + return (s); +} + +static RETSIGTYPE +toolong(int signo) +{ + + reply(421, + "Timeout (%d seconds): closing control connection.", + ftpd_timeout); + if (logging) + syslog(LOG_INFO, "User %s timed out after %d seconds", + (pw ? pw -> pw_name : "unknown"), ftpd_timeout); + dologout(1); + SIGRETURN(0); +} + +static int +yylex(void) +{ + static int cpos, state; + char *cp, *cp2; + struct tab *p; + int n; + char c; + + for (;;) { + switch (state) { + + case CMD: + signal(SIGALRM, toolong); + alarm((unsigned) ftpd_timeout); + if (getline(cbuf, sizeof(cbuf)-1) == NULL) { + reply(221, "You could at least say goodbye."); + dologout(0); + } + alarm(0); +#ifdef HASSETPROCTITLE + if (strncasecmp(cbuf, "PASS", 4) != NULL) + setproctitle("%s: %s", proctitle, cbuf); +#endif /* HASSETPROCTITLE */ + if ((cp = strchr(cbuf, '\r'))) { + *cp++ = '\n'; + *cp = '\0'; + } + if ((cp = strpbrk(cbuf, " \n"))) + cpos = cp - cbuf; + if (cpos == 0) + cpos = 4; + c = cbuf[cpos]; + cbuf[cpos] = '\0'; + strupr(cbuf); + p = lookup(cmdtab, cbuf); + cbuf[cpos] = c; + if (p != 0) { + if (p->implemented == 0) { + nack(p->name); + longjmp(errcatch,0); + /* NOTREACHED */ + } + state = p->state; + yylval.s = p->name; + return (p->token); + } + break; + + case SITECMD: + if (cbuf[cpos] == ' ') { + cpos++; + return (SP); + } + cp = &cbuf[cpos]; + if ((cp2 = strpbrk(cp, " \n"))) + cpos = cp2 - cbuf; + c = cbuf[cpos]; + cbuf[cpos] = '\0'; + strupr(cp); + p = lookup(sitetab, cp); + cbuf[cpos] = c; + if (p != 0) { + if (p->implemented == 0) { + state = CMD; + nack(p->name); + longjmp(errcatch,0); + /* NOTREACHED */ + } + state = p->state; + yylval.s = p->name; + return (p->token); + } + state = CMD; + break; + + case OSTR: + if (cbuf[cpos] == '\n') { + state = CMD; + return (CRLF); + } + /* FALLTHROUGH */ + + case STR1: + case ZSTR1: + dostr1: + if (cbuf[cpos] == ' ') { + cpos++; + state = state == OSTR ? STR2 : ++state; + return (SP); + } + break; + + case ZSTR2: + if (cbuf[cpos] == '\n') { + state = CMD; + return (CRLF); + } + /* FALLTHROUGH */ + + case STR2: + cp = &cbuf[cpos]; + n = strlen(cp); + cpos += n - 1; + /* + * Make sure the string is nonempty and \n terminated. + */ + if (n > 1 && cbuf[cpos] == '\n') { + cbuf[cpos] = '\0'; + yylval.s = copy(cp); + cbuf[cpos] = '\n'; + state = ARGS; + return (STRING); + } + break; + + case NSTR: + if (cbuf[cpos] == ' ') { + cpos++; + return (SP); + } + if (isdigit(cbuf[cpos])) { + cp = &cbuf[cpos]; + while (isdigit(cbuf[++cpos])) + ; + c = cbuf[cpos]; + cbuf[cpos] = '\0'; + yylval.i = atoi(cp); + cbuf[cpos] = c; + state = STR1; + return (NUMBER); + } + state = STR1; + goto dostr1; + + case ARGS: + if (isdigit(cbuf[cpos])) { + cp = &cbuf[cpos]; + while (isdigit(cbuf[++cpos])) + ; + c = cbuf[cpos]; + cbuf[cpos] = '\0'; + yylval.i = atoi(cp); + cbuf[cpos] = c; + return (NUMBER); + } + switch (cbuf[cpos++]) { + + case '\n': + state = CMD; + return (CRLF); + + case ' ': + return (SP); + + case ',': + return (COMMA); + + case 'A': + case 'a': + return (A); + + case 'B': + case 'b': + return (B); + + case 'C': + case 'c': + return (C); + + case 'E': + case 'e': + return (E); + + case 'F': + case 'f': + return (F); + + case 'I': + case 'i': + return (I); + + case 'L': + case 'l': + return (L); + + case 'N': + case 'n': + return (N); + + case 'P': + case 'p': + return (P); + + case 'R': + case 'r': + return (R); + + case 'S': + case 's': + return (S); + + case 'T': + case 't': + return (T); + + } + break; + + default: + fatal("Unknown state in scanner."); + } + yyerror((char *) 0); + state = CMD; + longjmp(errcatch,0); + } +} + +static char * +copy(char *s) +{ + char *p; + + p = strdup(s); + if (p == NULL) + fatal("Ran out of memory."); + return p; +} + +static void +help(struct tab *ctab, char *s) +{ + struct tab *c; + int width, NCMDS; + char *type; + char buf[1024]; + + if (ctab == sitetab) + type = "SITE "; + else + type = ""; + width = 0, NCMDS = 0; + for (c = ctab; c->name != NULL; c++) { + int len = strlen(c->name); + + if (len > width) + width = len; + NCMDS++; + } + width = (width + 8) &~ 7; + if (s == 0) { + int i, j, w; + int columns, lines; + + lreply(214, "The following %scommands are recognized %s.", + type, "(* =>'s unimplemented)"); + columns = 76 / width; + if (columns == 0) + columns = 1; + lines = (NCMDS + columns - 1) / columns; + for (i = 0; i < lines; i++) { + strcpy (buf, " "); + for (j = 0; j < columns; j++) { + c = ctab + j * lines + i; + snprintf (buf + strlen(buf), sizeof(buf) - strlen(buf), + "%s%c", c->name, c->implemented ? ' ' : '*'); + if (c + lines >= &ctab[NCMDS]) + break; + w = strlen(c->name) + 1; + while (w < width) { + strcat(buf, " "); + w++; + } + } + lreply(214, buf); + } + reply(214, "Direct comments to kth-krb-bugs@pdc.kth.se"); + return; + } + strupr(s); + c = lookup(ctab, s); + if (c == (struct tab *)0) { + reply(502, "Unknown command %s.", s); + return; + } + if (c->implemented) + reply(214, "Syntax: %s%s %s", type, c->name, c->help); + else + reply(214, "%s%-*s\t%s; unimplemented.", type, width, + c->name, c->help); +} + +static void +sizecmd(char *filename) +{ + switch (type) { + case TYPE_L: + case TYPE_I: { + struct stat stbuf; + if (stat(filename, &stbuf) < 0 || !S_ISREG(stbuf.st_mode)) + reply(550, "%s: not a plain file.", filename); + else + reply(213, "%lu", (unsigned long)stbuf.st_size); + break; } + case TYPE_A: { + FILE *fin; + int c; + off_t count; + struct stat stbuf; + fin = fopen(filename, "r"); + if (fin == NULL) { + perror_reply(550, filename); + return; + } + if (fstat(fileno(fin), &stbuf) < 0 || !S_ISREG(stbuf.st_mode)) { + reply(550, "%s: not a plain file.", filename); + fclose(fin); + return; + } + + count = 0; + while((c=getc(fin)) != EOF) { + if (c == '\n') /* will get expanded to \r\n */ + count++; + count++; + } + fclose(fin); + + reply(213, "%ld", count); + break; } + default: + reply(504, "SIZE not implemented for Type %c.", "?AEIL"[type]); + } +} diff --git a/crypto/kerberosIV/appl/ftp/ftpd/ftpd.c b/crypto/kerberosIV/appl/ftp/ftpd/ftpd.c new file mode 100644 index 0000000..17cd3b9 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/ftpd.c @@ -0,0 +1,2076 @@ +/* + * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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. + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +RCSID("$Id: ftpd.c,v 1.88 1997/06/01 03:13:48 assar Exp $"); +#endif + +/* + * FTP server. + */ +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#if defined(HAVE_SYS_IOCTL_H) && SunOS != 4 +#include <sys/ioctl.h> +#endif +#ifdef TIME_WITH_SYS_TIME +#include <sys/time.h> +#include <time.h> +#elif defined(HAVE_SYS_TIME_H) +#include <sys/time.h> +#else +#include <time.h> +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include <sys/resource.h> +#endif +#ifdef HAVE_SYS_WAIT_H +#include <sys/wait.h> +#endif + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN_SYSTM_H +#include <netinet/in_systm.h> +#endif +#ifdef HAVE_NETINET_IP_H +#include <netinet/ip.h> +#endif + +#ifdef HAVE_SYS_MMAN_H +#include <sys/mman.h> +#endif + +#define FTP_NAMES +#include <arpa/ftp.h> +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_ARPA_TELNET_H +#include <arpa/telnet.h> +#endif + +#include <ctype.h> +#ifdef HAVE_DIRENT_H +#include <dirent.h> +#endif +#include <errno.h> +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#include <glob.h> +#include <limits.h> +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#include <setjmp.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#ifdef HAVE_SYSLOG_H +#include <syslog.h> +#endif +#include <time.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_GRP_H +#include <grp.h> +#endif + +#include <err.h> + +#include "pathnames.h" +#include "extern.h" +#include "common.h" + +#include "auth.h" + +#include <krb.h> + +#include <kafs.h> +#include "roken.h" + +#include <otp.h> + +#ifdef SOCKS +#include <socks.h> +extern int LIBPREFIX(fclose) __P((FILE *)); +#endif + +void yyparse(); + +#ifndef LOG_FTP +#define LOG_FTP LOG_DAEMON +#endif + +static char version[] = "Version 6.00"; + +extern off_t restart_point; +extern char cbuf[]; + +struct sockaddr_in ctrl_addr; +struct sockaddr_in data_source; +struct sockaddr_in data_dest; +struct sockaddr_in his_addr; +struct sockaddr_in pasv_addr; + +int data; +jmp_buf errcatch, urgcatch; +int oobflag; +int logged_in; +struct passwd *pw; +int debug; +int ftpd_timeout = 900; /* timeout after 15 minutes of inactivity */ +int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ +int logging; +int guest; +int dochroot; +int type; +int form; +int stru; /* avoid C keyword */ +int mode; +int usedefault = 1; /* for data transfers */ +int pdata = -1; /* for passive mode */ +int transflag; +off_t file_size; +off_t byte_count; +#if !defined(CMASK) || CMASK == 0 +#undef CMASK +#define CMASK 027 +#endif +int defumask = CMASK; /* default umask value */ +int guest_umask = 0777; /* Paranoia for anonymous users */ +char tmpline[10240]; +char hostname[MaxHostNameLen]; +char remotehost[MaxHostNameLen]; +static char ttyline[20]; + +#define AUTH_PLAIN (1 << 0) /* allow sending passwords */ +#define AUTH_OTP (1 << 1) /* passwords are one-time */ +#define AUTH_FTP (1 << 2) /* allow anonymous login */ + +static int auth_level = 0; /* Only allow kerberos login by default */ + +/* + * Timeout intervals for retrying connections + * to hosts that don't accept PORT cmds. This + * is a kludge, but given the problems with TCP... + */ +#define SWAITMAX 90 /* wait at most 90 seconds */ +#define SWAITINT 5 /* interval between retries */ + +int swaitmax = SWAITMAX; +int swaitint = SWAITINT; + +#ifdef HAVE_SETPROCTITLE +char proctitle[BUFSIZ]; /* initial part of title */ +#endif /* HAVE_SETPROCTITLE */ + +#define LOGCMD(cmd, file) \ + if (logging > 1) \ + syslog(LOG_INFO,"%s %s%s", cmd, \ + *(file) == '/' ? "" : curdir(), file); +#define LOGCMD2(cmd, file1, file2) \ + if (logging > 1) \ + syslog(LOG_INFO,"%s %s%s %s%s", cmd, \ + *(file1) == '/' ? "" : curdir(), file1, \ + *(file2) == '/' ? "" : curdir(), file2); +#define LOGBYTES(cmd, file, cnt) \ + if (logging > 1) { \ + if (cnt == (off_t)-1) \ + syslog(LOG_INFO,"%s %s%s", cmd, \ + *(file) == '/' ? "" : curdir(), file); \ + else \ + syslog(LOG_INFO, "%s %s%s = %ld bytes", \ + cmd, (*(file) == '/') ? "" : curdir(), file, (long)cnt); \ + } + +static void ack (char *); +static void myoob (int); +static int checkuser (char *, char *); +static int checkaccess (char *); +static FILE *dataconn (char *, off_t, char *); +static void dolog (struct sockaddr_in *); +static void end_login (void); +static FILE *getdatasock (char *); +static char *gunique (char *); +static RETSIGTYPE lostconn (int); +static int receive_data (FILE *, FILE *); +static void send_data (FILE *, FILE *); +static struct passwd * sgetpwnam (char *); +static void usage(void); + +static char * +curdir(void) +{ + static char path[MaxPathLen+1+1]; /* path + '/' + '\0' */ + + if (getcwd(path, sizeof(path)-2) == NULL) + return (""); + if (path[1] != '\0') /* special case for root dir. */ + strcat(path, "/"); + /* For guest account, skip / since it's chrooted */ + return (guest ? path+1 : path); +} + +#ifndef LINE_MAX +#define LINE_MAX 1024 +#endif + +static int +parse_auth_level(char *str) +{ + char *p; + int ret = 0; + char *foo = NULL; + + for(p = strtok_r(str, ",", &foo); + p; + p = strtok_r(NULL, ",", &foo)) { + if(strcmp(p, "user") == 0) + ; + else if(strcmp(p, "otp") == 0) + ret |= AUTH_PLAIN|AUTH_OTP; + else if(strcmp(p, "ftp") == 0 || + strcmp(p, "safe") == 0) + ret |= AUTH_FTP; + else if(strcmp(p, "plain") == 0) + ret |= AUTH_PLAIN; + else if(strcmp(p, "none") == 0) + ret |= AUTH_PLAIN|AUTH_FTP; + else + warnx("bad value for -a: `%s'", p); + } + return ret; +} + +/* + * Print usage and die. + */ + +static void +usage (void) +{ + fprintf (stderr, + "Usage: %s [-d] [-i] [-g guest_umask] [-l] [-p port]" + " [-t timeout] [-T max_timeout] [-u umask] [-v]" + " [-a auth_level] \n", + __progname); + exit (1); +} + +int +main(int argc, char **argv) +{ + int addrlen, ch, on = 1, tos; + char *cp, line[LINE_MAX]; + FILE *fd; + int not_inetd = 0; + int port; + struct servent *sp; + char tkfile[1024]; + + set_progname (argv[0]); + + /* detach from any tickets and tokens */ + + snprintf(tkfile, sizeof(tkfile), + "/tmp/ftp_%u", (unsigned)getpid()); + krb_set_tkt_string(tkfile); + if(k_hasafs()) + k_setpag(); + + sp = getservbyname("ftp", "tcp"); + if(sp) + port = sp->s_port; + else + port = htons(21); + + while ((ch = getopt(argc, argv, "a:dg:ilp:t:T:u:v")) != EOF) { + switch (ch) { + case 'a': + auth_level = parse_auth_level(optarg); + break; + case 'd': + debug = 1; + break; + + case 'i': + not_inetd = 1; + break; + case 'g': + { + long val = 0; + + val = strtol(optarg, &optarg, 8); + if (*optarg != '\0' || val < 0) + warnx("bad value for -g"); + else + guest_umask = val; + break; + } + case 'l': + logging++; /* > 1 == extra logging */ + break; + + case 'p': + sp = getservbyname(optarg, "tcp"); + if(sp) + port = sp->s_port; + else + if(isdigit(optarg[0])) + port = htons(atoi(optarg)); + else + warnx("bad value for -p"); + break; + + case 't': + ftpd_timeout = atoi(optarg); + if (maxtimeout < ftpd_timeout) + maxtimeout = ftpd_timeout; + break; + + case 'T': + maxtimeout = atoi(optarg); + if (ftpd_timeout > maxtimeout) + ftpd_timeout = maxtimeout; + break; + + case 'u': + { + long val = 0; + + val = strtol(optarg, &optarg, 8); + if (*optarg != '\0' || val < 0) + warnx("bad value for -u"); + else + defumask = val; + break; + } + + case 'v': + debug = 1; + break; + + default: + usage (); + } + } + + if(not_inetd) + mini_inetd (port); + + /* + * LOG_NDELAY sets up the logging connection immediately, + * necessary for anonymous ftp's that chroot and can't do it later. + */ + openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); + addrlen = sizeof(his_addr); + if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) { + syslog(LOG_ERR, "getpeername (%s): %m",argv[0]); + exit(1); + } + addrlen = sizeof(ctrl_addr); + if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { + syslog(LOG_ERR, "getsockname (%s): %m",argv[0]); + exit(1); + } +#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT) + tos = IPTOS_LOWDELAY; + if (setsockopt(0, IPPROTO_IP, IP_TOS, (void *)&tos, sizeof(int)) < 0) + syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); +#endif + data_source.sin_port = htons(ntohs(ctrl_addr.sin_port) - 1); + debug = 0; + + /* set this here so it can be put in wtmp */ + snprintf(ttyline, sizeof(ttyline), "ftp%u", (unsigned)getpid()); + + + /* freopen(_PATH_DEVNULL, "w", stderr); */ + signal(SIGPIPE, lostconn); + signal(SIGCHLD, SIG_IGN); +#ifdef SIGURG + if (signal(SIGURG, myoob) == SIG_ERR) + syslog(LOG_ERR, "signal: %m"); +#endif + + auth_init(); + + /* Try to handle urgent data inline */ +#if defined(SO_OOBINLINE) && defined(HAVE_SETSOCKOPT) + if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (void *)&on, + sizeof(on)) < 0) + syslog(LOG_ERR, "setsockopt: %m"); +#endif + +#ifdef F_SETOWN + if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) + syslog(LOG_ERR, "fcntl F_SETOWN: %m"); +#endif + dolog(&his_addr); + /* + * Set up default state + */ + data = -1; + type = TYPE_A; + form = FORM_N; + stru = STRU_F; + mode = MODE_S; + tmpline[0] = '\0'; + + /* If logins are disabled, print out the message. */ + if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) { + while (fgets(line, sizeof(line), fd) != NULL) { + if ((cp = strchr(line, '\n')) != NULL) + *cp = '\0'; + lreply(530, "%s", line); + } + fflush(stdout); + fclose(fd); + reply(530, "System not available."); + exit(0); + } + if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) { + while (fgets(line, sizeof(line), fd) != NULL) { + if ((cp = strchr(line, '\n')) != NULL) + *cp = '\0'; + lreply(220, "%s", line); + } + fflush(stdout); + fclose(fd); + /* reply(220,) must follow */ + } + k_gethostname(hostname, sizeof(hostname)); + reply(220, "%s FTP server (%s+%s) ready.", hostname, + version, krb4_version); + setjmp(errcatch); + for (;;) + yyparse(); + /* NOTREACHED */ +} + +static RETSIGTYPE +lostconn(int signo) +{ + + if (debug) + syslog(LOG_DEBUG, "lost connection"); + dologout(-1); +} + +/* + * Helper function for sgetpwnam(). + */ +static char * +sgetsave(char *s) +{ + char *new = strdup(s); + + if (new == NULL) { + perror_reply(421, "Local resource failure: malloc"); + dologout(1); + /* NOTREACHED */ + } + return new; +} + +/* + * Save the result of a getpwnam. Used for USER command, since + * the data returned must not be clobbered by any other command + * (e.g., globbing). + */ +static struct passwd * +sgetpwnam(char *name) +{ + static struct passwd save; + struct passwd *p; + + if ((p = k_getpwnam(name)) == NULL) + return (p); + if (save.pw_name) { + free(save.pw_name); + free(save.pw_passwd); + free(save.pw_gecos); + free(save.pw_dir); + free(save.pw_shell); + } + save = *p; + save.pw_name = sgetsave(p->pw_name); + save.pw_passwd = sgetsave(p->pw_passwd); + save.pw_gecos = sgetsave(p->pw_gecos); + save.pw_dir = sgetsave(p->pw_dir); + save.pw_shell = sgetsave(p->pw_shell); + return (&save); +} + +static int login_attempts; /* number of failed login attempts */ +static int askpasswd; /* had user command, ask for passwd */ +static char curname[10]; /* current USER name */ +OtpContext otp_ctx; + +/* + * USER command. + * Sets global passwd pointer pw if named account exists and is acceptable; + * sets askpasswd if a PASS command is expected. If logged in previously, + * need to reset state. If name is "ftp" or "anonymous", the name is not in + * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return. + * If account doesn't exist, ask for passwd anyway. Otherwise, check user + * requesting login privileges. Disallow anyone who does not have a standard + * shell as returned by getusershell(). Disallow anyone mentioned in the file + * _PATH_FTPUSERS to allow people such as root and uucp to be avoided. + */ +void +user(char *name) +{ + char *cp, *shell; + + if(auth_level == 0 && !auth_complete){ + reply(530, "No login allowed without authorization."); + return; + } + + if (logged_in) { + if (guest) { + reply(530, "Can't change user from guest login."); + return; + } else if (dochroot) { + reply(530, "Can't change user from chroot user."); + return; + } + end_login(); + } + + guest = 0; + if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) { + if ((auth_level & AUTH_FTP) == 0 || + checkaccess("ftp") || + checkaccess("anonymous")) + reply(530, "User %s access denied.", name); + else if ((pw = sgetpwnam("ftp")) != NULL) { + guest = 1; + defumask = guest_umask; /* paranoia for incoming */ + askpasswd = 1; + reply(331, "Guest login ok, type your name as password."); + } else + reply(530, "User %s unknown.", name); + if (!askpasswd && logging) + syslog(LOG_NOTICE, + "ANONYMOUS FTP LOGIN REFUSED FROM %s(%s)", + remotehost, inet_ntoa(his_addr.sin_addr)); + return; + } + if((auth_level & AUTH_PLAIN) == 0 && !auth_complete){ + reply(530, "Only authorized and anonymous login allowed."); + return; + } + if ((pw = sgetpwnam(name))) { + if ((shell = pw->pw_shell) == NULL || *shell == 0) + shell = _PATH_BSHELL; + while ((cp = getusershell()) != NULL) + if (strcmp(cp, shell) == 0) + break; + endusershell(); + + if (cp == NULL || checkaccess(name)) { + reply(530, "User %s access denied.", name); + if (logging) + syslog(LOG_NOTICE, + "FTP LOGIN REFUSED FROM %s(%s), %s", + remotehost, + inet_ntoa(his_addr.sin_addr), + name); + pw = (struct passwd *) NULL; + return; + } + } + if (logging) + strncpy(curname, name, sizeof(curname)-1); + if(auth_ok()) + ct->userok(name); + else { + char ss[256]; + + if (otp_challenge(&otp_ctx, name, ss, sizeof(ss)) == 0) { + reply(331, "Password %s for %s required.", + ss, name); + askpasswd = 1; + } else if ((auth_level & AUTH_OTP) == 0) { + reply(331, "Password required for %s.", name); + askpasswd = 1; + } else { + char *s; + + if (s = otp_error (&otp_ctx)) + lreply(530, "OTP: %s", s); + reply(530, + "Only authorized, anonymous and OTP " + "login allowed."); + } + + } + /* + * Delay before reading passwd after first failed + * attempt to slow down passwd-guessing programs. + */ + if (login_attempts) + sleep(login_attempts); +} + +/* + * Check if a user is in the file "fname" + */ +static int +checkuser(char *fname, char *name) +{ + FILE *fd; + int found = 0; + char *p, line[BUFSIZ]; + + if ((fd = fopen(fname, "r")) != NULL) { + while (fgets(line, sizeof(line), fd) != NULL) + if ((p = strchr(line, '\n')) != NULL) { + *p = '\0'; + if (line[0] == '#') + continue; + if (strcmp(line, name) == 0) { + found = 1; + break; + } + } + fclose(fd); + } + return (found); +} + + +/* + * Determine whether a user has access, based on information in + * _PATH_FTPUSERS. The users are listed one per line, with `allow' + * or `deny' after the username. If anything other than `allow', or + * just nothing, is given after the username, `deny' is assumed. + * + * If the user is not found in the file, but the pseudo-user `*' is, + * the permission is taken from that line. + * + * This preserves the old semantics where if a user was listed in the + * file he was denied, otherwise he was allowed. + * + * Return 1 if the user is denied, or 0 if he is allowed. */ + +static int +match(const char *pattern, const char *string) +{ +#ifdef HAVE_FNMATCH + return fnmatch(pattern, string, FNM_NOESCAPE); +#else + return strcmp(pattern, "*") != 0 && strcmp(pattern, string) != 0; +#endif +} + +static int +checkaccess(char *name) +{ +#define ALLOWED 0 +#define NOT_ALLOWED 1 + FILE *fd; + int allowed = ALLOWED; + char *user, *perm, line[BUFSIZ]; + char *foo; + + fd = fopen(_PATH_FTPUSERS, "r"); + + if(fd == NULL) + return allowed; + + while (fgets(line, sizeof(line), fd) != NULL) { + foo = NULL; + user = strtok_r(line, " \t\n", &foo); + if (user == NULL || user[0] == '#') + continue; + perm = strtok_r(NULL, " \t\n", &foo); + if (match(user, name) == 0){ + if(perm && strcmp(perm, "allow") == 0) + allowed = ALLOWED; + else + allowed = NOT_ALLOWED; + break; + } + } + fclose(fd); + return allowed; +} +#undef ALLOWED +#undef NOT_ALLOWED + +int do_login(int code, char *passwd) +{ + FILE *fd; + login_attempts = 0; /* this time successful */ + if (setegid((gid_t)pw->pw_gid) < 0) { + reply(550, "Can't set gid."); + return -1; + } + initgroups(pw->pw_name, pw->pw_gid); + + /* open wtmp before chroot */ + logwtmp(ttyline, pw->pw_name, remotehost); + logged_in = 1; + + dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name); + if (guest) { + /* + * We MUST do a chdir() after the chroot. Otherwise + * the old current directory will be accessible as "." + * outside the new root! + */ + if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) { + reply(550, "Can't set guest privileges."); + return -1; + } + } else if (dochroot) { + if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) { + reply(550, "Can't change root."); + return -1; + } + } else if (chdir(pw->pw_dir) < 0) { + if (chdir("/") < 0) { + reply(530, "User %s: can't change directory to %s.", + pw->pw_name, pw->pw_dir); + return -1; + } else + lreply(code, "No directory! Logging in with home=/"); + } + if (seteuid((uid_t)pw->pw_uid) < 0) { + reply(550, "Can't set uid."); + return -1; + } + /* + * Display a login message, if it exists. + * N.B. reply(code,) must follow the message. + */ + if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) { + char *cp, line[LINE_MAX]; + + while (fgets(line, sizeof(line), fd) != NULL) { + if ((cp = strchr(line, '\n')) != NULL) + *cp = '\0'; + lreply(code, "%s", line); + } + } + if (guest) { + reply(code, "Guest login ok, access restrictions apply."); +#ifdef HAVE_SETPROCTITLE + snprintf (proctitle, sizeof(proctitle), + "%s: anonymous/%s", + remotehost, + passwd); +#endif /* HAVE_SETPROCTITLE */ + if (logging) + syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s(%s), %s", + remotehost, + inet_ntoa(his_addr.sin_addr), + passwd); + } else { + reply(code, "User %s logged in.", pw->pw_name); +#ifdef HAVE_SETPROCTITLE + snprintf(proctitle, sizeof(proctitle), "%s: %s", remotehost, pw->pw_name); + setproctitle(proctitle); +#endif /* HAVE_SETPROCTITLE */ + if (logging) + syslog(LOG_INFO, "FTP LOGIN FROM %s(%s) as %s", + remotehost, + inet_ntoa(his_addr.sin_addr), + pw->pw_name); + } + umask(defumask); + return 0; +} + +/* + * Terminate login as previous user, if any, resetting state; + * used when USER command is given or login fails. + */ +static void +end_login(void) +{ + + seteuid((uid_t)0); + if (logged_in) + logwtmp(ttyline, "", ""); + pw = NULL; + logged_in = 0; + guest = 0; + dochroot = 0; +} + +void +pass(char *passwd) +{ + int rval; + + /* some clients insists on sending a password */ + if (logged_in && askpasswd == 0){ + reply(230, "Dumpucko!"); + return; + } + + if (logged_in || askpasswd == 0) { + reply(503, "Login with USER first."); + return; + } + askpasswd = 0; + rval = 1; + if (!guest) { /* "ftp" is only account allowed no password */ + if (pw == NULL) + rval = 1; /* failure below */ + else if (otp_verify_user (&otp_ctx, passwd) == 0) { + rval = 0; + } else if((auth_level & AUTH_OTP) == 0) { + char realm[REALM_SZ]; + if((rval = krb_get_lrealm(realm, 1)) == KSUCCESS) + rval = krb_verify_user(pw->pw_name, "", realm, + passwd, 1, NULL); + if (rval == KSUCCESS ){ + if(k_hasafs()) + k_afsklog(0, 0); + }else + rval = unix_verify_user(pw->pw_name, passwd); + } else { + char *s; + + if (s = otp_error(&otp_ctx)) + lreply(530, "OTP: %s", s); + } + memset (passwd, 0, strlen(passwd)); + + /* + * If rval == 1, the user failed the authentication + * check above. If rval == 0, either Kerberos or + * local authentication succeeded. + */ + if (rval) { + reply(530, "Login incorrect."); + if (logging) + syslog(LOG_NOTICE, + "FTP LOGIN FAILED FROM %s(%s), %s", + remotehost, + inet_ntoa(his_addr.sin_addr), + curname); + pw = NULL; + if (login_attempts++ >= 5) { + syslog(LOG_NOTICE, + "repeated login failures from %s(%s)", + remotehost, + inet_ntoa(his_addr.sin_addr)); + exit(0); + } + return; + } + } + if(!do_login(230, passwd)) + return; + + /* Forget all about it... */ + end_login(); +} + +void +retrieve(char *cmd, char *name) +{ + FILE *fin = NULL, *dout; + struct stat st; + int (*closefunc) (FILE *); + char line[BUFSIZ]; + + + if (cmd == 0) { + fin = fopen(name, "r"); + closefunc = fclose; + st.st_size = 0; + if(fin == NULL){ + struct cmds { + char *ext; + char *cmd; + } cmds[] = { + {".tar", "/bin/gtar cPf - %s"}, + {".tar.gz", "/bin/gtar zcPf - %s"}, + {".tar.Z", "/bin/gtar ZcPf - %s"}, + {".gz", "/bin/gzip -c %s"}, + {".Z", "/bin/compress -c %s"}, + {NULL, NULL} + }; + struct cmds *p; + for(p = cmds; p->ext; p++){ + char *tail = name + strlen(name) - strlen(p->ext); + char c = *tail; + + if(strcmp(tail, p->ext) == 0 && + (*tail = 0) == 0 && + access(name, R_OK) == 0){ + snprintf (line, sizeof(line), p->cmd, name); + *tail = c; + break; + } + *tail = c; + } + if(p->ext){ + fin = ftpd_popen(line, "r", 0, 0); + closefunc = ftpd_pclose; + st.st_size = -1; + cmd = line; + } + } + } else { + snprintf(line, sizeof(line), cmd, name); + name = line; + fin = ftpd_popen(line, "r", 1, 0); + closefunc = ftpd_pclose; + st.st_size = -1; + } + if (fin == NULL) { + if (errno != 0) { + perror_reply(550, name); + if (cmd == 0) { + LOGCMD("get", name); + } + } + return; + } + byte_count = -1; + if (cmd == 0){ + if(fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) { + reply(550, "%s: not a plain file.", name); + goto done; + } + } + if (restart_point) { + if (type == TYPE_A) { + off_t i, n; + int c; + + n = restart_point; + i = 0; + while (i++ < n) { + if ((c=getc(fin)) == EOF) { + perror_reply(550, name); + goto done; + } + if (c == '\n') + i++; + } + } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) { + perror_reply(550, name); + goto done; + } + } + dout = dataconn(name, st.st_size, "w"); + if (dout == NULL) + goto done; + set_buffer_size(fileno(dout), 0); + send_data(fin, dout); + fclose(dout); + data = -1; + pdata = -1; +done: + if (cmd == 0) + LOGBYTES("get", name, byte_count); + (*closefunc)(fin); +} + +/* filename sanity check */ + +int +filename_check(char *filename) +{ + static const char good_chars[] = "+-=_,."; + char *p; + + p = strrchr(filename, '/'); + if(p) + filename = p + 1; + + p = filename; + + if(isalnum(*p)){ + p++; + while(*p && (isalnum(*p) || strchr(good_chars, *p))) + p++; + if(*p == '\0') + return 0; + } + lreply(553, "\"%s\" is an illegal filename.", filename); + lreply(553, "The filename must start with an alphanumeric " + "character and must only"); + reply(553, "consist of alphanumeric characters or any of the following: %s", + good_chars); + return 1; +} + +void +do_store(char *name, char *mode, int unique) +{ + FILE *fout, *din; + struct stat st; + int (*closefunc) (FILE *); + + if(guest && filename_check(name)) + return; + if (unique && stat(name, &st) == 0 && + (name = gunique(name)) == NULL) { + LOGCMD(*mode == 'w' ? "put" : "append", name); + return; + } + + if (restart_point) + mode = "r+"; + fout = fopen(name, mode); + closefunc = fclose; + if (fout == NULL) { + perror_reply(553, name); + LOGCMD(*mode == 'w' ? "put" : "append", name); + return; + } + byte_count = -1; + if (restart_point) { + if (type == TYPE_A) { + off_t i, n; + int c; + + n = restart_point; + i = 0; + while (i++ < n) { + if ((c=getc(fout)) == EOF) { + perror_reply(550, name); + goto done; + } + if (c == '\n') + i++; + } + /* + * We must do this seek to "current" position + * because we are changing from reading to + * writing. + */ + if (fseek(fout, 0L, SEEK_CUR) < 0) { + perror_reply(550, name); + goto done; + } + } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) { + perror_reply(550, name); + goto done; + } + } + din = dataconn(name, (off_t)-1, "r"); + if (din == NULL) + goto done; + set_buffer_size(fileno(din), 1); + if (receive_data(din, fout) == 0) { + if (unique) + reply(226, "Transfer complete (unique file name:%s).", + name); + else + reply(226, "Transfer complete."); + } + fclose(din); + data = -1; + pdata = -1; +done: + LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count); + (*closefunc)(fout); +} + +static FILE * +getdatasock(char *mode) +{ + int on = 1, s, t, tries; + + if (data >= 0) + return (fdopen(data, mode)); + seteuid((uid_t)0); + s = socket(AF_INET, SOCK_STREAM, 0); + if (s < 0) + goto bad; +#if defined(SO_REUSEADDR) && defined(HAVE_SETSOCKOPT) + if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, + (void *) &on, sizeof(on)) < 0) + goto bad; +#endif + /* anchor socket to avoid multi-homing problems */ + data_source.sin_family = AF_INET; + data_source.sin_addr = ctrl_addr.sin_addr; + for (tries = 1; ; tries++) { + if (bind(s, (struct sockaddr *)&data_source, + sizeof(data_source)) >= 0) + break; + if (errno != EADDRINUSE || tries > 10) + goto bad; + sleep(tries); + } + seteuid((uid_t)pw->pw_uid); +#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT) + on = IPTOS_THROUGHPUT; + if (setsockopt(s, IPPROTO_IP, IP_TOS, (void *)&on, sizeof(int)) < 0) + syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); +#endif + return (fdopen(s, mode)); +bad: + /* Return the real value of errno (close may change it) */ + t = errno; + seteuid((uid_t)pw->pw_uid); + close(s); + errno = t; + return (NULL); +} + +static FILE * +dataconn(char *name, off_t size, char *mode) +{ + char sizebuf[32]; + FILE *file; + int retry = 0, tos; + + file_size = size; + byte_count = 0; + if (size != (off_t) -1) + snprintf(sizebuf, sizeof(sizebuf), " (%ld bytes)", size); + else + strcpy(sizebuf, ""); + if (pdata >= 0) { + struct sockaddr_in from; + int s, fromlen = sizeof(from); + + s = accept(pdata, (struct sockaddr *)&from, &fromlen); + if (s < 0) { + reply(425, "Can't open data connection."); + close(pdata); + pdata = -1; + return (NULL); + } + close(pdata); + pdata = s; +#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT) + tos = IPTOS_THROUGHPUT; + setsockopt(s, IPPROTO_IP, IP_TOS, (void *)&tos, + sizeof(int)); +#endif + reply(150, "Opening %s mode data connection for '%s'%s.", + type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); + return (fdopen(pdata, mode)); + } + if (data >= 0) { + reply(125, "Using existing data connection for '%s'%s.", + name, sizebuf); + usedefault = 1; + return (fdopen(data, mode)); + } + if (usedefault) + data_dest = his_addr; + usedefault = 1; + file = getdatasock(mode); + if (file == NULL) { + reply(425, "Can't create data socket (%s,%d): %s.", + inet_ntoa(data_source.sin_addr), + ntohs(data_source.sin_port), strerror(errno)); + return (NULL); + } + data = fileno(file); + while (connect(data, (struct sockaddr *)&data_dest, + sizeof(data_dest)) < 0) { + if (errno == EADDRINUSE && retry < swaitmax) { + sleep((unsigned) swaitint); + retry += swaitint; + continue; + } + perror_reply(425, "Can't build data connection"); + fclose(file); + data = -1; + return (NULL); + } + reply(150, "Opening %s mode data connection for '%s'%s.", + type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); + return (file); +} + +/* + * Tranfer the contents of "instr" to "outstr" peer using the appropriate + * encapsulation of the data subject * to Mode, Structure, and Type. + * + * NB: Form isn't handled. + */ +static void +send_data(FILE *instr, FILE *outstr) +{ + int c, cnt, filefd, netfd; + static char *buf; + static size_t bufsize; + int i = 0; + char s[1024]; + + transflag++; + if (setjmp(urgcatch)) { + transflag = 0; + return; + } + switch (type) { + + case TYPE_A: + while ((c = getc(instr)) != EOF) { + byte_count++; + if(i > 1022){ + auth_write(fileno(outstr), s, i); + i = 0; + } + if(c == '\n') + s[i++] = '\r'; + s[i++] = c; + } + if(i) + auth_write(fileno(outstr), s, i); + auth_write(fileno(outstr), s, 0); + fflush(outstr); + transflag = 0; + if (ferror(instr)) + goto file_err; + if (ferror(outstr)) + goto data_err; + reply(226, "Transfer complete."); + return; + + case TYPE_I: + case TYPE_L: +#ifdef HAVE_MMAP +#ifndef MAP_FAILED +#define MAP_FAILED (-1) +#endif + { + struct stat st; + char *chunk; + int in = fileno(instr); + if(fstat(in, &st) == 0 && S_ISREG(st.st_mode)) { + chunk = mmap(0, st.st_size, PROT_READ, MAP_SHARED, in, 0); + if(chunk != (void *)MAP_FAILED) { + cnt = st.st_size - restart_point; + auth_write(fileno(outstr), + chunk + restart_point, + cnt); + munmap(chunk, st.st_size); + auth_write(fileno(outstr), NULL, 0); + byte_count = cnt; + transflag = 0; + } + } + } + +#endif + if(transflag){ + struct stat st; + + netfd = fileno(outstr); + filefd = fileno(instr); + buf = alloc_buffer (buf, &bufsize, + fstat(filefd, &st) >= 0 ? &st : NULL); + if (buf == NULL) { + transflag = 0; + perror_reply(451, "Local resource failure: malloc"); + return; + } + while ((cnt = read(filefd, buf, bufsize)) > 0 && + auth_write(netfd, buf, cnt) == cnt) + byte_count += cnt; + auth_write(netfd, buf, 0); /* to end an encrypted stream */ + transflag = 0; + if (cnt != 0) { + if (cnt < 0) + goto file_err; + goto data_err; + } + } + reply(226, "Transfer complete."); + return; + default: + transflag = 0; + reply(550, "Unimplemented TYPE %d in send_data", type); + return; + } + +data_err: + transflag = 0; + perror_reply(426, "Data connection"); + return; + +file_err: + transflag = 0; + perror_reply(551, "Error on input file"); +} + +/* + * Transfer data from peer to "outstr" using the appropriate encapulation of + * the data subject to Mode, Structure, and Type. + * + * N.B.: Form isn't handled. + */ +static int +receive_data(FILE *instr, FILE *outstr) +{ + int cnt, bare_lfs = 0; + static char *buf; + static size_t bufsize; + struct stat st; + + transflag++; + if (setjmp(urgcatch)) { + transflag = 0; + return (-1); + } + + buf = alloc_buffer (buf, &bufsize, + fstat(fileno(outstr), &st) >= 0 ? &st : NULL); + if (buf == NULL) { + transflag = 0; + perror_reply(451, "Local resource failure: malloc"); + return -1; + } + + switch (type) { + + case TYPE_I: + case TYPE_L: + while ((cnt = auth_read(fileno(instr), buf, bufsize)) > 0) { + if (write(fileno(outstr), buf, cnt) != cnt) + goto file_err; + byte_count += cnt; + } + if (cnt < 0) + goto data_err; + transflag = 0; + return (0); + + case TYPE_E: + reply(553, "TYPE E not implemented."); + transflag = 0; + return (-1); + + case TYPE_A: + { + char *p, *q; + int cr_flag = 0; + while ((cnt = auth_read(fileno(instr), + buf + cr_flag, + bufsize - cr_flag)) > 0){ + byte_count += cnt; + cnt += cr_flag; + cr_flag = 0; + for(p = buf, q = buf; p < buf + cnt;) { + if(*p == '\n') + bare_lfs++; + if(*p == '\r') + if(p == buf + cnt - 1){ + cr_flag = 1; + p++; + continue; + }else if(p[1] == '\n'){ + *q++ = '\n'; + p += 2; + continue; + } + *q++ = *p++; + } + fwrite(buf, q - buf, 1, outstr); + if(cr_flag) + buf[0] = '\r'; + } + if(cr_flag) + putc('\r', outstr); + fflush(outstr); + if (ferror(instr)) + goto data_err; + if (ferror(outstr)) + goto file_err; + transflag = 0; + if (bare_lfs) { + lreply(226, "WARNING! %d bare linefeeds received in ASCII mode\r\n" + " File may not have transferred correctly.\r\n", + bare_lfs); + } + return (0); + } + default: + reply(550, "Unimplemented TYPE %d in receive_data", type); + transflag = 0; + return (-1); + } + +data_err: + transflag = 0; + perror_reply(426, "Data Connection"); + return (-1); + +file_err: + transflag = 0; + perror_reply(452, "Error writing file"); + return (-1); +} + +void +statfilecmd(char *filename) +{ + FILE *fin; + int c; + char line[LINE_MAX]; + + snprintf(line, sizeof(line), "/bin/ls -la %s", filename); + fin = ftpd_popen(line, "r", 1, 0); + lreply(211, "status of %s:", filename); + while ((c = getc(fin)) != EOF) { + if (c == '\n') { + if (ferror(stdout)){ + perror_reply(421, "control connection"); + ftpd_pclose(fin); + dologout(1); + /* NOTREACHED */ + } + if (ferror(fin)) { + perror_reply(551, filename); + ftpd_pclose(fin); + return; + } + putc('\r', stdout); + } + putc(c, stdout); + } + ftpd_pclose(fin); + reply(211, "End of Status"); +} + +void +statcmd(void) +{ +#if 0 + struct sockaddr_in *sin; + u_char *a, *p; + + lreply(211, "%s FTP server status:", hostname, version); + printf(" %s\r\n", version); + printf(" Connected to %s", remotehost); + if (!isdigit(remotehost[0])) + printf(" (%s)", inet_ntoa(his_addr.sin_addr)); + printf("\r\n"); + if (logged_in) { + if (guest) + printf(" Logged in anonymously\r\n"); + else + printf(" Logged in as %s\r\n", pw->pw_name); + } else if (askpasswd) + printf(" Waiting for password\r\n"); + else + printf(" Waiting for user name\r\n"); + printf(" TYPE: %s", typenames[type]); + if (type == TYPE_A || type == TYPE_E) + printf(", FORM: %s", formnames[form]); + if (type == TYPE_L) +#if NBBY == 8 + printf(" %d", NBBY); +#else + printf(" %d", bytesize); /* need definition! */ +#endif + printf("; STRUcture: %s; transfer MODE: %s\r\n", + strunames[stru], modenames[mode]); + if (data != -1) + printf(" Data connection open\r\n"); + else if (pdata != -1) { + printf(" in Passive mode"); + sin = &pasv_addr; + goto printaddr; + } else if (usedefault == 0) { + printf(" PORT"); + sin = &data_dest; +printaddr: + a = (u_char *) &sin->sin_addr; + p = (u_char *) &sin->sin_port; +#define UC(b) (((int) b) & 0xff) + printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]), + UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); +#undef UC + } else + printf(" No data connection\r\n"); +#endif + reply(211, "End of status"); +} + +void +fatal(char *s) +{ + + reply(451, "Error in server: %s\n", s); + reply(221, "Closing connection due to server error."); + dologout(0); + /* NOTREACHED */ +} + +static void +int_reply(int, char *, const char *, va_list) +#ifdef __GNUC__ +__attribute__ ((format (printf, 3, 0))) +#endif +; + +static void +int_reply(int n, char *c, const char *fmt, va_list ap) +{ + char buf[10240]; + char *p; + p=buf; + if(n){ + snprintf(p, sizeof(buf), "%d%s", n, c); + p+=strlen(p); + } + vsnprintf(p, sizeof(buf) - strlen(p), fmt, ap); + p+=strlen(p); + snprintf(p, sizeof(buf) - strlen(p), "\r\n"); + p+=strlen(p); + auth_printf("%s", buf); + fflush(stdout); + if (debug) + syslog(LOG_DEBUG, "<--- %s- ", buf); +} + +void +reply(int n, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int_reply(n, " ", fmt, ap); + delete_ftp_command(); + va_end(ap); +} + +void +lreply(int n, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int_reply(n, "-", fmt, ap); + va_end(ap); +} + +void +nreply(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int_reply(0, NULL, fmt, ap); + va_end(ap); +} + +static void +ack(char *s) +{ + + reply(250, "%s command successful.", s); +} + +void +nack(char *s) +{ + + reply(502, "%s command not implemented.", s); +} + +/* ARGSUSED */ +void +yyerror(char *s) +{ + char *cp; + + if ((cp = strchr(cbuf,'\n'))) + *cp = '\0'; + reply(500, "'%s': command not understood.", cbuf); +} + +void +do_delete(char *name) +{ + struct stat st; + + LOGCMD("delete", name); + if (stat(name, &st) < 0) { + perror_reply(550, name); + return; + } + if ((st.st_mode&S_IFMT) == S_IFDIR) { + if (rmdir(name) < 0) { + perror_reply(550, name); + return; + } + goto done; + } + if (unlink(name) < 0) { + perror_reply(550, name); + return; + } +done: + ack("DELE"); +} + +void +cwd(char *path) +{ + + if (chdir(path) < 0) + perror_reply(550, path); + else + ack("CWD"); +} + +void +makedir(char *name) +{ + + LOGCMD("mkdir", name); + if(guest && filename_check(name)) + return; + if (mkdir(name, 0777) < 0) + perror_reply(550, name); + else{ + if(guest) + chmod(name, 0700); /* guest has umask 777 */ + reply(257, "MKD command successful."); + } +} + +void +removedir(char *name) +{ + + LOGCMD("rmdir", name); + if (rmdir(name) < 0) + perror_reply(550, name); + else + ack("RMD"); +} + +void +pwd(void) +{ + char path[MaxPathLen + 1]; + char *ret; + + /* SunOS has a broken getcwd that does popen(pwd) (!!!), this + * failes miserably when running chroot + */ + ret = getcwd(path, sizeof(path)); + if (ret == NULL) + reply(550, "%s.", strerror(errno)); + else + reply(257, "\"%s\" is current directory.", path); +} + +char * +renamefrom(char *name) +{ + struct stat st; + + if (stat(name, &st) < 0) { + perror_reply(550, name); + return NULL; + } + reply(350, "File exists, ready for destination name"); + return (name); +} + +void +renamecmd(char *from, char *to) +{ + + LOGCMD2("rename", from, to); + if(guest && filename_check(to)) + return; + if (rename(from, to) < 0) + perror_reply(550, "rename"); + else + ack("RNTO"); +} + +static void +dolog(struct sockaddr_in *sin) +{ + inaddr2str (sin->sin_addr, remotehost, sizeof(remotehost)); +#ifdef HAVE_SETPROCTITLE + snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); + setproctitle(proctitle); +#endif /* HAVE_SETPROCTITLE */ + + if (logging) + syslog(LOG_INFO, "connection from %s(%s)", + remotehost, + inet_ntoa(his_addr.sin_addr)); +} + +/* + * Record logout in wtmp file + * and exit with supplied status. + */ +void +dologout(int status) +{ + transflag = 0; + if (logged_in) { + seteuid((uid_t)0); + logwtmp(ttyline, "", ""); + dest_tkt(); + if(k_hasafs()) + k_unlog(); + } + /* beware of flushing buffers after a SIGPIPE */ +#ifdef XXX + exit(status); +#else + _exit(status); +#endif +} + +void abor(void) +{ +} + +static void +myoob(int signo) +{ +#if 0 + char *cp; +#endif + + /* only process if transfer occurring */ + if (!transflag) + return; + + /* This is all XXX */ + oobflag = 1; + /* if the command resulted in a new command, + parse that as well */ + do{ + yyparse(); + } while(ftp_command); + oobflag = 0; + +#if 0 + cp = tmpline; + if (getline(cp, 7) == NULL) { + reply(221, "You could at least say goodbye."); + dologout(0); + } + upper(cp); + if (strcmp(cp, "ABOR\r\n") == 0) { + tmpline[0] = '\0'; + reply(426, "Transfer aborted. Data connection closed."); + reply(226, "Abort successful"); + longjmp(urgcatch, 1); + } + if (strcmp(cp, "STAT\r\n") == 0) { + if (file_size != (off_t) -1) + reply(213, "Status: %ld of %ld bytes transferred", + (long)byte_count, + (long)file_size); + else + reply(213, "Status: %ld bytes transferred" + (long)byte_count); + } +#endif +} + +/* + * Note: a response of 425 is not mentioned as a possible response to + * the PASV command in RFC959. However, it has been blessed as + * a legitimate response by Jon Postel in a telephone conversation + * with Rick Adams on 25 Jan 89. + */ +void +passive(void) +{ + int len; + char *p, *a; + + pdata = socket(AF_INET, SOCK_STREAM, 0); + if (pdata < 0) { + perror_reply(425, "Can't open passive connection"); + return; + } + pasv_addr = ctrl_addr; + pasv_addr.sin_port = 0; + seteuid((uid_t)0); + if (bind(pdata, (struct sockaddr *)&pasv_addr, sizeof(pasv_addr)) < 0) { + seteuid((uid_t)pw->pw_uid); + goto pasv_error; + } + seteuid((uid_t)pw->pw_uid); + len = sizeof(pasv_addr); + if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) + goto pasv_error; + if (listen(pdata, 1) < 0) + goto pasv_error; + a = (char *) &pasv_addr.sin_addr; + p = (char *) &pasv_addr.sin_port; + +#define UC(b) (((int) b) & 0xff) + + reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]), + UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); + return; + +pasv_error: + close(pdata); + pdata = -1; + perror_reply(425, "Can't open passive connection"); + return; +} + +/* + * Generate unique name for file with basename "local". + * The file named "local" is already known to exist. + * Generates failure reply on error. + */ +static char * +gunique(char *local) +{ + static char new[MaxPathLen]; + struct stat st; + int count; + char *cp; + + cp = strrchr(local, '/'); + if (cp) + *cp = '\0'; + if (stat(cp ? local : ".", &st) < 0) { + perror_reply(553, cp ? local : "."); + return NULL; + } + if (cp) + *cp = '/'; + for (count = 1; count < 100; count++) { + snprintf (new, sizeof(new), "%s.%d", local, count); + if (stat(new, &st) < 0) + return (new); + } + reply(452, "Unique file name cannot be created."); + return (NULL); +} + +/* + * Format and send reply containing system error number. + */ +void +perror_reply(int code, char *string) +{ + reply(code, "%s: %s.", string, strerror(errno)); +} + +static char *onefile[] = { + "", + 0 +}; + +void +send_file_list(char *whichf) +{ + struct stat st; + DIR *dirp = NULL; + struct dirent *dir; + FILE *dout = NULL; + char **dirlist, *dirname; + int simple = 0; + int freeglob = 0; + glob_t gl; + char buf[MaxPathLen]; + + if (strpbrk(whichf, "~{[*?") != NULL) { + int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE; + + memset(&gl, 0, sizeof(gl)); + freeglob = 1; + if (glob(whichf, flags, 0, &gl)) { + reply(550, "not found"); + goto out; + } else if (gl.gl_pathc == 0) { + errno = ENOENT; + perror_reply(550, whichf); + goto out; + } + dirlist = gl.gl_pathv; + } else { + onefile[0] = whichf; + dirlist = onefile; + simple = 1; + } + + if (setjmp(urgcatch)) { + transflag = 0; + goto out; + } + while ((dirname = *dirlist++)) { + if (stat(dirname, &st) < 0) { + /* + * If user typed "ls -l", etc, and the client + * used NLST, do what the user meant. + */ + if (dirname[0] == '-' && *dirlist == NULL && + transflag == 0) { + retrieve("/bin/ls %s", dirname); + goto out; + } + perror_reply(550, whichf); + if (dout != NULL) { + fclose(dout); + transflag = 0; + data = -1; + pdata = -1; + } + goto out; + } + + if (S_ISREG(st.st_mode)) { + if (dout == NULL) { + dout = dataconn("file list", (off_t)-1, "w"); + if (dout == NULL) + goto out; + transflag++; + } + snprintf(buf, sizeof(buf), "%s%s\n", dirname, + type == TYPE_A ? "\r" : ""); + auth_write(fileno(dout), buf, strlen(buf)); + byte_count += strlen(dirname) + 1; + continue; + } else if (!S_ISDIR(st.st_mode)) + continue; + + if ((dirp = opendir(dirname)) == NULL) + continue; + + while ((dir = readdir(dirp)) != NULL) { + char nbuf[MaxPathLen]; + + if (!strcmp(dir->d_name, ".")) + continue; + if (!strcmp(dir->d_name, "..")) + continue; + + snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, dir->d_name); + + /* + * We have to do a stat to insure it's + * not a directory or special file. + */ + if (simple || (stat(nbuf, &st) == 0 && + S_ISREG(st.st_mode))) { + if (dout == NULL) { + dout = dataconn("file list", (off_t)-1, "w"); + if (dout == NULL) + goto out; + transflag++; + } + if(strncmp(nbuf, "./", 2) == 0) + snprintf(buf, sizeof(buf), "%s%s\n", nbuf +2, + type == TYPE_A ? "\r" : ""); + else + snprintf(buf, sizeof(buf), "%s%s\n", nbuf, + type == TYPE_A ? "\r" : ""); + auth_write(fileno(dout), buf, strlen(buf)); + byte_count += strlen(nbuf) + 1; + } + } + closedir(dirp); + } + if (dout == NULL) + reply(550, "No files found."); + else if (ferror(dout) != 0) + perror_reply(550, "Data connection"); + else + reply(226, "Transfer complete."); + + transflag = 0; + if (dout != NULL){ + auth_write(fileno(dout), buf, 0); /* XXX flush */ + + fclose(dout); + } + data = -1; + pdata = -1; +out: + if (freeglob) { + freeglob = 0; + globfree(&gl); + } +} + + +int +find(char *pattern) +{ + char line[1024]; + FILE *f; + + snprintf(line, sizeof(line), + "/bin/locate -d %s %s", + ftp_rooted("/etc/locatedb"), + pattern); + f = ftpd_popen(line, "r", 1, 1); + if(f == NULL){ + perror_reply(550, "/bin/locate"); + return 1; + } + lreply(200, "Output from find."); + while(fgets(line, sizeof(line), f)){ + if(line[strlen(line)-1] == '\n') + line[strlen(line)-1] = 0; + nreply("%s", line); + } + reply(200, "Done"); + ftpd_pclose(f); + return 0; +} + diff --git a/crypto/kerberosIV/appl/ftp/ftpd/kauth.c b/crypto/kerberosIV/appl/ftp/ftpd/kauth.c new file mode 100644 index 0000000..02d23d6 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/kauth.c @@ -0,0 +1,325 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +RCSID("$Id: kauth.c,v 1.14 1997/05/07 02:21:30 assar Exp $"); + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <time.h> +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#include <roken.h> + +#include <des.h> +#include <krb.h> +#include <kafs.h> + +#include "extern.h" +#include "krb4.h" +#include "auth.h" +#include "base64.h" + +static KTEXT_ST cip; +static unsigned int lifetime; +static time_t local_time; + +static krb_principal pr; + +static int +save_tkt(char *user, char *instance, char *realm, void *arg, + int (*key_proc)(char*, char*, char*, void*, des_cblock*), KTEXT *cipp) +{ + local_time = time(0); + memmove(&cip, *cipp, sizeof(cip)); + return -1; +} + +static int +store_ticket(KTEXT cip) +{ + char *ptr; + des_cblock session; + krb_principal sp; + unsigned char kvno; + KTEXT_ST tkt; + int left = cip->length; + + int kerror; + + time_t kdc_time; + + ptr = (char *) cip->dat; + + /* extract session key */ + memmove(session, ptr, 8); + ptr += 8; + left -= 8; + + if (strnlen(ptr, left) == left) + return(INTK_BADPW); + + /* extract server's name */ + strcpy(sp.name, ptr); + ptr += strlen(sp.name) + 1; + left -= strlen(sp.name) + 1; + + if (strnlen(ptr, left) == left) + return(INTK_BADPW); + + /* extract server's instance */ + strcpy(sp.instance, ptr); + ptr += strlen(sp.instance) + 1; + left -= strlen(sp.instance) + 1; + + if (strnlen(ptr, left) == left) + return(INTK_BADPW); + + /* extract server's realm */ + strcpy(sp.realm,ptr); + ptr += strlen(sp.realm) + 1; + left -= strlen(sp.realm) + 1; + + if(left < 3) + return INTK_BADPW; + /* extract ticket lifetime, server key version, ticket length */ + /* be sure to avoid sign extension on lifetime! */ + lifetime = (unsigned char) ptr[0]; + kvno = (unsigned char) ptr[1]; + tkt.length = (unsigned char) ptr[2]; + ptr += 3; + left -= 3; + + if (tkt.length > left) + return(INTK_BADPW); + + /* extract ticket itself */ + memmove(tkt.dat, ptr, tkt.length); + ptr += tkt.length; + left -= tkt.length; + + /* Here is where the time should be verified against the KDC. + * Unfortunately everything is sent in host byte order (receiver + * makes wrong) , and at this stage there is no way for us to know + * which byteorder the KDC has. So we simply ignore the time, + * there are no security risks with this, the only thing that can + * happen is that we might receive a replayed ticket, which could + * at most be useless. + */ + +#if 0 + /* check KDC time stamp */ + memmove(&kdc_time, ptr, sizeof(kdc_time)); + if (swap_bytes) swap_u_long(kdc_time); + + ptr += 4; + + if (abs((int)(local_time - kdc_time)) > CLOCK_SKEW) { + return(RD_AP_TIME); /* XXX should probably be better + code */ + } +#endif + + /* initialize ticket cache */ + + if (tf_create(TKT_FILE) != KSUCCESS) + return(INTK_ERR); + + if (tf_put_pname(pr.name) != KSUCCESS || + tf_put_pinst(pr.instance) != KSUCCESS) { + tf_close(); + return(INTK_ERR); + } + + + kerror = tf_save_cred(sp.name, sp.instance, sp.realm, session, + lifetime, kvno, &tkt, local_time); + tf_close(); + + return(kerror); +} + +void kauth(char *principal, char *ticket) +{ + char *p; + int ret; + + ret = krb_parse_name(principal, &pr); + if(ret){ + reply(500, "Bad principal: %s.", krb_get_err_text(ret)); + return; + } + if(pr.realm[0] == 0) + krb_get_lrealm(pr.realm, 1); + + if(ticket){ + cip.length = base64_decode(ticket, &cip.dat); + if(cip.length == -1){ + reply(500, "Failed to decode data."); + return; + } + ret = store_ticket(&cip); + if(ret){ + reply(500, "Kerberos error: %s.", krb_get_err_text(ret)); + memset(&cip, 0, sizeof(cip)); + return; + } + if(k_hasafs()) + k_afsklog(0, 0); + reply(200, "Tickets will be destroyed on exit."); + return; + } + + ret = krb_get_in_tkt (pr.name, + pr.instance, + pr.realm, + KRB_TICKET_GRANTING_TICKET, + pr.realm, + DEFAULT_TKT_LIFE, + NULL, save_tkt, NULL); + if(ret != INTK_BADPW){ + reply(500, "Kerberos error: %s.", krb_get_err_text(ret)); + return; + } + base64_encode(cip.dat, cip.length, &p); + reply(300, "P=%s T=%s", krb_unparse_name(&pr), p); + free(p); + memset(&cip, 0, sizeof(cip)); +} + + +static char * +short_date(int32_t dp) +{ + char *cp; + time_t t = (time_t)dp; + + if (t == (time_t)(-1L)) return "*** Never *** "; + cp = ctime(&t) + 4; + cp[15] = '\0'; + return (cp); +} + +void klist(void) +{ + int err; + + char *file = tkt_string(); + + krb_principal pr; + + char buf1[128], buf2[128]; + int header = 1; + CREDENTIALS c; + + + + err = tf_init(file, R_TKT_FIL); + if(err != KSUCCESS){ + reply(500, "%s", krb_get_err_text(err)); + return; + } + tf_close(); + + /* + * We must find the realm of the ticket file here before calling + * tf_init because since the realm of the ticket file is not + * really stored in the principal section of the file, the + * routine we use must itself call tf_init and tf_close. + */ + err = krb_get_tf_realm(file, pr.realm); + if(err != KSUCCESS){ + reply(500, "%s", krb_get_err_text(err)); + return; + } + + err = tf_init(file, R_TKT_FIL); + if(err != KSUCCESS){ + reply(500, "%s", krb_get_err_text(err)); + return; + } + + err = tf_get_pname(pr.name); + if(err != KSUCCESS){ + reply(500, "%s", krb_get_err_text(err)); + return; + } + err = tf_get_pinst(pr.instance); + if(err != KSUCCESS){ + reply(500, "%s", krb_get_err_text(err)); + return; + } + + /* + * You may think that this is the obvious place to get the + * realm of the ticket file, but it can't be done here as the + * routine to do this must open the ticket file. This is why + * it was done before tf_init. + */ + + lreply(200, "Principal: %s", krb_unparse_name(&pr)); + while ((err = tf_get_cred(&c)) == KSUCCESS) { + if (header) { + lreply(200, "%-15s %-15s %s", + " Issued", " Expires", " Principal (kvno)"); + header = 0; + } + strcpy(buf1, short_date(c.issue_date)); + c.issue_date = krb_life_to_time(c.issue_date, c.lifetime); + if (time(0) < (unsigned long) c.issue_date) + strcpy(buf2, short_date(c.issue_date)); + else + strcpy(buf2, ">>> Expired <<< "); + lreply(200, "%s %s %s (%d)", buf1, buf2, + krb_unparse_name_long(c.service, c.instance, c.realm), c.kvno); + } + if (header && err == EOF) { + lreply(200, "No tickets in file."); + } + reply(200, ""); +} diff --git a/crypto/kerberosIV/appl/ftp/ftpd/krb4.c b/crypto/kerberosIV/appl/ftp/ftpd/krb4.c new file mode 100644 index 0000000..2457c61 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/krb4.c @@ -0,0 +1,372 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +RCSID("$Id: krb4.c,v 1.19 1997/05/11 09:00:07 assar Exp $"); +#endif + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_NETINET_IN_h +#include <netinet/in.h> +#endif + +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <krb.h> + +#include "base64.h" +#include "extern.h" +#include "auth.h" +#include "krb4.h" + +#include <roken.h> + +static AUTH_DAT auth_dat; +static des_key_schedule schedule; + +int krb4_auth(char *auth) +{ + auth_complete = 0; + reply(334, "Using authentication type %s; ADAT must follow", auth); + return 0; +} + +int krb4_adat(char *auth) +{ + KTEXT_ST tkt; + char *p; + int kerror; + u_int32_t cs; + char msg[35]; /* size of encrypted block */ + int len; + + char inst[INST_SZ]; + + memset(&tkt, 0, sizeof(tkt)); + len = base64_decode(auth, tkt.dat); + + if(len < 0){ + reply(501, "Failed to decode base64 data."); + return -1; + } + tkt.length = len; + + k_getsockinst(0, inst, sizeof(inst)); + kerror = krb_rd_req(&tkt, "ftp", inst, 0, &auth_dat, ""); + if(kerror == RD_AP_UNDEC){ + k_getsockinst(0, inst, sizeof(inst)); + kerror = krb_rd_req(&tkt, "rcmd", inst, 0, &auth_dat, ""); + } + + if(kerror){ + reply(535, "Error reading request: %s.", krb_get_err_text(kerror)); + return -1; + } + + des_set_key(&auth_dat.session, schedule); + + cs = auth_dat.checksum + 1; + { + unsigned char tmp[4]; + tmp[0] = (cs >> 24) & 0xff; + tmp[1] = (cs >> 16) & 0xff; + tmp[2] = (cs >> 8) & 0xff; + tmp[3] = cs & 0xff; + len = krb_mk_safe(tmp, msg, 4, &auth_dat.session, + &ctrl_addr, &his_addr); + } + if(len < 0){ + reply(535, "Error creating reply: %s.", strerror(errno)); + return -1; + } + base64_encode(msg, len, &p); + reply(235, "ADAT=%s", p); + auth_complete = 1; + free(p); + return 0; +} + +int krb4_pbsz(int size) +{ + if(size > 1048576) /* XXX arbitrary number */ + size = 1048576; + buffer_size = size; + reply(200, "OK PBSZ=%d", buffer_size); + return 0; +} + +int krb4_prot(int level) +{ + if(level == prot_confidential) + return -1; + return 0; +} + +int krb4_ccc(void) +{ + reply(534, "Don't event think about it."); + return -1; +} + +int krb4_mic(char *msg) +{ + int len; + int kerror; + MSG_DAT m_data; + char *tmp, *cmd; + + cmd = strdup(msg); + + len = base64_decode(msg, cmd); + if(len < 0){ + reply(501, "Failed to decode base 64 data."); + free(cmd); + return -1; + } + kerror = krb_rd_safe(cmd, len, &auth_dat.session, + &his_addr, &ctrl_addr, &m_data); + + if(kerror){ + reply(535, "Error reading request: %s.", krb_get_err_text(kerror)); + free(cmd); + return -1; + } + + tmp = malloc(strlen(msg) + 1); + snprintf(tmp, strlen(msg) + 1, "%.*s", (int)m_data.app_length, m_data.app_data); + if(!strstr(tmp, "\r\n")) + strcat(tmp, "\r\n"); + new_ftp_command(tmp); + free(cmd); + return 0; +} + +int krb4_conf(char *msg) +{ + prot_level = prot_safe; + + reply(537, "Protection level not supported."); + return -1; +} + +int krb4_enc(char *msg) +{ + int len; + int kerror; + MSG_DAT m_data; + char *tmp, *cmd; + + cmd = strdup(msg); + + len = base64_decode(msg, cmd); + if(len < 0){ + reply(501, "Failed to decode base 64 data."); + free(cmd); + return -1; + } + kerror = krb_rd_priv(cmd, len, schedule, &auth_dat.session, + &his_addr, &ctrl_addr, &m_data); + + if(kerror){ + reply(535, "Error reading request: %s.", krb_get_err_text(kerror)); + free(cmd); + return -1; + } + + tmp = strdup(msg); + snprintf(tmp, strlen(msg) + 1, "%.*s", (int)m_data.app_length, m_data.app_data); + if(!strstr(tmp, "\r\n")) + strcat(tmp, "\r\n"); + new_ftp_command(tmp); + free(cmd); + return 0; +} + +int krb4_read(int fd, void *data, int length) +{ + static int left; + static char *extra; + static int eof; + int len, bytes, tx = 0; + + MSG_DAT m_data; + int kerror; + + if(eof){ /* if we haven't reported an end-of-file, do so */ + eof = 0; + return 0; + } + + if(left){ + if(length > left) + bytes = left; + else + bytes = length; + memmove(data, extra, bytes); + left -= bytes; + if(left) + memmove(extra, extra + bytes, left); + else + free(extra); + length -= bytes; + tx += bytes; + } + + while(length){ + unsigned char tmp[4]; + if(krb_net_read(fd, tmp, 4) < 4){ + reply(400, "Unexpected end of file.\n"); + return -1; + } + len = (tmp[0] << 24) | (tmp[1] << 16) | (tmp[2] << 8) | tmp[3]; + krb_net_read(fd, data_buffer, len); + if(data_protection == prot_safe) + kerror = krb_rd_safe(data_buffer, len, &auth_dat.session, + &his_addr, &ctrl_addr, &m_data); + else + kerror = krb_rd_priv(data_buffer, len, schedule, &auth_dat.session, + &his_addr, &ctrl_addr, &m_data); + + if(kerror){ + reply(400, "Failed to read data: %s.", krb_get_err_text(kerror)); + return -1; + } + + bytes = m_data.app_length; + if(bytes == 0){ + if(tx) eof = 1; + return tx; + } + if(bytes > length){ + left = bytes - length; + bytes = length; + extra = malloc(left); + memmove(extra, m_data.app_data + bytes, left); + } + memmove((unsigned char*)data + tx, m_data.app_data, bytes); + tx += bytes; + length -= bytes; + } + return tx; +} + +int krb4_write(int fd, void *data, int length) +{ + int len, bytes, tx = 0; + + len = buffer_size; + if(data_protection == prot_safe) + len -= 31; /* always 31 bytes overhead */ + else + len -= 26; /* at most 26 bytes */ + + do{ + if(length < len) + len = length; + if(data_protection == prot_safe) + bytes = krb_mk_safe(data, data_buffer+4, len, &auth_dat.session, + &ctrl_addr, &his_addr); + else + bytes = krb_mk_priv(data, data_buffer+4, len, schedule, + &auth_dat.session, + &ctrl_addr, &his_addr); + if(bytes == -1){ + reply(535, "Failed to make packet: %s.", strerror(errno)); + return -1; + } + data_buffer[0] = (bytes >> 24) & 0xff; + data_buffer[1] = (bytes >> 16) & 0xff; + data_buffer[2] = (bytes >> 8) & 0xff; + data_buffer[3] = bytes & 0xff; + if(krb_net_write(fd, data_buffer, bytes+4) < 0) + return -1; + length -= len; + data = (unsigned char*)data + len; + tx += len; + }while(length); + return tx; +} + +int krb4_userok(char *name) +{ + if(!kuserok(&auth_dat, name)){ + do_login(232, name); + }else{ + reply(530, "User %s access denied.", name); + } + return 0; +} + + +int +krb4_vprintf(const char *fmt, va_list ap) +{ + char buf[10240]; + char *p; + char *enc; + int code; + int len; + + vsnprintf (buf, sizeof(buf), fmt, ap); + enc = malloc(strlen(buf) + 31); + if(prot_level == prot_safe){ + len = krb_mk_safe((u_char*)buf, (u_char*)enc, strlen(buf), &auth_dat.session, + &ctrl_addr, &his_addr); + code = 631; + }else if(prot_level == prot_private){ + len = krb_mk_priv((u_char*)buf, (u_char*)enc, strlen(buf), schedule, + &auth_dat.session, &ctrl_addr, &his_addr); + code = 632; + }else{ + len = 0; /* XXX */ + code = 631; + } + base64_encode(enc, len, &p); + fprintf(stdout, "%d %s\r\n", code, p); + free(enc); + free(p); + return 0; +} diff --git a/crypto/kerberosIV/appl/ftp/ftpd/krb4.h b/crypto/kerberosIV/appl/ftp/ftpd/krb4.h new file mode 100644 index 0000000..f777dbd --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/krb4.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +/* $Id: krb4.h,v 1.6 1997/04/01 08:17:29 joda Exp $ */ + +#ifndef __KRB4_H__ +#define __KRB4_H__ + +#include <stdarg.h> + +int krb4_auth(char *auth); +int krb4_adat(char *auth); +int krb4_pbsz(int size); +int krb4_prot(int level); +int krb4_ccc(void); +int krb4_mic(char *msg); +int krb4_conf(char *msg); +int krb4_enc(char *msg); + +int krb4_read(int fd, void *data, int length); +int krb4_write(int fd, void *data, int length); + +int krb4_userok(char *name); +int krb4_vprintf(const char *fmt, va_list ap); + +#endif /* __KRB4_H__ */ diff --git a/crypto/kerberosIV/appl/ftp/ftpd/logwtmp.c b/crypto/kerberosIV/appl/ftp/ftpd/logwtmp.c new file mode 100644 index 0000000..95ab216 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/logwtmp.c @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Kungliga Tekniska + * Högskolan and its contributors. + * + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +RCSID("$Id: logwtmp.c,v 1.10 1997/05/25 15:17:56 assar Exp $"); +#endif + +#include <stdio.h> +#include <string.h> +#ifdef TIME_WITH_SYS_TIME +#include <sys/time.h> +#include <time.h> +#elif defined(HAVE_SYS_TIME_H) +#include <sys/time.h> +#else +#include <time.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_UTMP_H +#include <utmp.h> +#endif +#ifdef HAVE_UTMPX_H +#include <utmpx.h> +#endif +#include "extern.h" + +#ifndef WTMP_FILE +#ifdef _PATH_WTMP +#define WTMP_FILE _PATH_WTMP +#else +#define WTMP_FILE "/var/adm/wtmp" +#endif +#endif + +void +logwtmp(char *line, char *name, char *host) +{ + static int init = 0; + static int fd, fdx; + struct timeval tv; + struct utmp ut; +#ifdef WTMPX_FILE + struct utmpx utx; +#endif + + memset(&ut, 0, sizeof(struct utmp)); +#ifdef HAVE_UT_TYPE + if(name[0]) + ut.ut_type = USER_PROCESS; + else + ut.ut_type = DEAD_PROCESS; +#endif + strncpy(ut.ut_line, line, sizeof(ut.ut_line)); + strncpy(ut.ut_name, name, sizeof(ut.ut_name)); +#ifdef HAVE_UT_PID + ut.ut_pid = getpid(); +#endif +#ifdef HAVE_UT_HOST + strncpy(ut.ut_host, host, sizeof(ut.ut_host)); +#endif + ut.ut_time = time(NULL); + +#ifdef WTMPX_FILE + strncpy(utx.ut_line, line, sizeof(utx.ut_line)); + strncpy(utx.ut_user, name, sizeof(utx.ut_user)); + strncpy(utx.ut_host, host, sizeof(utx.ut_host)); +#ifdef HAVE_UT_SYSLEN + utx.ut_syslen = strlen(host) + 1; + if (utx.ut_syslen > sizeof(utx.ut_host)) + utx.ut_syslen = sizeof(utx.ut_host); +#endif + gettimeofday (&tv, 0); + utx.ut_tv.tv_sec = tv.tv_sec; + utx.ut_tv.tv_usec = tv.tv_usec; + + if(name[0]) + utx.ut_type = USER_PROCESS; + else + utx.ut_type = DEAD_PROCESS; +#endif + + if(!init){ + fd = open(WTMP_FILE, O_WRONLY|O_APPEND, 0); +#ifdef WTMPX_FILE + fdx = open(WTMPX_FILE, O_WRONLY|O_APPEND, 0); +#endif + init = 1; + } + if(fd >= 0) { + write(fd, &ut, sizeof(struct utmp)); /* XXX */ +#ifdef WTMPX_FILE + write(fdx, &utx, sizeof(struct utmpx)); +#endif + } +} diff --git a/crypto/kerberosIV/appl/ftp/ftpd/pathnames.h b/crypto/kerberosIV/appl/ftp/ftpd/pathnames.h new file mode 100644 index 0000000..1bd2be1 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/pathnames.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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. + * + * @(#)pathnames.h 8.1 (Berkeley) 6/4/93 + */ + +#ifdef HAVE_PATHS_H +#include <paths.h> +#endif + +#ifndef _PATH_DEVNULL +#define _PATH_DEVNULL "/dev/null" +#endif + +#ifndef _PATH_NOLOGIN +#define _PATH_NOLOGIN "/etc/nologin" +#endif + +#ifndef _PATH_BSHELL +#define _PATH_BSHELL "/bin/sh" +#endif + +#define _PATH_FTPUSERS "/etc/ftpusers" +#define _PATH_FTPCHROOT "/etc/ftpchroot" +#define _PATH_FTPWELCOME "/etc/ftpwelcome" +#define _PATH_FTPLOGINMESG "/etc/motd" diff --git a/crypto/kerberosIV/appl/ftp/ftpd/popen.c b/crypto/kerberosIV/appl/ftp/ftpd/popen.c new file mode 100644 index 0000000..58c4985 --- /dev/null +++ b/crypto/kerberosIV/appl/ftp/ftpd/popen.c @@ -0,0 +1,224 @@ +/* + * Copyright (c) 1988, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software written by Ken Arnold and + * published in UNIX Review, Vol. 6, No. 8. + * + * 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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. + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +RCSID("$Id: popen.c,v 1.16 1997/06/01 03:14:06 assar Exp $"); +#endif + +#include <sys/types.h> +#ifdef TIME_WITH_SYS_TIME +#include <sys/time.h> +#include <time.h> +#elif defined(HAVE_SYS_TIME_H) +#include <sys/time.h> +#else +#include <time.h> +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include <sys/resource.h> +#endif +#include <sys/wait.h> + +#include <errno.h> +#include <glob.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "extern.h" + +#include <roken.h> + +/* + * Special version of popen which avoids call to shell. This ensures + * no one may create a pipe to a hidden program as a side effect of a + * list or dir command. + */ +static int *pids; +static int fds; + +extern int dochroot; + +/* return path prepended with ~ftp if that file exists, otherwise + * return path unchanged + */ + +const char * +ftp_rooted(const char *path) +{ + static char home[MaxPathLen] = ""; + static char newpath[MaxPathLen]; + struct passwd *pwd; + + if(!home[0]) + if((pwd = k_getpwnam("ftp"))) + strcpy(home, pwd->pw_dir); + snprintf(newpath, sizeof(newpath), "%s/%s", home, path); + if(access(newpath, X_OK)) + strcpy(newpath, path); + return newpath; +} + + +FILE * +ftpd_popen(char *program, char *type, int do_stderr, int no_glob) +{ + char *cp; + FILE *iop; + int argc, gargc, pdes[2], pid; + char **pop, *argv[100], *gargv[1000]; + char *foo; + + if (strcmp(type, "r") && strcmp(type, "w")) + return (NULL); + + if (!pids) { + + /* This function is ugly and should be rewritten, in + * modern unices there is no such thing as a maximum + * filedescriptor. + */ + + fds = getdtablesize(); + pids = (int*)calloc(fds, sizeof(int)); + if(!pids) + return NULL; + } + if (pipe(pdes) < 0) + return (NULL); + + /* break up string into pieces */ + for (argc = 0, cp = program;; cp = NULL) { + foo = NULL; + if (!(argv[argc++] = strtok_r(cp, " \t\n", &foo))) + break; + } + + gargv[0] = (char*)ftp_rooted(argv[0]); + /* glob each piece */ + for (gargc = argc = 1; argv[argc]; argc++) { + glob_t gl; + int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE; + + memset(&gl, 0, sizeof(gl)); + if (no_glob || glob(argv[argc], flags, NULL, &gl)) + gargv[gargc++] = strdup(argv[argc]); + else + for (pop = gl.gl_pathv; *pop; pop++) + gargv[gargc++] = strdup(*pop); + globfree(&gl); + } + gargv[gargc] = NULL; + + iop = NULL; + switch(pid = fork()) { + case -1: /* error */ + close(pdes[0]); + close(pdes[1]); + goto pfree; + /* NOTREACHED */ + case 0: /* child */ + if (*type == 'r') { + if (pdes[1] != STDOUT_FILENO) { + dup2(pdes[1], STDOUT_FILENO); + close(pdes[1]); + } + if(do_stderr) + dup2(STDOUT_FILENO, STDERR_FILENO); + close(pdes[0]); + } else { + if (pdes[0] != STDIN_FILENO) { + dup2(pdes[0], STDIN_FILENO); + close(pdes[0]); + } + close(pdes[1]); + } + execv(gargv[0], gargv); + gargv[0] = argv[0]; + execv(gargv[0], gargv); + _exit(1); + } + /* parent; assume fdopen can't fail... */ + if (*type == 'r') { + iop = fdopen(pdes[0], type); + close(pdes[1]); + } else { + iop = fdopen(pdes[1], type); + close(pdes[0]); + } + pids[fileno(iop)] = pid; + +pfree: + for (argc = 1; gargv[argc] != NULL; argc++) + free(gargv[argc]); + + + return (iop); +} + +int +ftpd_pclose(FILE *iop) +{ + int fdes, status; + pid_t pid; + sigset_t sigset, osigset; + + /* + * pclose returns -1 if stream is not associated with a + * `popened' command, or, if already `pclosed'. + */ + if (pids == 0 || pids[fdes = fileno(iop)] == 0) + return (-1); + fclose(iop); + sigemptyset(&sigset); + sigaddset(&sigset, SIGINT); + sigaddset(&sigset, SIGQUIT); + sigaddset(&sigset, SIGHUP); + sigprocmask(SIG_BLOCK, &sigset, &osigset); + while ((pid = waitpid(pids[fdes], &status, 0)) < 0 && errno == EINTR) + continue; + sigprocmask(SIG_SETMASK, &osigset, NULL); + pids[fdes] = 0; + if (pid < 0) + return (pid); + if (WIFEXITED(status)) + return (WEXITSTATUS(status)); + return (1); +} |