@Override public void engineSetKeyEntry(String alias, byte[] keystoreBytes, Certificate[] chain) throws KeyStoreException { try { List<ModificationItem> items = new LinkedList<>(); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(keyAttribute, keystoreBytes))); CertificateFactory certFactory = CertificateFactory.getInstance(certificateType); CertPath certPath = certFactory.generateCertPath(Arrays.asList(chain)); BasicAttribute chainAttr = new BasicAttribute(certificateChainAttribute, certPath.getEncoded(certificateChainEncoding)); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, chainAttr)); BasicAttribute certificateAttr = new BasicAttribute(certificateAttribute, chain[0].getEncoded()); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, certificateAttr)); storeAttributes(alias, items); } catch (CertificateException e) { throw log.ldapKeyStoreFailedToSerializeCertificate(alias, e); } }
@Override public void clearCredentials() throws RealmUnavailableException { try { Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(algorithmAttributeName)); attributes.put(new BasicAttribute(hashAttributeName)); attributes.put(new BasicAttribute(seedAttributeName)); attributes.put(new BasicAttribute(sequenceAttributeName)); context.modifyAttributes(distinguishedName, DirContext.REMOVE_ATTRIBUTE, attributes); } catch (NoSuchAttributeException e) { // ignore if already clear } catch (NamingException e) { throw log.ldapRealmCredentialClearingFailed(distinguishedName, e); } } }
@Override public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { List<ModificationItem> items = new LinkedList<>(); try { BasicAttribute attribute = new BasicAttribute(certificateAttribute); attribute.add(cert.getEncoded()); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute)); } catch (CertificateEncodingException e) { throw log.ldapKeyStoreFailedToSerializeCertificate(alias, e); } storeAttributes(alias, items); }
private void modifyAuthorities(final DistinguishedName userDn, final Collection<? extends GrantedAuthority> authorities, final int modType) { template.executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext ctx) throws NamingException { for (GrantedAuthority authority : authorities) { String group = convertAuthorityToGroup(authority); DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); ModificationItem addGroup = new ModificationItem(modType, new BasicAttribute(groupMemberAttributeName, fullDn.toUrl())); ctx.modifyAttributes(buildGroupDn(group), new ModificationItem[] { addGroup }); } return null; } }); }
public Object executeWithContext(DirContext ctx) throws NamingException { for (GrantedAuthority authority : authorities) { String group = convertAuthorityToGroup(authority); DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); ModificationItem addGroup = new ModificationItem(modType, new BasicAttribute(groupMemberAttributeName, fullDn.toUrl())); ctx.modifyAttributes(buildGroupDn(group), new ModificationItem[] { addGroup }); } return null; } });
private Attributes buildAttributes( String dn, String[] attributes, String[] values, String multValuedSeparator ) { Attributes attrs = new javax.naming.directory.BasicAttributes( true ); int nrAttributes = attributes.length; for ( int i = 0; i < nrAttributes; i++ ) { if ( !Utils.isEmpty( values[i] ) ) { // We have a value String value = values[i].trim(); if ( multValuedSeparator != null && value.indexOf( multValuedSeparator ) > 0 ) { Attribute attr = new javax.naming.directory.BasicAttribute( attributes[i] ); for ( String attribute : value.split( multValuedSeparator ) ) { attr.add( attribute ); } attrs.put( attr ); } else { attrs.put( attributes[i], value ); } } } return attrs; }
@Override public void clearCredentials() throws RealmUnavailableException { try { Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(userPasswordAttributeName)); context.modifyAttributes(distinguishedName, DirContext.REMOVE_ATTRIBUTE, attributes); } catch (NoSuchAttributeException e) { // ignore if already clear } catch (NamingException e) { throw log.ldapRealmCredentialClearingFailed(distinguishedName, e); } } }
private void changePasswordUsingAttributeModification (DistinguishedName userDn, String oldPassword, String newPassword) { final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(userDn, passwordChange); return; } template.executeReadWrite(dirCtx -> { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException( "Authentication for password change failed."); } ctx.modifyAttributes(userDn, passwordChange); return null; }); }
@Test public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception { final DirContext dirCtx = mock(DirContext.class); final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class); final BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("uid", "bob")); PasswordComparisonAuthenticator authenticator = new PasswordComparisonAuthenticator( source); authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" }); // Get the mock to return an empty attribute set when(source.getReadOnlyContext()).thenReturn(dirCtx); when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))) .thenReturn(attrs); when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org"); // Setup a single return value (i.e. success) final NamingEnumeration searchResults = new BasicAttributes("", null).getAll(); when( dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class), any(SearchControls.class))).thenReturn( searchResults); authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword")); } }
private void storeAttributes(String alias, List<ModificationItem> items) throws KeyStoreException { DirContext context = obtainDirContext(); try { SearchResult result = searchAlias(context, alias, null, new String[]{}); LdapName distinguishName; if (result == null) { // alias not exists yet - create if (createPath == null || createAttributes == null || createRdn == null) throw log.creationNotConfigured(alias); distinguishName = (LdapName) createPath.clone(); distinguishName.add(new Rdn(createRdn, alias)); log.debugf("Creating keystore alias [%s] with DN [%s] in LDAP", alias, distinguishName.toString()); context.createSubcontext(distinguishName, createAttributes); items.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(aliasAttribute, alias))); } else { distinguishName = new LdapName(result.getNameInNamespace()); } context.modifyAttributes(distinguishName, items.toArray(new ModificationItem[items.size()])); } catch (NamingException e) { throw log.ldapKeyStoreFailedToStore(alias, e); } finally { returnDirContext(context); } }
private static Attributes mockAttributes(NameValues... namedValues) throws NamingException { Attributes attributes = new BasicAttributes(); for (NameValues namedValue : namedValues) { Attribute attr = new BasicAttribute(namedValue.name); for (String value : namedValue.values) { attr.add(value); } attributes.put(attr); } return attributes; }
@Test public void testPasswordAttributeIsMappedCorrectly() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setPasswordAttributeName("myappsPassword"); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("myappsPassword", "mypassword".getBytes())); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getPassword()).isEqualTo("mypassword"); }
BasicAttribute attribute = new BasicAttribute(mapping.getLdapName()); modItems.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute)); } else { BasicAttribute attribute = new BasicAttribute(mapping.getLdapName()); attributes.get(mapping.getName()).forEach(attribute::add); modItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute));
private BasicAttributes createSrvRecords() { BasicAttributes records = new BasicAttributes(); BasicAttribute record = new BasicAttribute("SRV"); // the structure of the service records is: // priority weight port hostname // for more information: http://en.wikipedia.org/wiki/SRV_record record.add("20 80 389 kdc3.springsource.com."); record.add("10 70 389 kdc.springsource.com."); record.add("20 20 389 kdc4.springsource.com."); record.add("10 30 389 kdc2.springsource.com"); records.put(record); return records; } }
public int update( String dn, String[] attributes, String[] values, boolean checkEntry ) throws KettleException { try { int nrAttributes = attributes.length; ModificationItem[] mods = new ModificationItem[nrAttributes]; for ( int i = 0; i < nrAttributes; i++ ) { // Define attribute Attribute mod = new BasicAttribute( attributes[i], values[i] ); if ( log.isDebug() ) { log .logDebug( BaseMessages.getString( PKG, "LDAPConnection.Update.Attribute", attributes[i], values[i] ) ); } // Save update action on attribute mods[i] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, mod ); } // We have all requested attribute // let's update now getInitialContext().modifyAttributes( dn, mods ); return STATUS_UPDATED; } catch ( NameNotFoundException n ) { // The entry is not found if ( checkEntry ) { throw new KettleException( BaseMessages.getString( PKG, "LDAPConnection.Error.Deleting.NameNotFound", dn ), n ); } return STATUS_SKIPPED; } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "LDAPConnection.Error.Update", dn ), e ); } }
/** * SEC-303. Non-retrieved role attribute causes NullPointerException */ @Test public void testNonRetrievedRoleAttributeIsIgnored() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setRoleAttributes(new String[] { "userRole", "nonRetrievedAttribute" }); BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userRole", "x")); DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(1); assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains("ROLE_X"); }
public static void storeDiff(ConfigurationChanges.ModifiedObject ldapObj, List<ModificationItem> mods, String attrId, int prev, int val, int defVal) { if (val != prev) { mods.add((val == defVal) ? new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(attrId)) : new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(attrId, Integer.toString(val)))); if (ldapObj != null) ldapObj.add(new ConfigurationChanges.ModifiedAttribute(attrId, prev, val)); } }
private void addConstantAttributes(String names, String values, Attributes attribs) { String[] arrNames = names.split(","); String[] arrValues = values.split(","); if (arrNames.length != arrValues.length) { throw new IllegalArgumentException( String.format("Inconsintent constant attributes: %s; %s", names, values)); } for (int i = 0; i < arrNames.length; i++) { attribs.put(new BasicAttribute(arrNames[i], arrValues[i])); } }
@Override public synchronized void removeCertificates(String dn) throws ConfigurationException { try { ModificationItem removeCert = new ModificationItem( DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(userCertificate)); ctx.modifyAttributes(dn, new ModificationItem[] { removeCert }); } catch (NameNotFoundException e) { throw new ConfigurationNotFoundException(e); } catch (NamingException e) { throw new ConfigurationException(e); } }
private static Attribute connRefs(Collection<Connection> conns, String deviceDN) { Attribute attr = new BasicAttribute("dicomNetworkConnectionReference"); for (Connection conn : conns) attr.add(LdapUtils.dnOf(conn, deviceDN)); return attr; }