summaryrefslogtreecommitdiffstats
path: root/base/util/src/netscape/security/extensions/GenericASN1Extension.java
blob: 43b2e0b2b8352638627f95420827c2ae1affc684 (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
// --- 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 netscape.security.extensions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.security.cert.CertificateException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

import netscape.security.util.BigInt;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.CertAttrSet;
import netscape.security.x509.Extension;
import netscape.security.x509.OIDMap;

/**
 * Represent the AsnInteger Extension.
 */
public class GenericASN1Extension extends Extension
        implements CertAttrSet {
    /**
     *
     */
    private static final long serialVersionUID = 8047548816784949009L;

    protected static final int MAX_ATTR = 10;

    protected static final String PROP_CRITICAL =
              "critical";
    protected static final String PROP_NAME =
              "name";
    protected static final String PROP_OID =
              "oid";
    protected static final String PROP_PATTERN =
              "pattern";
    protected static final String PROP_ATTRIBUTE =
              "attribute";
    protected static final String PROP_TYPE =
              "type";
    protected static final String PROP_SOURCE =
              "source";
    protected static final String PROP_VALUE =
              "value";
    protected static final String PROP_PREDICATE =
              "predicate";
    /**
     * Identifier for this attribute, to be used with the
     * get, set, delete methods of Certificate, x509 type.
     */
    private String name;
    public String OID = null;
    public static Hashtable<String, String> mConfig = null;
    public String pattern = null;
    private int index = 0;

    // Encode this value
    private void encodeThis()
            throws IOException, ParseException {
        this.extensionValue = encodePattern();
    }

    // Encode pattern
    private byte[] encodePattern()
            throws IOException, ParseException {
        DerOutputStream os = new DerOutputStream();
        DerOutputStream tmp = new DerOutputStream();
        String type = null;
        String value = null;
        String source = null;
        while (index < pattern.length()) {
            char ch = pattern.charAt(index);
            switch (ch) {
            case '{':
                index++;
                byte[] buff = encodePattern();
                tmp.putDerValue(new DerValue(buff));
                break;
            case '}':
                os.write(DerValue.tag_Sequence, tmp);
                return os.toByteArray();
            default:
                type = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_TYPE);
                if (type.equalsIgnoreCase("integer")) {
                    int num = Integer.parseInt(mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE));
                    PutInteger(tmp, num);
                } else if (type.equalsIgnoreCase("ia5string")) {
                    source = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    if (source.equalsIgnoreCase("file"))
                        PutIA5String(tmp, getFromFile(value));
                    else
                        PutIA5String(tmp, value);
                } else if (type.equalsIgnoreCase("octetstring")) {
                    source = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    // It should be colon seperated ASCII Hexdecimal String
                    if (source.equalsIgnoreCase("file"))
                        PutOctetString(tmp, getFromFile(value));
                    else
                        PutOctetString(tmp, value);
                } else if (type.equalsIgnoreCase("bmpstring")) {
                    source = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    if (source.equalsIgnoreCase("file"))
                        PutBMPString(tmp, getFromFile(value));
                    else
                        PutBMPString(tmp, value);
                } else if (type.equalsIgnoreCase("printablestring")) {
                    source = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    if (source.equalsIgnoreCase("file"))
                        PutPrintableString(tmp, getFromFile(value));
                    else
                        PutPrintableString(tmp, value);
                } else if (type.equalsIgnoreCase("visiblestring")) {
                    source = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_SOURCE);
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    if (source.equalsIgnoreCase("file"))
                        PutVisibleString(tmp, getFromFile(value));
                    else
                        PutVisibleString(tmp, value);
                } else if (type.equalsIgnoreCase("utctime")) {
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    PutUTCtime(tmp, value);
                } else if (type.equalsIgnoreCase("oid")) {
                    value = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    PutOID(tmp, value);
                } else if (type.equalsIgnoreCase("boolean")) {
                    boolean bool = false;
                    String b = mConfig.get(PROP_ATTRIBUTE + "." + ch + "." + PROP_VALUE);
                    if (b.equalsIgnoreCase("true"))
                        bool = true;
                    else
                        bool = false;
                    PutBoolean(tmp, bool);
                } else if (type.equalsIgnoreCase("null")) {
                    tmp.putNull();
                } else {
                    throw new ParseException("Unknown Attribute Type", 0);
                }
            }
            index++;
        }

        return tmp.toByteArray();
    }

    /**
     * Create a GenericASN1Extension with the value and oid.
     * The criticality is set to false.
     *
     * @param the values to be set for the extension.
     */
    public GenericASN1Extension(String name, String oid, String pattern, boolean critical,
            Hashtable<String, String> config)
            throws IOException, ParseException {
        ObjectIdentifier tmpid = new ObjectIdentifier(oid);
        this.name = name;
        OID = oid;
        mConfig = config;
        this.pattern = pattern;

        try {
            if (OIDMap.getName(tmpid) == null)
                OIDMap.addAttribute("netscape.security.x509.GenericASN1Extension", oid, name);
        } catch (CertificateException e) {
        }

        this.extensionId = tmpid;
        this.critical = critical;
        encodeThis();
    }

    /**
     * Create a GenericASN1Extension with the value and oid.
     * The criticality is set to false.
     *
     * @param the values to be set for the extension.
     */
    public GenericASN1Extension(Hashtable<String, String> config)
            throws IOException, ParseException {
        mConfig = config;
        ObjectIdentifier tmpid = new ObjectIdentifier(mConfig.get(PROP_OID));
        name = mConfig.get(PROP_NAME);
        OID = mConfig.get(PROP_OID);
        pattern = mConfig.get(PROP_PATTERN);

        try {
            if (OIDMap.getName(tmpid) == null)
                OIDMap.addAttribute("GenericASN1Extension", OID, name);
        } catch (CertificateException e) {
        }

        this.extensionId = tmpid;
        this.critical = false;
        String b = mConfig.get(PROP_CRITICAL);
        if (b.equalsIgnoreCase("true"))
            this.critical = true;
        else
            this.critical = false;
        encodeThis();
    }

    /**
     * Create the extension from the passed DER encoded value of the same.
     *
     * @param critical true if the extension is to be treated as critical.
     * @param value Array of DER encoded bytes of the actual value.
     * @exception IOException on error.
     */
    public GenericASN1Extension(Boolean critical, Object value)
            throws IOException {
        this.extensionId = new ObjectIdentifier(OID);
        this.critical = critical.booleanValue();

        int len = Array.getLength(value);
        byte[] extValue = new byte[len];
        for (int i = 0; i < len; i++) {
            extValue[i] = Array.getByte(value, i);
        }
        this.extensionValue = extValue;
    }

    /**
     * Set the attribute value.
     */
    public void set(String name, Object obj) throws IOException {
        throw new IOException("Method not to be called directly.");
    }

    /**
     * Get the attribute value.
     */
    public Object get(String name) throws IOException {
        return null;
    }

    /**
     * Delete the attribute value.
     */
    public void delete(String name) throws IOException {
        throw new IOException("Method not to be called directly.");
    }

    /**
     * Returns a printable representation of the GenericASN1Extension.
     */
    @Override
    public String toString() {
        return (null);
    }

    /**
     * Decode the extension from the InputStream.
     *
     * @param in the InputStream to unmarshal the contents from.
     * @exception IOException on decoding or validity errors.
     */
    public void decode(InputStream in) throws IOException {
        throw new IOException("Method not to be called directly.");
    }

    /**
     * Write the extension to the DerOutputStream.
     *
     * @param out the DerOutputStream to write the extension to.
     * @exception IOException on encoding errors.
     */
    public void encode(OutputStream out)
            throws IOException {
        DerOutputStream tmp = new DerOutputStream();

        try {
            if (this.extensionValue == null) {
                this.extensionId = new ObjectIdentifier(OID);
                this.critical = true;
                encodeThis();
            }
        } catch (ParseException e) {
        }

        super.encode(tmp);
        out.write(tmp.toByteArray());
    }

    /**
     * Return the name of this attribute.
     */
    public String getName() {
        return name;
    }

    /**
     * Set the name of this attribute.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Return the OID of this attribute.
     */
    public String getOID() {
        return OID;
    }

    /**
     * Set the OID of this attribute.
     */
    public void setOID(String oid) {
        OID = oid;
    }

    /**
     * Return an enumeration of names of attributes existing within this
     * attribute.
     */
    public Enumeration<String> getAttributeNames() {
        Vector<String> elements = new Vector<String>();
        elements.addElement("octet");

        return (elements.elements());
    }

    private void PutInteger(DerOutputStream os, int number)
            throws IOException, ParseException {
        os.putInteger(new BigInt(number));
        return;
    }

    private void PutIA5String(DerOutputStream os, String value)
            throws IOException, ParseException {
        os.putIA5String(value);
        return;
    }

    private void PutOctetString(DerOutputStream os, String value)
            throws IOException, ParseException {
        StringTokenizer token = new StringTokenizer(value, ":");
        byte[] octets = new byte[token.countTokens()];
        for (int i = 0; token.hasMoreElements(); i++) {
            String num = (String) token.nextElement();
            octets[i] = (byte) Integer.parseInt(num, 16);
        }

        os.putOctetString(octets);
        return;
    }

    private void PutBMPString(DerOutputStream os, String value)
            throws IOException, ParseException {
        os.putBMPString(value);
        return;
    }

    private void PutPrintableString(DerOutputStream os, String value)
            throws IOException, ParseException {
        os.putPrintableString(value);
        return;
    }

    private void PutVisibleString(DerOutputStream os, String value)
            throws IOException, ParseException {
        os.putVisibleString(value);
        return;
    }

    private void PutUTCtime(DerOutputStream os, String value)
            throws IOException, ParseException {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        os.putUTCTime(df.parse(value));
        return;
    }

    private void PutOID(DerOutputStream os, String value)
            throws IOException, ParseException {
        os.putOID(new ObjectIdentifier(value));
        return;
    }

    private void PutBoolean(DerOutputStream os, boolean value)
            throws IOException, ParseException {
        os.putBoolean(value);
        return;
    }

    private String getFromFile(String fname) throws IOException {
        String s = null;
        byte[] buff = null;
        int i = 0;
        int j = 0;
        if ((fname == null) || (fname.equals(""))) {
            throw new IOException("File name is not provided.");
        }

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fname);
            int n = 0;
            while ((n = fis.available()) > 0) {
                buff = new byte[n];
                int result = fis.read(buff);
                if (result == -1)
                    break;
                s = new String(buff);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        if (s == null) {
            return "";
        }
        for (i = 0, j = 0; j < s.length(); j++) {
            int ch = s.charAt(j);
            if (ch == 10 || ch == 13 || ch == 9)
                continue;
            i++;
        }
        buff = new byte[i];
        for (i = 0, j = 0; j < s.length(); j++) {
            int ch = s.charAt(j);
            if (ch == 10 || ch == 13 || ch == 9)
                continue;
            buff[i++] = (byte) ch;
        }
        s = new String(buff);

        return s;
    }

}