summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/profile/constraint/UniqueKeyConstraint.java
blob: 1770c13ef02ab88ffc1e34bcc6b73098fc816f7f (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
// --- 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.profile.constraint;


import java.util.*;
import java.io.*;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.profile.*;
import com.netscape.certsrv.request.*;
import com.netscape.certsrv.property.*;
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.ca.*;
import com.netscape.certsrv.dbs.certdb.*;
import com.netscape.cms.profile.common.*;
import com.netscape.cms.profile.def.*;

import netscape.security.x509.*;
//import netscape.security.provider.*;
import netscape.security.util.*;
import java.math.BigInteger;

/**
 * This constraint is to check for publickey uniqueness.
 * The config param "allowSameKeyRenewal" enables the
 * situation where if the publickey is not unique, and if
 * the subject DN is the same, that is a "renewal".
 *
 * Another "feature" that is quoted out of this code is the
 * "revokeDupKeyCert" option, which enables the revocation
 * of certs that bear the same publickey as the enrolling
 * request.  Since this can potentially be abused, it is taken
 * out and preserved in comments to allow future refinement.
 *
 * @version $Revision$, $Date$
 */
public class UniqueKeyConstraint extends EnrollConstraint {
	/*
	public static final String CONFIG_REVOKE_DUPKEY_CERT =
		"revokeDupKeyCert";
	boolean mRevokeDupKeyCert = false;
	*/
	public static final String CONFIG_ALLOW_SAME_KEY_RENEWAL =
		"allowSameKeyRenewal";
	boolean mAllowSameKeyRenewal = false;
    public ICertificateAuthority mCA = null;

	public UniqueKeyConstraint() {
		super();
		/*
		addConfigName(CONFIG_REVOKE_DUPKEY_CERT);
		*/
		addConfigName(CONFIG_ALLOW_SAME_KEY_RENEWAL);
	}

	public void init(IProfile profile, IConfigStore config)
        throws EProfileException {
        super.init(profile, config);
        mCA = (ICertificateAuthority)
			CMS.getSubsystem(CMS.SUBSYSTEM_CA);
    }

    public IDescriptor getConfigDescriptor(Locale locale, String name)
	{
		/*
		if (name.equals(CONFIG_REVOKE_DUPKEY_CERT)) {
			return new Descriptor(IDescriptor.BOOLEAN, null, "false",
				  CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_REVOKE_DUPKEY_CERT"));
		}
		*/
		if (name.equals(CONFIG_ALLOW_SAME_KEY_RENEWAL)) {
			return new Descriptor(IDescriptor.BOOLEAN, null, "false",
				  CMS.getUserMessage(locale, "CMS_PROFILE_CONFIG_ALLOW_SAME_KEY_RENEWAL"));
		}
        return null;
    }

    public String getDefaultConfig(String name) {
        return null;
    }

    /**
     * Validates the request. The request is not modified
     * during the validation.
     */
    public void validate(IRequest request, X509CertInfo info)
        throws ERejectException { 
		boolean rejected = false;
		int size = 0;
		ICertRecordList list;

		/*
		mRevokeDupKeyCert =
 getConfigBoolean(CONFIG_REVOKE_DUPKEY_CERT);
		*/
		mAllowSameKeyRenewal = getConfigBoolean(CONFIG_ALLOW_SAME_KEY_RENEWAL);

        try {
            CertificateX509Key infokey = (CertificateX509Key)
                info.get(X509CertInfo.KEY);
            X509Key key = (X509Key)
				infokey.get(CertificateX509Key.KEY);

			// check for key uniqueness
			byte pub[] = key.getEncoded();
			String pub_s = escapeBinaryData(pub);
			String filter = "(" + ICertRecord.ATTR_X509CERT_PUBLIC_KEY_DATA +"=" + pub_s + ")";
			list =
				(ICertRecordList)
				mCA.getCertificateRepository().findCertRecordsInList(filter, null, 10);
			size = list.getSize();

        } catch (Exception e) {
                throw new ERejectException(	
                        CMS.getUserMessage(
                            getLocale(request),
                            "CMS_PROFILE_INTERNAL_ERROR",e.toString()));
		}

		/*
		 * It does not matter if the corresponding cert's status
		 * is valid or not, we don't want a key that was once
		 * generated before
		 */
		if (size > 0) {
			CMS.debug("UniqueKeyConstraint: found existing cert with duplicate key.");

		/*
		    The following code revokes the existing certs that have
			the same public key as the one submitted for enrollment
			request.  However, it is not a good idea due to possible
			abuse.  It is therefore commented out.  It is still
			however still maintained for possible utilization at later
			time

			// if configured to revoke duplicated key
			//    revoke cert
			if (mRevokeDupKeyCert) {
				try {
					Enumeration e = list.getCertRecords(0, size-1);
					while (e != null && e.hasMoreElements()) {
						ICertRecord rec = (ICertRecord) e.nextElement();
						X509CertImpl cert = rec.getCertificate();

						// revoke the cert
						BigInteger serialNum = cert.getSerialNumber();
						ICAService service = (ICAService) mCA.getCAService();

						RevokedCertImpl crlEntry = 
							formCRLEntry(serialNum, RevocationReason.KEY_COMPROMISE);
						service.revokeCert(crlEntry);
						CMS.debug("UniqueKeyConstraint: certificate with duplicate publickey revoked successfully");
					}
				} catch (Exception ex) {
					CMS.debug("UniqueKeyConstraint: error in revoke dupkey cert");
				}
			} // revoke dupkey cert turned on
		*/

			if (mAllowSameKeyRenewal == true) {
				X500Name sjname_in_db = null;
				X500Name sjname_in_req = null;

				try {
					// get subject of request
					CertificateSubjectName subName = 
						(CertificateSubjectName) info.get(X509CertInfo.SUBJECT);

					if (subName != null) {

						sjname_in_req =
							(X500Name) subName.get(CertificateSubjectName.DN_NAME);
						CMS.debug("UniqueKeyConstraint: cert request subject DN ="+ sjname_in_req.toString());
						Enumeration e = list.getCertRecords(0, size-1);
						while (e != null && e.hasMoreElements()) {
							ICertRecord rec = (ICertRecord) e.nextElement();
							X509CertImpl cert = rec.getCertificate();
							String certDN =
								cert.getSubjectDN().toString();
						CMS.debug("UniqueKeyConstraint: cert retrieved from ldap has subject DN ="+ certDN);

							sjname_in_db = new X500Name(certDN);

							if (sjname_in_db.equals(sjname_in_req) == false) {
								rejected = true;
								break;
							} else {
								rejected = false;
							}
						} // while
					} else { //subName is null
						rejected = true;
					}
				} catch (Exception ex1) {
					CMS.debug("UniqueKeyConstraint: error in allowSameKeyRenewal: "+ex1.toString());
					rejected = true;
				} // try

			} else {
				rejected = true;
			}// allowSameKeyRenewal
		} // (size > 0)

		if (rejected == true) {
			CMS.debug("UniqueKeyConstraint: rejected");
			throw new ERejectException(	
						   CMS.getUserMessage(
						  getLocale(request),
						  "CMS_PROFILE_DUPLICATE_KEY"));
		} else {
			CMS.debug("UniqueKeyConstraint: approved");
		}
    }

   /**
     * make a CRL entry from a serial number and revocation reason.
     * @return a RevokedCertImpl that can be entered in a CRL.

    protected RevokedCertImpl formCRLEntry(
        BigInteger serialNo, RevocationReason reason)
        throws EBaseException {
        CRLReasonExtension reasonExt = new CRLReasonExtension(reason);
        CRLExtensions crlentryexts = new CRLExtensions();

        try {
            crlentryexts.set(CRLReasonExtension.NAME, reasonExt);
        } catch (IOException e) {
                CMS.debug("CMSGW_ERR_CRL_REASON "+e.toString());

				//            throw new ECMSGWException(
				//  CMS.getLogMessage("CMSGW_ERROR_SETTING_CRLREASON"));

        }
        RevokedCertImpl crlentry =
            new RevokedCertImpl(serialNo, CMS.getCurrentDate(),
								crlentryexts);

        return crlentry;
    }
   */

    public String getText(Locale locale) {
        String params[] = {
/*
                getConfig(CONFIG_REVOKE_DUPKEY_CERT),
*/
             };

        return CMS.getUserMessage(locale, 
                "CMS_PROFILE_CONSTRAINT_ALLOW_SAME_KEY_RENEWAL_TEXT", params);
    }

    public static String escapeBinaryData(byte data[]) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < data.length; i++) {
            int v = 0xff & data[i];
            sb.append("\\");
            sb.append((v < 16 ? "0" : ""));
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }

    public boolean isApplicable(IPolicyDefault def) {
		if (def instanceof NoDefault)
			return true;
        if (def instanceof UniqueKeyConstraint)
            return true;

		return false;
    }

}