1 /*
2  *
3  * Copyright (c) 2001 Gert Doering.  All rights reserved.
4  * Copyright (c) 2003,2004,2005,2006 Darren Tucker.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  */
27 #include "includes.h"
28 
29 #include "xmalloc.h"
30 #include "buffer.h"
31 #include "key.h"
32 #include "hostfile.h"
33 #include "auth.h"
34 #include "ssh.h"
35 #include "log.h"
36 
37 #ifdef _AIX
38 
39 #include <errno.h>
40 #if defined(HAVE_NETDB_H)
41 # include <netdb.h>
42 #endif
43 #include <uinfo.h>
44 #include <stdarg.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <sys/socket.h>
48 
49 #ifdef WITH_AIXAUTHENTICATE
50 # include <login.h>
51 # include <userpw.h>
52 # if defined(HAVE_SYS_AUDIT_H) && defined(AIX_LOGINFAILED_4ARG)
53 #  include <sys/audit.h>
54 # endif
55 # include <usersec.h>
56 #endif
57 
58 #include "port-aix.h"
59 
60 static char *lastlogin_msg = NULL;
61 
62 # ifdef HAVE_SETAUTHDB
63 static char old_registry[REGISTRY_SIZE] = "";
64 # endif
65 
66 /*
67  * AIX has a "usrinfo" area where logname and other stuff is stored -
68  * a few applications actually use this and die if it's not set
69  *
70  * NOTE: TTY= should be set, but since no one uses it and it's hard to
71  * acquire due to privsep code.  We will just drop support.
72  */
73 void
74 aix_usrinfo(struct passwd *pw)
75 {
76 	u_int i;
77 	size_t len;
78 	char *cp;
79 
80 	len = sizeof("LOGNAME= NAME= ") + (2 * strlen(pw->pw_name));
81 	cp = xmalloc(len);
82 
83 	i = snprintf(cp, len, "LOGNAME=%s%cNAME=%s%c", pw->pw_name, '\0',
84 	    pw->pw_name, '\0');
85 	if (usrinfo(SETUINFO, cp, i) == -1)
86 		fatal("Couldn't set usrinfo: %s", strerror(errno));
87 	debug3("AIX/UsrInfo: set len %d", i);
88 
89 	free(cp);
90 }
91 
92 # ifdef WITH_AIXAUTHENTICATE
93 /*
94  * Remove embedded newlines in string (if any).
95  * Used before logging messages returned by AIX authentication functions
96  * so the message is logged on one line.
97  */
98 void
99 aix_remove_embedded_newlines(char *p)
100 {
101 	if (p == NULL)
102 		return;
103 
104 	for (; *p; p++) {
105 		if (*p == '\n')
106 			*p = ' ';
107 	}
108 	/* Remove trailing whitespace */
109 	if (*--p == ' ')
110 		*p = '\0';
111 }
112 
113 /*
114  * Test specifically for the case where SYSTEM == NONE and AUTH1 contains
115  * anything other than NONE or SYSTEM, which indicates that the admin has
116  * configured the account for purely AUTH1-type authentication.
117  *
118  * Since authenticate() doesn't check AUTH1, and sshd can't sanely support
119  * AUTH1 itself, in such a case authenticate() will allow access without
120  * authentation, which is almost certainly not what the admin intends.
121  *
122  * (The native tools, eg login, will process the AUTH1 list in addition to
123  * the SYSTEM list by using ckuserID(), however ckuserID() and AUTH1 methods
124  * have been deprecated since AIX 4.2.x and would be very difficult for sshd
125  * to support.
126  *
127  * Returns 0 if an unsupportable combination is found, 1 otherwise.
128  */
129 static int
130 aix_valid_authentications(const char *user)
131 {
132 	char *auth1, *sys, *p;
133 	int valid = 1;
134 
135 	if (getuserattr((char *)user, S_AUTHSYSTEM, &sys, SEC_CHAR) != 0) {
136 		logit("Can't retrieve attribute SYSTEM for %s: %.100s",
137 		    user, strerror(errno));
138 		return 0;
139 	}
140 
141 	debug3("AIX SYSTEM attribute %s", sys);
142 	if (strcmp(sys, "NONE") != 0)
143 		return 1;	/* not "NONE", so is OK */
144 
145 	if (getuserattr((char *)user, S_AUTH1, &auth1, SEC_LIST) != 0) {
146 		logit("Can't retrieve attribute auth1 for %s: %.100s",
147 		    user, strerror(errno));
148 		return 0;
149 	}
150 
151 	p = auth1;
152 	/* A SEC_LIST is concatenated strings, ending with two NULs. */
153 	while (p[0] != '\0' && p[1] != '\0') {
154 		debug3("AIX auth1 attribute list member %s", p);
155 		if (strcmp(p, "NONE") != 0 && strcmp(p, "SYSTEM")) {
156 			logit("Account %s has unsupported auth1 value '%s'",
157 			    user, p);
158 			valid = 0;
159 		}
160 		p += strlen(p) + 1;
161 	}
162 
163 	return (valid);
164 }
165 
166 /*
167  * Do authentication via AIX's authenticate routine.  We loop until the
168  * reenter parameter is 0, but normally authenticate is called only once.
169  *
170  * Note: this function returns 1 on success, whereas AIX's authenticate()
171  * returns 0.
172  */
173 int
174 sys_auth_passwd(struct ssh *ssh, const char *password)
175 {
176 	Authctxt *ctxt = ssh->authctxt;
177 	char *authmsg = NULL, *msg = NULL, *name = ctxt->pw->pw_name;
178 	int authsuccess = 0, expired, reenter, result;
179 
180 	do {
181 		result = authenticate((char *)name, (char *)password, &reenter,
182 		    &authmsg);
183 		aix_remove_embedded_newlines(authmsg);
184 		debug3("AIX/authenticate result %d, authmsg %.100s", result,
185 		    authmsg);
186 	} while (reenter);
187 
188 	if (!aix_valid_authentications(name))
189 		result = -1;
190 
191 	if (result == 0) {
192 		authsuccess = 1;
193 
194 		/*
195 		 * Record successful login.  We don't have a pty yet, so just
196 		 * label the line as "ssh"
197 		 */
198 		aix_setauthdb(name);
199 
200 		/*
201 		 * Check if the user's password is expired.
202 		 */
203 		expired = passwdexpired(name, &msg);
204 		if (msg && *msg) {
205 			buffer_append(ctxt->loginmsg, msg, strlen(msg));
206 			aix_remove_embedded_newlines(msg);
207 		}
208 		debug3("AIX/passwdexpired returned %d msg %.100s", expired, msg);
209 
210 		switch (expired) {
211 		case 0: /* password not expired */
212 			break;
213 		case 1: /* expired, password change required */
214 			ctxt->force_pwchange = 1;
215 			break;
216 		default: /* user can't change(2) or other error (-1) */
217 			logit("Password can't be changed for user %s: %.100s",
218 			    name, msg);
219 			free(msg);
220 			authsuccess = 0;
221 		}
222 
223 		aix_restoreauthdb();
224 	}
225 
226 	free(authmsg);
227 
228 	return authsuccess;
229 }
230 
231 /*
232  * Check if specified account is permitted to log in.
233  * Returns 1 if login is allowed, 0 if not allowed.
234  */
235 int
236 sys_auth_allowed_user(struct passwd *pw, Buffer *loginmsg)
237 {
238 	char *msg = NULL;
239 	int result, permitted = 0;
240 	struct stat st;
241 
242 	/*
243 	 * Don't perform checks for root account (PermitRootLogin controls
244 	 * logins via ssh) or if running as non-root user (since
245 	 * loginrestrictions will always fail due to insufficient privilege).
246 	 */
247 	if (pw->pw_uid == 0 || geteuid() != 0) {
248 		debug3("%s: not checking", __func__);
249 		return 1;
250 	}
251 
252 	result = loginrestrictions(pw->pw_name, S_RLOGIN, NULL, &msg);
253 	if (result == 0)
254 		permitted = 1;
255 	/*
256 	 * If restricted because /etc/nologin exists, the login will be denied
257 	 * in session.c after the nologin message is sent, so allow for now
258 	 * and do not append the returned message.
259 	 */
260 	if (result == -1 && errno == EPERM && stat(_PATH_NOLOGIN, &st) == 0)
261 		permitted = 1;
262 	else if (msg != NULL)
263 		buffer_append(loginmsg, msg, strlen(msg));
264 	if (msg == NULL)
265 		msg = xstrdup("(none)");
266 	aix_remove_embedded_newlines(msg);
267 	debug3("AIX/loginrestrictions returned %d msg %.100s", result, msg);
268 
269 	if (!permitted)
270 		logit("Login restricted for %s: %.100s", pw->pw_name, msg);
271 	free(msg);
272 	return permitted;
273 }
274 
275 int
276 sys_auth_record_login(const char *user, const char *host, const char *ttynm,
277     Buffer *loginmsg)
278 {
279 	char *msg = NULL;
280 	int success = 0;
281 
282 	aix_setauthdb(user);
283 	if (loginsuccess((char *)user, (char *)host, (char *)ttynm, &msg) == 0) {
284 		success = 1;
285 		if (msg != NULL) {
286 			debug("AIX/loginsuccess: msg %s", msg);
287 			if (lastlogin_msg == NULL)
288 				lastlogin_msg = msg;
289 		}
290 	}
291 	aix_restoreauthdb();
292 	return (success);
293 }
294 
295 char *
296 sys_auth_get_lastlogin_msg(const char *user, uid_t uid)
297 {
298 	char *msg = lastlogin_msg;
299 
300 	lastlogin_msg = NULL;
301 	return msg;
302 }
303 
304 #  ifdef CUSTOM_FAILED_LOGIN
305 /*
306  * record_failed_login: generic "login failed" interface function
307  */
308 void
309 record_failed_login(const char *user, const char *hostname, const char *ttyname)
310 {
311 	if (geteuid() != 0)
312 		return;
313 
314 	aix_setauthdb(user);
315 #   ifdef AIX_LOGINFAILED_4ARG
316 	loginfailed((char *)user, (char *)hostname, (char *)ttyname,
317 	    AUDIT_FAIL_AUTH);
318 #   else
319 	loginfailed((char *)user, (char *)hostname, (char *)ttyname);
320 #   endif
321 	aix_restoreauthdb();
322 }
323 #  endif /* CUSTOM_FAILED_LOGIN */
324 
325 /*
326  * If we have setauthdb, retrieve the password registry for the user's
327  * account then feed it to setauthdb.  This will mean that subsequent AIX auth
328  * functions will only use the specified loadable module.  If we don't have
329  * setauthdb this is a no-op.
330  */
331 void
332 aix_setauthdb(const char *user)
333 {
334 #  ifdef HAVE_SETAUTHDB
335 	char *registry;
336 
337 	if (setuserdb(S_READ) == -1) {
338 		debug3("%s: Could not open userdb to read", __func__);
339 		return;
340 	}
341 
342 	if (getuserattr((char *)user, S_REGISTRY, &registry, SEC_CHAR) == 0) {
343 		if (setauthdb(registry, old_registry) == 0)
344 			debug3("AIX/setauthdb set registry '%s'", registry);
345 		else
346 			debug3("AIX/setauthdb set registry '%s' failed: %s",
347 			    registry, strerror(errno));
348 	} else
349 		debug3("%s: Could not read S_REGISTRY for user: %s", __func__,
350 		    strerror(errno));
351 	enduserdb();
352 #  endif /* HAVE_SETAUTHDB */
353 }
354 
355 /*
356  * Restore the user's registry settings from old_registry.
357  * Note that if the first aix_setauthdb fails, setauthdb("") is still safe
358  * (it restores the system default behaviour).  If we don't have setauthdb,
359  * this is a no-op.
360  */
361 void
362 aix_restoreauthdb(void)
363 {
364 #  ifdef HAVE_SETAUTHDB
365 	if (setauthdb(old_registry, NULL) == 0)
366 		debug3("%s: restoring old registry '%s'", __func__,
367 		    old_registry);
368 	else
369 		debug3("%s: failed to restore old registry %s", __func__,
370 		    old_registry);
371 #  endif /* HAVE_SETAUTHDB */
372 }
373 
374 # endif /* WITH_AIXAUTHENTICATE */
375 
376 # ifdef USE_AIX_KRB_NAME
377 /*
378  * aix_krb5_get_principal_name: returns the user's kerberos client principal name if
379  * configured, otherwise NULL.  Caller must free returned string.
380  */
381 char *
382 aix_krb5_get_principal_name(char *pw_name)
383 {
384 	char *authname = NULL, *authdomain = NULL, *principal = NULL;
385 
386 	setuserdb(S_READ);
387 	if (getuserattr(pw_name, S_AUTHDOMAIN, &authdomain, SEC_CHAR) != 0)
388 		debug("AIX getuserattr S_AUTHDOMAIN: %s", strerror(errno));
389 	if (getuserattr(pw_name, S_AUTHNAME, &authname, SEC_CHAR) != 0)
390 		debug("AIX getuserattr S_AUTHNAME: %s", strerror(errno));
391 
392 	if (authdomain != NULL)
393 		xasprintf(&principal, "%s@%s", authname ? authname : pw_name, authdomain);
394 	else if (authname != NULL)
395 		principal = xstrdup(authname);
396 	enduserdb();
397 	return principal;
398 }
399 # endif /* USE_AIX_KRB_NAME */
400 
401 # if defined(AIX_GETNAMEINFO_HACK) && !defined(BROKEN_ADDRINFO)
402 # undef getnameinfo
403 /*
404  * For some reason, AIX's getnameinfo will refuse to resolve the all-zeros
405  * IPv6 address into its textual representation ("::"), so we wrap it
406  * with a function that will.
407  */
408 int
409 sshaix_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
410     size_t hostlen, char *serv, size_t servlen, int flags)
411 {
412 	struct sockaddr_in6 *sa6;
413 	u_int32_t *a6;
414 
415 	if (flags & (NI_NUMERICHOST|NI_NUMERICSERV) &&
416 	    sa->sa_family == AF_INET6) {
417 		sa6 = (struct sockaddr_in6 *)sa;
418 		a6 = sa6->sin6_addr.u6_addr.u6_addr32;
419 
420 		if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) {
421 			strlcpy(host, "::", hostlen);
422 			snprintf(serv, servlen, "%d", sa6->sin6_port);
423 			return 0;
424 		}
425 	}
426 	return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
427 }
428 # endif /* AIX_GETNAMEINFO_HACK */
429 
430 # if defined(USE_GETGRSET)
431 #  include <stdlib.h>
432 int
433 getgrouplist(const char *user, gid_t pgid, gid_t *groups, int *grpcnt)
434 {
435 	char *cp, *grplist, *grp;
436 	gid_t gid;
437 	int ret = 0, ngroups = 0, maxgroups;
438 	long l;
439 
440 	maxgroups = *grpcnt;
441 
442 	if ((cp = grplist = getgrset(user)) == NULL)
443 		return -1;
444 
445 	/* handle zero-length case */
446 	if (maxgroups <= 0) {
447 		*grpcnt = 0;
448 		return -1;
449 	}
450 
451 	/* copy primary group */
452 	groups[ngroups++] = pgid;
453 
454 	/* copy each entry from getgrset into group list */
455 	while ((grp = strsep(&grplist, ",")) != NULL) {
456 		l = strtol(grp, NULL, 10);
457 		if (ngroups >= maxgroups || l == LONG_MIN || l == LONG_MAX) {
458 			ret = -1;
459 			goto out;
460 		}
461 		gid = (gid_t)l;
462 		if (gid == pgid)
463 			continue;	/* we have already added primary gid */
464 		groups[ngroups++] = gid;
465 	}
466 out:
467 	free(cp);
468 	*grpcnt = ngroups;
469 	return ret;
470 }
471 # endif	/* USE_GETGRSET */
472 
473 #endif /* _AIX */
474