Path: blob/master/test/jdk/sun/security/krb5/auto/Context.java
41152 views
/*1* Copyright (c) 2008, 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 com.sun.security.auth.module.Krb5LoginModule;2425import java.io.IOException;26import java.lang.reflect.InvocationTargetException;27import java.lang.reflect.Method;28import java.security.PrivilegedActionException;29import java.security.PrivilegedExceptionAction;30import java.util.Arrays;31import java.util.HashMap;32import java.util.Map;33import javax.security.auth.Subject;34import javax.security.auth.callback.Callback;35import javax.security.auth.callback.CallbackHandler;36import javax.security.auth.callback.NameCallback;37import javax.security.auth.callback.PasswordCallback;38import javax.security.auth.callback.UnsupportedCallbackException;39import javax.security.auth.kerberos.KerberosKey;40import javax.security.auth.kerberos.KerberosTicket;41import javax.security.auth.login.LoginContext;42import org.ietf.jgss.GSSContext;43import org.ietf.jgss.GSSCredential;44import org.ietf.jgss.GSSException;45import org.ietf.jgss.GSSManager;46import org.ietf.jgss.GSSName;47import org.ietf.jgss.MessageProp;48import org.ietf.jgss.Oid;49import sun.security.jgss.krb5.Krb5Util;50import sun.security.krb5.Credentials;51import sun.security.krb5.internal.ccache.CredentialsCache;5253import java.io.ByteArrayInputStream;54import java.io.ByteArrayOutputStream;55import java.security.Principal;56import java.util.Set;5758/**59* Context of a JGSS subject, encapsulating Subject and GSSContext.60*61* Three "constructors", which acquire the (private) credentials and fill62* it into the Subject:63*64* 1. static fromJAAS(): Creates a Context using a JAAS login config entry65* 2. static fromUserPass(): Creates a Context using a username and a password66* 3. delegated(): A new context which uses the delegated credentials from a67* previously established acceptor Context68*69* Two context initiators, which create the GSSContext object inside:70*71* 1. startAsClient()72* 2. startAsServer()73*74* Privileged action:75* doAs(): Performs an action in the name of the Subject76*77* Handshake process:78* static handShake(initiator, acceptor)79*80* A four-phase typical data communication which includes all four GSS81* actions (wrap, unwrap, getMic and veryfyMiC):82* static transmit(message, from, to)83*/84public class Context {8586private Subject s;87private GSSContext x;88private String name;89private GSSCredential cred; // see static method delegated().9091static boolean usingStream = false;9293private Context() {}9495/**96* Using the delegated credentials from a previous acceptor97*/98public Context delegated() throws Exception {99Context out = new Context();100out.s = s;101try {102out.cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {103@Override104public GSSCredential run() throws Exception {105GSSCredential cred = x.getDelegCred();106if (cred == null && x.getCredDelegState() ||107cred != null && !x.getCredDelegState()) {108throw new Exception("getCredDelegState not match");109}110return cred;111}112});113} catch (PrivilegedActionException pae) {114throw pae.getException();115}116out.name = name + " as " + out.cred.getName().toString();117return out;118}119120/**121* No JAAS login at all, can be used to test JGSS without JAAS122*/123public static Context fromThinAir() throws Exception {124Context out = new Context();125out.s = new Subject();126return out;127}128129/**130* Logins with a JAAS login config entry name131*/132public static Context fromJAAS(final String name) throws Exception {133Context out = new Context();134out.name = name;135LoginContext lc = new LoginContext(name);136lc.login();137out.s = lc.getSubject();138return out;139}140141/**142* Logins with username/password as a new Subject143*/144public static Context fromUserPass(145String user, char[] pass, boolean storeKey) throws Exception {146return fromUserPass(new Subject(), user, pass, storeKey);147}148149/**150* Logins with username/password as an existing Subject. The151* same subject can be used multiple times to simulate multiple logins.152*/153public static Context fromUserPass(Subject s,154String user, char[] pass, boolean storeKey) throws Exception {155Context out = new Context();156out.name = user;157out.s = s;158Krb5LoginModule krb5 = new Krb5LoginModule();159Map<String, String> map = new HashMap<>();160Map<String, Object> shared = new HashMap<>();161162if (storeKey) {163map.put("storeKey", "true");164}165166if (pass != null) {167krb5.initialize(out.s, new CallbackHandler() {168@Override169public void handle(Callback[] callbacks)170throws IOException, UnsupportedCallbackException {171for (Callback cb: callbacks) {172if (cb instanceof NameCallback) {173((NameCallback)cb).setName(user);174} else if (cb instanceof PasswordCallback) {175((PasswordCallback)cb).setPassword(pass);176}177}178}179}, shared, map);180} else {181map.put("doNotPrompt", "true");182map.put("useTicketCache", "true");183if (user != null) {184map.put("principal", user);185}186krb5.initialize(out.s, null, shared, map);187}188189krb5.login();190krb5.commit();191192return out;193}194195/**196* Logins with username/keytab as an existing Subject. The197* same subject can be used multiple times to simulate multiple logins.198*/199public static Context fromUserKtab(200String user, String ktab, boolean storeKey) throws Exception {201return fromUserKtab(new Subject(), user, ktab, storeKey);202}203204/**205* Logins with username/keytab as a new subject,206*/207public static Context fromUserKtab(Subject s,208String user, String ktab, boolean storeKey) throws Exception {209Context out = new Context();210out.name = user;211out.s = s;212Krb5LoginModule krb5 = new Krb5LoginModule();213Map<String, String> map = new HashMap<>();214215map.put("isInitiator", "false");216map.put("doNotPrompt", "true");217map.put("useTicketCache", "false");218map.put("useKeyTab", "true");219map.put("keyTab", ktab);220map.put("principal", user);221if (storeKey) {222map.put("storeKey", "true");223}224225krb5.initialize(out.s, null, null, map);226krb5.login();227krb5.commit();228return out;229}230231/**232* Starts as a client233* @param target communication peer234* @param mech GSS mech235* @throws java.lang.Exception236*/237public void startAsClient(final String target, final Oid mech) throws Exception {238doAs(new Action() {239@Override240public byte[] run(Context me, byte[] dummy) throws Exception {241GSSManager m = GSSManager.getInstance();242me.x = m.createContext(243target.indexOf('@') < 0 ?244m.createName(target, null) :245m.createName(target, GSSName.NT_HOSTBASED_SERVICE),246mech,247cred,248GSSContext.DEFAULT_LIFETIME);249return null;250}251}, null);252}253254/**255* Starts as a server256* @param mech GSS mech257* @throws java.lang.Exception258*/259public void startAsServer(final Oid mech) throws Exception {260startAsServer(null, mech, false);261}262263public void startAsServer(final String name, final Oid mech) throws Exception {264startAsServer(name, mech, false);265}266/**267* Starts as a server with the specified service name268* @param name the service name269* @param mech GSS mech270* @throws java.lang.Exception271*/272public void startAsServer(final String name, final Oid mech, final boolean asInitiator) throws Exception {273doAs(new Action() {274@Override275public byte[] run(Context me, byte[] dummy) throws Exception {276GSSManager m = GSSManager.getInstance();277me.cred = m.createCredential(278name == null ? null :279(name.indexOf('@') < 0 ?280m.createName(name, null) :281m.createName(name, GSSName.NT_HOSTBASED_SERVICE)),282GSSCredential.INDEFINITE_LIFETIME,283mech,284asInitiator?285GSSCredential.INITIATE_AND_ACCEPT:286GSSCredential.ACCEPT_ONLY);287me.x = m.createContext(me.cred);288return null;289}290}, null);291}292293/**294* Accesses the internal GSSContext object. Currently it's used for --295*296* 1. calling requestXXX() before handshake297* 2. accessing source name298*299* Note: If the application needs to do any privileged call on this300* object, please use doAs(). Otherwise, it can be done directly. The301* methods listed above are all non-privileged calls.302*303* @return the GSSContext object304*/305public GSSContext x() {306return x;307}308309/**310* Accesses the internal subject.311* @return the subject312*/313public Subject s() {314return s;315}316317/**318* Returns the cred inside, if there is one319*/320public GSSCredential cred() {321return cred;322}323324/**325* Disposes the GSSContext within326* @throws org.ietf.jgss.GSSException327*/328public void dispose() throws GSSException {329x.dispose();330}331332/**333* Does something using the Subject inside334* @param action the action335* @param in the input byte336* @return the output byte337* @throws java.lang.Exception338*/339public byte[] doAs(final Action action, final byte[] in) throws Exception {340try {341return Subject.doAs(s, new PrivilegedExceptionAction<byte[]>() {342343@Override344public byte[] run() throws Exception {345return action.run(Context.this, in);346}347});348} catch (PrivilegedActionException pae) {349throw pae.getException();350}351}352353/**354* Prints status of GSSContext and Subject355* @throws java.lang.Exception356*/357public void status() throws Exception {358System.out.println("STATUS OF " + name.toUpperCase());359if (x != null) {360StringBuffer sb = new StringBuffer();361if (x.getAnonymityState()) {362sb.append("anon, ");363}364if (x.getConfState()) {365sb.append("conf, ");366}367if (x.getCredDelegState()) {368sb.append("deleg, ");369}370if (x.getIntegState()) {371sb.append("integ, ");372}373if (x.getMutualAuthState()) {374sb.append("mutual, ");375}376if (x.getReplayDetState()) {377sb.append("rep det, ");378}379if (x.getSequenceDetState()) {380sb.append("seq det, ");381}382System.out.println(" Context status of " + name + ": " + sb.toString());383if (x.isProtReady() || x.isEstablished()) {384System.out.println(" " + x.getSrcName() + " -> " + x.getTargName());385}386}387xstatus();388if (s != null) {389System.out.println("====== START SUBJECT CONTENT =====");390for (Principal p : s.getPrincipals()) {391System.out.println(" Principal: " + p);392}393for (Object o : s.getPublicCredentials()) {394System.out.println(" " + o.getClass());395System.out.println(" " + o);396}397System.out.println("====== Private Credentials Set ======");398for (Object o : s.getPrivateCredentials()) {399System.out.println(" " + o.getClass());400if (o instanceof KerberosTicket) {401KerberosTicket kt = (KerberosTicket) o;402System.out.println(" " + kt.getServer() + " for " + kt.getClient());403} else if (o instanceof KerberosKey) {404KerberosKey kk = (KerberosKey) o;405System.out.print(" " + kk.getKeyType() + " " + kk.getVersionNumber() + " " + kk.getAlgorithm() + " ");406for (byte b : kk.getEncoded()) {407System.out.printf("%02X", b & 0xff);408}409System.out.println();410} else if (o instanceof Map) {411Map map = (Map) o;412for (Object k : map.keySet()) {413System.out.println(" " + k + ": " + map.get(k));414}415} else {416System.out.println(" " + o);417}418}419System.out.println("====== END SUBJECT CONTENT =====");420}421}422423public void xstatus() throws Exception {424System.out.println(" Extended context status:");425if (x != null) {426try {427Class<?> clazz = Class.forName("com.sun.security.jgss.ExtendedGSSContext");428if (clazz.isAssignableFrom(x.getClass())) {429if (clazz.getMethod("getDelegPolicyState").invoke(x) == Boolean.TRUE) {430System.out.println(" deleg policy");431}432if (x.isEstablished()) {433Class<?> inqType = Class.forName("com.sun.security.jgss.InquireType");434Method inqMethod = clazz.getMethod("inquireSecContext", inqType);435for (Object o : inqType.getEnumConstants()) {436System.out.println(" " + o + ":");437try {438System.out.println(" " + inqMethod.invoke(x, o));439} catch (Exception e) {440System.out.println(e.getCause());441}442}443}444}445} catch (ClassNotFoundException cnfe) {446System.out.println(" -- ExtendedGSSContext not available");447}448}449if (cred != null) {450try {451Class<?> clazz2 = Class.forName("com.sun.security.jgss.ExtendedGSSCredential");452if (!clazz2.isAssignableFrom(cred.getClass())) {453throw new Exception("cred is not extended");454}455} catch (ClassNotFoundException cnfe) {456System.out.println(" -- ExtendedGSSCredential not available");457}458}459}460461public byte[] wrap(byte[] t, final boolean privacy)462throws Exception {463return doAs(new Action() {464@Override465public byte[] run(Context me, byte[] input) throws Exception {466System.out.printf("wrap %s privacy from %s: ", privacy?"with":"without", me.name);467MessageProp p1 = new MessageProp(0, privacy);468byte[] out;469if (usingStream) {470ByteArrayOutputStream os = new ByteArrayOutputStream();471me.x.wrap(new ByteArrayInputStream(input), os, p1);472out = os.toByteArray();473} else {474out = me.x.wrap(input, 0, input.length, p1);475}476System.out.println(printProp(p1));477if ((x.getConfState() && privacy) != p1.getPrivacy()) {478throw new Exception("unexpected privacy status");479}480return out;481}482}, t);483}484485public byte[] unwrap(byte[] t, final boolean privacyExpected)486throws Exception {487return doAs(new Action() {488@Override489public byte[] run(Context me, byte[] input) throws Exception {490System.out.printf("unwrap from %s", me.name);491MessageProp p1 = new MessageProp(0, true);492byte[] bytes;493if (usingStream) {494ByteArrayOutputStream os = new ByteArrayOutputStream();495me.x.unwrap(new ByteArrayInputStream(input), os, p1);496bytes = os.toByteArray();497} else {498bytes = me.x.unwrap(input, 0, input.length, p1);499}500System.out.println(printProp(p1));501if (p1.getPrivacy() != privacyExpected) {502throw new Exception("Unexpected privacy: " + p1.getPrivacy());503}504return bytes;505}506}, t);507}508509public byte[] getMic(byte[] t) throws Exception {510return doAs(new Action() {511@Override512public byte[] run(Context me, byte[] input) throws Exception {513MessageProp p1 = new MessageProp(0, true);514byte[] bytes;515p1 = new MessageProp(0, true);516System.out.printf("getMic from %s: ", me.name);517if (usingStream) {518ByteArrayOutputStream os = new ByteArrayOutputStream();519me.x.getMIC(new ByteArrayInputStream(input), os, p1);520bytes = os.toByteArray();521} else {522bytes = me.x.getMIC(input, 0, input.length, p1);523}524System.out.println(printProp(p1));525return bytes;526}527}, t);528}529530public void verifyMic(byte[] t, final byte[] msg) throws Exception {531doAs(new Action() {532@Override533public byte[] run(Context me, byte[] input) throws Exception {534MessageProp p1 = new MessageProp(0, true);535System.out.printf("verifyMic from %s: ", me.name);536if (usingStream) {537me.x.verifyMIC(new ByteArrayInputStream(input),538new ByteArrayInputStream(msg), p1);539} else {540me.x.verifyMIC(input, 0, input.length,541msg, 0, msg.length,542p1);543}544System.out.println(printProp(p1));545if (p1.isUnseqToken() || p1.isOldToken()546|| p1.isDuplicateToken() || p1.isGapToken()) {547throw new Exception("Wrong sequence number detected");548}549return null;550}551}, t);552}553554/**555* Transmits a message from one Context to another. The sender wraps the556* message and sends it to the receiver. The receiver unwraps it, creates557* a MIC of the clear text and sends it back to the sender. The sender558* verifies the MIC against the message sent earlier.559* @param message the message560* @param s1 the sender561* @param s2 the receiver562* @throws java.lang.Exception If anything goes wrong563*/564static public void transmit(String message, final Context s1,565final Context s2) throws Exception {566transmit(message.getBytes(), s1, s2);567}568569/**570* Transmits a message from one Context to another. The sender wraps the571* message and sends it to the receiver. The receiver unwraps it, creates572* a MIC of the clear text and sends it back to the sender. The sender573* verifies the MIC against the message sent earlier.574* @param messageBytes the message575* @param s1 the sender576* @param s2 the receiver577* @throws java.lang.Exception If anything goes wrong578*/579static public void transmit(byte[] messageBytes, final Context s1,580final Context s2) throws Exception {581System.out.printf("-------------------- TRANSMIT from %s to %s------------------------\n",582s1.name, s2.name);583byte[] wrapped = s1.wrap(messageBytes, true);584byte[] unwrapped = s2.unwrap(wrapped, s2.x.getConfState());585if (!Arrays.equals(messageBytes, unwrapped)) {586throw new Exception("wrap/unwrap mismatch");587}588byte[] mic = s2.getMic(unwrapped);589s1.verifyMic(mic, messageBytes);590}591592/**593* Returns a string description of a MessageProp object594* @param prop the object595* @return the description596*/597static public String printProp(MessageProp prop) {598StringBuffer sb = new StringBuffer();599sb.append("MessagePop: ");600sb.append("QOP="+ prop.getQOP() + ", ");601sb.append(prop.getPrivacy()?"privacy, ":"");602sb.append(prop.isDuplicateToken()?"dup, ":"");603sb.append(prop.isGapToken()?"gap, ":"");604sb.append(prop.isOldToken()?"old, ":"");605sb.append(prop.isUnseqToken()?"unseq, ":"");606if (prop.getMinorStatus() != 0) {607sb.append(prop.getMinorString()+ "(" + prop.getMinorStatus()+")");608}609return sb.toString();610}611612public Context impersonate(final String someone) throws Exception {613try {614GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {615@Override616public GSSCredential run() throws Exception {617GSSManager m = GSSManager.getInstance();618GSSName other = m.createName(someone, GSSName.NT_USER_NAME);619if (Context.this.cred == null) {620Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY);621}622return (GSSCredential)623Class.forName("com.sun.security.jgss.ExtendedGSSCredential")624.getMethod("impersonate", GSSName.class)625.invoke(Context.this.cred, other);626}627});628Context out = new Context();629out.s = s;630out.cred = creds;631out.name = name + " as " + out.cred.getName().toString();632return out;633} catch (PrivilegedActionException pae) {634Exception e = pae.getException();635if (e instanceof InvocationTargetException) {636throw (Exception)((InvocationTargetException) e).getTargetException();637} else {638throw e;639}640}641}642643public byte[] take(final byte[] in) throws Exception {644return doAs(new Action() {645@Override646public byte[] run(Context me, byte[] input) throws Exception {647if (me.x.isEstablished()) {648System.out.println(name + " side established");649if (input != null) {650throw new Exception("Context established but " +651"still receive token at " + name);652}653return null;654} else {655if (me.x.isInitiator()) {656System.out.println(name + " call initSecContext");657return me.x.initSecContext(input, 0, input.length);658} else {659System.out.println(name + " call acceptSecContext");660return me.x.acceptSecContext(input, 0, input.length);661}662}663}664}, in);665}666667/**668* Saves the tickets to a ccache file.669*670* @param file pathname of the ccache file671* @return true if created, false otherwise.672*/673public boolean ccache(String file) throws Exception {674Set<KerberosTicket> tickets675= s.getPrivateCredentials(KerberosTicket.class);676if (tickets != null && !tickets.isEmpty()) {677CredentialsCache cc = null;678for (KerberosTicket t : tickets) {679Credentials cred = Krb5Util.ticketToCreds(t);680if (cc == null) {681cc = CredentialsCache.create(cred.getClient(), file);682}683cc.update(cred.toCCacheCreds());684}685if (cc != null) {686cc.save();687return true;688}689}690return false;691}692693/**694* Handshake (security context establishment process) between two Contexts695* @param c the initiator696* @param s the acceptor697* @throws java.lang.Exception698*/699static public void handshake(final Context c, final Context s) throws Exception {700byte[] t = new byte[0];701while (true) {702if (t != null || !c.x.isEstablished()) t = c.take(t);703if (t != null || !s.x.isEstablished()) t = s.take(t);704if (c.x.isEstablished() && s.x.isEstablished()) break;705}706}707}708709710