summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/policy/extensions/SubjectDirectoryAttributesExt.java
blob: b4ebb4b4530032c54a7f339041c78587ccba5d89 (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
// --- 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.io.IOException;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;

import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.AVAValueConverter;
import netscape.security.x509.Attribute;
import netscape.security.x509.CertificateExtensions;
import netscape.security.x509.CertificateVersion;
import netscape.security.x509.SubjectDirAttributesExtension;
import netscape.security.x509.X500NameAttrMap;
import netscape.security.x509.X509CertInfo;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.policy.IEnrollmentPolicy;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.cms.policy.APolicyRule;

/**
 * Policy to add the subject directory attributes extension.
 * <P>
 * 
 * <PRE>
 * NOTE:  The Policy Framework has been replaced by the Profile Framework.
 * </PRE>
 * <P>
 * 
 * @deprecated
 * @version $Revision$, $Date$
 */
public class SubjectDirectoryAttributesExt extends APolicyRule
        implements IEnrollmentPolicy, IExtendedPluginInfo {
    protected static final String PROP_CRITICAL = "critical";
    protected static final String PROP_ATTRIBUTE = "attribute";
    protected static final String PROP_NUM_ATTRIBUTES = "numAttributes";

    protected static final boolean DEF_CRITICAL = false;
    protected static final int DEF_NUM_ATTRIBUTES = 3;
    protected static final int MAX_NUM_ATTRIBUTES = 10;

    protected boolean mCritical;
    protected int mNumAttributes;
    protected AttributeConfig[] mAttributes = null;

    protected IConfigStore mConfig;
    protected SubjectDirAttributesExtension mExt = null;

    protected Vector<String> mParams = new Vector<String>();
    private String[] mEPI = null; // extended plugin info
    protected static Vector<String> mDefParams = new Vector<String>();

    static {
        setDefaultParams();
    }

    public SubjectDirectoryAttributesExt() {
        NAME = "SubjectDirectoryAttributesExtPolicy";
        DESC = "Sets Subject Directory Attributes Extension in certificates.";
        setExtendedPluginInfo();
    }

    public void init(ISubsystem owner, IConfigStore config)
            throws EBaseException {
        boolean enabled = config.getBoolean("enabled", false);

        mConfig = config;

        mCritical = mConfig.getBoolean(PROP_CRITICAL, false);
        mNumAttributes = mConfig.getInteger(PROP_NUM_ATTRIBUTES, DEF_NUM_ATTRIBUTES);
        if (mNumAttributes < 1) {
            EBaseException ex = new EBaseException(
                    CMS.getUserMessage("CMS_BASE_MUST_BE_POSITIVE_NUMBER", PROP_NUM_ATTRIBUTES));

            log(ILogger.LL_FAILURE, NAME + " Error: " + ex.toString());
            throw ex;
        }
        mAttributes = new AttributeConfig[mNumAttributes];
        for (int i = 0; i < mNumAttributes; i++) {
            String name = PROP_ATTRIBUTE + i;
            IConfigStore c = mConfig.getSubStore(name);

            mAttributes[i] = new AttributeConfig(name, c, enabled);
        }
        if (enabled) {
            try {
                mExt = formExt(null);
            } catch (IOException e) {
                log(ILogger.LL_FAILURE, NAME + " Error: " + e.getMessage());
                throw new EBaseException(CMS.getUserMessage("CMS_BASE_INTERNAL_ERROR",
                            "Error forming Subject Directory Attributes Extension. " +
                                    "See log file for details."));
            }
        }
        setInstanceParams();
    }

    public PolicyResult apply(IRequest req) {
        PolicyResult res = PolicyResult.ACCEPTED;
        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; // unrecoverable error.
        }

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

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

    public PolicyResult applyCert(IRequest req, X509CertInfo certInfo) {
        CertificateExtensions extensions = null;

        try {
            // get extension and remove if exists.
            extensions = (CertificateExtensions)
                    certInfo.get(X509CertInfo.EXTENSIONS);
            if (extensions == null) {
                extensions = new CertificateExtensions();
                certInfo.set(X509CertInfo.VERSION,
                        new CertificateVersion(CertificateVersion.V3));
                certInfo.set(X509CertInfo.EXTENSIONS, extensions);
            } else {
                try {
                    extensions.delete(SubjectDirAttributesExtension.NAME);
                } catch (IOException ee) {
                    // if name is not found, try deleting the extension using the OID
                    try {
                        extensions.delete("2.5.29.9");
                    } catch (IOException eee) {
                    }
                }
            }

            // form extension and set.
            if (mExt != null) {
                extensions.set(SubjectDirAttributesExtension.NAME, mExt);
            } else {
                SubjectDirAttributesExtension ext = formExt(req);

                if (ext != null)
                    extensions.set(SubjectDirAttributesExtension.NAME, formExt(req));
            }
            return PolicyResult.ACCEPTED;
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERT_INFO_ERROR", e.getMessage()));

            setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
                    NAME, "Certificate Info Error");
            return PolicyResult.REJECTED; // unrecoverable error.
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("BASE_IO_ERROR", e.getMessage()));
            setError(req, CMS.getUserMessage("CMS_POLICY_UNEXPECTED_POLICY_ERROR"),
                    NAME, "IOException Error");
            return PolicyResult.REJECTED;
        }
    }

    public Vector<String> getInstanceParams() {
        return mParams; // inited in init()
    }

    public Vector<String> getDefaultParams() {
        return mDefParams;
    }

    public String[] getExtendedPluginInfo(Locale locale) {
        return mEPI; // inited in the constructor.
    }

    private void setInstanceParams() {
        mParams.addElement(PROP_CRITICAL + "=" + mCritical);
        mParams.addElement(PROP_NUM_ATTRIBUTES + "=" + mNumAttributes);
        for (int i = 0; i < mNumAttributes; i++) {
            mAttributes[i].getInstanceParams(mParams);
        }
        // clean up others if exists. expensive.
        for (int j = mNumAttributes; j < MAX_NUM_ATTRIBUTES; j++) {
            mConfig.removeSubStore(PROP_ATTRIBUTE + j);
        }
    }

    private static void setDefaultParams() {
        mDefParams.addElement(PROP_CRITICAL + "=" + DEF_CRITICAL);
        mDefParams.addElement(PROP_NUM_ATTRIBUTES + "=" + DEF_NUM_ATTRIBUTES);
        for (int i = 0; i < DEF_NUM_ATTRIBUTES; i++) {
            AttributeConfig.getDefaultParams(PROP_ATTRIBUTE + i, mDefParams);
        }
    }

    private void setExtendedPluginInfo() {
        Vector<String> v = new Vector<String>();

        v.addElement(PROP_CRITICAL + ";boolean;" +
                "RFC 2459 recommendation: MUST be non-critical.");
        v.addElement(PROP_NUM_ATTRIBUTES + ";number;" +
                "Number of Attributes in the extension.");

        for (int i = 0; i < MAX_NUM_ATTRIBUTES; i++) {
            AttributeConfig.getExtendedPluginInfo(PROP_ATTRIBUTE + i, v);
        }

        v.addElement(IExtendedPluginInfo.HELP_TOKEN +
                ";configuration-policyrules-subjectdirectoryattributes");
        v.addElement(IExtendedPluginInfo.HELP_TEXT
                +
                ";Adds Subject Directory Attributes extension. See RFC 2459 (4.2.1.9). It's not recommended as an essential part of the profile, but may be used in local environments.");

        mEPI = com.netscape.cmsutil.util.Utils.getStringArrayFromVector(v);
    }

    private SubjectDirAttributesExtension formExt(IRequest req)
            throws IOException {
        Vector<Attribute> attrs = new Vector<Attribute>();

        // if we're called from init and one attribute is from request attribute
        // the ext can't be formed yet.
        if (req == null) {
            for (int i = 0; i < mNumAttributes; i++) {
                if (mAttributes[i].mWhereToGetValue == AttributeConfig.USE_REQUEST_ATTR)
                    return null;
            }
        }
        // either we're called from apply or all values are fixed.
        for (int i = 0; i < mNumAttributes; i++) {
            if (mAttributes[i].mAttribute != null) {
                attrs.addElement(mAttributes[i].mAttribute);
            } else {
                // skip attribute if request attribute doesn't exist.
                Attribute a = mAttributes[i].formAttr(req);

                if (a == null)
                    continue;
                attrs.addElement(a);
            }
        }
        if (attrs.size() == 0)
            return null;
        Attribute[] attrList = new Attribute[attrs.size()];

        attrs.copyInto(attrList);
        SubjectDirAttributesExtension ext =
                new SubjectDirAttributesExtension(attrList);

        return ext;
    }
}

class AttributeConfig {

    protected static final String PROP_ATTRIBUTE_NAME = "attributeName";
    protected static final String PROP_WTG_VALUE = "whereToGetValue";
    protected static final String PROP_VALUE = "value";

    protected static final String USE_REQUEST_ATTR = "Request Attribute";
    protected static final String USE_FIXED = "Fixed Value";

    protected String mAttributeName = null;
    protected String mWhereToGetValue = null;
    protected String mValue = null;

    protected String mPrefix = null;
    protected String mReqAttr = null;
    protected ObjectIdentifier mAttributeOID = null;

    protected String mName = null;
    protected IConfigStore mConfig = null;
    protected Attribute mAttribute = null;

    protected static final String ATTRIBUTE_NAME_INFO = "Attribute name.";
    protected static final String WTG_VALUE_INFO =
            PROP_WTG_VALUE + ";choice(" + USE_REQUEST_ATTR + "," + USE_FIXED + ");" +
                    "Get value from a request attribute or use a fixed value specified below.";
    protected static final String VALUE_INFO =
            PROP_VALUE + ";string;" +
                    "Request attribute name or a fixed value to put into the extension.";

    public AttributeConfig(String name, IConfigStore config, boolean enabled)
            throws EBaseException {
        X500NameAttrMap map = X500NameAttrMap.getDefault();

        mName = name;
        mConfig = config;
        if (enabled) {
            mAttributeName = mConfig.getString(PROP_ATTRIBUTE_NAME);
            mWhereToGetValue = mConfig.getString(PROP_WTG_VALUE);
            mValue = mConfig.getString(PROP_VALUE);
        } else {
            mAttributeName = mConfig.getString(PROP_ATTRIBUTE_NAME, "");
            mWhereToGetValue = mConfig.getString(PROP_WTG_VALUE, USE_REQUEST_ATTR);
            mValue = mConfig.getString(PROP_VALUE, "");
        }

        if (mAttributeName.length() > 0) {
            mAttributeOID = map.getOid(mAttributeName);
            if (mAttributeOID == null)
                throw new EBaseException(
                        CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", mAttributeName));
        }

        if (mWhereToGetValue.equalsIgnoreCase(USE_REQUEST_ATTR)) {
            mWhereToGetValue = USE_REQUEST_ATTR;
            if (enabled && mValue.length() == 0) {
                throw new EBaseException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED", PROP_VALUE));
            }
            int dot = mValue.indexOf('.');

            if (dot != -1) {
                mPrefix = mValue.substring(0, dot);
                mReqAttr = mValue.substring(dot + 1);
                if (mPrefix == null || mPrefix.length() == 0 ||
                        mReqAttr == null || mReqAttr.length() == 0) {
                    throw new EBaseException(
                            CMS.getUserMessage("CMS_BASE_INVALID_ATTRIBUTE", mValue));
                }
            } else {
                mPrefix = null;
                mReqAttr = mValue;
            }
        } else if (mWhereToGetValue.equalsIgnoreCase(USE_FIXED)) {
            mWhereToGetValue = USE_FIXED;
            if (mAttributeOID != null) {
                try {
                    checkValue(mAttributeOID, mValue);
                    mAttribute = new Attribute(mAttributeOID, mValue);
                } catch (Exception e) {
                    throw new EBaseException(
                            CMS.getUserMessage("CMS_BASE_INVALID_ATTR_VALUE",
                                    mAttributeName, e.getMessage()));
                }
            }
        } else if (enabled || mWhereToGetValue.length() > 0) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_VALUE_FOR_TYPE", PROP_WTG_VALUE,
                        "Must be either '" + USE_REQUEST_ATTR + "' or '" + USE_FIXED + "'."));
        }
    }

    public static void getDefaultParams(String name, Vector<String> v) {
        String nameDot = name + ".";

        v.addElement(nameDot + PROP_ATTRIBUTE_NAME + "=");
        v.addElement(nameDot + PROP_WTG_VALUE + "=" + USE_REQUEST_ATTR);
        v.addElement(nameDot + PROP_VALUE + "=");
    }

    public static void getExtendedPluginInfo(String name, Vector<String> v) {
        String nameDot = name + ".";
        String attrChoices = getAllNames();

        v.addElement(nameDot + PROP_ATTRIBUTE_NAME + ";choice(" + attrChoices + ");" +
                ATTRIBUTE_NAME_INFO);
        v.addElement(nameDot + WTG_VALUE_INFO);
        v.addElement(nameDot + VALUE_INFO);
    }

    public void getInstanceParams(Vector<String> v) {
        String nameDot = mName + ".";

        v.addElement(nameDot + PROP_ATTRIBUTE_NAME + "=" + mAttributeName);
        v.addElement(nameDot + PROP_WTG_VALUE + "=" + mWhereToGetValue);
        v.addElement(nameDot + PROP_VALUE + "=" + mValue);
    }

    public Attribute formAttr(IRequest req)
            throws IOException {
        String val = req.getExtDataInString(mPrefix, mReqAttr);

        if (val == null || val.length() == 0) {
            return null;
        }
        checkValue(mAttributeOID, val);
        return new Attribute(mAttributeOID, val);
    }

    static private String getAllNames() {
        Enumeration<String> n = X500NameAttrMap.getDefault().getAllNames();
        StringBuffer sb = new StringBuffer();
        sb.append(n.nextElement());

        while (n.hasMoreElements()) {
            sb.append(",");
            sb.append(n.nextElement());
        }
        return sb.toString();
    }

    private static void checkValue(ObjectIdentifier oid, String val)
            throws IOException {
        AVAValueConverter c = X500NameAttrMap.getDefault().getValueConverter(oid);

        @SuppressWarnings("unused")
        DerValue derval = c.getValue(val); // check for errors
        return;
    }

}