Path: blob/master/test/jdk/sun/security/krb5/auto/KdcPolicy.java
41152 views
/*1* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.*;24import java.net.DatagramSocket;25import java.net.ServerSocket;26import java.nio.file.Files;27import java.nio.file.Paths;28import java.security.Security;29import java.util.ArrayList;30import java.util.List;31import java.util.Random;32import java.util.regex.Matcher;33import java.util.regex.Pattern;34import javax.security.auth.login.LoginException;35import sun.security.krb5.Asn1Exception;36import sun.security.krb5.Config;3738/*39* @test40* @bug 8164656 8181461 819448641* @summary krb5.kdc.bad.policy test42* @library /test/lib43* @run main jdk.test.lib.FileInstaller TestHosts TestHosts44* @run main/othervm -Djdk.net.hosts.file=TestHosts KdcPolicy udp45* @run main/othervm -Djdk.net.hosts.file=TestHosts KdcPolicy tcp46*/47public class KdcPolicy {4849// Is this test on UDP?50static boolean udp;5152public static void main(String[] args) throws Exception {5354udp = args[0].equals("udp");5556try {57main0();58} catch (LoginException le) {59Throwable cause = le.getCause();60if (cause instanceof Asn1Exception) {61System.out.println("Another process sends a packet to " +62"this server. Ignored.");63return;64}65throw le;66}67}6869static DebugMatcher cm = new DebugMatcher();7071static void main0() throws Exception {7273System.setProperty("sun.security.krb5.debug", "true");7475// One real KDC. Must be created before fake KDCs76// to read the TestHosts file.77OneKDC kdc = new OneKDC(null);7879// Two fake KDCs, d1 and d2 only listen but do not respond.8081if (udp) {82try (DatagramSocket d1 = new DatagramSocket();83DatagramSocket d2 = new DatagramSocket()) {84run(d1.getLocalPort(), d2.getLocalPort(), kdc.getPort());85}86} else {87try (ServerSocket d1 = new ServerSocket(0);88ServerSocket d2 = new ServerSocket(0)) {89run(d1.getLocalPort(), d2.getLocalPort(), kdc.getPort());90}91}92}9394static void run(int p1, int p2, int p3) throws Exception {9596// cm.kdc() will return a and b for fake KDCs, and c for real KDC.97cm.addPort(-1).addPort(p1).addPort(p2).addPort(p3);9899System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");100101// Check default timeout is 30s. Use real KDC only, otherwise too102// slow to wait for timeout. Each request (without preauth and with103// preauth) might be retried 3 times, and could fail if one fails for104// all 3 times.105writeConf(-1, -1, p3);106test("(c30000){2,6}|(c30000){3,6}-");107108// 1. Default policy is tryLast109//Security.setProperty("krb5.kdc.bad.policy", "tryLast");110111// Need a real KDC, otherwise there is no last good.112// This test waste 3 seconds waiting for d1 to timeout.113// It is possible the real KDC cannot fulfil the request114// in 3s, so it might fail (either 1st time or 2nd time).115writeConf(1, 3000, p1, p3);116test("a3000c3000c3000|a3000c3000-|a3000c3000c3000a3000-");117118// If a test case won't use a real KDC, it can be sped up.119writeConf(3, 5, p1, p2);120test("a5a5a5b5b5b5-"); // default max_retries == 3121test("a5a5a5b5b5b5-"); // all bad means no bad122123// 2. No policy.124Security.setProperty("krb5.kdc.bad.policy", "");125Config.refresh();126127// This case needs a real KDC, otherwise, all bad means no128// bad and we cannot tell the difference. This case waste 3129// seconds on d1 to timeout twice. It is possible the real KDC130// cannot fulfil the request within 3s, so it might fail131// (either 1st time or 2nd time).132writeConf(1, 3000, p1, p3);133test("a3000c3000a3000c3000|a3000c3000-|a3000c3000a3000c3000-");134135// 3. tryLess with no argument means tryLess:1,5000136Security.setProperty("krb5.kdc.bad.policy", "tryLess");137138// This case will waste 11s. We are checking that the default139// value of 5000 in tryLess is only used if it's less than timeout140// in krb5.conf141writeConf(1, 6000, p1);142test("a6000-"); // timeout in krb5.conf is 6s143test("a5000-"); // tryLess to 5s. This line can be made faster if144// d1 is a read KDC, but we have no existing method145// to start KDC on an existing ServerSocket (port).146147writeConf(-1, 4, p1, p2);148test("a4a4a4b4b4b4-"); // default max_retries == 3149test("a4b4-"); // tryLess to 1. And since 4 < 5000, use 4.150Config.refresh();151test("a4a4a4b4b4b4-");152153writeConf(5, 4, p1, p2);154test("a4a4a4a4a4b4b4b4b4b4-"); // user-provided max_retries == 5155test("a4b4-");156Config.refresh();157test("a4a4a4a4a4b4b4b4b4b4-");158159// 3. tryLess with arguments160Security.setProperty("krb5.kdc.bad.policy",161"tryLess:2,5");162163writeConf(-1, 6, p1, p2);164test("a6a6a6b6b6b6-"); // default max_retries == 3165test("a5a5b5b5-"); // tryLess to 2166Config.refresh();167test("a6a6a6b6b6b6-");168169writeConf(5, 4, p1, p2);170test("a4a4a4a4a4b4b4b4b4b4-"); // user-provided max_retries == 5171test("a4a4b4b4-"); // tryLess to 2172Config.refresh();173test("a4a4a4a4a4b4b4b4b4b4-");174}175176/**177* Writes a krb5.conf file.178* @param max max_retries, -1 if not set179* @param to kdc_timeout, -1 if not set180* @param ports where KDCs listen on181*/182static void writeConf(int max, int to, int... ports) throws Exception {183184// content of krb5.conf185String conf = "";186187// Extra settings in [libdefaults]188String inDefaults = "";189190// Extra settings in [realms]191String inRealm = "";192193// We will randomly put extra settings only in [libdefaults],194// or in [realms] but with different values in [libdefaults],195// to prove that settings in [realms] override those in [libdefaults].196Random r = new Random();197198if (max > 0) {199if (r.nextBoolean()) {200inDefaults += "max_retries = " + max + "\n";201} else {202inRealm += " max_retries = " + max + "\n";203inDefaults += "max_retries = " + (max + 1) + "\n";204}205}206207if (to > 0) {208if (r.nextBoolean()) {209inDefaults += "kdc_timeout = " + to + "\n";210} else {211inRealm += " kdc_timeout = " + to + "\n";212inDefaults += "kdc_timeout = " + (to + 1) + "\n";213}214}215216if (udp) {217if (r.nextBoolean()) {218inDefaults += "udp_preference_limit = 10000\n";219} else if (r.nextBoolean()) {220inRealm += " udp_preference_limit = 10000\n";221inDefaults += "udp_preference_limit = 1\n";222} // else no settings means UDP223} else {224if (r.nextBoolean()) {225inDefaults += "udp_preference_limit = 1\n";226} else {227inRealm += " udp_preference_limit = 1\n";228inDefaults += "udp_preference_limit = 10000\n";229}230}231232conf = "[libdefaults]\n" +233"default_realm = " + OneKDC.REALM + "\n" +234inDefaults +235"\n" +236"[realms]\n" +237OneKDC.REALM + " = {\n";238239for (int port : ports) {240conf += " kdc = " + OneKDC.KDCHOST + ":" + port + "\n" +241inRealm;242}243244conf += "}\n";245246Files.write(Paths.get("alternative-krb5.conf"), conf.getBytes());247Config.refresh();248}249250/**251* One call of krb5 login. As long as the result matches one of expected,252* the test is considered as success. The grammar of expected is253*254* kdc#, timeout, kdc#, timeout, ..., optional "-" for failure255*/256static void test(String... expected) throws Exception {257258System.out.println("------------------TEST----------------------");259PrintStream oldOut = System.out;260boolean failed = false;261ByteArrayOutputStream bo = new ByteArrayOutputStream();262System.setOut(new PrintStream(bo));263try {264Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);265} catch (Exception e) {266failed = true;267} finally {268System.setOut(oldOut);269}270271String[] lines = new String(bo.toByteArray()).split("\n");272StringBuilder sb = new StringBuilder();273for (String line: lines) {274if (cm.match(line)) {275if (udp != cm.isUDP()) {276sb.append("x");277}278sb.append(cm.kdc()).append(cm.timeout());279}280}281if (failed) sb.append('-');282283String output = sb.toString();284285boolean found = false;286for (String ex : expected) {287if (output.matches(ex)) {288System.out.println("Expected: " + ex + ", actual " + output);289found = true;290break;291}292}293294if (!found) {295System.out.println("--------------- ERROR START -------------");296System.out.println(new String(bo.toByteArray()));297System.out.println("--------------- ERROR END ---------------");298throw new Exception("Does not match. Output is " + output);299}300}301302/**303* A helper class to match the krb5 debug output:304* >>> KDCCommunication: kdc=host UDP:11555, timeout=200,Attempt =1, #bytes=138305*306* Example:307* DebugMatcher cm = new DebugMatcher();308* cm.addPort(12345).addPort(11555);309* for (String line : debugOutput) {310* if (cm.match(line)) {311* System.out.printf("%c%d\n", cm.kdc(), cm.timeout());312* // shows b200 for the example above313* }314* }315*/316static class DebugMatcher {317318static final Pattern re = Pattern.compile(319">>> KDCCommunication: kdc=\\S+ (TCP|UDP):(\\d+), " +320"timeout=(\\d+),Attempt\\s*=(\\d+)");321322List<Integer> kdcPorts = new ArrayList<>();323Matcher matcher;324325/**326* Add KDC ports one by one. See {@link #kdc()}.327*/328DebugMatcher addPort(int port) {329if (port > 0) {330kdcPorts.add(port);331} else {332kdcPorts.clear();333}334return this;335}336337/**338* When a line matches the ">>> KDCCommunication:" pattern. After a339* match, the getters below can be called on this match.340*/341boolean match(String line) {342matcher = re.matcher(line);343return matcher.find();344}345346/**347* Protocol of this match, "UDP" or "TCP".348*/349boolean isUDP() {350return matcher.group(1).equals("UDP");351}352353/**354* KDC for this match, "a" for the one 1st added bt addPort(), "b"355* for second, etc. Undefined for not added.356*/357char kdc() {358int port = Integer.parseInt(matcher.group(2));359return (char) (kdcPorts.indexOf(port) + 'a');360}361362/**363* Timeout value for this match.364*/365int timeout() {366return Integer.parseInt(matcher.group(3));367}368}369}370371372