LdapUserHandler.java 12.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
/*
 * Copyright Codecrew Ry
 * 
 * All rights reserved.
 * 
 * This license applies to any software containing a notice placed by the 
 * copyright holder. Such software is herein referred to as the Software. 
 * This license covers modification, distribution and use of the Software. 
 * 
 * Any distribution and use in source and binary forms, with or without 
 * modification is not permitted without explicit written permission from the 
 * copyright owner. 
 * 
 * A non-exclusive royalty-free right is granted to the copyright owner of the 
 * Software to use, modify and distribute all modifications to the Software in 
 * future versions of the Software. 
 * 
 */
package fi.codecrew.moya.beanutil;

/**
 * Copyright Iudex / Tuomas Riihimäki
 * 
 */
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.OrgRole;
import fi.codecrew.moya.utilities.PasswordFunctions;

public class LdapUserHandler {
	private final String ldapURI;
	private final String userBaseDn;
	//private final String roleBaseDn;
	private final String mgmtPass;
	private final String mgmtUser;
	private final String roleBaseDn;

	private String fallbackuser = null;
	private String fallbackpass = null;

	private static final String MEMBER_OF_FIELD = "memberOf";

	private static final Logger logger = LoggerFactory.getLogger(LdapUserHandler.class);
	private static final Charset LATIN1 = Charset.forName("ISO-8859-1");

	private Integer gidBase = 20000;
	private Integer uidBase = 20000;

	public enum PasswordChangeStatus {
		PWD_CHANGED, PWD_COMPLEXITY_NOT_MET, UNKNOWN_ERROR, WRONG_PASSWORD, UNKNOWN_USER,

	}

	public LdapUserHandler(String ldapUri, String userBaseDn, String roleBaseDn, String mgmtUser, String mgmtPass)
	{
		this.ldapURI = ldapUri;
		this.userBaseDn = userBaseDn;
		this.roleBaseDn = roleBaseDn;
		this.mgmtUser = mgmtUser;
		this.mgmtPass = mgmtPass;
	}

	protected InitialLdapContext getContext() throws NamingException {

		return createInitialContext(mgmtUser, mgmtPass, true);
	}

	private InitialLdapContext createInitialContext(String userRDN, String password, boolean pool) throws NamingException {
		Hashtable<String, String> authEnv = new Hashtable<String, String>(11);
		authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		authEnv.put(Context.PROVIDER_URL, ldapURI);

		if (password != null && userRDN != null && !userRDN.isEmpty()) {

			authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
			authEnv.put(Context.SECURITY_PRINCIPAL, userRDN);
			authEnv.put(Context.SECURITY_CREDENTIALS, password);
			authEnv.put(Context.REFERRAL, "follow");

			if (ldapURI.startsWith("ldaps"))
			{
				authEnv.put("java.naming.ldap.factory.socket",
						"fi.iudex.utils.ldap.NocheckSSLSocketFactory");
				authEnv.put(Context.SECURITY_PROTOCOL, "ssl");

			}
			if (pool) {
				// Default AD timeout value is 900..
				authEnv.put("com.sun.jndi.ldap.connect.pool.timeout", "900");
				authEnv.put("com.sun.jndi.ldap.connect.pool", "true");
			}
			// authEnv.put(Context.SECURITY_PROTOCOL, "ssl");
		}

		return new InitialLdapContext(authEnv, null);
	}

	protected List<String> createLdapAttrSingleAttrSearch(String baseDn, String filter, String field) {
		Map<String, List<String>> retMap = createLdapAttrUniqueDnSearch(baseDn, filter, field);
		List<String> ret = null;
		if (retMap != null) {
			ret = retMap.get(field);
		}
		return ret;
	}

	protected Map<String, List<String>> createLdapAttrUniqueDnSearch(String baseDn, String filter, String... fields)
	{
		Map<String, Map<String, List<String>>> retMap = createLdapAttrSearch(baseDn, filter, fields);
		Map<String, List<String>> ret = null;
		if (retMap != null) {
			if (retMap.isEmpty()) {
				ret = new HashMap<>();
			} else if (retMap.size() != 1) {
				throw new RuntimeException("Got multiple results for attribute search with filter: " + filter);
			} else {
				ret = retMap.values().iterator().next();
			}
		}
		return ret;
	}

	protected Map<String, Map<String, List<String>>> createLdapAttrSearch(String baseDn, String filter, String... fields)
	{
		InitialLdapContext ctx = null;
		Map<String, Map<String, List<String>>> ret = new HashMap<>();
		try {
			ctx = getContext();
			SearchControls ctls = new SearchControls();
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			ctls.setReturningAttributes(fields);

			NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, ctls);
			while (results.hasMore())
			{
				SearchResult result = results.next();
				logger.info("Got dn:{}", result.getName());
				Map<String, List<String>> resultAttrs = ret.get(result.getName());
				if (resultAttrs == null) {
					resultAttrs = new HashMap<>();
					ret.put(result.getName(), resultAttrs);
				}
				NamingEnumeration<? extends Attribute> searchAttrs = result.getAttributes().getAll();

				while (searchAttrs.hasMore()) {
					Attribute next = searchAttrs.next();
					if (next == null || next.get() == null)
						continue;
					logger.info("Got {}, {}, {}", new Object[] { next.getID(), next.get(), searchAttrs.hasMore() });

					List<String> resultList = resultAttrs.get(next.getID());
					if (resultList == null) {
						resultList = new ArrayList<>();
						resultAttrs.put(next.getID(), resultList);
					}
					NamingEnumeration<?> searchField = next.getAll();
					while (searchField.hasMore()) {
						Object fieldResult = searchField.next();
						if (fieldResult != null) {
							resultList.add(fieldResult.toString());
						}
					}
				}
			}

		} catch (NamingException e) {
			logger.warn("Error searching parameters", e);
		} finally {
			close(ctx);
		}
		return ret;
	}

	//	public Set<String> getMemberships(String user) {
	//		Set<String> rolenames = new HashSet<String>();
	//		InitialLdapContext ctx = null;
	//		try {
	//			ctx = getContext();
	//			NamingEnumeration<SearchResult> roleSearch = getLdapParameters(ctx, user, MEMBER_OF_FIELD);
	//			if (roleSearch.hasMore())
	//			{
	//				SearchResult result = roleSearch.next();
	//
	//				if (roleSearch.hasMore()) {
	//					logger.warn("Found multiple users Clearing usergroups! {}", roleSearch.next());
	//					return null;
	//				}
	//				Attribute groupAttrs = result.getAttributes().get(MEMBER_OF_FIELD);
	//
	//				if (groupAttrs != null) {
	//					NamingEnumeration<?> roleOUs = groupAttrs.getAll();
	//					while (roleOUs.hasMore()) {
	//						String roleObject = roleOUs.next().toString();
	//						Matcher roleFinder = GROUP_PATTERN.matcher(roleObject);
	//
	//						if (roleFinder.find()) {
	//							String roleName = roleFinder.group(1);
	//							logger.info("Got group {} to user {}", roleName, user);
	//							rolenames.add(roleName);
	//						}
	//						else {
	//							logger.info("role pattern did not match {}", roleObject);
	//						}
	//					}
	//				}
	//
	//			}
	//		} catch (CommunicationException ce) {
	//			rolenames = null;
	//			logger.info("Error connecting to server", ce);
	//
	//		} catch (NamingException e) {
	//			logger.warn("Error while getting group names.", e);
	//		} finally {
	//			close(ctx);
	//		}
	//		return rolenames;
	//
	//	}

	protected NamingEnumeration<SearchResult> getLdapParameters(InitialLdapContext ctx, String user, String... attrs) throws NamingException {

		StringBuilder filter = new StringBuilder("(&(objectClass=posixAccount)(uid=").append(user).append("))");
		SearchControls ctls = new SearchControls();
		ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		ctls.setReturningAttributes(attrs);

		return ctx.search(this.userBaseDn, filter.toString(), ctls);

	}

	public String createUser(EventUser user, List<OrgRole> roles)
	{
		InitialLdapContext ctx = null;
		OrgRole primary = null;

		for (OrgRole role : roles) {

			if (role.isLdapRole() && (primary == null || primary.getLdapWeight() < role.getLdapWeight())) {
				primary = role;
			}
		}
		String dnStr = null;

		try {

			StringBuilder dnBld = new StringBuilder();
			dnBld.append("uid=").append(user.getLogin());
			dnBld.append(",ou=").append(primary.getName());
			dnBld.append(",").append(userBaseDn);
			String dn = dnBld.toString();
			ctx = getContext();
			BasicAttributes entry = new BasicAttributes();
			entry.put(new BasicAttribute("uid", user.getLogin()));
			entry.put(new BasicAttribute("givenName", user.getFirstnames()));
			entry.put(new BasicAttribute("sn", user.getLastname()));
			entry.put(new BasicAttribute("cn", user.getWholeName()));
			entry.put(new BasicAttribute("loginShell", "/bin/bash"));
			entry.put(new BasicAttribute("homeDirectory", user.getLogin()));
			entry.put(new BasicAttribute("uidNumber", uidBase + user.getId()));
			entry.put(new BasicAttribute("gidNumber", gidBase + primary.getId()));
			entry.put(new BasicAttribute("userPassword", user.getPassword()));
			entry.put(new BasicAttribute("mail", user.getEmail()));

			BasicAttribute oc = new BasicAttribute("objectClass");
			oc.add("inetOrgPerson");
			oc.add("posixAccount");
			oc.add("shadowAccount");
			oc.add("person");
			oc.add("organizationalPerson");
			entry.put(oc);

			ctx.createSubcontext(dn, entry);
			dnStr = dn;

		} catch (NamingException e) {
			logger.warn("Error while creating user to ldap");
		} finally {
			close(ctx);
		}
		return dnStr;
	}

	protected String buildUserRdn(String username) {
		InitialLdapContext ctx = null;
		String ret = null;
		try {
			ctx = getContext();
			SearchControls ctls = new SearchControls();
			ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			ctls.setReturningAttributes(new String[] { "dn" });
			NamingEnumeration<SearchResult> result = ctx.search(this.userBaseDn, "uid=" + username, ctls);
			if (result.hasMore()) {
				SearchResult dn = result.next();
				ret = dn.getNameInNamespace();
			}
		} catch (NamingException e) {
			logger.warn("Error building RDN", e);
		} finally {
			close(ctx);
		}
		return ret;
	}

	public boolean authenticate(String username, char[] passwd) {
		if (username == null || passwd == null || username.isEmpty()) {
			return false;
		}
		String pwd = new String(passwd);
		if (pwd.isEmpty()) {
			return false;
		}
		InitialLdapContext userCtx = null;
		try {
			String userDn = buildUserRdn(username);
			if (userDn == null || userDn.isEmpty()) {
				logger.info("Username {}, not found when authenticating");
				return false;
			}
			userCtx = createInitialContext(userDn, pwd, false);
			return true;
		} catch (AuthenticationException authEx) {
			logger.info("Authentication failed!", authEx);
		} catch (CommunicationException ce) {
			// If ldap server can not be reached, check if we are trying to auth with fallback credentials 
			// WARNING!!!! THIS IS A BACKDOOR! DO NOT USE IN PRODUCTION!
			if (username.equals(fallbackuser) && pwd.equals(fallbackpass)) {
				logger.warn("Login successfull for backupuser. ");
				return true;
			} else {
				logger.info("Error connecting to ldapserver", ce);
			}
		} catch (NamingException e) {
			logger.warn("Error connecting to auth context", e);
		} finally {
			close(userCtx);
		}
		return false;
	}

	protected void close(InitialLdapContext userCtx) {
		try {
			if (userCtx != null) {
				userCtx.close();
			}
			userCtx = null;
		} catch (NamingException e) {
			logger.warn("Error closing...", e);
		}
	}

	public PasswordChangeStatus changePassword(String username, String oldPwd, String newPwd) {
		InitialLdapContext userCtx = null;
		try {
			String newHash = PasswordFunctions.getEncryptedPassword(newPwd);

			String userDn = buildUserRdn(username);
			if (userDn == null || userDn.isEmpty()) {
				return PasswordChangeStatus.UNKNOWN_USER;
			}
			logger.info("Chpass {} for user {} ", newHash, userDn);

			userCtx = createInitialContext(userDn, oldPwd, false);

			ModificationItem[] mods = new ModificationItem[1];
			Attribute mod0 = new BasicAttribute("userpassword", newHash);
			mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);

			userCtx.modifyAttributes(userDn, mods);
		} catch (NamingException e) {
			logger.warn("Error changing password", e);
			return PasswordChangeStatus.UNKNOWN_ERROR;
		} finally {
			close(userCtx);
		}
		return PasswordChangeStatus.PWD_CHANGED;
	}

	protected void setFallbackpass(String fallbackpass) {
		this.fallbackpass = fallbackpass;
	}

	protected void setFallbackuser(String fallbackuser) {
		this.fallbackuser = fallbackuser;
	}
}