1 /*
   2  * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  *
  28  *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
  29  *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
  30  */
  31 
  32 package sun.security.krb5;
  33 
  34 import sun.security.krb5.internal.Krb5;
  35 import sun.security.util.*;
  36 import java.io.IOException;
  37 import java.util.StringTokenizer;
  38 import java.util.Vector;
  39 import java.util.Stack;
  40 import java.util.EmptyStackException;
  41 import sun.security.krb5.internal.util.KerberosString;
  42 
  43 /**
  44  * Implements the ASN.1 Realm type.
  45  *
  46  * <xmp>
  47  * Realm ::= GeneralString
  48  * </xmp>
  49  */
  50 public class Realm implements Cloneable {
  51     private String realm;
  52     private static boolean DEBUG = Krb5.DEBUG;
  53 
  54     private Realm() {
  55     }
  56 
  57     public Realm(String name) throws RealmException {
  58         realm = parseRealm(name);
  59     }
  60 
  61     public Object clone() {
  62         Realm new_realm = new Realm();
  63         if (realm != null) {
  64             new_realm.realm = new String(realm);
  65         }
  66         return new_realm;
  67     }
  68 
  69     public boolean equals(Object obj) {
  70         if (this == obj) {
  71             return true;
  72         }
  73 
  74         if (!(obj instanceof Realm)) {
  75             return false;
  76         }
  77 
  78         Realm that = (Realm)obj;
  79         if (this.realm != null && that.realm != null ) {
  80             return this.realm.equals(that.realm);
  81         } else {
  82             return (this.realm == null && that.realm == null);
  83         }
  84     }
  85 
  86     public int hashCode() {
  87         int result = 17 ;
  88 
  89         if( realm != null ) {
  90             result = 37 * result + realm.hashCode();
  91         }
  92 
  93         return result;
  94     }
  95 
  96     /**
  97      * Constructs a Realm object.
  98      * @param encoding a Der-encoded data.
  99      * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
 100      * @exception IOException if an I/O error occurs while reading encoded data.
 101      * @exception RealmException if an error occurs while parsing a Realm object.
 102      */
 103     public Realm(DerValue encoding)
 104         throws Asn1Exception, RealmException, IOException {
 105         if (encoding == null) {
 106             throw new IllegalArgumentException("encoding can not be null");
 107         }
 108         realm = new KerberosString(encoding).toString();
 109         if (realm == null || realm.length() == 0)
 110             throw new RealmException(Krb5.REALM_NULL);
 111         if (!isValidRealmString(realm))
 112             throw new RealmException(Krb5.REALM_ILLCHAR);
 113     }
 114 
 115     public String toString() {
 116         return realm;
 117     }
 118 
 119     public static String parseRealmAtSeparator(String name)
 120         throws RealmException {
 121         if (name == null) {
 122             throw new IllegalArgumentException
 123                 ("null input name is not allowed");
 124         }
 125         String temp = new String(name);
 126         String result = null;
 127         int i = 0;
 128         while (i < temp.length()) {
 129             if (temp.charAt(i) == PrincipalName.NAME_REALM_SEPARATOR) {
 130                 if (i == 0 || temp.charAt(i - 1) != '\\') {
 131                     if (i + 1 < temp.length())
 132                         result = temp.substring(i + 1, temp.length());
 133                     break;
 134                 }
 135             }
 136             i++;
 137         }
 138         if (result != null) {
 139             if (result.length() == 0)
 140                 throw new RealmException(Krb5.REALM_NULL);
 141             if (!isValidRealmString(result))
 142                 throw new RealmException(Krb5.REALM_ILLCHAR);
 143         }
 144         return result;
 145     }
 146 
 147     public static String parseRealmComponent(String name) {
 148         if (name == null) {
 149             throw new IllegalArgumentException
 150                 ("null input name is not allowed");
 151         }
 152         String temp = new String(name);
 153         String result = null;
 154         int i = 0;
 155         while (i < temp.length()) {
 156             if (temp.charAt(i) == PrincipalName.REALM_COMPONENT_SEPARATOR) {
 157                 if (i == 0 || temp.charAt(i - 1) != '\\') {
 158                     if (i + 1 < temp.length())
 159                         result = temp.substring(i + 1, temp.length());
 160                     break;
 161                 }
 162             }
 163             i++;
 164         }
 165         return result;
 166     }
 167 
 168     protected static String parseRealm(String name) throws RealmException {
 169         String result = parseRealmAtSeparator(name);
 170         if (result == null)
 171             result = name;
 172         if (result == null || result.length() == 0)
 173             throw new RealmException(Krb5.REALM_NULL);
 174         if (!isValidRealmString(result))
 175             throw new RealmException(Krb5.REALM_ILLCHAR);
 176         return result;
 177     }
 178 
 179     // This is protected because the definition of a realm
 180     // string is fixed
 181     protected static boolean isValidRealmString(String name) {
 182         if (name == null)
 183             return false;
 184         if (name.length() == 0)
 185             return false;
 186         for (int i = 0; i < name.length(); i++) {
 187             if (name.charAt(i) == '/' ||
 188                 name.charAt(i) == ':' ||
 189                 name.charAt(i) == '\0') {
 190                 return false;
 191             }
 192         }
 193         return true;
 194     }
 195 
 196     /**
 197      * Encodes a Realm object.
 198      * @return the byte array of encoded KrbCredInfo object.
 199      * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
 200      * @exception IOException if an I/O error occurs while reading encoded data.
 201      *
 202      */
 203     public byte[] asn1Encode() throws Asn1Exception, IOException {
 204         DerOutputStream out = new DerOutputStream();
 205         out.putDerValue(new KerberosString(this.realm).toDerValue());
 206         return out.toByteArray();
 207     }
 208 
 209 
 210     /**
 211      * Parse (unmarshal) a realm from a DER input stream.  This form
 212      * parsing might be used when expanding a value which is part of
 213      * a constructed sequence and uses explicitly tagged type.
 214      *
 215      * @exception Asn1Exception on error.
 216      * @param data the Der input stream value, which contains one or more marshaled value.
 217      * @param explicitTag tag number.
 218      * @param optional indicate if this data field is optional
 219      * @return an instance of Realm.
 220      *
 221      */
 222     public static Realm parse(DerInputStream data, byte explicitTag, boolean optional) throws Asn1Exception, IOException, RealmException {
 223         if ((optional) && (((byte)data.peekByte() & (byte)0x1F) != explicitTag)) {
 224             return null;
 225         }
 226         DerValue der = data.getDerValue();
 227         if (explicitTag != (der.getTag() & (byte)0x1F))  {
 228             throw new Asn1Exception(Krb5.ASN1_BAD_ID);
 229         } else {
 230             DerValue subDer = der.getData().getDerValue();
 231             return new Realm(subDer);
 232         }
 233     }
 234 
 235     /*
 236      * First leg of realms parsing. Used by getRealmsList.
 237      */
 238     private static String[] doInitialParse(String cRealm, String sRealm)
 239         throws KrbException {
 240             if (cRealm == null || sRealm == null){
 241                 throw new KrbException(Krb5.API_INVALID_ARG);
 242             }
 243             if (DEBUG) {
 244                 System.out.println(">>> Realm doInitialParse: cRealm=["
 245                                    + cRealm + "], sRealm=[" +sRealm + "]");
 246             }
 247             if (cRealm.equals(sRealm)) {
 248                 String[] retList = null;
 249                 retList = new String[1];
 250                 retList[0] = new String(cRealm);
 251 
 252                 if (DEBUG) {
 253                     System.out.println(">>> Realm doInitialParse: "
 254                                        + retList[0]);
 255                 }
 256                 return retList;
 257             }
 258             return null;
 259         }
 260 
 261     /**
 262      * Returns an array of realms that may be traversed to obtain
 263      * a TGT from the initiating realm cRealm to the target realm
 264      * sRealm.
 265      * <br>
 266      * There may be an arbitrary number of intermediate realms
 267      * between cRealm and sRealm. The realms may be organized
 268      * organized hierarchically, or the paths between them may be
 269      * specified in the [capaths] stanza of the caller's
 270      * Kerberos configuration file. The configuration file is consulted
 271      * first. Then a hirarchical organization is assumed if no realms
 272      * are found in the configuration file.
 273      * <br>
 274      * The returned list, if not null, contains cRealm as the first
 275      * entry. sRealm is not included unless it is mistakenly listed
 276      * in the configuration file as an intermediary realm.
 277      *
 278      * @param cRealm the initiating realm
 279      * @param sRealm the target realm
 280      * @returns array of realms
 281      * @thows KrbException
 282      */
 283     public static String[] getRealmsList(String cRealm, String sRealm)
 284         throws KrbException {
 285             String[] retList = doInitialParse(cRealm, sRealm);
 286             if (retList != null && retList.length != 0) {
 287                 return retList;
 288             }
 289             /*
 290              * Try [capaths].
 291              */
 292             retList = parseCapaths(cRealm, sRealm);
 293             if (retList != null && retList.length != 0) {
 294                 return retList;
 295             }
 296             /*
 297              * Now assume the realms are organized hierarchically.
 298              */
 299             retList = parseHierarchy(cRealm, sRealm);
 300             return retList;
 301         }
 302 
 303     /**
 304      * Parses the [capaths] stanza of the configuration file
 305      * for a list of realms to traverse
 306      * to obtain credentials from the initiating realm cRealm to
 307      * the target realm sRealm.
 308      * @param cRealm the initiating realm
 309      * @param sRealm the target realm
 310      * @returns array of realms
 311      * @ throws KrbException
 312      */
 313 
 314     /*
 315      * parseCapaths works for a capaths organized such that
 316      * for a given client realm C there is a tag C that
 317      * contains subtags Ci ... Cn that completely define intermediate
 318      * realms from C to target T. For example:
 319      *
 320      * [capaths]
 321      *    TIVOLI.COM = {
 322      *        IBM.COM = IBM_LDAPCENTRAL.COM MOONLITE.ORG
 323      *        IBM_LDAPCENTRAL.COM = LDAPCENTRAL.NET
 324      *        LDAPCENTRAL.NET = .
 325      *    }
 326      *
 327      * The tag TIVOLI.COM contains subtags IBM.COM, IBM_LDAPCENTRAL.COM
 328      * and LDAPCENTRAL.NET that completely define the path from TIVOLI.COM
 329      * to IBM.COM (TIVOLI.COM->LADAPCENTRAL.NET->IBM_LDAPCENTRAL.COM->IBM
 330      * or TIVOLI.COM->MOONLITE.ORG->IBM.COM).
 331      *
 332      * A direct path is assumed for an intermediary whose entry is not
 333      * "closed" by a "." In the above example, TIVOLI.COM is assumed
 334      * to have a direct path to MOONLITE.ORG and MOONLITE.COM
 335      * in turn to IBM.COM.
 336      */
 337 
 338     private static String[] parseCapaths(String cRealm, String sRealm) throws KrbException {
 339         String[] retList = null;
 340 
 341         Config cfg = null;
 342         try {
 343             cfg = Config.getInstance();
 344         } catch (Exception exc) {
 345             if (DEBUG) {
 346                 System.out.println ("Configuration information can not be " +
 347                                     "obtained " + exc.getMessage());
 348             }
 349             return null;
 350         }
 351 
 352         String intermediaries = cfg.getDefault(sRealm, cRealm);
 353 
 354         if (intermediaries == null) {
 355             if (DEBUG) {
 356                 System.out.println(">>> Realm parseCapaths: no cfg entry");
 357             }
 358             return null;
 359         }
 360 
 361         String tempTarget = null, tempRealm = null;
 362         Stack<String> iStack = new Stack<>();
 363 
 364         /*
 365          * I don't expect any more than a handful of intermediaries.
 366          */
 367         Vector<String> tempList = new Vector<>(8, 8);
 368 
 369         /*
 370          * The initiator at first location.
 371          */
 372         tempList.add(cRealm);
 373 
 374         int count = 0; // For debug only
 375         if (DEBUG) {
 376             tempTarget = sRealm;
 377         }
 378 
 379         out: do {
 380             if (DEBUG) {
 381                 count++;
 382                 System.out.println(">>> Realm parseCapaths: loop " +
 383                                    count + ": target=" + tempTarget);
 384             }
 385 
 386             if (intermediaries != null &&
 387                 !intermediaries.equals(PrincipalName.REALM_COMPONENT_SEPARATOR_STR))
 388             {
 389                 if (DEBUG) {
 390                     System.out.println(">>> Realm parseCapaths: loop " +
 391                                        count + ": intermediaries=[" +
 392                                        intermediaries + "]");
 393                 }
 394 
 395                 /*
 396                  * We have one or more space-separated intermediary realms.
 397                  * Stack them. A null is always added between intermedies of
 398                  * different targets. When this null is popped, it means none
 399                  * of the intermedies for this target is useful (because of
 400                  * infinite loop), the target is then removed from the partial
 401                  * tempList, and the next possible intermediary is tried.
 402                  */
 403                 iStack.push(null);
 404                 String[] ints = intermediaries.split("\\s+");
 405                 for (int i = ints.length-1; i>=0; i--)
 406                 {
 407                     tempRealm = ints[i];
 408                     if (tempRealm.equals(PrincipalName.REALM_COMPONENT_SEPARATOR_STR)) {
 409                         break out;
 410                     }
 411                     if (!tempList.contains(tempRealm)) {
 412                         iStack.push(tempRealm);
 413                         if (DEBUG) {
 414                             System.out.println(">>> Realm parseCapaths: loop " +
 415                                                count +
 416                                                ": pushed realm on to stack: " +
 417                                                tempRealm);
 418                         }
 419                     } else if (DEBUG) {
 420                         System.out.println(">>> Realm parseCapaths: loop " +
 421                                            count +
 422                                            ": ignoring realm: [" +
 423                                            tempRealm + "]");
 424                     }
 425                 }
 426             } else {
 427                 if (DEBUG) {
 428                     System.out.println(">>> Realm parseCapaths: loop " +
 429                                        count +
 430                                        ": no intermediaries");
 431                 }
 432                 break;
 433             }
 434 
 435             /*
 436              * Get next intermediary realm from the stack
 437              */
 438 
 439             try {
 440                 while ((tempTarget = iStack.pop()) == null) {
 441                     tempList.removeElementAt(tempList.size()-1);
 442                     if (DEBUG) {
 443                         System.out.println(">>> Realm parseCapaths: backtrack, remove tail");
 444                     }
 445                 }
 446             } catch (EmptyStackException exc) {
 447                 tempTarget = null;
 448             }
 449 
 450             if (tempTarget == null) {
 451                 /*
 452                  * No more intermediaries. We're done.
 453                  */
 454                 break;
 455             }
 456 
 457             tempList.add(tempTarget);
 458 
 459             if (DEBUG) {
 460                 System.out.println(">>> Realm parseCapaths: loop " + count +
 461                                    ": added intermediary to list: " +
 462                                    tempTarget);
 463             }
 464 
 465             intermediaries = cfg.getDefault(tempTarget, cRealm);
 466 
 467         } while (true);
 468 
 469         retList = new String[tempList.size()];
 470         try {
 471             retList = tempList.toArray(retList);
 472         } catch (ArrayStoreException exc) {
 473             retList = null;
 474         }
 475 
 476         if (DEBUG && retList != null) {
 477             for (int i = 0; i < retList.length; i++) {
 478                 System.out.println(">>> Realm parseCapaths [" + i +
 479                                    "]=" + retList[i]);
 480             }
 481         }
 482 
 483         return retList;
 484     }
 485 
 486     /**
 487      * Build a list of realm that can be traversed
 488      * to obtain credentials from the initiating realm cRealm
 489      * for a service in the target realm sRealm.
 490      * @param cRealm the initiating realm
 491      * @param sRealm the target realm
 492      * @returns array of realms
 493      * @throws KrbException
 494      */
 495     private static String[] parseHierarchy(String cRealm, String sRealm)
 496         throws KrbException
 497     {
 498         String[] retList = null;
 499 
 500         // Parse the components and determine common part, if any.
 501 
 502         String[] cComponents = null;
 503         String[] sComponents = null;
 504 
 505         StringTokenizer strTok =
 506         new StringTokenizer(cRealm,
 507                             PrincipalName.REALM_COMPONENT_SEPARATOR_STR);
 508 
 509         // Parse cRealm
 510 
 511         int cCount = strTok.countTokens();
 512         cComponents = new String[cCount];
 513 
 514         for (cCount = 0; strTok.hasMoreTokens(); cCount++) {
 515             cComponents[cCount] = strTok.nextToken();
 516         }
 517 
 518         if (DEBUG) {
 519             System.out.println(">>> Realm parseHierarchy: cRealm has " +
 520                                cCount + " components:");
 521             int j = 0;
 522             while (j < cCount) {
 523                 System.out.println(">>> Realm parseHierarchy: " +
 524                                    "cComponents["+j+"]=" + cComponents[j++]);
 525             }
 526         }
 527 
 528         // Parse sRealm
 529 
 530         strTok = new StringTokenizer(sRealm,
 531                                      PrincipalName.REALM_COMPONENT_SEPARATOR_STR);
 532 
 533         int sCount = strTok.countTokens();
 534         sComponents = new String[sCount];
 535 
 536         for (sCount = 0; strTok.hasMoreTokens(); sCount++) {
 537             sComponents[sCount] = strTok.nextToken();
 538         }
 539 
 540         if (DEBUG) {
 541             System.out.println(">>> Realm parseHierarchy: sRealm has " +
 542                                sCount + " components:");
 543             int j = 0;
 544             while (j < sCount) {
 545                 System.out.println(">>> Realm parseHierarchy: sComponents["+j+
 546                                    "]=" + sComponents[j++]);
 547             }
 548         }
 549 
 550         // Determine common components, if any.
 551 
 552         int commonComponents = 0;
 553 
 554         //while (sCount > 0 && cCount > 0 &&
 555         //          sComponents[--sCount].equals(cComponents[--cCount]))
 556 
 557         for (sCount--, cCount--; sCount >=0 && cCount >= 0 &&
 558                  sComponents[sCount].equals(cComponents[cCount]);
 559              sCount--, cCount--) {
 560             commonComponents++;
 561         }
 562 
 563         int cCommonStart = -1;
 564         int sCommonStart = -1;
 565 
 566         int links = 0;
 567 
 568         if (commonComponents > 0) {
 569             sCommonStart = sCount+1;
 570             cCommonStart = cCount+1;
 571 
 572             // components from common to ancestors
 573             links += sCommonStart;
 574             links += cCommonStart;
 575         } else {
 576             links++;
 577         }
 578 
 579         if (DEBUG) {
 580             if (commonComponents > 0) {
 581                 System.out.println(">>> Realm parseHierarchy: " +
 582                                    commonComponents + " common component" +
 583                                    (commonComponents > 1 ? "s" : " "));
 584 
 585                 System.out.println(">>> Realm parseHierarchy: common part "
 586                                    +
 587                                    "in cRealm (starts at index " +
 588                                    cCommonStart + ")");
 589                 System.out.println(">>> Realm parseHierarchy: common part in sRealm (starts at index " +
 590                                    sCommonStart + ")");
 591 
 592 
 593                 String commonPart = substring(cRealm, cCommonStart);
 594                 System.out.println(">>> Realm parseHierarchy: common part in cRealm=" +
 595                                    commonPart);
 596 
 597                 commonPart = substring(sRealm, sCommonStart);
 598                 System.out.println(">>> Realm parseHierarchy: common part in sRealm=" +
 599                                    commonPart);
 600 
 601             } else
 602             System.out.println(">>> Realm parseHierarchy: no common part");
 603         }
 604 
 605         if (DEBUG) {
 606             System.out.println(">>> Realm parseHierarchy: total links=" + links);
 607         }
 608 
 609         retList = new String[links];
 610 
 611         retList[0] = new String(cRealm);
 612 
 613         if (DEBUG) {
 614             System.out.println(">>> Realm parseHierarchy A: retList[0]=" +
 615                                retList[0]);
 616         }
 617 
 618         // For an initiator realm A.B.C.D.COM,
 619         // build a list krbtgt/B.C.D.COM@A.B.C.D.COM up to the common part,
 620         // ie the issuer realm is the immediate descendant
 621         // of the target realm.
 622 
 623         String cTemp = null, sTemp = null;
 624         int i;
 625         for (i = 1, cCount = 0; i < links && cCount < cCommonStart; cCount++) {
 626             sTemp = substring(cRealm, cCount+1);
 627             //cTemp = substring(cRealm, cCount);
 628             retList[i++] = new String(sTemp);
 629 
 630             if (DEBUG) {
 631                 System.out.println(">>> Realm parseHierarchy B: retList[" +
 632                                    (i-1) +"]="+retList[i-1]);
 633             }
 634         }
 635 
 636 
 637         for (sCount = sCommonStart; i < links && sCount - 1 > 0; sCount--) {
 638             sTemp = substring(sRealm, sCount-1);
 639             //cTemp = substring(sRealm, sCount);
 640             retList[i++] = new String(sTemp);
 641             if (DEBUG) {
 642                 System.out.println(">>> Realm parseHierarchy D: retList[" +
 643                                    (i-1) +"]="+retList[i-1]);
 644             }
 645         }
 646 
 647         return retList;
 648     }
 649 
 650     private static String substring(String realm, int componentIndex)
 651     {
 652         int i = 0 , j = 0, len = realm.length();
 653 
 654         while(i < len && j != componentIndex) {
 655             if (realm.charAt(i++) != PrincipalName.REALM_COMPONENT_SEPARATOR)
 656                 continue;
 657             j++;
 658         }
 659 
 660         return realm.substring(i);
 661     }
 662 
 663     static int getRandIndex(int arraySize) {
 664         return (int)(Math.random() * 16384.0) % arraySize;
 665     }
 666 
 667     static void printNames(String[] names) {
 668         if (names == null || names.length == 0)
 669             return;
 670 
 671         int len = names.length;
 672         int i = 0;
 673         System.out.println("List length = " + len);
 674         while (i < names.length) {
 675             System.out.println("["+ i +"]=" + names[i]);
 676             i++;
 677         }
 678     }
 679 
 680 }