1 /*
   2  * Copyright (c) 2009, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 6894643 6913636 8005523 8025123
  27  * @summary Test JSSE Kerberos ciphersuite
  28 
  29  * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA
  30  * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA unbound
  31  * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA unbound sni
  32  * @run main/othervm SSL TLS_KRB5_WITH_3DES_EDE_CBC_SHA
  33  * @run main/othervm SSL TLS_KRB5_WITH_3DES_EDE_CBC_MD5
  34  * @run main/othervm SSL TLS_KRB5_WITH_DES_CBC_SHA
  35  * @run main/othervm SSL TLS_KRB5_WITH_DES_CBC_MD5
  36  * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_RC4_40_SHA
  37  * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_RC4_40_MD5
  38  * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
  39  * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
  40  */
  41 import java.io.*;
  42 import java.security.Permission;
  43 import javax.net.ssl.*;
  44 import java.security.Principal;
  45 import java.security.Security;
  46 import java.util.Date;
  47 import java.util.List;
  48 import java.util.ArrayList;
  49 import java.util.Locale;
  50 import javax.security.auth.kerberos.ServicePermission;
  51 import sun.security.jgss.GSSUtil;
  52 import sun.security.krb5.PrincipalName;
  53 import sun.security.krb5.internal.ktab.KeyTab;
  54 
  55 public class SSL extends SecurityManager {
  56 
  57     private static String krb5Cipher;
  58     private static final int LOOP_LIMIT = 3;
  59     private static int loopCount = 0;
  60     private static volatile String server;
  61     private static volatile int port;
  62     private static String sniHostname = null;
  63     private static String sniMatcherPattern = null;
  64 
  65     private static String permChecks = "";
  66 
  67     // 0-Not started, 1-Start OK, 2-Failure
  68     private static volatile int serverState = 0;
  69 
  70     @Override
  71     public void checkPermission(Permission perm, Object context) {
  72         checkPermission(perm);
  73     }
  74 
  75     public void checkPermission(Permission perm) {
  76         if (!(perm instanceof ServicePermission)) {
  77             return;
  78         }
  79         ServicePermission p = (ServicePermission)perm;
  80         permChecks = permChecks + p.getActions().toUpperCase().charAt(0);
  81     }
  82 
  83     public static void main(String[] args) throws Exception {
  84         // reset the security property to make sure that the algorithms
  85         // and keys used in this test are not disabled.
  86         Security.setProperty("jdk.tls.disabledAlgorithms", "");
  87 
  88         krb5Cipher = args[0];
  89 
  90         boolean unbound = args.length > 1;
  91 
  92         System.setSecurityManager(new SSL());
  93 
  94         KDC kdc = KDC.create(OneKDC.REALM);
  95         server = "host." + OneKDC.REALM.toLowerCase(Locale.US);
  96 
  97         if (args.length > 2) {
  98             sniHostname = "test." + server;
  99             sniMatcherPattern = ".*";
 100         }
 101 
 102         kdc.addPrincipal(OneKDC.USER, OneKDC.PASS);
 103         kdc.addPrincipalRandKey("krbtgt/" + OneKDC.REALM);
 104         KDC.saveConfig(OneKDC.KRB5_CONF, kdc);
 105         System.setProperty("java.security.krb5.conf", OneKDC.KRB5_CONF);
 106 
 107         // Add 3 versions of keys into keytab
 108         KeyTab ktab = KeyTab.create(OneKDC.KTAB);
 109         String serviceName = null;
 110         if (sniHostname != null) {
 111             serviceName = "host/" + sniHostname;
 112         } else {
 113             serviceName = "host/" + server;
 114         }
 115         PrincipalName service = new PrincipalName(
 116             serviceName, PrincipalName.KRB_NT_SRV_HST);
 117         ktab.addEntry(service, "pass1".toCharArray(), 1, true);
 118         ktab.addEntry(service, "pass2".toCharArray(), 2, true);
 119         ktab.addEntry(service, "pass3".toCharArray(), 3, true);
 120         ktab.save();
 121 
 122         // and use the middle one as the real key
 123         kdc.addPrincipal(serviceName, "pass2".toCharArray());
 124 
 125 
 126         // JAAS config entry name ssl
 127         System.setProperty("java.security.auth.login.config", OneKDC.JAAS_CONF);
 128         File f = new File(OneKDC.JAAS_CONF);
 129         FileOutputStream fos = new FileOutputStream(f);
 130         fos.write((
 131                 "ssl {\n" +
 132                 "    com.sun.security.auth.module.Krb5LoginModule required\n" +
 133                 (unbound ?
 134                     "    principal=*\n" :
 135                     "    principal=\"" + serviceName + "\"\n") +
 136                 "    useKeyTab=true\n" +
 137                 "    keyTab=" + OneKDC.KTAB + "\n" +
 138                 "    isInitiator=false\n" +
 139                 "    storeKey=true;\n};\n"
 140                 ).getBytes());
 141         fos.close();
 142 
 143         Context c;
 144         final Context s = Context.fromJAAS("ssl");
 145 
 146         s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
 147 
 148         Thread server = new Thread(new Runnable() {
 149             public void run() {
 150                 try {
 151                     s.doAs(new JsseServerAction(), null);
 152                 } catch (Exception e) {
 153                     e.printStackTrace();
 154                     serverState = 2;
 155                 }
 156             }
 157         });
 158         server.setDaemon(true);
 159         server.start();
 160 
 161         while (serverState == 0) {
 162             Thread.sleep(50);
 163         }
 164 
 165         if (serverState == 2) {
 166             throw new Exception("Server already failed");
 167         }
 168 
 169         c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
 170         c.startAsClient(serviceName, GSSUtil.GSS_KRB5_MECH_OID);
 171         c.doAs(new JsseClientAction(), null);
 172 
 173         // Add another version of key, make sure it can be loaded
 174         Thread.sleep(2000);
 175         ktab = KeyTab.getInstance(OneKDC.KTAB);
 176         ktab.addEntry(service, "pass4".toCharArray(), 4, true);
 177         ktab.save();
 178         kdc.addPrincipal(serviceName, "pass4".toCharArray());
 179 
 180         c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
 181         c.startAsClient(serviceName, GSSUtil.GSS_KRB5_MECH_OID);
 182         c.doAs(new JsseClientAction(), null);
 183 
 184         // Permission checking check. Please note this is highly
 185         // implementation related.
 186         if (unbound) {
 187             // For unbound, server does not know what name to check.
 188             // Client checks "initiate", then server gets the name
 189             // and checks "accept". Second connection resume.
 190             if (!permChecks.equals("IA")) {
 191                 throw new Exception();
 192             }
 193         } else {
 194             // For bound, JAAS checks "accept" once. Server checks again,
 195             // client then checks "initiate". Second connection resume.
 196             if (!permChecks.equals("AAI")) {
 197                 throw new Exception();
 198             }
 199         }
 200     }
 201 
 202     // Following codes copied from
 203     // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/lab/part2.html#JSSE
 204     private static class JsseClientAction implements Action {
 205         public byte[] run(Context s, byte[] input) throws Exception {
 206             SSLSocketFactory sslsf =
 207                 (SSLSocketFactory) SSLSocketFactory.getDefault();
 208             System.out.println("Connecting " + server + ":" + port);
 209             SSLSocket sslSocket = (SSLSocket) sslsf.createSocket(server, port);
 210 
 211             // Enable only a KRB5 cipher suite.
 212             String enabledSuites[] = {krb5Cipher};
 213             sslSocket.setEnabledCipherSuites(enabledSuites);
 214             // Should check for exception if enabledSuites is not supported
 215 
 216             if (sniHostname != null) {
 217                 List<SNIServerName> serverNames = new ArrayList<>();
 218                 serverNames.add(new SNIHostName(sniHostname));
 219                 SSLParameters params = sslSocket.getSSLParameters();
 220                 params.setServerNames(serverNames);
 221                 sslSocket.setSSLParameters(params);
 222             }
 223 
 224             BufferedReader in = new BufferedReader(new InputStreamReader(
 225                 sslSocket.getInputStream()));
 226             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
 227                 sslSocket.getOutputStream()));
 228 
 229             String outStr = "Hello There!\n";
 230             out.write(outStr);
 231             out.flush();
 232             System.out.print("Sending " + outStr);
 233 
 234             String inStr = in.readLine();
 235             System.out.println("Received " + inStr);
 236 
 237             String cipherSuiteChosen = sslSocket.getSession().getCipherSuite();
 238             System.out.println("Cipher suite in use: " + cipherSuiteChosen);
 239             Principal self = sslSocket.getSession().getLocalPrincipal();
 240             System.out.println("I am: " + self.toString());
 241             Principal peer = sslSocket.getSession().getPeerPrincipal();
 242             System.out.println("Server is: " + peer.toString());
 243 
 244             sslSocket.close();
 245             // This line should not be needed. It's the server's duty to
 246             // forget the old key
 247             //sslSocket.getSession().invalidate();
 248             return null;
 249         }
 250     }
 251 
 252     private static class JsseServerAction implements Action {
 253         public byte[] run(Context s, byte[] input) throws Exception {
 254             SSLServerSocketFactory sslssf =
 255                 (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
 256             SSLServerSocket sslServerSocket =
 257                 (SSLServerSocket) sslssf.createServerSocket(0); // any port
 258             port = sslServerSocket.getLocalPort();
 259             System.out.println("Listening on " + port);
 260             serverState = 1;
 261 
 262             // Enable only a KRB5 cipher suite.
 263             String enabledSuites[] = {krb5Cipher};
 264             sslServerSocket.setEnabledCipherSuites(enabledSuites);
 265             // Should check for exception if enabledSuites is not supported
 266 
 267             if (sniMatcherPattern != null) {
 268                 List<SNIMatcher> matchers = new ArrayList<>();
 269                 matchers.add(SNIHostName.createSNIMatcher(sniMatcherPattern));
 270                 SSLParameters params = sslServerSocket.getSSLParameters();
 271                 params.setSNIMatchers(matchers);
 272                 sslServerSocket.setSSLParameters(params);
 273             }
 274 
 275             while (loopCount++ < LOOP_LIMIT) {
 276                 System.out.println("Waiting for incoming connection...");
 277 
 278                 SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
 279 
 280                 System.out.println("Got connection from client "
 281                     + sslSocket.getInetAddress());
 282 
 283                 BufferedReader in = new BufferedReader(new InputStreamReader(
 284                     sslSocket.getInputStream()));
 285                 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
 286                     sslSocket.getOutputStream()));
 287 
 288                 String inStr = in.readLine();
 289                 System.out.println("Received " + inStr);
 290 
 291                 String outStr = inStr + " " + new Date().toString() + "\n";
 292                 out.write(outStr);
 293                 System.out.println("Sending " + outStr);
 294                 out.flush();
 295 
 296                 String cipherSuiteChosen =
 297                     sslSocket.getSession().getCipherSuite();
 298                 System.out.println("Cipher suite in use: " + cipherSuiteChosen);
 299                 Principal self = sslSocket.getSession().getLocalPrincipal();
 300                 System.out.println("I am: " + self.toString());
 301                 Principal peer = sslSocket.getSession().getPeerPrincipal();
 302                 System.out.println("Client is: " + peer.toString());
 303 
 304                 sslSocket.close();
 305             }
 306             return null;
 307         }
 308     }
 309 }