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