use of com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl in project ldapsdk by pingidentity.
the class LDAPModify method getBindControls.
/**
* {@inheritDoc}
*/
@Override()
@NotNull()
protected List<Control> getBindControls() {
final ArrayList<Control> bindControls = new ArrayList<>(10);
if (bindControl.isPresent()) {
bindControls.addAll(bindControl.getValues());
}
if (authorizationIdentity.isPresent()) {
bindControls.add(new AuthorizationIdentityRequestControl(false));
}
if (getAuthorizationEntryAttribute.isPresent()) {
bindControls.add(new GetAuthorizationEntryRequestControl(true, true, getAuthorizationEntryAttribute.getValues()));
}
if (getRecentLoginHistory.isPresent()) {
bindControls.add(new GetRecentLoginHistoryRequestControl());
}
if (getUserResourceLimits.isPresent()) {
bindControls.add(new GetUserResourceLimitsRequestControl());
}
if (usePasswordPolicyControl.isPresent()) {
bindControls.add(new PasswordPolicyRequestControl());
}
if (suppressOperationalAttributeUpdates.isPresent()) {
final EnumSet<SuppressType> suppressTypes = EnumSet.noneOf(SuppressType.class);
for (final String s : suppressOperationalAttributeUpdates.getValues()) {
if (s.equalsIgnoreCase("last-access-time")) {
suppressTypes.add(SuppressType.LAST_ACCESS_TIME);
} else if (s.equalsIgnoreCase("last-login-time")) {
suppressTypes.add(SuppressType.LAST_LOGIN_TIME);
} else if (s.equalsIgnoreCase("last-login-ip")) {
suppressTypes.add(SuppressType.LAST_LOGIN_IP);
}
}
bindControls.add(new SuppressOperationalAttributeUpdateRequestControl(suppressTypes));
}
return bindControls;
}
use of com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl in project ldapsdk by pingidentity.
the class AuthRate method doToolProcessing.
/**
* Performs the actual processing for this tool. In this case, it gets a
* connection to the directory server and uses it to perform the requested
* searches.
*
* @return The result code for the processing that was performed.
*/
@Override()
@NotNull()
public ResultCode doToolProcessing() {
// variable rate data file and return.
if (sampleRateFile.isPresent()) {
try {
RateAdjustor.writeSampleVariableRateFile(sampleRateFile.getValue());
return ResultCode.SUCCESS;
} catch (final Exception e) {
Debug.debugException(e);
err("An error occurred while trying to write sample variable data " + "rate file '", sampleRateFile.getValue().getAbsolutePath(), "': ", StaticUtils.getExceptionMessage(e));
return ResultCode.LOCAL_ERROR;
}
}
// Determine the random seed to use.
final Long seed;
if (randomSeed.isPresent()) {
seed = Long.valueOf(randomSeed.getValue());
} else {
seed = null;
}
// Create value patterns for the base DN and filter.
final ValuePattern dnPattern;
try {
dnPattern = new ValuePattern(baseDN.getValue(), seed);
} catch (final ParseException pe) {
Debug.debugException(pe);
err("Unable to parse the base DN value pattern: ", pe.getMessage());
return ResultCode.PARAM_ERROR;
}
final ValuePattern filterPattern;
if (filter.isPresent()) {
try {
filterPattern = new ValuePattern(filter.getValue(), seed);
} catch (final ParseException pe) {
Debug.debugException(pe);
err("Unable to parse the filter pattern: ", pe.getMessage());
return ResultCode.PARAM_ERROR;
}
} else {
filterPattern = null;
}
// Get the attributes to return.
final String[] attrs;
if (attributes.isPresent()) {
final List<String> attrList = attributes.getValues();
attrs = new String[attrList.size()];
attrList.toArray(attrs);
} else {
attrs = StaticUtils.NO_STRINGS;
}
// If the --ratePerSecond option was specified, then limit the rate
// accordingly.
FixedRateBarrier fixedRateBarrier = null;
if (ratePerSecond.isPresent() || variableRateData.isPresent()) {
// We might not have a rate per second if --variableRateData is specified.
// The rate typically doesn't matter except when we have warm-up
// intervals. In this case, we'll run at the max rate.
final int intervalSeconds = collectionInterval.getValue();
final int ratePerInterval = (ratePerSecond.getValue() == null) ? Integer.MAX_VALUE : ratePerSecond.getValue() * intervalSeconds;
fixedRateBarrier = new FixedRateBarrier(1000L * intervalSeconds, ratePerInterval);
}
// If --variableRateData was specified, then initialize a RateAdjustor.
RateAdjustor rateAdjustor = null;
if (variableRateData.isPresent()) {
try {
rateAdjustor = RateAdjustor.newInstance(fixedRateBarrier, ratePerSecond.getValue(), variableRateData.getValue());
} catch (final IOException | IllegalArgumentException e) {
Debug.debugException(e);
err("Initializing the variable rates failed: " + e.getMessage());
return ResultCode.PARAM_ERROR;
}
}
// Determine whether to include timestamps in the output and if so what
// format should be used for them.
final boolean includeTimestamp;
final String timeFormat;
if (timestampFormat.getValue().equalsIgnoreCase("with-date")) {
includeTimestamp = true;
timeFormat = "dd/MM/yyyy HH:mm:ss";
} else if (timestampFormat.getValue().equalsIgnoreCase("without-date")) {
includeTimestamp = true;
timeFormat = "HH:mm:ss";
} else {
includeTimestamp = false;
timeFormat = null;
}
// Get the controls to include in bind requests.
final ArrayList<Control> bindControls = new ArrayList<>(5);
if (authorizationIdentityRequestControl.isPresent()) {
bindControls.add(new AuthorizationIdentityRequestControl());
}
if (passwordPolicyRequestControl.isPresent()) {
bindControls.add(new DraftBeheraLDAPPasswordPolicy10RequestControl());
}
bindControls.addAll(bindControl.getValues());
// Determine whether any warm-up intervals should be run.
final long totalIntervals;
final boolean warmUp;
int remainingWarmUpIntervals = warmUpIntervals.getValue();
if (remainingWarmUpIntervals > 0) {
warmUp = true;
totalIntervals = 0L + numIntervals.getValue() + remainingWarmUpIntervals;
} else {
warmUp = true;
totalIntervals = 0L + numIntervals.getValue();
}
// Create the table that will be used to format the output.
final OutputFormat outputFormat;
if (csvFormat.isPresent()) {
outputFormat = OutputFormat.CSV;
} else {
outputFormat = OutputFormat.COLUMNS;
}
final ColumnFormatter formatter = new ColumnFormatter(includeTimestamp, timeFormat, outputFormat, " ", new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Auths/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Avg Dur ms"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Errors/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall", "Auths/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall", "Avg Dur ms"));
// Create values to use for statistics collection.
final AtomicLong authCounter = new AtomicLong(0L);
final AtomicLong errorCounter = new AtomicLong(0L);
final AtomicLong authDurations = new AtomicLong(0L);
final ResultCodeCounter rcCounter = new ResultCodeCounter();
// Determine the length of each interval in milliseconds.
final long intervalMillis = 1000L * collectionInterval.getValue();
// Create the threads to use for the searches.
final CyclicBarrier barrier = new CyclicBarrier(numThreads.getValue() + 1);
final AuthRateThread[] threads = new AuthRateThread[numThreads.getValue()];
for (int i = 0; i < threads.length; i++) {
final LDAPConnection searchConnection;
final LDAPConnection bindConnection;
try {
searchConnection = getConnection();
bindConnection = getConnection();
} catch (final LDAPException le) {
Debug.debugException(le);
err("Unable to connect to the directory server: ", StaticUtils.getExceptionMessage(le));
return le.getResultCode();
}
threads[i] = new AuthRateThread(this, i, searchConnection, bindConnection, dnPattern, scopeArg.getValue(), filterPattern, attrs, userPassword.getValue(), bindOnly.isPresent(), authType.getValue(), searchControl.getValues(), bindControls, runningThreads, barrier, authCounter, authDurations, errorCounter, rcCounter, fixedRateBarrier);
threads[i].start();
}
// Display the table header.
for (final String headerLine : formatter.getHeaderLines(true)) {
out(headerLine);
}
// which case, we'll start it after the warm-up is complete.
if ((rateAdjustor != null) && (remainingWarmUpIntervals <= 0)) {
rateAdjustor.start();
}
// Indicate that the threads can start running.
try {
barrier.await();
} catch (final Exception e) {
Debug.debugException(e);
}
long overallStartTime = System.nanoTime();
long nextIntervalStartTime = System.currentTimeMillis() + intervalMillis;
boolean setOverallStartTime = false;
long lastDuration = 0L;
long lastNumErrors = 0L;
long lastNumAuths = 0L;
long lastEndTime = System.nanoTime();
for (long i = 0; i < totalIntervals; i++) {
if (rateAdjustor != null) {
if (!rateAdjustor.isAlive()) {
out("All of the rates in " + variableRateData.getValue().getName() + " have been completed.");
break;
}
}
final long startTimeMillis = System.currentTimeMillis();
final long sleepTimeMillis = nextIntervalStartTime - startTimeMillis;
nextIntervalStartTime += intervalMillis;
if (sleepTimeMillis > 0) {
sleeper.sleep(sleepTimeMillis);
}
if (stopRequested.get()) {
break;
}
final long endTime = System.nanoTime();
final long intervalDuration = endTime - lastEndTime;
final long numAuths;
final long numErrors;
final long totalDuration;
if (warmUp && (remainingWarmUpIntervals > 0)) {
numAuths = authCounter.getAndSet(0L);
numErrors = errorCounter.getAndSet(0L);
totalDuration = authDurations.getAndSet(0L);
} else {
numAuths = authCounter.get();
numErrors = errorCounter.get();
totalDuration = authDurations.get();
}
final long recentNumAuths = numAuths - lastNumAuths;
final long recentNumErrors = numErrors - lastNumErrors;
final long recentDuration = totalDuration - lastDuration;
final double numSeconds = intervalDuration / 1_000_000_000.0d;
final double recentAuthRate = recentNumAuths / numSeconds;
final double recentErrorRate = recentNumErrors / numSeconds;
final double recentAvgDuration;
if (recentNumAuths > 0L) {
recentAvgDuration = 1.0d * recentDuration / recentNumAuths / 1_000_000;
} else {
recentAvgDuration = 0.0d;
}
if (warmUp && (remainingWarmUpIntervals > 0)) {
out(formatter.formatRow(recentAuthRate, recentAvgDuration, recentErrorRate, "warming up", "warming up"));
remainingWarmUpIntervals--;
if (remainingWarmUpIntervals == 0) {
out("Warm-up completed. Beginning overall statistics collection.");
setOverallStartTime = true;
if (rateAdjustor != null) {
rateAdjustor.start();
}
}
} else {
if (setOverallStartTime) {
overallStartTime = lastEndTime;
setOverallStartTime = false;
}
final double numOverallSeconds = (endTime - overallStartTime) / 1_000_000_000.0d;
final double overallAuthRate = numAuths / numOverallSeconds;
final double overallAvgDuration;
if (numAuths > 0L) {
overallAvgDuration = 1.0d * totalDuration / numAuths / 1_000_000;
} else {
overallAvgDuration = 0.0d;
}
out(formatter.formatRow(recentAuthRate, recentAvgDuration, recentErrorRate, overallAuthRate, overallAvgDuration));
lastNumAuths = numAuths;
lastNumErrors = numErrors;
lastDuration = totalDuration;
}
final List<ObjectPair<ResultCode, Long>> rcCounts = rcCounter.getCounts(true);
if ((!suppressErrorsArgument.isPresent()) && (!rcCounts.isEmpty())) {
err("\tError Results:");
for (final ObjectPair<ResultCode, Long> p : rcCounts) {
err("\t", p.getFirst().getName(), ": ", p.getSecond());
}
}
lastEndTime = endTime;
}
// Shut down the RateAdjustor if we have one.
if (rateAdjustor != null) {
rateAdjustor.shutDown();
}
// Stop all of the threads.
ResultCode resultCode = ResultCode.SUCCESS;
for (final AuthRateThread t : threads) {
final ResultCode r = t.stopRunning();
if (resultCode == ResultCode.SUCCESS) {
resultCode = r;
}
}
return resultCode;
}
use of com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTestCase method testSASLBindWithAuthorizationIdentity.
/**
* Provides test coverage for the ability to process a SASL bind operation,
* including the authorization identity request control.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSASLBindWithAuthorizationIdentity() throws Exception {
final InMemoryDirectoryServer ds = getTestDS(true, true);
final LDAPConnection conn = ds.getConnection();
final RootDSE rootDSE = conn.getRootDSE();
assertNotNull(rootDSE);
assertTrue(rootDSE.supportsSASLMechanism("PLAIN"));
assertTrue(rootDSE.supportsControl(AuthorizationIdentityRequestControl.AUTHORIZATION_IDENTITY_REQUEST_OID));
// Test a successful anonymous bind.
PLAINBindRequest bindRequest = new PLAINBindRequest("dn:", "", new AuthorizationIdentityRequestControl());
BindResult bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
AuthorizationIdentityResponseControl authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
String authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.equals("dn:"));
// Perform the same test without the authorization identity request control.
bindRequest = new PLAINBindRequest("dn:", "");
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
assertFalse(bindResult.hasResponseControl(AuthorizationIdentityResponseControl.AUTHORIZATION_IDENTITY_RESPONSE_OID));
// Test an anonymous bind with a password.
bindRequest = new PLAINBindRequest("dn:", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with a " + "password");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test an anonymous bind with an authzID.
bindRequest = new PLAINBindRequest("dn:", "dn:cn=Directory Manager", "");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test with a DN-style authID and no authzID.
bindRequest = new PLAINBindRequest("dn:uid=test.user,ou=People,dc=example,dc=com", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("uid=test.user,ou=People,dc=example,dc=com"));
// Test with a DN-style authID that is an additional bind user.
bindRequest = new PLAINBindRequest("dn:cn=Directory Manager", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("cn=Directory Manager"));
// Test with a u-style authID and an authzID that is an additional bind
// user.
bindRequest = new PLAINBindRequest("u:test.user", "dn:cn=Directory Manager", "password", new AuthorizationIdentityRequestControl());
bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
authzIDResponse = AuthorizationIdentityResponseControl.get(bindResult);
assertNotNull(authzIDResponse);
authzID = authzIDResponse.getAuthorizationID();
assertNotNull(authzID);
assertTrue(authzID.startsWith("dn:"));
assertEquals(new DN(authzID.substring(3)), new DN("cn=Directory Manager"));
// Test a bind as a nonexistent dn-style authentication ID.
bindRequest = new PLAINBindRequest("dn:cn=missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "dn-style authentication ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind as a nonexistent u-style authentication ID.
bindRequest = new PLAINBindRequest("u:missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "u-style authentication ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind as a nonexistent dn-style authorization ID.
bindRequest = new PLAINBindRequest("dn:cn=Directory Manager", "dn:cn=missing", "password");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind with a nonexistent " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind with an incorrect password.
bindRequest = new PLAINBindRequest("u:test.user", "wrong");
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.INVALID_CREDENTIALS);
}
// Test a bind with an unsupported critical control.
bindRequest = new PLAINBindRequest("u:test.user", "wrong", new Control("1.2.3.4", true));
try {
bindResult = conn.bind(bindRequest);
fail("Expected an exception when trying to bind anonymously with an " + "authorization ID");
} catch (final LDAPException le) {
assertEquals(le.getResultCode(), ResultCode.UNAVAILABLE_CRITICAL_EXTENSION);
}
final Control[] unbindControls = { new Control("1.2.3.4", false), new Control("1.2.3.5", false, new ASN1OctetString("foo")) };
conn.close(unbindControls);
}
use of com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl in project ldapsdk by pingidentity.
the class RequestControlPreProcessorTestCase method testAuthorizationIdentityControl.
/**
* Provides test coverage for the authorization identity control.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testAuthorizationIdentityControl() throws Exception {
final String oid = AuthorizationIdentityRequestControl.AUTHORIZATION_IDENTITY_REQUEST_OID;
final Control vc = new AuthorizationIdentityRequestControl(true);
final Control vn = new AuthorizationIdentityRequestControl(false);
final Control ic = new Control(oid, true, new ASN1OctetString("foo"));
final Control in = new Control(oid, false, new ASN1OctetString("foo"));
final Class<?> c = AuthorizationIdentityRequestControl.class;
// Test with acceptable operation types.
for (final byte opType : Arrays.asList(LDAPMessage.PROTOCOL_OP_TYPE_BIND_REQUEST)) {
// A valid critical control.
ensureControlHandled(opType, Arrays.asList(vc), oid, c);
// A valid non-critical control.
ensureControlHandled(opType, Arrays.asList(vn), oid, c);
// Multiple instances of the control.
ensureException(opType, Arrays.asList(vc, vn));
// Malformed critical control.
ensureException(opType, Arrays.asList(ic));
// Malformed non-critical control.
ensureException(opType, Arrays.asList(in));
}
// Test with unacceptable operation types.
for (final byte opType : Arrays.asList(LDAPMessage.PROTOCOL_OP_TYPE_ABANDON_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_ADD_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_COMPARE_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_DELETE_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_EXTENDED_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_MODIFY_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_MODIFY_DN_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_SEARCH_REQUEST, LDAPMessage.PROTOCOL_OP_TYPE_UNBIND_REQUEST)) {
// A valid critical control.
ensureException(opType, Arrays.asList(vc));
// A valid non-critical control.
ensureControlIgnored(opType, Arrays.asList(vn), oid);
// Malformed critical control.
ensureException(opType, Arrays.asList(ic));
// Malformed non-critical control.
ensureControlIgnored(opType, Arrays.asList(in), oid);
}
}
use of com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl in project ldapsdk by pingidentity.
the class RetainIdentityRequestControlTestCase method testSendAuthenticatedPLAINRequest.
/**
* Sends a request to the server containing the retain identity request
* control. It will establish an unauthenticated connection, then send a SASL
* PLAIN bind including the retain identity request control It will verify
* that the identity of the client connection has not changed.
* <BR><BR>
* Access to a Directory Server instance is required for complete processing.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testSendAuthenticatedPLAINRequest() throws Exception {
if (!isDirectoryInstanceAvailable()) {
return;
}
LDAPConnection conn = getAdminConnection();
conn.add(getTestBaseDN(), getBaseEntryAttributes());
conn.add("dn: uid=test," + getTestBaseDN(), "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "objectClass: inetOrgPerson", "givenName: Test", "sn: User", "cn: Test User", "uid: test", "userPassword: password");
// First, use the "Who Am I?" request to get the current authorization
// identity.
WhoAmIExtendedResult whoAmIResult = (WhoAmIExtendedResult) conn.processExtendedOperation(new WhoAmIExtendedRequest());
String authzID = whoAmIResult.getAuthorizationID();
assertNotNull(authzID);
// Perform an authenticated simple bind that includes both the retain
// identity request control and the authorization identity request control.
Control[] controls = { new RetainIdentityRequestControl(), new AuthorizationIdentityRequestControl() };
PLAINBindRequest bindRequest = new PLAINBindRequest("dn:uid=test," + getTestBaseDN(), "password", controls);
BindResult bindResult = conn.bind(bindRequest);
assertEquals(bindResult.getResultCode(), ResultCode.SUCCESS);
boolean authzIDFound = false;
for (Control c : bindResult.getResponseControls()) {
if (c instanceof AuthorizationIdentityResponseControl) {
authzIDFound = true;
String bindAuthzID = ((AuthorizationIdentityResponseControl) c).getAuthorizationID();
assertNotNull(bindAuthzID);
assertFalse(bindAuthzID.equals(authzID));
break;
}
}
assertTrue(authzIDFound);
// Use the "Who Am I?" request again to verify that the client identity
// hasn't really changed.
whoAmIResult = (WhoAmIExtendedResult) conn.processExtendedOperation(new WhoAmIExtendedRequest());
assertNotNull(whoAmIResult.getAuthorizationID());
assertEquals(whoAmIResult.getAuthorizationID(), authzID);
conn.delete("uid=test," + getTestBaseDN());
conn.delete(getTestBaseDN());
conn.close();
}
Aggregations