feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,168 @@
/*
* Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
/**
* A principal identified by a distinguished name as specified by
* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
*
* <p>
* After successful authentication, a user {@link java.security.Principal}
* can be associated with a particular {@link javax.security.auth.Subject}
* to augment that <code>Subject</code> with an additional identity.
* Authorization decisions can then be based upon the
* <code>Principal</code>s that are associated with a <code>Subject</code>.
*
* <p>
* This class is immutable.
*
* @since 1.6
*/
@jdk.Exported
public final class LdapPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = 6820120005580754861L;
/**
* The principal's string name
*
* @serial
*/
private final String nameString;
/**
* The principal's name
*
* @serial
*/
private final LdapName name;
/**
* Creates an LDAP principal.
*
* @param name The principal's string distinguished name.
* @throws InvalidNameException If a syntax violation is detected.
* @exception NullPointerException If the <code>name</code> is
* <code>null</code>.
*/
public LdapPrincipal(String name) throws InvalidNameException {
if (name == null) {
throw new NullPointerException("null name is illegal");
}
this.name = getLdapName(name);
nameString = name;
}
/**
* Compares this principal to the specified object.
*
* @param object The object to compare this principal against.
* @return true if they are equal; false otherwise.
*/
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof LdapPrincipal) {
try {
return
name.equals(getLdapName(((LdapPrincipal)object).getName()));
} catch (InvalidNameException e) {
return false;
}
}
return false;
}
/**
* Computes the hash code for this principal.
*
* @return The principal's hash code.
*/
public int hashCode() {
return name.hashCode();
}
/**
* Returns the name originally used to create this principal.
*
* @return The principal's string name.
*/
public String getName() {
return nameString;
}
/**
* Creates a string representation of this principal's name in the format
* defined by <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
* If the name has zero components an empty string is returned.
*
* @return The principal's string name.
*/
public String toString() {
return name.toString();
}
// Create an LdapName object from a string distinguished name.
private LdapName getLdapName(String name) throws InvalidNameException {
return new LdapName(name);
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if ((name == null) || (nameString == null)) {
throw new InvalidObjectException(
"null name/nameString is illegal");
}
try {
if (!name.equals(getLdapName(nameString))) {
throw new InvalidObjectException("Inconsistent names");
}
} catch (InvalidNameException e) {
InvalidObjectException nse = new InvalidObjectException(
"Invalid Name");
nse.initCause(e);
throw nse;
}
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents the name of the Windows NT domain into which the
* user authenticated. This will be a domain name if the user logged
* into a Windows NT domain, a workgroup name if the user logged into
* a workgroup, or a machine name if the user logged into a standalone
* configuration.
*
* <p> Principals such as this <code>NTDomainPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTDomainPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -4408637351440771220L;
/**
* @serial
*/
private String name;
/**
* Create an <code>NTDomainPrincipal</code> with a Windows NT domain name.
*
* <p>
*
* @param name the Windows NT domain name for this user. <p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTDomainPrincipal(String name) {
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new NullPointerException(form.format(source));
}
this.name = name;
}
/**
* Return the Windows NT domain name for this
* <code>NTDomainPrincipal</code>.
*
* <p>
*
* @return the Windows NT domain name for this
* <code>NTDomainPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return a string representation of this <code>NTDomainPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>NTDomainPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTDomainPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTDomainPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTDomainPrincipal</code> and the two NTDomainPrincipals
* have the same name.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTDomainPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTDomainPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTDomainPrincipal))
return false;
NTDomainPrincipal that = (NTDomainPrincipal)o;
return name.equals(that.getName());
}
/**
* Return a hash code for this <code>NTDomainPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>NTDomainPrincipal</code>.
*/
public int hashCode() {
return this.getName().hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new InvalidObjectException(form.format(source));
}
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* <p> This class abstracts an NT security token
* and provides a mechanism to do same-process security impersonation.
*
*/
@jdk.Exported
public class NTNumericCredential {
private long impersonationToken;
/**
* Create an <code>NTNumericCredential</code> with an integer value.
*
* <p>
*
* @param token the Windows NT security token for this user. <p>
*
*/
public NTNumericCredential(long token) {
this.impersonationToken = token;
}
/**
* Return an integer representation of this
* <code>NTNumericCredential</code>.
*
* <p>
*
* @return an integer representation of this
* <code>NTNumericCredential</code>.
*/
public long getToken() {
return impersonationToken;
}
/**
* Return a string representation of this <code>NTNumericCredential</code>.
*
* <p>
*
* @return a string representation of this <code>NTNumericCredential</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTNumericCredential.name",
"sun.security.util.AuthResources"));
Object[] source = {Long.toString(impersonationToken)};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTNumericCredential</code>
* for equality. Returns true if the given object is also a
* <code>NTNumericCredential</code> and the two NTNumericCredentials
* represent the same NT security token.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTNumericCredential</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTNumericCredential</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTNumericCredential))
return false;
NTNumericCredential that = (NTNumericCredential)o;
if (impersonationToken == that.getToken())
return true;
return false;
}
/**
* Return a hash code for this <code>NTNumericCredential</code>.
*
* <p>
*
* @return a hash code for this <code>NTNumericCredential</code>.
*/
public int hashCode() {
return (int)this.impersonationToken;
}
}

View File

@@ -0,0 +1,185 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents information about a Windows NT user, group or realm.
*
* <p> Windows NT chooses to represent users, groups and realms (or domains)
* with not only common names, but also relatively unique numbers. These
* numbers are called Security IDentifiers, or SIDs. Windows NT
* also provides services that render these SIDs into string forms.
* This class represents these string forms.
*
* <p> Principals such as this <code>NTSid</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTSid implements Principal, java.io.Serializable {
private static final long serialVersionUID = 4412290580770249885L;
/**
* @serial
*/
private String sid;
/**
* Create an <code>NTSid</code> with a Windows NT SID.
*
* <p>
*
* @param stringSid the Windows NT SID. <p>
*
* @exception NullPointerException if the <code>String</code>
* is <code>null</code>.
*
* @exception IllegalArgumentException if the <code>String</code>
* has zero length.
*/
public NTSid (String stringSid) {
if (stringSid == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"stringSid"};
throw new NullPointerException(form.format(source));
}
if (stringSid.length() == 0) {
throw new IllegalArgumentException
(sun.security.util.ResourcesMgr.getString
("Invalid.NTSid.value",
"sun.security.util.AuthResources"));
}
sid = stringSid;
}
/**
* Return a string version of this <code>NTSid</code>.
*
* <p>
*
* @return a string version of this <code>NTSid</code>
*/
public String getName() {
return sid;
}
/**
* Return a string representation of this <code>NTSid</code>.
*
* <p>
*
* @return a string representation of this <code>NTSid</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTSid.name",
"sun.security.util.AuthResources"));
Object[] source = {sid};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTSid</code>
* for equality. Returns true if the given object is also a
* <code>NTSid</code> and the two NTSids have the same String
* representation.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTSid</code>.
*
* @return true if the specified Object is equal to this
* <code>NTSid</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTSid))
return false;
NTSid that = (NTSid)o;
return sid.equals(that.sid);
}
/**
* Return a hash code for this <code>NTSid</code>.
*
* <p>
*
* @return a hash code for this <code>NTSid</code>.
*/
public int hashCode() {
return sid.hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (sid == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"stringSid"};
throw new InvalidObjectException(form.format(source));
}
if (sid.length() == 0) {
throw new InvalidObjectException
(sun.security.util.ResourcesMgr.getString
("Invalid.NTSid.value",
"sun.security.util.AuthResources"));
}
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* <p> This class extends <code>NTSid</code>
* and represents a Windows NT user's domain SID.
*
* <p> An NT user only has a domain SID if in fact they are logged
* into an NT domain. If the user is logged into a workgroup or
* just a standalone configuration, they will NOT have a domain SID.
*
* <p> Principals such as this <code>NTSidDomainPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTSidDomainPrincipal extends NTSid {
private static final long serialVersionUID = 5247810785821650912L;
/**
* Create an <code>NTSidDomainPrincipal</code> with a Windows NT SID.
*
* <p>
*
* @param name a string version of the Windows NT SID for this
* user's domain.<p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTSidDomainPrincipal(String name) {
super(name);
}
/**
* Return a string representation of this <code>NTSidDomainPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>NTSidDomainPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTSidDomainPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {getName()};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTSidDomainPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTSidDomainPrincipal</code> and the two NTSidDomainPrincipals
* have the same SID.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTSidDomainPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTSidDomainPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTSidDomainPrincipal))
return false;
return super.equals(o);
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* <p> This class extends <code>NTSid</code>
* and represents one of the groups to which a Windows NT user belongs.
*
* <p> Principals such as this <code>NTSidGroupPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
* @see com.sun.security.auth.NTSid
*/
@jdk.Exported
public class NTSidGroupPrincipal extends NTSid {
private static final long serialVersionUID = -1373347438636198229L;
/**
* Create an <code>NTSidGroupPrincipal</code> with a Windows NT group name.
*
* <p>
*
* @param name the Windows NT group SID for this user. <p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTSidGroupPrincipal(String name) {
super(name);
}
/**
* Return a string representation of this <code>NTSidGroupPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>NTSidGroupPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTSidGroupPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {getName()};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTSidGroupPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTSidGroupPrincipal</code> and the two NTSidGroupPrincipals
* have the same SID.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTSidGroupPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTSidGroupPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTSidGroupPrincipal))
return false;
return super.equals(o);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* <p> This class extends <code>NTSid</code>
* and represents a Windows NT user's primary group SID.
*
* <p> Principals such as this <code>NTSidPrimaryGroupPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTSidPrimaryGroupPrincipal extends NTSid {
private static final long serialVersionUID = 8011978367305190527L;
/**
* Create an <code>NTSidPrimaryGroupPrincipal</code> with a Windows NT
* group SID.
*
* <p>
*
* @param name the primary Windows NT group SID for this user. <p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTSidPrimaryGroupPrincipal(String name) {
super(name);
}
/**
* Return a string representation of this
* <code>NTSidPrimaryGroupPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>NTSidPrimaryGroupPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTSidPrimaryGroupPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {getName()};
return form.format(source);
}
/**
* Compares the specified Object with this
* <code>NTSidPrimaryGroupPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTSidPrimaryGroupPrincipal</code> and the two
* NTSidPrimaryGroupPrincipals have the same SID.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTSidPrimaryGroupPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTSidPrimaryGroupPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTSidPrimaryGroupPrincipal))
return false;
return super.equals(o);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* <p> This class extends <code>NTSid</code>
* and represents a Windows NT user's SID.
*
* <p> Principals such as this <code>NTSidUserPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTSidUserPrincipal extends NTSid {
private static final long serialVersionUID = -5573239889517749525L;
/**
* Create an <code>NTSidUserPrincipal</code> with a Windows NT SID.
*
* <p>
*
* @param name a string version of the Windows NT SID for this user.<p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTSidUserPrincipal(String name) {
super(name);
}
/**
* Return a string representation of this <code>NTSidUserPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>NTSidUserPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTSidUserPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {getName()};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTSidUserPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTSidUserPrincipal</code> and the two NTSidUserPrincipals
* have the same SID.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTSidUserPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTSidUserPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTSidUserPrincipal))
return false;
return super.equals(o);
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a Windows NT user.
*
* <p> Principals such as this <code>NTUserPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class NTUserPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -8737649811939033735L;
/**
* @serial
*/
private String name;
/**
* Create an <code>NTUserPrincipal</code> with a Windows NT username.
*
* <p>
*
* @param name the Windows NT username for this user. <p>
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public NTUserPrincipal(String name) {
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new NullPointerException(form.format(source));
}
this.name = name;
}
/**
* Return the Windows NT username for this <code>NTPrincipal</code>.
*
* <p>
*
* @return the Windows NT username for this <code>NTPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return a string representation of this <code>NTPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>NTPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("NTUserPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
}
/**
* Compares the specified Object with this <code>NTUserPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>NTUserPrincipal</code> and the two NTUserPrincipals
* have the same name.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>NTPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>NTPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof NTUserPrincipal))
return false;
NTUserPrincipal that = (NTUserPrincipal)o;
return name.equals(that.getName());
}
/**
* Return a hash code for this <code>NTUserPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>NTUserPrincipal</code>.
*/
public int hashCode() {
return this.getName().hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new InvalidObjectException(form.format(source));
}
}
}

View File

@@ -0,0 +1,305 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.security.CodeSource;
import java.security.PermissionCollection;
import javax.security.auth.Subject;
/**
* This class represents a default implementation for
* <code>javax.security.auth.Policy</code>.
*
* <p> This object stores the policy for entire Java runtime,
* and is the amalgamation of multiple static policy
* configurations that resides in files.
* The algorithm for locating the policy file(s) and reading their
* information into this <code>Policy</code> object is:
*
* <ol>
* <li>
* Loop through the security properties,
* <i>auth.policy.url.1</i>, <i>auth.policy.url.2</i>, ...,
* <i>auth.policy.url.X</i>".
* Each property value specifies a <code>URL</code> pointing to a
* policy file to be loaded. Read in and load each policy.
*
* <li>
* The <code>java.lang.System</code> property <i>java.security.auth.policy</i>
* may also be set to a <code>URL</code> pointing to another policy file
* (which is the case when a user uses the -D switch at runtime).
* If this property is defined, and its use is allowed by the
* security property file (the Security property,
* <i>policy.allowSystemProperty</i> is set to <i>true</i>),
* also load that policy.
*
* <li>
* If the <i>java.security.auth.policy</i> property is defined using
* "==" (rather than "="), then ignore all other specified
* policies and only load this policy.
* </ol>
*
* Each policy file consists of one or more grant entries, each of
* which consists of a number of permission entries.
*
* <pre>
* grant signedBy "<b>alias</b>", codeBase "<b>URL</b>",
* principal <b>principalClass</b> "<b>principalName</b>",
* principal <b>principalClass</b> "<b>principalName</b>",
* ... {
*
* permission <b>Type</b> "<b>name</b> "<b>action</b>",
* signedBy "<b>alias</b>";
* permission <b>Type</b> "<b>name</b> "<b>action</b>",
* signedBy "<b>alias</b>";
* ....
* };
* </pre>
*
* All non-bold items above must appear as is (although case
* doesn't matter and some are optional, as noted below).
* Italicized items represent variable values.
*
* <p> A grant entry must begin with the word <code>grant</code>.
* The <code>signedBy</code> and <code>codeBase</code>
* name/value pairs are optional.
* If they are not present, then any signer (including unsigned code)
* will match, and any codeBase will match. Note that the
* <code>principal</code> name/value pair is not optional.
* This <code>Policy</code> implementation only permits
* Principal-based grant entries. Note that the <i>principalClass</i>
* may be set to the wildcard value, *, which allows it to match
* any <code>Principal</code> class. In addition, the <i>principalName</i>
* may also be set to the wildcard value, *, allowing it to match
* any <code>Principal</code> name. When setting the <i>principalName</i>
* to the *, do not surround the * with quotes.
*
* <p> A permission entry must begin with the word <code>permission</code>.
* The word <code><i>Type</i></code> in the template above is
* a specific permission type, such as <code>java.io.FilePermission</code>
* or <code>java.lang.RuntimePermission</code>.
*
* <p> The "<i>action</i>" is required for
* many permission types, such as <code>java.io.FilePermission</code>
* (where it specifies what type of file access that is permitted).
* It is not required for categories such as
* <code>java.lang.RuntimePermission</code>
* where it is not necessary - you either have the
* permission specified by the <code>"<i>name</i>"</code>
* value following the type name or you don't.
*
* <p> The <code>signedBy</code> name/value pair for a permission entry
* is optional. If present, it indicates a signed permission. That is,
* the permission class itself must be signed by the given alias in
* order for it to be granted. For example,
* suppose you have the following grant entry:
*
* <pre>
* grant principal foo.com.Principal "Duke" {
* permission Foo "foobar", signedBy "FooSoft";
* }
* </pre>
*
* <p> Then this permission of type <i>Foo</i> is granted if the
* <code>Foo.class</code> permission has been signed by the
* "FooSoft" alias, or if <code>Foo.class</code> is a
* system class (i.e., is found on the CLASSPATH).
*
* <p> Items that appear in an entry must appear in the specified order
* (<code>permission</code>, <i>Type</i>, "<i>name</i>", and
* "<i>action</i>"). An entry is terminated with a semicolon.
*
* <p> Case is unimportant for the identifiers (<code>permission</code>,
* <code>signedBy</code>, <code>codeBase</code>, etc.) but is
* significant for the <i>Type</i>
* or for any string that is passed in as a value. <p>
*
* <p> An example of two entries in a policy configuration file is
* <pre>
* // if the code is comes from "foo.com" and is running as "Duke",
* // grant it read/write to all files in /tmp.
*
* grant codeBase "foo.com", principal foo.com.Principal "Duke" {
* permission java.io.FilePermission "/tmp/*", "read,write";
* };
*
* // grant any code running as "Duke" permission to read
* // the "java.vendor" Property.
*
* grant principal foo.com.Principal "Duke" {
* permission java.util.PropertyPermission "java.vendor";
* </pre>
*
* <p> This <code>Policy</code> implementation supports
* special handling for PrivateCredentialPermissions.
* If a grant entry is configured with a
* <code>PrivateCredentialPermission</code>,
* and the "Principal Class/Principal Name" for that
* <code>PrivateCredentialPermission</code> is "self",
* then the entry grants the specified <code>Subject</code> permission to
* access its own private Credential. For example,
* the following grants the <code>Subject</code> "Duke"
* access to its own a.b.Credential.
*
* <pre>
* grant principal foo.com.Principal "Duke" {
* permission javax.security.auth.PrivateCredentialPermission
* "a.b.Credential self",
* "read";
* };
* </pre>
*
* The following grants the <code>Subject</code> "Duke"
* access to all of its own private Credentials:
*
* <pre>
* grant principal foo.com.Principal "Duke" {
* permission javax.security.auth.PrivateCredentialPermission
* "* self",
* "read";
* };
* </pre>
*
* The following grants all Subjects authenticated as a
* <code>SolarisPrincipal</code> (regardless of their respective names)
* permission to access their own private Credentials:
*
* <pre>
* grant principal com.sun.security.auth.SolarisPrincipal * {
* permission javax.security.auth.PrivateCredentialPermission
* "* self",
* "read";
* };
* </pre>
*
* The following grants all Subjects permission to access their own
* private Credentials:
*
* <pre>
* grant principal * * {
* permission javax.security.auth.PrivateCredentialPermission
* "* self",
* "read";
* };
* </pre>
* @deprecated As of JDK&nbsp;1.4, replaced by
* <code>sun.security.provider.PolicyFile</code>.
* This class is entirely deprecated.
*
* @see java.security.CodeSource
* @see java.security.Permissions
* @see java.security.ProtectionDomain
* @see java.security.Security security properties
*/
@jdk.Exported(false)
@Deprecated
public class PolicyFile extends javax.security.auth.Policy {
private final sun.security.provider.AuthPolicyFile apf;
/**
* Initializes the Policy object and reads the default policy
* configuration file(s) into the Policy object.
*/
public PolicyFile() {
apf = new sun.security.provider.AuthPolicyFile();
}
/**
* Refreshes the policy object by re-reading all the policy files.
*
* <p>
*
* @exception SecurityException if the caller doesn't have permission
* to refresh the <code>Policy</code>.
*/
@Override
public void refresh() {
apf.refresh();
}
/**
* Examines this <code>Policy</code> and returns the Permissions granted
* to the specified <code>Subject</code> and <code>CodeSource</code>.
*
* <p> Permissions for a particular <i>grant</i> entry are returned
* if the <code>CodeSource</code> constructed using the codebase and
* signedby values specified in the entry <code>implies</code>
* the <code>CodeSource</code> provided to this method, and if the
* <code>Subject</code> provided to this method contains all of the
* Principals specified in the entry.
*
* <p> The <code>Subject</code> provided to this method contains all
* of the Principals specified in the entry if, for each
* <code>Principal</code>, "P1", specified in the <i>grant</i> entry
* one of the following two conditions is met:
*
* <p>
* <ol>
* <li> the <code>Subject</code> has a
* <code>Principal</code>, "P2", where
* <code>P2.getClass().getName()</code> equals the
* P1's class name, and where
* <code>P2.getName()</code> equals the P1's name.
*
* <li> P1 implements
* <code>com.sun.security.auth.PrincipalComparator</code>,
* and <code>P1.implies</code> the provided <code>Subject</code>.
* </ol>
*
* <p> Note that this <code>Policy</code> implementation has
* special handling for PrivateCredentialPermissions.
* When this method encounters a <code>PrivateCredentialPermission</code>
* which specifies "self" as the <code>Principal</code> class and name,
* it does not add that <code>Permission</code> to the returned
* <code>PermissionCollection</code>. Instead, it builds
* a new <code>PrivateCredentialPermission</code>
* for each <code>Principal</code> associated with the provided
* <code>Subject</code>. Each new <code>PrivateCredentialPermission</code>
* contains the same Credential class as specified in the
* originally granted permission, as well as the Class and name
* for the respective <code>Principal</code>.
*
* <p>
*
* @param subject the Permissions granted to this <code>Subject</code>
* and the additionally provided <code>CodeSource</code>
* are returned. <p>
*
* @param codesource the Permissions granted to this <code>CodeSource</code>
* and the additionally provided <code>Subject</code>
* are returned.
*
* @return the Permissions granted to the provided <code>Subject</code>
* <code>CodeSource</code>.
*/
@Override
public PermissionCollection getPermissions(final Subject subject,
final CodeSource codesource) {
return apf.getPermissions(subject, codesource);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
/**
* An object that implements the <code>java.security.Principal</code>
* interface typically also implements this interface to provide
* a means for comparing that object to a specified <code>Subject</code>.
*
* <p> The comparison is achieved via the <code>implies</code> method.
* The implementation of the <code>implies</code> method determines
* whether this object "implies" the specified <code>Subject</code>.
* One example application of this method may be for
* a "group" object to imply a particular <code>Subject</code>
* if that <code>Subject</code> belongs to the group.
* Another example application of this method would be for
* "role" object to imply a particular <code>Subject</code>
* if that <code>Subject</code> is currently acting in that role.
*
* <p> Although classes that implement this interface typically
* also implement the <code>java.security.Principal</code> interface,
* it is not required. In other words, classes may implement the
* <code>java.security.Principal</code> interface by itself,
* the <code>PrincipalComparator</code> interface by itself,
* or both at the same time.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public interface PrincipalComparator {
/**
* Check if the specified <code>Subject</code> is implied by
* this object.
*
* <p>
*
* @return true if the specified <code>Subject</code> is implied by
* this object, or false otherwise.
*/
boolean implies(javax.security.auth.Subject subject);
}

View File

@@ -0,0 +1,217 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a user's Solaris group identification number (GID).
*
* <p> Principals such as this <code>SolarisNumericGroupPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
* @deprecated As of JDK&nbsp;1.4, replaced by
* {@link UnixNumericGroupPrincipal}.
* This class is entirely deprecated.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported(false)
@Deprecated
public class SolarisNumericGroupPrincipal implements
Principal,
java.io.Serializable {
private static final long serialVersionUID = 2345199581042573224L;
private static final java.util.ResourceBundle rb =
java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<java.util.ResourceBundle>() {
public java.util.ResourceBundle run() {
return (java.util.ResourceBundle.getBundle
("sun.security.util.AuthResources"));
}
});
/**
* @serial
*/
private String name;
/**
* @serial
*/
private boolean primaryGroup;
/**
* Create a <code>SolarisNumericGroupPrincipal</code> using a
* <code>String</code> representation of the user's
* group identification number (GID).
*
* <p>
*
* @param name the user's group identification number (GID)
* for this user. <p>
*
* @param primaryGroup true if the specified GID represents the
* primary group to which this user belongs.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public SolarisNumericGroupPrincipal(String name, boolean primaryGroup) {
if (name == null)
throw new NullPointerException(rb.getString("provided.null.name"));
this.name = name;
this.primaryGroup = primaryGroup;
}
/**
* Create a <code>SolarisNumericGroupPrincipal</code> using a
* long representation of the user's group identification number (GID).
*
* <p>
*
* @param name the user's group identification number (GID) for this user
* represented as a long. <p>
*
* @param primaryGroup true if the specified GID represents the
* primary group to which this user belongs.
*
*/
public SolarisNumericGroupPrincipal(long name, boolean primaryGroup) {
this.name = (new Long(name)).toString();
this.primaryGroup = primaryGroup;
}
/**
* Return the user's group identification number (GID) for this
* <code>SolarisNumericGroupPrincipal</code>.
*
* <p>
*
* @return the user's group identification number (GID) for this
* <code>SolarisNumericGroupPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return the user's group identification number (GID) for this
* <code>SolarisNumericGroupPrincipal</code> as a long.
*
* <p>
*
* @return the user's group identification number (GID) for this
* <code>SolarisNumericGroupPrincipal</code> as a long.
*/
public long longValue() {
return ((new Long(name)).longValue());
}
/**
* Return whether this group identification number (GID) represents
* the primary group to which this user belongs.
*
* <p>
*
* @return true if this group identification number (GID) represents
* the primary group to which this user belongs,
* or false otherwise.
*/
public boolean isPrimaryGroup() {
return primaryGroup;
}
/**
* Return a string representation of this
* <code>SolarisNumericGroupPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>SolarisNumericGroupPrincipal</code>.
*/
public String toString() {
return((primaryGroup ?
rb.getString
("SolarisNumericGroupPrincipal.Primary.Group.") + name :
rb.getString
("SolarisNumericGroupPrincipal.Supplementary.Group.") + name));
}
/**
* Compares the specified Object with this
* <code>SolarisNumericGroupPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>SolarisNumericGroupPrincipal</code> and the two
* SolarisNumericGroupPrincipals
* have the same group identification number (GID).
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>SolarisNumericGroupPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>SolarisNumericGroupPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof SolarisNumericGroupPrincipal))
return false;
SolarisNumericGroupPrincipal that = (SolarisNumericGroupPrincipal)o;
if (this.getName().equals(that.getName()) &&
this.isPrimaryGroup() == that.isPrimaryGroup())
return true;
return false;
}
/**
* Return a hash code for this <code>SolarisNumericGroupPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>SolarisNumericGroupPrincipal</code>.
*/
public int hashCode() {
return toString().hashCode();
}
}

View File

@@ -0,0 +1,183 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a user's Solaris identification number (UID).
*
* <p> Principals such as this <code>SolarisNumericUserPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
* @deprecated As of JDK&nbsp;1.4, replaced by
* {@link UnixNumericUserPrincipal}.
* This class is entirely deprecated.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported(false)
@Deprecated
public class SolarisNumericUserPrincipal implements
Principal,
java.io.Serializable {
private static final long serialVersionUID = -3178578484679887104L;
private static final java.util.ResourceBundle rb =
java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<java.util.ResourceBundle>() {
public java.util.ResourceBundle run() {
return (java.util.ResourceBundle.getBundle
("sun.security.util.AuthResources"));
}
});
/**
* @serial
*/
private String name;
/**
* Create a <code>SolarisNumericUserPrincipal</code> using a
* <code>String</code> representation of the
* user's identification number (UID).
*
* <p>
*
* @param name the user identification number (UID) for this user.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public SolarisNumericUserPrincipal(String name) {
if (name == null)
throw new NullPointerException(rb.getString("provided.null.name"));
this.name = name;
}
/**
* Create a <code>SolarisNumericUserPrincipal</code> using a
* long representation of the user's identification number (UID).
*
* <p>
*
* @param name the user identification number (UID) for this user
* represented as a long.
*/
public SolarisNumericUserPrincipal(long name) {
this.name = (new Long(name)).toString();
}
/**
* Return the user identification number (UID) for this
* <code>SolarisNumericUserPrincipal</code>.
*
* <p>
*
* @return the user identification number (UID) for this
* <code>SolarisNumericUserPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return the user identification number (UID) for this
* <code>SolarisNumericUserPrincipal</code> as a long.
*
* <p>
*
* @return the user identification number (UID) for this
* <code>SolarisNumericUserPrincipal</code> as a long.
*/
public long longValue() {
return ((new Long(name)).longValue());
}
/**
* Return a string representation of this
* <code>SolarisNumericUserPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>SolarisNumericUserPrincipal</code>.
*/
public String toString() {
return(rb.getString("SolarisNumericUserPrincipal.") + name);
}
/**
* Compares the specified Object with this
* <code>SolarisNumericUserPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>SolarisNumericUserPrincipal</code> and the two
* SolarisNumericUserPrincipals
* have the same user identification number (UID).
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>SolarisNumericUserPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>SolarisNumericUserPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof SolarisNumericUserPrincipal))
return false;
SolarisNumericUserPrincipal that = (SolarisNumericUserPrincipal)o;
if (this.getName().equals(that.getName()))
return true;
return false;
}
/**
* Return a hash code for this <code>SolarisNumericUserPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>SolarisNumericUserPrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
}

View File

@@ -0,0 +1,147 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a Solaris user.
*
* <p> Principals such as this <code>SolarisPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @deprecated As of JDK&nbsp;1.4, replaced by
* {@link UnixPrincipal}.
* This class is entirely deprecated.
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported(false)
@Deprecated
public class SolarisPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -7840670002439379038L;
private static final java.util.ResourceBundle rb =
java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<java.util.ResourceBundle>() {
public java.util.ResourceBundle run() {
return (java.util.ResourceBundle.getBundle
("sun.security.util.AuthResources"));
}
});
/**
* @serial
*/
private String name;
/**
* Create a SolarisPrincipal with a Solaris username.
*
* <p>
*
* @param name the Unix username for this user.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public SolarisPrincipal(String name) {
if (name == null)
throw new NullPointerException(rb.getString("provided.null.name"));
this.name = name;
}
/**
* Return the Unix username for this <code>SolarisPrincipal</code>.
*
* <p>
*
* @return the Unix username for this <code>SolarisPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return a string representation of this <code>SolarisPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>SolarisPrincipal</code>.
*/
public String toString() {
return(rb.getString("SolarisPrincipal.") + name);
}
/**
* Compares the specified Object with this <code>SolarisPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>SolarisPrincipal</code> and the two SolarisPrincipals
* have the same username.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>SolarisPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>SolarisPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof SolarisPrincipal))
return false;
SolarisPrincipal that = (SolarisPrincipal)o;
if (this.getName().equals(that.getName()))
return true;
return false;
}
/**
* Return a hash code for this <code>SolarisPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>SolarisPrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a user's Unix group identification number (GID).
*
* <p> Principals such as this <code>UnixNumericGroupPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class UnixNumericGroupPrincipal implements
Principal,
java.io.Serializable {
private static final long serialVersionUID = 3941535899328403223L;
/**
* @serial
*/
private String name;
/**
* @serial
*/
private boolean primaryGroup;
/**
* Create a <code>UnixNumericGroupPrincipal</code> using a
* <code>String</code> representation of the user's
* group identification number (GID).
*
* <p>
*
* @param name the user's group identification number (GID)
* for this user. <p>
*
* @param primaryGroup true if the specified GID represents the
* primary group to which this user belongs.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public UnixNumericGroupPrincipal(String name, boolean primaryGroup) {
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new NullPointerException(form.format(source));
}
this.name = name;
this.primaryGroup = primaryGroup;
}
/**
* Create a <code>UnixNumericGroupPrincipal</code> using a
* long representation of the user's group identification number (GID).
*
* <p>
*
* @param name the user's group identification number (GID) for this user
* represented as a long. <p>
*
* @param primaryGroup true if the specified GID represents the
* primary group to which this user belongs.
*
*/
public UnixNumericGroupPrincipal(long name, boolean primaryGroup) {
this.name = (new Long(name)).toString();
this.primaryGroup = primaryGroup;
}
/**
* Return the user's group identification number (GID) for this
* <code>UnixNumericGroupPrincipal</code>.
*
* <p>
*
* @return the user's group identification number (GID) for this
* <code>UnixNumericGroupPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return the user's group identification number (GID) for this
* <code>UnixNumericGroupPrincipal</code> as a long.
*
* <p>
*
* @return the user's group identification number (GID) for this
* <code>UnixNumericGroupPrincipal</code> as a long.
*/
public long longValue() {
return ((new Long(name)).longValue());
}
/**
* Return whether this group identification number (GID) represents
* the primary group to which this user belongs.
*
* <p>
*
* @return true if this group identification number (GID) represents
* the primary group to which this user belongs,
* or false otherwise.
*/
public boolean isPrimaryGroup() {
return primaryGroup;
}
/**
* Return a string representation of this
* <code>UnixNumericGroupPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>UnixNumericGroupPrincipal</code>.
*/
public String toString() {
if (primaryGroup) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("UnixNumericGroupPrincipal.Primary.Group.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
} else {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("UnixNumericGroupPrincipal.Supplementary.Group.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
}
}
/**
* Compares the specified Object with this
* <code>UnixNumericGroupPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>UnixNumericGroupPrincipal</code> and the two
* UnixNumericGroupPrincipals
* have the same group identification number (GID).
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>UnixNumericGroupPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>UnixNumericGroupPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof UnixNumericGroupPrincipal))
return false;
UnixNumericGroupPrincipal that = (UnixNumericGroupPrincipal)o;
return this.getName().equals(that.getName()) &&
this.isPrimaryGroup() == that.isPrimaryGroup();
}
/**
* Return a hash code for this <code>UnixNumericGroupPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>UnixNumericGroupPrincipal</code>.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new InvalidObjectException(form.format(source));
}
}
}

View File

@@ -0,0 +1,200 @@
/*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a user's Unix identification number (UID).
*
* <p> Principals such as this <code>UnixNumericUserPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class UnixNumericUserPrincipal implements
Principal,
java.io.Serializable {
private static final long serialVersionUID = -4329764253802397821L;
/**
* @serial
*/
private String name;
/**
* Create a <code>UnixNumericUserPrincipal</code> using a
* <code>String</code> representation of the
* user's identification number (UID).
*
* <p>
*
* @param name the user identification number (UID) for this user.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public UnixNumericUserPrincipal(String name) {
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new NullPointerException(form.format(source));
}
this.name = name;
}
/**
* Create a <code>UnixNumericUserPrincipal</code> using a
* long representation of the user's identification number (UID).
*
* <p>
*
* @param name the user identification number (UID) for this user
* represented as a long.
*/
public UnixNumericUserPrincipal(long name) {
this.name = (new Long(name)).toString();
}
/**
* Return the user identification number (UID) for this
* <code>UnixNumericUserPrincipal</code>.
*
* <p>
*
* @return the user identification number (UID) for this
* <code>UnixNumericUserPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return the user identification number (UID) for this
* <code>UnixNumericUserPrincipal</code> as a long.
*
* <p>
*
* @return the user identification number (UID) for this
* <code>UnixNumericUserPrincipal</code> as a long.
*/
public long longValue() {
return ((new Long(name)).longValue());
}
/**
* Return a string representation of this
* <code>UnixNumericUserPrincipal</code>.
*
* <p>
*
* @return a string representation of this
* <code>UnixNumericUserPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("UnixNumericUserPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
}
/**
* Compares the specified Object with this
* <code>UnixNumericUserPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>UnixNumericUserPrincipal</code> and the two
* UnixNumericUserPrincipals
* have the same user identification number (UID).
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>UnixNumericUserPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>UnixNumericUserPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof UnixNumericUserPrincipal))
return false;
UnixNumericUserPrincipal that = (UnixNumericUserPrincipal)o;
return this.getName().equals(that.getName());
}
/**
* Return a hash code for this <code>UnixNumericUserPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>UnixNumericUserPrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new InvalidObjectException(form.format(source));
}
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a Unix user.
*
* <p> Principals such as this <code>UnixPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
@jdk.Exported
public class UnixPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -2951667807323493631L;
/**
* @serial
*/
private String name;
/**
* Create a UnixPrincipal with a Unix username.
*
* <p>
*
* @param name the Unix username for this user.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public UnixPrincipal(String name) {
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new NullPointerException(form.format(source));
}
this.name = name;
}
/**
* Return the Unix username for this <code>UnixPrincipal</code>.
*
* <p>
*
* @return the Unix username for this <code>UnixPrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return a string representation of this <code>UnixPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>UnixPrincipal</code>.
*/
public String toString() {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("UnixPrincipal.name",
"sun.security.util.AuthResources"));
Object[] source = {name};
return form.format(source);
}
/**
* Compares the specified Object with this <code>UnixPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>UnixPrincipal</code> and the two UnixPrincipals
* have the same username.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>UnixPrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>UnixPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof UnixPrincipal))
return false;
UnixPrincipal that = (UnixPrincipal)o;
return this.getName().equals(that.getName());
}
/**
* Return a hash code for this <code>UnixPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>UnixPrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
java.text.MessageFormat form = new java.text.MessageFormat
(sun.security.util.ResourcesMgr.getString
("invalid.null.input.value",
"sun.security.util.AuthResources"));
Object[] source = {"name"};
throw new InvalidObjectException(form.format(source));
}
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.security.Principal;
/**
* A user principal identified by a username or account name.
*
* <p>
* After successful authentication, a user {@link java.security.Principal}
* can be associated with a particular {@link javax.security.auth.Subject}
* to augment that <code>Subject</code> with an additional identity.
* Authorization decisions can then be based upon the
* <code>Principal</code>s that are associated with a <code>Subject</code>.
*
* <p>
* This class is immutable.
*
* @since 1.6
*/
@jdk.Exported
public final class UserPrincipal implements Principal, java.io.Serializable {
private static final long serialVersionUID = 892106070870210969L;
/**
* The principal's name
*
* @serial
*/
private final String name;
/**
* Creates a principal.
*
* @param name The principal's string name.
* @exception NullPointerException If the <code>name</code> is
* <code>null</code>.
*/
public UserPrincipal(String name) {
if (name == null) {
throw new NullPointerException("null name is illegal");
}
this.name = name;
}
/**
* Compares this principal to the specified object.
*
* @param object The object to compare this principal against.
* @return true if they are equal; false otherwise.
*/
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof UserPrincipal) {
return name.equals(((UserPrincipal)object).getName());
}
return false;
}
/**
* Returns a hash code for this principal.
*
* @return The principal's hash code.
*/
public int hashCode() {
return name.hashCode();
}
/**
* Returns the name of this principal.
*
* @return The principal's name.
*/
public String getName() {
return name;
}
/**
* Returns a string representation of this principal.
*
* @return The principal's name.
*/
public String toString() {
return name;
}
/**
* Restores the state of this object from the stream.
*
* @param stream the {@code ObjectInputStream} from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (name == null) {
throw new InvalidObjectException("null name is illegal");
}
}
}

View File

@@ -0,0 +1,185 @@
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth;
import java.security.Principal;
import sun.security.x509.X500Name;
/**
* <p> This class represents an X.500 <code>Principal</code>.
* X500Principals have names such as,
* "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"
* (RFC 1779 style).
*
* <p> Principals such as this <code>X500Principal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
* @deprecated A new X500Principal class is available in the Java platform.
* This X500Principal classs is entirely deprecated and
* is here to allow for a smooth transition to the new
* class.
* @see javax.security.auth.x500.X500Principal
*/
@jdk.Exported(false)
@Deprecated
public class X500Principal implements Principal, java.io.Serializable {
private static final long serialVersionUID = -8222422609431628648L;
private static final java.util.ResourceBundle rb =
java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<java.util.ResourceBundle>() {
public java.util.ResourceBundle run() {
return (java.util.ResourceBundle.getBundle
("sun.security.util.AuthResources"));
}
});
/**
* @serial
*/
private String name;
transient private X500Name thisX500Name;
/**
* Create a X500Principal with an X.500 Name,
* such as "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"
* (RFC 1779 style).
*
* <p>
*
* @param name the X.500 name
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>. <p>
*
* @exception IllegalArgumentException if the <code>name</code>
* is improperly specified.
*/
public X500Principal(String name) {
if (name == null)
throw new NullPointerException(rb.getString("provided.null.name"));
try {
thisX500Name = new X500Name(name);
} catch (Exception e) {
throw new IllegalArgumentException(e.toString());
}
this.name = name;
}
/**
* Return the Unix username for this <code>X500Principal</code>.
*
* <p>
*
* @return the Unix username for this <code>X500Principal</code>
*/
public String getName() {
return thisX500Name.getName();
}
/**
* Return a string representation of this <code>X500Principal</code>.
*
* <p>
*
* @return a string representation of this <code>X500Principal</code>.
*/
public String toString() {
return thisX500Name.toString();
}
/**
* Compares the specified Object with this <code>X500Principal</code>
* for equality.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>X500Principal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>X500Principal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (o instanceof X500Principal) {
X500Principal that = (X500Principal)o;
try {
X500Name thatX500Name = new X500Name(that.getName());
return thisX500Name.equals(thatX500Name);
} catch (Exception e) {
// any parsing exceptions, return false
return false;
}
} else if (o instanceof Principal) {
// this will return 'true' if 'o' is a sun.security.x509.X500Name
// and the X500Names are equal
return o.equals(thisX500Name);
}
return false;
}
/**
* Return a hash code for this <code>X500Principal</code>.
*
* <p>
*
* @return a hash code for this <code>X500Principal</code>.
*/
public int hashCode() {
return thisX500Name.hashCode();
}
/**
* Reads this object from a stream (i.e., deserializes it)
*/
private void readObject(java.io.ObjectInputStream s) throws
java.io.IOException,
java.io.NotActiveException,
ClassNotFoundException {
s.defaultReadObject();
// re-create thisX500Name
thisX500Name = new X500Name(name);
}
}

View File

@@ -0,0 +1,319 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.callback;
/* JAAS imports */
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/* Java imports */
import java.awt.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
* <p>
* Uses a Swing dialog window to query the user for answers to
* authentication questions.
* This can be used by a JAAS application to instantiate a
* CallbackHandler
* @see javax.security.auth.callback
* @deprecated This class will be removed in a future release.
*/
@jdk.Exported(false)
@Deprecated
public class DialogCallbackHandler implements CallbackHandler {
/* -- Fields -- */
/* The parent window, or null if using the default parent */
private Component parentComponent;
private static final int JPasswordFieldLen = 8 ;
private static final int JTextFieldLen = 8 ;
/* -- Methods -- */
/**
* Creates a callback dialog with the default parent window.
*/
public DialogCallbackHandler() { }
/**
* Creates a callback dialog and specify the parent window.
*
* @param parentComponent the parent window -- specify <code>null</code>
* for the default parent
*/
public DialogCallbackHandler(Component parentComponent) {
this.parentComponent = parentComponent;
}
/*
* An interface for recording actions to carry out if the user
* clicks OK for the dialog.
*/
private static interface Action {
void perform();
}
/**
* Handles the specified set of callbacks.
*
* @param callbacks the callbacks to handle
* @throws UnsupportedCallbackException if the callback is not an
* instance of NameCallback or PasswordCallback
*/
public void handle(Callback[] callbacks)
throws UnsupportedCallbackException
{
/* Collect messages to display in the dialog */
final List<Object> messages = new ArrayList<>(3);
/* Collection actions to perform if the user clicks OK */
final List<Action> okActions = new ArrayList<>(2);
ConfirmationInfo confirmation = new ConfirmationInfo();
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof TextOutputCallback) {
TextOutputCallback tc = (TextOutputCallback) callbacks[i];
switch (tc.getMessageType()) {
case TextOutputCallback.INFORMATION:
confirmation.messageType = JOptionPane.INFORMATION_MESSAGE;
break;
case TextOutputCallback.WARNING:
confirmation.messageType = JOptionPane.WARNING_MESSAGE;
break;
case TextOutputCallback.ERROR:
confirmation.messageType = JOptionPane.ERROR_MESSAGE;
break;
default:
throw new UnsupportedCallbackException(
callbacks[i], "Unrecognized message type");
}
messages.add(tc.getMessage());
} else if (callbacks[i] instanceof NameCallback) {
final NameCallback nc = (NameCallback) callbacks[i];
JLabel prompt = new JLabel(nc.getPrompt());
final JTextField name = new JTextField(JTextFieldLen);
String defaultName = nc.getDefaultName();
if (defaultName != null) {
name.setText(defaultName);
}
/*
* Put the prompt and name in a horizontal box,
* and add that to the set of messages.
*/
Box namePanel = Box.createHorizontalBox();
namePanel.add(prompt);
namePanel.add(name);
messages.add(namePanel);
/* Store the name back into the callback if OK */
okActions.add(new Action() {
public void perform() {
nc.setName(name.getText());
}
});
} else if (callbacks[i] instanceof PasswordCallback) {
final PasswordCallback pc = (PasswordCallback) callbacks[i];
JLabel prompt = new JLabel(pc.getPrompt());
final JPasswordField password =
new JPasswordField(JPasswordFieldLen);
if (!pc.isEchoOn()) {
password.setEchoChar('*');
}
Box passwordPanel = Box.createHorizontalBox();
passwordPanel.add(prompt);
passwordPanel.add(password);
messages.add(passwordPanel);
okActions.add(new Action() {
public void perform() {
pc.setPassword(password.getPassword());
}
});
} else if (callbacks[i] instanceof ConfirmationCallback) {
ConfirmationCallback cc = (ConfirmationCallback)callbacks[i];
confirmation.setCallback(cc);
if (cc.getPrompt() != null) {
messages.add(cc.getPrompt());
}
} else {
throw new UnsupportedCallbackException(
callbacks[i], "Unrecognized Callback");
}
}
/* Display the dialog */
int result = JOptionPane.showOptionDialog(
parentComponent,
messages.toArray(),
"Confirmation", /* title */
confirmation.optionType,
confirmation.messageType,
null, /* icon */
confirmation.options, /* options */
confirmation.initialValue); /* initialValue */
/* Perform the OK actions */
if (result == JOptionPane.OK_OPTION
|| result == JOptionPane.YES_OPTION)
{
Iterator<Action> iterator = okActions.iterator();
while (iterator.hasNext()) {
iterator.next().perform();
}
}
confirmation.handleResult(result);
}
/*
* Provides assistance with translating between JAAS and Swing
* confirmation dialogs.
*/
private static class ConfirmationInfo {
private int[] translations;
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object[] options = null;
Object initialValue = null;
int messageType = JOptionPane.QUESTION_MESSAGE;
private ConfirmationCallback callback;
/* Set the confirmation callback handler */
void setCallback(ConfirmationCallback callback)
throws UnsupportedCallbackException
{
this.callback = callback;
int confirmationOptionType = callback.getOptionType();
switch (confirmationOptionType) {
case ConfirmationCallback.YES_NO_OPTION:
optionType = JOptionPane.YES_NO_OPTION;
translations = new int[] {
JOptionPane.YES_OPTION, ConfirmationCallback.YES,
JOptionPane.NO_OPTION, ConfirmationCallback.NO,
JOptionPane.CLOSED_OPTION, ConfirmationCallback.NO
};
break;
case ConfirmationCallback.YES_NO_CANCEL_OPTION:
optionType = JOptionPane.YES_NO_CANCEL_OPTION;
translations = new int[] {
JOptionPane.YES_OPTION, ConfirmationCallback.YES,
JOptionPane.NO_OPTION, ConfirmationCallback.NO,
JOptionPane.CANCEL_OPTION, ConfirmationCallback.CANCEL,
JOptionPane.CLOSED_OPTION, ConfirmationCallback.CANCEL
};
break;
case ConfirmationCallback.OK_CANCEL_OPTION:
optionType = JOptionPane.OK_CANCEL_OPTION;
translations = new int[] {
JOptionPane.OK_OPTION, ConfirmationCallback.OK,
JOptionPane.CANCEL_OPTION, ConfirmationCallback.CANCEL,
JOptionPane.CLOSED_OPTION, ConfirmationCallback.CANCEL
};
break;
case ConfirmationCallback.UNSPECIFIED_OPTION:
options = callback.getOptions();
/*
* There's no way to know if the default option means
* to cancel the login, but there isn't a better way
* to guess this.
*/
translations = new int[] {
JOptionPane.CLOSED_OPTION, callback.getDefaultOption()
};
break;
default:
throw new UnsupportedCallbackException(
callback,
"Unrecognized option type: " + confirmationOptionType);
}
int confirmationMessageType = callback.getMessageType();
switch (confirmationMessageType) {
case ConfirmationCallback.WARNING:
messageType = JOptionPane.WARNING_MESSAGE;
break;
case ConfirmationCallback.ERROR:
messageType = JOptionPane.ERROR_MESSAGE;
break;
case ConfirmationCallback.INFORMATION:
messageType = JOptionPane.INFORMATION_MESSAGE;
break;
default:
throw new UnsupportedCallbackException(
callback,
"Unrecognized message type: " + confirmationMessageType);
}
}
/* Process the result returned by the Swing dialog */
void handleResult(int result) {
if (callback == null) {
return;
}
for (int i = 0; i < translations.length; i += 2) {
if (translations[i] == result) {
result = translations[i + 1];
break;
}
}
callback.setSelectedIndex(result);
}
}
}

View File

@@ -0,0 +1,262 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.callback;
/* JAAS imports */
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/* Java imports */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.util.Arrays;
import sun.security.util.Password;
/**
* <p>
* Prompts and reads from the command line for answers to authentication
* questions.
* This can be used by a JAAS application to instantiate a
* CallbackHandler
* @see javax.security.auth.callback
*/
@jdk.Exported
public class TextCallbackHandler implements CallbackHandler {
/**
* <p>Creates a callback handler that prompts and reads from the
* command line for answers to authentication questions.
* This can be used by JAAS applications to instantiate a
* CallbackHandler.
*/
public TextCallbackHandler() { }
/**
* Handles the specified set of callbacks.
*
* @param callbacks the callbacks to handle
* @throws IOException if an input or output error occurs.
* @throws UnsupportedCallbackException if the callback is not an
* instance of NameCallback or PasswordCallback
*/
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException
{
ConfirmationCallback confirmation = null;
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof TextOutputCallback) {
TextOutputCallback tc = (TextOutputCallback) callbacks[i];
String text;
switch (tc.getMessageType()) {
case TextOutputCallback.INFORMATION:
text = "";
break;
case TextOutputCallback.WARNING:
text = "Warning: ";
break;
case TextOutputCallback.ERROR:
text = "Error: ";
break;
default:
throw new UnsupportedCallbackException(
callbacks[i], "Unrecognized message type");
}
String message = tc.getMessage();
if (message != null) {
text += message;
}
if (text != null) {
System.err.println(text);
}
} else if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
if (nc.getDefaultName() == null) {
System.err.print(nc.getPrompt());
} else {
System.err.print(nc.getPrompt() +
" [" + nc.getDefaultName() + "] ");
}
System.err.flush();
String result = readLine();
if (result.equals("")) {
result = nc.getDefaultName();
}
nc.setName(result);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
System.err.print(pc.getPrompt());
System.err.flush();
pc.setPassword(Password.readPassword(System.in, pc.isEchoOn()));
} else if (callbacks[i] instanceof ConfirmationCallback) {
confirmation = (ConfirmationCallback) callbacks[i];
} else {
throw new UnsupportedCallbackException(
callbacks[i], "Unrecognized Callback");
}
}
/* Do the confirmation callback last. */
if (confirmation != null) {
doConfirmation(confirmation);
}
}
/* Reads a line of input */
private String readLine() throws IOException {
String result = new BufferedReader
(new InputStreamReader(System.in)).readLine();
if (result == null) {
throw new IOException("Cannot read from System.in");
}
return result;
}
private void doConfirmation(ConfirmationCallback confirmation)
throws IOException, UnsupportedCallbackException
{
String prefix;
int messageType = confirmation.getMessageType();
switch (messageType) {
case ConfirmationCallback.WARNING:
prefix = "Warning: ";
break;
case ConfirmationCallback.ERROR:
prefix = "Error: ";
break;
case ConfirmationCallback.INFORMATION:
prefix = "";
break;
default:
throw new UnsupportedCallbackException(
confirmation, "Unrecognized message type: " + messageType);
}
class OptionInfo {
String name;
int value;
OptionInfo(String name, int value) {
this.name = name;
this.value = value;
}
}
OptionInfo[] options;
int optionType = confirmation.getOptionType();
switch (optionType) {
case ConfirmationCallback.YES_NO_OPTION:
options = new OptionInfo[] {
new OptionInfo("Yes", ConfirmationCallback.YES),
new OptionInfo("No", ConfirmationCallback.NO)
};
break;
case ConfirmationCallback.YES_NO_CANCEL_OPTION:
options = new OptionInfo[] {
new OptionInfo("Yes", ConfirmationCallback.YES),
new OptionInfo("No", ConfirmationCallback.NO),
new OptionInfo("Cancel", ConfirmationCallback.CANCEL)
};
break;
case ConfirmationCallback.OK_CANCEL_OPTION:
options = new OptionInfo[] {
new OptionInfo("OK", ConfirmationCallback.OK),
new OptionInfo("Cancel", ConfirmationCallback.CANCEL)
};
break;
case ConfirmationCallback.UNSPECIFIED_OPTION:
String[] optionStrings = confirmation.getOptions();
options = new OptionInfo[optionStrings.length];
for (int i = 0; i < options.length; i++) {
options[i] = new OptionInfo(optionStrings[i], i);
}
break;
default:
throw new UnsupportedCallbackException(
confirmation, "Unrecognized option type: " + optionType);
}
int defaultOption = confirmation.getDefaultOption();
String prompt = confirmation.getPrompt();
if (prompt == null) {
prompt = "";
}
prompt = prefix + prompt;
if (!prompt.equals("")) {
System.err.println(prompt);
}
for (int i = 0; i < options.length; i++) {
if (optionType == ConfirmationCallback.UNSPECIFIED_OPTION) {
// defaultOption is an index into the options array
System.err.println(
i + ". " + options[i].name +
(i == defaultOption ? " [default]" : ""));
} else {
// defaultOption is an option value
System.err.println(
i + ". " + options[i].name +
(options[i].value == defaultOption ? " [default]" : ""));
}
}
System.err.print("Enter a number: ");
System.err.flush();
int result;
try {
result = Integer.parseInt(readLine());
if (result < 0 || result > (options.length - 1)) {
result = defaultOption;
}
result = options[result].value;
} catch (NumberFormatException e) {
result = defaultOption;
}
confirmation.setSelectedIndex(result);
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@jdk.Exported
package com.sun.security.auth.callback;

View File

@@ -0,0 +1,141 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.login;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import java.net.URI;
// NOTE: As of JDK 8, this class instantiates
// sun.security.provider.ConfigFile.Spi and forwards all methods to that
// implementation. All implementation fixes and enhancements should be made to
// sun.security.provider.ConfigFile.Spi and not this class.
// See JDK-8005117 for more information.
/**
* This class represents a default implementation for
* {@code javax.security.auth.login.Configuration}.
*
* <p> This object stores the runtime login configuration representation,
* and is the amalgamation of multiple static login
* configurations that resides in files.
* The algorithm for locating the login configuration file(s) and reading their
* information into this {@code Configuration} object is:
*
* <ol>
* <li>
* Loop through the security properties,
* <i>login.config.url.1</i>, <i>login.config.url.2</i>, ...,
* <i>login.config.url.X</i>.
* Each property value specifies a {@code URL} pointing to a
* login configuration file to be loaded. Read in and load
* each configuration.
*
* <li>
* The {@code java.lang.System} property
* <i>java.security.auth.login.config</i>
* may also be set to a {@code URL} pointing to another
* login configuration file
* (which is the case when a user uses the -D switch at runtime).
* If this property is defined, and its use is allowed by the
* security property file (the Security property,
* <i>policy.allowSystemProperty</i> is set to <i>true</i>),
* also load that login configuration.
*
* <li>
* If the <i>java.security.auth.login.config</i> property is defined using
* "==" (rather than "="), then ignore all other specified
* login configurations and only load this configuration.
*
* <li>
* If no system or security properties were set, try to read from the file,
* ${user.home}/.java.login.config, where ${user.home} is the value
* represented by the "user.home" System property.
* </ol>
*
* <p> The configuration syntax supported by this implementation
* is exactly that syntax specified in the
* {@code javax.security.auth.login.Configuration} class.
*
* @see javax.security.auth.login.LoginContext
* @see java.security.Security security properties
*/
@jdk.Exported
public class ConfigFile extends Configuration {
private final sun.security.provider.ConfigFile.Spi spi;
/**
* Create a new {@code Configuration} object.
*
* @throws SecurityException if the {@code Configuration} can not be
* initialized
*/
public ConfigFile() {
spi = new sun.security.provider.ConfigFile.Spi();
}
/**
* Create a new {@code Configuration} object from the specified {@code URI}.
*
* @param uri the {@code URI}
* @throws SecurityException if the {@code Configuration} can not be
* initialized
* @throws NullPointerException if {@code uri} is null
*/
public ConfigFile(URI uri) {
spi = new sun.security.provider.ConfigFile.Spi(uri);
}
/**
* Retrieve an entry from the {@code Configuration} using an application
* name as an index.
*
* @param applicationName the name used to index the {@code Configuration}
* @return an array of {@code AppConfigurationEntry} which correspond to
* the stacked configuration of {@code LoginModule}s for this
* application, or null if this application has no configured
* {@code LoginModule}s.
*/
@Override
public AppConfigurationEntry[] getAppConfigurationEntry
(String applicationName) {
return spi.engineGetAppConfigurationEntry(applicationName);
}
/**
* Refresh and reload the {@code Configuration} by re-reading all of the
* login configurations.
*
* @throws SecurityException if the caller does not have permission
* to refresh the {@code Configuration}
*/
@Override
public void refresh() {
spi.engineRefresh();
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@jdk.Exported
package com.sun.security.auth.login;

View File

@@ -0,0 +1,398 @@
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* Copyright (c) 1988 AT&T */
/* All Rights Reserved */
/**
* Implements the UNIX crypt(3) function, based on a direct port of the
* libc crypt function.
*
* <p>
* From the crypt man page:
* <p>
* crypt() is the password encryption routine, based on the NBS
* Data Encryption Standard, with variations intended (among
* other things) to frustrate use of hardware implementations
* of the DES for key search.
* <p>
* The first argument to crypt() is normally a user's typed
* password. The second is a 2-character string chosen from
* the set [a-zA-Z0-9./]. the salt string is used to perturb
* the DES algorithm in one
* of 4096 different ways, after which the password is used as
* the key to encrypt repeatedly a constant string. The
* returned value points to the encrypted password, in the same
* alphabet as the salt. The first two characters are the salt
* itself.
*
* @author Roland Schemers
*/
package com.sun.security.auth.module;
class Crypt {
/* EXPORT DELETE START */
private static final byte[] IP = {
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
};
private static final byte[] FP = {
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25,
};
private static final byte[] PC1_C = {
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
};
private static final byte[] PC1_D = {
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4,
};
private static final byte[] shifts = { 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1, };
private static final byte[] PC2_C = {
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
};
private static final byte[] PC2_D = {
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32,
};
private byte[] C = new byte[28];
private byte[] D = new byte[28];
private byte[] KS;
private byte[] E = new byte[48];
private static final byte[] e2 = {
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9,10,11,12,13,
12,13,14,15,16,17,
16,17,18,19,20,21,
20,21,22,23,24,25,
24,25,26,27,28,29,
28,29,30,31,32, 1,
};
private void setkey(byte[] key) {
int i, j, k;
byte t;
if (KS == null) {
KS = new byte[16*48];
}
for (i = 0; i < 28; i++) {
C[i] = key[PC1_C[i]-1];
D[i] = key[PC1_D[i]-1];
}
for (i = 0; i < 16; i++) {
for (k = 0; k < shifts[i]; k++) {
t = C[0];
for (j = 0; j < 28-1; j++)
C[j] = C[j+1];
C[27] = t;
t = D[0];
for (j = 0; j < 28-1; j++)
D[j] = D[j+1];
D[27] = t;
}
for (j = 0; j < 24; j++) {
int index = i * 48;
KS[index+j] = C[PC2_C[j]-1];
KS[index+j+24] = D[PC2_D[j]-28-1];
}
}
for (i = 0; i < 48; i++)
E[i] = e2[i];
}
private static final byte[][] S = {
{14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13},
{15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9},
{10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12},
{7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14},
{2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3},
{12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13},
{4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12},
{13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11},
};
private static final byte[] P = {
16, 7,20,21,
29,12,28,17,
1,15,23,26,
5,18,31,10,
2, 8,24,14,
32,27, 3, 9,
19,13,30, 6,
22,11, 4,25,
};
private byte[] L = new byte[64];
private byte[] tempL = new byte[32];
private byte[] f = new byte[32];
private byte[] preS = new byte[48];
private void encrypt(byte[] block,int fake) {
int i;
int t, j, k;
int R = 32; // &L[32]
if (KS == null) {
KS = new byte[16*48];
}
for(j=0; j < 64; j++) {
L[j] = block[IP[j]-1];
}
for(i=0; i < 16; i++) {
int index = i * 48;
for(j=0; j < 32; j++) {
tempL[j] = L[R+j];
}
for(j=0; j < 48; j++) {
preS[j] = (byte) (L[R+E[j]-1] ^ KS[index+j]);
}
for(j=0; j < 8; j++) {
t = 6*j;
k = S[j][(preS[t+0]<<5)+
(preS[t+1]<<3)+
(preS[t+2]<<2)+
(preS[t+3]<<1)+
(preS[t+4]<<0)+
(preS[t+5]<<4)];
t = 4*j;
f[t+0] = (byte) ((k>>3)&01);
f[t+1] = (byte) ((k>>2)&01);
f[t+2] = (byte) ((k>>1)&01);
f[t+3] = (byte) ((k>>0)&01);
}
for(j=0; j < 32; j++) {
L[R+j] = (byte) (L[j] ^ f[P[j]-1]);
}
for(j=0; j < 32; j++) {
L[j] = tempL[j];
}
}
for(j=0; j < 32; j++) {
t = L[j];
L[j] = L[R+j];
L[R+j] = (byte)t;
}
for(j=0; j < 64; j++) {
block[j] = L[FP[j]-1];
}
}
/* EXPORT DELETE END */
/**
* Creates a new Crypt object for use with the crypt method.
*
*/
public Crypt()
{
// does nothing at this time
super();
}
/**
* Implements the libc crypt(3) function.
*
* @param pw the password to "encrypt".
*
* @param salt the salt to use.
*
* @return A new byte[13] array that contains the encrypted
* password. The first two characters are the salt.
*
*/
public synchronized byte[] crypt(byte[] pw, byte[] salt) {
int c, i, j, pwi;
byte temp;
byte[] block = new byte[66];
byte[] iobuf = new byte[13];
/* EXPORT DELETE START */
pwi = 0;
for(i=0; pwi < pw.length && i < 64; pwi++) {
c = pw[pwi];
for(j=0; j < 7; j++, i++) {
block[i] = (byte) ((c>>(6-j)) & 01);
}
i++;
}
setkey(block);
for(i=0; i < 66; i++) {
block[i] = 0;
}
for(i=0; i < 2; i++) {
c = salt[i];
iobuf[i] = (byte)c;
if(c > 'Z')
c -= 6;
if(c > '9')
c -= 7;
c -= '.';
for(j=0; j < 6; j++) {
if( ((c>>j) & 01) != 0) {
temp = E[6*i+j];
E[6*i+j] = E[6*i+j+24];
E[6*i+j+24] = temp;
}
}
}
for(i=0; i < 25; i++) {
encrypt(block,0);
}
for(i=0; i < 11; i++) {
c = 0;
for(j=0; j < 6; j++) {
c <<= 1;
c |= block[6*i+j];
}
c += '.';
if(c > '9') {
c += 7;
}
if(c > 'Z') {
c += 6;
}
iobuf[i+2] = (byte)c;
}
//iobuf[i+2] = 0;
if(iobuf[1] == 0) {
iobuf[1] = iobuf[0];
}
/* EXPORT DELETE END */
return(iobuf);
}
/**
* program to test the crypt routine.
*
* The first parameter is the cleartext password, the second is
* the salt to use. The salt should be two characters from the
* set [a-zA-Z0-9./]. Outputs the crypt result.
*
* @param arg command line arguments.
*
*/
public static void main(String arg[]) {
if (arg.length!=2) {
System.err.println("usage: Crypt password salt");
System.exit(1);
}
Crypt c = new Crypt();
try {
byte result[] = c.crypt
(arg[0].getBytes("ISO-8859-1"), arg[1].getBytes("ISO-8859-1"));
for (int i=0; i<result.length; i++) {
System.out.println(" "+i+" "+(char)result[i]);
}
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen
}
}
}

View File

@@ -0,0 +1,779 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import javax.naming.*;
import javax.naming.directory.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.LinkedList;
import java.util.ResourceBundle;
import com.sun.security.auth.UnixPrincipal;
import com.sun.security.auth.UnixNumericUserPrincipal;
import com.sun.security.auth.UnixNumericGroupPrincipal;
/**
* <p> The module prompts for a username and password
* and then verifies the password against the password stored in
* a directory service configured under JNDI.
*
* <p> This <code>LoginModule</code> interoperates with
* any conformant JNDI service provider. To direct this
* <code>LoginModule</code> to use a specific JNDI service provider,
* two options must be specified in the login <code>Configuration</code>
* for this <code>LoginModule</code>.
* <pre>
* user.provider.url=<b>name_service_url</b>
* group.provider.url=<b>name_service_url</b>
* </pre>
*
* <b>name_service_url</b> specifies
* the directory service and path where this <code>LoginModule</code>
* can access the relevant user and group information. Because this
* <code>LoginModule</code> only performs one-level searches to
* find the relevant user information, the <code>URL</code>
* must point to a directory one level above where the user and group
* information is stored in the directory service.
* For example, to instruct this <code>LoginModule</code>
* to contact a NIS server, the following URLs must be specified:
* <pre>
* user.provider.url="nis://<b>NISServerHostName</b>/<b>NISDomain</b>/user"
* group.provider.url="nis://<b>NISServerHostName</b>/<b>NISDomain</b>/system/group"
* </pre>
*
* <b>NISServerHostName</b> specifies the server host name of the
* NIS server (for example, <i>nis.sun.com</i>, and <b>NISDomain</b>
* specifies the domain for that NIS server (for example, <i>jaas.sun.com</i>.
* To contact an LDAP server, the following URLs must be specified:
* <pre>
* user.provider.url="ldap://<b>LDAPServerHostName</b>/<b>LDAPName</b>"
* group.provider.url="ldap://<b>LDAPServerHostName</b>/<b>LDAPName</b>"
* </pre>
*
* <b>LDAPServerHostName</b> specifies the server host name of the
* LDAP server, which may include a port number
* (for example, <i>ldap.sun.com:389</i>),
* and <b>LDAPName</b> specifies the entry name in the LDAP directory
* (for example, <i>ou=People,o=Sun,c=US</i> and <i>ou=Groups,o=Sun,c=US</i>
* for user and group information, respectively).
*
* <p> The format in which the user's information must be stored in
* the directory service is specified in RFC 2307. Specifically,
* this <code>LoginModule</code> will search for the user's entry in the
* directory service using the user's <i>uid</i> attribute,
* where <i>uid=<b>username</b></i>. If the search succeeds,
* this <code>LoginModule</code> will then
* obtain the user's encrypted password from the retrieved entry
* using the <i>userPassword</i> attribute.
* This <code>LoginModule</code> assumes that the password is stored
* as a byte array, which when converted to a <code>String</code>,
* has the following format:
* <pre>
* "{crypt}<b>encrypted_password</b>"
* </pre>
*
* The LDAP directory server must be configured
* to permit read access to the userPassword attribute.
* If the user entered a valid username and password,
* this <code>LoginModule</code> associates a
* <code>UnixPrincipal</code>, <code>UnixNumericUserPrincipal</code>,
* and the relevant UnixNumericGroupPrincipals with the
* <code>Subject</code>.
*
* <p> This LoginModule also recognizes the following <code>Configuration</code>
* options:
* <pre>
* debug if, true, debug messages are output to System.out.
*
* useFirstPass if, true, this LoginModule retrieves the
* username and password from the module's shared state,
* using "javax.security.auth.login.name" and
* "javax.security.auth.login.password" as the respective
* keys. The retrieved values are used for authentication.
* If authentication fails, no attempt for a retry is made,
* and the failure is reported back to the calling
* application.
*
* tryFirstPass if, true, this LoginModule retrieves the
* the username and password from the module's shared state,
* using "javax.security.auth.login.name" and
* "javax.security.auth.login.password" as the respective
* keys. The retrieved values are used for authentication.
* If authentication fails, the module uses the
* CallbackHandler to retrieve a new username and password,
* and another attempt to authenticate is made.
* If the authentication fails, the failure is reported
* back to the calling application.
*
* storePass if, true, this LoginModule stores the username and password
* obtained from the CallbackHandler in the module's
* shared state, using "javax.security.auth.login.name" and
* "javax.security.auth.login.password" as the respective
* keys. This is not performed if existing values already
* exist for the username and password in the shared state,
* or if authentication fails.
*
* clearPass if, true, this <code>LoginModule</code> clears the
* username and password stored in the module's shared state
* after both phases of authentication (login and commit)
* have completed.
* </pre>
*
*/
@jdk.Exported
public class JndiLoginModule implements LoginModule {
private static final ResourceBundle rb = AccessController.doPrivileged(
new PrivilegedAction<ResourceBundle>() {
public ResourceBundle run() {
return ResourceBundle.getBundle(
"sun.security.util.AuthResources");
}
}
);
/** JNDI Provider */
public final String USER_PROVIDER = "user.provider.url";
public final String GROUP_PROVIDER = "group.provider.url";
// configurable options
private boolean debug = false;
private boolean strongDebug = false;
private String userProvider;
private String groupProvider;
private boolean useFirstPass = false;
private boolean tryFirstPass = false;
private boolean storePass = false;
private boolean clearPass = false;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
// username, password, and JNDI context
private String username;
private char[] password;
DirContext ctx;
// the user (assume it is a UnixPrincipal)
private UnixPrincipal userPrincipal;
private UnixNumericUserPrincipal UIDPrincipal;
private UnixNumericGroupPrincipal GIDPrincipal;
private LinkedList<UnixNumericGroupPrincipal> supplementaryGroups =
new LinkedList<>();
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, Object> sharedState;
private Map<String, ?> options;
private static final String CRYPT = "{crypt}";
private static final String USER_PWD = "userPassword";
private static final String USER_UID = "uidNumber";
private static final String USER_GID = "gidNumber";
private static final String GROUP_ID = "gidNumber";
private static final String NAME = "javax.security.auth.login.name";
private static final String PWD = "javax.security.auth.login.password";
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example). <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
// Unchecked warning from (Map<String, Object>)sharedState is safe
// since javax.security.auth.login.LoginContext passes a raw HashMap.
// Unchecked warnings from options.get(String) are safe since we are
// passing known keys.
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = (Map<String, Object>)sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
strongDebug =
"true".equalsIgnoreCase((String)options.get("strongDebug"));
userProvider = (String)options.get(USER_PROVIDER);
groupProvider = (String)options.get(GROUP_PROVIDER);
tryFirstPass =
"true".equalsIgnoreCase((String)options.get("tryFirstPass"));
useFirstPass =
"true".equalsIgnoreCase((String)options.get("useFirstPass"));
storePass =
"true".equalsIgnoreCase((String)options.get("storePass"));
clearPass =
"true".equalsIgnoreCase((String)options.get("clearPass"));
}
/**
* <p> Prompt for username and password.
* Verify the password against the relevant name service.
*
* <p>
*
* @return true always, since this <code>LoginModule</code>
* should not be ignored.
*
* @exception FailedLoginException if the authentication fails. <p>
*
* @exception LoginException if this <code>LoginModule</code>
* is unable to perform the authentication.
*/
public boolean login() throws LoginException {
if (userProvider == null) {
throw new LoginException
("Error: Unable to locate JNDI user provider");
}
if (groupProvider == null) {
throw new LoginException
("Error: Unable to locate JNDI group provider");
}
if (debug) {
System.out.println("\t\t[JndiLoginModule] user provider: " +
userProvider);
System.out.println("\t\t[JndiLoginModule] group provider: " +
groupProvider);
}
// attempt the authentication
if (tryFirstPass) {
try {
// attempt the authentication by getting the
// username and password from shared state
attemptAuthentication(true);
// authentication succeeded
succeeded = true;
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"tryFirstPass succeeded");
}
return true;
} catch (LoginException le) {
// authentication failed -- try again below by prompting
cleanState();
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"tryFirstPass failed with:" +
le.toString());
}
}
} else if (useFirstPass) {
try {
// attempt the authentication by getting the
// username and password from shared state
attemptAuthentication(true);
// authentication succeeded
succeeded = true;
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"useFirstPass succeeded");
}
return true;
} catch (LoginException le) {
// authentication failed
cleanState();
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"useFirstPass failed");
}
throw le;
}
}
// attempt the authentication by prompting for the username and pwd
try {
attemptAuthentication(false);
// authentication succeeded
succeeded = true;
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"regular authentication succeeded");
}
return true;
} catch (LoginException le) {
cleanState();
if (debug) {
System.out.println("\t\t[JndiLoginModule] " +
"regular authentication failed");
}
throw le;
}
}
/**
* Abstract method to commit the authentication process (phase 2).
*
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates a
* <code>UnixPrincipal</code>
* with the <code>Subject</code> located in the
* <code>LoginModule</code>. If this LoginModule's own
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails
*
* @return true if this LoginModule's own login and commit
* attempts succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
return false;
} else {
if (subject.isReadOnly()) {
cleanState();
throw new LoginException ("Subject is Readonly");
}
// add Principals to the Subject
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (!subject.getPrincipals().contains(UIDPrincipal))
subject.getPrincipals().add(UIDPrincipal);
if (!subject.getPrincipals().contains(GIDPrincipal))
subject.getPrincipals().add(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
if (!subject.getPrincipals().contains
(supplementaryGroups.get(i)))
subject.getPrincipals().add(supplementaryGroups.get(i));
}
if (debug) {
System.out.println("\t\t[JndiLoginModule]: " +
"added UnixPrincipal,");
System.out.println("\t\t\t\tUnixNumericUserPrincipal,");
System.out.println("\t\t\t\tUnixNumericGroupPrincipal(s),");
System.out.println("\t\t\t to Subject");
}
}
// in any case, clean out state
cleanState();
commitSucceeded = true;
return true;
}
/**
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> and <code>commit</code> methods),
* then this method cleans up any state that was originally saved.
*
* <p>
*
* @exception LoginException if the abort fails.
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (debug)
System.out.println("\t\t[JndiLoginModule]: " +
"aborted authentication failed");
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// Clean out state
succeeded = false;
cleanState();
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups = new LinkedList<UnixNumericGroupPrincipal>();
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
/**
* Logout a user.
*
* <p> This method removes the Principals
* that were added by the <code>commit</code> method.
*
* <p>
*
* @exception LoginException if the logout fails.
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*/
public boolean logout() throws LoginException {
if (subject.isReadOnly()) {
cleanState();
throw new LoginException ("Subject is Readonly");
}
subject.getPrincipals().remove(userPrincipal);
subject.getPrincipals().remove(UIDPrincipal);
subject.getPrincipals().remove(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
subject.getPrincipals().remove(supplementaryGroups.get(i));
}
// clean out state
cleanState();
succeeded = false;
commitSucceeded = false;
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups = new LinkedList<UnixNumericGroupPrincipal>();
if (debug) {
System.out.println("\t\t[JndiLoginModule]: " +
"logged out Subject");
}
return true;
}
/**
* Attempt authentication
*
* <p>
*
* @param getPasswdFromSharedState boolean that tells this method whether
* to retrieve the password from the sharedState.
*/
private void attemptAuthentication(boolean getPasswdFromSharedState)
throws LoginException {
String encryptedPassword = null;
// first get the username and password
getUsernamePassword(getPasswdFromSharedState);
try {
// get the user's passwd entry from the user provider URL
InitialContext iCtx = new InitialContext();
ctx = (DirContext)iCtx.lookup(userProvider);
/*
SearchControls controls = new SearchControls
(SearchControls.ONELEVEL_SCOPE,
0,
5000,
new String[] { USER_PWD },
false,
false);
*/
SearchControls controls = new SearchControls();
NamingEnumeration<SearchResult> ne = ctx.search("",
"(uid=" + username + ")",
controls);
if (ne.hasMore()) {
SearchResult result = ne.next();
Attributes attributes = result.getAttributes();
// get the password
// this module works only if the LDAP directory server
// is configured to permit read access to the userPassword
// attribute. The directory administrator need to grant
// this access.
//
// A workaround would be to make the server do authentication
// by setting the Context.SECURITY_PRINCIPAL
// and Context.SECURITY_CREDENTIALS property.
// However, this would make it not work with systems that
// don't do authentication at the server (like NIS).
//
// Setting the SECURITY_* properties and using "simple"
// authentication for LDAP is recommended only for secure
// channels. For nonsecure channels, SSL is recommended.
Attribute pwd = attributes.get(USER_PWD);
String encryptedPwd = new String((byte[])pwd.get(), "UTF8");
encryptedPassword = encryptedPwd.substring(CRYPT.length());
// check the password
if (verifyPassword
(encryptedPassword, new String(password)) == true) {
// authentication succeeded
if (debug)
System.out.println("\t\t[JndiLoginModule] " +
"attemptAuthentication() succeeded");
} else {
// authentication failed
if (debug)
System.out.println("\t\t[JndiLoginModule] " +
"attemptAuthentication() failed");
throw new FailedLoginException("Login incorrect");
}
// save input as shared state only if
// authentication succeeded
if (storePass &&
!sharedState.containsKey(NAME) &&
!sharedState.containsKey(PWD)) {
sharedState.put(NAME, username);
sharedState.put(PWD, password);
}
// create the user principal
userPrincipal = new UnixPrincipal(username);
// get the UID
Attribute uid = attributes.get(USER_UID);
String uidNumber = (String)uid.get();
UIDPrincipal = new UnixNumericUserPrincipal(uidNumber);
if (debug && uidNumber != null) {
System.out.println("\t\t[JndiLoginModule] " +
"user: '" + username + "' has UID: " +
uidNumber);
}
// get the GID
Attribute gid = attributes.get(USER_GID);
String gidNumber = (String)gid.get();
GIDPrincipal = new UnixNumericGroupPrincipal
(gidNumber, true);
if (debug && gidNumber != null) {
System.out.println("\t\t[JndiLoginModule] " +
"user: '" + username + "' has GID: " +
gidNumber);
}
// get the supplementary groups from the group provider URL
ctx = (DirContext)iCtx.lookup(groupProvider);
ne = ctx.search("", new BasicAttributes("memberUid", username));
while (ne.hasMore()) {
result = ne.next();
attributes = result.getAttributes();
gid = attributes.get(GROUP_ID);
String suppGid = (String)gid.get();
if (!gidNumber.equals(suppGid)) {
UnixNumericGroupPrincipal suppPrincipal =
new UnixNumericGroupPrincipal(suppGid, false);
supplementaryGroups.add(suppPrincipal);
if (debug && suppGid != null) {
System.out.println("\t\t[JndiLoginModule] " +
"user: '" + username +
"' has Supplementary Group: " +
suppGid);
}
}
}
} else {
// bad username
if (debug) {
System.out.println("\t\t[JndiLoginModule]: User not found");
}
throw new FailedLoginException("User not found");
}
} catch (NamingException ne) {
// bad username
if (debug) {
System.out.println("\t\t[JndiLoginModule]: User not found");
ne.printStackTrace();
}
throw new FailedLoginException("User not found");
} catch (java.io.UnsupportedEncodingException uee) {
// password stored in incorrect format
if (debug) {
System.out.println("\t\t[JndiLoginModule]: " +
"password incorrectly encoded");
uee.printStackTrace();
}
throw new LoginException("Login failure due to incorrect " +
"password encoding in the password database");
}
// authentication succeeded
}
/**
* Get the username and password.
* This method does not return any value.
* Instead, it sets global name and password variables.
*
* <p> Also note that this method will set the username and password
* values in the shared state in case subsequent LoginModules
* want to use them via use/tryFirstPass.
*
* <p>
*
* @param getPasswdFromSharedState boolean that tells this method whether
* to retrieve the password from the sharedState.
*/
private void getUsernamePassword(boolean getPasswdFromSharedState)
throws LoginException {
if (getPasswdFromSharedState) {
// use the password saved by the first module in the stack
username = (String)sharedState.get(NAME);
password = (char[])sharedState.get(PWD);
return;
}
// prompt for a username and password
if (callbackHandler == null)
throw new LoginException("Error: no CallbackHandler available " +
"to garner authentication information from the user");
String protocol = userProvider.substring(0, userProvider.indexOf(":"));
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback(protocol + " "
+ rb.getString("username."));
callbacks[1] = new PasswordCallback(protocol + " " +
rb.getString("password."),
false);
try {
callbackHandler.handle(callbacks);
username = ((NameCallback)callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
password = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0,
password, 0, tmpPassword.length);
((PasswordCallback)callbacks[1]).clearPassword();
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("Error: " + uce.getCallback().toString() +
" not available to garner authentication information " +
"from the user");
}
// print debugging information
if (strongDebug) {
System.out.println("\t\t[JndiLoginModule] " +
"user entered username: " +
username);
System.out.print("\t\t[JndiLoginModule] " +
"user entered password: ");
for (int i = 0; i < password.length; i++)
System.out.print(password[i]);
System.out.println();
}
}
/**
* Verify a password against the encrypted passwd from /etc/shadow
*/
private boolean verifyPassword(String encryptedPassword, String password) {
if (encryptedPassword == null)
return false;
Crypt c = new Crypt();
try {
byte oldCrypt[] = encryptedPassword.getBytes("UTF8");
byte newCrypt[] = c.crypt(password.getBytes("UTF8"),
oldCrypt);
if (newCrypt.length != oldCrypt.length)
return false;
for (int i = 0; i < newCrypt.length; i++) {
if (oldCrypt[i] != newCrypt[i])
return false;
}
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen, but return false just to be safe
return false;
}
return true;
}
/**
* Clean out state because of a failed authentication attempt
*/
private void cleanState() {
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
ctx = null;
if (clearPass) {
sharedState.remove(NAME);
sharedState.remove(PWD);
}
}
}

View File

@@ -0,0 +1,939 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.*;
import javax.security.auth.Destroyable;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Subject;
import javax.security.auth.x500.*;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import sun.security.util.Password;
/**
* Provides a JAAS login module that prompts for a key store alias and
* populates the subject with the alias's principal and credentials. Stores
* an <code>X500Principal</code> for the subject distinguished name of the
* first certificate in the alias's credentials in the subject's principals,
* the alias's certificate path in the subject's public credentials, and a
* <code>X500PrivateCredential</code> whose certificate is the first
* certificate in the alias's certificate path and whose private key is the
* alias's private key in the subject's private credentials. <p>
*
* Recognizes the following options in the configuration file:
* <dl>
*
* <dt> <code>keyStoreURL</code> </dt>
* <dd> A URL that specifies the location of the key store. Defaults to
* a URL pointing to the .keystore file in the directory specified by the
* <code>user.home</code> system property. The input stream from this
* URL is passed to the <code>KeyStore.load</code> method.
* "NONE" may be specified if a <code>null</code> stream must be
* passed to the <code>KeyStore.load</code> method.
* "NONE" should be specified if the KeyStore resides
* on a hardware token device, for example.</dd>
*
* <dt> <code>keyStoreType</code> </dt>
* <dd> The key store type. If not specified, defaults to the result of
* calling <code>KeyStore.getDefaultType()</code>.
* If the type is "PKCS11", then keyStoreURL must be "NONE"
* and privateKeyPasswordURL must not be specified.</dd>
*
* <dt> <code>keyStoreProvider</code> </dt>
* <dd> The key store provider. If not specified, uses the standard search
* order to find the provider. </dd>
*
* <dt> <code>keyStoreAlias</code> </dt>
* <dd> The alias in the key store to login as. Required when no callback
* handler is provided. No default value. </dd>
*
* <dt> <code>keyStorePasswordURL</code> </dt>
* <dd> A URL that specifies the location of the key store password. Required
* when no callback handler is provided and
* <code>protected</code> is false.
* No default value. </dd>
*
* <dt> <code>privateKeyPasswordURL</code> </dt>
* <dd> A URL that specifies the location of the specific private key password
* needed to access the private key for this alias.
* The keystore password
* is used if this value is needed and not specified. </dd>
*
* <dt> <code>protected</code> </dt>
* <dd> This value should be set to "true" if the KeyStore
* has a separate, protected authentication path
* (for example, a dedicated PIN-pad attached to a smart card).
* Defaults to "false". If "true" keyStorePasswordURL and
* privateKeyPasswordURL must not be specified.</dd>
*
* </dl>
*/
@jdk.Exported
public class KeyStoreLoginModule implements LoginModule {
private static final ResourceBundle rb = AccessController.doPrivileged(
new PrivilegedAction<ResourceBundle>() {
public ResourceBundle run() {
return ResourceBundle.getBundle(
"sun.security.util.AuthResources");
}
}
);
/* -- Fields -- */
private static final int UNINITIALIZED = 0;
private static final int INITIALIZED = 1;
private static final int AUTHENTICATED = 2;
private static final int LOGGED_IN = 3;
private static final int PROTECTED_PATH = 0;
private static final int TOKEN = 1;
private static final int NORMAL = 2;
private static final String NONE = "NONE";
private static final String P11KEYSTORE = "PKCS11";
private static final TextOutputCallback bannerCallback =
new TextOutputCallback
(TextOutputCallback.INFORMATION,
rb.getString("Please.enter.keystore.information"));
private final ConfirmationCallback confirmationCallback =
new ConfirmationCallback
(ConfirmationCallback.INFORMATION,
ConfirmationCallback.OK_CANCEL_OPTION,
ConfirmationCallback.OK);
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, Object> sharedState;
private Map<String, ?> options;
private char[] keyStorePassword;
private char[] privateKeyPassword;
private KeyStore keyStore;
private String keyStoreURL;
private String keyStoreType;
private String keyStoreProvider;
private String keyStoreAlias;
private String keyStorePasswordURL;
private String privateKeyPasswordURL;
private boolean debug;
private javax.security.auth.x500.X500Principal principal;
private Certificate[] fromKeyStore;
private java.security.cert.CertPath certP = null;
private X500PrivateCredential privateCredential;
private int status = UNINITIALIZED;
private boolean nullStream = false;
private boolean token = false;
private boolean protectedPath = false;
/* -- Methods -- */
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example),
* which may be <code>null</code>. <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
// Unchecked warning from (Map<String, Object>)sharedState is safe
// since javax.security.auth.login.LoginContext passes a raw HashMap.
@SuppressWarnings("unchecked")
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options)
{
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = (Map<String, Object>)sharedState;
this.options = options;
processOptions();
status = INITIALIZED;
}
private void processOptions() {
keyStoreURL = (String) options.get("keyStoreURL");
if (keyStoreURL == null) {
keyStoreURL =
"file:" +
System.getProperty("user.home").replace(
File.separatorChar, '/') +
'/' + ".keystore";
} else if (NONE.equals(keyStoreURL)) {
nullStream = true;
}
keyStoreType = (String) options.get("keyStoreType");
if (keyStoreType == null) {
keyStoreType = KeyStore.getDefaultType();
}
if (P11KEYSTORE.equalsIgnoreCase(keyStoreType)) {
token = true;
}
keyStoreProvider = (String) options.get("keyStoreProvider");
keyStoreAlias = (String) options.get("keyStoreAlias");
keyStorePasswordURL = (String) options.get("keyStorePasswordURL");
privateKeyPasswordURL = (String) options.get("privateKeyPasswordURL");
protectedPath = "true".equalsIgnoreCase((String)options.get
("protected"));
debug = "true".equalsIgnoreCase((String) options.get("debug"));
if (debug) {
debugPrint(null);
debugPrint("keyStoreURL=" + keyStoreURL);
debugPrint("keyStoreType=" + keyStoreType);
debugPrint("keyStoreProvider=" + keyStoreProvider);
debugPrint("keyStoreAlias=" + keyStoreAlias);
debugPrint("keyStorePasswordURL=" + keyStorePasswordURL);
debugPrint("privateKeyPasswordURL=" + privateKeyPasswordURL);
debugPrint("protectedPath=" + protectedPath);
debugPrint(null);
}
}
/**
* Authenticate the user.
*
* <p> Get the Keystore alias and relevant passwords.
* Retrieve the alias's principal and credentials from the Keystore.
*
* <p>
*
* @exception FailedLoginException if the authentication fails. <p>
*
* @return true in all cases (this <code>LoginModule</code>
* should not be ignored).
*/
public boolean login() throws LoginException {
switch (status) {
case UNINITIALIZED:
default:
throw new LoginException("The login module is not initialized");
case INITIALIZED:
case AUTHENTICATED:
if (token && !nullStream) {
throw new LoginException
("if keyStoreType is " + P11KEYSTORE +
" then keyStoreURL must be " + NONE);
}
if (token && privateKeyPasswordURL != null) {
throw new LoginException
("if keyStoreType is " + P11KEYSTORE +
" then privateKeyPasswordURL must not be specified");
}
if (protectedPath &&
(keyStorePasswordURL != null ||
privateKeyPasswordURL != null)) {
throw new LoginException
("if protected is true then keyStorePasswordURL and " +
"privateKeyPasswordURL must not be specified");
}
// get relevant alias and password info
if (protectedPath) {
getAliasAndPasswords(PROTECTED_PATH);
} else if (token) {
getAliasAndPasswords(TOKEN);
} else {
getAliasAndPasswords(NORMAL);
}
// log into KeyStore to retrieve data,
// then clear passwords
try {
getKeyStoreInfo();
} finally {
if (privateKeyPassword != null &&
privateKeyPassword != keyStorePassword) {
Arrays.fill(privateKeyPassword, '\0');
privateKeyPassword = null;
}
if (keyStorePassword != null) {
Arrays.fill(keyStorePassword, '\0');
keyStorePassword = null;
}
}
status = AUTHENTICATED;
return true;
case LOGGED_IN:
return true;
}
}
/** Get the alias and passwords to use for looking up in the KeyStore. */
@SuppressWarnings("fallthrough")
private void getAliasAndPasswords(int env) throws LoginException {
if (callbackHandler == null) {
// No callback handler - check for alias and password options
switch (env) {
case PROTECTED_PATH:
checkAlias();
break;
case TOKEN:
checkAlias();
checkStorePass();
break;
case NORMAL:
checkAlias();
checkStorePass();
checkKeyPass();
break;
}
} else {
// Callback handler available - prompt for alias and passwords
NameCallback aliasCallback;
if (keyStoreAlias == null || keyStoreAlias.length() == 0) {
aliasCallback = new NameCallback(
rb.getString("Keystore.alias."));
} else {
aliasCallback =
new NameCallback(rb.getString("Keystore.alias."),
keyStoreAlias);
}
PasswordCallback storePassCallback = null;
PasswordCallback keyPassCallback = null;
switch (env) {
case PROTECTED_PATH:
break;
case NORMAL:
keyPassCallback = new PasswordCallback
(rb.getString("Private.key.password.optional."), false);
// fall thru
case TOKEN:
storePassCallback = new PasswordCallback
(rb.getString("Keystore.password."), false);
break;
}
prompt(aliasCallback, storePassCallback, keyPassCallback);
}
if (debug) {
debugPrint("alias=" + keyStoreAlias);
}
}
private void checkAlias() throws LoginException {
if (keyStoreAlias == null) {
throw new LoginException
("Need to specify an alias option to use " +
"KeyStoreLoginModule non-interactively.");
}
}
private void checkStorePass() throws LoginException {
if (keyStorePasswordURL == null) {
throw new LoginException
("Need to specify keyStorePasswordURL option to use " +
"KeyStoreLoginModule non-interactively.");
}
InputStream in = null;
try {
in = new URL(keyStorePasswordURL).openStream();
keyStorePassword = Password.readPassword(in);
} catch (IOException e) {
LoginException le = new LoginException
("Problem accessing keystore password \"" +
keyStorePasswordURL + "\"");
le.initCause(e);
throw le;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
LoginException le = new LoginException(
"Problem closing the keystore password stream");
le.initCause(ioe);
throw le;
}
}
}
}
private void checkKeyPass() throws LoginException {
if (privateKeyPasswordURL == null) {
privateKeyPassword = keyStorePassword;
} else {
InputStream in = null;
try {
in = new URL(privateKeyPasswordURL).openStream();
privateKeyPassword = Password.readPassword(in);
} catch (IOException e) {
LoginException le = new LoginException
("Problem accessing private key password \"" +
privateKeyPasswordURL + "\"");
le.initCause(e);
throw le;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
LoginException le = new LoginException(
"Problem closing the private key password stream");
le.initCause(ioe);
throw le;
}
}
}
}
}
private void prompt(NameCallback aliasCallback,
PasswordCallback storePassCallback,
PasswordCallback keyPassCallback)
throws LoginException {
if (storePassCallback == null) {
// only prompt for alias
try {
callbackHandler.handle(
new Callback[] {
bannerCallback, aliasCallback, confirmationCallback
});
} catch (IOException e) {
LoginException le = new LoginException
("Problem retrieving keystore alias");
le.initCause(e);
throw le;
} catch (UnsupportedCallbackException e) {
throw new LoginException(
"Error: " + e.getCallback().toString() +
" is not available to retrieve authentication " +
" information from the user");
}
int confirmationResult = confirmationCallback.getSelectedIndex();
if (confirmationResult == ConfirmationCallback.CANCEL) {
throw new LoginException("Login cancelled");
}
saveAlias(aliasCallback);
} else if (keyPassCallback == null) {
// prompt for alias and key store password
try {
callbackHandler.handle(
new Callback[] {
bannerCallback, aliasCallback,
storePassCallback, confirmationCallback
});
} catch (IOException e) {
LoginException le = new LoginException
("Problem retrieving keystore alias and password");
le.initCause(e);
throw le;
} catch (UnsupportedCallbackException e) {
throw new LoginException(
"Error: " + e.getCallback().toString() +
" is not available to retrieve authentication " +
" information from the user");
}
int confirmationResult = confirmationCallback.getSelectedIndex();
if (confirmationResult == ConfirmationCallback.CANCEL) {
throw new LoginException("Login cancelled");
}
saveAlias(aliasCallback);
saveStorePass(storePassCallback);
} else {
// prompt for alias, key store password, and key password
try {
callbackHandler.handle(
new Callback[] {
bannerCallback, aliasCallback,
storePassCallback, keyPassCallback,
confirmationCallback
});
} catch (IOException e) {
LoginException le = new LoginException
("Problem retrieving keystore alias and passwords");
le.initCause(e);
throw le;
} catch (UnsupportedCallbackException e) {
throw new LoginException(
"Error: " + e.getCallback().toString() +
" is not available to retrieve authentication " +
" information from the user");
}
int confirmationResult = confirmationCallback.getSelectedIndex();
if (confirmationResult == ConfirmationCallback.CANCEL) {
throw new LoginException("Login cancelled");
}
saveAlias(aliasCallback);
saveStorePass(storePassCallback);
saveKeyPass(keyPassCallback);
}
}
private void saveAlias(NameCallback cb) {
keyStoreAlias = cb.getName();
}
private void saveStorePass(PasswordCallback c) {
keyStorePassword = c.getPassword();
if (keyStorePassword == null) {
/* Treat a NULL password as an empty password */
keyStorePassword = new char[0];
}
c.clearPassword();
}
private void saveKeyPass(PasswordCallback c) {
privateKeyPassword = c.getPassword();
if (privateKeyPassword == null || privateKeyPassword.length == 0) {
/*
* Use keystore password if no private key password is
* specified.
*/
privateKeyPassword = keyStorePassword;
}
c.clearPassword();
}
/** Get the credentials from the KeyStore. */
private void getKeyStoreInfo() throws LoginException {
/* Get KeyStore instance */
try {
if (keyStoreProvider == null) {
keyStore = KeyStore.getInstance(keyStoreType);
} else {
keyStore =
KeyStore.getInstance(keyStoreType, keyStoreProvider);
}
} catch (KeyStoreException e) {
LoginException le = new LoginException
("The specified keystore type was not available");
le.initCause(e);
throw le;
} catch (NoSuchProviderException e) {
LoginException le = new LoginException
("The specified keystore provider was not available");
le.initCause(e);
throw le;
}
/* Load KeyStore contents from file */
InputStream in = null;
try {
if (nullStream) {
// if using protected auth path, keyStorePassword will be null
keyStore.load(null, keyStorePassword);
} else {
in = new URL(keyStoreURL).openStream();
keyStore.load(in, keyStorePassword);
}
} catch (MalformedURLException e) {
LoginException le = new LoginException
("Incorrect keyStoreURL option");
le.initCause(e);
throw le;
} catch (GeneralSecurityException e) {
LoginException le = new LoginException
("Error initializing keystore");
le.initCause(e);
throw le;
} catch (IOException e) {
LoginException le = new LoginException
("Error initializing keystore");
le.initCause(e);
throw le;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
LoginException le = new LoginException
("Error initializing keystore");
le.initCause(ioe);
throw le;
}
}
}
/* Get certificate chain and create a certificate path */
try {
fromKeyStore =
keyStore.getCertificateChain(keyStoreAlias);
if (fromKeyStore == null
|| fromKeyStore.length == 0
|| !(fromKeyStore[0] instanceof X509Certificate))
{
throw new FailedLoginException(
"Unable to find X.509 certificate chain in keystore");
} else {
LinkedList<Certificate> certList = new LinkedList<>();
for (int i=0; i < fromKeyStore.length; i++) {
certList.add(fromKeyStore[i]);
}
CertificateFactory certF=
CertificateFactory.getInstance("X.509");
certP =
certF.generateCertPath(certList);
}
} catch (KeyStoreException e) {
LoginException le = new LoginException("Error using keystore");
le.initCause(e);
throw le;
} catch (CertificateException ce) {
LoginException le = new LoginException
("Error: X.509 Certificate type unavailable");
le.initCause(ce);
throw le;
}
/* Get principal and keys */
try {
X509Certificate certificate = (X509Certificate)fromKeyStore[0];
principal = new javax.security.auth.x500.X500Principal
(certificate.getSubjectDN().getName());
// if token, privateKeyPassword will be null
Key privateKey = keyStore.getKey(keyStoreAlias, privateKeyPassword);
if (privateKey == null
|| !(privateKey instanceof PrivateKey))
{
throw new FailedLoginException(
"Unable to recover key from keystore");
}
privateCredential = new X500PrivateCredential(
certificate, (PrivateKey) privateKey, keyStoreAlias);
} catch (KeyStoreException e) {
LoginException le = new LoginException("Error using keystore");
le.initCause(e);
throw le;
} catch (NoSuchAlgorithmException e) {
LoginException le = new LoginException("Error using keystore");
le.initCause(e);
throw le;
} catch (UnrecoverableKeyException e) {
FailedLoginException fle = new FailedLoginException
("Unable to recover key from keystore");
fle.initCause(e);
throw fle;
}
if (debug) {
debugPrint("principal=" + principal +
"\n certificate="
+ privateCredential.getCertificate() +
"\n alias =" + privateCredential.getAlias());
}
}
/**
* Abstract method to commit the authentication process (phase 2).
*
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates a
* <code>X500Principal</code> for the subject distinguished name of the
* first certificate in the alias's credentials in the subject's
* principals,the alias's certificate path in the subject's public
* credentials, and a<code>X500PrivateCredential</code> whose certificate
* is the first certificate in the alias's certificate path and whose
* private key is the alias's private key in the subject's private
* credentials. If this LoginModule's own
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails
*
* @return true if this LoginModule's own login and commit
* attempts succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
switch (status) {
case UNINITIALIZED:
default:
throw new LoginException("The login module is not initialized");
case INITIALIZED:
logoutInternal();
throw new LoginException("Authentication failed");
case AUTHENTICATED:
if (commitInternal()) {
return true;
} else {
logoutInternal();
throw new LoginException("Unable to retrieve certificates");
}
case LOGGED_IN:
return true;
}
}
private boolean commitInternal() throws LoginException {
/* If the subject is not readonly add to the principal and credentials
* set; otherwise just return true
*/
if (subject.isReadOnly()) {
throw new LoginException ("Subject is set readonly");
} else {
subject.getPrincipals().add(principal);
subject.getPublicCredentials().add(certP);
subject.getPrivateCredentials().add(privateCredential);
status = LOGGED_IN;
return true;
}
}
/**
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> and <code>commit</code> methods),
* then this method cleans up any state that was originally saved.
*
* <p> If the loaded KeyStore's provider extends
* <code>java.security.AuthProvider</code>,
* then the provider's <code>logout</code> method is invoked.
*
* <p>
*
* @exception LoginException if the abort fails.
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
switch (status) {
case UNINITIALIZED:
default:
return false;
case INITIALIZED:
return false;
case AUTHENTICATED:
logoutInternal();
return true;
case LOGGED_IN:
logoutInternal();
return true;
}
}
/**
* Logout a user.
*
* <p> This method removes the Principals, public credentials and the
* private credentials that were added by the <code>commit</code> method.
*
* <p> If the loaded KeyStore's provider extends
* <code>java.security.AuthProvider</code>,
* then the provider's <code>logout</code> method is invoked.
*
* <p>
*
* @exception LoginException if the logout fails.
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*/
public boolean logout() throws LoginException {
if (debug)
debugPrint("Entering logout " + status);
switch (status) {
case UNINITIALIZED:
throw new LoginException
("The login module is not initialized");
case INITIALIZED:
case AUTHENTICATED:
default:
// impossible for LoginModule to be in AUTHENTICATED
// state
// assert status != AUTHENTICATED;
return false;
case LOGGED_IN:
logoutInternal();
return true;
}
}
private void logoutInternal() throws LoginException {
if (debug) {
debugPrint("Entering logoutInternal");
}
// assumption is that KeyStore.load did a login -
// perform explicit logout if possible
LoginException logoutException = null;
Provider provider = keyStore.getProvider();
if (provider instanceof AuthProvider) {
AuthProvider ap = (AuthProvider)provider;
try {
ap.logout();
if (debug) {
debugPrint("logged out of KeyStore AuthProvider");
}
} catch (LoginException le) {
// save but continue below
logoutException = le;
}
}
if (subject.isReadOnly()) {
// attempt to destroy the private credential
// even if the Subject is read-only
principal = null;
certP = null;
status = INITIALIZED;
// destroy the private credential
Iterator<Object> it = subject.getPrivateCredentials().iterator();
while (it.hasNext()) {
Object obj = it.next();
if (privateCredential.equals(obj)) {
privateCredential = null;
try {
((Destroyable)obj).destroy();
if (debug)
debugPrint("Destroyed private credential, " +
obj.getClass().getName());
break;
} catch (DestroyFailedException dfe) {
LoginException le = new LoginException
("Unable to destroy private credential, "
+ obj.getClass().getName());
le.initCause(dfe);
throw le;
}
}
}
// throw an exception because we can not remove
// the principal and public credential from this
// read-only Subject
throw new LoginException
("Unable to remove Principal ("
+ "X500Principal "
+ ") and public credential (certificatepath) "
+ "from read-only Subject");
}
if (principal != null) {
subject.getPrincipals().remove(principal);
principal = null;
}
if (certP != null) {
subject.getPublicCredentials().remove(certP);
certP = null;
}
if (privateCredential != null) {
subject.getPrivateCredentials().remove(privateCredential);
privateCredential = null;
}
// throw pending logout exception if there is one
if (logoutException != null) {
throw logoutException;
}
status = INITIALIZED;
}
private void debugPrint(String message) {
// we should switch to logging API
if (message == null) {
System.err.println();
} else {
System.err.println("Debug KeyStoreLoginModule: " + message);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,399 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
import java.util.*;
import java.io.IOException;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import java.security.Principal;
import com.sun.security.auth.NTUserPrincipal;
import com.sun.security.auth.NTSidUserPrincipal;
import com.sun.security.auth.NTDomainPrincipal;
import com.sun.security.auth.NTSidDomainPrincipal;
import com.sun.security.auth.NTSidPrimaryGroupPrincipal;
import com.sun.security.auth.NTSidGroupPrincipal;
import com.sun.security.auth.NTNumericCredential;
/**
* <p> This <code>LoginModule</code>
* renders a user's NT security information as some number of
* <code>Principal</code>s
* and associates them with a <code>Subject</code>.
*
* <p> This LoginModule recognizes the debug option.
* If set to true in the login Configuration,
* debug messages will be output to the output stream, System.out.
*
* <p> This LoginModule also recognizes the debugNative option.
* If set to true in the login Configuration,
* debug messages from the native component of the module
* will be output to the output stream, System.out.
*
* @see javax.security.auth.spi.LoginModule
*/
@jdk.Exported
public class NTLoginModule implements LoginModule {
private NTSystem ntSystem;
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
// configurable option
private boolean debug = false;
private boolean debugNative = false;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
private NTUserPrincipal userPrincipal; // user name
private NTSidUserPrincipal userSID; // user SID
private NTDomainPrincipal userDomain; // user domain
private NTSidDomainPrincipal domainSID; // domain SID
private NTSidPrimaryGroupPrincipal primaryGroup; // primary group
private NTSidGroupPrincipal groups[]; // supplementary groups
private NTNumericCredential iToken; // impersonation token
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example). This particular LoginModule only
* extracts the underlying NT system information, so this
* parameter is ignored.<p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options)
{
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
debugNative="true".equalsIgnoreCase((String)options.get("debugNative"));
if (debugNative == true) {
debug = true;
}
}
/**
* Import underlying NT system identity information.
*
* <p>
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*
* @exception FailedLoginException if the authentication fails. <p>
*
* @exception LoginException if this <code>LoginModule</code>
* is unable to perform the authentication.
*/
public boolean login() throws LoginException {
succeeded = false; // Indicate not yet successful
ntSystem = new NTSystem(debugNative);
if (ntSystem == null) {
if (debug) {
System.out.println("\t\t[NTLoginModule] " +
"Failed in NT login");
}
throw new FailedLoginException
("Failed in attempt to import the " +
"underlying NT system identity information");
}
if (ntSystem.getName() == null) {
throw new FailedLoginException
("Failed in attempt to import the " +
"underlying NT system identity information");
}
userPrincipal = new NTUserPrincipal(ntSystem.getName());
if (debug) {
System.out.println("\t\t[NTLoginModule] " +
"succeeded importing info: ");
System.out.println("\t\t\tuser name = " +
userPrincipal.getName());
}
if (ntSystem.getUserSID() != null) {
userSID = new NTSidUserPrincipal(ntSystem.getUserSID());
if (debug) {
System.out.println("\t\t\tuser SID = " +
userSID.getName());
}
}
if (ntSystem.getDomain() != null) {
userDomain = new NTDomainPrincipal(ntSystem.getDomain());
if (debug) {
System.out.println("\t\t\tuser domain = " +
userDomain.getName());
}
}
if (ntSystem.getDomainSID() != null) {
domainSID =
new NTSidDomainPrincipal(ntSystem.getDomainSID());
if (debug) {
System.out.println("\t\t\tuser domain SID = " +
domainSID.getName());
}
}
if (ntSystem.getPrimaryGroupID() != null) {
primaryGroup =
new NTSidPrimaryGroupPrincipal(ntSystem.getPrimaryGroupID());
if (debug) {
System.out.println("\t\t\tuser primary group = " +
primaryGroup.getName());
}
}
if (ntSystem.getGroupIDs() != null &&
ntSystem.getGroupIDs().length > 0) {
String groupSIDs[] = ntSystem.getGroupIDs();
groups = new NTSidGroupPrincipal[groupSIDs.length];
for (int i = 0; i < groupSIDs.length; i++) {
groups[i] = new NTSidGroupPrincipal(groupSIDs[i]);
if (debug) {
System.out.println("\t\t\tuser group = " +
groups[i].getName());
}
}
}
if (ntSystem.getImpersonationToken() != 0) {
iToken = new NTNumericCredential(ntSystem.getImpersonationToken());
if (debug) {
System.out.println("\t\t\timpersonation token = " +
ntSystem.getImpersonationToken());
}
}
succeeded = true;
return succeeded;
}
/**
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates some
* number of various <code>Principal</code>s
* with the <code>Subject</code> located in the
* <code>LoginModuleContext</code>. If this LoginModule's own
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails.
*
* @return true if this LoginModule's own login and commit
* attempts succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
if (debug) {
System.out.println("\t\t[NTLoginModule]: " +
"did not add any Principals to Subject " +
"because own authentication failed.");
}
return false;
}
if (subject.isReadOnly()) {
throw new LoginException ("Subject is ReadOnly");
}
Set<Principal> principals = subject.getPrincipals();
// we must have a userPrincipal - everything else is optional
if (!principals.contains(userPrincipal)) {
principals.add(userPrincipal);
}
if (userSID != null && !principals.contains(userSID)) {
principals.add(userSID);
}
if (userDomain != null && !principals.contains(userDomain)) {
principals.add(userDomain);
}
if (domainSID != null && !principals.contains(domainSID)) {
principals.add(domainSID);
}
if (primaryGroup != null && !principals.contains(primaryGroup)) {
principals.add(primaryGroup);
}
for (int i = 0; groups != null && i < groups.length; i++) {
if (!principals.contains(groups[i])) {
principals.add(groups[i]);
}
}
Set<Object> pubCreds = subject.getPublicCredentials();
if (iToken != null && !pubCreds.contains(iToken)) {
pubCreds.add(iToken);
}
commitSucceeded = true;
return true;
}
/**
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> and <code>commit</code> methods),
* then this method cleans up any state that was originally saved.
*
* <p>
*
* @exception LoginException if the abort fails.
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (debug) {
System.out.println("\t\t[NTLoginModule]: " +
"aborted authentication attempt");
}
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
ntSystem = null;
userPrincipal = null;
userSID = null;
userDomain = null;
domainSID = null;
primaryGroup = null;
groups = null;
iToken = null;
succeeded = false;
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return succeeded;
}
/**
* Logout the user.
*
* <p> This method removes the <code>NTUserPrincipal</code>,
* <code>NTDomainPrincipal</code>, <code>NTSidUserPrincipal</code>,
* <code>NTSidDomainPrincipal</code>, <code>NTSidGroupPrincipal</code>s,
* and <code>NTSidPrimaryGroupPrincipal</code>
* that may have been added by the <code>commit</code> method.
*
* <p>
*
* @exception LoginException if the logout fails.
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*/
public boolean logout() throws LoginException {
if (subject.isReadOnly()) {
throw new LoginException ("Subject is ReadOnly");
}
Set<Principal> principals = subject.getPrincipals();
if (principals.contains(userPrincipal)) {
principals.remove(userPrincipal);
}
if (principals.contains(userSID)) {
principals.remove(userSID);
}
if (principals.contains(userDomain)) {
principals.remove(userDomain);
}
if (principals.contains(domainSID)) {
principals.remove(domainSID);
}
if (principals.contains(primaryGroup)) {
principals.remove(primaryGroup);
}
for (int i = 0; groups != null && i < groups.length; i++) {
if (principals.contains(groups[i])) {
principals.remove(groups[i]);
}
}
Set<Object> pubCreds = subject.getPublicCredentials();
if (pubCreds.contains(iToken)) {
pubCreds.remove(iToken);
}
succeeded = false;
commitSucceeded = false;
userPrincipal = null;
userDomain = null;
userSID = null;
domainSID = null;
groups = null;
primaryGroup = null;
iToken = null;
ntSystem = null;
if (debug) {
System.out.println("\t\t[NTLoginModule] " +
"completed logout processing");
}
return true;
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
/**
* <p> This class implementation retrieves and makes available NT
* security information for the current user.
*
*/
@jdk.Exported
public class NTSystem {
private native void getCurrent(boolean debug);
private native long getImpersonationToken0();
private String userName;
private String domain;
private String domainSID;
private String userSID;
private String groupIDs[];
private String primaryGroupID;
private long impersonationToken;
/**
* Instantiate an <code>NTSystem</code> and load
* the native library to access the underlying system information.
*/
public NTSystem() {
this(false);
}
/**
* Instantiate an <code>NTSystem</code> and load
* the native library to access the underlying system information.
*/
NTSystem(boolean debug) {
loadNative();
getCurrent(debug);
}
/**
* Get the username for the current NT user.
*
* <p>
*
* @return the username for the current NT user.
*/
public String getName() {
return userName;
}
/**
* Get the domain for the current NT user.
*
* <p>
*
* @return the domain for the current NT user.
*/
public String getDomain() {
return domain;
}
/**
* Get a printable SID for the current NT user's domain.
*
* <p>
*
* @return a printable SID for the current NT user's domain.
*/
public String getDomainSID() {
return domainSID;
}
/**
* Get a printable SID for the current NT user.
*
* <p>
*
* @return a printable SID for the current NT user.
*/
public String getUserSID() {
return userSID;
}
/**
* Get a printable primary group SID for the current NT user.
*
* <p>
*
* @return the primary group SID for the current NT user.
*/
public String getPrimaryGroupID() {
return primaryGroupID;
}
/**
* Get the printable group SIDs for the current NT user.
*
* <p>
*
* @return the group SIDs for the current NT user.
*/
public String[] getGroupIDs() {
return groupIDs == null ? null : groupIDs.clone();
}
/**
* Get an impersonation token for the current NT user.
*
* <p>
*
* @return an impersonation token for the current NT user.
*/
public synchronized long getImpersonationToken() {
if (impersonationToken == 0) {
impersonationToken = getImpersonationToken0();
}
return impersonationToken;
}
private void loadNative() {
System.loadLibrary("jaas_nt");
}
}

View File

@@ -0,0 +1,315 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
import java.util.*;
import java.io.IOException;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import com.sun.security.auth.SolarisPrincipal;
import com.sun.security.auth.SolarisNumericUserPrincipal;
import com.sun.security.auth.SolarisNumericGroupPrincipal;
/**
* <p> This <code>LoginModule</code> imports a user's Solaris
* <code>Principal</code> information (<code>SolarisPrincipal</code>,
* <code>SolarisNumericUserPrincipal</code>,
* and <code>SolarisNumericGroupPrincipal</code>)
* and associates them with the current <code>Subject</code>.
*
* <p> This LoginModule recognizes the debug option.
* If set to true in the login Configuration,
* debug messages will be output to the output stream, System.out.
* @deprecated As of JDK1.4, replaced by
* <code>com.sun.security.auth.module.UnixLoginModule</code>.
* This LoginModule is entirely deprecated and
* is here to allow for a smooth transition to the new
* UnixLoginModule.
*
*/
@jdk.Exported(false)
@Deprecated
public class SolarisLoginModule implements LoginModule {
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
// configurable option
private boolean debug = true;
// SolarisSystem to retrieve underlying system info
private SolarisSystem ss;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
// Underlying system info
private SolarisPrincipal userPrincipal;
private SolarisNumericUserPrincipal UIDPrincipal;
private SolarisNumericGroupPrincipal GIDPrincipal;
private LinkedList<SolarisNumericGroupPrincipal> supplementaryGroups =
new LinkedList<>();
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example). <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options)
{
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
}
/**
* Authenticate the user (first phase).
*
* <p> The implementation of this method attempts to retrieve the user's
* Solaris <code>Subject</code> information by making a native Solaris
* system call.
*
* <p>
*
* @exception FailedLoginException if attempts to retrieve the underlying
* system information fail.
*
* @return true in all cases (this <code>LoginModule</code>
* should not be ignored).
*/
public boolean login() throws LoginException {
long[] solarisGroups = null;
ss = new SolarisSystem();
if (ss == null) {
succeeded = false;
throw new FailedLoginException
("Failed in attempt to import " +
"the underlying system identity information");
} else {
userPrincipal = new SolarisPrincipal(ss.getUsername());
UIDPrincipal = new SolarisNumericUserPrincipal(ss.getUid());
GIDPrincipal = new SolarisNumericGroupPrincipal(ss.getGid(), true);
if (ss.getGroups() != null && ss.getGroups().length > 0)
solarisGroups = ss.getGroups();
for (int i = 0; i < solarisGroups.length; i++) {
SolarisNumericGroupPrincipal ngp =
new SolarisNumericGroupPrincipal
(solarisGroups[i], false);
if (!ngp.getName().equals(GIDPrincipal.getName()))
supplementaryGroups.add(ngp);
}
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"succeeded importing info: ");
System.out.println("\t\t\tuid = " + ss.getUid());
System.out.println("\t\t\tgid = " + ss.getGid());
solarisGroups = ss.getGroups();
for (int i = 0; i < solarisGroups.length; i++) {
System.out.println("\t\t\tsupp gid = " + solarisGroups[i]);
}
}
succeeded = true;
return true;
}
}
/**
* Commit the authentication (second phase).
*
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (the importing of the Solaris authentication information
* succeeded), then this method associates the Solaris Principals
* with the <code>Subject</code> currently tied to the
* <code>LoginModule</code>. If this LoginModule's
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails
*
* @return true if this LoginModule's own login and commit attempts
* succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"did not add any Principals to Subject " +
"because own authentication failed.");
}
return false;
}
if (subject.isReadOnly()) {
throw new LoginException ("Subject is Readonly");
}
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (!subject.getPrincipals().contains(UIDPrincipal))
subject.getPrincipals().add(UIDPrincipal);
if (!subject.getPrincipals().contains(GIDPrincipal))
subject.getPrincipals().add(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
if (!subject.getPrincipals().contains(supplementaryGroups.get(i)))
subject.getPrincipals().add(supplementaryGroups.get(i));
}
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"added SolarisPrincipal,");
System.out.println("\t\t\t\tSolarisNumericUserPrincipal,");
System.out.println("\t\t\t\tSolarisNumericGroupPrincipal(s),");
System.out.println("\t\t\t to Subject");
}
commitSucceeded = true;
return true;
}
/**
* Abort the authentication (second phase).
*
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> This method cleans up any state that was originally saved
* as part of the authentication attempt from the <code>login</code>
* and <code>commit</code> methods.
*
* <p>
*
* @exception LoginException if the abort fails
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"aborted authentication attempt");
}
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// Clean out state
succeeded = false;
ss = null;
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups =
new LinkedList<SolarisNumericGroupPrincipal>();
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
/**
* Logout the user
*
* <p> This method removes the Principals associated
* with the <code>Subject</code>.
*
* <p>
*
* @exception LoginException if the logout fails
*
* @return true in all cases (this <code>LoginModule</code>
* should not be ignored).
*/
public boolean logout() throws LoginException {
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"Entering logout");
}
if (subject.isReadOnly()) {
throw new LoginException ("Subject is Readonly");
}
// remove the added Principals from the Subject
subject.getPrincipals().remove(userPrincipal);
subject.getPrincipals().remove(UIDPrincipal);
subject.getPrincipals().remove(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
subject.getPrincipals().remove(supplementaryGroups.get(i));
}
// clean out state
ss = null;
succeeded = false;
commitSucceeded = false;
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups = new LinkedList<SolarisNumericGroupPrincipal>();
if (debug) {
System.out.println("\t\t[SolarisLoginModule]: " +
"logged out Subject");
}
return true;
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
/**
* <p> This class implementation retrieves and makes available Solaris
* UID/GID/groups information for the current user.
*
*/
@jdk.Exported
public class SolarisSystem {
private native void getSolarisInfo();
protected String username;
protected long uid;
protected long gid;
protected long[] groups;
/**
* Instantiate a <code>SolarisSystem</code> and load
* the native library to access the underlying system information.
*/
public SolarisSystem() {
System.loadLibrary("jaas_unix");
getSolarisInfo();
}
/**
* Get the username for the current Solaris user.
*
* <p>
*
* @return the username for the current Solaris user.
*/
public String getUsername() {
return username;
}
/**
* Get the UID for the current Solaris user.
*
* <p>
*
* @return the UID for the current Solaris user.
*/
public long getUid() {
return uid;
}
/**
* Get the GID for the current Solaris user.
*
* <p>
*
* @return the GID for the current Solaris user.
*/
public long getGid() {
return gid;
}
/**
* Get the supplementary groups for the current Solaris user.
*
* <p>
*
* @return the supplementary groups for the current Solaris user.
*/
public long[] getGroups() {
return groups == null ? null : groups.clone();
}
}

View File

@@ -0,0 +1,308 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
import java.util.*;
import java.io.IOException;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import com.sun.security.auth.UnixPrincipal;
import com.sun.security.auth.UnixNumericUserPrincipal;
import com.sun.security.auth.UnixNumericGroupPrincipal;
/**
* <p> This <code>LoginModule</code> imports a user's Unix
* <code>Principal</code> information (<code>UnixPrincipal</code>,
* <code>UnixNumericUserPrincipal</code>,
* and <code>UnixNumericGroupPrincipal</code>)
* and associates them with the current <code>Subject</code>.
*
* <p> This LoginModule recognizes the debug option.
* If set to true in the login Configuration,
* debug messages will be output to the output stream, System.out.
*
*/
@jdk.Exported
public class UnixLoginModule implements LoginModule {
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
// configurable option
private boolean debug = true;
// UnixSystem to retrieve underlying system info
private UnixSystem ss;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
// Underlying system info
private UnixPrincipal userPrincipal;
private UnixNumericUserPrincipal UIDPrincipal;
private UnixNumericGroupPrincipal GIDPrincipal;
private LinkedList<UnixNumericGroupPrincipal> supplementaryGroups =
new LinkedList<>();
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for usernames and
* passwords, for example). <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String,?> sharedState,
Map<String,?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
}
/**
* Authenticate the user (first phase).
*
* <p> The implementation of this method attempts to retrieve the user's
* Unix <code>Subject</code> information by making a native Unix
* system call.
*
* <p>
*
* @exception FailedLoginException if attempts to retrieve the underlying
* system information fail.
*
* @return true in all cases (this <code>LoginModule</code>
* should not be ignored).
*/
public boolean login() throws LoginException {
long[] unixGroups = null;
ss = new UnixSystem();
if (ss == null) {
succeeded = false;
throw new FailedLoginException
("Failed in attempt to import " +
"the underlying system identity information");
} else {
userPrincipal = new UnixPrincipal(ss.getUsername());
UIDPrincipal = new UnixNumericUserPrincipal(ss.getUid());
GIDPrincipal = new UnixNumericGroupPrincipal(ss.getGid(), true);
if (ss.getGroups() != null && ss.getGroups().length > 0) {
unixGroups = ss.getGroups();
for (int i = 0; i < unixGroups.length; i++) {
UnixNumericGroupPrincipal ngp =
new UnixNumericGroupPrincipal
(unixGroups[i], false);
if (!ngp.getName().equals(GIDPrincipal.getName()))
supplementaryGroups.add(ngp);
}
}
if (debug) {
System.out.println("\t\t[UnixLoginModule]: " +
"succeeded importing info: ");
System.out.println("\t\t\tuid = " + ss.getUid());
System.out.println("\t\t\tgid = " + ss.getGid());
unixGroups = ss.getGroups();
for (int i = 0; i < unixGroups.length; i++) {
System.out.println("\t\t\tsupp gid = " + unixGroups[i]);
}
}
succeeded = true;
return true;
}
}
/**
* Commit the authentication (second phase).
*
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (the importing of the Unix authentication information
* succeeded), then this method associates the Unix Principals
* with the <code>Subject</code> currently tied to the
* <code>LoginModule</code>. If this LoginModule's
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails
*
* @return true if this LoginModule's own login and commit attempts
* succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
if (debug) {
System.out.println("\t\t[UnixLoginModule]: " +
"did not add any Principals to Subject " +
"because own authentication failed.");
}
return false;
} else {
if (subject.isReadOnly()) {
throw new LoginException
("commit Failed: Subject is Readonly");
}
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (!subject.getPrincipals().contains(UIDPrincipal))
subject.getPrincipals().add(UIDPrincipal);
if (!subject.getPrincipals().contains(GIDPrincipal))
subject.getPrincipals().add(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
if (!subject.getPrincipals().contains
(supplementaryGroups.get(i)))
subject.getPrincipals().add(supplementaryGroups.get(i));
}
if (debug) {
System.out.println("\t\t[UnixLoginModule]: " +
"added UnixPrincipal,");
System.out.println("\t\t\t\tUnixNumericUserPrincipal,");
System.out.println("\t\t\t\tUnixNumericGroupPrincipal(s),");
System.out.println("\t\t\t to Subject");
}
commitSucceeded = true;
return true;
}
}
/**
* Abort the authentication (second phase).
*
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> This method cleans up any state that was originally saved
* as part of the authentication attempt from the <code>login</code>
* and <code>commit</code> methods.
*
* <p>
*
* @exception LoginException if the abort fails
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (debug) {
System.out.println("\t\t[UnixLoginModule]: " +
"aborted authentication attempt");
}
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// Clean out state
succeeded = false;
ss = null;
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups = new LinkedList<UnixNumericGroupPrincipal>();
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
/**
* Logout the user
*
* <p> This method removes the Principals associated
* with the <code>Subject</code>.
*
* <p>
*
* @exception LoginException if the logout fails
*
* @return true in all cases (this <code>LoginModule</code>
* should not be ignored).
*/
public boolean logout() throws LoginException {
if (subject.isReadOnly()) {
throw new LoginException
("logout Failed: Subject is Readonly");
}
// remove the added Principals from the Subject
subject.getPrincipals().remove(userPrincipal);
subject.getPrincipals().remove(UIDPrincipal);
subject.getPrincipals().remove(GIDPrincipal);
for (int i = 0; i < supplementaryGroups.size(); i++) {
subject.getPrincipals().remove(supplementaryGroups.get(i));
}
// clean out state
ss = null;
succeeded = false;
commitSucceeded = false;
userPrincipal = null;
UIDPrincipal = null;
GIDPrincipal = null;
supplementaryGroups = new LinkedList<UnixNumericGroupPrincipal>();
if (debug) {
System.out.println("\t\t[UnixLoginModule]: " +
"logged out Subject");
}
return true;
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.auth.module;
/**
* <p> This class implementation retrieves and makes available Unix
* UID/GID/groups information for the current user.
*
*/
@jdk.Exported
public class UnixSystem {
private native void getUnixInfo();
protected String username;
protected long uid;
protected long gid;
protected long[] groups;
/**
* Instantiate a <code>UnixSystem</code> and load
* the native library to access the underlying system information.
*/
public UnixSystem() {
System.loadLibrary("jaas_unix");
getUnixInfo();
}
/**
* Get the username for the current Unix user.
*
* <p>
*
* @return the username for the current Unix user.
*/
public String getUsername() {
return username;
}
/**
* Get the UID for the current Unix user.
*
* <p>
*
* @return the UID for the current Unix user.
*/
public long getUid() {
return uid;
}
/**
* Get the GID for the current Unix user.
*
* <p>
*
* @return the GID for the current Unix user.
*/
public long getGid() {
return gid;
}
/**
* Get the supplementary groups for the current Unix user.
*
* <p>
*
* @return the supplementary groups for the current Unix user.
*/
public long[] getGroups() {
return groups == null ? null : groups.clone();
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@jdk.Exported
package com.sun.security.auth.module;

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@jdk.Exported
package com.sun.security.auth;

View File

@@ -0,0 +1,326 @@
/*
* Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.cert.internal.x509;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.Signature;
import javax.security.cert.*;
import java.security.*;
import java.util.Date;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.Vector;
/**
* The X509V1CertImpl class is used as a conversion wrapper around
* sun.security.x509.X509Cert certificates when running under JDK1.1.x.
*
* @author Jeff Nisewanger
*/
public class X509V1CertImpl extends X509Certificate implements Serializable {
static final long serialVersionUID = -2048442350420423405L;
private java.security.cert.X509Certificate wrappedCert;
synchronized private static java.security.cert.CertificateFactory
getFactory()
throws java.security.cert.CertificateException
{
return java.security.cert.CertificateFactory.getInstance("X.509");
}
/**
* Default constructor.
*/
public X509V1CertImpl() { }
/**
* Unmarshals a certificate from its encoded form, parsing the
* encoded bytes. This form of constructor is used by agents which
* need to examine and use certificate contents. That is, this is
* one of the more commonly used constructors. Note that the buffer
* must include only a certificate, and no "garbage" may be left at
* the end. If you need to ignore data at the end of a certificate,
* use another constructor.
*
* @param certData the encoded bytes, with no trailing padding.
* @exception CertificateException on parsing errors.
*/
public X509V1CertImpl(byte[] certData)
throws CertificateException {
try {
ByteArrayInputStream bs;
bs = new ByteArrayInputStream(certData);
wrappedCert = (java.security.cert.X509Certificate)
getFactory().generateCertificate(bs);
} catch (java.security.cert.CertificateException e) {
throw new CertificateException(e.getMessage());
}
}
/**
* unmarshals an X.509 certificate from an input stream.
*
* @param in an input stream holding at least one certificate
* @exception CertificateException on parsing errors.
*/
public X509V1CertImpl(InputStream in)
throws CertificateException {
try {
wrappedCert = (java.security.cert.X509Certificate)
getFactory().generateCertificate(in);
} catch (java.security.cert.CertificateException e) {
throw new CertificateException(e.getMessage());
}
}
/**
* Returns the encoded form of this certificate. It is
* assumed that each certificate type would have only a single
* form of encoding; for example, X.509 certificates would
* be encoded as ASN.1 DER.
*/
public byte[] getEncoded() throws CertificateEncodingException {
try {
return wrappedCert.getEncoded();
} catch (java.security.cert.CertificateEncodingException e) {
throw new CertificateEncodingException(e.getMessage());
}
}
/**
* Throws an exception if the certificate was not signed using the
* verification key provided. Successfully verifying a certificate
* does <em>not</em> indicate that one should trust the entity which
* it represents.
*
* @param key the public key used for verification.
*/
public void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException
{
try {
wrappedCert.verify(key);
} catch (java.security.cert.CertificateException e) {
throw new CertificateException(e.getMessage());
}
}
/**
* Throws an exception if the certificate was not signed using the
* verification key provided. Successfully verifying a certificate
* does <em>not</em> indicate that one should trust the entity which
* it represents.
*
* @param key the public key used for verification.
* @param sigProvider the name of the provider.
*/
public void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException
{
try {
wrappedCert.verify(key, sigProvider);
} catch (java.security.cert.CertificateException e) {
throw new CertificateException(e.getMessage());
}
}
/**
* Checks that the certificate is currently valid, i.e. the current
* time is within the specified validity period.
*/
public void checkValidity() throws
CertificateExpiredException, CertificateNotYetValidException {
checkValidity(new Date());
}
/**
* Checks that the specified date is within the certificate's
* validity period, or basically if the certificate would be
* valid at the specified date/time.
*
* @param date the Date to check against to see if this certificate
* is valid at that date/time.
*/
public void checkValidity(Date date) throws
CertificateExpiredException, CertificateNotYetValidException {
try {
wrappedCert.checkValidity(date);
} catch (java.security.cert.CertificateNotYetValidException e) {
throw new CertificateNotYetValidException(e.getMessage());
} catch (java.security.cert.CertificateExpiredException e) {
throw new CertificateExpiredException(e.getMessage());
}
}
/**
* Returns a printable representation of the certificate. This does not
* contain all the information available to distinguish this from any
* other certificate. The certificate must be fully constructed
* before this function may be called.
*/
public String toString() {
return wrappedCert.toString();
}
/**
* Gets the publickey from this certificate.
*
* @return the publickey.
*/
public PublicKey getPublicKey() {
PublicKey key = wrappedCert.getPublicKey();
return key;
}
/*
* Gets the version number from the certificate.
*
* @return the version number.
*/
public int getVersion() {
return wrappedCert.getVersion() - 1;
}
/**
* Gets the serial number from the certificate.
*
* @return the serial number.
*/
public BigInteger getSerialNumber() {
return wrappedCert.getSerialNumber();
}
/**
* Gets the subject distinguished name from the certificate.
*
* @return the subject name.
* @exception CertificateException if a parsing error occurs.
*/
public Principal getSubjectDN() {
return wrappedCert.getSubjectDN();
}
/**
* Gets the issuer distinguished name from the certificate.
*
* @return the issuer name.
* @exception CertificateException if a parsing error occurs.
*/
public Principal getIssuerDN() {
return wrappedCert.getIssuerDN();
}
/**
* Gets the notBefore date from the validity period of the certificate.
*
* @return the start date of the validity period.
* @exception CertificateException if a parsing error occurs.
*/
public Date getNotBefore() {
return wrappedCert.getNotBefore();
}
/**
* Gets the notAfter date from the validity period of the certificate.
*
* @return the end date of the validity period.
* @exception CertificateException if a parsing error occurs.
*/
public Date getNotAfter() {
return wrappedCert.getNotAfter();
}
/**
* Gets the signature algorithm name for the certificate
* signature algorithm.
* For example, the string "SHA1/DSA".
*
* @return the signature algorithm name.
* @exception CertificateException if a parsing error occurs.
*/
public String getSigAlgName() {
return wrappedCert.getSigAlgName();
}
/**
* Gets the signature algorithm OID string from the certificate.
* For example, the string "1.2.840.10040.4.3"
*
* @return the signature algorithm oid string.
* @exception CertificateException if a parsing error occurs.
*/
public String getSigAlgOID() {
return wrappedCert.getSigAlgOID();
}
/**
* Gets the DER encoded signature algorithm parameters from this
* certificate's signature algorithm.
*
* @return the DER encoded signature algorithm parameters, or
* null if no parameters are present.
* @exception CertificateException if a parsing error occurs.
*/
public byte[] getSigAlgParams() {
return wrappedCert.getSigAlgParams();
}
private synchronized void writeObject(ObjectOutputStream stream)
throws IOException {
try {
stream.write(getEncoded());
} catch (CertificateEncodingException e) {
throw new IOException("getEncoded failed: " + e.getMessage());
}
}
private synchronized void readObject(ObjectInputStream stream)
throws IOException {
try {
wrappedCert = (java.security.cert.X509Certificate)
getFactory().generateCertificate(stream);
} catch (java.security.cert.CertificateException e) {
throw new IOException("generateCertificate failed: " + e.getMessage());
}
}
public java.security.cert.X509Certificate getX509Certificate() {
return wrappedCert;
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
/**
* Kerberos 5 AuthorizationData entry.
*/
@jdk.Exported
public final class AuthorizationDataEntry {
private final int type;
private final byte[] data;
/**
* Create an AuthorizationDataEntry object.
* @param type the ad-type
* @param data the ad-data, a copy of the data will be saved
* inside the object.
*/
public AuthorizationDataEntry(int type, byte[] data) {
this.type = type;
this.data = data.clone();
}
/**
* Get the ad-type field.
* @return ad-type
*/
public int getType() {
return type;
}
/**
* Get a copy of the ad-data field.
* @return ad-data
*/
public byte[] getData() {
return data.clone();
}
public String toString() {
return "AuthorizationDataEntry: type="+type+", data=" +
data.length + " bytes:\n" +
new sun.misc.HexDumpEncoder().encodeBuffer(data);
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
import org.ietf.jgss.*;
/**
* The extended GSSContext interface for supporting additional
* functionalities not defined by {@code org.ietf.jgss.GSSContext},
* such as querying context-specific attributes.
*/
@jdk.Exported
public interface ExtendedGSSContext extends GSSContext {
/**
* Return the mechanism-specific attribute associated with {@code type}.
* <br><br>
* For each supported attribute type, the type for the output are
* defined below.
* <ol>
* <li>{@code KRB5_GET_TKT_FLAGS}:
* the returned object is a boolean array for the service ticket flags,
* which is long enough to contain all true bits. This means if
* the user wants to get the <em>n</em>'th bit but the length of the
* returned array is less than <em>n</em>, it is regarded as false.
* <li>{@code KRB5_GET_SESSION_KEY}:
* the returned object is an instance of {@link java.security.Key},
* which has the following properties:
* <ul>
* <li>Algorithm: enctype as a string, where
* enctype is defined in RFC 3961, section 8.
* <li>Format: "RAW"
* <li>Encoded form: the raw key bytes, not in any ASN.1 encoding
* </ul>
* <li>{@code KRB5_GET_AUTHZ_DATA}:
* the returned object is an array of
* {@link com.sun.security.jgss.AuthorizationDataEntry}, or null if the
* optional field is missing in the service ticket.
* <li>{@code KRB5_GET_AUTHTIME}:
* the returned object is a String object in the standard KerberosTime
* format defined in RFC 4120 5.2.3
* </ol>
*
* If there is a security manager, an {@link InquireSecContextPermission}
* with the name {@code type.mech} must be granted. Otherwise, this could
* result in a {@link SecurityException}.<p>
*
* Example:
* <pre>
* GSSContext ctxt = m.createContext(...)
* // Establishing the context
* if (ctxt instanceof ExtendedGSSContext) {
* ExtendedGSSContext ex = (ExtendedGSSContext)ctxt;
* try {
* Key key = (key)ex.inquireSecContext(
* InquireType.KRB5_GET_SESSION_KEY);
* // read key info
* } catch (GSSException gsse) {
* // deal with exception
* }
* }
* </pre>
* @param type the type of the attribute requested
* @return the attribute, see the method documentation for details.
* @throws GSSException containing the following
* major error codes:
* {@link GSSException#BAD_MECH GSSException.BAD_MECH} if the mechanism
* does not support this method,
* {@link GSSException#UNAVAILABLE GSSException.UNAVAILABLE} if the
* type specified is not supported,
* {@link GSSException#NO_CONTEXT GSSException.NO_CONTEXT} if the
* security context is invalid,
* {@link GSSException#FAILURE GSSException.FAILURE} for other
* unspecified failures.
* @throws SecurityException if a security manager exists and a proper
* {@link InquireSecContextPermission} is not granted.
* @see InquireSecContextPermission
*/
public Object inquireSecContext(InquireType type)
throws GSSException;
/**
* Requests that the delegation policy be respected. When a true value is
* requested, the underlying context would use the delegation policy
* defined by the environment as a hint to determine whether credentials
* delegation should be performed. This request can only be made on the
* context initiator's side and it has to be done prior to the first
* call to <code>initSecContext</code>.
* <p>
* When this flag is false, delegation will only be tried when the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* is true.
* <p>
* When this flag is true but the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* is false, delegation will be only tried if the delegation policy permits
* delegation.
* <p>
* When both this flag and the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* are true, delegation will be always tried. However, if the delegation
* policy does not permit delegation, the value of
* {@link #getDelegPolicyState} will be false, even
* if delegation is performed successfully.
* <p>
* In any case, if the delegation is not successful, the value returned
* by {@link GSSContext#getCredDelegState()} is false, and the value
* returned by {@link #getDelegPolicyState()} is also false.
* <p>
* Not all mechanisms support delegation policy. Therefore, the
* application should check to see if the request was honored with the
* {@link #getDelegPolicyState() getDelegPolicyState} method. When
* delegation policy is not supported, <code>requestDelegPolicy</code>
* should return silently without throwing an exception.
* <p>
* Note: for the Kerberos 5 mechanism, the delegation policy is expressed
* through the OK-AS-DELEGATE flag in the service ticket. When it's true,
* the KDC permits delegation to the target server. In a cross-realm
* environment, in order for delegation be permitted, all cross-realm TGTs
* on the authentication path must also have the OK-AS-DELAGATE flags set.
* @param state true if the policy should be respected
* @throws GSSException containing the following
* major error codes:
* {@link GSSException#FAILURE GSSException.FAILURE}
*/
public void requestDelegPolicy(boolean state) throws GSSException;
/**
* Returns the delegation policy response. Called after a security context
* is established. This method can be only called on the initiator's side.
* See {@link ExtendedGSSContext#requestDelegPolicy}.
* @return the delegation policy response
*/
public boolean getDelegPolicyState();
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
import org.ietf.jgss.*;
/**
* The extended GSSCredential interface for supporting additional
* functionalities not defined by {@code org.ietf.jgss.GSSCredential}.
* @since 1.8
*/
@jdk.Exported
public interface ExtendedGSSCredential extends GSSCredential {
/**
* Impersonates a principal. In Kerberos, this can be implemented
* using the Microsoft S4U2self extension.
* <p>
* A {@link GSSException#NO_CRED GSSException.NO_CRED} will be thrown if the
* impersonation fails. A {@link GSSException#FAILURE GSSException.FAILURE}
* will be thrown if the impersonation method is not available to this
* credential object.
* @param name the name of the principal to impersonate
* @return a credential for that principal
* @throws GSSException containing the following
* major error codes:
* {@link GSSException#NO_CRED GSSException.NO_CRED}
* {@link GSSException#FAILURE GSSException.FAILURE}
*/
public GSSCredential impersonate(GSSName name) throws GSSException;
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
import javax.security.auth.Subject;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.GSSCredential;
/**
* GSS-API Utilities for using in conjunction with Sun Microsystem's
* implementation of Java GSS-API.
*/
@jdk.Exported
public class GSSUtil {
/**
* Use this method to convert a GSSName and GSSCredential into a
* Subject. Typically this would be done by a server that wants to
* impersonate a client thread at the Java level by setting a client
* Subject in the current access control context. If the server is merely
* interested in using a principal based policy in its local JVM, then
* it only needs to provide the GSSName of the client.
*
* The elements from the GSSName are placed in the principals set of this
* Subject and those from the GSSCredential are placed in the private
* credentials set of the Subject. Any Kerberos specific elements that
* are added to the subject will be instances of the standard Kerberos
* implementation classes defined in javax.security.auth.kerberos.
*
* @return a Subject with the entries that contain elements from the
* given GSSName and GSSCredential.
*
* @param principals a GSSName containing one or more mechanism specific
* representations of the same entity. These mechanism specific
* representations will be populated in the returned Subject's principal
* set.
*
* @param credentials a GSSCredential containing one or more mechanism
* specific credentials for the same entity. These mechanism specific
* credentials will be populated in the returned Subject's private
* credential set. Passing in a value of null will imply that the private
* credential set should be left empty.
*/
public static Subject createSubject(GSSName principals,
GSSCredential credentials) {
return sun.security.jgss.GSSUtil.getSubject(principals,
credentials);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
import java.security.BasicPermission;
/**
* This class is used to protect various attributes of an established
* GSS security context that can be accessed using the
* {@link com.sun.security.jgss.ExtendedGSSContext#inquireSecContext}
* method.
*
* <p>The target name is the {@link InquireType} allowed.
*/
@jdk.Exported
public final class InquireSecContextPermission extends BasicPermission {
private static final long serialVersionUID = -7131173349668647297L;
/**
* Constructs a new {@code InquireSecContextPermission} object with
* the specified name. The name is the symbolic name of the
* {@link InquireType} allowed.
*
* @param name the {@link InquireType} allowed by this
* permission. "*" means all {@link InquireType}s are allowed.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public InquireSecContextPermission(String name) {
super(name);
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.jgss;
/**
* Attribute types that can be specified as an argument of
* {@link com.sun.security.jgss.ExtendedGSSContext#inquireSecContext}
*/
@jdk.Exported
public enum InquireType {
/**
* Attribute type for retrieving the session key of an
* established Kerberos 5 security context.
*/
KRB5_GET_SESSION_KEY,
/**
* Attribute type for retrieving the service ticket flags of an
* established Kerberos 5 security context.
*/
KRB5_GET_TKT_FLAGS,
/**
* Attribute type for retrieving the authorization data in the
* service ticket of an established Kerberos 5 security context.
* Only supported on the acceptor side.
*/
KRB5_GET_AUTHZ_DATA,
/**
* Attribute type for retrieving the authtime in the service ticket
* of an established Kerberos 5 security context.
*/
KRB5_GET_AUTHTIME
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@jdk.Exported
package com.sun.security.jgss;

View File

@@ -0,0 +1,207 @@
/*
* Copyright (c) 2010, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
/**
* The NTLM client. Not multi-thread enabled.<p>
* Example:
* <pre>
* Client client = new Client(null, "host", "dummy",
* "REALM", "t0pSeCr3t".toCharArray());
* byte[] type1 = client.type1();
* // Send type1 to server and receive response as type2
* byte[] type3 = client.type3(type2, nonce);
* // Send type3 to server
* </pre>
*/
public final class Client extends NTLM {
final private String hostname;
final private String username;
private String domain;
private byte[] pw1, pw2;
/**
* Creates an NTLM Client instance.
* @param version the NTLM version to use, which can be:
* <ul>
* <li>LM/NTLM: Original NTLM v1
* <li>LM: Original NTLM v1, LM only
* <li>NTLM: Original NTLM v1, NTLM only
* <li>NTLM2: NTLM v1 with Client Challenge
* <li>LMv2/NTLMv2: NTLM v2
* <li>LMv2: NTLM v2, LM only
* <li>NTLMv2: NTLM v2, NTLM only
* </ul>
* If null, "LMv2/NTLMv2" will be used.
* @param hostname hostname of the client, can be null
* @param username username to be authenticated, must not be null
* @param domain domain of {@code username}, can be null
* @param password password for {@code username}, must not be not null.
* This method does not make any modification to this parameter, it neither
* needs to access the content of this parameter after this method call,
* so you are free to modify or nullify this parameter after this call.
* @throws NTLMException if {@code username} or {@code password} is null,
* or {@code version} is illegal.
*
*/
public Client(String version, String hostname, String username,
String domain, char[] password) throws NTLMException {
super(version);
if ((username == null || password == null)) {
throw new NTLMException(NTLMException.PROTOCOL,
"username/password cannot be null");
}
this.hostname = hostname;
this.username = username;
this.domain = domain == null ? "" : domain;
this.pw1 = getP1(password);
this.pw2 = getP2(password);
debug("NTLM Client: (h,u,t,version(v)) = (%s,%s,%s,%s(%s))\n",
hostname, username, domain, version, v.toString());
}
/**
* Generates the Type 1 message
* @return the message generated
*/
public byte[] type1() {
Writer p = new Writer(1, 32);
// Negotiate always sign, Negotiate NTLM,
// Request Target, Negotiate OEM, Negotiate unicode
int flags = 0x8207;
if (v != Version.NTLM) {
flags |= 0x80000;
}
p.writeInt(12, flags);
debug("NTLM Client: Type 1 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Generates the Type 3 message
* @param type2 the responding Type 2 message from server, must not be null
* @param nonce random 8-byte array to be used in message generation,
* must not be null except for original NTLM v1
* @return the message generated
* @throws NTLMException if the incoming message is invalid, or
* {@code nonce} is null for NTLM v1.
*/
public byte[] type3(byte[] type2, byte[] nonce) throws NTLMException {
if (type2 == null || (v != Version.NTLM && nonce == null) ||
(nonce != null && nonce.length != 8)) {
throw new NTLMException(NTLMException.PROTOCOL,
"type2 cannot be null, and nonce must be 8-byte long");
}
debug("NTLM Client: Type 2 received\n");
debug(type2);
Reader r = new Reader(type2);
byte[] challenge = r.readBytes(24, 8);
int inputFlags = r.readInt(20);
boolean unicode = (inputFlags & 1) == 1;
// IE uses domainFromServer to generate an alist if server has not
// provided one. Firefox/WebKit do not. Neither do we.
//String domainFromServer = r.readSecurityBuffer(12, unicode);
int flags = 0x88200 | (inputFlags & 3);
Writer p = new Writer(3, 64);
byte[] lm = null, ntlm = null;
p.writeSecurityBuffer(28, domain, unicode);
p.writeSecurityBuffer(36, username, unicode);
p.writeSecurityBuffer(44, hostname, unicode);
if (v == Version.NTLM) {
byte[] lmhash = calcLMHash(pw1);
byte[] nthash = calcNTHash(pw2);
if (writeLM) lm = calcResponse (lmhash, challenge);
if (writeNTLM) ntlm = calcResponse (nthash, challenge);
} else if (v == Version.NTLM2) {
byte[] nthash = calcNTHash(pw2);
lm = ntlm2LM(nonce);
ntlm = ntlm2NTLM(nthash, nonce, challenge);
} else {
byte[] nthash = calcNTHash(pw2);
if (writeLM) lm = calcV2(nthash,
username.toUpperCase(Locale.US)+domain, nonce, challenge);
if (writeNTLM) {
// Some client create a alist even if server does not send
// one: (i16)2 (i16)len target_in_unicode (i16)0 (i16) 0
byte[] alist = ((inputFlags & 0x800000) != 0) ?
r.readSecurityBuffer(40) : new byte[0];
byte[] blob = new byte[32+alist.length];
System.arraycopy(new byte[]{1,1,0,0,0,0,0,0}, 0, blob, 0, 8);
// TS
byte[] time = BigInteger.valueOf(new Date().getTime())
.add(new BigInteger("11644473600000"))
.multiply(BigInteger.valueOf(10000))
.toByteArray();
for (int i=0; i<time.length; i++) {
blob[8+time.length-i-1] = time[i];
}
System.arraycopy(nonce, 0, blob, 16, 8);
System.arraycopy(new byte[]{0,0,0,0}, 0, blob, 24, 4);
System.arraycopy(alist, 0, blob, 28, alist.length);
System.arraycopy(new byte[]{0,0,0,0}, 0,
blob, 28+alist.length, 4);
ntlm = calcV2(nthash, username.toUpperCase(Locale.US)+domain,
blob, challenge);
}
}
p.writeSecurityBuffer(12, lm);
p.writeSecurityBuffer(20, ntlm);
p.writeSecurityBuffer(52, new byte[0]);
p.writeInt(60, flags);
debug("NTLM Client: Type 3 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Returns the domain value provided by server after the authentication
* is complete, or the domain value provided by the client before it.
* @return the domain
*/
public String getDomain() {
return domain;
}
/**
* Disposes any password-derived information.
*/
public void dispose() {
Arrays.fill(pw1, (byte)0);
Arrays.fill(pw2, (byte)0);
}
}

View File

@@ -0,0 +1,432 @@
/*
* Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import static com.sun.security.ntlm.Version.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Locale;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* NTLM authentication implemented according to MS-NLMP, version 12.1
* @since 1.7
*/
class NTLM {
private final SecretKeyFactory fac;
private final Cipher cipher;
private final MessageDigest md4;
private final Mac hmac;
private final MessageDigest md5;
private static final boolean DEBUG =
System.getProperty("ntlm.debug") != null;
final Version v;
final boolean writeLM;
final boolean writeNTLM;
protected NTLM(String version) throws NTLMException {
if (version == null) version = "LMv2/NTLMv2";
switch (version) {
case "LM": v = NTLM; writeLM = true; writeNTLM = false; break;
case "NTLM": v = NTLM; writeLM = false; writeNTLM = true; break;
case "LM/NTLM": v = NTLM; writeLM = writeNTLM = true; break;
case "NTLM2": v = NTLM2; writeLM = writeNTLM = true; break;
case "LMv2": v = NTLMv2; writeLM = true; writeNTLM = false; break;
case "NTLMv2": v = NTLMv2; writeLM = false; writeNTLM = true; break;
case "LMv2/NTLMv2": v = NTLMv2; writeLM = writeNTLM = true; break;
default: throw new NTLMException(NTLMException.BAD_VERSION,
"Unknown version " + version);
}
try {
fac = SecretKeyFactory.getInstance ("DES");
cipher = Cipher.getInstance ("DES/ECB/NoPadding");
md4 = sun.security.provider.MD4.getInstance();
hmac = Mac.getInstance("HmacMD5");
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchPaddingException e) {
throw new AssertionError();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError();
}
}
/**
* Prints out a formatted string, called in various places inside then NTLM
* implementation for debugging/logging purposes. When the system property
* "ntlm.debug" is set, <code>System.out.printf(format, args)</code> is
* called. This method is designed to be overridden by child classes to
* match their own debugging/logging mechanisms.
* @param format a format string
* @param args the arguments referenced by <code>format</code>
* @see java.io.PrintStream#printf(java.lang.String, java.lang.Object[])
*/
public void debug(String format, Object... args) {
if (DEBUG) {
System.out.printf(format, args);
}
}
/**
* Prints out the content of a byte array, called in various places inside
* the NTLM implementation for debugging/logging purposes. When the system
* property "ntlm.debug" is set, the hexdump of the array is printed into
* System.out. This method is designed to be overridden by child classes to
* match their own debugging/logging mechanisms.
* @param bytes the byte array to print out
*/
public void debug(byte[] bytes) {
if (DEBUG) {
try {
new sun.misc.HexDumpEncoder().encodeBuffer(bytes, System.out);
} catch (IOException ioe) {
// Impossible
}
}
}
/**
* Reading an NTLM packet
*/
static class Reader {
private final byte[] internal;
Reader(byte[] data) {
internal = data;
}
int readInt(int offset) throws NTLMException {
try {
return (internal[offset] & 0xff) +
((internal[offset+1] & 0xff) << 8) +
((internal[offset+2] & 0xff) << 16) +
((internal[offset+3] & 0xff) << 24);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
int readShort(int offset) throws NTLMException {
try {
return (internal[offset] & 0xff) +
(((internal[offset+1] & 0xff) << 8));
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
byte[] readBytes(int offset, int len) throws NTLMException {
try {
return Arrays.copyOfRange(internal, offset, offset + len);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
byte[] readSecurityBuffer(int offset) throws NTLMException {
int pos = readInt(offset+4);
if (pos == 0) return new byte[0];
try {
return Arrays.copyOfRange(
internal, pos, pos + readShort(offset));
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
String readSecurityBuffer(int offset, boolean unicode)
throws NTLMException {
byte[] raw = readSecurityBuffer(offset);
try {
return raw == null ? null : new String(
raw, unicode ? "UnicodeLittleUnmarked" : "ISO8859_1");
} catch (UnsupportedEncodingException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Invalid input encoding");
}
}
}
/**
* Writing an NTLM packet
*/
static class Writer {
private byte[] internal; // buffer
private int current; // current written content interface buffer
/**
* Starts writing a NTLM packet
* @param type NEGOTIATE || CHALLENGE || AUTHENTICATE
* @param len the base length, without security buffers
*/
Writer(int type, int len) {
assert len < 256;
internal = new byte[256];
current = len;
System.arraycopy (
new byte[] {'N','T','L','M','S','S','P',0,(byte)type},
0, internal, 0, 9);
}
void writeShort(int offset, int number) {
internal[offset] = (byte)(number);
internal[offset+1] = (byte)(number >> 8);
}
void writeInt(int offset, int number) {
internal[offset] = (byte)(number);
internal[offset+1] = (byte)(number >> 8);
internal[offset+2] = (byte)(number >> 16);
internal[offset+3] = (byte)(number >> 24);
}
void writeBytes(int offset, byte[] data) {
System.arraycopy(data, 0, internal, offset, data.length);
}
void writeSecurityBuffer(int offset, byte[] data) throws NTLMException {
if (data == null) {
writeInt(offset+4, current);
} else {
int len = data.length;
if (len > 65535) {
throw new NTLMException(NTLMException.INVALID_INPUT,
"Invalid data length " + len);
}
if (current + len > internal.length) {
internal = Arrays.copyOf(internal, current + len + 256);
}
writeShort(offset, len);
writeShort(offset+2, len);
writeInt(offset+4, current);
System.arraycopy(data, 0, internal, current, len);
current += len;
}
}
void writeSecurityBuffer(int offset, String str, boolean unicode) throws NTLMException {
try {
writeSecurityBuffer(offset, str == null ? null : str.getBytes(
unicode ? "UnicodeLittleUnmarked" : "ISO8859_1"));
} catch (UnsupportedEncodingException ex) {
assert false;
}
}
byte[] getBytes() {
return Arrays.copyOf(internal, current);
}
}
// LM/NTLM
/* Convert a 7 byte array to an 8 byte array (for a des key with parity)
* input starts at offset off
*/
byte[] makeDesKey (byte[] input, int off) {
int[] in = new int [input.length];
for (int i=0; i<in.length; i++ ) {
in[i] = input[i]<0 ? input[i]+256: input[i];
}
byte[] out = new byte[8];
out[0] = (byte)in[off+0];
out[1] = (byte)(((in[off+0] << 7) & 0xFF) | (in[off+1] >> 1));
out[2] = (byte)(((in[off+1] << 6) & 0xFF) | (in[off+2] >> 2));
out[3] = (byte)(((in[off+2] << 5) & 0xFF) | (in[off+3] >> 3));
out[4] = (byte)(((in[off+3] << 4) & 0xFF) | (in[off+4] >> 4));
out[5] = (byte)(((in[off+4] << 3) & 0xFF) | (in[off+5] >> 5));
out[6] = (byte)(((in[off+5] << 2) & 0xFF) | (in[off+6] >> 6));
out[7] = (byte)((in[off+6] << 1) & 0xFF);
return out;
}
byte[] calcLMHash (byte[] pwb) {
byte[] magic = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
byte[] pwb1 = new byte [14];
int len = pwb.length;
if (len > 14)
len = 14;
System.arraycopy (pwb, 0, pwb1, 0, len); /* Zero padded */
try {
DESKeySpec dks1 = new DESKeySpec (makeDesKey (pwb1, 0));
DESKeySpec dks2 = new DESKeySpec (makeDesKey (pwb1, 7));
SecretKey key1 = fac.generateSecret (dks1);
SecretKey key2 = fac.generateSecret (dks2);
cipher.init (Cipher.ENCRYPT_MODE, key1);
byte[] out1 = cipher.doFinal (magic, 0, 8);
cipher.init (Cipher.ENCRYPT_MODE, key2);
byte[] out2 = cipher.doFinal (magic, 0, 8);
byte[] result = new byte [21];
System.arraycopy (out1, 0, result, 0, 8);
System.arraycopy (out2, 0, result, 8, 8);
return result;
} catch (InvalidKeyException ive) {
// Will not happen, all key material are 8 bytes
assert false;
} catch (InvalidKeySpecException ikse) {
// Will not happen, we only feed DESKeySpec to DES factory
assert false;
} catch (IllegalBlockSizeException ibse) {
// Will not happen, we encrypt 8 bytes
assert false;
} catch (BadPaddingException bpe) {
// Will not happen, this is encryption
assert false;
}
return null; // will not happen, we returned already
}
byte[] calcNTHash (byte[] pw) {
byte[] out = md4.digest (pw);
byte[] result = new byte [21];
System.arraycopy (out, 0, result, 0, 16);
return result;
}
/* key is a 21 byte array. Split it into 3 7 byte chunks,
* Convert each to 8 byte DES keys, encrypt the text arg with
* each key and return the three results in a sequential []
*/
byte[] calcResponse (byte[] key, byte[] text) {
try {
assert key.length == 21;
DESKeySpec dks1 = new DESKeySpec(makeDesKey(key, 0));
DESKeySpec dks2 = new DESKeySpec(makeDesKey(key, 7));
DESKeySpec dks3 = new DESKeySpec(makeDesKey(key, 14));
SecretKey key1 = fac.generateSecret(dks1);
SecretKey key2 = fac.generateSecret(dks2);
SecretKey key3 = fac.generateSecret(dks3);
cipher.init(Cipher.ENCRYPT_MODE, key1);
byte[] out1 = cipher.doFinal(text, 0, 8);
cipher.init(Cipher.ENCRYPT_MODE, key2);
byte[] out2 = cipher.doFinal(text, 0, 8);
cipher.init(Cipher.ENCRYPT_MODE, key3);
byte[] out3 = cipher.doFinal(text, 0, 8);
byte[] result = new byte[24];
System.arraycopy(out1, 0, result, 0, 8);
System.arraycopy(out2, 0, result, 8, 8);
System.arraycopy(out3, 0, result, 16, 8);
return result;
} catch (IllegalBlockSizeException ex) { // None will happen
assert false;
} catch (BadPaddingException ex) {
assert false;
} catch (InvalidKeySpecException ex) {
assert false;
} catch (InvalidKeyException ex) {
assert false;
}
return null;
}
// LMv2/NTLMv2
byte[] hmacMD5(byte[] key, byte[] text) {
try {
SecretKeySpec skey =
new SecretKeySpec(Arrays.copyOf(key, 16), "HmacMD5");
hmac.init(skey);
return hmac.doFinal(text);
} catch (InvalidKeyException ex) {
assert false;
} catch (RuntimeException e) {
assert false;
}
return null;
}
byte[] calcV2(byte[] nthash, String text, byte[] blob, byte[] challenge) {
try {
byte[] ntlmv2hash = hmacMD5(nthash,
text.getBytes("UnicodeLittleUnmarked"));
byte[] cn = new byte[blob.length+8];
System.arraycopy(challenge, 0, cn, 0, 8);
System.arraycopy(blob, 0, cn, 8, blob.length);
byte[] result = new byte[16+blob.length];
System.arraycopy(hmacMD5(ntlmv2hash, cn), 0, result, 0, 16);
System.arraycopy(blob, 0, result, 16, blob.length);
return result;
} catch (UnsupportedEncodingException ex) {
assert false;
}
return null;
}
// NTLM2 LM/NTLM
static byte[] ntlm2LM(byte[] nonce) {
return Arrays.copyOf(nonce, 24);
}
byte[] ntlm2NTLM(byte[] ntlmHash, byte[] nonce, byte[] challenge) {
byte[] b = Arrays.copyOf(challenge, 16);
System.arraycopy(nonce, 0, b, 8, 8);
byte[] sesshash = Arrays.copyOf(md5.digest(b), 8);
return calcResponse(ntlmHash, sesshash);
}
// Password in ASCII and UNICODE
static byte[] getP1(char[] password) {
try {
return new String(password).toUpperCase(
Locale.ENGLISH).getBytes("ISO8859_1");
} catch (UnsupportedEncodingException ex) {
return null;
}
}
static byte[] getP2(char[] password) {
try {
return new String(password).getBytes("UnicodeLittleUnmarked");
} catch (UnsupportedEncodingException ex) {
return null;
}
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.security.GeneralSecurityException;
/**
* An NTLM-related Exception
*/
public final class NTLMException extends GeneralSecurityException {
private static final long serialVersionUID = -3298539507906689430L;
/**
* If the incoming packet is invalid.
*/
public final static int PACKET_READ_ERROR = 1;
/**
* If the client cannot get a domain value from the server and the
* caller has not provided one.
*/
public final static int NO_DOMAIN_INFO = 2;
/**
* If the domain provided by the client does not match the one received
* from server.
*/
//public final static int DOMAIN_UNMATCH = 3;
/**
* If the client name is not found on server's user database.
*/
public final static int USER_UNKNOWN = 3;
/**
* If authentication fails.
*/
public final static int AUTH_FAILED = 4;
/**
* If an illegal version string is provided.
*/
public final static int BAD_VERSION = 5;
/**
* Protocol errors.
*/
public final static int PROTOCOL = 6;
/**
* If an invalid input is provided.
*/
public static final int INVALID_INPUT = 7;
private int errorCode;
/**
* Constructs an NTLMException object.
* @param errorCode the error code, which can be retrieved by
* the {@link #errorCode() } method.
* @param msg the string message, which can be retrived by
* the {@link Exception#getMessage() } method.
*/
public NTLMException(int errorCode, String msg) {
super(msg);
this.errorCode = errorCode;
}
/**
* Returns the error code associated with this NTLMException.
* @return the error code
*/
public int errorCode() {
return errorCode;
}
}

View File

@@ -0,0 +1,214 @@
/*
* Copyright (c) 2010, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.util.Arrays;
import java.util.Locale;
/**
* The NTLM server, not multi-thread enabled.<p>
* Example:
* <pre>
* Server server = new Server(null, "REALM") {
* public char[] getPassword(String ntdomain, String username) {
* switch (username) {
* case "dummy": return "t0pSeCr3t".toCharArray();
* case "guest": return "".toCharArray();
* default: return null;
* }
* }
* };
* // Receive client request as type1
* byte[] type2 = server.type2(type1, nonce);
* // Send type2 to client and receive type3
* verify(type3, nonce);
* </pre>
*/
public abstract class Server extends NTLM {
final private String domain;
final private boolean allVersion;
/**
* Creates a Server instance.
* @param version the NTLM version to use, which can be:
* <ul>
* <li>NTLM: Original NTLM v1
* <li>NTLM2: NTLM v1 with Client Challenge
* <li>NTLMv2: NTLM v2
* </ul>
* If null, all versions will be supported. Please note that unless NTLM2
* is selected, authentication succeeds if one of LM (or LMv2) or
* NTLM (or NTLMv2) is verified.
* @param domain the domain, must not be null
* @throws NTLMException if {@code domain} is null.
*/
public Server(String version, String domain) throws NTLMException {
super(version);
if (domain == null) {
throw new NTLMException(NTLMException.PROTOCOL,
"domain cannot be null");
}
this.allVersion = (version == null);
this.domain = domain;
debug("NTLM Server: (t,version) = (%s,%s)\n", domain, version);
}
/**
* Generates the Type 2 message
* @param type1 the Type1 message received, must not be null
* @param nonce the random 8-byte array to be used in message generation,
* must not be null
* @return the message generated
* @throws NTLMException if the incoming message is invalid, or
* {@code nonce} is null.
*/
public byte[] type2(byte[] type1, byte[] nonce) throws NTLMException {
if (nonce == null || nonce.length != 8) {
throw new NTLMException(NTLMException.PROTOCOL,
"nonce must be 8-byte long");
}
debug("NTLM Server: Type 1 received\n");
if (type1 != null) debug(type1);
Writer p = new Writer(2, 32);
// Negotiate NTLM2 Key, Target Type Domain,
// Negotiate NTLM, Request Target, Negotiate unicode
int flags = 0x90205;
p.writeSecurityBuffer(12, domain, true);
p.writeInt(20, flags);
p.writeBytes(24, nonce);
debug("NTLM Server: Type 2 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Verifies the Type3 message received from client and returns
* various negotiated information.
* @param type3 the incoming Type3 message from client, must not be null
* @param nonce the same nonce provided in {@link #type2}, must not be null
* @return client username, client hostname, and the request target
* @throws NTLMException if the incoming message is invalid, or
* {@code nonce} is null.
*/
public String[] verify(byte[] type3, byte[] nonce)
throws NTLMException {
if (type3 == null || nonce == null) {
throw new NTLMException(NTLMException.PROTOCOL,
"type1 or nonce cannot be null");
}
debug("NTLM Server: Type 3 received\n");
if (type3 != null) debug(type3);
Reader r = new Reader(type3);
String username = r.readSecurityBuffer(36, true);
String hostname = r.readSecurityBuffer(44, true);
String incomingDomain = r.readSecurityBuffer(28, true);
/*if (incomingDomain != null && !incomingDomain.equals(domain)) {
throw new NTLMException(NTLMException.DOMAIN_UNMATCH,
"Wrong domain: " + incomingDomain +
" vs " + domain); // Needed?
}*/
boolean verified = false;
char[] password = getPassword(incomingDomain, username);
if (password == null) {
throw new NTLMException(NTLMException.USER_UNKNOWN,
"Unknown user");
}
byte[] incomingLM = r.readSecurityBuffer(12);
byte[] incomingNTLM = r.readSecurityBuffer(20);
if (!verified && (allVersion || v == Version.NTLM)) {
if (incomingLM.length > 0) {
byte[] pw1 = getP1(password);
byte[] lmhash = calcLMHash(pw1);
byte[] lmresponse = calcResponse (lmhash, nonce);
if (Arrays.equals(lmresponse, incomingLM)) {
verified = true;
}
}
if (incomingNTLM.length > 0) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
byte[] ntresponse = calcResponse (nthash, nonce);
if (Arrays.equals(ntresponse, incomingNTLM)) {
verified = true;
}
}
debug("NTLM Server: verify using NTLM: " + verified + "\n");
}
if (!verified && (allVersion || v == Version.NTLM2)) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
byte[] clientNonce = Arrays.copyOf(incomingLM, 8);
byte[] ntlmresponse = ntlm2NTLM(nthash, clientNonce, nonce);
if (Arrays.equals(incomingNTLM, ntlmresponse)) {
verified = true;
}
debug("NTLM Server: verify using NTLM2: " + verified + "\n");
}
if (!verified && (allVersion || v == Version.NTLMv2)) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
if (incomingLM.length > 0) {
byte[] clientNonce = Arrays.copyOfRange(
incomingLM, 16, incomingLM.length);
byte[] lmresponse = calcV2(nthash,
username.toUpperCase(Locale.US)+incomingDomain,
clientNonce, nonce);
if (Arrays.equals(lmresponse, incomingLM)) {
verified = true;
}
}
if (incomingNTLM.length > 0) {
// We didn't sent alist in type2(), so there
// is nothing to check here.
byte[] clientBlob = Arrays.copyOfRange(
incomingNTLM, 16, incomingNTLM.length);
byte[] ntlmresponse = calcV2(nthash,
username.toUpperCase(Locale.US)+incomingDomain,
clientBlob, nonce);
if (Arrays.equals(ntlmresponse, incomingNTLM)) {
verified = true;
}
}
debug("NTLM Server: verify using NTLMv2: " + verified + "\n");
}
if (!verified) {
throw new NTLMException(NTLMException.AUTH_FAILED,
"None of LM and NTLM verified");
}
return new String[] {username, hostname, incomingDomain};
}
/**
* Retrieves the password for a given user. This method should be
* overridden in a concrete class.
* @param domain can be null
* @param username must not be null
* @return the password for the user, or null if unknown
*/
public abstract char[] getPassword(String domain, String username);
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
enum Version {
NTLM, NTLM2, NTLMv2
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import com.sun.security.sasl.util.PolicyUtils;
import java.util.Map;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Client factory for EXTERNAL, CRAM-MD5, PLAIN.
*
* Requires the following callbacks to be satisfied by callback handler
* when using CRAM-MD5 or PLAIN.
* - NameCallback (to get username)
* - PasswordCallback (to get password)
*
* @author Rosanna Lee
*/
final public class ClientFactoryImpl implements SaslClientFactory {
private static final String myMechs[] = {
"EXTERNAL",
"CRAM-MD5",
"PLAIN",
};
private static final int mechPolicies[] = {
// %%% RL: Policies should actually depend on the external channel
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOACTIVE|PolicyUtils.NODICTIONARY,
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5
PolicyUtils.NOANONYMOUS, // PLAIN
};
private static final int EXTERNAL = 0;
private static final int CRAMMD5 = 1;
private static final int PLAIN = 2;
public ClientFactoryImpl() {
}
public SaslClient createSaslClient(String[] mechs,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
for (int i = 0; i < mechs.length; i++) {
if (mechs[i].equals(myMechs[EXTERNAL])
&& PolicyUtils.checkPolicy(mechPolicies[EXTERNAL], props)) {
return new ExternalClient(authorizationId);
} else if (mechs[i].equals(myMechs[CRAMMD5])
&& PolicyUtils.checkPolicy(mechPolicies[CRAMMD5], props)) {
Object[] uinfo = getUserInfo("CRAM-MD5", authorizationId, cbh);
// Callee responsible for clearing bytepw
return new CramMD5Client((String) uinfo[0],
(byte []) uinfo[1]);
} else if (mechs[i].equals(myMechs[PLAIN])
&& PolicyUtils.checkPolicy(mechPolicies[PLAIN], props)) {
Object[] uinfo = getUserInfo("PLAIN", authorizationId, cbh);
// Callee responsible for clearing bytepw
return new PlainClient(authorizationId,
(String) uinfo[0], (byte []) uinfo[1]);
}
}
return null;
};
public String[] getMechanismNames(Map<String,?> props) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
}
/**
* Gets the authentication id and password. The
* password is converted to bytes using UTF-8 and stored in bytepw.
* The authentication id is stored in authId.
*
* @param prefix The non-null prefix to use for the prompt (e.g., mechanism
* name)
* @param authorizationId The possibly null authorization id. This is used
* as a default for the NameCallback. If null, it is not used in prompt.
* @param cbh The non-null callback handler to use.
* @return an {authid, passwd} pair
*/
private Object[] getUserInfo(String prefix, String authorizationId,
CallbackHandler cbh) throws SaslException {
if (cbh == null) {
throw new SaslException(
"Callback handler to get username/password required");
}
try {
String userPrompt = prefix + " authentication id: ";
String passwdPrompt = prefix + " password: ";
NameCallback ncb = authorizationId == null?
new NameCallback(userPrompt) :
new NameCallback(userPrompt, authorizationId);
PasswordCallback pcb = new PasswordCallback(passwdPrompt, false);
cbh.handle(new Callback[]{ncb,pcb});
char[] pw = pcb.getPassword();
byte[] bytepw;
String authId;
if (pw != null) {
bytepw = new String(pw).getBytes("UTF8");
pcb.clearPassword();
} else {
bytepw = null;
}
authId = ncb.getName();
return new Object[]{authId, bytepw};
} catch (IOException e) {
throw new SaslException("Cannot get password", e);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Cannot get userid/password", e);
}
}
}

View File

@@ -0,0 +1,228 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.Sasl;
// For HMAC_MD5
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Base class for implementing CRAM-MD5 client and server mechanisms.
*
* @author Vincent Ryan
* @author Rosanna Lee
*/
abstract class CramMD5Base {
protected boolean completed = false;
protected boolean aborted = false;
protected byte[] pw;
protected CramMD5Base() {
initLogger();
}
/**
* Retrieves this mechanism's name.
*
* @return The string "CRAM-MD5".
*/
public String getMechanismName() {
return "CRAM-MD5";
}
/**
* Determines whether this mechanism has completed.
* CRAM-MD5 completes after processing one challenge from the server.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer. CRAM-MD5 supports no security layer.
*
* @throws SaslException If attempt to use this method.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 supports neither integrity nor privacy");
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
/**
* Wraps the outgoing buffer. CRAM-MD5 supports no security layer.
*
* @throws SaslException If attempt to use this method.
*/
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 supports neither integrity nor privacy");
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@codeisComplete()} returns true); otherwise, a
* {@codeSaslException} is thrown.
*
* @return value of property; only QOP is applicable to CRAM-MD5.
* @exception IllegalStateException if this authentication exchange has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
if (propName.equals(Sasl.QOP)) {
return "auth";
} else {
return null;
}
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
public void dispose() throws SaslException {
clearPassword();
}
protected void clearPassword() {
if (pw != null) {
// zero out password
for (int i = 0; i < pw.length; i++) {
pw[i] = (byte)0;
}
pw = null;
}
}
protected void finalize() {
clearPassword();
}
static private final int MD5_BLOCKSIZE = 64;
/**
* Hashes its input arguments according to HMAC-MD5 (RFC 2104)
* and returns the resulting digest in its ASCII representation.
*
* HMAC-MD5 function is described as follows:
*
* MD5(key XOR opad, MD5(key XOR ipad, text))
*
* where key is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* text is the data to be protected
*/
final static String HMAC_MD5(byte[] key, byte[] text)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
/* digest the key if longer than 64 bytes */
if (key.length > MD5_BLOCKSIZE) {
key = md5.digest(key);
}
byte[] ipad = new byte[MD5_BLOCKSIZE]; /* inner padding */
byte[] opad = new byte[MD5_BLOCKSIZE]; /* outer padding */
byte[] digest;
int i;
/* store key in pads */
for (i = 0; i < key.length; i++) {
ipad[i] = key[i];
opad[i] = key[i];
}
/* XOR key with pads */
for (i = 0; i < MD5_BLOCKSIZE; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* inner MD5 */
md5.update(ipad);
md5.update(text);
digest = md5.digest();
/* outer MD5 */
md5.update(opad);
md5.update(digest);
digest = md5.digest();
// Get character representation of digest
StringBuffer digestString = new StringBuffer();
for (i = 0; i < digest.length; i++) {
if ((digest[i] & 0x000000ff) < 0x10) {
digestString.append("0" +
Integer.toHexString(digest[i] & 0x000000ff));
} else {
digestString.append(
Integer.toHexString(digest[i] & 0x000000ff));
}
}
Arrays.fill(ipad, (byte)0);
Arrays.fill(opad, (byte)0);
ipad = null;
opad = null;
return (digestString.toString());
}
/**
* Sets logger field.
*/
private static synchronized void initLogger() {
if (logger == null) {
logger = Logger.getLogger(SASL_LOGGER_NAME);
}
}
/**
* Logger for debug messages
*/
private static final String SASL_LOGGER_NAME = "javax.security.sasl";
protected static Logger logger; // set in initLogger(); lazily loads logger
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Implements the CRAM-MD5 SASL client-side mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2195.txt">RFC 2195</A>).
* CRAM-MD5 has no initial response. It receives bytes from
* the server as a challenge, which it hashes by using MD5 and the password.
* It concatenates the authentication ID with this result and returns it
* as the response to the challenge. At that point, the exchange is complete.
*
* @author Vincent Ryan
* @author Rosanna Lee
*/
final class CramMD5Client extends CramMD5Base implements SaslClient {
private String username;
/**
* Creates a SASL mechanism with client credentials that it needs
* to participate in CRAM-MD5 authentication exchange with the server.
*
* @param authID A non-null string representing the principal
* being authenticated.
*
* @param pw A non-null String or byte[]
* containing the password. If it is an array, it is first cloned.
*/
CramMD5Client(String authID, byte[] pw) throws SaslException {
if (authID == null || pw == null) {
throw new SaslException(
"CRAM-MD5: authentication ID and password must be specified");
}
username = authID;
this.pw = pw; // caller should have already cloned
}
/**
* CRAM-MD5 has no initial response.
*/
public boolean hasInitialResponse() {
return false;
}
/**
* Processes the challenge data.
*
* The server sends a challenge data using which the client must
* compute an MD5-digest with its password as the key.
*
* @param challengeData A non-null byte array containing the challenge
* data from the server.
* @return A non-null byte array containing the response to be sent to
* the server.
* @throws SaslException If platform does not have MD5 support
* @throw IllegalStateException if this method is invoked more than once.
*/
public byte[] evaluateChallenge(byte[] challengeData)
throws SaslException {
// See if we've been here before
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 authentication already completed");
}
if (aborted) {
throw new IllegalStateException(
"CRAM-MD5 authentication previously aborted due to error");
}
// generate a keyed-MD5 digest from the user's password and challenge.
try {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "CRAMCLNT01:Received challenge: {0}",
new String(challengeData, "UTF8"));
}
String digest = HMAC_MD5(pw, challengeData);
// clear it when we no longer need it
clearPassword();
// response is username + " " + digest
String resp = username + " " + digest;
logger.log(Level.FINE, "CRAMCLNT02:Sending response: {0}", resp);
completed = true;
return resp.getBytes("UTF8");
} catch (java.security.NoSuchAlgorithmException e) {
aborted = true;
throw new SaslException("MD5 algorithm not available on platform", e);
} catch (java.io.UnsupportedEncodingException e) {
aborted = true;
throw new SaslException("UTF8 not available on platform", e);
}
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import javax.security.auth.callback.*;
import java.util.Random;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
/**
* Implements the CRAM-MD5 SASL server-side mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2195.txt">RFC 2195</A>).
* CRAM-MD5 has no initial response.
*
* client <---- M={random, timestamp, server-fqdn} ------- server
* client ----- {username HMAC_MD5(pw, M)} --------------> server
*
* CallbackHandler must be able to handle the following callbacks:
* - NameCallback: default name is name of user for whom to get password
* - PasswordCallback: must fill in password; if empty, no pw
* - AuthorizeCallback: must setAuthorized() and canonicalized authorization id
* - auth id == authzid, but needed to get canonicalized authzid
*
* @author Rosanna Lee
*/
final class CramMD5Server extends CramMD5Base implements SaslServer {
private String fqdn;
private byte[] challengeData = null;
private String authzid;
private CallbackHandler cbh;
/**
* Creates a CRAM-MD5 SASL server.
*
* @param protocol ignored in CRAM-MD5
* @param serverFqdn non-null, used in generating a challenge
* @param props ignored in CRAM-MD5
* @param cbh find password, authorize user
*/
CramMD5Server(String protocol, String serverFqdn, Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
if (serverFqdn == null) {
throw new SaslException(
"CRAM-MD5: fully qualified server name must be specified");
}
fqdn = serverFqdn;
this.cbh = cbh;
}
/**
* Generates challenge based on response sent by client.
*
* CRAM-MD5 has no initial response.
* First call generates challenge.
* Second call verifies client response. If authentication fails, throws
* SaslException.
*
* @param responseData A non-null byte array containing the response
* data from the client.
* @return A non-null byte array containing the challenge to be sent to
* the client for the first call; null when 2nd call is successful.
* @throws SaslException If authentication fails.
*/
public byte[] evaluateResponse(byte[] responseData)
throws SaslException {
// See if we've been here before
if (completed) {
throw new IllegalStateException(
"CRAM-MD5 authentication already completed");
}
if (aborted) {
throw new IllegalStateException(
"CRAM-MD5 authentication previously aborted due to error");
}
try {
if (challengeData == null) {
if (responseData.length != 0) {
aborted = true;
throw new SaslException(
"CRAM-MD5 does not expect any initial response");
}
// Generate challenge {random, timestamp, fqdn}
Random random = new Random();
long rand = random.nextLong();
long timestamp = System.currentTimeMillis();
StringBuffer buf = new StringBuffer();
buf.append('<');
buf.append(rand);
buf.append('.');
buf.append(timestamp);
buf.append('@');
buf.append(fqdn);
buf.append('>');
String challengeStr = buf.toString();
logger.log(Level.FINE,
"CRAMSRV01:Generated challenge: {0}", challengeStr);
challengeData = challengeStr.getBytes("UTF8");
return challengeData.clone();
} else {
// Examine response to see if correctly encrypted challengeData
if(logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"CRAMSRV02:Received response: {0}",
new String(responseData, "UTF8"));
}
// Extract username from response
int ulen = 0;
for (int i = 0; i < responseData.length; i++) {
if (responseData[i] == ' ') {
ulen = i;
break;
}
}
if (ulen == 0) {
aborted = true;
throw new SaslException(
"CRAM-MD5: Invalid response; space missing");
}
String username = new String(responseData, 0, ulen, "UTF8");
logger.log(Level.FINE,
"CRAMSRV03:Extracted username: {0}", username);
// Get user's password
NameCallback ncb =
new NameCallback("CRAM-MD5 authentication ID: ", username);
PasswordCallback pcb =
new PasswordCallback("CRAM-MD5 password: ", false);
cbh.handle(new Callback[]{ncb,pcb});
char pwChars[] = pcb.getPassword();
if (pwChars == null || pwChars.length == 0) {
// user has no password; OK to disclose to server
aborted = true;
throw new SaslException(
"CRAM-MD5: username not found: " + username);
}
pcb.clearPassword();
String pwStr = new String(pwChars);
for (int i = 0; i < pwChars.length; i++) {
pwChars[i] = 0;
}
pw = pwStr.getBytes("UTF8");
// Generate a keyed-MD5 digest from the user's password and
// original challenge.
String digest = HMAC_MD5(pw, challengeData);
logger.log(Level.FINE,
"CRAMSRV04:Expecting digest: {0}", digest);
// clear pw when we no longer need it
clearPassword();
// Check whether digest is as expected
byte [] expectedDigest = digest.getBytes("UTF8");
int digestLen = responseData.length - ulen - 1;
if (expectedDigest.length != digestLen) {
aborted = true;
throw new SaslException("Invalid response");
}
int j = 0;
for (int i = ulen + 1; i < responseData.length ; i++) {
if (expectedDigest[j++] != responseData[i]) {
aborted = true;
throw new SaslException("Invalid response");
}
}
// All checks out, use AuthorizeCallback to canonicalize name
AuthorizeCallback acb = new AuthorizeCallback(username, username);
cbh.handle(new Callback[]{acb});
if (acb.isAuthorized()) {
authzid = acb.getAuthorizedID();
} else {
// Not authorized
aborted = true;
throw new SaslException(
"CRAM-MD5: user not authorized: " + username);
}
logger.log(Level.FINE,
"CRAMSRV05:Authorization id: {0}", authzid);
completed = true;
return null;
}
} catch (UnsupportedEncodingException e) {
aborted = true;
throw new SaslException("UTF8 not available on platform", e);
} catch (NoSuchAlgorithmException e) {
aborted = true;
throw new SaslException("MD5 algorithm not available on platform", e);
} catch (UnsupportedCallbackException e) {
aborted = true;
throw new SaslException("CRAM-MD5 authentication failed", e);
} catch (SaslException e) {
throw e; // rethrow
} catch (IOException e) {
aborted = true;
throw new SaslException("CRAM-MD5 authentication failed", e);
}
}
public String getAuthorizationID() {
if (completed) {
return authzid;
} else {
throw new IllegalStateException(
"CRAM-MD5 authentication not completed");
}
}
}

View File

@@ -0,0 +1,159 @@
/*
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
/**
* Implements the EXTERNAL SASL client mechanism.
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>).
* The EXTERNAL mechanism returns the optional authorization ID as
* the initial response. It processes no challenges.
*
* @author Rosanna Lee
*/
final class ExternalClient implements SaslClient {
private byte[] username;
private boolean completed = false;
/**
* Constructs an External mechanism with optional authorization ID.
*
* @param authorizationID If non-null, used to specify authorization ID.
* @throws SaslException if cannot convert authorizationID into UTF-8
* representation.
*/
ExternalClient(String authorizationID) throws SaslException {
if (authorizationID != null) {
try {
username = authorizationID.getBytes("UTF8");
} catch (java.io.UnsupportedEncodingException e) {
throw new SaslException("Cannot convert " + authorizationID +
" into UTF-8", e);
}
} else {
username = new byte[0];
}
}
/**
* Retrieves this mechanism's name for initiating the "EXTERNAL" protocol
* exchange.
*
* @return The string "EXTERNAL".
*/
public String getMechanismName() {
return "EXTERNAL";
}
/**
* This mechanism has an initial response.
*/
public boolean hasInitialResponse() {
return true;
}
public void dispose() throws SaslException {
}
/**
* Processes the challenge data.
* It returns the EXTERNAL mechanism's initial response,
* which is the authorization id encoded in UTF-8.
* This is the optional information that is sent along with the SASL command.
* After this method is called, isComplete() returns true.
*
* @param challengeData Ignored.
* @return The possible empty initial response.
* @throws SaslException If authentication has already been called.
*/
public byte[] evaluateChallenge(byte[] challengeData)
throws SaslException {
if (completed) {
throw new IllegalStateException(
"EXTERNAL authentication already completed");
}
completed = true;
return username;
}
/**
* Returns whether this mechanism is complete.
* @return true if initial response has been sent; false otherwise.
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException("EXTERNAL has no supported QOP");
} else {
throw new IllegalStateException(
"EXTERNAL authentication Not completed");
}
}
/**
* Wraps the outgoing buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException("EXTERNAL has no supported QOP");
} else {
throw new IllegalStateException(
"EXTERNAL authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, a
* {@code IllegalStateException} is thrown.
*
* @return null No property is applicable to this mechanism.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
return null;
} else {
throw new IllegalStateException(
"EXTERNAL authentication not completed");
}
}
}

View File

@@ -0,0 +1,205 @@
/*
* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
/**
* Implements the PLAIN SASL client mechanism.
* (<A
* HREF="http://ftp.isi.edu/in-notes/rfc2595.txt">RFC 2595</A>)
*
* @author Rosanna Lee
*/
final class PlainClient implements SaslClient {
private boolean completed = false;
private byte[] pw;
private String authorizationID;
private String authenticationID;
private static byte SEP = 0; // US-ASCII <NUL>
/**
* Creates a SASL mechanism with client credentials that it needs
* to participate in Plain authentication exchange with the server.
*
* @param authorizationID A possibly null string representing the principal
* for which authorization is being granted; if null, same as
* authenticationID
* @param authenticationID A non-null string representing the principal
* being authenticated. pw is associated with with this principal.
* @param pw A non-null byte[] containing the password.
*/
PlainClient(String authorizationID, String authenticationID, byte[] pw)
throws SaslException {
if (authenticationID == null || pw == null) {
throw new SaslException(
"PLAIN: authorization ID and password must be specified");
}
this.authorizationID = authorizationID;
this.authenticationID = authenticationID;
this.pw = pw; // caller should have already cloned
}
/**
* Retrieves this mechanism's name for to initiate the PLAIN protocol
* exchange.
*
* @return The string "PLAIN".
*/
public String getMechanismName() {
return "PLAIN";
}
public boolean hasInitialResponse() {
return true;
}
public void dispose() throws SaslException {
clearPassword();
}
/**
* Retrieves the initial response for the SASL command, which for
* PLAIN is the concatenation of authorization ID, authentication ID
* and password, with each component separated by the US-ASCII <NUL> byte.
*
* @param challengeData Ignored
* @return A non-null byte array containing the response to be sent to the server.
* @throws SaslException If cannot encode ids in UTF-8
* @throw IllegalStateException if authentication already completed
*/
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
if (completed) {
throw new IllegalStateException(
"PLAIN authentication already completed");
}
completed = true;
try {
byte[] authz = (authorizationID != null)?
authorizationID.getBytes("UTF8") :
null;
byte[] auth = authenticationID.getBytes("UTF8");
byte[] answer = new byte[pw.length + auth.length + 2 +
(authz == null ? 0 : authz.length)];
int pos = 0;
if (authz != null) {
System.arraycopy(authz, 0, answer, 0, authz.length);
pos = authz.length;
}
answer[pos++] = SEP;
System.arraycopy(auth, 0, answer, pos, auth.length);
pos += auth.length;
answer[pos++] = SEP;
System.arraycopy(pw, 0, answer, pos, pw.length);
clearPassword();
return answer;
} catch (java.io.UnsupportedEncodingException e) {
throw new SaslException("Cannot get UTF-8 encoding of ids", e);
}
}
/**
* Determines whether this mechanism has completed.
* Plain completes after returning one response.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Unwraps the incoming buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
if (completed) {
throw new SaslException(
"PLAIN supports neither integrity nor privacy");
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
/**
* Wraps the outgoing buffer.
*
* @throws SaslException Not applicable to this mechanism.
*/
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (completed) {
throw new SaslException(
"PLAIN supports neither integrity nor privacy");
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
/**
* Retrieves the negotiated property.
* This method can be called only after the authentication exchange has
* completed (i.e., when {@code isComplete()} returns true); otherwise, a
* {@code SaslException} is thrown.
*
* @return value of property; only QOP is applicable to PLAIN.
* @exception IllegalStateException if this authentication exchange
* has not completed
*/
public Object getNegotiatedProperty(String propName) {
if (completed) {
if (propName.equals(Sasl.QOP)) {
return "auth";
} else {
return null;
}
} else {
throw new IllegalStateException("PLAIN authentication not completed");
}
}
private void clearPassword() {
if (pw != null) {
// zero out password
for (int i = 0; i < pw.length; i++) {
pw[i] = (byte)0;
}
pw = null;
}
}
protected void finalize() {
clearPassword();
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* The SASL provider.
* Provides client support for
* - EXTERNAL
* - PLAIN
* - CRAM-MD5
* - DIGEST-MD5
* - GSSAPI/Kerberos v5
* - NTLM
* And server support for
* - CRAM-MD5
* - DIGEST-MD5
* - GSSAPI/Kerberos v5
* - NTLM
*/
public final class Provider extends java.security.Provider {
private static final long serialVersionUID = 8622598936488630849L;
private static final String info = "Sun SASL provider" +
"(implements client mechanisms for: " +
"DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
" server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)";
public Provider() {
super("SunSASL", 1.8d, info);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
// Client mechanisms
put("SaslClientFactory.DIGEST-MD5",
"com.sun.security.sasl.digest.FactoryImpl");
put("SaslClientFactory.NTLM",
"com.sun.security.sasl.ntlm.FactoryImpl");
put("SaslClientFactory.GSSAPI",
"com.sun.security.sasl.gsskerb.FactoryImpl");
put("SaslClientFactory.EXTERNAL",
"com.sun.security.sasl.ClientFactoryImpl");
put("SaslClientFactory.PLAIN",
"com.sun.security.sasl.ClientFactoryImpl");
put("SaslClientFactory.CRAM-MD5",
"com.sun.security.sasl.ClientFactoryImpl");
// Server mechanisms
put("SaslServerFactory.CRAM-MD5",
"com.sun.security.sasl.ServerFactoryImpl");
put("SaslServerFactory.GSSAPI",
"com.sun.security.sasl.gsskerb.FactoryImpl");
put("SaslServerFactory.DIGEST-MD5",
"com.sun.security.sasl.digest.FactoryImpl");
put("SaslServerFactory.NTLM",
"com.sun.security.sasl.ntlm.FactoryImpl");
return null;
}
});
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl;
import javax.security.sasl.*;
import com.sun.security.sasl.util.PolicyUtils;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* Server factory for CRAM-MD5.
*
* Requires the following callback to be satisfied by callback handler
* when using CRAM-MD5.
* - AuthorizeCallback (to get canonicalized authzid)
*
* @author Rosanna Lee
*/
final public class ServerFactoryImpl implements SaslServerFactory {
private static final String myMechs[] = {
"CRAM-MD5", //
};
private static final int mechPolicies[] = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5
};
private static final int CRAMMD5 = 0;
public ServerFactoryImpl() {
}
public SaslServer createSaslServer(String mech,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
if (mech.equals(myMechs[CRAMMD5])
&& PolicyUtils.checkPolicy(mechPolicies[CRAMMD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback required");
}
return new CramMD5Server(protocol, serverName, props, cbh);
}
return null;
};
public String[] getMechanismNames(Map<String,?> props) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,700 @@
/*
* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.security.NoSuchAlgorithmException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* An implementation of the DIGEST-MD5
* (<a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>) SASL
* (<a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>) mechanism.
*
* The DIGEST-MD5 SASL mechanism specifies two modes of authentication.
* - Initial Authentication
* - Subsequent Authentication - optional, (currently unsupported)
*
* Required callbacks:
* - RealmChoiceCallback
* shows user list of realms server has offered; handler must choose one
* from list
* - RealmCallback
* shows user the only realm server has offered or none; handler must
* enter realm to use
* - NameCallback
* handler must enter username to use for authentication
* - PasswordCallback
* handler must enter password for username to use for authentication
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* quality of protection; list of auth, auth-int, auth-conf; default is "auth"
* javax.security.sasl.strength
* auth-conf strength; list of high, medium, low; default is highest
* available on platform ["high,medium,low"].
* high means des3 or rc4 (128); medium des or rc4-56; low is rc4-40;
* choice of cipher depends on its availablility on platform
* javax.security.sasl.maxbuf
* max receive buffer size; default is 65536
* javax.security.sasl.sendmaxbuffer
* max send buffer size; default is 65536; (min with server max recv size)
*
* com.sun.security.sasl.digest.cipher
* name a specific cipher to use; setting must be compatible with the
* setting of the javax.security.sasl.strength property.
*
* @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
* - Simple Authentication and Security Layer (SASL)
* @see <a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>
* - Using Digest Authentication as a SASL Mechanism
* @see <a href="http://java.sun.com/products/jce">Java(TM)
* Cryptography Extension 1.2.1 (JCE)</a>
* @see <a href="http://java.sun.com/products/jaas">Java(TM)
* Authentication and Authorization Service (JAAS)</a>
*
* @author Jonathan Bruce
* @author Rosanna Lee
*/
final class DigestMD5Client extends DigestMD5Base implements SaslClient {
private static final String MY_CLASS_NAME = DigestMD5Client.class.getName();
// Property for specifying cipher explicitly
private static final String CIPHER_PROPERTY =
"com.sun.security.sasl.digest.cipher";
/* Directives encountered in challenges sent by the server. */
private static final String[] DIRECTIVE_KEY = {
"realm", // >= 0 times
"qop", // atmost once; default is "auth"
"algorithm", // exactly once
"nonce", // exactly once
"maxbuf", // atmost once; default is 65536
"charset", // atmost once; default is ISO 8859-1
"cipher", // exactly once if qop is "auth-conf"
"rspauth", // exactly once in 2nd challenge
"stale", // atmost once for in subsequent auth (not supported)
};
/* Indices into DIRECTIVE_KEY */
private static final int REALM = 0;
private static final int QOP = 1;
private static final int ALGORITHM = 2;
private static final int NONCE = 3;
private static final int MAXBUF = 4;
private static final int CHARSET = 5;
private static final int CIPHER = 6;
private static final int RESPONSE_AUTH = 7;
private static final int STALE = 8;
private int nonceCount; // number of times nonce has been used/seen
/* User-supplied/generated information */
private String specifiedCipher; // cipher explicitly requested by user
private byte[] cnonce; // client generated nonce
private String username;
private char[] passwd;
private byte[] authzidBytes; // byte repr of authzid
/**
* Constructor for DIGEST-MD5 mechanism.
*
* @param authzid A non-null String representing the principal
* for which authorization is being granted..
* @param digestURI A non-null String representing detailing the
* combined protocol and host being used for authentication.
* @param props The possibly null properties to be used by the SASL
* mechanism to configure the authentication exchange.
* @param cbh The non-null CallbackHanlder object for callbacks
* @throws SaslException if no authentication ID or password is supplied
*/
DigestMD5Client(String authzid, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh);
// authzID can only be encoded in UTF8 - RFC 2222
if (authzid != null) {
this.authzid = authzid;
try {
authzidBytes = authzid.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error encoding authzid value into UTF-8", e);
}
}
if (props != null) {
specifiedCipher = (String)props.get(CIPHER_PROPERTY);
logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}",
specifiedCipher);
}
}
/**
* DIGEST-MD5 has no initial response
*
* @return false
*/
public boolean hasInitialResponse() {
return false;
}
/**
* Process the challenge data.
*
* The server sends a digest-challenge which the client must reply to
* in a digest-response. When the authentication is complete, the
* completed field is set to true.
*
* @param challengeData A non-null byte array containing the challenge
* data from the server.
* @return A possibly null byte array containing the response to
* be sent to the server.
*
* @throws SaslException If the platform does not have MD5 digest support
* or if the server sends an invalid challenge.
*/
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
if (challengeData.length > MAX_CHALLENGE_LENGTH) {
throw new SaslException(
"DIGEST-MD5: Invalid digest-challenge length. Got: " +
challengeData.length + " Expected < " + MAX_CHALLENGE_LENGTH);
}
/* Extract and process digest-challenge */
byte[][] challengeVal;
switch (step) {
case 2:
/* Process server's first challenge (from Step 1) */
/* Get realm, qop, maxbuf, charset, algorithm, cipher, nonce
directives */
List<byte[]> realmChoices = new ArrayList<byte[]>(3);
challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY,
realmChoices, REALM);
try {
processChallenge(challengeVal, realmChoices);
checkQopSupport(challengeVal[QOP], challengeVal[CIPHER]);
++step;
return generateClientResponse(challengeVal[CHARSET]);
} catch (SaslException e) {
step = 0;
clearPassword();
throw e; // rethrow
} catch (IOException e) {
step = 0;
clearPassword();
throw new SaslException("DIGEST-MD5: Error generating " +
"digest response-value", e);
}
case 3:
try {
/* Process server's step 3 (server response to digest response) */
/* Get rspauth directive */
challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY,
null, REALM);
validateResponseValue(challengeVal[RESPONSE_AUTH]);
/* Initialize SecurityCtx implementation */
if (integrity && privacy) {
secCtx = new DigestPrivacy(true /* client */);
} else if (integrity) {
secCtx = new DigestIntegrity(true /* client */);
}
return null; // Mechanism has completed.
} finally {
clearPassword();
step = 0; // Set to invalid state
completed = true;
}
default:
// No other possible state
throw new SaslException("DIGEST-MD5: Client at illegal state");
}
}
/**
* Record information from the challengeVal array into variables/fields.
* Check directive values that are multi-valued and ensure that mandatory
* directives not missing from the digest-challenge.
*
* @throws SaslException if a sasl is a the mechanism cannot
* correcly handle a callbacks or if a violation in the
* digest challenge format is detected.
*/
private void processChallenge(byte[][] challengeVal, List<byte[]> realmChoices)
throws SaslException, UnsupportedEncodingException {
/* CHARSET: optional atmost once */
if (challengeVal[CHARSET] != null) {
if (!"utf-8".equals(new String(challengeVal[CHARSET], encoding))) {
throw new SaslException("DIGEST-MD5: digest-challenge format " +
"violation. Unrecognised charset value: " +
new String(challengeVal[CHARSET]));
} else {
encoding = "UTF8";
useUTF8 = true;
}
}
/* ALGORITHM: required exactly once */
if (challengeVal[ALGORITHM] == null) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation: algorithm directive missing");
} else if (!"md5-sess".equals(new String(challengeVal[ALGORITHM], encoding))) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation. Invalid value for 'algorithm' directive: " +
challengeVal[ALGORITHM]);
}
/* NONCE: required exactly once */
if (challengeVal[NONCE] == null) {
throw new SaslException("DIGEST-MD5: Digest-challenge format " +
"violation: nonce directive missing");
} else {
nonce = challengeVal[NONCE];
}
try {
/* REALM: optional, if multiple, stored in realmChoices */
String[] realmTokens = null;
if (challengeVal[REALM] != null) {
if (realmChoices == null || realmChoices.size() <= 1) {
// Only one realm specified
negotiatedRealm = new String(challengeVal[REALM], encoding);
} else {
realmTokens = new String[realmChoices.size()];
for (int i = 0; i < realmTokens.length; i++) {
realmTokens[i] =
new String(realmChoices.get(i), encoding);
}
}
}
NameCallback ncb = authzid == null ?
new NameCallback("DIGEST-MD5 authentication ID: ") :
new NameCallback("DIGEST-MD5 authentication ID: ", authzid);
PasswordCallback pcb =
new PasswordCallback("DIGEST-MD5 password: ", false);
if (realmTokens == null) {
// Server specified <= 1 realm
// If 0, RFC 2831: the client SHOULD solicit a realm from the user.
RealmCallback tcb =
(negotiatedRealm == null? new RealmCallback("DIGEST-MD5 realm: ") :
new RealmCallback("DIGEST-MD5 realm: ", negotiatedRealm));
cbh.handle(new Callback[] {tcb, ncb, pcb});
/* Acquire realm from RealmCallback */
negotiatedRealm = tcb.getText();
if (negotiatedRealm == null) {
negotiatedRealm = "";
}
} else {
RealmChoiceCallback ccb = new RealmChoiceCallback(
"DIGEST-MD5 realm: ",
realmTokens,
0, false);
cbh.handle(new Callback[] {ccb, ncb, pcb});
// Acquire realm from RealmChoiceCallback
int[] selected = ccb.getSelectedIndexes();
if (selected == null
|| selected[0] < 0
|| selected[0] >= realmTokens.length) {
throw new SaslException("DIGEST-MD5: Invalid realm chosen");
}
negotiatedRealm = realmTokens[selected[0]];
}
passwd = pcb.getPassword();
pcb.clearPassword();
username = ncb.getName();
} catch (SaslException se) {
throw se;
} catch (UnsupportedCallbackException e) {
throw new SaslException("DIGEST-MD5: Cannot perform callback to " +
"acquire realm, authentication ID or password", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: Error acquiring realm, authentication ID or password", e);
}
if (username == null || passwd == null) {
throw new SaslException(
"DIGEST-MD5: authentication ID and password must be specified");
}
/* MAXBUF: optional atmost once */
int srvMaxBufSize =
(challengeVal[MAXBUF] == null) ? DEFAULT_MAXBUF
: Integer.parseInt(new String(challengeVal[MAXBUF], encoding));
sendMaxBufSize =
(sendMaxBufSize == 0) ? srvMaxBufSize
: Math.min(sendMaxBufSize, srvMaxBufSize);
}
/**
* Parses the 'qop' directive. If 'auth-conf' is specified by
* the client and offered as a QOP option by the server, then a check
* is client-side supported ciphers is performed.
*
* @throws IOException
*/
private void checkQopSupport(byte[] qopInChallenge, byte[] ciphersInChallenge)
throws IOException {
/* QOP: optional; if multiple, merged earlier */
String qopOptions;
if (qopInChallenge == null) {
qopOptions = "auth";
} else {
qopOptions = new String(qopInChallenge, encoding);
}
// process
String[] serverQopTokens = new String[3];
byte[] serverQop = parseQop(qopOptions, serverQopTokens,
true /* ignore unrecognized tokens */);
byte serverAllQop = combineMasks(serverQop);
switch (findPreferredMask(serverAllQop, qop)) {
case 0:
throw new SaslException("DIGEST-MD5: No common protection " +
"layer between client and server");
case NO_PROTECTION:
negotiatedQop = "auth";
// buffer sizes not applicable
break;
case INTEGRITY_ONLY_PROTECTION:
negotiatedQop = "auth-int";
integrity = true;
rawSendSize = sendMaxBufSize - 16;
break;
case PRIVACY_PROTECTION:
negotiatedQop = "auth-conf";
privacy = integrity = true;
rawSendSize = sendMaxBufSize - 26;
checkStrengthSupport(ciphersInChallenge);
break;
}
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "DIGEST61:Raw send size: {0}",
new Integer(rawSendSize));
}
}
/**
* Processes the 'cipher' digest-challenge directive. This allows the
* mechanism to check for client-side support against the list of
* supported ciphers send by the server. If no match is found,
* the mechanism aborts.
*
* @throws SaslException If an error is encountered in processing
* the cipher digest-challenge directive or if no client-side
* support is found.
*/
private void checkStrengthSupport(byte[] ciphersInChallenge)
throws IOException {
/* CIPHER: required exactly once if qop=auth-conf */
if (ciphersInChallenge == null) {
throw new SaslException("DIGEST-MD5: server did not specify " +
"cipher to use for 'auth-conf'");
}
// First determine ciphers that server supports
String cipherOptions = new String(ciphersInChallenge, encoding);
StringTokenizer parser = new StringTokenizer(cipherOptions, ", \t\n");
int tokenCount = parser.countTokens();
String token = null;
byte[] serverCiphers = { UNSET,
UNSET,
UNSET,
UNSET,
UNSET };
String[] serverCipherStrs = new String[serverCiphers.length];
// Parse ciphers in challenge; mark each that server supports
for (int i = 0; i < tokenCount; i++) {
token = parser.nextToken();
for (int j = 0; j < CIPHER_TOKENS.length; j++) {
if (token.equals(CIPHER_TOKENS[j])) {
serverCiphers[j] |= CIPHER_MASKS[j];
serverCipherStrs[j] = token; // keep for replay to server
logger.log(Level.FINE, "DIGEST62:Server supports {0}", token);
}
}
}
// Determine which ciphers are available on client
byte[] clntCiphers = getPlatformCiphers();
// Take intersection of server and client supported ciphers
byte inter = 0;
for (int i = 0; i < serverCiphers.length; i++) {
serverCiphers[i] &= clntCiphers[i];
inter |= serverCiphers[i];
}
if (inter == UNSET) {
throw new SaslException(
"DIGEST-MD5: Client supports none of these cipher suites: " +
cipherOptions);
}
// now have a clear picture of user / client; client / server
// cipher options. Leverage strength array against what is
// supported to choose a cipher.
negotiatedCipher = findCipherAndStrength(serverCiphers, serverCipherStrs);
if (negotiatedCipher == null) {
throw new SaslException("DIGEST-MD5: Unable to negotiate " +
"a strength level for 'auth-conf'");
}
logger.log(Level.FINE, "DIGEST63:Cipher suite: {0}", negotiatedCipher);
}
/**
* Steps through the ordered 'strength' array, and compares it with
* the 'supportedCiphers' array. The cipher returned represents
* the best possible cipher based on the strength preference and the
* available ciphers on both the server and client environments.
*
* @param tokens The array of cipher tokens sent by server
* @return The agreed cipher.
*/
private String findCipherAndStrength(byte[] supportedCiphers,
String[] tokens) {
byte s;
for (int i = 0; i < strength.length; i++) {
if ((s=strength[i]) != 0) {
for (int j = 0; j < supportedCiphers.length; j++) {
// If user explicitly requested cipher, then it
// must be the one we choose
if (s == supportedCiphers[j] &&
(specifiedCipher == null ||
specifiedCipher.equals(tokens[j]))) {
switch (s) {
case HIGH_STRENGTH:
negotiatedStrength = "high";
break;
case MEDIUM_STRENGTH:
negotiatedStrength = "medium";
break;
case LOW_STRENGTH:
negotiatedStrength = "low";
break;
}
return tokens[j];
}
}
}
}
return null; // none found
}
/**
* Returns digest-response suitable for an initial authentication.
*
* The following are qdstr-val (quoted string values) as per RFC 2831,
* which means that any embedded quotes must be escaped.
* realm-value
* nonce-value
* username-value
* cnonce-value
* authzid-value
* @returns {@code digest-response} in a byte array
* @throws SaslException if there is an error generating the
* response value or the cnonce value.
*/
private byte[] generateClientResponse(byte[] charset) throws IOException {
ByteArrayOutputStream digestResp = new ByteArrayOutputStream();
if (useUTF8) {
digestResp.write("charset=".getBytes(encoding));
digestResp.write(charset);
digestResp.write(',');
}
digestResp.write(("username=\"" +
quotedStringValue(username) + "\",").getBytes(encoding));
if (negotiatedRealm.length() > 0) {
digestResp.write(("realm=\"" +
quotedStringValue(negotiatedRealm) + "\",").getBytes(encoding));
}
digestResp.write("nonce=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, nonce);
digestResp.write('"');
digestResp.write(',');
nonceCount = getNonceCount(nonce);
digestResp.write(("nc=" +
nonceCountToHex(nonceCount) + ",").getBytes(encoding));
cnonce = generateNonce();
digestResp.write("cnonce=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, cnonce);
digestResp.write("\",".getBytes(encoding));
digestResp.write(("digest-uri=\"" + digestUri + "\",").getBytes(encoding));
digestResp.write("maxbuf=".getBytes(encoding));
digestResp.write(String.valueOf(recvMaxBufSize).getBytes(encoding));
digestResp.write(',');
try {
digestResp.write("response=".getBytes(encoding));
digestResp.write(generateResponseValue("AUTHENTICATE",
digestUri, negotiatedQop, username,
negotiatedRealm, passwd, nonce, cnonce,
nonceCount, authzidBytes));
digestResp.write(',');
} catch (Exception e) {
throw new SaslException(
"DIGEST-MD5: Error generating response value", e);
}
digestResp.write(("qop=" + negotiatedQop).getBytes(encoding));
if (negotiatedCipher != null) {
digestResp.write((",cipher=\"" + negotiatedCipher + "\"").getBytes(encoding));
}
if (authzidBytes != null) {
digestResp.write(",authzid=\"".getBytes(encoding));
writeQuotedStringValue(digestResp, authzidBytes);
digestResp.write("\"".getBytes(encoding));
}
if (digestResp.size() > MAX_RESPONSE_LENGTH) {
throw new SaslException ("DIGEST-MD5: digest-response size too " +
"large. Length: " + digestResp.size());
}
return digestResp.toByteArray();
}
/**
* From RFC 2831, Section 2.1.3: Step Three
* [Server] sends a message formatted as follows:
* response-auth = "rspauth" "=" response-value
* where response-value is calculated as above, using the values sent in
* step two, except that if qop is "auth", then A2 is
*
* A2 = { ":", digest-uri-value }
*
* And if qop is "auth-int" or "auth-conf" then A2 is
*
* A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" }
*/
private void validateResponseValue(byte[] fromServer) throws SaslException {
if (fromServer == null) {
throw new SaslException("DIGEST-MD5: Authenication failed. " +
"Expecting 'rspauth' authentication success message");
}
try {
byte[] expected = generateResponseValue("",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce, cnonce, nonceCount, authzidBytes);
if (!Arrays.equals(expected, fromServer)) {
/* Server's rspauth value does not match */
throw new SaslException(
"Server's rspauth value does not match what client expects");
}
} catch (NoSuchAlgorithmException e) {
throw new SaslException(
"Problem generating response value for verification", e);
} catch (IOException e) {
throw new SaslException(
"Problem generating response value for verification", e);
}
}
/**
* Returns the number of requests (including current request)
* that the client has sent in response to nonceValue.
* This is 1 the first time nonceValue is seen.
*
* We don't cache nonce values seen, and we don't support subsequent
* authentication, so the value is always 1.
*/
private static int getNonceCount(byte[] nonceValue) {
return 1;
}
private void clearPassword() {
if (passwd != null) {
for (int i = 0; i < passwd.length; i++) {
passwd[i] = 0;
}
passwd = null;
}
}
}

View File

@@ -0,0 +1,724 @@
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.security.NoSuchAlgorithmException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.logging.Level;
import javax.security.sasl.*;
import javax.security.auth.callback.*;
/**
* An implementation of the DIGEST-MD5 server SASL mechanism.
* (<a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>)
* <p>
* The DIGEST-MD5 SASL mechanism specifies two modes of authentication.
* <ul><li>Initial Authentication
* <li>Subsequent Authentication - optional, (currently not supported)
* </ul>
*
* Required callbacks:
* - RealmCallback
* used as key by handler to fetch password
* - NameCallback
* used as key by handler to fetch password
* - PasswordCallback
* handler must enter password for username/realm supplied
* - AuthorizeCallback
* handler must verify that authid/authzids are allowed and set
* authorized ID to be the canonicalized authzid (if applicable).
*
* Environment properties that affect the implementation:
* javax.security.sasl.qop:
* specifies list of qops; default is "auth"; typically, caller should set
* this to "auth, auth-int, auth-conf".
* javax.security.sasl.strength
* specifies low/medium/high strength of encryption; default is all available
* ciphers [high,medium,low]; high means des3 or rc4 (128); medium des or
* rc4-56; low is rc4-40.
* javax.security.sasl.maxbuf
* specifies max receive buf size; default is 65536
* javax.security.sasl.sendmaxbuffer
* specifies max send buf size; default is 65536 (min of this and client's max
* recv size)
*
* com.sun.security.sasl.digest.utf8:
* "true" means to use UTF-8 charset; "false" to use ISO-8859-1 encoding;
* default is "true".
* com.sun.security.sasl.digest.realm:
* space-separated list of realms; default is server name (fqdn parameter)
*
* @author Rosanna Lee
*/
final class DigestMD5Server extends DigestMD5Base implements SaslServer {
private static final String MY_CLASS_NAME = DigestMD5Server.class.getName();
private static final String UTF8_DIRECTIVE = "charset=utf-8,";
private static final String ALGORITHM_DIRECTIVE = "algorithm=md5-sess";
/*
* Always expect nonce count value to be 1 because we support only
* initial authentication.
*/
private static final int NONCE_COUNT_VALUE = 1;
/* "true" means use UTF8; "false" ISO 8859-1; default is "true" */
private static final String UTF8_PROPERTY =
"com.sun.security.sasl.digest.utf8";
/* List of space-separated realms used for authentication */
private static final String REALM_PROPERTY =
"com.sun.security.sasl.digest.realm";
/* Directives encountered in responses sent by the client. */
private static final String[] DIRECTIVE_KEY = {
"username", // exactly once
"realm", // exactly once if sent by server
"nonce", // exactly once
"cnonce", // exactly once
"nonce-count", // atmost once; default is 00000001
"qop", // atmost once; default is "auth"
"digest-uri", // atmost once; (default?)
"response", // exactly once
"maxbuf", // atmost once; default is 65536
"charset", // atmost once; default is ISO-8859-1
"cipher", // exactly once if qop is "auth-conf"
"authzid", // atmost once; default is none
"auth-param", // >= 0 times (ignored)
};
/* Indices into DIRECTIVE_KEY */
private static final int USERNAME = 0;
private static final int REALM = 1;
private static final int NONCE = 2;
private static final int CNONCE = 3;
private static final int NONCE_COUNT = 4;
private static final int QOP = 5;
private static final int DIGEST_URI = 6;
private static final int RESPONSE = 7;
private static final int MAXBUF = 8;
private static final int CHARSET = 9;
private static final int CIPHER = 10;
private static final int AUTHZID = 11;
private static final int AUTH_PARAM = 12;
/* Server-generated/supplied information */
private String specifiedQops;
private byte[] myCiphers;
private List<String> serverRealms;
DigestMD5Server(String protocol, String serverName, Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME, 1,
protocol + "/" + (serverName==null?"*":serverName),
cbh);
serverRealms = new ArrayList<String>();
useUTF8 = true; // default
if (props != null) {
specifiedQops = (String) props.get(Sasl.QOP);
if ("false".equals((String) props.get(UTF8_PROPERTY))) {
useUTF8 = false;
logger.log(Level.FINE, "DIGEST80:Server supports ISO-Latin-1");
}
String realms = (String) props.get(REALM_PROPERTY);
if (realms != null) {
StringTokenizer parser = new StringTokenizer(realms, ", \t\n");
int tokenCount = parser.countTokens();
String token = null;
for (int i = 0; i < tokenCount; i++) {
token = parser.nextToken();
logger.log(Level.FINE, "DIGEST81:Server supports realm {0}",
token);
serverRealms.add(token);
}
}
}
encoding = (useUTF8 ? "UTF8" : "8859_1");
// By default, use server name as realm
if (serverRealms.isEmpty()) {
if (serverName == null) {
throw new SaslException(
"A realm must be provided in props or serverName");
} else {
serverRealms.add(serverName);
}
}
}
public byte[] evaluateResponse(byte[] response) throws SaslException {
if (response.length > MAX_RESPONSE_LENGTH) {
throw new SaslException(
"DIGEST-MD5: Invalid digest response length. Got: " +
response.length + " Expected < " + MAX_RESPONSE_LENGTH);
}
byte[] challenge;
switch (step) {
case 1:
if (response.length != 0) {
throw new SaslException(
"DIGEST-MD5 must not have an initial response");
}
/* Generate first challenge */
String supportedCiphers = null;
if ((allQop&PRIVACY_PROTECTION) != 0) {
myCiphers = getPlatformCiphers();
StringBuffer buf = new StringBuffer();
// myCipher[i] is a byte that indicates whether CIPHER_TOKENS[i]
// is supported
for (int i = 0; i < CIPHER_TOKENS.length; i++) {
if (myCiphers[i] != 0) {
if (buf.length() > 0) {
buf.append(',');
}
buf.append(CIPHER_TOKENS[i]);
}
}
supportedCiphers = buf.toString();
}
try {
challenge = generateChallenge(serverRealms, specifiedQops,
supportedCiphers);
step = 3;
return challenge;
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error encoding challenge", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: Error generating challenge", e);
}
// Step 2 is performed by client
case 3:
/* Validates client's response and generate challenge:
* response-auth = "rspauth" "=" response-value
*/
try {
byte[][] responseVal = parseDirectives(response, DIRECTIVE_KEY,
null, REALM);
challenge = validateClientResponse(responseVal);
} catch (SaslException e) {
throw e;
} catch (UnsupportedEncodingException e) {
throw new SaslException(
"DIGEST-MD5: Error validating client response", e);
} finally {
step = 0; // Set to invalid state
}
completed = true;
/* Initialize SecurityCtx implementation */
if (integrity && privacy) {
secCtx = new DigestPrivacy(false /* not client */);
} else if (integrity) {
secCtx = new DigestIntegrity(false /* not client */);
}
return challenge;
default:
// No other possible state
throw new SaslException("DIGEST-MD5: Server at illegal state");
}
}
/**
* Generates challenge to be sent to client.
* digest-challenge =
* 1#( realm | nonce | qop-options | stale | maxbuf | charset
* algorithm | cipher-opts | auth-param )
*
* realm = "realm" "=" <"> realm-value <">
* realm-value = qdstr-val
* nonce = "nonce" "=" <"> nonce-value <">
* nonce-value = qdstr-val
* qop-options = "qop" "=" <"> qop-list <">
* qop-list = 1#qop-value
* qop-value = "auth" | "auth-int" | "auth-conf" |
* token
* stale = "stale" "=" "true"
* maxbuf = "maxbuf" "=" maxbuf-value
* maxbuf-value = 1*DIGIT
* charset = "charset" "=" "utf-8"
* algorithm = "algorithm" "=" "md5-sess"
* cipher-opts = "cipher" "=" <"> 1#cipher-value <">
* cipher-value = "3des" | "des" | "rc4-40" | "rc4" |
* "rc4-56" | token
* auth-param = token "=" ( token | quoted-string )
*/
private byte[] generateChallenge(List<String> realms, String qopStr,
String cipherStr) throws UnsupportedEncodingException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Realms (>= 0)
for (int i = 0; realms != null && i < realms.size(); i++) {
out.write("realm=\"".getBytes(encoding));
writeQuotedStringValue(out, realms.get(i).getBytes(encoding));
out.write('"');
out.write(',');
}
// Nonce - required (1)
out.write(("nonce=\"").getBytes(encoding));
nonce = generateNonce();
writeQuotedStringValue(out, nonce);
out.write('"');
out.write(',');
// QOP - optional (1) [default: auth]
// qop="auth,auth-conf,auth-int"
if (qopStr != null) {
out.write(("qop=\"").getBytes(encoding));
// Check for quotes in case of non-standard qop options
writeQuotedStringValue(out, qopStr.getBytes(encoding));
out.write('"');
out.write(',');
}
// maxbuf - optional (1) [default: 65536]
if (recvMaxBufSize != DEFAULT_MAXBUF) {
out.write(("maxbuf=\"" + recvMaxBufSize + "\",").getBytes(encoding));
}
// charset - optional (1) [default: ISO 8859_1]
if (useUTF8) {
out.write(UTF8_DIRECTIVE.getBytes(encoding));
}
if (cipherStr != null) {
out.write("cipher=\"".getBytes(encoding));
// Check for quotes in case of custom ciphers
writeQuotedStringValue(out, cipherStr.getBytes(encoding));
out.write('"');
out.write(',');
}
// algorithm - required (1)
out.write(ALGORITHM_DIRECTIVE.getBytes(encoding));
return out.toByteArray();
}
/**
* Validates client's response.
* digest-response = 1#( username | realm | nonce | cnonce |
* nonce-count | qop | digest-uri | response |
* maxbuf | charset | cipher | authzid |
* auth-param )
*
* username = "username" "=" <"> username-value <">
* username-value = qdstr-val
* cnonce = "cnonce" "=" <"> cnonce-value <">
* cnonce-value = qdstr-val
* nonce-count = "nc" "=" nc-value
* nc-value = 8LHEX
* qop = "qop" "=" qop-value
* digest-uri = "digest-uri" "=" <"> digest-uri-value <">
* digest-uri-value = serv-type "/" host [ "/" serv-name ]
* serv-type = 1*ALPHA
* host = 1*( ALPHA | DIGIT | "-" | "." )
* serv-name = host
* response = "response" "=" response-value
* response-value = 32LHEX
* LHEX = "0" | "1" | "2" | "3" |
* "4" | "5" | "6" | "7" |
* "8" | "9" | "a" | "b" |
* "c" | "d" | "e" | "f"
* cipher = "cipher" "=" cipher-value
* authzid = "authzid" "=" <"> authzid-value <">
* authzid-value = qdstr-val
* sets:
* negotiatedQop
* negotiatedCipher
* negotiatedRealm
* negotiatedStrength
* digestUri (checked and set to clients to account for case diffs)
* sendMaxBufSize
* authzid (gotten from callback)
* @return response-value ('rspauth') for client to validate
*/
private byte[] validateClientResponse(byte[][] responseVal)
throws SaslException, UnsupportedEncodingException {
/* CHARSET: optional atmost once */
if (responseVal[CHARSET] != null) {
// The client should send this directive only if the server has
// indicated it supports UTF-8.
if (!useUTF8 ||
!"utf-8".equals(new String(responseVal[CHARSET], encoding))) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Incompatible charset value: " +
new String(responseVal[CHARSET]));
}
}
// maxbuf: atmost once
int clntMaxBufSize =
(responseVal[MAXBUF] == null) ? DEFAULT_MAXBUF
: Integer.parseInt(new String(responseVal[MAXBUF], encoding));
// Max send buf size is min of client's max recv buf size and
// server's max send buf size
sendMaxBufSize = ((sendMaxBufSize == 0) ? clntMaxBufSize :
Math.min(sendMaxBufSize, clntMaxBufSize));
/* username: exactly once */
String username;
if (responseVal[USERNAME] != null) {
username = new String(responseVal[USERNAME], encoding);
logger.log(Level.FINE, "DIGEST82:Username: {0}", username);
} else {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing username.");
}
/* realm: exactly once if sent by server */
negotiatedRealm = ((responseVal[REALM] != null) ?
new String(responseVal[REALM], encoding) : "");
logger.log(Level.FINE, "DIGEST83:Client negotiated realm: {0}",
negotiatedRealm);
if (!serverRealms.contains(negotiatedRealm)) {
// Server had sent at least one realm
// Check that response is one of these
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Nonexistent realm: " + negotiatedRealm);
}
// Else, client specified realm was one of server's or server had none
/* nonce: exactly once */
if (responseVal[NONCE] == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing nonce.");
}
byte[] nonceFromClient = responseVal[NONCE];
if (!Arrays.equals(nonceFromClient, nonce)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched nonce.");
}
/* cnonce: exactly once */
if (responseVal[CNONCE] == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Missing cnonce.");
}
byte[] cnonce = responseVal[CNONCE];
/* nonce-count: atmost once */
if (responseVal[NONCE_COUNT] != null &&
NONCE_COUNT_VALUE != Integer.parseInt(
new String(responseVal[NONCE_COUNT], encoding), 16)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Nonce count does not match: " +
new String(responseVal[NONCE_COUNT]));
}
/* qop: atmost once; default is "auth" */
negotiatedQop = ((responseVal[QOP] != null) ?
new String(responseVal[QOP], encoding) : "auth");
logger.log(Level.FINE, "DIGEST84:Client negotiated qop: {0}",
negotiatedQop);
// Check that QOP is one sent by server
byte cQop;
switch (negotiatedQop) {
case "auth":
cQop = NO_PROTECTION;
break;
case "auth-int":
cQop = INTEGRITY_ONLY_PROTECTION;
integrity = true;
rawSendSize = sendMaxBufSize - 16;
break;
case "auth-conf":
cQop = PRIVACY_PROTECTION;
integrity = privacy = true;
rawSendSize = sendMaxBufSize - 26;
break;
default:
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Invalid QOP: " + negotiatedQop);
}
if ((cQop&allQop) == 0) {
throw new SaslException("DIGEST-MD5: server does not support " +
" qop: " + negotiatedQop);
}
if (privacy) {
negotiatedCipher = ((responseVal[CIPHER] != null) ?
new String(responseVal[CIPHER], encoding) : null);
if (negotiatedCipher == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. No cipher specified.");
}
int foundCipher = -1;
logger.log(Level.FINE, "DIGEST85:Client negotiated cipher: {0}",
negotiatedCipher);
// Check that cipher is one that we offered
for (int j = 0; j < CIPHER_TOKENS.length; j++) {
if (negotiatedCipher.equals(CIPHER_TOKENS[j]) &&
myCiphers[j] != 0) {
foundCipher = j;
break;
}
}
if (foundCipher == -1) {
throw new SaslException("DIGEST-MD5: server does not " +
"support cipher: " + negotiatedCipher);
}
// Set negotiatedStrength
if ((CIPHER_MASKS[foundCipher]&HIGH_STRENGTH) != 0) {
negotiatedStrength = "high";
} else if ((CIPHER_MASKS[foundCipher]&MEDIUM_STRENGTH) != 0) {
negotiatedStrength = "medium";
} else {
// assume default low
negotiatedStrength = "low";
}
logger.log(Level.FINE, "DIGEST86:Negotiated strength: {0}",
negotiatedStrength);
}
// atmost once
String digestUriFromResponse = ((responseVal[DIGEST_URI]) != null ?
new String(responseVal[DIGEST_URI], encoding) : null);
if (digestUriFromResponse != null) {
logger.log(Level.FINE, "DIGEST87:digest URI: {0}",
digestUriFromResponse);
}
// serv-type "/" host [ "/" serv-name ]
// e.g.: smtp/mail3.example.com/example.com
// e.g.: ftp/ftp.example.com
// e.g.: ldap/ldapserver.example.com
// host should match one of service's configured service names
// Check against digest URI that mech was created with
if (uriMatches(digestUri, digestUriFromResponse)) {
digestUri = digestUriFromResponse; // account for case-sensitive diffs
} else {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched URI: " + digestUriFromResponse +
"; expecting: " + digestUri);
}
// response: exactly once
byte[] responseFromClient = responseVal[RESPONSE];
if (responseFromClient == null) {
throw new SaslException("DIGEST-MD5: digest response format " +
" violation. Missing response.");
}
// authzid: atmost once
byte[] authzidBytes;
String authzidFromClient = ((authzidBytes=responseVal[AUTHZID]) != null?
new String(authzidBytes, encoding) : username);
if (authzidBytes != null) {
logger.log(Level.FINE, "DIGEST88:Authzid: {0}",
new String(authzidBytes));
}
// Ignore auth-param
// Get password need to generate verifying response
char[] passwd;
try {
// Realm and Name callbacks are used to provide info
RealmCallback rcb = new RealmCallback("DIGEST-MD5 realm: ",
negotiatedRealm);
NameCallback ncb = new NameCallback("DIGEST-MD5 authentication ID: ",
username);
// PasswordCallback is used to collect info
PasswordCallback pcb =
new PasswordCallback("DIGEST-MD5 password: ", false);
cbh.handle(new Callback[] {rcb, ncb, pcb});
passwd = pcb.getPassword();
pcb.clearPassword();
} catch (UnsupportedCallbackException e) {
throw new SaslException(
"DIGEST-MD5: Cannot perform callback to acquire password", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: IO error acquiring password", e);
}
if (passwd == null) {
throw new SaslException(
"DIGEST-MD5: cannot acquire password for " + username +
" in realm : " + negotiatedRealm);
}
try {
// Validate response value sent by client
byte[] expectedResponse;
try {
expectedResponse = generateResponseValue("AUTHENTICATE",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce /* use own nonce */,
cnonce, NONCE_COUNT_VALUE, authzidBytes);
} catch (NoSuchAlgorithmException e) {
throw new SaslException(
"DIGEST-MD5: problem duplicating client response", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: problem duplicating client response", e);
}
if (!Arrays.equals(responseFromClient, expectedResponse)) {
throw new SaslException("DIGEST-MD5: digest response format " +
"violation. Mismatched response.");
}
// Ensure that authzid mapping is OK
try {
AuthorizeCallback acb =
new AuthorizeCallback(username, authzidFromClient);
cbh.handle(new Callback[]{acb});
if (acb.isAuthorized()) {
authzid = acb.getAuthorizedID();
} else {
throw new SaslException("DIGEST-MD5: " + username +
" is not authorized to act as " + authzidFromClient);
}
} catch (SaslException e) {
throw e;
} catch (UnsupportedCallbackException e) {
throw new SaslException(
"DIGEST-MD5: Cannot perform callback to check authzid", e);
} catch (IOException e) {
throw new SaslException(
"DIGEST-MD5: IO error checking authzid", e);
}
return generateResponseAuth(username, passwd, cnonce,
NONCE_COUNT_VALUE, authzidBytes);
} finally {
// Clear password
for (int i = 0; i < passwd.length; i++) {
passwd[i] = 0;
}
}
}
private static boolean uriMatches(String thisUri, String incomingUri) {
// Full match
if (thisUri.equalsIgnoreCase(incomingUri)) {
return true;
}
// Unbound match
if (thisUri.endsWith("/*")) {
int protoAndSlash = thisUri.length() - 1;
String thisProtoAndSlash = thisUri.substring(0, protoAndSlash);
String incomingProtoAndSlash = incomingUri.substring(0, protoAndSlash);
return thisProtoAndSlash.equalsIgnoreCase(incomingProtoAndSlash);
}
return false;
}
/**
* Server sends a message formatted as follows:
* response-auth = "rspauth" "=" response-value
* where response-value is calculated as above, using the values sent in
* step two, except that if qop is "auth", then A2 is
*
* A2 = { ":", digest-uri-value }
*
* And if qop is "auth-int" or "auth-conf" then A2 is
*
* A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" }
*
* Clears password afterwards.
*/
private byte[] generateResponseAuth(String username, char[] passwd,
byte[] cnonce, int nonceCount, byte[] authzidBytes) throws SaslException {
// Construct response value
try {
byte[] responseValue = generateResponseValue("",
digestUri, negotiatedQop, username, negotiatedRealm,
passwd, nonce, cnonce, nonceCount, authzidBytes);
byte[] challenge = new byte[responseValue.length + 8];
System.arraycopy("rspauth=".getBytes(encoding), 0, challenge, 0, 8);
System.arraycopy(responseValue, 0, challenge, 8,
responseValue.length );
return challenge;
} catch (NoSuchAlgorithmException e) {
throw new SaslException("DIGEST-MD5: problem generating response", e);
} catch (IOException e) {
throw new SaslException("DIGEST-MD5: problem generating response", e);
}
}
public String getAuthorizationID() {
if (completed) {
return authzid;
} else {
throw new IllegalStateException(
"DIGEST-MD5 server negotiation not complete");
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import java.util.Map;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import com.sun.security.sasl.util.PolicyUtils;
/**
* Client and server factory for DIGEST-MD5 SASL client/server mechanisms.
* See DigestMD5Client and DigestMD5Server for input requirements.
*
* @author Jonathan Bruce
* @author Rosanna Lee
*/
public final class FactoryImpl implements SaslClientFactory,
SaslServerFactory{
private static final String myMechs[] = { "DIGEST-MD5" };
private static final int DIGEST_MD5 = 0;
private static final int mechPolicies[] = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS};
/**
* Empty constructor.
*/
public FactoryImpl() {
}
/**
* Returns a new instance of the DIGEST-MD5 SASL client mechanism.
*
* @throws SaslException If there is an error creating the DigestMD5
* SASL client.
* @return a new SaslClient; otherwise null if unsuccessful.
*/
public SaslClient createSaslClient(String[] mechs,
String authorizationId, String protocol, String serverName,
Map<String,?> props, CallbackHandler cbh)
throws SaslException {
for (int i=0; i<mechs.length; i++) {
if (mechs[i].equals(myMechs[DIGEST_MD5]) &&
PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for RealmChoiceCallback, " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new DigestMD5Client(authorizationId,
protocol, serverName, props, cbh);
}
}
return null;
}
/**
* Returns a new instance of the DIGEST-MD5 SASL server mechanism.
*
* @throws SaslException If there is an error creating the DigestMD5
* SASL server.
* @return a new SaslServer; otherwise null if unsuccessful.
*/
public SaslServer createSaslServer(String mech,
String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
throws SaslException {
if (mech.equals(myMechs[DIGEST_MD5]) &&
PolicyUtils.checkPolicy(mechPolicies[DIGEST_MD5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback, "+
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new DigestMD5Server(protocol, serverName, props, cbh);
}
return null;
}
/**
* Returns the authentication mechanisms that this factory can produce.
*
* @return String[] {"DigestMD5"} if policies in env match those of this
* factory.
*/
public String[] getMechanismNames(Map<String,?> env) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.digest;
import javax.security.sasl.SaslException;
/**
* Interface used for classes implementing integrity checking and privacy
* for DIGEST-MD5 SASL mechanism implementation.
*
* @see <a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>
* - Using Digest Authentication as a SASL Mechanism
*
* @author Jonathan Bruce
*/
interface SecurityCtx {
/**
* Wrap out-going message and return wrapped message
*
* @throws SaslException
*/
byte[] wrap(byte[] dest, int start, int len)
throws SaslException;
/**
* Unwrap incoming message and return original message
*
* @throws SaslException
*/
byte[] unwrap(byte[] outgoing, int start, int len)
throws SaslException;
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.gsskerb;
import javax.security.sasl.*;
import com.sun.security.sasl.util.PolicyUtils;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* Client/server factory for GSSAPI (Kerberos V5) SASL client/server mechs.
* See GssKrb5Client/GssKrb5Server for input requirements.
*
* @author Rosanna Lee
*/
public final class FactoryImpl implements SaslClientFactory, SaslServerFactory {
private static final String myMechs[] = {
"GSSAPI"};
private static final int mechPolicies[] = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS|PolicyUtils.NOACTIVE
};
private static final int GSS_KERB_V5 = 0;
public FactoryImpl() {
}
public SaslClient createSaslClient(String[] mechs,
String authorizationId,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
for (int i = 0; i < mechs.length; i++) {
if (mechs[i].equals(myMechs[GSS_KERB_V5])
&& PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
return new GssKrb5Client(
authorizationId,
protocol,
serverName,
props,
cbh);
}
}
return null;
};
public SaslServer createSaslServer(String mech,
String protocol,
String serverName,
Map<String,?> props,
CallbackHandler cbh) throws SaslException {
if (mech.equals(myMechs[GSS_KERB_V5])
&& PolicyUtils.checkPolicy(mechPolicies[GSS_KERB_V5], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback required");
}
return new GssKrb5Server(
protocol,
serverName,
props,
cbh);
}
return null;
};
public String[] getMechanismNames(Map<String,?> props) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, props);
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.gsskerb;
import java.util.Map;
import java.util.logging.Level;
import javax.security.sasl.*;
import com.sun.security.sasl.util.AbstractSaslImpl;
import org.ietf.jgss.*;
abstract class GssKrb5Base extends AbstractSaslImpl {
private static final String KRB5_OID_STR = "1.2.840.113554.1.2.2";
protected static Oid KRB5_OID;
protected static final byte[] EMPTY = new byte[0];
static {
try {
KRB5_OID = new Oid(KRB5_OID_STR);
} catch (GSSException ignore) {}
}
protected GSSContext secCtx = null;
protected static final int JGSS_QOP = 0; // unrelated to SASL QOP mask
protected GssKrb5Base(Map<String, ?> props, String className)
throws SaslException {
super(props, className);
}
/**
* Retrieves this mechanism's name.
*
* @return The string "GSSAPI".
*/
public String getMechanismName() {
return "GSSAPI";
}
public byte[] unwrap(byte[] incoming, int start, int len)
throws SaslException {
if (!completed) {
throw new IllegalStateException("GSSAPI authentication not completed");
}
// integrity will be true if either privacy or integrity negotiated
if (!integrity) {
throw new IllegalStateException("No security layer negotiated");
}
try {
MessageProp msgProp = new MessageProp(JGSS_QOP, false);
byte[] answer = secCtx.unwrap(incoming, start, len, msgProp);
if (privacy && !msgProp.getPrivacy()) {
throw new SaslException("Privacy not protected");
}
checkMessageProp("", msgProp);
if (logger.isLoggable(Level.FINEST)) {
traceOutput(myClassName, "KRB501:Unwrap", "incoming: ",
incoming, start, len);
traceOutput(myClassName, "KRB502:Unwrap", "unwrapped: ",
answer, 0, answer.length);
}
return answer;
} catch (GSSException e) {
throw new SaslException("Problems unwrapping SASL buffer", e);
}
}
public byte[] wrap(byte[] outgoing, int start, int len) throws SaslException {
if (!completed) {
throw new IllegalStateException("GSSAPI authentication not completed");
}
// integrity will be true if either privacy or integrity negotiated
if (!integrity) {
throw new IllegalStateException("No security layer negotiated");
}
// Generate GSS token
try {
MessageProp msgProp = new MessageProp(JGSS_QOP, privacy);
byte[] answer = secCtx.wrap(outgoing, start, len, msgProp);
if (logger.isLoggable(Level.FINEST)) {
traceOutput(myClassName, "KRB503:Wrap", "outgoing: ",
outgoing, start, len);
traceOutput(myClassName, "KRB504:Wrap", "wrapped: ",
answer, 0, answer.length);
}
return answer;
} catch (GSSException e) {
throw new SaslException("Problem performing GSS wrap", e);
}
}
public void dispose() throws SaslException {
if (secCtx != null) {
try {
secCtx.dispose();
} catch (GSSException e) {
throw new SaslException("Problem disposing GSS context", e);
}
secCtx = null;
}
}
protected void finalize() throws Throwable {
dispose();
}
void checkMessageProp(String label, MessageProp msgProp)
throws SaslException {
if (msgProp.isDuplicateToken()) {
throw new SaslException(label + "Duplicate token");
}
if (msgProp.isGapToken()) {
throw new SaslException(label + "Gap token");
}
if (msgProp.isOldToken()) {
throw new SaslException(label + "Old token");
}
if (msgProp.isUnseqToken()) {
throw new SaslException(label + "Token not in sequence");
}
}
}

View File

@@ -0,0 +1,331 @@
/*
* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.gsskerb;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import javax.security.sasl.*;
// JAAS
import javax.security.auth.callback.CallbackHandler;
// JGSS
import org.ietf.jgss.*;
/**
* Implements the GSSAPI SASL client mechanism for Kerberos V5.
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>,
* <a HREF="http://www.ietf.org/internet-drafts/draft-ietf-cat-sasl-gssapi-04.txt">draft-ietf-cat-sasl-gssapi-04.txt</a>).
* It uses the Java Bindings for GSSAPI
* (<A HREF="http://www.ietf.org/rfc/rfc2853.txt">RFC 2853</A>)
* for getting GSSAPI/Kerberos V5 support.
*
* The client/server interactions are:
* C0: bind (GSSAPI, initial response)
* S0: sasl-bind-in-progress, challenge 1 (output of accept_sec_context or [])
* C1: bind (GSSAPI, response 1 (output of init_sec_context or []))
* S1: sasl-bind-in-progress challenge 2 (security layer, server max recv size)
* C2: bind (GSSAPI, response 2 (security layer, client max recv size, authzid))
* S2: bind success response
*
* Expects the client's credentials to be supplied from the
* javax.security.sasl.credentials property or from the thread's Subject.
* Otherwise the underlying KRB5 mech will attempt to acquire Kerberos creds
* by logging into Kerberos (via default TextCallbackHandler).
* These creds will be used for exchange with server.
*
* Required callbacks: none.
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* - quality of protection; list of auth, auth-int, auth-conf; default is "auth"
* javax.security.sasl.maxbuf
* - max receive buffer size; default is 65536
* javax.security.sasl.sendmaxbuffer
* - max send buffer size; default is 65536; (min with server max recv size)
*
* javax.security.sasl.server.authentication
* - "true" means require mutual authentication; default is "false"
*
* javax.security.sasl.credentials
* - an {@link org.ietf.jgss.GSSCredential} used for delegated authentication.
*
* @author Rosanna Lee
*/
final class GssKrb5Client extends GssKrb5Base implements SaslClient {
// ---------------- Constants -----------------
private static final String MY_CLASS_NAME = GssKrb5Client.class.getName();
private boolean finalHandshake = false;
private boolean mutual = false; // default false
private byte[] authzID;
/**
* Creates a SASL mechanism with client credentials that it needs
* to participate in GSS-API/Kerberos v5 authentication exchange
* with the server.
*/
GssKrb5Client(String authzID, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME);
String service = protocol + "@" + serverName;
logger.log(Level.FINE, "KRB5CLNT01:Requesting service name: {0}",
service);
try {
GSSManager mgr = GSSManager.getInstance();
// Create the name for the requested service entity for Krb5 mech
GSSName acceptorName = mgr.createName(service,
GSSName.NT_HOSTBASED_SERVICE, KRB5_OID);
// Parse properties to check for supplied credentials
GSSCredential credentials = null;
if (props != null) {
Object prop = props.get(Sasl.CREDENTIALS);
if (prop != null && prop instanceof GSSCredential) {
credentials = (GSSCredential) prop;
logger.log(Level.FINE,
"KRB5CLNT01:Using the credentials supplied in " +
"javax.security.sasl.credentials");
}
}
// Create a context using credentials for Krb5 mech
secCtx = mgr.createContext(acceptorName,
KRB5_OID, /* mechanism */
credentials, /* credentials */
GSSContext.INDEFINITE_LIFETIME);
// Request credential delegation when credentials have been supplied
if (credentials != null) {
secCtx.requestCredDeleg(true);
}
// Parse properties to set desired context options
if (props != null) {
// Mutual authentication
String prop = (String)props.get(Sasl.SERVER_AUTH);
if (prop != null) {
mutual = "true".equalsIgnoreCase(prop);
}
}
secCtx.requestMutualAuth(mutual);
// Always specify potential need for integrity and confidentiality
// Decision will be made during final handshake
secCtx.requestConf(true);
secCtx.requestInteg(true);
} catch (GSSException e) {
throw new SaslException("Failure to initialize security context", e);
}
if (authzID != null && authzID.length() > 0) {
try {
this.authzID = authzID.getBytes("UTF8");
} catch (IOException e) {
throw new SaslException("Cannot encode authorization ID", e);
}
}
}
public boolean hasInitialResponse() {
return true;
}
/**
* Processes the challenge data.
*
* The server sends a challenge data using which the client must
* process using GSS_Init_sec_context.
* As per RFC 2222, when GSS_S_COMPLETE is returned, we do
* an extra handshake to determine the negotiated security protection
* and buffer sizes.
*
* @param challengeData A non-null byte array containing the
* challenge data from the server.
* @return A non-null byte array containing the response to be
* sent to the server.
*/
public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
if (completed) {
throw new IllegalStateException(
"GSSAPI authentication already complete");
}
if (finalHandshake) {
return doFinalHandshake(challengeData);
} else {
// Security context not established yet; continue with init
try {
byte[] gssOutToken = secCtx.initSecContext(challengeData,
0, challengeData.length);
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "evaluteChallenge",
"KRB5CLNT02:Challenge: [raw]", challengeData);
traceOutput(MY_CLASS_NAME, "evaluateChallenge",
"KRB5CLNT03:Response: [after initSecCtx]", gssOutToken);
}
if (secCtx.isEstablished()) {
finalHandshake = true;
if (gssOutToken == null) {
// RFC 2222 7.2.1: Client responds with no data
return EMPTY;
}
}
return gssOutToken;
} catch (GSSException e) {
throw new SaslException("GSS initiate failed", e);
}
}
}
private byte[] doFinalHandshake(byte[] challengeData) throws SaslException {
try {
// Security context already established. challengeData
// should contain security layers and server's maximum buffer size
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
"KRB5CLNT04:Challenge [raw]:", challengeData);
}
if (challengeData.length == 0) {
// Received S0, should return []
return EMPTY;
}
// Received S1 (security layer, server max recv size)
MessageProp msgProp = new MessageProp(false);
byte[] gssOutToken = secCtx.unwrap(challengeData, 0,
challengeData.length, msgProp);
checkMessageProp("Handshake failure: ", msgProp);
// First octet is a bit-mask specifying the protections
// supported by the server
if (logger.isLoggable(Level.FINE)) {
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
"KRB5CLNT05:Challenge [unwrapped]:", gssOutToken);
}
logger.log(Level.FINE, "KRB5CLNT06:Server protections: {0}",
new Byte(gssOutToken[0]));
}
// Client selects preferred protection
// qop is ordered list of qop values
byte selectedQop = findPreferredMask(gssOutToken[0], qop);
if (selectedQop == 0) {
throw new SaslException(
"No common protection layer between client and server");
}
if ((selectedQop&PRIVACY_PROTECTION) != 0) {
privacy = true;
integrity = true;
} else if ((selectedQop&INTEGRITY_ONLY_PROTECTION) != 0) {
integrity = true;
}
// 2nd-4th octets specifies maximum buffer size expected by
// server (in network byte order)
int srvMaxBufSize = networkByteOrderToInt(gssOutToken, 1, 3);
// Determine the max send buffer size based on what the
// server is able to receive and our specified max
sendMaxBufSize = (sendMaxBufSize == 0) ? srvMaxBufSize :
Math.min(sendMaxBufSize, srvMaxBufSize);
// Update context to limit size of returned buffer
rawSendSize = secCtx.getWrapSizeLimit(JGSS_QOP, privacy,
sendMaxBufSize);
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"KRB5CLNT07:Client max recv size: {0}; server max recv size: {1}; rawSendSize: {2}",
new Object[] {new Integer(recvMaxBufSize),
new Integer(srvMaxBufSize),
new Integer(rawSendSize)});
}
// Construct negotiated security layers and client's max
// receive buffer size and authzID
int len = 4;
if (authzID != null) {
len += authzID.length;
}
byte[] gssInToken = new byte[len];
gssInToken[0] = selectedQop;
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"KRB5CLNT08:Selected protection: {0}; privacy: {1}; integrity: {2}",
new Object[]{new Byte(selectedQop),
Boolean.valueOf(privacy),
Boolean.valueOf(integrity)});
}
intToNetworkByteOrder(recvMaxBufSize, gssInToken, 1, 3);
if (authzID != null) {
// copy authorization id
System.arraycopy(authzID, 0, gssInToken, 4, authzID.length);
logger.log(Level.FINE, "KRB5CLNT09:Authzid: {0}", authzID);
}
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
"KRB5CLNT10:Response [raw]", gssInToken);
}
gssOutToken = secCtx.wrap(gssInToken,
0, gssInToken.length,
new MessageProp(0 /* qop */, false /* privacy */));
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doFinalHandshake",
"KRB5CLNT11:Response [after wrap]", gssOutToken);
}
completed = true; // server authenticated
return gssOutToken;
} catch (GSSException e) {
throw new SaslException("Final handshake failed", e);
}
}
}

View File

@@ -0,0 +1,367 @@
/*
* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.gsskerb;
import javax.security.sasl.*;
import java.io.*;
import java.util.Map;
import java.util.logging.Level;
// JAAS
import javax.security.auth.callback.*;
// JGSS
import org.ietf.jgss.*;
/**
* Implements the GSSAPI SASL server mechanism for Kerberos V5.
* (<A HREF="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</A>,
* <a HREF="http://www.ietf.org/internet-drafts/draft-ietf-cat-sasl-gssapi-00.txt">draft-ietf-cat-sasl-gssapi-00.txt</a>).
*
* Expects thread's Subject to contain server's Kerberos credentials
* - If not, underlying KRB5 mech will attempt to acquire Kerberos creds
* by logging into Kerberos (via default TextCallbackHandler).
* - These creds will be used for exchange with client.
*
* Required callbacks:
* - AuthorizeCallback
* handler must verify that authid/authzids are allowed and set
* authorized ID to be the canonicalized authzid (if applicable).
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* - quality of protection; list of auth, auth-int, auth-conf; default is "auth"
* javax.security.sasl.maxbuf
* - max receive buffer size; default is 65536
* javax.security.sasl.sendmaxbuffer
* - max send buffer size; default is 65536; (min with client max recv size)
*
* @author Rosanna Lee
*/
final class GssKrb5Server extends GssKrb5Base implements SaslServer {
private static final String MY_CLASS_NAME = GssKrb5Server.class.getName();
private int handshakeStage = 0;
private String peer;
private String me;
private String authzid;
private CallbackHandler cbh;
// When serverName is null, the server will be unbound. We need to save and
// check the protocol name after the context is established. This value
// will be null if serverName is not null.
private final String protocolSaved;
/**
* Creates a SASL mechanism with server credentials that it needs
* to participate in GSS-API/Kerberos v5 authentication exchange
* with the client.
*/
GssKrb5Server(String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
super(props, MY_CLASS_NAME);
this.cbh = cbh;
String service;
if (serverName == null) {
protocolSaved = protocol;
service = null;
} else {
protocolSaved = null;
service = protocol + "@" + serverName;
}
logger.log(Level.FINE, "KRB5SRV01:Using service name: {0}", service);
try {
GSSManager mgr = GSSManager.getInstance();
// Create the name for the requested service entity for Krb5 mech
GSSName serviceName = service == null ? null:
mgr.createName(service, GSSName.NT_HOSTBASED_SERVICE, KRB5_OID);
GSSCredential cred = mgr.createCredential(serviceName,
GSSCredential.INDEFINITE_LIFETIME,
KRB5_OID, GSSCredential.ACCEPT_ONLY);
// Create a context using the server's credentials
secCtx = mgr.createContext(cred);
if ((allQop&INTEGRITY_ONLY_PROTECTION) != 0) {
// Might need integrity
secCtx.requestInteg(true);
}
if ((allQop&PRIVACY_PROTECTION) != 0) {
// Might need privacy
secCtx.requestConf(true);
}
} catch (GSSException e) {
throw new SaslException("Failure to initialize security context", e);
}
logger.log(Level.FINE, "KRB5SRV02:Initialization complete");
}
/**
* Processes the response data.
*
* The client sends response data to which the server must
* process using GSS_accept_sec_context.
* As per RFC 2222, the GSS authenication completes (GSS_S_COMPLETE)
* we do an extra hand shake to determine the negotiated security protection
* and buffer sizes.
*
* @param responseData A non-null but possible empty byte array containing the
* response data from the client.
* @return A non-null byte array containing the challenge to be
* sent to the client, or null when no more data is to be sent.
*/
public byte[] evaluateResponse(byte[] responseData) throws SaslException {
if (completed) {
throw new SaslException(
"SASL authentication already complete");
}
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "evaluateResponse",
"KRB5SRV03:Response [raw]:", responseData);
}
switch (handshakeStage) {
case 1:
return doHandshake1(responseData);
case 2:
return doHandshake2(responseData);
default:
// Security context not established yet; continue with accept
try {
byte[] gssOutToken = secCtx.acceptSecContext(responseData,
0, responseData.length);
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "evaluateResponse",
"KRB5SRV04:Challenge: [after acceptSecCtx]", gssOutToken);
}
if (secCtx.isEstablished()) {
handshakeStage = 1;
peer = secCtx.getSrcName().toString();
me = secCtx.getTargName().toString();
logger.log(Level.FINE,
"KRB5SRV05:Peer name is : {0}, my name is : {1}",
new Object[]{peer, me});
// me might take the form of proto@host or proto/host
if (protocolSaved != null &&
!protocolSaved.equalsIgnoreCase(me.split("[/@]")[0])) {
throw new SaslException(
"GSS context targ name protocol error: " + me);
}
if (gssOutToken == null) {
return doHandshake1(EMPTY);
}
}
return gssOutToken;
} catch (GSSException e) {
throw new SaslException("GSS initiate failed", e);
}
}
}
private byte[] doHandshake1(byte[] responseData) throws SaslException {
try {
// Security context already established. responseData
// should contain no data
if (responseData != null && responseData.length > 0) {
throw new SaslException(
"Handshake expecting no response data from server");
}
// Construct 4 octets of data:
// First octet contains bitmask specifying protections supported
// 2nd-4th octets contains max receive buffer of server
byte[] gssInToken = new byte[4];
gssInToken[0] = allQop;
intToNetworkByteOrder(recvMaxBufSize, gssInToken, 1, 3);
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"KRB5SRV06:Supported protections: {0}; recv max buf size: {1}",
new Object[]{new Byte(allQop),
new Integer(recvMaxBufSize)});
}
handshakeStage = 2; // progress to next stage
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doHandshake1",
"KRB5SRV07:Challenge [raw]", gssInToken);
}
byte[] gssOutToken = secCtx.wrap(gssInToken, 0, gssInToken.length,
new MessageProp(0 /* gop */, false /* privacy */));
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doHandshake1",
"KRB5SRV08:Challenge [after wrap]", gssOutToken);
}
return gssOutToken;
} catch (GSSException e) {
throw new SaslException("Problem wrapping handshake1", e);
}
}
private byte[] doHandshake2(byte[] responseData) throws SaslException {
try {
// Expecting 4 octets from client selected protection
// and client's receive buffer size
MessageProp msgProp = new MessageProp(false);
byte[] gssOutToken = secCtx.unwrap(responseData, 0,
responseData.length, msgProp);
checkMessageProp("Handshake failure: ", msgProp);
if (logger.isLoggable(Level.FINER)) {
traceOutput(MY_CLASS_NAME, "doHandshake2",
"KRB5SRV09:Response [after unwrap]", gssOutToken);
}
// First octet is a bit-mask specifying the selected protection
byte selectedQop = gssOutToken[0];
if ((selectedQop&allQop) == 0) {
throw new SaslException("Client selected unsupported protection: "
+ selectedQop);
}
if ((selectedQop&PRIVACY_PROTECTION) != 0) {
privacy = true;
integrity = true;
} else if ((selectedQop&INTEGRITY_ONLY_PROTECTION) != 0) {
integrity = true;
}
// 2nd-4th octets specifies maximum buffer size expected by
// client (in network byte order). This is the server's send
// buffer maximum.
int clntMaxBufSize = networkByteOrderToInt(gssOutToken, 1, 3);
// Determine the max send buffer size based on what the
// client is able to receive and our specified max
sendMaxBufSize = (sendMaxBufSize == 0) ? clntMaxBufSize :
Math.min(sendMaxBufSize, clntMaxBufSize);
// Update context to limit size of returned buffer
rawSendSize = secCtx.getWrapSizeLimit(JGSS_QOP, privacy,
sendMaxBufSize);
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE,
"KRB5SRV10:Selected protection: {0}; privacy: {1}; integrity: {2}",
new Object[]{new Byte(selectedQop),
Boolean.valueOf(privacy),
Boolean.valueOf(integrity)});
logger.log(Level.FINE,
"KRB5SRV11:Client max recv size: {0}; server max send size: {1}; rawSendSize: {2}",
new Object[] {new Integer(clntMaxBufSize),
new Integer(sendMaxBufSize),
new Integer(rawSendSize)});
}
// Get authorization identity, if any
if (gssOutToken.length > 4) {
try {
authzid = new String(gssOutToken, 4,
gssOutToken.length - 4, "UTF-8");
} catch (UnsupportedEncodingException uee) {
throw new SaslException ("Cannot decode authzid", uee);
}
} else {
authzid = peer;
}
logger.log(Level.FINE, "KRB5SRV12:Authzid: {0}", authzid);
AuthorizeCallback acb = new AuthorizeCallback(peer, authzid);
// In Kerberos, realm is embedded in peer name
cbh.handle(new Callback[] {acb});
if (acb.isAuthorized()) {
authzid = acb.getAuthorizedID();
completed = true;
} else {
// Authorization failed
throw new SaslException(peer +
" is not authorized to connect as " + authzid);
}
return null;
} catch (GSSException e) {
throw new SaslException("Final handshake step failed", e);
} catch (IOException e) {
throw new SaslException("Problem with callback handler", e);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Problem with callback handler", e);
}
}
public String getAuthorizationID() {
if (completed) {
return authzid;
} else {
throw new IllegalStateException("Authentication incomplete");
}
}
public Object getNegotiatedProperty(String propName) {
if (!completed) {
throw new IllegalStateException("Authentication incomplete");
}
Object result;
switch (propName) {
case Sasl.BOUND_SERVER_NAME:
try {
// me might take the form of proto@host or proto/host
result = me.split("[/@]")[1];
} catch (Exception e) {
result = null;
}
break;
default:
result = super.getNegotiatedProperty(propName);
}
return result;
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import java.util.Map;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import com.sun.security.sasl.util.PolicyUtils;
/**
* Client and server factory for NTLM SASL client/server mechanisms.
* See NTLMClient and NTLMServer for input requirements.
*
* @since 1.7
*/
public final class FactoryImpl implements SaslClientFactory,
SaslServerFactory{
private static final String myMechs[] = { "NTLM" };
private static final int mechPolicies[] = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS
};
/**
* Empty constructor.
*/
public FactoryImpl() {
}
/**
* Returns a new instance of the NTLM SASL client mechanism.
* Argument checks are performed in SaslClient's constructor.
* @return a new SaslClient; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL client.
*/
public SaslClient createSaslClient(String[] mechs,
String authorizationId, String protocol, String serverName,
Map<String,?> props, CallbackHandler cbh)
throws SaslException {
for (int i=0; i<mechs.length; i++) {
if (mechs[i].equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
if (cbh == null) {
throw new SaslException(
"Callback handler with support for " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new NTLMClient(mechs[i], authorizationId,
protocol, serverName, props, cbh);
}
}
return null;
}
/**
* Returns a new instance of the NTLM SASL server mechanism.
* Argument checks are performed in SaslServer's constructor.
* @return a new SaslServer; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL server.
*/
public SaslServer createSaslServer(String mech,
String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
throws SaslException {
if (mech.equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
}
if (cbh == null) {
throw new SaslException(
"Callback handler with support for " +
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new NTLMServer(mech, protocol, serverName, props, cbh);
}
return null;
}
/**
* Returns the authentication mechanisms that this factory can produce.
*
* @return String[] {"NTLM"} if policies in env match those of this
* factory.
*/
public String[] getMechanismNames(Map<String,?> env) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
}
}

View File

@@ -0,0 +1,243 @@
/*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import com.sun.security.ntlm.Client;
import com.sun.security.ntlm.NTLMException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Random;
import javax.security.auth.callback.Callback;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Required callbacks:
* - RealmCallback
* handle can provide domain info for authentication, optional
* - NameCallback
* handler must enter username to use for authentication
* - PasswordCallback
* handler must enter password for username to use for authentication
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* String, quality of protection; only "auth" is accepted, default "auth"
*
* com.sun.security.sasl.ntlm.version
* String, name a specific version to use; can be:
* LM/NTLM: Original NTLM v1
* LM: Original NTLM v1, LM only
* NTLM: Original NTLM v1, NTLM only
* NTLM2: NTLM v1 with Client Challenge
* LMv2/NTLMv2: NTLM v2
* LMv2: NTLM v2, LM only
* NTLMv2: NTLM v2, NTLM only
* If not specified, use system property "ntlm.version". If
* still not specified, use default value "LMv2/NTLMv2".
*
* com.sun.security.sasl.ntlm.random
* java.util.Random, the nonce source to be used in NTLM v2 or NTLM v1 with
* Client Challenge. Default null, an internal java.util.Random object
* will be used
*
* Negotiated Properties:
*
* javax.security.sasl.qop
* Always "auth"
*
* com.sun.security.sasl.html.domain
* The domain for the user, provided by the server
*
* @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
* - Simple Authentication and Security Layer (SASL)
*
*/
final class NTLMClient implements SaslClient {
private static final String NTLM_VERSION =
"com.sun.security.sasl.ntlm.version";
private static final String NTLM_RANDOM =
"com.sun.security.sasl.ntlm.random";
private final static String NTLM_DOMAIN =
"com.sun.security.sasl.ntlm.domain";
private final static String NTLM_HOSTNAME =
"com.sun.security.sasl.ntlm.hostname";
private final Client client;
private final String mech;
private final Random random;
private int step = 0; // 0-start,1-nego,2-auth,3-done
/**
* @param mech non-null
* @param authorizationId can be null or empty and ignored
* @param protocol non-null for Sasl, useless for NTLM
* @param serverName non-null for Sasl, but can be null for NTLM
* @param props can be null
* @param cbh can be null for Sasl, already null-checked in factory
* @throws SaslException
*/
NTLMClient(String mech, String authzid, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException {
this.mech = mech;
String version = null;
Random rtmp = null;
String hostname = null;
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
version = (String)props.get(NTLM_VERSION);
rtmp = (Random)props.get(NTLM_RANDOM);
hostname = (String)props.get(NTLM_HOSTNAME);
}
this.random = rtmp != null ? rtmp : new Random();
if (version == null) {
version = System.getProperty("ntlm.version");
}
RealmCallback dcb = (serverName != null && !serverName.isEmpty())?
new RealmCallback("Realm: ", serverName) :
new RealmCallback("Realm: ");
NameCallback ncb = (authzid != null && !authzid.isEmpty()) ?
new NameCallback("User name: ", authzid) :
new NameCallback("User name: ");
PasswordCallback pcb =
new PasswordCallback("Password: ", false);
try {
cbh.handle(new Callback[] {dcb, ncb, pcb});
} catch (UnsupportedCallbackException e) {
throw new SaslException("NTLM: Cannot perform callback to " +
"acquire realm, username or password", e);
} catch (IOException e) {
throw new SaslException(
"NTLM: Error acquiring realm, username or password", e);
}
if (hostname == null) {
try {
hostname = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
hostname = "localhost";
}
}
try {
String name = ncb.getName();
if (name == null) {
name = authzid;
}
String domain = dcb.getText();
if (domain == null) {
domain = serverName;
}
client = new Client(version, hostname,
name,
domain,
pcb.getPassword());
} catch (NTLMException ne) {
throw new SaslException(
"NTLM: client creation failure", ne);
}
}
@Override
public String getMechanismName() {
return mech;
}
@Override
public boolean isComplete() {
return step >= 2;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported.");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported.");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
switch (propName) {
case Sasl.QOP:
return "auth";
case NTLM_DOMAIN:
return client.getDomain();
default:
return null;
}
}
@Override
public void dispose() throws SaslException {
client.dispose();
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
step++;
if (step == 1) {
return client.type1();
} else {
try {
byte[] nonce = new byte[8];
random.nextBytes(nonce);
return client.type3(challenge, nonce);
} catch (NTLMException ex) {
throw new SaslException("Type3 creation failed", ex);
}
}
}
}

View File

@@ -0,0 +1,240 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import com.sun.security.ntlm.NTLMException;
import com.sun.security.ntlm.Server;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.Random;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.*;
/**
* Required callbacks:
* - RealmCallback
* used as key by handler to fetch password, optional
* - NameCallback
* used as key by handler to fetch password
* - PasswordCallback
* handler must enter password for username/realm supplied
*
* Environment properties that affect the implementation:
*
* javax.security.sasl.qop
* String, quality of protection; only "auth" is accepted, default "auth"
*
* com.sun.security.sasl.ntlm.version
* String, name a specific version to accept:
* LM/NTLM: Original NTLM v1
* LM: Original NTLM v1, LM only
* NTLM: Original NTLM v1, NTLM only
* NTLM2: NTLM v1 with Client Challenge
* LMv2/NTLMv2: NTLM v2
* LMv2: NTLM v2, LM only
* NTLMv2: NTLM v2, NTLM only
* If not specified, use system property "ntlm.version". If also
* not specified, all versions are accepted.
*
* com.sun.security.sasl.ntlm.domain
* String, the domain of the server, default is server name (fqdn parameter)
*
* com.sun.security.sasl.ntlm.random
* java.util.Random, the nonce source. Default null, an internal
* java.util.Random object will be used
*
* Negotiated Properties:
*
* javax.security.sasl.qop
* Always "auth"
*
* com.sun.security.sasl.ntlm.hostname
* The hostname for the user, provided by the client
*
*/
final class NTLMServer implements SaslServer {
private final static String NTLM_VERSION =
"com.sun.security.sasl.ntlm.version";
private final static String NTLM_DOMAIN =
"com.sun.security.sasl.ntlm.domain";
private final static String NTLM_HOSTNAME =
"com.sun.security.sasl.ntlm.hostname";
private static final String NTLM_RANDOM =
"com.sun.security.sasl.ntlm.random";
private final Random random;
private final Server server;
private byte[] nonce;
private int step = 0;
private String authzId;
private final String mech;
private String hostname;
private String target;
/**
* @param mech not null
* @param protocol not null for Sasl, ignored in NTLM
* @param serverName not null for Sasl, can be null in NTLM. If non-null,
* might be used as domain if not provided in props
* @param props can be null
* @param cbh can be null for Sasl, already null-checked in factory
* @throws SaslException
*/
NTLMServer(String mech, String protocol, String serverName,
Map<String, ?> props, final CallbackHandler cbh)
throws SaslException {
this.mech = mech;
String version = null;
String domain = null;
Random rtmp = null;
if (props != null) {
domain = (String) props.get(NTLM_DOMAIN);
version = (String)props.get(NTLM_VERSION);
rtmp = (Random)props.get(NTLM_RANDOM);
}
random = rtmp != null ? rtmp : new Random();
if (version == null) {
version = System.getProperty("ntlm.version");
}
if (domain == null) {
domain = serverName;
}
if (domain == null) {
throw new SaslException("Domain must be provided as"
+ " the serverName argument or in props");
}
try {
server = new Server(version, domain) {
public char[] getPassword(String ntdomain, String username) {
try {
RealmCallback rcb =
(ntdomain == null || ntdomain.isEmpty())
? new RealmCallback("Domain: ")
: new RealmCallback("Domain: ", ntdomain);
NameCallback ncb = new NameCallback(
"Name: ", username);
PasswordCallback pcb = new PasswordCallback(
"Password: ", false);
cbh.handle(new Callback[] { rcb, ncb, pcb });
char[] passwd = pcb.getPassword();
pcb.clearPassword();
return passwd;
} catch (IOException ioe) {
return null;
} catch (UnsupportedCallbackException uce) {
return null;
}
}
};
} catch (NTLMException ne) {
throw new SaslException(
"NTLM: server creation failure", ne);
}
nonce = new byte[8];
}
@Override
public String getMechanismName() {
return mech;
}
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
try {
step++;
if (step == 1) {
random.nextBytes(nonce);
return server.type2(response, nonce);
} else {
String[] out = server.verify(response, nonce);
authzId = out[0];
hostname = out[1];
target = out[2];
return null;
}
} catch (NTLMException ex) {
throw new SaslException("NTLM: generate response failure", ex);
}
}
@Override
public boolean isComplete() {
return step >= 2;
}
@Override
public String getAuthorizationID() {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
return authzId;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported yet.");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
throw new IllegalStateException("Not supported yet.");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete()) {
throw new IllegalStateException("authentication not complete");
}
switch (propName) {
case Sasl.QOP:
return "auth";
case Sasl.BOUND_SERVER_NAME:
return target;
case NTLM_HOSTNAME:
return hostname;
default:
return null;
}
}
@Override
public void dispose() throws SaslException {
return;
}
}

View File

@@ -0,0 +1,365 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.util;
import javax.security.sasl.*;
import java.io.*;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.util.logging.Level;
import sun.misc.HexDumpEncoder;
/**
* The base class used by client and server implementations of SASL
* mechanisms to process properties passed in the props argument
* and strings with the same format (e.g., used in digest-md5).
*
* Also contains utilities for doing int to network-byte-order
* transformations.
*
* @author Rosanna Lee
*/
public abstract class AbstractSaslImpl {
protected boolean completed = false;
protected boolean privacy = false;
protected boolean integrity = false;
protected byte[] qop; // ordered list of qops
protected byte allQop; // a mask indicating which QOPs are requested
protected byte[] strength; // ordered list of cipher strengths
// These are relevant only when privacy or integray have been negotiated
protected int sendMaxBufSize = 0; // specified by peer but can override
protected int recvMaxBufSize = 65536; // optionally specified by self
protected int rawSendSize; // derived from sendMaxBufSize
protected String myClassName;
protected AbstractSaslImpl(Map<String, ?> props, String className)
throws SaslException {
myClassName = className;
// Parse properties to set desired context options
if (props != null) {
String prop;
// "auth", "auth-int", "auth-conf"
qop = parseQop(prop=(String)props.get(Sasl.QOP));
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL01:Preferred qop property: {0}", prop);
allQop = combineMasks(qop);
if (logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL02:Preferred qop mask: {0}", new Byte(allQop));
if (qop.length > 0) {
StringBuffer qopbuf = new StringBuffer();
for (int i = 0; i < qop.length; i++) {
qopbuf.append(Byte.toString(qop[i]));
qopbuf.append(' ');
}
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL03:Preferred qops : {0}", qopbuf.toString());
}
}
// "low", "medium", "high"
strength = parseStrength(prop=(String)props.get(Sasl.STRENGTH));
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL04:Preferred strength property: {0}", prop);
if (logger.isLoggable(Level.FINE) && strength.length > 0) {
StringBuffer strbuf = new StringBuffer();
for (int i = 0; i < strength.length; i++) {
strbuf.append(Byte.toString(strength[i]));
strbuf.append(' ');
}
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL05:Cipher strengths: {0}", strbuf.toString());
}
// Max receive buffer size
prop = (String)props.get(Sasl.MAX_BUFFER);
if (prop != null) {
try {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL06:Max receive buffer size: {0}", prop);
recvMaxBufSize = Integer.parseInt(prop);
} catch (NumberFormatException e) {
throw new SaslException(
"Property must be string representation of integer: " +
Sasl.MAX_BUFFER);
}
}
// Max send buffer size
prop = (String)props.get(MAX_SEND_BUF);
if (prop != null) {
try {
logger.logp(Level.FINE, myClassName, "constructor",
"SASLIMPL07:Max send buffer size: {0}", prop);
sendMaxBufSize = Integer.parseInt(prop);
} catch (NumberFormatException e) {
throw new SaslException(
"Property must be string representation of integer: " +
MAX_SEND_BUF);
}
}
} else {
qop = DEFAULT_QOP;
allQop = NO_PROTECTION;
strength = STRENGTH_MASKS;
}
}
/**
* Determines whether this mechanism has completed.
*
* @return true if has completed; false otherwise;
*/
public boolean isComplete() {
return completed;
}
/**
* Retrieves the negotiated property.
* @exception IllegalStateException if this authentication exchange has
* not completed
*/
public Object getNegotiatedProperty(String propName) {
if (!completed) {
throw new IllegalStateException("SASL authentication not completed");
}
switch (propName) {
case Sasl.QOP:
if (privacy) {
return "auth-conf";
} else if (integrity) {
return "auth-int";
} else {
return "auth";
}
case Sasl.MAX_BUFFER:
return Integer.toString(recvMaxBufSize);
case Sasl.RAW_SEND_SIZE:
return Integer.toString(rawSendSize);
case MAX_SEND_BUF:
return Integer.toString(sendMaxBufSize);
default:
return null;
}
}
protected static final byte combineMasks(byte[] in) {
byte answer = 0;
for (int i = 0; i < in.length; i++) {
answer |= in[i];
}
return answer;
}
protected static final byte findPreferredMask(byte pref, byte[] in) {
for (int i = 0; i < in.length; i++) {
if ((in[i]&pref) != 0) {
return in[i];
}
}
return (byte)0;
}
private static final byte[] parseQop(String qop) throws SaslException {
return parseQop(qop, null, false);
}
protected static final byte[] parseQop(String qop, String[] saveTokens,
boolean ignore) throws SaslException {
if (qop == null) {
return DEFAULT_QOP; // default
}
return parseProp(Sasl.QOP, qop, QOP_TOKENS, QOP_MASKS, saveTokens, ignore);
}
private static final byte[] parseStrength(String strength)
throws SaslException {
if (strength == null) {
return DEFAULT_STRENGTH; // default
}
return parseProp(Sasl.STRENGTH, strength, STRENGTH_TOKENS,
STRENGTH_MASKS, null, false);
}
private static final byte[] parseProp(String propName, String propVal,
String[] vals, byte[] masks, String[] tokens, boolean ignore)
throws SaslException {
StringTokenizer parser = new StringTokenizer(propVal, ", \t\n");
String token;
byte[] answer = new byte[vals.length];
int i = 0;
boolean found;
while (parser.hasMoreTokens() && i < answer.length) {
token = parser.nextToken();
found = false;
for (int j = 0; !found && j < vals.length; j++) {
if (token.equalsIgnoreCase(vals[j])) {
found = true;
answer[i++] = masks[j];
if (tokens != null) {
tokens[j] = token; // save what was parsed
}
}
}
if (!found && !ignore) {
throw new SaslException(
"Invalid token in " + propName + ": " + propVal);
}
}
// Initialize rest of array with 0
for (int j = i; j < answer.length; j++) {
answer[j] = 0;
}
return answer;
}
/**
* Outputs a byte array. Can be null.
*/
protected static final void traceOutput(String srcClass, String srcMethod,
String traceTag, byte[] output) {
traceOutput(srcClass, srcMethod, traceTag, output, 0,
output == null ? 0 : output.length);
}
protected static final void traceOutput(String srcClass, String srcMethod,
String traceTag, byte[] output, int offset, int len) {
try {
int origlen = len;
Level lev;
if (!logger.isLoggable(Level.FINEST)) {
len = Math.min(16, len);
lev = Level.FINER;
} else {
lev = Level.FINEST;
}
String content;
if (output != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream(len);
new HexDumpEncoder().encodeBuffer(
new ByteArrayInputStream(output, offset, len), out);
content = out.toString();
} else {
content = "NULL";
}
// Message id supplied by caller as part of traceTag
logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
new Object[] {traceTag, new Integer(origlen), content});
} catch (Exception e) {
logger.logp(Level.WARNING, srcClass, srcMethod,
"SASLIMPL09:Error generating trace output: {0}", e);
}
}
/**
* Returns the integer represented by 4 bytes in network byte order.
*/
protected static final int networkByteOrderToInt(byte[] buf, int start,
int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more than 4 bytes");
}
int answer = 0;
for (int i = 0; i < count; i++) {
answer <<= 8;
answer |= ((int)buf[start+i] & 0xff);
}
return answer;
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
protected static final void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
// ---------------- Constants -----------------
private static final String SASL_LOGGER_NAME = "javax.security.sasl";
protected static final String MAX_SEND_BUF = "javax.security.sasl.sendmaxbuffer";
/**
* Logger for debug messages
*/
protected static final Logger logger = Logger.getLogger(SASL_LOGGER_NAME);
// default 0 (no protection); 1 (integrity only)
protected static final byte NO_PROTECTION = (byte)1;
protected static final byte INTEGRITY_ONLY_PROTECTION = (byte)2;
protected static final byte PRIVACY_PROTECTION = (byte)4;
protected static final byte LOW_STRENGTH = (byte)1;
protected static final byte MEDIUM_STRENGTH = (byte)2;
protected static final byte HIGH_STRENGTH = (byte)4;
private static final byte[] DEFAULT_QOP = new byte[]{NO_PROTECTION};
private static final String[] QOP_TOKENS = {"auth-conf",
"auth-int",
"auth"};
private static final byte[] QOP_MASKS = {PRIVACY_PROTECTION,
INTEGRITY_ONLY_PROTECTION,
NO_PROTECTION};
private static final byte[] DEFAULT_STRENGTH = new byte[]{
HIGH_STRENGTH, MEDIUM_STRENGTH, LOW_STRENGTH};
private static final String[] STRENGTH_TOKENS = {"low",
"medium",
"high"};
private static final byte[] STRENGTH_MASKS = {LOW_STRENGTH,
MEDIUM_STRENGTH,
HIGH_STRENGTH};
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.util;
import javax.security.sasl.Sasl;
import java.util.Map;
/**
* Static class that contains utilities for dealing with Java SASL
* security policy-related properties.
*
* @author Rosanna Lee
*/
final public class PolicyUtils {
// Can't create one of these
private PolicyUtils() {
}
public final static int NOPLAINTEXT = 0x0001;
public final static int NOACTIVE = 0x0002;
public final static int NODICTIONARY = 0x0004;
public final static int FORWARD_SECRECY = 0x0008;
public final static int NOANONYMOUS = 0x0010;
public final static int PASS_CREDENTIALS = 0x0200;
/**
* Determines whether a mechanism's characteristics, as defined in flags,
* fits the security policy properties found in props.
* @param flags The mechanism's security characteristics
* @param props The security policy properties to check
* @return true if passes; false if fails
*/
public static boolean checkPolicy(int flags, Map<String, ?> props) {
if (props == null) {
return true;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOPLAINTEXT))
&& (flags&NOPLAINTEXT) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOACTIVE))
&& (flags&NOACTIVE) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NODICTIONARY))
&& (flags&NODICTIONARY) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOANONYMOUS))
&& (flags&NOANONYMOUS) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_FORWARD_SECRECY))
&& (flags&FORWARD_SECRECY) == 0) {
return false;
}
if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_PASS_CREDENTIALS))
&& (flags&PASS_CREDENTIALS) == 0) {
return false;
}
return true;
}
/**
* Given a list of mechanisms and their characteristics, select the
* subset that conforms to the policies defined in props.
* Useful for SaslXXXFactory.getMechanismNames(props) implementations.
*
*/
public static String[] filterMechs(String[] mechs, int[] policies,
Map<String, ?> props) {
if (props == null) {
return mechs.clone();
}
boolean[] passed = new boolean[mechs.length];
int count = 0;
for (int i = 0; i< mechs.length; i++) {
if (passed[i] = checkPolicy(policies[i], props)) {
++count;
}
}
String[] answer = new String[count];
for (int i = 0, j=0; i< mechs.length; i++) {
if (passed[i]) {
answer[j++] = mechs[i];
}
}
return answer;
}
}