Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/security/krb5/auto/KdcPolicy.java
38853 views
/*1* Copyright (c) 2016, 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 816465641* @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KdcPolicy udp42* @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KdcPolicy tcp43* @summary krb5.kdc.bad.policy test44*/45public class KdcPolicy {4647// Is this test on UDP?48static boolean udp;4950public static void main(String[] args) throws Exception {5152udp = args[0].equals("udp");5354try {55main0();56} catch (LoginException le) {57Throwable cause = le.getCause();58if (cause instanceof Asn1Exception) {59System.out.println("Another process sends a packet to " +60"this server. Ignored.");61return;62}63throw le;64}65}6667static DebugMatcher cm = new DebugMatcher();6869static void main0() throws Exception {7071System.setProperty("sun.security.krb5.debug", "true");7273// One real KDC. Must be created before fake KDCs74// to read the TestHosts file.75OneKDC kdc = new OneKDC(null);7677// Two fake KDCs, d1 and d2 only listen but do not respond.7879if (udp) {80try (DatagramSocket d1 = new DatagramSocket();81DatagramSocket d2 = new DatagramSocket()) {82run(d1.getLocalPort(), d2.getLocalPort(), kdc.getPort());83}84} else {85try (ServerSocket d1 = new ServerSocket(0);86ServerSocket d2 = new ServerSocket(0)) {87run(d1.getLocalPort(), d2.getLocalPort(), kdc.getPort());88}89}90}9192static void run(int p1, int p2, int p3) throws Exception {9394// cm.kdc() will return a and b for fake KDCs, and c for real KDC.95cm.addPort(-1).addPort(p1).addPort(p2).addPort(p3);9697System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");9899// Check default timeout is 30s. Use real KDC only, otherwise too100// slow to wait for timeout.101writeConf(-1, -1, p3);102test("c30000c30000");103104// 1. Default policy is tryLast105//Security.setProperty("krb5.kdc.bad.policy", "tryLast");106107// Need a real KDC, otherwise there is no last good.108// This test waste 3 seconds waiting for d1 to timeout.109// It is possible the real KDC cannot fulfil the request110// in 3s, so it might fail (either 1st time or 2nd time).111writeConf(1, 3000, p1, p3);112test("a3000c3000c3000|a3000c3000-|a3000c3000c3000-");113114// If a test case won't use a real KDC, it can be sped up.115writeConf(3, 5, p1, p2);116test("a5a5a5b5b5b5-"); // default max_retries == 3117test("a5a5a5b5b5b5-"); // all bad means no bad118119// 2. No policy.120Security.setProperty("krb5.kdc.bad.policy", "");121Config.refresh();122123// This case needs a real KDC, otherwise, all bad means no124// bad and we cannot tell the difference. This case waste 3125// seconds on d1 to timeout twice. It is possible the real KDC126// cannot fulfil the request within 3s, so it might fail127// (either 1st time or 2nd time).128writeConf(1, 3000, p1, p3);129test("a3000c3000a3000c3000|a3000c3000-|a3000c3000a3000c3000-");130131// 3. tryLess with no argument means tryLess:1,5000132Security.setProperty("krb5.kdc.bad.policy", "tryLess");133134// This case will waste 11s. We are checking that the default135// value of 5000 in tryLess is only used if it's less than timeout136// in krb5.conf137writeConf(1, 6000, p1);138test("a6000-"); // timeout in krb5.conf is 6s139test("a5000-"); // tryLess to 5s. This line can be made faster if140// d1 is a read KDC, but we have no existing method141// to start KDC on an existing ServerSocket (port).142143writeConf(-1, 4, p1, p2);144test("a4a4a4b4b4b4-"); // default max_retries == 3145test("a4b4-"); // tryLess to 1. And since 4 < 5000, use 4.146Config.refresh();147test("a4a4a4b4b4b4-");148149writeConf(5, 4, p1, p2);150test("a4a4a4a4a4b4b4b4b4b4-"); // user-provided max_retries == 5151test("a4b4-");152Config.refresh();153test("a4a4a4a4a4b4b4b4b4b4-");154155// 3. tryLess with arguments156Security.setProperty("krb5.kdc.bad.policy",157"tryLess:2,5");158159writeConf(-1, 6, p1, p2);160test("a6a6a6b6b6b6-"); // default max_retries == 3161test("a5a5b5b5-"); // tryLess to 2162Config.refresh();163test("a6a6a6b6b6b6-");164165writeConf(5, 4, p1, p2);166test("a4a4a4a4a4b4b4b4b4b4-"); // user-provided max_retries == 5167test("a4a4b4b4-"); // tryLess to 2168Config.refresh();169test("a4a4a4a4a4b4b4b4b4b4-");170}171172/**173* Writes a krb5.conf file.174* @param max max_retries, -1 if not set175* @param to kdc_timeout, -1 if not set176* @param ports where KDCs listen on177*/178static void writeConf(int max, int to, int... ports) throws Exception {179180// content of krb5.conf181String conf = "";182183// Extra settings in [libdefaults]184String inDefaults = "";185186// Extra settings in [realms]187String inRealm = "";188189// We will randomly put extra settings only in [libdefaults],190// or in [realms] but with different values in [libdefaults],191// to prove that settings in [realms] override those in [libdefaults].192Random r = new Random();193194if (max > 0) {195if (r.nextBoolean()) {196inDefaults += "max_retries = " + max + "\n";197} else {198inRealm += " max_retries = " + max + "\n";199inDefaults += "max_retries = " + (max + 1) + "\n";200}201}202203if (to > 0) {204if (r.nextBoolean()) {205inDefaults += "kdc_timeout = " + to + "\n";206} else {207inRealm += " kdc_timeout = " + to + "\n";208inDefaults += "kdc_timeout = " + (to + 1) + "\n";209}210}211212if (udp) {213if (r.nextBoolean()) {214inDefaults += "udp_preference_limit = 10000\n";215} else if (r.nextBoolean()) {216inRealm += " udp_preference_limit = 10000\n";217inDefaults += "udp_preference_limit = 1\n";218} // else no settings means UDP219} else {220if (r.nextBoolean()) {221inDefaults += "udp_preference_limit = 1\n";222} else {223inRealm += " udp_preference_limit = 1\n";224inDefaults += "udp_preference_limit = 10000\n";225}226}227228conf = "[libdefaults]\n" +229"default_realm = " + OneKDC.REALM + "\n" +230inDefaults +231"\n" +232"[realms]\n" +233OneKDC.REALM + " = {\n";234235for (int port : ports) {236conf += " kdc = " + OneKDC.KDCHOST + ":" + port + "\n" +237inRealm;238}239240conf += "}\n";241242Files.write(Paths.get("alternative-krb5.conf"), conf.getBytes());243Config.refresh();244}245246/**247* One call of krb5 login. As long as the result matches one of expected,248* the test is considered as success. The grammar of expected is249*250* kdc#, timeout, kdc#, timeout, ..., optional "-" for failure251*/252static void test(String... expected) throws Exception {253254System.out.println("------------------TEST----------------------");255PrintStream oldOut = System.out;256boolean failed = false;257ByteArrayOutputStream bo = new ByteArrayOutputStream();258System.setOut(new PrintStream(bo));259try {260Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);261} catch (Exception e) {262failed = true;263} finally {264System.setOut(oldOut);265}266267String[] lines = new String(bo.toByteArray()).split("\n");268StringBuilder sb = new StringBuilder();269for (String line: lines) {270if (cm.match(line)) {271if (udp != cm.isUDP()) {272sb.append("x");273}274sb.append(cm.kdc()).append(cm.timeout());275}276}277if (failed) sb.append('-');278279String output = sb.toString();280281boolean found = false;282for (String ex : expected) {283if (output.matches(ex)) {284System.out.println("Expected: " + ex + ", actual " + output);285found = true;286break;287}288}289290if (!found) {291System.out.println("--------------- ERROR START -------------");292System.out.println(new String(bo.toByteArray()));293System.out.println("--------------- ERROR END ---------------");294throw new Exception("Does not match. Output is " + output);295}296}297298/**299* A helper class to match the krb5 debug output:300* >>> KDCCommunication: kdc=host UDP:11555, timeout=200,Attempt =1, #bytes=138301*302* Example:303* DebugMatcher cm = new DebugMatcher();304* cm.addPort(12345).addPort(11555);305* for (String line : debugOutput) {306* if (cm.match(line)) {307* System.out.printf("%c%d\n", cm.kdc(), cm.timeout());308* // shows b200 for the example above309* }310* }311*/312static class DebugMatcher {313314static final Pattern re = Pattern.compile(315">>> KDCCommunication: kdc=\\S+ (TCP|UDP):(\\d+), " +316"timeout=(\\d+),Attempt\\s*=(\\d+)");317318List<Integer> kdcPorts = new ArrayList<>();319Matcher matcher;320321/**322* Add KDC ports one by one. See {@link #kdc()}.323*/324DebugMatcher addPort(int port) {325if (port > 0) {326kdcPorts.add(port);327} else {328kdcPorts.clear();329}330return this;331}332333/**334* When a line matches the ">>> KDCCommunication:" pattern. After a335* match, the getters below can be called on this match.336*/337boolean match(String line) {338matcher = re.matcher(line);339return matcher.find();340}341342/**343* Protocol of this match, "UDP" or "TCP".344*/345boolean isUDP() {346return matcher.group(1).equals("UDP");347}348349/**350* KDC for this match, "a" for the one 1st added bt addPort(), "b"351* for second, etc. Undefined for not added.352*/353char kdc() {354int port = Integer.parseInt(matcher.group(2));355return (char) (kdcPorts.indexOf(port) + 'a');356}357358/**359* Timeout value for this match.360*/361int timeout() {362return Integer.parseInt(matcher.group(3));363}364}365}366367368