summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cmscore/authentication/ChallengePhraseAuthentication.java
blob: 2f8a33faabb8a084378202cab349ff29b6517660 (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
// --- 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.cmscore.authentication;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;

import netscape.security.x509.X509CertImpl;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.AuthToken;
import com.netscape.certsrv.authentication.EAuthException;
import com.netscape.certsrv.authentication.EAuthUserError;
import com.netscape.certsrv.authentication.EInvalidCredentials;
import com.netscape.certsrv.authentication.EMissingCredential;
import com.netscape.certsrv.authentication.IAuthCredentials;
import com.netscape.certsrv.authentication.IAuthManager;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.MetaInfo;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.ra.IRegistrationAuthority;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.certsrv.usrgrp.ICertUserLocator;
import com.netscape.cmscore.base.SubsystemRegistry;
import com.netscape.cmscore.dbs.CertRecord;
import com.netscape.cmscore.dbs.CertificateRepository;
import com.netscape.cmscore.util.Debug;

/**
 * Challenge phrase based authentication.
 * Maps a certificate to the request in the
 * internal database and further compares the challenge phrase with
 * that from the EE input.
 * <P>
 * 
 * @author cfu chrisho
 * @version $Revision$, $Date$
 */
public class ChallengePhraseAuthentication implements IAuthManager {

    /* result auth token attributes */
    public static final String TOKEN_CERT_SERIAL = "certSerialToRevoke";

    /* required credentials */
    public static final String CRED_CERT_SERIAL = IAuthManager.CRED_CERT_SERIAL_TO_REVOKE;
    public static final String CRED_CHALLENGE = "challengePhrase";
    protected String[] mRequiredCreds = { CRED_CERT_SERIAL, CRED_CHALLENGE };

    /* config parameters to pass to console (none) */
    protected static String[] mConfigParams = null;
    protected ICertificateAuthority mCA = null;
    protected ICertificateRepository mCertDB = null;

    private String mName = null;
    private String mImplName = null;
    private IConfigStore mConfig = null;

    private ICertUserLocator mCULocator = null;
    private ILogger mLogger = CMS.getLogger();
    private String mRequestor = null;
    private Vector mID = null;
    private MessageDigest mSHADigest = null;

    // request attributes hacks 
    public static final String CHALLENGE_PHRASE = CRED_CHALLENGE;
    public static final String SUBJECTNAME = "subjectName";
    public static final String SERIALNUMBER = "serialNumber";
    public static final String SERIALNOARRAY = "serialNoArray";

    public ChallengePhraseAuthentication() {
    }

    /**
     * initializes the ChallengePhraseAuthentication auth manager
     * <p>
     * called by AuthSubsystem init() method, when initializing all available authentication managers.
     * 
     * @param name The name of this authentication manager instance.
     * @param implName The name of the authentication manager plugin.
     * @param config The configuration store for this authentication manager.
     */
    public void init(String name, String implName, IConfigStore config)
            throws EBaseException {
        mName = name;
        mImplName = implName;
        mConfig = config;

        try {
            mSHADigest = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new EAuthException(CMS.getUserMessage("CMS_AUTHENTICATION_INTERNAL_ERROR", e.getMessage()));
        }

        log(ILogger.LL_INFO, CMS.getLogMessage("INIT_DONE", name));
    }

    /**
     * Gets the name of this authentication manager.
     */
    public String getName() {
        return mName;
    }

    /**
     * Gets the plugin name of authentication manager.
     */
    public String getImplName() {
        return mImplName;
    }

    /**
     * authenticates revocation of a certification by a challenge phrase
     * <p>
     * called by other subsystems or their servlets to authenticate a revocation request
     * 
     * @param authCred - authentication credential that contains
     *            a Certificate to revoke
     * @return the authentication token that contains the request id
     * 
     * @exception EMissingCredential If a required credential for this
     *                authentication manager is missing.
     * @exception EInvalidCredentials If credentials cannot be authenticated.
     * @exception EBaseException If an internal error occurred.
     * @see com.netscape.certsrv.authentication.AuthToken
     */
    public IAuthToken authenticate(IAuthCredentials authCred)
            throws EMissingCredential, EInvalidCredentials, EBaseException {
        mCA = (ICertificateAuthority)
                SubsystemRegistry.getInstance().get("ca");

        if (mCA != null) {
            mCertDB = (CertificateRepository) mCA.getCertificateRepository();
        }

        AuthToken authToken = new AuthToken(this);

        /*
         X509Certificate[] x509Certs = 
         (X509Certificate[]) authCred.get(CRED_CERT);
         if (x509Certs == null) {
         log(ILogger.LL_FAILURE, 
         " missing cert credential.");
         throw new EMissingCredential(CRED_CERT_SERIAL);
         }
         */

        String serialNumString = (String) authCred.get(CRED_CERT_SERIAL);

        BigInteger serialNum = null;

        if (serialNumString == null || serialNumString.equals(""))
            throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CERT_SERIAL));
        else {
            //serialNumString = getDecimalStr(serialNumString);
            try {
                serialNumString = serialNumString.trim();
                if (serialNumString.startsWith("0x") || serialNumString.startsWith("0X")) {
                    serialNum = new
                            BigInteger(serialNumString.substring(2), 16);
                } else {
                    serialNum = new
                            BigInteger(serialNumString);
                }

            } catch (NumberFormatException e) {
                throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE",
                        "Invalid serial number."));
            }
        }

        String challenge = (String) authCred.get(CRED_CHALLENGE);

        if (challenge == null) {
            throw new EMissingCredential(CMS.getUserMessage("CMS_AUTHENTICATION_NULL_CREDENTIAL", CRED_CHALLENGE));
        }
        if (challenge.equals("")) {
            // empty challenge not allowed
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_REVO_ATTEMPT", serialNum.toString()));
            throw new EInvalidCredentials(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_CREDENTIAL"));
        }

        /* maybe later
         if (mCertDB.isCertificateRevoked(cert) != null) {
         log(ILogger.LL_FAILURE, 
         "Certificate has already been revoked.");
         // throw something else...cfu
         throw new EInvalidCredentials();
         }
         */

        X509CertImpl[] certsToRevoke = null;
        BigInteger[] bigIntArray = null;

        // check challenge phrase against request
        /*
         * map cert to a request: a cert serial number maps to a
         * cert record in the internal db, from the cert record,
         * where we'll find the challenge phrase
         */
        if (mCertDB != null) { /* is CA */
            CertRecord record = null;

            try {
                record = (CertRecord) mCertDB.readCertificateRecord(serialNum);
            } catch (EBaseException ee) {
                if (Debug.ON) {
                    Debug.trace(ee.toString());
                }
            }
            if (record != null) {
                String status = record.getStatus();

                if (!status.equals("REVOKED")) {
                    boolean samepwd = compareChallengePassword(record, challenge);

                    if (samepwd) {
                        bigIntArray = new BigInteger[1];
                        bigIntArray[0] = record.getSerialNumber();
                    } else
                        throw new EAuthUserError(CMS.getUserMessage("CMS_AUTHENTICATION_INVALID_ATTRIBUTE_VALUE",
                                "Invalid password."));

                } else {
                    bigIntArray = new BigInteger[0];
                }
            } else {
                bigIntArray = new BigInteger[0];
            }
        } else {

            /*
             * ra, build a request and send through the connection for
             * authentication
             */
            IRequestQueue queue = getReqQueue();

            if (queue != null) {
                IRequest checkChallengeReq = null;

                checkChallengeReq =
                        queue.newRequest(IRequest.REVOCATION_CHECK_CHALLENGE_REQUEST);
                checkChallengeReq.setExtData(CHALLENGE_PHRASE, challenge);
                // pass just serial number instead of whole cert
                if (serialNum != null)
                    checkChallengeReq.setExtData(SERIALNUMBER, serialNum);
                queue.processRequest(checkChallengeReq);
                // check request status...
                RequestStatus status = checkChallengeReq.getRequestStatus();

                if (status == RequestStatus.COMPLETE) {
                    bigIntArray = checkChallengeReq.getExtDataInBigIntegerArray("serialNoArray");
                } else {
                    log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_INCOMPLETE_REQUEST"));
                }
            } else {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_AUTH_FAILED_GET_QUEUE"));
                throw new EBaseException(CMS.getUserMessage("CMS_BASE_REVOCATION_CHALLENGE_QUEUE_FAILED"));
            }
        } // else, ra
        if (bigIntArray != null && bigIntArray.length > 0) {
            if (Debug.ON) {
                Debug.trace("challenge authentication serialno array not null");
                for (int i = 0; i < bigIntArray.length; i++)
                    Debug.trace("challenge auth serialno " + bigIntArray[i]);
            }
        }
        if (Debug.ON) {
            Debug.trace("challenge authentication set " + TOKEN_CERT_SERIAL);
        }
        authToken.set(TOKEN_CERT_SERIAL, bigIntArray);

        return authToken;
    }

    private boolean compareChallengePassword(CertRecord record, String pwd)
            throws EBaseException {
        MetaInfo metaInfo = (MetaInfo) record.get(CertRecord.ATTR_META_INFO);

        if (metaInfo == null) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", "metaInfo"));
        }

        if (pwd == null) {
            if (Debug.ON) {
                Debug.trace("challenge pwd is null");
            }
            return false;
        }
        String hashpwd = hashPassword(pwd);

        // got metaInfo
        String challengeString =
                (String) metaInfo.get(CertRecord.META_CHALLENGE_PHRASE);

        if (challengeString == null) {
            if (Debug.ON) {
                Debug.trace("challengeString null");
            }
            return false;
        }

        if (!challengeString.equals(hashpwd)) {
            return false;

            /*
             log(ILogger.LL_FAILURE,
             "Incorrect challenge phrase password used for revocation");
             throw new EInvalidCredentials();
             */
        } else
            return true;
    }

    /**
     * get the list of authentication credential attribute names
     * required by this authentication manager. Generally used by
     * the servlets that handle agent operations to authenticate its
     * users. It calls this method to know which are the
     * required credentials from the user (e.g. Javascript form data)
     * 
     * @return attribute names in Vector
     */
    public String[] getRequiredCreds() {
        return (mRequiredCreds);
    }

    /**
     * get the list of configuration parameter names
     * required by this authentication manager. Generally used by
     * the Certificate Server Console to display the table for
     * configuration purposes. ChallengePhraseAuthentication is currently not
     * exposed in this case, so this method is not to be used.
     * 
     * @return configuration parameter names in Hashtable of Vectors
     *         where each hashtable entry's key is the substore name, value is a
     *         Vector of parameter names. If no substore, the parameter name
     *         is the Hashtable key itself, with value same as key.
     */
    public String[] getConfigParams() {
        return (mConfigParams);
    }

    /**
     * prepare this authentication manager for shutdown.
     */
    public void shutdown() {
    }

    /**
     * gets the configuretion substore used by this authentication
     * manager
     * 
     * @return configuration store
     */
    public IConfigStore getConfigStore() {
        return mConfig;
    }

    private void log(int level, String msg) {
        if (mLogger == null)
            return;
        mLogger.log(ILogger.EV_SYSTEM, null, ILogger.S_AUTHENTICATION,
                level, msg);
    }

    private IRequestQueue getReqQueue() {
        IRequestQueue queue = null;

        try {
            IRegistrationAuthority ra = (IRegistrationAuthority)
                    SubsystemRegistry.getInstance().get("ra");

            if (ra != null) {
                queue = ra.getRequestQueue();
                mRequestor = IRequest.REQUESTOR_RA;
            }
        } catch (Exception e) {
            log(ILogger.LL_FAILURE,
                    " cannot get access to the request queue.");
        }

        return queue;
    }

    private String hashPassword(String pwd) {
        String salt = "lala123";
        byte[] pwdDigest = mSHADigest.digest((salt + pwd).getBytes());
        String b64E = com.netscape.osutil.OSUtil.BtoA(pwdDigest);

        return "{SHA}" + b64E;
    }
}