use of com.gitblit.ldap.LdapConnection in project gitblit by gitblit.
the class LdapConnectionTest method testRebindAsUser.
@Test
public void testRebindAsUser() {
LdapConnection conn = new LdapConnection(settings);
try {
assertTrue(conn.connect());
assertFalse(conn.rebindAsUser());
BindResult br = conn.bind();
assertNotNull(br);
assertFalse(conn.rebindAsUser());
String bindPattern = "CN=${username},OU=Canada," + ACCOUNT_BASE;
br = conn.bind(bindPattern, "UserThree", "userThreePassword");
assertNotNull(br);
assertFalse(conn.rebindAsUser());
br = conn.bind();
assertNotNull(br);
assertTrue(conn.rebindAsUser());
assertEquals(ResultCode.SUCCESS, br.getResultCode());
assertEquals("CN=UserThree,OU=Canada," + ACCOUNT_BASE, authMode.getBindTracker().getLastSuccessfulBindDN());
} finally {
conn.close();
}
}
use of com.gitblit.ldap.LdapConnection in project gitblit by gitblit.
the class LdapConnectionTest method testBindToBindpattern.
@Test
public void testBindToBindpattern() {
LdapConnection conn = new LdapConnection(settings);
try {
assertTrue(conn.connect());
String bindPattern = "CN=${username},OU=Canada," + ACCOUNT_BASE;
BindResult br = conn.bind(bindPattern, "UserThree", "userThreePassword");
assertNotNull(br);
assertEquals(ResultCode.SUCCESS, br.getResultCode());
assertEquals("CN=UserThree,OU=Canada," + ACCOUNT_BASE, authMode.getBindTracker().getLastSuccessfulBindDN(br.getMessageID()));
br = conn.bind(bindPattern, "UserFour", "userThreePassword");
assertNull(br);
br = conn.bind(bindPattern, "UserTwo", "userTwoPassword");
assertNull(br);
} finally {
conn.close();
}
}
use of com.gitblit.ldap.LdapConnection in project gitblit by gitblit.
the class LdapAuthProvider method sync.
public synchronized void sync() {
final boolean enabled = settings.getBoolean(Keys.realm.ldap.synchronize, false);
if (enabled) {
logger.info("Synchronizing with LDAP @ " + settings.getRequiredString(Keys.realm.ldap.server));
final boolean deleteRemovedLdapUsers = settings.getBoolean(Keys.realm.ldap.removeDeletedUsers, true);
LdapConnection ldapConnection = new LdapConnection(settings);
if (ldapConnection.connect()) {
if (ldapConnection.bind() == null) {
ldapConnection.close();
logger.error("Cannot synchronize with LDAP.");
return;
}
try {
String uidAttribute = settings.getString(Keys.realm.ldap.uid, "uid");
String accountBase = ldapConnection.getAccountBase();
String accountPattern = ldapConnection.getAccountPattern();
accountPattern = StringUtils.replace(accountPattern, "${username}", "*");
SearchResult result = doSearch(ldapConnection, accountBase, accountPattern);
if (result != null && result.getEntryCount() > 0) {
final Map<String, UserModel> ldapUsers = new HashMap<String, UserModel>();
for (SearchResultEntry loggingInUser : result.getSearchEntries()) {
Attribute uid = loggingInUser.getAttribute(uidAttribute);
if (uid == null) {
logger.error("Can not synchronize with LDAP, missing \"{}\" attribute", uidAttribute);
continue;
}
final String username = uid.getValue();
logger.debug("LDAP synchronizing: " + username);
UserModel user = userManager.getUserModel(username);
if (user == null) {
user = new UserModel(username);
}
if (!supportsTeamMembershipChanges()) {
getTeamsFromLdap(ldapConnection, username, loggingInUser, user);
}
// Get User Attributes
setUserAttributes(user, loggingInUser);
// store in map
ldapUsers.put(username.toLowerCase(), user);
}
if (deleteRemovedLdapUsers) {
logger.debug("detecting removed LDAP users...");
for (UserModel userModel : userManager.getAllUsers()) {
if (AccountType.LDAP == userModel.accountType) {
if (!ldapUsers.containsKey(userModel.username)) {
logger.info("deleting removed LDAP user " + userModel.username + " from user service");
userManager.deleteUser(userModel.username);
}
}
}
}
userManager.updateUserModels(ldapUsers.values());
if (!supportsTeamMembershipChanges()) {
final Map<String, TeamModel> userTeams = new HashMap<String, TeamModel>();
for (UserModel user : ldapUsers.values()) {
for (TeamModel userTeam : user.teams) {
// Is this an administrative team?
setAdminAttribute(userTeam);
userTeams.put(userTeam.name, userTeam);
}
}
userManager.updateTeamModels(userTeams.values());
}
}
if (!supportsTeamMembershipChanges()) {
getEmptyTeamsFromLdap(ldapConnection);
}
} finally {
ldapConnection.close();
}
}
}
}
use of com.gitblit.ldap.LdapConnection in project gitblit by gitblit.
the class LdapKeyManager method getKeysImpl.
@Override
protected List<SshKey> getKeysImpl(String username) {
try (LdapConnection conn = new LdapConnection(settings)) {
if (conn.connect()) {
log.info("loading ssh key for {} from LDAP directory", username);
BindResult bindResult = conn.bind();
if (bindResult == null) {
conn.close();
return null;
}
// Search the user entity
// Support prefixing the key data, e.g. when using altSecurityIdentities in AD.
String pubKeyAttribute = settings.getString(Keys.realm.ldap.sshPublicKey, "sshPublicKey");
String pkaPrefix = null;
int idx = pubKeyAttribute.indexOf(':');
if (idx > 0) {
pkaPrefix = pubKeyAttribute.substring(idx + 1);
pubKeyAttribute = pubKeyAttribute.substring(0, idx);
}
SearchResult result = conn.searchUser(getSimpleUsername(username), Arrays.asList(pubKeyAttribute));
conn.close();
if (result != null && result.getResultCode() == ResultCode.SUCCESS) {
if (result.getEntryCount() > 1) {
log.info("Found more than one entry for user {} in LDAP. Cannot retrieve SSH key.", username);
return null;
} else if (result.getEntryCount() < 1) {
log.info("Found no entry for user {} in LDAP. Cannot retrieve SSH key.", username);
return null;
}
// Retrieve the SSH key attributes
SearchResultEntry foundUser = result.getSearchEntries().get(0);
String[] attrs = foundUser.getAttributeValues(pubKeyAttribute);
if (attrs == null || attrs.length == 0) {
log.info("found no keys for user {} under attribute {} in directory", username, pubKeyAttribute);
return null;
}
// Filter resulting list to match with required special prefix in entry
List<GbAuthorizedKeyEntry> authorizedKeys = new ArrayList<>(attrs.length);
Matcher m = PREFIX_PATTERN.matcher("");
for (int i = 0; i < attrs.length; ++i) {
// strip out line breaks
String keyEntry = Joiner.on("").join(attrs[i].replace("\r\n", "\n").split("\n"));
m.reset(keyEntry);
try {
if (m.lookingAt()) {
// Key is prefixed in LDAP
if (pkaPrefix == null) {
continue;
}
String prefix = m.group(1).trim();
if (!pkaPrefix.equalsIgnoreCase(prefix)) {
continue;
}
// Strip prefix off
String s = keyEntry.substring(m.end());
authorizedKeys.add(GbAuthorizedKeyEntry.parseAuthorizedKeyEntry(s));
} else {
// Key is not prefixed in LDAP
if (pkaPrefix != null) {
continue;
}
// Strip prefix off
String s = keyEntry;
authorizedKeys.add(GbAuthorizedKeyEntry.parseAuthorizedKeyEntry(s));
}
} catch (IllegalArgumentException e) {
log.info("Failed to parse key entry={}:", keyEntry, e.getMessage());
}
}
List<SshKey> keyList = new ArrayList<>(authorizedKeys.size());
for (GbAuthorizedKeyEntry keyEntry : authorizedKeys) {
try {
SshKey key = new SshKey(keyEntry.resolvePublicKey(null));
key.setComment(keyEntry.getComment());
setKeyPermissions(key, keyEntry);
keyList.add(key);
} catch (GeneralSecurityException | IOException e) {
log.warn("Error resolving key entry for user {}. Entry={}", username, keyEntry, e);
}
}
return keyList;
}
}
}
return null;
}
use of com.gitblit.ldap.LdapConnection in project gitblit by gitblit.
the class LdapAuthProvider method authenticate.
@Override
public UserModel authenticate(String username, char[] password) {
String simpleUsername = getSimpleUsername(username);
LdapConnection ldapConnection = new LdapConnection(settings);
if (ldapConnection.connect()) {
// Try to bind either to the "manager" account,
// or directly to the DN of the user logging in, if realm.ldap.bindpattern is configured.
String passwd = new String(password);
BindResult bindResult = null;
String bindPattern = settings.getString(Keys.realm.ldap.bindpattern, "");
if (!StringUtils.isEmpty(bindPattern)) {
bindResult = ldapConnection.bind(bindPattern, simpleUsername, passwd);
} else {
bindResult = ldapConnection.bind();
}
if (bindResult == null) {
ldapConnection.close();
return null;
}
try {
// Find the logging in user's DN
SearchResult result = ldapConnection.searchUser(simpleUsername);
if (result != null && result.getEntryCount() == 1) {
SearchResultEntry loggingInUser = result.getSearchEntries().get(0);
String loggingInUserDN = loggingInUser.getDN();
if (ldapConnection.isAuthenticated(loggingInUserDN, passwd)) {
logger.debug("LDAP authenticated: " + username);
UserModel user = null;
synchronized (this) {
user = userManager.getUserModel(simpleUsername);
if (user == null) {
// create user object for new authenticated user
user = new UserModel(simpleUsername);
}
// create a user cookie
setCookie(user);
if (!supportsTeamMembershipChanges()) {
getTeamsFromLdap(ldapConnection, simpleUsername, loggingInUser, user);
}
// Get User Attributes
setUserAttributes(user, loggingInUser);
// Push the ldap looked up values to backing file
updateUser(user);
if (!supportsTeamMembershipChanges()) {
for (TeamModel userTeam : user.teams) {
// Is this an administrative team?
setAdminAttribute(userTeam);
updateTeam(userTeam);
}
}
}
return user;
}
}
} finally {
ldapConnection.close();
}
}
return null;
}
Aggregations