summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/policy/APolicyRule.java
blob: d0bd6a6bc5cfc1760cfe51ee73dda1c8aa8b5b0f (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
// --- 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;


import java.util.*;
import java.text.*;
import java.io.IOException;
import java.security.InvalidKeyException;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.policy.*;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.PolicyResult;
import com.netscape.certsrv.request.AgentApprovals;
import com.netscape.certsrv.common.*;
import com.netscape.certsrv.logging.*;
import com.netscape.certsrv.apps.*;
import netscape.security.x509.*;
import java.security.*;
import java.security.cert.*;


/**
 * The abstract policy rule that concrete implementations will
 * extend.
 * <P>
 * <PRE>
 * NOTE:  The Policy Framework has been replaced by the Profile Framework.
 * </PRE>
 * <P>
 *
 * @deprecated
 * @version $Revision$, $Date$
 */
public abstract class APolicyRule implements IPolicyRule {
    protected String NAME = null;
    protected String DESC = null;
    protected IExpression mFilterExp = null;
    protected String mInstanceName = null;
    protected ILogger mLogger = CMS.getLogger();

    public APolicyRule() {
    }

    /**
     * Initializes the policy rule.
     * <P>
     *
     * @param config	The config store reference
     */
    public abstract void init(ISubsystem owner, IConfigStore config)
        throws EBaseException;

    /**
     * Gets the description for this policy rule.
     * <P>
     * @return The Description for this rule.
     */
    public String getDescription() {
        return DESC;
    }

    /**
     * Sets a predicate expression for rule matching.
     * <P>
     *
     * @param exp	The predicate expression for the rule.
     */
    public void setPredicate(IExpression exp) {
        mFilterExp = exp;
    }

    /**
     * Returns the predicate expression for the rule.
     * <P>
     *
     * @return The predicate expression for the rule.
     */
    public IExpression getPredicate() {
        return mFilterExp;
    }

    /**
     * Returns the name of the policy rule.
     * <P>
     *
     * @return The name of the policy class.
     */
    public String getName() {
        return NAME;
    }

    /**
     * Sets the instance name for a policy rule. 
     * <P>
     *
     * @param instanceName	The name of the rule instance.
     */
    public void setInstanceName(String instanceName) { 
        mInstanceName = instanceName;
    }

    /**
     * Returns the name of the policy rule instance.
     * <P>
     *
     * @return The name of the policy rule instance if set, else
     *		   the name of the rule class. 
     */
    public String getInstanceName() { 
        return mInstanceName != null ? mInstanceName : NAME;
    }

    /**
     * Applies the policy on the given Request.
     * <P>
     *
     * @param req	The request on which to apply policy.
     * @return The policy result object.
     */
    public abstract PolicyResult apply(IRequest req);

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

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

    public void setError(IRequest req, String format, Object[] params) {
        setPolicyException(req, format, params);
    }

    public void setError(IRequest req, String format, String arg1, 
        String arg2) {
        Object[] np = new Object[2];

        np[0] = arg1;
        np[1] = arg2;
        setPolicyException(req, format, np);
    }

    public void setError(IRequest req, String format, String arg) {
        Object[] np = new Object[1];

        np[0] = arg;
        setPolicyException(req, format, np);
    }

    public void setPolicyException(IRequest req, EBaseException ex) {
        Vector ev = req.getExtDataInStringVector(IRequest.ERRORS);
        if (ev == null) {
            ev = new Vector();
        }
        ev.addElement(ex.toString());
        req.setExtData(IRequest.ERRORS, ev);

    }

    /**
     * determines whether a DEFERRED policy result should be returned
     * by checking the contents of the AgentApprovals attribute.  This
     * call should be used by policy modules instead of returning
     * PolicyResult.DEFERRED directly.
     * <p>
     */
    protected PolicyResult deferred(IRequest req) {
        // Try to find an agent approval
        AgentApprovals aa = AgentApprovals.fromStringVector(
                req.getExtDataInStringVector(AgentApprovals.class.getName()));

        // Any approvals causes success
        if (aa != null && aa.elements().hasMoreElements()) {
            return PolicyResult.ACCEPTED;
        } else {
            return PolicyResult.DEFERRED;
        }
    }

    /**
     * request has previously been approved by an agent
     */
    protected boolean agentApproved(IRequest req) {
        // Try to find an agent approval
        AgentApprovals aa = AgentApprovals.fromStringVector(
                req.getExtDataInStringVector(AgentApprovals.class.getName()));

        // Any approvals causes success
        if (aa != null && aa.elements().hasMoreElements()) {
            return true;
        } else {
            return false;
        }
    }

    public void setPolicyException(IRequest req, String format, 
        Object[] params) {
        if (format == null) 
            return;

        EPolicyException ex; 

        if (params == null)
            ex = new EPolicyException(format);
        else
            ex = new EPolicyException(format, params);

        Vector ev = req.getExtDataInStringVector(IRequest.ERRORS);
        if (ev == null) {
            ev = new Vector();
        }
        ev.addElement(ex.toString());
        req.setExtData(IRequest.ERRORS, ev);
    }

    /**
     * log a message for this policy rule.
     */
    protected void log(int level, String msg) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level, 
            "APolicyRule " + NAME + ": " + msg);
    }

    public static KeyIdentifier createKeyIdentifier(X509Key key) 
        throws NoSuchAlgorithmException, InvalidKeyException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");

        md.update(key.getEncoded());
        return new KeyIdentifier(md.digest());
    }

    /**
     * Form a byte array of octet string key identifier from the sha-1 hash of 
     * the Subject Public Key INFO. (including algorithm ID, etc.)
     * <p>
     * @param certInfo cert info of the certificate.
     * @return A Key identifier with the sha-1 hash of subject public key.
     */
    protected KeyIdentifier formSpkiSHA1KeyId(X509CertInfo certInfo)
        throws EBaseException {
        KeyIdentifier keyId = null;

        try {
            CertificateX509Key certKey =
                (CertificateX509Key) certInfo.get(X509CertInfo.KEY);

            if (certKey == null) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
                throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_MISSING_KEY", NAME));
            }
            X509Key key = (X509Key) certKey.get(CertificateX509Key.KEY);

            if (key == null) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
                throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_MISSING_KEY", NAME));
            }
            keyId = createKeyIdentifier(key);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        } catch (NoSuchAlgorithmException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        } catch (InvalidKeyException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        }
        return keyId;
    }

    /**
     * Form a byte array of octet string key identifier from the sha-1 hash of 
     * the Subject Public Key BIT STRING.
     * <p>
     * @param certInfo cert info of the certificate.
     * @return A Key identifier with the sha-1 hash of subject public key.
     */
    protected KeyIdentifier formSHA1KeyId(X509CertInfo certInfo)
        throws EBaseException {
        KeyIdentifier keyId = null;

        try {
            CertificateX509Key certKey =
                (CertificateX509Key) certInfo.get(X509CertInfo.KEY);

            if (certKey == null) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
                throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_MISSING_KEY", NAME));
            }
            X509Key key = (X509Key) certKey.get(CertificateX509Key.KEY);

            if (key == null) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("POLICY_MISSING_KEY_1", ""));
                throw new EPolicyException(CMS.getUserMessage("CMS_POLICY_MISSING_KEY", NAME));
            }
            byte[] rawKey = key.getKey();

            MessageDigest md = MessageDigest.getInstance("SHA-1");

            md.update(rawKey);
            keyId = new KeyIdentifier(md.digest());
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        } catch (NoSuchAlgorithmException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("POLICY_ERROR_SUBJECT_KEY_ID_1", NAME));
            throw new EPolicyException(
                    CMS.getUserMessage("CMS_POLICY_SUBJECT_KEY_ID_ERROR", NAME));
        }
        return keyId;
    }
}