001/*
002 * Copyright 2007-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2007-2020 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2015-2020 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.ldap.sdk.unboundidds.controls;
037
038
039
040import java.util.ArrayList;
041
042import com.unboundid.asn1.ASN1Element;
043import com.unboundid.asn1.ASN1Enumerated;
044import com.unboundid.asn1.ASN1Exception;
045import com.unboundid.asn1.ASN1Integer;
046import com.unboundid.asn1.ASN1OctetString;
047import com.unboundid.asn1.ASN1Sequence;
048import com.unboundid.ldap.sdk.Control;
049import com.unboundid.ldap.sdk.DecodeableControl;
050import com.unboundid.ldap.sdk.LDAPException;
051import com.unboundid.ldap.sdk.LDAPResult;
052import com.unboundid.ldap.sdk.ResultCode;
053import com.unboundid.util.Debug;
054import com.unboundid.util.NotMutable;
055import com.unboundid.util.StaticUtils;
056import com.unboundid.util.ThreadSafety;
057import com.unboundid.util.ThreadSafetyLevel;
058
059import static com.unboundid.ldap.sdk.unboundidds.controls.ControlMessages.*;
060
061
062
063/**
064 * This class provides an implementation of the password policy response control
065 * as described in draft-behera-ldap-password-policy.  It may be used to provide
066 * information related to a user's password policy.  It may include at most one
067 * warning from the set of {@link PasswordPolicyWarningType} values and at most
068 * one error from the set of {@link PasswordPolicyErrorType} values.  See the
069 * documentation for those classes for more information on the information that
070 * may be included.  See the {@link PasswordPolicyRequestControl} documentation
071 * for an example that demonstrates the use of the password policy request and
072 * response controls.
073 * <BR>
074 * <BLOCKQUOTE>
075 *   <B>NOTE:</B>  This class, and other classes within the
076 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
077 *   supported for use against Ping Identity, UnboundID, and
078 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
079 *   for proprietary functionality or for external specifications that are not
080 *   considered stable or mature enough to be guaranteed to work in an
081 *   interoperable way with other types of LDAP servers.
082 * </BLOCKQUOTE>
083 * <BR>
084 * The control has an OID of 1.3.6.1.4.1.42.2.27.8.5.1 and a criticality of
085 * false.  It must have a value with the following encoding:
086 * <PRE>
087 *   PasswordPolicyResponseValue ::= SEQUENCE {
088 *      warning [0] CHOICE {
089 *         timeBeforeExpiration [0] INTEGER (0 .. maxInt),
090 *         graceAuthNsRemaining [1] INTEGER (0 .. maxInt) } OPTIONAL,
091 *      error   [1] ENUMERATED {
092 *         passwordExpired             (0),
093 *         accountLocked               (1),
094 *         changeAfterReset            (2),
095 *         passwordModNotAllowed       (3),
096 *         mustSupplyOldPassword       (4),
097 *         insufficientPasswordQuality (5),
098 *         passwordTooShort            (6),
099 *         passwordTooYoung            (7),
100 *         passwordInHistory           (8) } OPTIONAL }
101 * </PRE>
102 */
103@NotMutable()
104@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
105public final class PasswordPolicyResponseControl
106       extends Control
107       implements DecodeableControl
108{
109  /**
110   * The OID (1.3.6.1.4.1.42.2.27.8.5.1) for the password policy response
111   * control.
112   */
113  public static final String PASSWORD_POLICY_RESPONSE_OID =
114       "1.3.6.1.4.1.42.2.27.8.5.1";
115
116
117
118  /**
119   * The BER type for the password policy warning element.
120   */
121  private static final byte TYPE_WARNING = (byte) 0xA0;
122
123
124
125  /**
126   * The BER type for the password policy error element.
127   */
128  private static final byte TYPE_ERROR = (byte) 0x81;
129
130
131
132  /**
133   * The BER type for the "time before expiration" warning element.
134   */
135  private static final byte TYPE_TIME_BEFORE_EXPIRATION = (byte) 0x80;
136
137
138
139  /**
140   * The BER type for the "grace logins remaining" warning element.
141   */
142  private static final byte TYPE_GRACE_LOGINS_REMAINING = (byte) 0x81;
143
144
145
146  /**
147   * The serial version UID for this serializable class.
148   */
149  private static final long serialVersionUID = 1835830253434331833L;
150
151
152
153  // The password policy warning value, if applicable.
154  private final int warningValue;
155
156  // The password policy error type, if applicable.
157  private final PasswordPolicyErrorType errorType;
158
159  // The password policy warning type, if applicable.
160  private final PasswordPolicyWarningType warningType;
161
162
163
164  /**
165   * Creates a new empty control instance that is intended to be used only for
166   * decoding controls via the {@code DecodeableControl} interface.
167   */
168  PasswordPolicyResponseControl()
169  {
170    warningType  = null;
171    errorType    = null;
172    warningValue = -1;
173  }
174
175
176
177  /**
178   * Creates a new password policy response control with the provided
179   * information.  It will not be critical.
180   *
181   * @param  warningType   The password policy warning type for this response
182   *                       control, or {@code null} if there should be no
183   *                       warning type.
184   * @param  warningValue  The value for the password policy warning type, or -1
185   *                       if there is no warning type.
186   * @param  errorType     The password policy error type for this response
187   *                       control, or {@code null} if there should be no error
188   *                       type.
189   */
190  public PasswordPolicyResponseControl(
191              final PasswordPolicyWarningType warningType,
192              final int warningValue, final PasswordPolicyErrorType errorType)
193  {
194    this(warningType, warningValue, errorType, false);
195  }
196
197
198
199  /**
200   * Creates a new password policy response control with the provided
201   * information.
202   *
203   * @param  warningType   The password policy warning type for this response
204   *                       control, or {@code null} if there should be no
205   *                       warning type.
206   * @param  warningValue  The value for the password policy warning type, or -1
207   *                       if there is no warning type.
208   * @param  errorType     The password policy error type for this response
209   *                       control, or {@code null} if there should be no error
210   *                       type.
211   * @param  isCritical    Indicates whether this control should be marked
212   *                       critical.  Response controls should generally not be
213   *                       critical.
214   */
215  public PasswordPolicyResponseControl(
216              final PasswordPolicyWarningType warningType,
217              final int warningValue, final PasswordPolicyErrorType errorType,
218              final boolean isCritical)
219  {
220    super(PASSWORD_POLICY_RESPONSE_OID, isCritical,
221          encodeValue(warningType, warningValue, errorType));
222
223    this.warningType = warningType;
224    this.errorType   = errorType;
225
226    if (warningType == null)
227    {
228      this.warningValue = -1;
229    }
230    else
231    {
232      this.warningValue = warningValue;
233    }
234  }
235
236
237
238  /**
239   * Creates a new password policy response control with the provided
240   * information.
241   *
242   * @param  oid         The OID for the control.
243   * @param  isCritical  Indicates whether the control should be marked
244   *                     critical.
245   * @param  value       The encoded value for the control.  This may be
246   *                     {@code null} if no value was provided.
247   *
248   * @throws  LDAPException  If the provided control cannot be decoded as a
249   *                         password policy response control.
250   */
251  public PasswordPolicyResponseControl(final String oid,
252                                       final boolean isCritical,
253                                       final ASN1OctetString value)
254         throws LDAPException
255  {
256    super(oid, isCritical, value);
257
258    if (value == null)
259    {
260      throw new LDAPException(ResultCode.DECODING_ERROR,
261                              ERR_PWP_RESPONSE_NO_VALUE.get());
262    }
263
264    final ASN1Sequence valueSequence;
265    try
266    {
267      final ASN1Element valueElement = ASN1Element.decode(value.getValue());
268      valueSequence = ASN1Sequence.decodeAsSequence(valueElement);
269    }
270    catch (final ASN1Exception ae)
271    {
272      Debug.debugException(ae);
273      throw new LDAPException(ResultCode.DECODING_ERROR,
274                              ERR_PWP_RESPONSE_VALUE_NOT_SEQUENCE.get(ae), ae);
275    }
276
277    final ASN1Element[] valueElements = valueSequence.elements();
278    if (valueElements.length > 2)
279    {
280      throw new LDAPException(ResultCode.DECODING_ERROR,
281                              ERR_PWP_RESPONSE_INVALID_ELEMENT_COUNT.get(
282                                   valueElements.length));
283    }
284
285    int                       wv = -1;
286    PasswordPolicyErrorType   et = null;
287    PasswordPolicyWarningType wt = null;
288    for (final ASN1Element e : valueElements)
289    {
290      switch (e.getType())
291      {
292        case TYPE_WARNING:
293          if (wt == null)
294          {
295            try
296            {
297              final ASN1Element warningElement =
298                   ASN1Element.decode(e.getValue());
299              wv = ASN1Integer.decodeAsInteger(warningElement).intValue();
300              switch (warningElement.getType())
301              {
302                case TYPE_TIME_BEFORE_EXPIRATION:
303                  wt = PasswordPolicyWarningType.TIME_BEFORE_EXPIRATION;
304                  break;
305
306                case TYPE_GRACE_LOGINS_REMAINING:
307                  wt = PasswordPolicyWarningType.GRACE_LOGINS_REMAINING;
308                  break;
309
310                default:
311                  throw new LDAPException(ResultCode.DECODING_ERROR,
312                       ERR_PWP_RESPONSE_INVALID_WARNING_TYPE.get(
313                            StaticUtils.toHex(warningElement.getType())));
314              }
315            }
316            catch (final ASN1Exception ae)
317            {
318              Debug.debugException(ae);
319              throw new LDAPException(ResultCode.DECODING_ERROR,
320                   ERR_PWP_RESPONSE_CANNOT_DECODE_WARNING.get(ae), ae);
321            }
322          }
323          else
324          {
325            throw new LDAPException(ResultCode.DECODING_ERROR,
326                                    ERR_PWP_RESPONSE_MULTIPLE_WARNING.get());
327          }
328          break;
329
330        case TYPE_ERROR:
331          if (et == null)
332          {
333            try
334            {
335              final ASN1Enumerated errorElement =
336                   ASN1Enumerated.decodeAsEnumerated(e);
337              et = PasswordPolicyErrorType.valueOf(errorElement.intValue());
338              if (et == null)
339              {
340                  throw new LDAPException(ResultCode.DECODING_ERROR,
341                       ERR_PWP_RESPONSE_INVALID_ERROR_TYPE.get(
342                            errorElement.intValue()));
343              }
344            }
345            catch (final ASN1Exception ae)
346            {
347              Debug.debugException(ae);
348              throw new LDAPException(ResultCode.DECODING_ERROR,
349                   ERR_PWP_RESPONSE_CANNOT_DECODE_ERROR.get(ae), ae);
350            }
351          }
352          else
353          {
354            throw new LDAPException(ResultCode.DECODING_ERROR,
355                 ERR_PWP_RESPONSE_MULTIPLE_ERROR.get());
356          }
357          break;
358
359        default:
360          throw new LDAPException(ResultCode.DECODING_ERROR,
361               ERR_PWP_RESPONSE_INVALID_TYPE.get(
362                    StaticUtils.toHex(e.getType())));
363      }
364    }
365
366    warningType  = wt;
367    warningValue = wv;
368    errorType    = et;
369  }
370
371
372
373  /**
374   * {@inheritDoc}
375   */
376  @Override()
377  public PasswordPolicyResponseControl
378              decodeControl(final String oid, final boolean isCritical,
379                            final ASN1OctetString value)
380         throws LDAPException
381  {
382    return new PasswordPolicyResponseControl(oid, isCritical, value);
383  }
384
385
386
387  /**
388   * Extracts a password policy response control from the provided result.
389   *
390   * @param  result  The result from which to retrieve the password policy
391   *                 response control.
392   *
393   * @return  The password policy response control contained in the provided
394   *          result, or {@code null} if the result did not contain a password
395   *          policy response control.
396   *
397   * @throws  LDAPException  If a problem is encountered while attempting to
398   *                         decode the password policy response control
399   *                         contained in the provided result.
400   */
401  public static PasswordPolicyResponseControl get(final LDAPResult result)
402         throws LDAPException
403  {
404    final Control c = result.getResponseControl(PASSWORD_POLICY_RESPONSE_OID);
405    if (c == null)
406    {
407      return null;
408    }
409
410    if (c instanceof PasswordPolicyResponseControl)
411    {
412      return (PasswordPolicyResponseControl) c;
413    }
414    else
415    {
416      return new PasswordPolicyResponseControl(c.getOID(), c.isCritical(),
417           c.getValue());
418    }
419  }
420
421
422
423  /**
424   * Encodes the provided information as appropriate for use as the value of a
425   * password policy response control.
426   *
427   * @param  warningType   The warning type to use for the warning element, or
428   *                       {@code null} if there is not to be a warning element.
429   * @param  warningValue  The value to use for the warning element.
430   * @param  errorType     The error type to use for the error element, or
431   *                       {@code null} if there is not to be an error element.
432   *
433   * @return  The ASN.1 octet string containing the encoded control value.
434   */
435  private static ASN1OctetString
436          encodeValue(final PasswordPolicyWarningType warningType,
437                      final int warningValue,
438                      final PasswordPolicyErrorType errorType)
439  {
440    final ArrayList<ASN1Element> valueElements = new ArrayList<>(2);
441
442    if (warningType != null)
443    {
444      switch (warningType)
445      {
446        case TIME_BEFORE_EXPIRATION:
447          valueElements.add(new ASN1Element(TYPE_WARNING,
448               new ASN1Integer(TYPE_TIME_BEFORE_EXPIRATION,
449                               warningValue).encode()));
450          break;
451
452        case GRACE_LOGINS_REMAINING:
453          valueElements.add(new ASN1Element(TYPE_WARNING,
454               new ASN1Integer(TYPE_GRACE_LOGINS_REMAINING,
455                               warningValue).encode()));
456          break;
457      }
458    }
459
460    if (errorType != null)
461    {
462      valueElements.add(new ASN1Enumerated(TYPE_ERROR, errorType.intValue()));
463    }
464
465    return new ASN1OctetString(new ASN1Sequence(valueElements).encode());
466  }
467
468
469
470  /**
471   * Retrieves the warning type for this password policy response control, if
472   * available.
473   *
474   * @return  The warning type for this password policy response control, or
475   *          {@code null} if there is no warning type.
476   */
477  public PasswordPolicyWarningType getWarningType()
478  {
479    return warningType;
480  }
481
482
483
484  /**
485   * Retrieves the warning value for this password policy response control, if
486   * available.
487   *
488   * @return  The warning value for this password policy response control, or -1
489   *          if there is no warning type.
490   */
491  public int getWarningValue()
492  {
493    return warningValue;
494  }
495
496
497
498  /**
499   * Retrieves the error type for this password policy response control, if
500   * available.
501   *
502   * @return  The error type for this password policy response control, or
503   *          {@code null} if there is no error type.
504   */
505  public PasswordPolicyErrorType getErrorType()
506  {
507    return errorType;
508  }
509
510
511
512  /**
513   * {@inheritDoc}
514   */
515  @Override()
516  public String getControlName()
517  {
518    return INFO_CONTROL_NAME_PW_POLICY_RESPONSE.get();
519  }
520
521
522
523  /**
524   * {@inheritDoc}
525   */
526  @Override()
527  public void toString(final StringBuilder buffer)
528  {
529
530    buffer.append("PasswordPolicyResponseControl(");
531
532    boolean elementAdded = false;
533    if (warningType != null)
534    {
535      buffer.append("warningType='");
536      buffer.append(warningType.getName());
537      buffer.append("', warningValue=");
538      buffer.append(warningValue);
539      elementAdded = true;
540    }
541
542    if (errorType != null)
543    {
544      if (elementAdded)
545      {
546        buffer.append(", ");
547      }
548
549      buffer.append("errorType='");
550      buffer.append(errorType.getName());
551      buffer.append('\'');
552      elementAdded = true;
553    }
554
555    if (elementAdded)
556    {
557      buffer.append(", ");
558    }
559
560    buffer.append("isCritical=");
561    buffer.append(isCritical());
562    buffer.append(')');
563  }
564}