1 /*
   2  * Copyright (c) 1998, 2015, 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 package sun.security.util;
  27 
  28 import java.math.BigInteger;
  29 import java.util.regex.Pattern;
  30 import java.util.regex.Matcher;
  31 import java.util.Locale;
  32 import sun.security.action.GetPropertyAction;
  33 
  34 /**
  35  * A utility class for debuging.
  36  *
  37  * @author Roland Schemers
  38  */
  39 public class Debug {
  40 
  41     private String prefix;
  42 
  43     private static String args;
  44 
  45     static {
  46         args = GetPropertyAction.getProperty("java.security.debug");
  47 
  48         String args2 =
  49                 GetPropertyAction.getProperty("java.security.auth.debug");
  50 
  51         if (args == null) {
  52             args = args2;
  53         } else {
  54             if (args2 != null)
  55                args = args + "," + args2;
  56         }
  57 
  58         if (args != null) {
  59             args = marshal(args);
  60             if (args.equals("help")) {
  61                 Help();
  62             }
  63         }
  64     }
  65 
  66     public static void Help()
  67     {
  68         System.err.println();
  69         System.err.println("all           turn on all debugging");
  70         System.err.println("access        print all checkPermission results");
  71         System.err.println("certpath      PKIX CertPathBuilder and");
  72         System.err.println("              CertPathValidator debugging");
  73         System.err.println("combiner      SubjectDomainCombiner debugging");
  74         System.err.println("gssloginconfig");
  75         System.err.println("              GSS LoginConfigImpl debugging");
  76         System.err.println("configfile    JAAS ConfigFile loading");
  77         System.err.println("configparser  JAAS ConfigFile parsing");
  78         System.err.println("jar           jar verification");
  79         System.err.println("logincontext  login context results");
  80         System.err.println("jca           JCA engine class debugging");
  81         System.err.println("keystore      KeyStore debugging");
  82         System.err.println("policy        loading and granting");
  83         System.err.println("provider      security provider debugging");
  84         System.err.println("pkcs11        PKCS11 session manager debugging");
  85         System.err.println("pkcs11keystore");
  86         System.err.println("              PKCS11 KeyStore debugging");
  87         System.err.println("pkcs12        PKCS12 KeyStore debugging");
  88         System.err.println("sunpkcs11     SunPKCS11 provider debugging");
  89         System.err.println("scl           permissions SecureClassLoader assigns");
  90         System.err.println("ts            timestamping");
  91         System.err.println();
  92         System.err.println("The following can be used with access:");
  93         System.err.println();
  94         System.err.println("stack         include stack trace");
  95         System.err.println("domain        dump all domains in context");
  96         System.err.println("failure       before throwing exception, dump stack");
  97         System.err.println("              and domain that didn't have permission");
  98         System.err.println();
  99         System.err.println("The following can be used with stack and domain:");
 100         System.err.println();
 101         System.err.println("permission=<classname>");
 102         System.err.println("              only dump output if specified permission");
 103         System.err.println("              is being checked");
 104         System.err.println("codebase=<URL>");
 105         System.err.println("              only dump output if specified codebase");
 106         System.err.println("              is being checked");
 107         System.err.println();
 108         System.err.println("The following can be used with provider:");
 109         System.err.println();
 110         System.err.println("engine=<engines>");
 111         System.err.println("              only dump output for the specified list");
 112         System.err.println("              of JCA engines. Supported values:");
 113         System.err.println("              Cipher, KeyAgreement, KeyGenerator,");
 114         System.err.println("              KeyPairGenerator, KeyStore, Mac,");
 115         System.err.println("              MessageDigest, SecureRandom, Signature.");
 116         System.err.println();
 117         System.err.println("The following can be used with certpath:");
 118         System.err.println();
 119         System.err.println("ocsp          dump the OCSP protocol exchanges");
 120         System.err.println();
 121         System.err.println("Note: Separate multiple options with a comma");
 122         System.exit(0);
 123     }
 124 
 125 
 126     /**
 127      * Get a Debug object corresponding to whether or not the given
 128      * option is set. Set the prefix to be the same as option.
 129      */
 130 
 131     public static Debug getInstance(String option)
 132     {
 133         return getInstance(option, option);
 134     }
 135 
 136     /**
 137      * Get a Debug object corresponding to whether or not the given
 138      * option is set. Set the prefix to be prefix.
 139      */
 140     public static Debug getInstance(String option, String prefix)
 141     {
 142         if (isOn(option)) {
 143             Debug d = new Debug();
 144             d.prefix = prefix;
 145             return d;
 146         } else {
 147             return null;
 148         }
 149     }
 150 
 151     /**
 152      * True if the system property "security.debug" contains the
 153      * string "option".
 154      */
 155     public static boolean isOn(String option)
 156     {
 157         if (args == null)
 158             return false;
 159         else {
 160             if (args.indexOf("all") != -1)
 161                 return true;
 162             else
 163                 return (args.indexOf(option) != -1);
 164         }
 165     }
 166 
 167     /**
 168      * print a message to stderr that is prefixed with the prefix
 169      * created from the call to getInstance.
 170      */
 171 
 172     public void println(String message)
 173     {
 174         System.err.println(prefix + ": "+message);
 175     }
 176 
 177     /**
 178      * print a blank line to stderr that is prefixed with the prefix.
 179      */
 180 
 181     public void println()
 182     {
 183         System.err.println(prefix + ":");
 184     }
 185 
 186     /**
 187      * print a message to stderr that is prefixed with the prefix.
 188      */
 189 
 190     public static void println(String prefix, String message)
 191     {
 192         System.err.println(prefix + ": "+message);
 193     }
 194 
 195     /**
 196      * return a hexadecimal printed representation of the specified
 197      * BigInteger object. the value is formatted to fit on lines of
 198      * at least 75 characters, with embedded newlines. Words are
 199      * separated for readability, with eight words (32 bytes) per line.
 200      */
 201     public static String toHexString(BigInteger b) {
 202         String hexValue = b.toString(16);
 203         StringBuilder sb = new StringBuilder(hexValue.length()*2);
 204 
 205         if (hexValue.startsWith("-")) {
 206             sb.append("   -");
 207             hexValue = hexValue.substring(1);
 208         } else {
 209             sb.append("    ");     // four spaces
 210         }
 211         if ((hexValue.length()%2) != 0) {
 212             // add back the leading 0
 213             hexValue = "0" + hexValue;
 214         }
 215         int i=0;
 216         while (i < hexValue.length()) {
 217             // one byte at a time
 218             sb.append(hexValue.substring(i, i + 2));
 219             i+=2;
 220             if (i!= hexValue.length()) {
 221                 if ((i%64) == 0) {
 222                     sb.append("\n    ");     // line after eight words
 223                 } else if (i%8 == 0) {
 224                     sb.append(" ");     // space between words
 225                 }
 226             }
 227         }
 228         return sb.toString();
 229     }
 230 
 231     /**
 232      * change a string into lower case except permission classes and URLs.
 233      */
 234     private static String marshal(String args) {
 235         if (args != null) {
 236             StringBuilder target = new StringBuilder();
 237             StringBuffer source = new StringBuffer(args);
 238 
 239             // obtain the "permission=<classname>" options
 240             // the syntax of classname: IDENTIFIER.IDENTIFIER
 241             // the regular express to match a class name:
 242             // "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*"
 243             String keyReg = "[Pp][Ee][Rr][Mm][Ii][Ss][Ss][Ii][Oo][Nn]=";
 244             String keyStr = "permission=";
 245             String reg = keyReg +
 246                 "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*";
 247             Pattern pattern = Pattern.compile(reg);
 248             Matcher matcher = pattern.matcher(source);
 249             StringBuffer left = new StringBuffer();
 250             while (matcher.find()) {
 251                 String matched = matcher.group();
 252                 target.append(matched.replaceFirst(keyReg, keyStr));
 253                 target.append("  ");
 254 
 255                 // delete the matched sequence
 256                 matcher.appendReplacement(left, "");
 257             }
 258             matcher.appendTail(left);
 259             source = left;
 260 
 261             // obtain the "codebase=<URL>" options
 262             // the syntax of URL is too flexible, and here assumes that the
 263             // URL contains no space, comma(','), and semicolon(';'). That
 264             // also means those characters also could be used as separator
 265             // after codebase option.
 266             // However, the assumption is incorrect in some special situation
 267             // when the URL contains comma or semicolon
 268             keyReg = "[Cc][Oo][Dd][Ee][Bb][Aa][Ss][Ee]=";
 269             keyStr = "codebase=";
 270             reg = keyReg + "[^, ;]*";
 271             pattern = Pattern.compile(reg);
 272             matcher = pattern.matcher(source);
 273             left = new StringBuffer();
 274             while (matcher.find()) {
 275                 String matched = matcher.group();
 276                 target.append(matched.replaceFirst(keyReg, keyStr));
 277                 target.append("  ");
 278 
 279                 // delete the matched sequence
 280                 matcher.appendReplacement(left, "");
 281             }
 282             matcher.appendTail(left);
 283             source = left;
 284 
 285             // convert the rest to lower-case characters
 286             target.append(source.toString().toLowerCase(Locale.ENGLISH));
 287 
 288             return target.toString();
 289         }
 290 
 291         return null;
 292     }
 293 
 294     private static final char[] hexDigits = "0123456789abcdef".toCharArray();
 295 
 296     public static String toString(byte[] b) {
 297         if (b == null) {
 298             return "(null)";
 299         }
 300         StringBuilder sb = new StringBuilder(b.length * 3);
 301         for (int i = 0; i < b.length; i++) {
 302             int k = b[i] & 0xff;
 303             if (i != 0) {
 304                 sb.append(':');
 305             }
 306             sb.append(hexDigits[k >>> 4]);
 307             sb.append(hexDigits[k & 0xf]);
 308         }
 309         return sb.toString();
 310     }
 311 
 312 }