aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java
blob: 66a587511e81970d8db761556e0ff21bd7ae4f22 (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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Copyright  1999-2004 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.sun.org.apache.xml.internal.security.utils;



import java.io.IOException;
import java.io.StringReader;


/**
 *
 * @author $Author: mullan $
 */
public class RFC2253Parser {


   /** {@link java.util.logging} logging facility */
   /* static java.util.logging.Logger log =
        java.util.logging.Logger.getLogger(RFC2253Parser.class.getName());
   */

   static boolean _TOXML = true;

   /**
    * Method rfc2253toXMLdsig
    *
    * @param dn
    * @return normalized string
    *
    */
   public static String rfc2253toXMLdsig(String dn) {

      _TOXML = true;

      // Transform from RFC1779 to RFC2253
      String normalized = normalize(dn);

      return rfctoXML(normalized);
   }

   /**
    * Method xmldsigtoRFC2253
    *
    * @param dn
    * @return normalized string
    */
   public static String xmldsigtoRFC2253(String dn) {

      _TOXML = false;

      // Transform from RFC1779 to RFC2253
      String normalized = normalize(dn);

      return xmltoRFC(normalized);
   }

   /**
    * Method normalize
    *
    * @param dn
    * @return normalized string
    */
   public static String normalize(String dn) {

      //if empty string
      if ((dn == null) || dn.equals("")) {
         return "";
      }

      try {
         String _DN = semicolonToComma(dn);
         StringBuffer sb = new StringBuffer();
         int i = 0;
         int l = 0;
         int k;

         //for name component
         for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) {
            l += countQuotes(_DN, j, k);

            if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) {
               sb.append(parseRDN(_DN.substring(i, k).trim()) + ",");

               i = k + 1;
               l = 0;
            }
         }

         sb.append(parseRDN(trim(_DN.substring(i))));

         return sb.toString();
      } catch (IOException ex) {
         return dn;
      }
   }

   /**
    * Method parseRDN
    *
    * @param str
    * @return normalized string
    * @throws IOException
    */
   static String parseRDN(String str) throws IOException {

      StringBuffer sb = new StringBuffer();
      int i = 0;
      int l = 0;
      int k;

      for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) {
         l += countQuotes(str, j, k);

         if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
            sb.append(parseATAV(trim(str.substring(i, k))) + "+");

            i = k + 1;
            l = 0;
         }
      }

      sb.append(parseATAV(trim(str.substring(i))));

      return sb.toString();
   }

   /**
    * Method parseATAV
    *
    * @param str
    * @return normalized string
    * @throws IOException
    */
   static String parseATAV(String str) throws IOException {

      int i = str.indexOf("=");

      if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) {
         return str;
      }
      String attrType = normalizeAT(str.substring(0, i));
      // only normalize if value is a String
      String attrValue = null;
      if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') {
          attrValue = str.substring(i + 1);
      } else {
          attrValue = normalizeV(str.substring(i + 1));
      }

      return attrType + "=" + attrValue;

   }

   /**
    * Method normalizeAT
    *
    * @param str
    * @return normalized string
    */
   static String normalizeAT(String str) {

      String at = str.toUpperCase().trim();

      if (at.startsWith("OID")) {
         at = at.substring(3);
      }

      return at;
   }

   /**
    * Method normalizeV
    *
    * @param str
    * @return normalized string
    * @throws IOException
    */
   static String normalizeV(String str) throws IOException {

      String value = trim(str);

      if (value.startsWith("\"")) {
         StringBuffer sb = new StringBuffer();
         StringReader sr = new StringReader(value.substring(1,
                              value.length() - 1));
         int i = 0;
         char c;

         for (; (i = sr.read()) > -1; ) {
            c = (char) i;

            //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253
            if ((c == ',') || (c == '=') || (c == '+') || (c == '<')
                    || (c == '>') || (c == '#') || (c == ';')) {
               sb.append('\\');
            }

            sb.append(c);
         }

         value = trim(sb.toString());
      }

      if (_TOXML == true) {
         if (value.startsWith("#")) {
            value = '\\' + value;
         }
      } else {
         if (value.startsWith("\\#")) {
            value = value.substring(1);
         }
      }

      return value;
   }

   /**
    * Method rfctoXML
    *
    * @param string
    * @return normalized string
    */
   static String rfctoXML(String string) {

      try {
         String s = changeLess32toXML(string);

         return changeWStoXML(s);
      } catch (Exception e) {
         return string;
      }
   }

   /**
    * Method xmltoRFC
    *
    * @param string
    * @return normalized string
    */
   static String xmltoRFC(String string) {

      try {
         String s = changeLess32toRFC(string);

         return changeWStoRFC(s);
      } catch (Exception e) {
         return string;
      }
   }

   /**
    * Method changeLess32toRFC
    *
    * @param string
    * @return normalized string
    * @throws IOException
    */
   static String changeLess32toRFC(String string) throws IOException {

      StringBuffer sb = new StringBuffer();
      StringReader sr = new StringReader(string);
      int i = 0;
      char c;

      for (; (i = sr.read()) > -1; ) {
         c = (char) i;

         if (c == '\\') {
            sb.append(c);

            char c1 = (char) sr.read();
            char c2 = (char) sr.read();

            //65 (A) 97 (a)
            if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102)))
                    && (((c2 >= 48) && (c2 <= 57))
                        || ((c2 >= 65) && (c2 <= 70))
                        || ((c2 >= 97) && (c2 <= 102)))) {
               char ch = (char) Byte.parseByte("" + c1 + c2, 16);

               sb.append(ch);
            } else {
               sb.append(c1);
               sb.append(c2);
            }
         } else {
            sb.append(c);
         }
      }

      return sb.toString();
   }

   /**
    * Method changeLess32toXML
    *
    * @param string
    * @return normalized string
    * @throws IOException
    */
   static String changeLess32toXML(String string) throws IOException {

      StringBuffer sb = new StringBuffer();
      StringReader sr = new StringReader(string);
      int i = 0;

      for (; (i = sr.read()) > -1; ) {
         if (i < 32) {
            sb.append('\\');
            sb.append(Integer.toHexString(i));
         } else {
            sb.append((char) i);
         }
      }

      return sb.toString();
   }

   /**
    * Method changeWStoXML
    *
    * @param string
    * @return normalized string
    * @throws IOException
    */
   static String changeWStoXML(String string) throws IOException {

      StringBuffer sb = new StringBuffer();
      StringReader sr = new StringReader(string);
      int i = 0;
      char c;

      for (; (i = sr.read()) > -1; ) {
         c = (char) i;

         if (c == '\\') {
            char c1 = (char) sr.read();

            if (c1 == ' ') {
               sb.append('\\');

               String s = "20";

               sb.append(s);
            } else {
               sb.append('\\');
               sb.append(c1);
            }
         } else {
            sb.append(c);
         }
      }

      return sb.toString();
   }

   /**
    * Method changeWStoRFC
    *
    * @param string
    * @return normalized string
    */
   static String changeWStoRFC(String string) {

      StringBuffer sb = new StringBuffer();
      int i = 0;
      int k;

      for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) {
         sb.append(trim(string.substring(i, k)) + "\\ ");

         i = k + 3;
      }

      sb.append(string.substring(i));

      return sb.toString();
   }

   /**
    * Method semicolonToComma
    *
    * @param str
    * @return normalized string
    */
   static String semicolonToComma(String str) {
      return removeWSandReplace(str, ";", ",");
   }

   /**
    * Method removeWhiteSpace
    *
    * @param str
    * @param symbol
    * @return normalized string
    */
   static String removeWhiteSpace(String str, String symbol) {
      return removeWSandReplace(str, symbol, symbol);
   }

   /**
    * Method removeWSandReplace
    *
    * @param str
    * @param symbol
    * @param replace
    * @return normalized string
    */
   static String removeWSandReplace(String str, String symbol, String replace) {

      StringBuffer sb = new StringBuffer();
      int i = 0;
      int l = 0;
      int k;

      for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
         l += countQuotes(str, j, k);

         if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
            sb.append(trim(str.substring(i, k)) + replace);

            i = k + 1;
            l = 0;
         }
      }

      sb.append(trim(str.substring(i)));

      return sb.toString();
   }

   /**
    * Returns the number of Quotation from i to j
    *
    * @param s
    * @param i
    * @param j
    * @return number of quotes
    */
   private static int countQuotes(String s, int i, int j) {

      int k = 0;

      for (int l = i; l < j; l++) {
         if (s.charAt(l) == '"') {
            k++;
         }
      }

      return k;
   }

   //only for the end of a space character occurring at the end of the string from rfc2253

   /**
    * Method trim
    *
    * @param str
    * @return the string
    */
   static String trim(String str) {

      String trimed = str.trim();
      int i = str.indexOf(trimed) + trimed.length();

      if ((str.length() > i) && trimed.endsWith("\\")
              &&!trimed.endsWith("\\\\")) {
         if (str.charAt(i) == ' ') {
            trimed = trimed + " ";
         }
      }

      return trimed;
   }

   /**
    * Method main
    *
    * @param args
    * @throws Exception
    */
   public static void main(String[] args) throws Exception {

      testToXML("CN=\"Steve, Kille\",  O=Isode Limited, C=GB");
      testToXML("CN=Steve Kille    ,   O=Isode Limited,C=GB");
      testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ ");
      testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
      testToXML("CN=Before\\0DAfter,O=Test,C=GB");
      testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB");
      testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB");

      {
         StringBuffer sb = new StringBuffer();

         sb.append('L');
         sb.append('u');
         sb.append('\uc48d');
         sb.append('i');
         sb.append('\uc487');

         String test7 = "SN=" + sb.toString();

         testToXML(test7);
      }

      testToRFC("CN=\"Steve, Kille\",  O=Isode Limited, C=GB");
      testToRFC("CN=Steve Kille    ,   O=Isode Limited,C=GB");
      testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 ");
      testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
      testToRFC("CN=Before\\12After,O=Test,C=GB");
      testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB");
      testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB");

      {
         StringBuffer sb = new StringBuffer();

         sb.append('L');
         sb.append('u');
         sb.append('\uc48d');
         sb.append('i');
         sb.append('\uc487');

         String test7 = "SN=" + sb.toString();

         testToRFC(test7);
      }
   }

   /** Field i */
   static int counter = 0;

   /**
    * Method test
    *
    * @param st
    */
   static void testToXML(String st) {

      System.out.println("start " + counter++ + ": " + st);
      System.out.println("         " + rfc2253toXMLdsig(st));
      System.out.println("");
   }

   /**
    * Method testToRFC
    *
    * @param st
    */
   static void testToRFC(String st) {

      System.out.println("start " + counter++ + ": " + st);
      System.out.println("         " + xmldsigtoRFC2253(st));
      System.out.println("");
   }
}