All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.jee.api.sql.Authenticate Maven / Gradle / Ivy

/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.jee.api.sql;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.naming.AuthenticationException;
import javax.naming.NamingException;

import base.KeyValue;
import base.Query;
import base.jee.Constants;
import base.jee.api.model.Location;
import base.json.Json;
import base.ldap.LdapHelper;
import base.security.PermissionException;
import base.security.User;
import base.text.Password;
import base.text.StringHelper;

import static base.jee.api.sql.util.AddPerson.addPerson;
import static base.jee.api.sql.util.CreateSession.createSession;
import static base.jee.api.sql.util.IpLocation.ipLocation;
import static base.jee.api.sql.util.Log.log;
import static base.jee.api.sql.util.UpdatePersonFromLdap.updatePersonFromLdap;
import static base.text.StringHelper.chomp;

/**
 */
public class Authenticate extends Query {

	private SqlAPI api;
	private String site;
	private String currentToken;
	private String email;
	private String password;
	private String ip;

	public Authenticate() {
	}

	public Authenticate(SqlAPI api, String site, String currentToken, String email, String password, String ip) {

		if(api == null) {
			throw new IllegalArgumentException("Invalid parameter: api");
		}
		if(email == null) {
			throw new IllegalArgumentException("Invalid parameter: email");
		}
		if(password == null) {
			throw new IllegalArgumentException("Invalid parameter: password");
		}

		if(currentToken != null && currentToken.trim().length() > Constants.MAX_TOKEN_LENGTH) {
			throw new IllegalArgumentException("Invalid token.");
		}
		if(chomp(email).length() > Constants.MAX_USERNAME_LENGTH) {
			throw new IllegalArgumentException("Invalid username. Usernames should not have more than " + Constants.MAX_USERNAME_LENGTH + " characters.");
		}
		if(chomp(password).length() > Constants.MAX_PASSWORD_LENGTH) {
			throw new IllegalArgumentException("Invalid password. Passwords should not have more than " + Constants.MAX_PASSWORD_LENGTH + " characters.");
		}
		if(ip != null && ip.trim().length() > Constants.MAX_IP_ADDRESS_LENGTH) {
			throw new IllegalArgumentException("Invalid IP address. IP address should not have more than " + Constants.MAX_IP_ADDRESS_LENGTH + " characters.");
		}

		this.api = api;
		this.site = site;
		this.currentToken = currentToken;
		this.email = chomp(email).toLowerCase();
		this.password = chomp(password);
		this.ip = ip == null?null:ip.trim();
	}

	@Override
	public Query newWithParameters(Map parameters) throws IOException, PermissionException {
		String email = (String)parameters.get("email");
		if(email == null) {
			email = (String)parameters.get("username");
		}

		return new Authenticate(
				(SqlAPI)parameters.get("api"),
				((User)parameters.get("user")).getSite(),
				(String)parameters.get("current_token"),
				email,
				(String)parameters.get("password"),
				((User)parameters.get("user")).getIp());
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();
		String token = null;
		Connection c = null;
		PreparedStatement s = null;
		ResultSet r = null;

		try {
			c = api.getDataSource().getConnection();
			c.setAutoCommit(false);

			if(isThrottled(c, ip, "ip")) {
				log(c, "SEVERE", null, "Blocked authentication for throttled IP address: " + ip);
				c.commit();
				c.close();
				c = null;
				results.add(new KeyValue("error", "Sign-in from this IP address is temporarily disabled due to repated sign in failures. Please try again shortly."));
				return results;
			}

			if(isThrottled(c, email, "auth")) {
				markForThrottling(c, ip, "ip");
				log(c, "SEVERE", null, "Blocked authentication for throttled email: " + email);
				c.commit();
				c.close();
				c = null;
				results.add(new KeyValue("error", "Sign-in using this account is temporarily disabled due to repeated sign in failures. Please try again shortly."));
				return results;
			}

			if(password.trim().length() < Constants.MIN_PASSWORD_LENGTH) {
				badUser(c, email, ip);
				c.commit();
				c.close();
				c = null;
				results.add(new KeyValue("error", "Invalid password."));
				return results;
			}

			UUID personUuid = null;

			s = c.prepareStatement("select uuid, password, expiry from person where " + (email.contains("@")?"email":"username") + "=?");
			s.setString(1, email);
			r = s.executeQuery();
			if(r.next() && r.getString(2) != null && r.getString(2).length() > 0) {
				personUuid = UUID.fromString(r.getString(1));

				// Expiry check before password check, ensuring there is no fall through
				// to LDAP authentication in this case.
				if(r.getLong(3) > 0 && new Date(r.getLong(3)).getTime() < new Date().getTime()) {
					log(c, "FINE", User.userWithUuidAndIp(personUuid, ip, site), "Sign-in attempted from account that is expired.");
					return null;
				}

				// If password hash does not match password, we forget this search result,
				// this enables a lookup on LDAP (below).
				if(!Password.verifyPassword(r.getString(2), password)) {
					personUuid = null;
				}

				// Internal authentication success
			}
			r.close();
			r = null;
			s.close();
			s = null;

			// Internal password check failed. Do LDAP lookup if this feature is configured to be enabled.
			if(personUuid == null) {
				boolean ldapEnabled = api.getSettingsCache().get("ldap.enabled", "false").equalsIgnoreCase("true");
				String ldapUrl = api.getSettingsCache().get("ldap.url", null);
				String ldapUserDn = api.getSettingsCache().get("ldap.userdn", null);

				if(ldapEnabled && !email.contains("@")) {
					String user = ldapUserDn.replace("{u}", LdapHelper.ldapEscape(email));
					LdapHelper ldap;
					Map attributes;
					try {
						ldap = new LdapHelper(ldapUrl, user, password, true);
						attributes = ldap.getAttributes(user);
					} catch (AuthenticationException e) {
						badUser(c, email, ip);
						log(c, "FINE", User.userWithIp(ip, site), "Invalid internal and/or ldap username or password. Username: " + email);
						c.commit();
						c.close();
						c = null;
						results.add(new KeyValue("error", "Invalid username or password."));
						return results;
					} catch (NamingException | IOException e) {
						log(c, "SEVERE", User.userWithIp(ip, site), "Problem communicating with LDAP server. user: " + user + " - " + StringHelper.exceptionToString(e, "\n    "));
						c.commit();
						c.close();
						c = null;
						results.add(new KeyValue("error", "Authentication temporarily unavailable."));
						return results;
					}
					personUuid = createOrUpdatePersonUsingLdapAttributes(c, email, attributes);
				}

				if(personUuid == null) {
					badUser(c, email, ip);
					log(c, "FINE", User.userWithIp(ip, site), "Invalid username or password. Username: " + email);
					c.commit();
					c.close();
					c = null;
					results.add(new KeyValue("error", "Invalid username or password."));
					return results;
				}
			}

			if(password.length() == 0) {
				log(c, "SEVERE", User.userWithUuidAndIp(personUuid, ip, site), "Blocked authentication for account with no password. Email: " + email);
				c.commit();
				c.close();
				c = null;
				results.add(new KeyValue("error", "This account has no password. Please contact support."));
				return results;
			}

			s = c.prepareStatement("update person set last_auth=?,last_auth_ip=? where uuid=?");
			s.setLong(1, new Date().getTime());
			s.setString(2, ip);
			s.setString(3, personUuid.toString());
			s.executeUpdate();
			s.close();
			s = null;

			int expiry = 60;
			try {
				expiry = Integer.parseInt(api.getSettingsCache().get("session.expiry", "3600"));
			} catch(Exception e) {
			}

			token = createSession(c, personUuid, site, currentToken, ip, expiry);

			Location l = ipLocation(c, ip);
			log(c, "INFO", User.userWithUuidAndIp(personUuid, ip, site), "Authentication success. Location: " + (l == null?"unknown":l.toString()));

			c.commit();
			c.close();
			c = null;
		} catch(SQLException | NoSuchAlgorithmException e) {
			throw new IOException(e);
		} finally {
			if(r != null) { try { r.close(); } catch(Exception e) {} }
			if(s != null) { try { s.close(); } catch(Exception e) {} }
			if(c != null) {
				try { c.rollback(); } catch (SQLException e) { }
				try { c.close(); } catch (SQLException e) { }
			}
		}
		results.add(new KeyValue("token", token));
		return results;
	}

	private UUID createOrUpdatePersonUsingLdapAttributes(Connection c, String username, Map attributes) throws IOException {
		UUID personUuid = null;
		PreparedStatement s = null;
		ResultSet r = null;

		String firstName = attributes.get("givenName");
		String lastName = attributes.get("sn");
		String email = attributes.get("mail");

		try {
			s = c.prepareStatement("select uuid, first_name, last_name, email from person where username=?");
			s.setString(1, username);
			r = s.executeQuery();
			if(r.next()) {
				personUuid = UUID.fromString(r.getString(1));
				if((email != null && !email.equals(r.getString(4)))
					|| (firstName != null && !firstName.equals(r.getString(2)))
					|| (lastName != null && !lastName.equals(r.getString(3)))
					) {
					if(email.equals(r.getString(4))) {
						email = null;
					}
					if(firstName.equals(r.getString(2))) {
						firstName = null;
					}
					if(lastName.equals(r.getString(3))) {
						lastName = null;
					}
					updatePersonFromLdap(c, User.userWithUuidAndIp(personUuid, ip, site), firstName, lastName, email);
				}
				return personUuid;
			}
			personUuid = addPerson(c, site, firstName, lastName, email, username, null, null);
			log(c, "INFO", User.userWithUuidAndIp(personUuid, ip, site), "Auto created user account using LDAP date for username=" + username);
		} catch(SQLException | NoSuchAlgorithmException e) {
			throw new IOException(e);
		} finally {
			if(r != null) { try { r.close(); } catch(Exception e) {} }
			if(s != null) { try { s.close(); } catch(Exception e) {} }
		}
		return personUuid;
	}

	@Override
	public String getJsonParameters() {
		return "{" +
				"\"current_token\":\"" + Json.escape(currentToken) + "\"," +
				(ip == null?"":("\"ip\":\"" + Json.escape(ip) + "\",")) +
				"\"email\":\"" + Json.escape(email) + "\"" +
				"}";
	}

	public boolean isThrottled(Connection c, String key, String type) throws SQLException {
		PreparedStatement q = null;
		PreparedStatement q2 = null;
		ResultSet r = null;

		try {
			int lockout = 60;
			try {
				lockout = Integer.parseInt(api.getSettingsCache().get("throttle." + type + ".lockout", "60"));
			} catch(Exception e) {
			}

			int attempts = 10;
			try {
				attempts = Integer.parseInt(api.getSettingsCache().get("throttle." + type + ".attempts", "10"));
			} catch(Exception e) {
			}

			q = c.prepareStatement(
					"select updated + " + lockout + " " +
					"from throttle " +
					"where key_value=? and attempts>=" + attempts);
			q.setString(1, key);
			r = q.executeQuery();
			if(r.next()) {
				if((new Date().getTime()/1000) < r.getLong(1)) {
					return true;
				} else {
					q2 = c.prepareStatement("delete from throttle where key_value=?");
					q2.setString(1, key);
					q2.execute();
					return false;
				}
			} else {
				return false;
			}
		} finally {
			try { if(r != null) { r.close(); } } catch(Exception e) {}
			try { if(q != null) { q.close(); } } catch(Exception e) {}
			try { if(q2 != null) { q2.close(); } } catch(Exception e) {}
		}

	}

	public void markForThrottling(Connection c, String key, String type) throws SQLException {
		PreparedStatement q = null;
		PreparedStatement q2 = null;
		PreparedStatement q3 = null;
		ResultSet r = null;

		try {
			q = c.prepareStatement("select attempts,updated from throttle where key_value=?");
			q.setString(1, key);
			r = q.executeQuery();
			if(!r.next()) {
				// Insert new throttle
				q3 = c.prepareStatement("insert into throttle (key_value,attempts,updated) values(?,1,?)");
				q3.setString(1, key);
				q3.setLong(2, new Date().getTime()/1000);
				q3.executeUpdate();
				return;
			} else {
				long updated = r.getLong(2);
				r.close();
				r = null;
				q2 = c.prepareStatement("select value from setting where name = 'throttle." + type + ".window'");
				r = q2.executeQuery();
				if(!r.next()) {
					throw new IllegalStateException("System configuration setting 'throttle." + type + ".window' is missing.");
				}
				if(updated < (new Date().getTime()/1000)-Integer.parseInt(r.getString(1))) {
					// Marking outside the throttle window, reset the attempt counter
					q3 = c.prepareStatement("update throttle set attempts=1,updated=? where key_value=?");
					q3.setLong(1, new Date().getTime()/1000);
					q3.setString(2, key);
					q3.executeUpdate();
				} else {
					// Marking within the throttle window, just increment the attempts counter
					q3 = c.prepareStatement("update throttle set attempts=attempts+1 where key_value=?");
					q3.setString(1, key);
					q3.executeUpdate();
					return;
				}

			}
		} finally {
			try { if(r != null) { r.close(); } } catch(Exception e) {}
			try { if(q != null) { q.close(); } } catch(Exception e) {}
			try { if(q2 != null) { q2.close(); } } catch(Exception e) {}
			try { if(q3 != null) { q3.close(); } } catch(Exception e) {}
		}
	}

	private void badUser(Connection c, String username, String ip) throws SQLException {
		if(username.contains("=") || username.contains("&")
			|| username.contains("%") || username.contains("..")
			|| username.contains("/") || username.contains("\\")
			|| username.contains("(") || username.contains(")")
			|| username.contains("!") || username.contains("--")
			|| username.contains(";") || username.contains("$")) {
			markForThrottling(c, ip, "ip");
			markForThrottling(c, ip, "ip");
			markForThrottling(c, ip, "ip");
		}
		if(username.contains("cn=") || username.contains("file://")
			|| username.contains("http://") || username.contains("sleep(")
			|| username.contains("




© 2015 - 2025 Weber Informatics LLC | Privacy Policy