summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/policy/extensions/NameConstraintsExt.java
blob: b204e57b28b8826ceeb338dbb491c5f94001834c (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
465
466
467
468
// --- 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.policy.extensions;


import java.util.*;
import java.io.*;
import java.security.cert.*;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.certsrv.policy.*;
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.ca.*;
import com.netscape.certsrv.logging.ILogger;
import netscape.security.x509.*;
import netscape.security.util.*;
import com.netscape.cms.policy.APolicyRule;


/**
 * Name Constraints Extension Policy
 * Adds the name constraints extension to a (CA) certificate. 
 * Filtering of CA certificates is done through predicates.
 * <P>
 * <PRE>
 * NOTE:  The Policy Framework has been replaced by the Profile Framework.
 * </PRE>
 * <P>
 *
 * @deprecated
 * @version $Revision$, $Date$
 */
public class NameConstraintsExt extends APolicyRule
    implements IEnrollmentPolicy, IExtendedPluginInfo {
    protected static final String PROP_CRITICAL = "critical";
    protected static final String PROP_NUM_PERMITTEDSUBTREES = "numPermittedSubtrees";
    protected static final String PROP_NUM_EXCLUDEDSUBTREES = "numExcludedSubtrees";

    protected static final String PROP_PERMITTEDSUBTREES = "permittedSubtrees";
    protected static final String PROP_EXCLUDEDSUBTREES = "excludedSubtrees";

    protected static final boolean DEF_CRITICAL = true;
    protected static final int DEF_NUM_PERMITTEDSUBTREES = 8;
    protected static final int DEF_NUM_EXCLUDEDSUBTREES = 8;

    protected boolean mEnabled = false;
    protected IConfigStore mConfig = null;

    protected boolean mCritical = DEF_CRITICAL;
    protected int mNumPermittedSubtrees = 0;
    protected int mNumExcludedSubtrees = 0;
    protected Subtree[] mPermittedSubtrees = null;
    protected Subtree[] mExcludedSubtrees = null;
    protected NameConstraintsExtension mNameConstraintsExtension = null;

    protected Vector mInstanceParams = new Vector();

    public NameConstraintsExt() {
        NAME = "NameConstraintsExt";
        DESC = "Sets Name Constraints Extension on subordinate CA certificates";
    }

    /**
     * Initializes this policy rule.
     * <P>
     *
     * The entries may be of the form:
     *
     *      ca.Policy.rule.<ruleName>.predicate=certType==ca
     *      ca.Policy.rule.<ruleName>.implName=
     *      ca.Policy.rule.<ruleName>.enable=true
     *
     * @param config	The config store reference
     */
    public void init(ISubsystem owner, IConfigStore config)
        throws EBaseException {
        mConfig = config;

        // XXX should do do this ? 
        // if CA does not allow subordinate CAs by way of basic constraints, 
        // this policy always rejects 
        /*****
         ICertAuthority certAuthority = (ICertAuthority)
         ((IPolicyProcessor)owner).getAuthority();
         if (certAuthority instanceof ICertificateAuthority) {
         CertificateChain caChain = certAuthority.getCACertChain();
         X509Certificate caCert = null;
         // Note that in RA the chain could be null if CA was not up when
         // RA was started. In that case just set the length to -1 and let
         // CA reject if it does not allow any subordinate CA certs.
         if (caChain != null) {
         caCert = caChain.getFirstCertificate();
         if (caCert != null) 
         mCAPathLen = caCert.getBasicConstraints();
         }
         }
         ****/

        mEnabled = mConfig.getBoolean(
                    IPolicyProcessor.PROP_ENABLE, false);
        mCritical = mConfig.getBoolean(PROP_CRITICAL, DEF_CRITICAL);
        mNumPermittedSubtrees = mConfig.getInteger(
                    PROP_NUM_PERMITTEDSUBTREES, DEF_NUM_PERMITTEDSUBTREES);
        mNumExcludedSubtrees = mConfig.getInteger(
                    PROP_NUM_EXCLUDEDSUBTREES, DEF_NUM_EXCLUDEDSUBTREES);

        if (mNumPermittedSubtrees < 0) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
                        PROP_NUM_PERMITTEDSUBTREES, 
                        "value must be greater than or equal to 0"));
        }
        if (mNumExcludedSubtrees < 0) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
                        PROP_NUM_EXCLUDEDSUBTREES, 
                        "value must be greater than or equal to 0"));
        }

        // init permitted subtrees if any.
        if (mNumPermittedSubtrees > 0) {
            mPermittedSubtrees = 
                    form_subtrees(PROP_PERMITTEDSUBTREES, mNumPermittedSubtrees);
            CMS.debug("NameConstraintsExt: formed permitted subtrees");
        }

        // init excluded subtrees if any.
        if (mNumExcludedSubtrees > 0) {
            mExcludedSubtrees = 
                    form_subtrees(PROP_EXCLUDEDSUBTREES, mNumExcludedSubtrees);
            CMS.debug("NameConstraintsExt: formed excluded subtrees");
        }

        // create instance of name constraints extension if enabled.
        if (mEnabled) {
            try {
                Vector permittedSubtrees = new Vector();

                for (int i = 0; i < mNumPermittedSubtrees; i++) {
                    permittedSubtrees.addElement(
                        mPermittedSubtrees[i].mGeneralSubtree);
                }
                Vector excludedSubtrees = new Vector();

                for (int j = 0; j < mNumExcludedSubtrees; j++) {
                    excludedSubtrees.addElement(
                        mExcludedSubtrees[j].mGeneralSubtree);
                }
                GeneralSubtrees psb = null;

                if (permittedSubtrees.size() > 0) {
                    psb = new GeneralSubtrees(permittedSubtrees);
                }
                GeneralSubtrees esb = null;

                if (excludedSubtrees.size() > 0) {
                    esb = new GeneralSubtrees(excludedSubtrees);
                }
                mNameConstraintsExtension = 
                        new NameConstraintsExtension(mCritical, 
                            psb,
                            esb);
                CMS.debug("NameConstraintsExt: formed Name Constraints Extension " +
                    mNameConstraintsExtension);
            } catch (IOException e) {
                throw new EBaseException(
                        CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
                            "Error initializing Name Constraints Extension: " + e));
            }
        }

        // form instance params 
        mInstanceParams.addElement(PROP_CRITICAL + "=" + mCritical);
        mInstanceParams.addElement(
            PROP_NUM_PERMITTEDSUBTREES + "=" + mNumPermittedSubtrees);
        mInstanceParams.addElement(
            PROP_NUM_EXCLUDEDSUBTREES + "=" + mNumExcludedSubtrees);
        if (mNumPermittedSubtrees > 0) {
            for (int i = 0; i < mPermittedSubtrees.length; i++) 
                mPermittedSubtrees[i].getInstanceParams(mInstanceParams);
        }
        if (mNumExcludedSubtrees > 0) {
            for (int j = 0; j < mExcludedSubtrees.length; j++) 
                mExcludedSubtrees[j].getInstanceParams(mInstanceParams);
        }
    }

    Subtree[] form_subtrees(String subtreesName, int numSubtrees) 
        throws EBaseException {
        Subtree[] subtrees = new Subtree[numSubtrees];

        for (int i = 0; i < numSubtrees; i++) {
            String subtreeName = subtreesName + i;
            IConfigStore subtreeConfig = mConfig.getSubStore(subtreeName);
            Subtree subtree = 
                new Subtree(subtreeName, subtreeConfig, mEnabled);

            subtrees[i] = subtree;
        }
        return subtrees;
    }

    /**
     * Adds Name Constraints Extension to a (CA) certificate.
     * 
     * If a Name constraints Extension is already there, accept it if 
     * it's been approved by agent, else replace it.
     *
     * @param req	The request on which to apply policy.
     * @return The policy result object.
     */
    public PolicyResult apply(IRequest req) {
        // if extension hasn't been properly configured reject requests until 
        // it has been resolved (or disabled).
        if (mNameConstraintsExtension == null) {
            //setError(req, PolicyResources.EXTENSION_NOT_INITED_1, NAME);
            //return PolicyResult.REJECTED;
            return PolicyResult.ACCEPTED;
        }

        // get certInfo from request.
        X509CertInfo[] ci = 
            req.getExtDataInCertInfoArray(IRequest.CERT_INFO);

        if (ci == null || ci[0] == null) {
            setError(req, CMS.getUserMessage("CMS_POLICY_NO_CERT_INFO"), NAME);
            return PolicyResult.REJECTED; 
        }

        for (int i = 0; i < ci.length; i++) {
            PolicyResult certRes = applyCert(req, ci[i]);

            if (certRes == PolicyResult.REJECTED)
                return certRes;
        }
        return PolicyResult.ACCEPTED;

    }

    public PolicyResult applyCert(IRequest req, X509CertInfo certInfo) {
        // check if name constraints extension already exists.
        // if not agent approved, replace name constraints extension with ours.
        // else ignore.
        try {
            NameConstraintsExtension nameConstraintsExt = null;
            CertificateExtensions extensions = (CertificateExtensions)
                certInfo.get(X509CertInfo.EXTENSIONS);

            try {
                if (extensions != null) {
                    nameConstraintsExt = (NameConstraintsExtension)
                            extensions.get(NameConstraintsExtension.NAME);
                }
            } catch (IOException e) {
                // extension isn't there. 
            }

            if (nameConstraintsExt != null) {
                if (agentApproved(req)) {
                    CMS.debug(
                        "NameConstraintsExt: request id from agent " + req.getRequestId() +
                        " already has name constraints - accepted");
                    return PolicyResult.ACCEPTED;
                } else {
                    CMS.debug(
                        "NameConstraintsExt: request id " + req.getRequestId() + " from user " +
                        " already has name constraints - deleted");
                    extensions.delete(NameConstraintsExtension.NAME);
                }
            }

            if (extensions == null) {
                certInfo.set(X509CertInfo.VERSION,
                    new CertificateVersion(CertificateVersion.V3));
                extensions = new CertificateExtensions();
                certInfo.set(X509CertInfo.EXTENSIONS, extensions);
            }
            extensions.set(
                NameConstraintsExtension.NAME, mNameConstraintsExtension);
            CMS.debug(
                "NameConstraintsExt: added Name Constraints Extension to request " +
                req.getRequestId());
            return PolicyResult.ACCEPTED;
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_NAME_CONST_EXTENSION", e.getMessage()));
            setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), 
                NAME, e.getMessage());
            return PolicyResult.REJECTED;
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.toString()));
            setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"), 
                NAME, "Certificate Info Error");
            return PolicyResult.REJECTED;
        }
    }

    /**
     * Return configured parameters for a policy rule instance.
     *
     * @return nvPairs A Vector of name/value pairs.
     */
    public Vector getInstanceParams() { 
        return mInstanceParams;
    }

    /**
     * Default config parameters. 
     * To add more permitted or excluded subtrees, 
     * increase the num to greater than 0 and more configuration params 
     * will show up in the console.
     */
    private static Vector mDefParams = new Vector();
    static {
        mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
        mDefParams.addElement(
            PROP_NUM_PERMITTEDSUBTREES + "=" + DEF_NUM_PERMITTEDSUBTREES);
        mDefParams.addElement(
            PROP_NUM_EXCLUDEDSUBTREES + "=" + DEF_NUM_EXCLUDEDSUBTREES);
        for (int k = 0; k < DEF_NUM_PERMITTEDSUBTREES; k++) {
            Subtree.getDefaultParams(PROP_PERMITTEDSUBTREES + k, mDefParams);
        }
        for (int l = 0; l < DEF_NUM_EXCLUDEDSUBTREES; l++) {
            Subtree.getDefaultParams(PROP_EXCLUDEDSUBTREES + l, mDefParams);
        }
    }

    /**
     * Return default parameters for a policy implementation.
     *
     * @return nvPairs A Vector of name/value pairs.
     */
    public Vector getDefaultParams() { 
        return mDefParams;
    }

    public String[] getExtendedPluginInfo(Locale locale) {
        Vector theparams = new Vector();

        theparams.addElement(PROP_CRITICAL + ";boolean;RFC 2459 recommendation: MUST be critical.");
        theparams.addElement(
            PROP_NUM_PERMITTEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");
        theparams.addElement(
            PROP_NUM_EXCLUDEDSUBTREES + ";number;See RFC 2459 sec 4.2.1.11");

        // now do the subtrees.
        for (int k = 0; k < DEF_NUM_PERMITTEDSUBTREES; k++) {
            Subtree.getExtendedPluginInfo(PROP_PERMITTEDSUBTREES + k, theparams);
        }
        for (int l = 0; l < DEF_NUM_EXCLUDEDSUBTREES; l++) {
            Subtree.getExtendedPluginInfo(PROP_EXCLUDEDSUBTREES + l, theparams);
        }
        theparams.addElement(IExtendedPluginInfo.HELP_TOKEN +
            ";configuration-policyrules-nameconstraints");
        theparams.addElement(IExtendedPluginInfo.HELP_TEXT +
            ";Adds Name Constraints Extension. See RFC 2459");

        String[] info = new String[theparams.size()];

        theparams.copyInto(info);
        return info;
    }
}


/**
 * subtree configuration 
 */
class Subtree {

    protected static final String PROP_BASE = "base";
    protected static final String PROP_MIN = "min";
    protected static final String PROP_MAX = "max";

    protected static final int DEF_MIN = 0;
    protected static final int DEF_MAX = -1; // -1 (less than 0) means not set.

    protected static final String 
        MINMAX_INFO = "number;See RFC 2459 section 4.2.1.11";

    String mName = null;
    IConfigStore mConfig = null;
    int mMin = DEF_MIN, mMax = DEF_MAX;
    IGeneralNameAsConstraintsConfig mBase = null;
    GeneralSubtree mGeneralSubtree = null;

    String mNameDot = null;
    String mNameDotMin = null;
    String mNameDotMax = null;

    public Subtree(
        String subtreeName, IConfigStore config, boolean policyEnabled) 
        throws EBaseException {
        mName = subtreeName;
        mConfig = config;

        if (mName != null) {
            mNameDot = mName + "."; 
            mNameDotMin = mNameDot + PROP_MIN;
            mNameDotMax = mNameDot + PROP_MAX;
        } else {
            mNameDot = "";
            mNameDotMin = PROP_MIN;
            mNameDotMax = PROP_MAX;
        }

        // necessary to expand/shrink # general names from console.
        if (mConfig.size() == 0) {
            mConfig.putInteger(mNameDotMin, mMin);
            mConfig.putInteger(mNameDotMax, mMax);
            // GeneralNameConfig will take care of stuff for generalname.
        }

        // if policy enabled get values to form the general subtree.
        mMin = mConfig.getInteger(PROP_MIN, DEF_MIN);
        mMax = mConfig.getInteger(PROP_MAX, DEF_MAX);
        if (mMax < -1) mMax = -1;
        mBase = CMS.createGeneralNameAsConstraintsConfig(
                    mNameDot + PROP_BASE, mConfig.getSubStore(PROP_BASE), 
                    true, policyEnabled);

        if (policyEnabled) {
            mGeneralSubtree = 
                    new GeneralSubtree(mBase.getGeneralName(), mMin, mMax);
        }
    }

    void getInstanceParams(Vector instanceParams) {
        mBase.getInstanceParams(instanceParams);
        instanceParams.addElement(mNameDotMin + "=" + mMin);
        instanceParams.addElement(mNameDotMax + "=" + mMax);
    }

    static void getDefaultParams(String name, Vector params) {
        String nameDot = "";

        if (name != null && name.length() >= 0)
            nameDot = name + ".";
        CMS.getGeneralNameConfigDefaultParams(nameDot + PROP_BASE, true, params);
        params.addElement(nameDot + PROP_MIN + "=" + DEF_MIN);
        params.addElement(nameDot + PROP_MAX + "=" + DEF_MAX);
    }

    static void getExtendedPluginInfo(String name, Vector info) {
        String nameDot = "";

        if (name != null && name.length() > 0)
            nameDot = name + ".";
        CMS.getGeneralNameConfigExtendedPluginInfo(nameDot + PROP_BASE, true, info);
        info.addElement(nameDot + PROP_MIN + ";" + MINMAX_INFO);
        info.addElement(nameDot + PROP_MAX + ";" + MINMAX_INFO);
    }
}