summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/authentication/UidPwdPinDirAuthentication.java
blob: 7b6e41da02412f0e3fc420c15eb42c16f2290b7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.authentication;


// ldap java sdk
import netscape.ldap.*;
import java.util.*;

// cert server imports.
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.ldap.*;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.ldap.ELdapException;
import com.netscape.certsrv.ldap.LdapResources;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.authentication.*;
import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.profile.*;
import com.netscape.certsrv.property.*;
import com.netscape.certsrv.request.*;

// cert server x509 imports
import netscape.security.x509.X509CertInfo;
import netscape.security.x509.X500Name;
import netscape.security.x509.CertificateSubjectName;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;

// java sdk imports.
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
import java.io.IOException;
import java.io.*;


/**
 * uid/pwd/pin directory based authentication manager
 * <P>
 *
 * @version $Revision$, $Date$
 */
public class UidPwdPinDirAuthentication extends DirBasedAuthentication
    implements IExtendedPluginInfo, IProfileAuthenticator {

    /* required credentials to authenticate. uid and pwd are strings. */
    public static final String CRED_UID = "uid";
    public static final String CRED_PWD = "pwd";
    public static final String CRED_PIN = "pin";
    protected static String[] mRequiredCreds = { CRED_UID, CRED_PWD, CRED_PIN };

    public static final String PROP_REMOVE_PIN = "removePin";
    public static final String PROP_PIN_ATTR = "pinAttr";

    public static final boolean DEF_REMOVE_PIN = false;
    public static final String DEF_PIN_ATTR = "pin";

    protected static final byte SENTINEL_SHA = 0;
    protected static final byte SENTINEL_MD5 = 1;
    protected static final byte SENTINEL_NONE = 0x2d;

    /* Holds configuration parameters accepted by this implementation.
     * This list is passed to the configuration console so configuration
     * for instances of this implementation can be configured through the
     * console.
     */
    protected static String[] mConfigParams = 
        new String[] { PROP_REMOVE_PIN,
            PROP_PIN_ATTR,
            PROP_DNPATTERN,
            PROP_LDAPSTRINGATTRS,
            PROP_LDAPBYTEATTRS,
            "ldap.ldapconn.host",
            "ldap.ldapconn.port",
            "ldap.ldapconn.secureConn",
            "ldap.ldapconn.version",
            "ldap.ldapauth.bindDN",
            "ldap.ldapauth.bindPWPrompt",
            "ldap.ldapauth.clientCertNickname",
            "ldap.ldapauth.authtype",
            "ldap.basedn",
            "ldap.minConns", 
            "ldap.maxConns",
        };

    static {
        mExtendedPluginInfo.add(
            PROP_REMOVE_PIN + ";boolean;SEE DOCUMENTATION for pin removal");
        mExtendedPluginInfo.add(
            PROP_PIN_ATTR + ";string;directory attribute to use for pin (default 'pin')");
        mExtendedPluginInfo.add(
            "ldap.ldapauth.bindDN;string;DN to bind as for pin removal. "
            + "For example 'CN=PinRemoval User'");
        mExtendedPluginInfo.add(
            "ldap.ldapauth.bindPWPrompt;password;Enter password used to bind as " +
            "the above user");
        mExtendedPluginInfo.add(
            "ldap.ldapauth.clientCertNickname;string;If you want to use "
            + "SSL client auth to the directory, set the client "
            + "cert nickname here");
        mExtendedPluginInfo.add(
            "ldap.ldapauth.authtype;choice(BasicAuth,SslClientAuth),required;"
            + "How to bind to the directory (for pin removal only)");
        mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TEXT
            + ";Authenticate the username, password and pin provided "
            + "by the user against an LDAP directory. Works with the "
            + "Dir/Pin Based Enrollment HTML form");
        mExtendedPluginInfo.add(IExtendedPluginInfo.HELP_TOKEN +
            ";configuration-authrules-uidpwdpindirauth");

    }

    protected boolean mRemovePin = DEF_REMOVE_PIN;
    protected String mPinAttr = DEF_PIN_ATTR;
    protected MessageDigest mSHADigest = null;
    protected MessageDigest mMD5Digest = null;

    private   String mBindDN = null;
    private   String mBindPassword = null;

    private   ILdapConnFactory  removePinLdapFactory = null;
    private   LDAPConnection        removePinLdapConnection = null;
    private   IConfigStore          removePinLdapConfigStore = null;

    /**
     * Default constructor, initialization must follow.
     */
    public UidPwdPinDirAuthentication() {
        super();
    }

    public void init(String name, String implName, IConfigStore config) 
        throws EBaseException {
        super.init(name, implName, config);
        mRemovePin = 
                config.getBoolean(PROP_REMOVE_PIN, DEF_REMOVE_PIN);
        mPinAttr = 
                config.getString(PROP_PIN_ATTR, DEF_PIN_ATTR);
        if (mPinAttr.equals("")) {
            mPinAttr = DEF_PIN_ATTR;
        }

        if (mRemovePin) {
            removePinLdapConfigStore = config.getSubStore("ldap");
            removePinLdapFactory = CMS.getLdapBoundConnFactory();
            removePinLdapFactory.init(removePinLdapConfigStore);
            removePinLdapConnection = removePinLdapFactory.getConn();
        }
        
        try {
            mSHADigest = MessageDigest.getInstance("SHA1");
            mMD5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.getMessage()));
        }

    }

    protected void verifyPassword(String Password) {
    }    

    /**
     * Authenticates a user based on its uid, pwd, pin in the directory.
     * 
     * @param authCreds The authentication credentials with uid, pwd, pin.
     * @return The user's ldap entry dn.
     * @exception EInvalidCredentials If the uid and password are not valid
     * @exception EBaseException If an internal error occurs. 
     */
    protected String authenticate(LDAPConnection conn, 
        IAuthCredentials authCreds,
        AuthToken token)
        throws EBaseException {
        String userdn = null;
        String uid = null; 
        String pwd = null; 
        String pin = null; 

        try {
            // get the uid.
            uid = (String) authCreds.get(CRED_UID);
            if (uid == null) {
                throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_UID));
            }
	
            // get the password.
            pwd = (String) authCreds.get(CRED_PWD);
            if (pwd == null) {
                throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_PWD));
            }
            if (pwd.equals("")) {
                // anonymous binding not allowed
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_EMPTY_PASSWORD", uid));
                throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
            }

            // get the pin.
            pin = (String) authCreds.get(CRED_PIN);
            if (pin == null) {
                throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_PIN));
            }
            if (pin.equals("")) {
                // empty pin not allowed
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_EMPTY_PIN", uid));
                throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
            }

            // get user dn.
            LDAPSearchResults res = conn.search(mBaseDN,
                    LDAPv2.SCOPE_SUB, "(uid=" + uid + ")", null, false);

            if (res.hasMoreElements()) {
                LDAPEntry entry = (LDAPEntry) res.nextElement();

                userdn = entry.getDN();
            } else {
                log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_USER_NOT_EXIST", uid));
                throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
            }

            // bind as user dn and pwd - authenticates user with pwd.
            conn.authenticate(userdn, pwd);

            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_AUTHENTICATED", uid));
            // log(ILogger.LL_SECURITY, "found user : " + userdn);

            // check pin. 
            checkpin(conn, userdn, uid, pin);

            // set uid in the token.
            token.set(CRED_UID, uid);

            return userdn;
        } catch (ELdapException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CANNOT_CONNECT_LDAP", e.toString()));
            throw e;
        } catch (LDAPException e) {
            switch (e.getLDAPResultCode()) {
            case LDAPException.NO_SUCH_OBJECT: 
            case LDAPException.LDAP_PARTIAL_RESULTS: 
                log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_USER_NOT_EXIST", uid));
                throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));

            case LDAPException.INVALID_CREDENTIALS:
                log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_BAD_PASSWORD", uid));
                throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));

            case LDAPException.SERVER_DOWN:
                log(ILogger.LL_SECURITY, CMS.getLogMessage("LDAP_SERVER_DOWN"));
                throw new ELdapException(
                        CMS.getUserMessage("CMS_LDAP_SERVER_UNAVAILABLE", conn.getHost(), "" + conn.getPort()));

            default: 
                log(ILogger.LL_FAILURE, CMS.getLogMessage("OPERATION_ERROR", e.getMessage()));
                throw new ELdapException(
                        CMS.getUserMessage("CMS_LDAP_OTHER_LDAP_EXCEPTION", 
                            e.errorCodeToString()));
            }
        } 
    }

    protected void checkpin(LDAPConnection conn, String userdn, 
        String uid, String pin)
        throws EBaseException, LDAPException {
        LDAPSearchResults res = null;
        LDAPEntry entry = null;

        // get pin.

        res = conn.search(userdn, LDAPv2.SCOPE_BASE, 
                    "(objectclass=*)", new String[] { mPinAttr }, false);
        if (res.hasMoreElements()) {
            entry = (LDAPEntry) res.nextElement();
        } else {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_ENTRY_RETURNED", uid, userdn));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        LDAPAttribute pinAttr = entry.getAttribute(mPinAttr);

        if (pinAttr == null) {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        Enumeration pinValues = pinAttr.getByteValues();

        if (!pinValues.hasMoreElements()) {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }
        byte[] entrypin = (byte[]) pinValues.nextElement();  

        // compare value digest.

        if (entrypin == null || entrypin.length < 2) {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_NO_PIN_FOUND", uid));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }
       
        byte hashtype = entrypin[0];

        byte[] pinDigest = null;
        String toBeDigested = userdn + pin;

        if (hashtype == SENTINEL_SHA) {
            
            pinDigest = mSHADigest.digest(toBeDigested.getBytes());
        } else if (hashtype == SENTINEL_MD5) {
            pinDigest = mMD5Digest.digest(toBeDigested.getBytes());
        } else if (hashtype == SENTINEL_NONE) {
            pinDigest = toBeDigested.getBytes();
        } else {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMS_AUTH_UKNOWN_ENCODING_TYPE", mPinAttr, "*", userdn));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        if (pinDigest.length != (entrypin.length - 1)) {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_LENGTH_NOT_MATCHED", uid));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        int i;

        for (i = 0; i < (entrypin.length - 1); i++) {
            if (pinDigest[i] != entrypin[i + 1]) 
                break;
        }
        if (i != (entrypin.length - 1)) {
            log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_BAD_PASSWORD", uid));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        // pin ok. remove pin if so configured
        // Note that this means that a policy may reject this request later,
        // but the user will not be able to enroll again as his pin is gone.
        
        // We remove the pin using a different connection which is bound as
        // a more privileged user.

        if (mRemovePin) {

            try {
                removePinLdapConnection.modify(userdn, 
                    new LDAPModification(
                        LDAPModification.DELETE,
                        new LDAPAttribute(mPinAttr, entrypin)));

            } catch (LDAPException e) {
                log(ILogger.LL_SECURITY, CMS.getLogMessage("CMS_AUTH_CANT_REMOVE_PIN", userdn));
            }

        }
    }

    /**
     * Returns a list of configuration parameter names. 
     * The list is passed to the configuration console so instances of 
     * this implementation can be configured through the console.
     *
     * @return String array of configuration parameter names.
     */
    public String[] getConfigParams() {
        return (mConfigParams);
    }

    /**
     * Returns array of required credentials for this authentication manager.
     * @return Array of required credentials.
     */
    public String[] getRequiredCreds() {
        return mRequiredCreds;
    }

    // Profile-related methods

    public void init(IProfile profile, IConfigStore config)
        throws EProfileException {
    }

    /**
     * Retrieves the localizable name of this policy.
     */
    public String getName(Locale locale) {
        return CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_UID_PIN_NAME");
    }

    /**
     * Retrieves the localizable description of this policy.
     */
    public String getText(Locale locale) {
        return CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_UID_PIN_TEXT");
    }

    /**
     * Retrieves a list of names of the value parameter.
     */
    public Enumeration getValueNames() {
        Vector v = new Vector();

        v.addElement(CRED_UID);
        v.addElement(CRED_PWD);
        v.addElement(CRED_PIN);
        return v.elements();
    }

    public boolean isValueWriteable(String name) {
        if (name.equals(CRED_UID)) {
            return true;
        } else if (name.equals(CRED_PWD)) {
            return false;
        }
        return false;
    }

    /**
     * Retrieves the descriptor of the given value
     * parameter by name.
     */
    public IDescriptor getValueDescriptor(Locale locale, String name) {
        if (name.equals(CRED_UID)) {
            return new Descriptor(IDescriptor.STRING, null, null,
                    CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_UID"));
        } else if (name.equals(CRED_PWD)) {
            return new Descriptor(IDescriptor.PASSWORD, null, null,
                    CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_PWD"));
        } else if (name.equals(CRED_PIN)) {
            return new Descriptor(IDescriptor.PASSWORD, null, null,
                    CMS.getUserMessage(locale, "CMS_AUTHENTICATION_LDAP_PIN"));

        }
        return null;
    }

    public void populate(IAuthToken token, IRequest request)
        throws EProfileException {
        request.setExtData(IProfileAuthenticator.AUTHENTICATED_NAME,
                token.getInString(USER_DN));
    }

    public boolean isSSLClientRequired() {
        return false;
    }
}