Skip to content

Instantly share code, notes, and snippets.

@zxlooong
Created November 7, 2014 17:16
Show Gist options
  • Save zxlooong/ad5829b5829c8ffbbd14 to your computer and use it in GitHub Desktop.
Save zxlooong/ad5829b5829c8ffbbd14 to your computer and use it in GitHub Desktop.
/*************************************************************************
* *
* EJBCA: The OpenSource Certificate Authority *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.ejbca.core.ejb.ca.auth;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
import org.cesecore.core.ejb.log.LogSessionLocal;
import org.ejbca.core.ejb.JndiHelper;
import org.ejbca.core.ejb.ra.UserAdminSessionLocal;
import org.ejbca.core.ejb.ra.UserData;
import org.ejbca.core.model.InternalResources;
import org.ejbca.core.model.approval.ApprovalException;
import org.ejbca.core.model.approval.WaitingForApprovalException;
import org.ejbca.core.model.authorization.AuthorizationDeniedException;
import org.ejbca.core.model.ca.AuthLoginException;
import org.ejbca.core.model.ca.AuthStatusException;
import org.ejbca.core.model.log.Admin;
import org.ejbca.core.model.log.LogConstants;
import org.ejbca.core.model.ra.ExtendedInformation;
import org.ejbca.core.model.ra.UserDataConstants;
import org.ejbca.core.model.ra.UserDataVO;
/**
* Authenticates users towards a user database.
* @see AuthenticationSession
*
* @version $Id: AuthenticationSessionBean.java 11635 2011-03-30 11:53:08Z jeklund $
*/
@Stateless(mappedName = JndiHelper.APP_JNDI_PREFIX + "AuthenticationSessionRemote")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class AuthenticationSessionBean implements AuthenticationSessionLocal, AuthenticationSessionRemote {
private static final Logger log = Logger.getLogger(AuthenticationSessionBean.class);
@PersistenceContext(unitName="ejbca")
private EntityManager entityManager;
@EJB
private UserAdminSessionLocal userAdminSession;
@EJB
private LogSessionLocal logSession;
/** Internal localization of logs and errors */
private static final InternalResources intres = InternalResources.getInstance();
@Override
public UserDataVO authenticateUser(final Admin admin, final String username, final String password) throws ObjectNotFoundException, AuthStatusException, AuthLoginException {
log.info(">authenticateUser(" + username + ", hiddenpwd)");
try {
log.info("UserData.findByUsername in");
// Find the user with username username, or throw FinderException
final UserData data1 = UserData.findByUsername(entityManager, username);
if (data1 == null) {
//log.info("UserData.findByUsername in A");
String dn_fix = "";
String username_fix = "";
String organization = "";
String username_uid = "";
if(username.contains(",")){
String[] strs = username.split(",");
for(int i=0; i<strs.length; i++) {
if(strs[i].contains("cn=")||strs[i].contains("CN=")){
username_fix = strs[i].substring(strs[i].indexOf("cn=")+3);
}
if(strs[i].contains("ou=")||strs[i].contains("OU=")){
organization = strs[i].substring(strs[i].indexOf("ou=")+3);
}
if (strs[i].contains("uid=")||strs[i].contains("uid=")){
username_uid = strs[i].substring(strs[i].indexOf("uid=")+4);
}
}
}else{
username_fix = username;
}
log.error("fix: "+ username_fix +" "+ organization +" "+ username_uid );
if (0 == username.compareTo(username_fix)) {
dn_fix = "CN=" + username;
}else{
dn_fix = "CN=" + username_fix;
if(organization.length()>0){
dn_fix += ",";
dn_fix += "OU=" + organization;
}
if(username_uid.length()>0){
dn_fix += ",";
dn_fix += "UID=" + username_uid;
}
}
log.error("dnfix: "+dn_fix);
String pssword = "12345678"; // "$2a$01$N7QJHUN.OGFL59B9.y7rEu2/gbeORG0vptaFzQkNk2AxyOp./BHkO" test
boolean clearpwd = true;
//String dn = "CN=" + username;
String dn = dn_fix;
int caid = 1725190127; // pp user center
//int caid = -1965483724; // pp root ca
String cardnumber = null;
String altname = "";
String email = null;
int type = 1;
int eeprofileid = 1771651268;
//int eeprofileid = 253675057;
int certprofileid = 1962332722;
//int certprofileid = 1485179037;
int tokentype = 2;
int hardtokenissuerid = 0;
ExtendedInformation extendedInformation = null;
UserData dataTmp = new UserData(username, password, clearpwd, dn, caid, cardnumber, altname, email, type, eeprofileid, certprofileid, tokentype, hardtokenissuerid, extendedInformation);
//EntityManager sourceEntityManager = Persistence.createEntityManagerFactory("User").createEntityManager();
entityManager.persist(dataTmp);
entityManager.flush();
//log.info("UserData.findByUsername a");
}else{
//log.info("UserData.findByUsername in B");
// String pssword = "12345678"; // "$2a$01$N7QJHUN.OGFL59B9.y7rEu2/gbeORG0vptaFzQkNk2AxyOp./BHkO" test
// boolean clearpwd = true;
// String dn = "CN=" + username;
// int caid = -1965483724;
// String cardnumber = null;
// String altname = "";
// String email = null;
// int type = 1;
// int eeprofileid = 1771651268;
// int certprofileid = 1962332722;
// int tokentype = 2;
// int hardtokenissuerid = 0;
// ExtendedInformation extendedInformation = null;
//
// UserData dataTmp = new UserData(username, password, clearpwd, dn, caid, cardnumber, altname, email, type, eeprofileid, certprofileid, tokentype, hardtokenissuerid, extendedInformation);
//EntityManager sourceEntityManager = Persistence.createEntityManagerFactory("User").createEntityManager();
data1.setStatus(10);
entityManager.merge(data1);
//entityManager.refresh(data1);
entityManager.flush();
//log.info("UserData.findByUsername b");
}
final UserData data = UserData.findByUsername(entityManager, username);
if (data == null) {
log.info("UserData.findByUsername null");
throw new ObjectNotFoundException("Could not find username " + username);
}
log.info("UserData.findByUsername ok");
// Decrease the remaining login attempts. When zero, the status is set to STATUS_GENERATED
userAdminSession.decRemainingLoginAttempts(admin, username);
final int status = data.getStatus();
if ( (status == UserDataConstants.STATUS_NEW) || (status == UserDataConstants.STATUS_FAILED) || (status == UserDataConstants.STATUS_INPROCESS) || (status == UserDataConstants.STATUS_KEYRECOVERY)) {
if (log.isDebugEnabled()) {
log.debug("Trying to authenticate user: username="+username+", dn="+data.getSubjectDN()+", email="+data.getSubjectEmail()+", status="+status+", type="+data.getType());
}
if (!data.comparePassword(password)) {
final String msg = intres.getLocalizedMessage("authentication.invalidpwd", username);
logSession.log(admin, data.getCaId(), LogConstants.MODULE_CA, new Date(),username, null, LogConstants.EVENT_ERROR_USERAUTHENTICATION,msg);
throw new AuthLoginException(msg);
}
// Resets the remaining login attempts as this was a successful login
userAdminSession.resetRemainingLoginAttempts(admin, username);
// Log formal message that authentication was successful
final String msg = intres.getLocalizedMessage("authentication.authok", username);
logSession.log(admin, data.getCaId(), LogConstants.MODULE_CA, new Date(),username, null, LogConstants.EVENT_INFO_USERAUTHENTICATION, msg);
if (log.isTraceEnabled()) {
log.trace("<authenticateUser("+username+", hiddenpwd)");
}
return data.toUserDataVO();
}
final String msg = intres.getLocalizedMessage("authentication.wrongstatus", UserDataConstants.getStatusText(status), Integer.valueOf(status), username);
logSession.log(admin, data.getCaId(), LogConstants.MODULE_CA, new Date(),username, null, LogConstants.EVENT_INFO_USERAUTHENTICATION, msg);
throw new AuthStatusException(msg);
} catch (ObjectNotFoundException oe) {
final String msg = intres.getLocalizedMessage("authentication.usernotfound", username);
logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new Date(),username, null, LogConstants.EVENT_INFO_USERAUTHENTICATION, msg);
throw oe;
} catch (AuthStatusException se) {
throw se;
} catch (AuthLoginException le) {
throw le;
} catch (Exception e) {
log.error(intres.getLocalizedMessage("error.unknown"), e);
throw new EJBException(e);
}
}
@Override
public void finishUser(UserDataVO data) throws ObjectNotFoundException {
if (log.isTraceEnabled()) {
log.trace(">finishUser(" + data.getUsername() + ", hiddenpwd)");
}
// This admin can be the public web user, which may not be allowed to change status,
// this is a bit ugly, but what can a man do...
Admin statusadmin = Admin.getInternalAdmin();
try {
// See if we are allowed for make more requests than this one. If not user status changed by decRequestCounter
int counter = userAdminSession.decRequestCounter(statusadmin, data.getUsername());
if (counter <= 0) {
String msg = intres.getLocalizedMessage("authentication.statuschanged", data.getUsername());
logSession.log(statusadmin, data.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), data.getUsername(), null, LogConstants.EVENT_INFO_CHANGEDENDENTITY,msg);
}
if (log.isTraceEnabled()) {
log.trace("<finishUser("+data.getUsername()+", hiddenpwd)");
}
} catch (FinderException e) {
String msg = intres.getLocalizedMessage("authentication.usernotfound", data.getUsername());
logSession.log(statusadmin, statusadmin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), data.getUsername(), null, LogConstants.EVENT_ERROR_USERAUTHENTICATION,msg);
throw new ObjectNotFoundException(e.getMessage());
} catch (AuthorizationDeniedException e) {
// Should never happen
log.error("AuthorizationDeniedException: ", e);
throw new EJBException(e);
} catch (ApprovalException e) {
// Should never happen
log.error("ApprovalException: ", e);
throw new EJBException(e);
} catch (WaitingForApprovalException e) {
// Should never happen
log.error("ApprovalException: ", e);
throw new EJBException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment