summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/profile/def/SubjectAltNameExtDefault.java
blob: 7da63e71e6c149c9d6224085d7b01829902c129c (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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// --- 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.def;


import java.io.*;
import java.util.*;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.profile.*;
import com.netscape.certsrv.request.*;
import com.netscape.certsrv.property.*;
import com.netscape.certsrv.pattern.*;
import com.netscape.certsrv.apps.*;

import netscape.security.x509.*;
import netscape.security.util.*;
import netscape.security.extensions.*;
import com.netscape.cms.profile.common.*;


/**
 * This class implements an enrollment default policy
 * that populates a subject alternative name extension
 * into the certificate template.
 *
 * @version $Revision$, $Date$
 */
public class SubjectAltNameExtDefault extends EnrollExtDefault {

    public static final String CONFIG_CRITICAL = "subjAltNameExtCritical";
    public static final String CONFIG_NUM_GNS = "subjAltNameNumGNs";
    public static final String CONFIG_GN_ENABLE = "subjAltExtGNEnable_";
    public static final String CONFIG_TYPE = "subjAltExtType_";
    public static final String CONFIG_PATTERN = "subjAltExtPattern_";
    public static final String CONFIG_SOURCE = "subjAltExtSource_";
    public static final String CONFIG_SOURCE_UUID4 = "UUID4";

    public static final String CONFIG_OLD_TYPE = "subjAltExtType";
    public static final String CONFIG_OLD_PATTERN = "subjAltExtPattern";

    public static final String VAL_CRITICAL = "subjAltNameExtCritical";
    public static final String VAL_GENERAL_NAMES = "subjAltNames";

    private static final String GN_ENABLE = "Enable";
    private static final String GN_TYPE = "Pattern Type";
    private static final String GN_PATTERN = "Pattern";

    private static final int DEF_NUM_GN = 1;
    private static final int MAX_NUM_GN = 100;

    public SubjectAltNameExtDefault() {
        super();
    }

    protected int getNumGNs() {
        int num = DEF_NUM_GN;
        String numGNs = getConfig(CONFIG_NUM_GNS);

        if (numGNs != null) {
            try {
                num = Integer.parseInt(numGNs);
            } catch (NumberFormatException e) {
                // ignore
            }
        }

        if (num >= MAX_NUM_GN)
           num = DEF_NUM_GN;
        return num;
    }
 

    public void init(IProfile profile, IConfigStore config)
        throws EProfileException {

        super.init(profile,config);
        refreshConfigAndValueNames();  
        // migrate old parameters to new parameters
        String old_type = null;
        String old_pattern = null;
        IConfigStore paramConfig = config.getSubStore("params");
        try {
          if (paramConfig != null) {
            old_type = paramConfig.getString(CONFIG_OLD_TYPE);
          }
        } catch (EBaseException e) {
          // nothing to do here
        }
        CMS.debug("SubjectAltNameExtDefault: Upgrading old_type=" +
                old_type);
        try {
          if (paramConfig != null) {
            old_pattern = paramConfig.getString(CONFIG_OLD_PATTERN);
          }
        } catch (EBaseException e) {
          // nothing to do here
        }
        CMS.debug("SubjectAltNameExtDefault: Upgrading old_pattern=" +
                old_pattern);
        if (old_type != null && old_pattern != null)  {
           CMS.debug("SubjectAltNameExtDefault: Upgrading");
           try {
             paramConfig.putString(CONFIG_NUM_GNS, "1");
             paramConfig.putString(CONFIG_GN_ENABLE + "0", "true");
             paramConfig.putString(CONFIG_TYPE + "0", old_type);
             paramConfig.putString(CONFIG_PATTERN + "0", old_pattern);
             paramConfig.remove(CONFIG_OLD_TYPE);
             paramConfig.remove(CONFIG_OLD_PATTERN);
             profile.getConfigStore().commit(true);
           } catch (Exception e) {
             CMS.debug("SubjectAltNameExtDefault: Failed to upgrade " + e);
           }
        }
    }

    public void setConfig(String name, String value)
        throws EPropertyException {
        int num = 0;
        if (name.equals(CONFIG_NUM_GNS)) {
          try {
            num = Integer.parseInt(value);

            if (num >= MAX_NUM_GN || num < 0) {
                throw new EPropertyException(CMS.getUserMessage(
                            "CMS_INVALID_PROPERTY", CONFIG_NUM_GNS));
            }

          } catch (Exception e) {
                throw new EPropertyException(CMS.getUserMessage(
                            "CMS_INVALID_PROPERTY", CONFIG_NUM_GNS));
          }
        }
        super.setConfig(name, value);
    }

    public Enumeration getConfigNames() {
        refreshConfigAndValueNames();
        return super.getConfigNames();
    }

    protected void refreshConfigAndValueNames() {
        super.refreshConfigAndValueNames();

        addValueName(VAL_CRITICAL);
        addValueName(VAL_GENERAL_NAMES);

        addConfigName(CONFIG_CRITICAL);
        int num = getNumGNs();
        addConfigName(CONFIG_NUM_GNS);
        for (int i = 0; i < num; i++) {
        addConfigName(CONFIG_TYPE + i);
        addConfigName(CONFIG_PATTERN + i);
        addConfigName(CONFIG_GN_ENABLE + i);
        }
    }
    
    public IDescriptor getConfigDescriptor(Locale locale, String name) { 
        if (name.equals(CONFIG_CRITICAL)) {
            return new Descriptor(IDescriptor.BOOLEAN, null, 
                    "false",
                    CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
        } else if (name.startsWith(CONFIG_TYPE)) {
            return new Descriptor(IDescriptor.CHOICE, "RFC822Name,DNSName,DirectoryName,EDIPartyName,URIName,IPAddress,OIDName,OtherName",
                    "RFC822Name",
                    CMS.getUserMessage(locale, 
                        "CMS_PROFILE_SUBJECT_ALT_NAME_TYPE"));
        } else if (name.startsWith(CONFIG_PATTERN)) {
            return new Descriptor(IDescriptor.STRING, null, 
                    null,
                    CMS.getUserMessage(locale, 
                        "CMS_PROFILE_SUBJECT_ALT_NAME_PATTERN"));
        } else if (name.startsWith(CONFIG_GN_ENABLE)) {
            return new Descriptor(IDescriptor.BOOLEAN, null, 
                    "false",
                    CMS.getUserMessage(locale, "CMS_PROFILE_GN_ENABLE"));
        } else if (name.startsWith(CONFIG_NUM_GNS)) {
            return new Descriptor(IDescriptor.INTEGER, null,
                    "1",
                    CMS.getUserMessage(locale, "CMS_PROFILE_NUM_GNS"));
        }

        return null;
    }

    public IDescriptor getValueDescriptor(Locale locale, String name) {
        if (name.equals(VAL_CRITICAL)) {
            return new Descriptor(IDescriptor.BOOLEAN, null, 
                    "false",
                    CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
        } else if (name.equals(VAL_GENERAL_NAMES)) {
            return new Descriptor(IDescriptor.STRING_LIST, null, 
                    null,
                    CMS.getUserMessage(locale, "CMS_PROFILE_GENERAL_NAMES"));
        } else {
            return null;
        }
    }

    public void setValue(String name, Locale locale,
        X509CertInfo info, String value)
        throws EPropertyException {
        try {
            SubjectAlternativeNameExtension ext = null;

            if (name == null) { 
                throw new EPropertyException(CMS.getUserMessage( 
                            locale, "CMS_INVALID_PROPERTY", name));
            }

            ext =
                        (SubjectAlternativeNameExtension)
                        getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);

            if(ext == null)  {
                populate(null,info);
            } 

            if (name.equals(VAL_CRITICAL)) {
                ext = 
                        (SubjectAlternativeNameExtension)
                        getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);

                if (ext == null) {
                    // it is ok, the extension is never populated or delted
                    return;
                }
                boolean critical = Boolean.valueOf(value).booleanValue();

                ext.setCritical(critical);
            } else if (name.equals(VAL_GENERAL_NAMES)) {
                ext = 
                        (SubjectAlternativeNameExtension)
                        getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);

                if (ext == null) {
                    // it is ok, the extension is never populated or delted
                    return;
                }
                if (value.equals("")) {
                    // if value is empty, do not add this extension
                    deleteExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
                    return;
                }
                GeneralNames gn = new GeneralNames();
                StringTokenizer st = new StringTokenizer(value, "\r\n");

                while (st.hasMoreTokens()) {
                    String gname = (String) st.nextToken();
                    CMS.debug("SubjectAltNameExtDefault: setValue GN:" + gname);

                    if (!isGeneralNameValid(gname)) {
                        continue;
                    }
                    GeneralNameInterface n = parseGeneralName(gname);
                    if (n != null) {
                      gn.addElement(n);
                    }
                }
                if (gn.size() == 0) {
                   CMS.debug("GN size is zero");
                   deleteExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
                    return;
                } else {
                   CMS.debug("GN size is non zero (" + gn.size() + ")");
                  ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
                }
            } else {
                throw new EPropertyException(CMS.getUserMessage( 
                            locale, "CMS_INVALID_PROPERTY", name));
            }
            replaceExtension(
                PKIXExtensions.SubjectAlternativeName_Id.toString(),
                ext, info);
        } catch (IOException e) {
            CMS.debug("SubjectAltNameExtDefault: setValue " + e.toString());
            throw new EPropertyException(CMS.getUserMessage( 
                        locale, "CMS_INVALID_PROPERTY", name));
        } catch (EProfileException e) {
            CMS.debug("SubjectAltNameExtDefault: setValue " + e.toString());
            throw new EPropertyException(CMS.getUserMessage( 
                        locale, "CMS_INVALID_PROPERTY", name));
        }
    }

    public String getValue(String name, Locale locale,
        X509CertInfo info)
        throws EPropertyException {
        try {
            if (name == null) {
                throw new EPropertyException(CMS.getUserMessage( 
                            locale, "CMS_INVALID_PROPERTY", name));
            }

            SubjectAlternativeNameExtension ext =
                    (SubjectAlternativeNameExtension)
                    getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);

            if(ext == null)
            {
                try {
                    populate(null,info);

                } catch (EProfileException e) {
                     throw new EPropertyException(CMS.getUserMessage(
                          locale, "CMS_INVALID_PROPERTY", name));
                }

            }

            if (name.equals(VAL_CRITICAL)) {
                ext = 
                    (SubjectAlternativeNameExtension)
                    getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);

                if (ext == null) {
                    return null;
                }
                if (ext.isCritical()) {
                    return "true";
                } else {
                    return "false";
                }
            } else if (name.equals(VAL_GENERAL_NAMES)) {
                ext = 
                    (SubjectAlternativeNameExtension)
                    getExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), info);
                if (ext == null) {
                    return null;
                }

                GeneralNames names = (GeneralNames)
                    ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                StringBuffer sb = new StringBuffer();
                Enumeration e = names.elements();

                while (e.hasMoreElements()) {
                    Object o = (Object) e.nextElement();
                    if (!(o instanceof GeneralName))
                            continue;
                    GeneralName gn = (GeneralName) o;

                    if (!sb.toString().equals("")) {
                        sb.append("\r\n");
                    }
                    sb.append(toGeneralNameString(gn));
                    CMS.debug("SubjectAltNameExtDefault: getValue append GN:" + toGeneralNameString(gn));
                }
                return sb.toString();
            } else {
                throw new EPropertyException(CMS.getUserMessage( 
                            locale, "CMS_INVALID_PROPERTY", name));
            }
        } catch (IOException e) {
            CMS.debug("SubjectAltNameExtDefault: getValue " + 
                e.toString());
        }
        return null;
    }

    /*
     * returns text that goes into description for this extension on
     * a profile
     */
    public String getText(Locale locale) {
        StringBuffer sb = new StringBuffer();
        String numGNs = getConfig(CONFIG_NUM_GNS);
        int num = getNumGNs();

        for (int i= 0; i< num; i++) {
            sb.append("Record #");
            sb.append(i);
            sb.append("{");
            sb.append(GN_PATTERN + ":");
            sb.append(getConfig(CONFIG_PATTERN + i));
            sb.append(",");
            sb.append(GN_TYPE +":");
            sb.append(getConfig(CONFIG_TYPE +i));
            sb.append(",");
            sb.append(GN_ENABLE + ":");
            sb.append(getConfig(CONFIG_GN_ENABLE + i));
            sb.append("}");
        };

        return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_SUBJECT_ALT_NAME_EXT", getConfig(CONFIG_CRITICAL), sb.toString());
    }

    /**
     * Populates the request with this policy default.
     */
    public void populate(IRequest request, X509CertInfo info)
        throws EProfileException {
        SubjectAlternativeNameExtension ext = null;

        try {
            /* read from config file*/
            ext = createExtension(request);

        } catch (IOException e) {
            CMS.debug("SubjectAltNameExtDefault: populate " + e.toString());
        }
        if (ext != null) {
        addExtension(PKIXExtensions.SubjectAlternativeName_Id.toString(), 
            ext, info);
        } else {
            CMS.debug("SubjectAltNameExtDefault: populate sees no extension.  get out");
        }
    }

    public SubjectAlternativeNameExtension createExtension(IRequest request)
        throws IOException {
        SubjectAlternativeNameExtension ext = null;
        int num = getNumGNs();

        boolean critical = Boolean.valueOf(
                getConfig(CONFIG_CRITICAL)).booleanValue();

        GeneralNames gn = new GeneralNames();
        int count = 0; // # of actual gnames
        for (int i=0; i< num; i++) {
        String enable = getConfig(CONFIG_GN_ENABLE +i);
            if (enable != null && enable.equals("true")) {
                CMS.debug("SubjectAltNameExtDefault: createExtension i=" +i);
                
                String pattern = getConfig(CONFIG_PATTERN + i);
                if (pattern == null || pattern.equals("")) {
                    pattern = " ";
                }

                if (!pattern.equals("")) {
                    String gname = "";

                    // cfu - see if this is server-generated (e.g. UUID4)
                    // to use this feature, use $server.source$ in pattern
                    String source = getConfig(CONFIG_SOURCE +i); 
                    String type = getConfig(CONFIG_TYPE + i);
                    if ((source != null) && (!source.equals(""))) {
                        if (type.equalsIgnoreCase("OtherName")) {
                            CMS.debug("SubjectAlternativeNameExtension: using "+
                               source+ " as gn");
                            if (source.equals(CONFIG_SOURCE_UUID4)) {
                              UUID randUUID = UUID.randomUUID();
                              // call the mapPattern that does server-side gen
                              // request is not used, but needed for the substitute
                              // function
                              gname = mapPattern(randUUID.toString(), request, pattern);
                            } else { //expand more server-gen types here
                              CMS.debug("SubjectAltNameExtDefault: createExtension - unsupported server-generated type: "+source+". Supported: UUID4");
                              continue;
                            }
                        } else {
                              CMS.debug("SubjectAltNameExtDefault: createExtension - source is only supported for subjAltExtType OtherName");
                              continue;
                        }
                    } else {
                        if (request != null)  {
                            gname = mapPattern(request, pattern);
                        }
                    }

                    if (gname.equals("")) {
                        CMS.debug("gname is empty, not added");
                        continue;
                    }
                    CMS.debug("SubjectAltNameExtDefault: createExtension got gname=" +gname);

                    GeneralNameInterface n = parseGeneralName(type + ":" + gname);

                    CMS.debug("adding gname: "+gname);
                    if (n != null) {
                        CMS.debug("SubjectAlternativeNameExtension: n not null");
                        gn.addElement(n);
                        count++;
                    } else {
                        CMS.debug("SubjectAlternativeNameExtension: n null");
                    }
                }
           }
        } //for

        if (count != 0) {
          try {
            ext = new SubjectAlternativeNameExtension();
          } catch (Exception e) {
            CMS.debug(e.toString());
            throw new IOException( e.toString() );
          }
          ext.set(SubjectAlternativeNameExtension.SUBJECT_NAME, gn);
          ext.setCritical(critical);
        } else {
          CMS.debug("count is 0");
        } 
        return ext;
    }

    public String mapPattern(IRequest request, String pattern) 
        throws IOException {
        Pattern p = new Pattern(pattern);
        IAttrSet attrSet = null;
        if (request != null) {
            attrSet = request.asIAttrSet();
        }
        return p.substitute("request", attrSet);
    }

    // for server-side generated values
    public String mapPattern(String val, IRequest request, String pattern) 
        throws IOException {
        Pattern p = new Pattern(pattern);
        IAttrSet attrSet = null;
        if (request != null) {
            attrSet = request.asIAttrSet();
        }
        try {
            attrSet.set("source", val);
        } catch (Exception e) {
            CMS.debug("SubjectAlternativeNameExtension: mapPattern source "+e.toString());
        }

        return p.substitute("server", attrSet);
    }
}