use of sun.security.krb5.PrincipalName in project jdk8u_jdk by JetBrains.
the class Credentials method acquireTGTFromCache.
/**
* Returns a TGT for the given client principal from a ticket cache.
*
* @param princ the client principal. A value of null means that the
* default principal name in the credentials cache will be used.
* @param ticketCache the path to the tickets file. A value
* of null will be accepted to indicate that the default
* path should be searched
* @returns the TGT credentials or null if none were found. If the tgt
* expired, it is the responsibility of the caller to determine this.
*/
public static Credentials acquireTGTFromCache(PrincipalName princ, String ticketCache) throws KrbException, IOException {
if (ticketCache == null) {
// The default ticket cache on Windows and Mac is not a file.
String os = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("os.name"));
if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS") || os.toUpperCase(Locale.ENGLISH).contains("OS X")) {
Credentials creds = acquireDefaultCreds();
if (creds == null) {
if (DEBUG) {
System.out.println(">>> Found no TGT's in LSA");
}
return null;
}
if (princ != null) {
if (creds.getClient().equals(princ)) {
if (DEBUG) {
System.out.println(">>> Obtained TGT from LSA: " + creds);
}
return creds;
} else {
if (DEBUG) {
System.out.println(">>> LSA contains TGT for " + creds.getClient() + " not " + princ);
}
return null;
}
} else {
if (DEBUG) {
System.out.println(">>> Obtained TGT from LSA: " + creds);
}
return creds;
}
}
}
/*
* Returns the appropriate cache. If ticketCache is null, it is the
* default cache otherwise it is the cache filename contained in it.
*/
CredentialsCache ccache = CredentialsCache.getInstance(princ, ticketCache);
if (ccache == null) {
return null;
}
sun.security.krb5.internal.ccache.Credentials tgtCred = ccache.getDefaultCreds();
if (tgtCred == null) {
return null;
}
if (EType.isSupported(tgtCred.getEType())) {
return tgtCred.setKrbCreds();
} else {
if (DEBUG) {
System.out.println(">>> unsupported key type found the default TGT: " + tgtCred.getEType());
}
return null;
}
}
use of sun.security.krb5.PrincipalName in project jdk8u_jdk by JetBrains.
the class KeyTabInputStream method readEntry.
KeyTabEntry readEntry(int entryLen, int ktVersion) throws IOException, RealmException {
index = entryLen;
if (index == 0) {
//in native implementation, when the last entry is deleted, a byte 0 is left.
return null;
}
if (index < 0) {
//in native implementation, when one of the entries is deleted, the entry length turns to be negative, and
//the fields are left with 0 bytes
skip(Math.abs(index));
return null;
}
//the number of service names.
int principalNum = read(2);
index -= 2;
if (ktVersion == KRB5_KT_VNO_1) {
//V1 includes realm in the count.
principalNum -= 1;
}
Realm realm = new Realm(readName());
String[] nameParts = new String[principalNum];
for (int i = 0; i < principalNum; i++) {
nameParts[i] = readName();
}
int nameType = read(4);
index -= 4;
PrincipalName service = new PrincipalName(nameType, nameParts, realm);
KerberosTime timeStamp = readTimeStamp();
int keyVersion = read() & 0xff;
index -= 1;
int keyType = read(2);
index -= 2;
int keyLength = read(2);
index -= 2;
byte[] keyblock = readKey(keyLength);
index -= keyLength;
// right, otherwise trust the new nonzero value.
if (index >= 4) {
int extKvno = read(4);
if (extKvno != 0) {
keyVersion = extKvno;
}
index -= 4;
}
// if index is negative, the keytab format must be wrong.
if (index < 0) {
throw new RealmException("Keytab is corrupted");
}
// ignore the left bytes.
skip(index);
return new KeyTabEntry(service, realm, timeStamp, keyVersion, keyType, keyblock);
}
use of sun.security.krb5.PrincipalName in project jdk8u_jdk by JetBrains.
the class KerberosClientKeyExchangeImpl method init.
/**
* Creates an instance of KerberosClientKeyExchange from its ASN.1 encoding.
* Used by ServerHandshaker to verify and obtain premaster secret.
*
* @param protocolVersion current protocol version
* @param clientVersion version requested by client in its ClientHello;
* used by premaster secret version check
* @param rand random number generator used for generating random
* premaster secret if ticket and/or premaster verification fails
* @param input inputstream from which to get ASN.1-encoded KerberosWrapper
* @param acc the AccessControlContext of the handshaker
* @param serviceCreds server's creds
*/
@Override
public void init(ProtocolVersion protocolVersion, ProtocolVersion clientVersion, SecureRandom rand, HandshakeInStream input, AccessControlContext acc, Object serviceCreds) throws IOException {
// Read ticket
encodedTicket = input.getBytes16();
if (debug != null && Debug.isOn("verbose")) {
Debug.println(System.out, "encoded Kerberos service ticket", encodedTicket);
}
EncryptionKey sessionKey = null;
try {
Ticket t = new Ticket(encodedTicket);
EncryptedData encPart = t.encPart;
PrincipalName ticketSname = t.sname;
final ServiceCreds creds = (ServiceCreds) serviceCreds;
final KerberosPrincipal princ = new KerberosPrincipal(ticketSname.toString());
// For bound service, permission already checked at setup
if (creds.getName() == null) {
SecurityManager sm = System.getSecurityManager();
try {
if (sm != null) {
// Eliminate dependency on ServicePermission
sm.checkPermission(Krb5Helper.getServicePermission(ticketSname.toString(), "accept"), acc);
}
} catch (SecurityException se) {
serviceCreds = null;
// Do not destroy keys. Will affect Subject
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Permission to access Kerberos" + " secret key denied");
}
throw new IOException("Kerberos service not allowedy");
}
}
KerberosKey[] serverKeys = AccessController.doPrivileged(new PrivilegedAction<KerberosKey[]>() {
@Override
public KerberosKey[] run() {
return creds.getKKeys(princ);
}
});
if (serverKeys.length == 0) {
throw new IOException("Found no key for " + princ + (creds.getName() == null ? "" : (", this keytab is for " + creds.getName() + " only")));
}
/*
* permission to access and use the secret key of the Kerberized
* "host" service is done in ServerHandshaker.getKerberosKeys()
* to ensure server has the permission to use the secret key
* before promising the client
*/
// See if we have the right key to decrypt the ticket to get
// the session key.
int encPartKeyType = encPart.getEType();
Integer encPartKeyVersion = encPart.getKeyVersionNumber();
KerberosKey dkey = null;
try {
dkey = findKey(encPartKeyType, encPartKeyVersion, serverKeys);
} catch (KrbException ke) {
// a kvno mismatch
throw new IOException("Cannot find key matching version number", ke);
}
if (dkey == null) {
// %%% Should print string repr of etype
throw new IOException("Cannot find key of appropriate type" + " to decrypt ticket - need etype " + encPartKeyType);
}
EncryptionKey secretKey = new EncryptionKey(encPartKeyType, dkey.getEncoded());
// Decrypt encPart using server's secret key
byte[] bytes = encPart.decrypt(secretKey, KeyUsage.KU_TICKET);
// Reset data stream after decryption, remove redundant bytes
byte[] temp = encPart.reset(bytes);
EncTicketPart encTicketPart = new EncTicketPart(temp);
// Record the Kerberos Principals
peerPrincipal = new KerberosPrincipal(encTicketPart.cname.getName());
localPrincipal = new KerberosPrincipal(ticketSname.getName());
sessionKey = encTicketPart.key;
if (debug != null && Debug.isOn("handshake")) {
System.out.println("server principal: " + ticketSname);
System.out.println("cname: " + encTicketPart.cname.toString());
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("KerberosWrapper error getting session key," + " generating random secret (" + e.getMessage() + ")");
}
sessionKey = null;
}
// XXX Read and ignore authenticator
input.getBytes16();
if (sessionKey != null) {
preMaster = new KerberosPreMasterSecret(protocolVersion, clientVersion, rand, input, sessionKey);
} else {
// Generate bogus premaster secret
preMaster = new KerberosPreMasterSecret(clientVersion, rand);
}
}
use of sun.security.krb5.PrincipalName in project jdk8u_jdk by JetBrains.
the class KerberosClientKeyExchangeImpl method getServiceTicket.
// Similar to sun.security.jgss.krb5.Krb5InitCredenetial/Krb5Context
private static KerberosTicket getServiceTicket(String serverName, final AccessControlContext acc) throws IOException {
if ("localhost".equals(serverName) || "localhost.localdomain".equals(serverName)) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Get the local hostname");
}
String localHost = java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
public String run() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (java.net.UnknownHostException e) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Warning," + " cannot get the local hostname: " + e.getMessage());
}
return null;
}
}
});
if (localHost != null) {
serverName = localHost;
}
}
// Resolve serverName (possibly in IP addr form) to Kerberos principal
// name for service with hostname
String serviceName = "host/" + serverName;
PrincipalName principal;
try {
principal = new PrincipalName(serviceName, PrincipalName.KRB_NT_SRV_HST);
} catch (SecurityException se) {
throw se;
} catch (Exception e) {
IOException ioe = new IOException("Invalid service principal" + " name: " + serviceName);
ioe.initCause(e);
throw ioe;
}
String realm = principal.getRealmAsString();
final String serverPrincipal = principal.toString();
final String tgsPrincipal = "krbtgt/" + realm + "@" + realm;
// use default
final String clientPrincipal = null;
// check permission to obtain a service ticket to initiate a
// context with the "host" service
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new ServicePermission(serverPrincipal, "initiate"), acc);
}
try {
KerberosTicket ticket = AccessController.doPrivileged(new PrivilegedExceptionAction<KerberosTicket>() {
public KerberosTicket run() throws Exception {
return Krb5Util.getTicketFromSubjectAndTgs(GSSCaller.CALLER_SSL_CLIENT, clientPrincipal, serverPrincipal, tgsPrincipal, acc);
}
});
if (ticket == null) {
throw new IOException("Failed to find any kerberos service" + " ticket for " + serverPrincipal);
}
return ticket;
} catch (PrivilegedActionException e) {
IOException ioe = new IOException("Attempt to obtain kerberos service ticket for " + serverPrincipal + " failed!");
ioe.initCause(e);
throw ioe;
}
}
use of sun.security.krb5.PrincipalName in project jdk8u_jdk by JetBrains.
the class KDC method writeKtab.
/**
* Writes or appends keys into a keytab.
* <p>
* Attention: This is the most basic one of a series of methods below on
* keytab creation or modification. All these methods reference krb5.conf
* settings. If you need to modify krb5.conf or switch to another krb5.conf
* later, please call <code>Config.refresh()</code> again. For example:
* <pre>
* kdc.writeKtab("/etc/kdc/ktab", true); // Config is initialized,
* System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf");
* Config.refresh();
* </pre>
* Inside this method there are 2 places krb5.conf is used:
* <ol>
* <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys
* <li> (Has workaround) Creating PrincipalName
* </ol>
* @param tab the keytab file name
* @param append true if append, otherwise, overwrite.
* @param names the names to write into, write all if names is empty
*/
public void writeKtab(String tab, boolean append, String... names) throws IOException, KrbException {
KeyTab ktab = append ? KeyTab.getInstance(tab) : KeyTab.create(tab);
Iterable<String> entries = (names.length != 0) ? Arrays.asList(names) : passwords.keySet();
for (String name : entries) {
char[] pass = passwords.get(name);
int kvno = 0;
if (Character.isDigit(pass[pass.length - 1])) {
kvno = pass[pass.length - 1] - '0';
}
PrincipalName pn = new PrincipalName(name, name.indexOf('/') < 0 ? PrincipalName.KRB_NT_UNKNOWN : PrincipalName.KRB_NT_SRV_HST);
ktab.addEntry(pn, getSalt(pn), pass, kvno, true);
}
ktab.save();
}
Aggregations