diff options
author | Casey Marshall <csm@gnu.org> | 2004-08-14 18:21:34 +0000 |
---|---|---|
committer | Casey Marshall <csm@gnu.org> | 2004-08-14 18:21:34 +0000 |
commit | 449f390a69782e6ea3bb48913f027da1dc04011a (patch) | |
tree | 397a5d08f77527b823150aaf01037bdff26130a4 /javax/security | |
parent | 5593f57038abf197fb29aecfe42f2cb4d7ea3cb2 (diff) | |
download | classpath-449f390a69782e6ea3bb48913f027da1dc04011a.tar.gz |
2004-08-14 Casey Marshall <csm@gnu.org>
The Big Crypto Merge of 2004.
* lib/Makefile.am: updated for jgss resources.
* lib/gen-classlist.sh.in: updated for classes in org/.
* javax/security/auth/x500/X500Principal.java: replaced with GNU
Crypto's version.
* resource/org/Makefile.am,
* resource/org/ietf/Makefile.am,
* resource/org/ietf/jgss/Makefile.am:
new files.
Files imported from GNU Crypto.
* javax/crypto/BadPaddingException.java
* javax/crypto/Cipher.java
* javax/crypto/CipherInputStream.java
* javax/crypto/CipherOutputStream.java
* javax/crypto/CipherSpi.java
* javax/crypto/EncryptedPrivateKeyInfo.java
* javax/crypto/ExemptionMechanism.java
* javax/crypto/ExemptionMechanismException.java
* javax/crypto/ExemptionMechanismSpi.java
* javax/crypto/IllegalBlockSizeException.java
* javax/crypto/KeyAgreement.java
* javax/crypto/KeyAgreementSpi.java
* javax/crypto/KeyGenerator.java
* javax/crypto/KeyGeneratorSpi.java
* javax/crypto/Mac.java
* javax/crypto/MacSpi.java
* javax/crypto/Makefile.am
* javax/crypto/NoSuchPaddingException.java
* javax/crypto/NullCipher.java
* javax/crypto/NullCipherImpl.java
* javax/crypto/SealedObject.java
* javax/crypto/SecretKey.java
* javax/crypto/SecretKeyFactory.java
* javax/crypto/SecretKeyFactorySpi.java
* javax/crypto/ShortBufferException.java
* javax/crypto/interfaces/DHKey.java
* javax/crypto/interfaces/DHPrivateKey.java
* javax/crypto/interfaces/DHPublicKey.java
* javax/crypto/interfaces/PBEKey.java
* javax/crypto/spec/DESKeySpec.java
* javax/crypto/spec/DESedeKeySpec.java
* javax/crypto/spec/DHGenParameterSpec.java
* javax/crypto/spec/DHParameterSpec.java
* javax/crypto/spec/DHPrivateKeySpec.java
* javax/crypto/spec/DHPublicKeySpec.java
* javax/crypto/spec/IvParameterSpec.java
* javax/crypto/spec/PBEKeySpec.java
* javax/crypto/spec/PBEParameterSpec.java
* javax/crypto/spec/RC2ParameterSpec.java
* javax/crypto/spec/RC5ParameterSpec.java
* javax/crypto/spec/SecretKeySpec.java
* javax/security/auth/AuthPermission.java
* javax/security/auth/DestroyFailedException.java
* javax/security/auth/Destroyable.java
* javax/security/auth/Policy.java
* javax/security/auth/PrivateCredentialPermission.java
* javax/security/auth/RefreshFailedException.java
* javax/security/auth/Refreshable.java
* javax/security/auth/Subject.java
* javax/security/auth/SubjectDomainCombiner.java
* javax/security/auth/callback/Callback.java
* javax/security/auth/callback/CallbackHandler.java
* javax/security/auth/callback/ChoiceCallback.java
* javax/security/auth/callback/ConfirmationCallback.java
* javax/security/auth/callback/LanguageCallback.java
* javax/security/auth/callback/NameCallback.java
* javax/security/auth/callback/PasswordCallback.java
* javax/security/auth/callback/TextInputCallback.java
* javax/security/auth/callback/TextOutputCallback.java
* javax/security/auth/callback/UnsupportedCallbackException.java
* javax/security/auth/login/AccountExpiredException.java
* javax/security/auth/login/AppConfigurationEntry.java
* javax/security/auth/login/Configuration.java
* javax/security/auth/login/CredentialExpiredException.java
* javax/security/auth/login/FailedLoginException.java
* javax/security/auth/login/LoginContext.java
* javax/security/auth/login/LoginException.java
* javax/security/auth/login/NullConfiguration.java
* javax/security/auth/x500/X500PrivateCredential.java
* javax/security/sasl/AuthenticationException.java
* javax/security/sasl/AuthorizeCallback.java
* javax/security/sasl/RealmCallback.java
* javax/security/sasl/RealmChoiceCallback.java
* javax/security/sasl/Sasl.java
* javax/security/sasl/SaslClient.java
* javax/security/sasl/SaslClientFactory.java
* javax/security/sasl/SaslException.java
* javax/security/sasl/SaslServer.java
* javax/security/sasl/SaslServerFactory.java
* org/ietf/jgss/ChannelBinding.java
* org/ietf/jgss/GSSContext.java
* org/ietf/jgss/GSSCredential.java
* org/ietf/jgss/GSSException.java
* org/ietf/jgss/GSSManager.java
* org/ietf/jgss/GSSName.java
* org/ietf/jgss/MessageProp.java
* org/ietf/jgss/Oid.java
* resources/org/ietf/jgss/MessagesBundle.properties
Files imported from Jessie <http://www.nongnu.org/jessie/>
* javax/net/ServerSocketFactory.java
* javax/net/SocketFactory.java
* javax/net/VanillaServerSocketFactory.java
* javax/net/VanillaSocketFactory.java
* javax/net/ssl/HandshakeCompletedEvent.java
* javax/net/ssl/HandshakeCompletedListener.java
* javax/net/ssl/HostnameVerifier.java
* javax/net/ssl/HttpsURLConnection.java
* javax/net/ssl/KeyManager.java
* javax/net/ssl/KeyManagerFactory.java
* javax/net/ssl/KeyManagerFactorySpi.java
* javax/net/ssl/ManagerFactoryParameters.java
* javax/net/ssl/SSLContext.java
* javax/net/ssl/SSLContextSpi.java
* javax/net/ssl/SSLException.java
* javax/net/ssl/SSLHandshakeException.java
* javax/net/ssl/SSLKeyException.java
* javax/net/ssl/SSLPeerUnverifiedException.java
* javax/net/ssl/SSLPermission.java
* javax/net/ssl/SSLProtocolException.java
* javax/net/ssl/SSLServerSocket.java
* javax/net/ssl/SSLServerSocketFactory.java
* javax/net/ssl/SSLSession.java
* javax/net/ssl/SSLSessionBindingEvent.java
* javax/net/ssl/SSLSessionBindingListener.java
* javax/net/ssl/SSLSessionContext.java
* javax/net/ssl/SSLSocket.java
* javax/net/ssl/SSLSocketFactory.java
* javax/net/ssl/TrivialHostnameVerifier.java
* javax/net/ssl/TrustManager.java
* javax/net/ssl/TrustManagerFactory.java
* javax/net/ssl/TrustManagerFactorySpi.java
* javax/net/ssl/X509KeyManager.java
* javax/net/ssl/X509TrustManager.java
* javax/security/cert/Certificate.java
* javax/security/cert/CertificateEncodingException.java
* javax/security/cert/CertificateException.java
* javax/security/cert/CertificateExpiredException.java
* javax/security/cert/CertificateNotYetValidException.java
* javax/security/cert/CertificateParsingException.java
* javax/security/cert/X509CertBridge.java
* javax/security/cert/X509Certificate.java
Diffstat (limited to 'javax/security')
47 files changed, 7327 insertions, 30 deletions
diff --git a/javax/security/auth/AuthPermission.java b/javax/security/auth/AuthPermission.java new file mode 100644 index 000000000..b4ffa15a9 --- /dev/null +++ b/javax/security/auth/AuthPermission.java @@ -0,0 +1,146 @@ +/* AuthPermission.java -- permissions related to authentication. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +import java.security.BasicPermission; + +/** + * <p>A permission controlling access to authentication service. The + * <i>actions</i> field of auth permission objects is ignored; the whole + * of the permission is defined by the <i>target</i>.</p> + * + * <p>The authentication permission targets recognized are:</p> + * + * <dl> + * <dt><code>doAs</code></dt> + * + * <dd><p>Allows access to the {@link + * Subject#doAs(javax.security.auth.Subject java.security.PrivilegedAction)} + * methods.</p></dd> + * + * <dt><code>doAsPrivileged</code></dt> + * + * <dd><p>Allows access to the {@link + * Subject#doAsPrivileged(javax.security.auth.Subject, + * java.security.PrivilegedAction, java.security.AccessControlContext)} + * methods.</p></dd> + * + * <dt><code>getSubject</code></dt> + * + * <dd><p>Allows access to the {@link Subject} associated with a + * thread.</p></dd> + * + * <dt><code>getSubjectFromDomainCombiner</code></dt> + * + * <dd><p>Allows access to the {@link Subject} associated with a + * {@link SubjectDomainCombiner}.</p></dd> + * + * <dt><code>setReadOnly</code></dt> + * + * <dd><p>Allows a {@link Subject} to be marked as read-only.</p></dd> + * + * <dt><code>modifyPrincipals</code></dt> + * + * <dd><p>Allows the set of principals of a subject to be modified.</p></dd> + * + * <dt><code>modifyPublicCredentials</code></dt> + * + * <dd><p>Allows the set of public credentials of a subject to be + * modified.</p></dd> + * + * <dt><code>modifyPrivateCredentials</code></dt> + * + * <dd><p>Allows the set of private credentials of a subject to be + * modified.</p></dd> + * + * <dt><code>refreshCredential</code></dt> + * + * <dd><p>Allows a {@link Refreshable} credential to be refreshed.</p></dd> + * + * <dt><code>destroyCredential</code></dt> + * + * <dd><p>Allows a {@link Destroyable} credential to be destroyed.</p></dd> + * + * <dt><code>createLoginContext.<i>name</i></code></dt> + * + * <dd><p>Allows a {@link javax.security.auth.login.LoginContext} for the + * given <i>name</i>. <i>name</i> can also be a wildcard (<code>'*'</code>), + * which allows the creation of a context with any name.</p></dd> + * + * <dt><code>getLoginConfiguration</code></dt> + * + * <dd><p>Allows the system-wide login {@link + * javax.security.auth.login.Configuration} to be retrieved.</p></dd> + * + * <dt><code>setLoginConfiguration</code></dt> + * + * <dd><p>Allows the system-wide login {@link + * javax.security.auth.login.Configuration} to be set.</p></dd> + * + * <dt><code>refreshLoginConfiguration</code></dt> + * + * <dd><p>Allows the system-wide login {@link + * javax.security.auth.login.Configuration} to be refreshed.</p></dd> + * </dl> + */ +public final class AuthPermission extends BasicPermission +{ + + /** + * Creates a new authentication permission for the given target name. + * + * @param name The target name. + */ + public AuthPermission (String name) + { + super (name); + } + + /** + * Creates a new authentication permission for the given target name. + * The actions list is not used by this class. + * + * @param name The target name. + * @param actions The action list. + */ + public AuthPermission (String name, String actions) + { + super (name, actions); + } +} diff --git a/javax/security/auth/DestroyFailedException.java b/javax/security/auth/DestroyFailedException.java new file mode 100644 index 000000000..00bbd8966 --- /dev/null +++ b/javax/security/auth/DestroyFailedException.java @@ -0,0 +1,67 @@ +/* DestroyFailedException.java -- signals an object could not be destroyed. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +/** + * An exception thrown when the {@link Destroyable#destroy()} method + * fails for a credential. + * + * @see Destroyable + */ +public class DestroyFailedException extends Exception +{ + + /** + * Creates a new DestroyFailedException with no detail message. + */ + public DestroyFailedException() + { + super(); + } + + /** + * Creates a new DestroyFailedException with a detail message. + * + * @param message The detail message. + */ + public DestroyFailedException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/Destroyable.java b/javax/security/auth/Destroyable.java new file mode 100644 index 000000000..484bece8d --- /dev/null +++ b/javax/security/auth/Destroyable.java @@ -0,0 +1,64 @@ +/* Destroyable.java -- an immutable object that may be destroyed. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +/** + * An interface for objects that are immutable but whose sensitive + * data may be wiped out. + */ +public interface Destroyable +{ + + /** + * Destroy this object, clearing all sensitive fields appropriately. + * + * @throws DestroyFailedException If this object could not be + * destroyed. + * @throws SecurityException If the caller does not have permission + * to destroy this object. + */ + void destroy() throws DestroyFailedException; + + /** + * Tells whether or not this object has been destroyed. + * + * @return True if this object has been destroyed. + */ + boolean isDestroyed(); +} diff --git a/javax/security/auth/Policy.java b/javax/security/auth/Policy.java new file mode 100644 index 000000000..2234d8573 --- /dev/null +++ b/javax/security/auth/Policy.java @@ -0,0 +1,79 @@ +/* Policy.java -- deprecated precursor to java.security.Policy. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +import java.security.CodeSource; +import java.security.PermissionCollection; + +/** + * @deprecated The classes java.security.Policy and + * java.security.ProtectionDomain provide the functionality of this class. + */ +public abstract class Policy +{ + + private static Policy policy; + + protected Policy() + { + } + + public static synchronized Policy getPolicy() + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("getPolicy")); + } + return policy; + } + + public static synchronized void setPolicy (Policy p) + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("setPolicy")); + } + policy = p; + } + + public abstract PermissionCollection getPermissions (Subject subject, CodeSource source); + public abstract void refresh(); +} diff --git a/javax/security/auth/PrivateCredentialPermission.java b/javax/security/auth/PrivateCredentialPermission.java new file mode 100644 index 000000000..db9fed793 --- /dev/null +++ b/javax/security/auth/PrivateCredentialPermission.java @@ -0,0 +1,322 @@ +/* PrivateCredentialPermission.java -- permissions governing private credentials. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +import java.io.Serializable; + +import java.security.Permission; +import java.security.PermissionCollection; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.StringTokenizer; + +/** + * A permission governing access to a private credential. The action of this + * permission is always "read" -- meaning that the private credential + * information can be read from an object. + * + * <p>The target of this permission is formatted as follows:</p> + * + * <p><code>CredentialClassName ( PrinicpalClassName PrincipalName )*</code></p> + * + * <p><i>CredentialClassName</i> is either the name of a private credential + * class name, or a wildcard character (<code>'*'</code>). + * <i>PrinicpalClassName</i> is the class name of a principal object, and + * <i>PrincipalName</i> is a string representing the principal, or the + * wildcard character.</p> + */ +public class PrivateCredentialPermission extends Permission + implements Serializable +{ + + // Fields. + // ------------------------------------------------------------------------- + + /** + * @serial The credential class name. + */ + private final String credentialClass; + + /** + * @serial The principals, a set of CredOwner objects (an undocumented + * inner class of this class). + */ + private final Set principals; + + /** + * @serial Who knows? + */ + private final boolean testing; + + // Constructor. + // ------------------------------------------------------------------------- + + /** + * Create a new private credential permission. + * + * @param name The permission target name. + * @param actions The list of actions, which, for this class, must be + * <code>"read"</code>. + */ + public PrivateCredentialPermission (final String name, String actions) + { + super(name); + actions = actions.trim().toLowerCase(); + if (!"read".equals (actions)) + { + throw new IllegalArgumentException("actions must be \"read\""); + } + StringTokenizer st = new StringTokenizer (name, " \"'"); + principals = new HashSet(); + if (st.countTokens() < 3 || (st.countTokens() & 1) == 0) + { + throw new IllegalArgumentException ("badly formed credential name"); + } + credentialClass = st.nextToken(); + while (st.hasMoreTokens()) + { + principals.add (new CredOwner (st.nextToken(), st.nextToken())); + } + testing = false; // WTF ever. + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public boolean equals (Object o) + { + if (! (o instanceof PrivateCredentialPermission)) + { + return false; + } + PrivateCredentialPermission that = (PrivateCredentialPermission) o; + if (!that.getActions().equals (getActions())) + { + return false; + } + if (!that.getCredentialClass().equals (getCredentialClass())) + { + return false; + } + + final String[][] principals = getPrincipals(); + final String[][] that_principals = that.getPrincipals(); + if (that_principals == null) + { + return false; + } + if (that_principals.length != principals.length) + { + return false; + } + for (int i = 0; i < principals.length; i++) + { + if (!principals[i][0].equals (that_principals[i][0]) || + !principals[i][1].equals (that_principals[i][1])) + { + return false; + } + } + return true; + } + + /** + * Returns the actions this permission encompasses. For private credential + * permissions, this is always the string <code>"read"</code>. + * + * @return The list of actions. + */ + public String getActions() + { + return "read"; + } + + /** + * Returns the credential class name that was embedded in this permission's + * target name. + * + * @return The credential class name. + */ + public String getCredentialClass() + { + return credentialClass; + } + + /** + * Returns the principal list that was embedded in this permission's target + * name. + * + * <p>Each element of the returned array is a pair; the first element is the + * principal class name, and the second is the principal name. + * + * @return The principal list. + */ + public String[][] getPrincipals() + { + String[][] ret = new String[principals.size()][]; + Iterator it = principals.iterator(); + for (int i = 0; i < principals.size() && it.hasNext(); i++) + { + CredOwner co = (CredOwner) it.next(); + ret[i] = new String[] { co.getPrincipalClass(), co.getPrincipalName() }; + } + return ret; + } + + public int hashCode() + { + return credentialClass.hashCode() + principals.hashCode(); + } + + /** + * Test if this permission implies another. This method returns true if: + * + * <ol> + * <li><i>p</i> is an instance of PrivateCredentialPermission</li>. + * <li>The credential class name of this instance matches that of <i>p</i>, + * and one of the principals of <i>p</i> is contained in the principals of + * this class. Thus, + * <ul> + * <li><code>[ * P "foo" ] implies [ C P "foo" ]</code></li> + * <li><code>[ C P1 "foo" ] implies [ C P1 "foo" P2 "bar" ]</code></li> + * <li><code>[ C P1 "*" ] implies [ C P1 "foo" ]</code></li> + * </ul> + * </ol> + * + * @param p The permission to check. + * @return True if this permission implies <i>p</i>. + */ + public boolean implies (Permission p) + { + if (! (p instanceof PrivateCredentialPermission)) + { + return false; + } + PrivateCredentialPermission that = (PrivateCredentialPermission) p; + if (!credentialClass.equals ("*") + && !credentialClass.equals (that.getCredentialClass())) + { + return false; + } + String[][] principals = getPrincipals(); + String[][] that_principals = that.getPrincipals(); + if (that_principals == null) + { + return false; + } + for (int i = 0; i < principals.length; i++) + { + for (int j = 0; j < that_principals.length; j++) + { + if (principals[i][0].equals (that_principals[j][0]) && + (principals[i][1].equals ("*") || + principals[i][1].equals (that_principals[j][1]))) + { + return true; + } + } + } + return false; + } + + /** + * This method is not necessary for this class, thus it always returns null. + * + * @return null. + */ + public PermissionCollection newPermissionCollection() + { + return null; + } + + // Inner class. + // ------------------------------------------------------------------------- + + /** + * An undocumented inner class present for serialization compatibility. + */ + private static class CredOwner implements Serializable + { + + // Fields. + // ----------------------------------------------------------------------- + + private final String principalClass; + private final String principalName; + + // Constructor. + // ----------------------------------------------------------------------- + + CredOwner (final String principalClass, final String principalName) + { + this.principalClass = principalClass; + this.principalName = principalName; + } + + // Instance methods. + // ----------------------------------------------------------------------- + + public boolean equals (Object o) + { + if (!(o instanceof CredOwner)) + { + return false; + } + return principalClass.equals (((CredOwner) o).getPrincipalClass()) && + principalName.equals (((CredOwner) o).getPrincipalName()); + } + + public int hashCode() + { + return principalClass.hashCode() + principalName.hashCode(); + } + + public String getPrincipalClass() + { + return principalClass; + } + + public String getPrincipalName() + { + return principalName; + } + } +} diff --git a/javax/security/auth/RefreshFailedException.java b/javax/security/auth/RefreshFailedException.java new file mode 100644 index 000000000..5be9ab75e --- /dev/null +++ b/javax/security/auth/RefreshFailedException.java @@ -0,0 +1,63 @@ +/* RefreshFailedException.java -- signals a failed refresh. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +/** + * A signal that a call to {@link Refreshable#refresh()} failed. + */ +public class RefreshFailedException extends Exception +{ + + /** + * Create a new RefreshFailedException with no detail message. + */ + public RefreshFailedException() + { + } + + /** + * Create a new RefreshFailedException with a detail message. + * + * @param message The detail message. + */ + public RefreshFailedException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/Refreshable.java b/javax/security/auth/Refreshable.java new file mode 100644 index 000000000..b3ceded41 --- /dev/null +++ b/javax/security/auth/Refreshable.java @@ -0,0 +1,65 @@ +/* Refreshable.java -- an object whose state may be refreshed. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +/** + * An object whose internal state may be <em>refreshed:</em> as in a + * credential object with a expiry date. + */ +public interface Refreshable +{ + + /** + * Tells whether or not this object is current. Refreshable objects that + * are not current may need to be refreshed. + * + * @return Whether this object is current. + */ + boolean isCurrent(); + + /** + * Refresh this object. The process involved in refreshing an object is + * per-implementation dependent. + * + * @throws RefreshFailedException If refreshing this object fails. + * @throws SecurityException If the caller does not have permission to + * refresh, or to take the steps involved in refreshing, this object. + */ + void refresh() throws RefreshFailedException; +} diff --git a/javax/security/auth/Subject.java b/javax/security/auth/Subject.java new file mode 100644 index 000000000..264a41c05 --- /dev/null +++ b/javax/security/auth/Subject.java @@ -0,0 +1,559 @@ +/* Subject.java -- a single entity in the system. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.DomainCombiner; +import java.security.Principal; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; + +import java.util.AbstractSet; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Set; + +/** + * + */ +public final class Subject implements Serializable +{ + + // Fields. + // ------------------------------------------------------------------------- + + private static final long serialVersionUID = -8308522755600156056L; + + /** + * @serial The set of principals. The type of this field is SecureSet, a + * private inner class. + */ + private final Set principals; + + /** + * @serial The read-only flag. + */ + private boolean readOnly; + + private transient final SecureSet pubCred; + private transient final SecureSet privCred; + + // Constructors. + // ------------------------------------------------------------------------- + + public Subject() + { + principals = new SecureSet (this, SecureSet.PRINCIPALS); + pubCred = new SecureSet (this, SecureSet.PUBLIC_CREDENTIALS); + privCred = new SecureSet (this, SecureSet.PRIVATE_CREDENTIALS); + readOnly = false; + } + + public Subject (final boolean readOnly, final Set principals, + final Set pubCred, final Set privCred) + { + if (principals == null || pubCred == null || privCred == null) + { + throw new NullPointerException(); + } + this.principals = new SecureSet (this, SecureSet.PRINCIPALS, principals); + this.pubCred = new SecureSet (this, SecureSet.PUBLIC_CREDENTIALS, pubCred); + this.privCred = new SecureSet (this, SecureSet.PRIVATE_CREDENTIALS, privCred); + this.readOnly = readOnly; + } + + // Class methods. + // ------------------------------------------------------------------------- + + /** + * <p>Returns the subject associated with the given {@link + * AccessControlContext}.</p> + * + * <p>All this method does is retrieve the Subject object from the supplied + * context's {@link DomainCombiner}, if any, and if it is an instance of + * a {@link SubjectDomainCombiner}. + * + * @param context The context to retrieve the subject from. + * @return The subject assoctiated with the context, or <code>null</code> + * if there is none. + * @throws NullPointerException If <i>subject</i> is null. + * @throws SecurityException If the caller does not have permission to get + * the subject (<code>"getSubject"</code> target of {@link AuthPermission}. + */ + public static Subject getSubject (final AccessControlContext context) + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("getSubject")); + } + DomainCombiner dc = context.getDomainCombiner(); + if (!(dc instanceof SubjectDomainCombiner)) + { + return null; + } + return ((SubjectDomainCombiner) dc).getSubject(); + } + + /** + * <p>Run a method as another subject. This method will obtain the current + * {@link AccessControlContext} for this thread, then creates another with + * a {@link SubjectDomainCombiner} with the given subject. The supplied + * action will then be run with the modified context.</p> + * + * @param subject The subject to run as. + * @param action The action to run. + * @return The value returned by the privileged action. + * @throws SecurityException If the caller is not allowed to run under a + * different identity (<code>"doAs"</code> target of {@link AuthPermission}. + */ + public static Object doAs (final Subject subject, final PrivilegedAction action) + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("doAs")); + } + AccessControlContext context = + new AccessControlContext (AccessController.getContext(), + new SubjectDomainCombiner (subject)); + return AccessController.doPrivileged (action, context); + } + + /** + * <p>Run a method as another subject. This method will obtain the current + * {@link AccessControlContext} for this thread, then creates another with + * a {@link SubjectDomainCombiner} with the given subject. The supplied + * action will then be run with the modified context.</p> + * + * @param subject The subject to run as. + * @param action The action to run. + * @return The value returned by the privileged action. + * @throws SecurityException If the caller is not allowed to run under a + * different identity (<code>"doAs"</code> target of {@link AuthPermission}. + * @throws PrivilegedActionException If the action throws an exception. + */ + public static Object doAs (final Subject subject, + final PrivilegedExceptionAction action) + throws PrivilegedActionException + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("doAs")); + } + AccessControlContext context = + new AccessControlContext (AccessController.getContext(), + new SubjectDomainCombiner(subject)); + return AccessController.doPrivileged (action, context); + } + + /** + * <p>Run a method as another subject. This method will create a new + * {@link AccessControlContext} derived from the given one, with a + * {@link SubjectDomainCombiner} with the given subject. The supplied + * action will then be run with the modified context.</p> + * + * @param subject The subject to run as. + * @param action The action to run. + * @param acc The context to use. + * @return The value returned by the privileged action. + * @throws SecurityException If the caller is not allowed to run under a + * different identity (<code>"doAsPrivileged"</code> target of {@link + * AuthPermission}. + */ + public static Object doAsPrivileged (final Subject subject, + final PrivilegedAction action, + final AccessControlContext acc) + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("doAsPrivileged")); + } + AccessControlContext context = + new AccessControlContext (acc, new SubjectDomainCombiner (subject)); + return AccessController.doPrivileged (action, context); + } + + /** + * <p>Run a method as another subject. This method will create a new + * {@link AccessControlContext} derived from the given one, with a + * {@link SubjectDomainCombiner} with the given subject. The supplied + * action will then be run with the modified context.</p> + * + * @param subject The subject to run as. + * @param action The action to run. + * @param acc The context to use. + * @return The value returned by the privileged action. + * @throws SecurityException If the caller is not allowed to run under a + * different identity (<code>"doAsPrivileged"</code> target of + * {@link AuthPermission}. + * @throws PrivilegedActionException If the action throws an exception. + */ + public static Object doAsPrivileged (final Subject subject, + final PrivilegedExceptionAction action, + final AccessControlContext acc) + throws PrivilegedActionException + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("doAsPrivileged")); + } + AccessControlContext context = + new AccessControlContext (acc, new SubjectDomainCombiner (subject)); + return AccessController.doPrivileged (action, context); + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public boolean equals (Object o) + { + if (!(o instanceof Subject)) + { + return false; + } + Subject that = (Subject) o; + return principals.containsAll (that.getPrincipals()) && + pubCred.containsAll (that.getPublicCredentials()) && + privCred.containsAll (that.getPrivateCredentials()); + } + + public Set getPrincipals() + { + return principals; + } + + public Set getPrincipals(Class clazz) + { + HashSet result = new HashSet (principals.size()); + for (Iterator it = principals.iterator(); it.hasNext(); ) + { + Object o = it.next(); + if (o != null && clazz.isAssignableFrom (o.getClass())) + { + result.add(o); + } + } + return Collections.unmodifiableSet (result); + } + + public Set getPrivateCredentials() + { + return privCred; + } + + public Set getPrivateCredentials (Class clazz) + { + HashSet result = new HashSet (privCred.size()); + for (Iterator it = privCred.iterator(); it.hasNext(); ) + { + Object o = it.next(); + if (o != null && clazz.isAssignableFrom (o.getClass())) + { + result.add(o); + } + } + return Collections.unmodifiableSet (result); + } + + public Set getPublicCredentials() + { + return pubCred; + } + + public Set getPublicCredentials (Class clazz) + { + HashSet result = new HashSet (pubCred.size()); + for (Iterator it = pubCred.iterator(); it.hasNext(); ) + { + Object o = it.next(); + if (o != null && clazz.isAssignableFrom (o.getClass())) + { + result.add(o); + } + } + return Collections.unmodifiableSet (result); + } + + public int hashCode() + { + return principals.hashCode() + privCred.hashCode() + pubCred.hashCode(); + } + + /** + * <p>Returns whether or not this subject is read-only.</p> + * + * @return True is this subject is read-only. + */ + public boolean isReadOnly() + { + return readOnly; + } + + /** + * <p>Marks this subject as read-only.</p> + * + * @throws SecurityException If the caller does not have permission to + * set this subject as read-only (<code>"setReadOnly"</code> target of + * {@link AuthPermission}. + */ + public void setReadOnly() + { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + sm.checkPermission (new AuthPermission ("setReadOnly")); + } + readOnly = true; + } + + public String toString() + { + return Subject.class.getName() + " [ principals=" + principals + + ", private credentials=" + privCred + ", public credentials=" + + pubCred + ", read-only=" + readOnly + " ]"; + } + +// Inner class. + // ------------------------------------------------------------------------- + + /** + * An undocumented inner class that is used for sets in the parent class. + */ + private static class SecureSet extends AbstractSet implements Serializable + { + + // Fields. + // ----------------------------------------------------------------------- + + private static final long serialVersionUID = 7911754171111800359L; + + static final int PRINCIPALS = 0; + static final int PUBLIC_CREDENTIALS = 1; + static final int PRIVATE_CREDENTIALS = 2; + + private final Subject subject; + private final LinkedList elements; + private transient final int type; + + // Constructors. + // ----------------------------------------------------------------------- + + SecureSet (final Subject subject, final int type, final Collection elements) + { + this (subject, type); + for (Iterator it = elements.iterator(); it.hasNext(); ) + { + Object o = it.next(); + if (type == PRINCIPALS && !(o instanceof Principal)) + { + throw new IllegalArgumentException(o+" is not a Principal"); + } + if (!elements.contains (o)) + { + elements.add (o); + } + } + } + + SecureSet (final Subject subject, final int type) + { + this.subject = subject; + this.type = type; + this.elements = new LinkedList(); + } + + // Instance methods. + // ----------------------------------------------------------------------- + + public synchronized int size() + { + return elements.size(); + } + + public Iterator iterator() + { + return elements.iterator(); + } + + public synchronized boolean add(Object element) + { + if (subject.isReadOnly()) + { + throw new IllegalStateException ("subject is read-only"); + } + final SecurityManager sm = System.getSecurityManager(); + switch (type) + { + case PRINCIPALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPrincipals")); + } + if (!(element instanceof Principal)) + { + throw new IllegalArgumentException ("element is not a Principal"); + } + break; + + case PUBLIC_CREDENTIALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPublicCredentials")); + } + break; + + case PRIVATE_CREDENTIALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPrivateCredentials")); + } + break; + + default: + throw new Error ("this statement should be unreachable"); + } + + if (elements.contains (element)) + { + return false; + } + + return elements.add (element); + } + + public synchronized boolean remove (final Object element) + { + if (subject.isReadOnly()) + { + throw new IllegalStateException ("subject is read-only"); + } + final SecurityManager sm = System.getSecurityManager(); + switch (type) + { + case PRINCIPALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPrincipals")); + } + if (!(element instanceof Principal)) + { + throw new IllegalArgumentException ("element is not a Principal"); + } + break; + + case PUBLIC_CREDENTIALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPublicCredentials")); + } + break; + + case PRIVATE_CREDENTIALS: + if (sm != null) + { + sm.checkPermission (new AuthPermission ("modifyPrivateCredentials")); + } + break; + + default: + throw new Error("this statement should be unreachable"); + } + + return elements.remove(element); + } + + public synchronized boolean contains (final Object element) + { + return elements.remove (element); + } + + public boolean removeAll (final Collection c) + { + if (subject.isReadOnly()) + { + throw new IllegalStateException ("subject is read-only"); + } + return super.removeAll (c); + } + + public boolean retainAll (final Collection c) + { + if (subject.isReadOnly()) + { + throw new IllegalStateException ("subject is read-only"); + } + return super.retainAll (c); + } + + public void clear() + { + if (subject.isReadOnly()) + { + throw new IllegalStateException ("subject is read-only"); + } + elements.clear(); + } + + private synchronized void writeObject (ObjectOutputStream out) + throws IOException + { + throw new UnsupportedOperationException ("FIXME: determine serialization"); + } + + private void readObject (ObjectInputStream in) + throws ClassNotFoundException, IOException + { + throw new UnsupportedOperationException ("FIXME: determine serialization"); + } + } +} diff --git a/javax/security/auth/SubjectDomainCombiner.java b/javax/security/auth/SubjectDomainCombiner.java new file mode 100644 index 000000000..194e1130a --- /dev/null +++ b/javax/security/auth/SubjectDomainCombiner.java @@ -0,0 +1,96 @@ +/* SubjectDomainCombiner.java -- domain combiner for Subjects. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth; + +import java.security.DomainCombiner; +import java.security.Principal; +import java.security.ProtectionDomain; + +import java.util.LinkedList; + +public class SubjectDomainCombiner implements DomainCombiner +{ + + // Field. + // ------------------------------------------------------------------------- + + private final Subject subject; + + // Constructor. + // ------------------------------------------------------------------------- + + public SubjectDomainCombiner (final Subject subject) + { + this.subject = subject; + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public ProtectionDomain[] combine (final ProtectionDomain[] current, + final ProtectionDomain[] assigned) + { + LinkedList domains = new LinkedList(); + Principal[] principals = + (Principal[]) subject.getPrincipals().toArray (new Principal[0]); + if (current != null) + { + for (int i = 0; i < current.length; i++) + { + domains.add (new ProtectionDomain (current[i].getCodeSource(), + current[i].getPermissions(), + current[i].getClassLoader(), + principals)); + } + } + if (assigned != null) + { + for (int i = 0; i < assigned.length; i++) + { + domains.add (assigned[i]); + } + } + return (ProtectionDomain[]) domains.toArray (new ProtectionDomain[domains.size()]); + } + + public Subject getSubject() + { + return subject; + } +} diff --git a/javax/security/auth/callback/Callback.java b/javax/security/auth/callback/Callback.java new file mode 100644 index 000000000..655ad3348 --- /dev/null +++ b/javax/security/auth/callback/Callback.java @@ -0,0 +1,65 @@ +/* Callback.java -- marker interface for callback classes + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +/** + * <p>Implementations of this interface are passed to a {@link CallbackHandler}, + * allowing underlying security services the ability to interact with a calling + * application to retrieve specific authentication data such as usernames and + * passwords, or to display certain information, such as error and warning + * messages.</p> + * + * <p><code>Callback</code> implementations do not retrieve or display the + * information requested by underlying security services. <code>Callback</code> + * implementations simply provide the means to pass such requests to + * applications, and for applications, if appropriate, to return requested + * information back to the underlying security services.</p> + * + * @see CallbackHandler + * @see ChoiceCallback + * @see ConfirmationCallback + * @see LanguageCallback + * @see NameCallback + * @see PasswordCallback + * @see TextInputCallback + * @see TextOutputCallback + * @version $Revision: 1.1 $ + */ +public interface Callback { +} diff --git a/javax/security/auth/callback/CallbackHandler.java b/javax/security/auth/callback/CallbackHandler.java new file mode 100644 index 000000000..289999c5e --- /dev/null +++ b/javax/security/auth/callback/CallbackHandler.java @@ -0,0 +1,156 @@ +/* CallbackHandler.java -- base interface for callback handlers. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.IOException; + +/** + * <p>An application implements a <code>CallbackHandler</code> and passes it to + * underlying security services so that they may interact with the application + * to retrieve specific authentication data, such as usernames and passwords, or + * to display certain information, such as error and warning messages.</p> + * + * <p><code>CallbackHandler</code>s are implemented in an application-dependent + * fashion. For example, implementations for an application with a graphical + * user interface (GUI) may pop up windows to prompt for requested information + * or to display error messages. An implementation may also choose to obtain + * requested information from an alternate source without asking the end user.</p> + * + * <p>Underlying security services make requests for different types of + * information by passing individual Callbacks to the <code>CallbackHandler</code>. + * The <code>CallbackHandler</code> implementation decides how to retrieve and + * display information depending on the {@link Callback}s passed to it. For + * example, if the underlying service needs a username and password to + * authenticate a user, it uses a {@link NameCallback} and + * {@link PasswordCallback}. The <code>CallbackHandler</code> can then choose + * to prompt for a username and password serially, or to prompt for both in a + * single window.</p> + * + * <p>A default <code>CallbackHandler</code> class implementation may be + * specified in the <code>auth.login.defaultCallbackHandler</code> security + * property. The security property can be set in the Java security properties + * file located in the file named + * <code><JAVA_HOME>/lib/security/java.security</code>, where + * <code><JAVA_HOME></code> refers to the directory where the SDK was + * installed.</p> + * + * <p>If the security property is set to the fully qualified name of a + * <code>CallbackHandler</code> implementation class, then a + * <code>LoginContext</code>will load the specified <code>CallbackHandler</code> + * and pass it to the underlying <code>LoginModules</code>. The + * <code>LoginContext</code> only loads the default handler if one was not + * provided.</p> + * + * <p>All default handler implementations must provide a public zero-argument + * constructor.</p> + * + * @version $Revision: 1.1 $ + */ +public interface CallbackHandler +{ + + /** + * <p>Retrieve or display the information requested in the provided + * {@link Callback}s.</p> + * + * <p>The <code>handle()</code> method implementation checks the instance(s) + * of the {@link Callback} object(s) passed in to retrieve or display the + * requested information. The following example is provided to help + * demonstrate what an <code>handle()</code> method implementation might look + * like. This example code is for guidance only. Many details, including + * proper error handling, are left out for simplicity.</p> + * + * <pre> + *public void handle(Callback[] callbacks) + *throws IOException, UnsupportedCallbackException { + * for (int i = 0; i < callbacks.length; i++) { + * if (callbacks[i] instanceof TextOutputCallback) { + * // display the message according to the specified type + * TextOutputCallback toc = (TextOutputCallback)callbacks[i]; + * switch (toc.getMessageType()) { + * case TextOutputCallback.INFORMATION: + * System.out.println(toc.getMessage()); + * break; + * case TextOutputCallback.ERROR: + * System.out.println("ERROR: " + toc.getMessage()); + * break; + * case TextOutputCallback.WARNING: + * System.out.println("WARNING: " + toc.getMessage()); + * break; + * default: + * throw new IOException("Unsupported message type: " + * + toc.getMessageType()); + * } + * } else if (callbacks[i] instanceof NameCallback) { + * // prompt the user for a username + * NameCallback nc = (NameCallback)callbacks[i]; + * // ignore the provided defaultName + * System.err.print(nc.getPrompt()); + * System.err.flush(); + * nc.setName((new BufferedReader( + * new InputStreamReader(System.in))).readLine()); + * } else if (callbacks[i] instanceof PasswordCallback) { + * // prompt the user for sensitive information + * PasswordCallback pc = (PasswordCallback)callbacks[i]; + * System.err.print(pc.getPrompt()); + * System.err.flush(); + * pc.setPassword(readPassword(System.in)); + * } else { + * throw new UnsupportedCallbackException( + * callbacks[i], "Unrecognized Callback"); + * } + * } + *} + * + * // Reads user password from given input stream. + *private char[] readPassword(InputStream in) throws IOException { + * // insert code to read a user password from the input stream + *} + * </pre> + * + * @param callbacks an array of {@link Callback} objects provided by an + * underlying security service which contains the information requested to + * be retrieved or displayed. + * @throws IOException if an input or output error occurs. + * @throws UnsupportedCallbackException if the implementation of this method + * does not support one or more of the Callbacks specified in the + * <code>callbacks</code> parameter. + */ + void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException; +} diff --git a/javax/security/auth/callback/ChoiceCallback.java b/javax/security/auth/callback/ChoiceCallback.java new file mode 100644 index 000000000..44b5ffcba --- /dev/null +++ b/javax/security/auth/callback/ChoiceCallback.java @@ -0,0 +1,237 @@ +/* ChoiceCallback.java -- callback for a choice of values. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * Underlying security services instantiate and pass a + * <code>ChoiceCallback</code> to the <code>handle()</code> method of a + * {@link CallbackHandler} to display a list of choices and to retrieve the + * selected choice(s). + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class ChoiceCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial + * @since 1.4 + */ + private String prompt; + + /** + * @serial the list of choices. + * @since 1.4 + */ + private String[] choices; + + /** + * @serial the choice to be used as the default choice. + * @since 1.4 + */ + private int defaultChoice; + + /** + * @serial whether multiple selections are allowed from the list of choices. + * @since 1.4 + */ + private boolean multipleSelectionsAllowed; + + /** + * @serial the selected choices, represented as indexes into the choices list. + * @since 1.4 + */ + private int[] selections; + + // Constructor(s) + //-------------------------------------------------------------------------- + + /** + * Construct a <code>ChoiceCallback</code> with a prompt, a list of choices, + * a default choice, and a boolean specifying whether or not multiple + * selections from the list of choices are allowed. + * + * @param prompt the prompt used to describe the list of choices. + * @param choices the list of choices. + * @param defaultChoice the choice to be used as the default choice when the + * list of choices are displayed. This value is represented as an index into + * the <code>choices</code> array. + * @param multipleSelectionsAllowed boolean specifying whether or not + * multiple selections can be made from the list of choices. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>, + * if <code>prompt</code> has a length of <code>0</code>, if <code>choices</code> + * is <code>null</code>, if <code>choices</code> has a length of <code>0</code>, + * if any element from <code>choices</code> is <code>null</code>, if any + * element from <code>choices</code> has a length of <code>0</code> or if + * <code>defaultChoice</code> does not fall within the array boundaries of + * <code>choices</code>. + */ + public ChoiceCallback(String prompt, String[] choices, int defaultChoice, + boolean multipleSelectionsAllowed) + { + super(); + + setPrompt(prompt); + setChoices(choices); + if (defaultChoice < 0 || defaultChoice >= this.choices.length) + { + throw new IllegalArgumentException("default choice is out of bounds"); + } + this.defaultChoice = defaultChoice; + this.multipleSelectionsAllowed = multipleSelectionsAllowed; + } + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the prompt. + * + * @return the prompt. + */ + public String getPrompt() + { + return prompt; + } + + /** + * Get the list of choices. + * + * @return the list of choices. + */ + public String[] getChoices() + { + return choices; + } + + /** + * Get the defaultChoice. + * + * @return the defaultChoice, represented as an index into the choices list. + */ + public int getDefaultChoice() + { + return defaultChoice; + } + + /** + * Get the boolean determining whether multiple selections from the choices + * list are allowed. + * + * @return whether multiple selections are allowed. + */ + public boolean allowMultipleSelections() + { + return multipleSelectionsAllowed; + } + + /** + * Set the selected choice. + * + * @param selection the selection represented as an index into the choices + * list. + * @see #getSelectedIndexes() + */ + public void setSelectedIndex(int selection) + { + this.selections = new int[1]; + this.selections[0] = selection; + } + + /** + * Set the selected choices. + * + * @param selections the selections represented as indexes into the choices + * list. + * @throws UnsupportedOperationException if multiple selections are not + * allowed, as determined by <code>allowMultipleSelections</code>. + * @see #getSelectedIndexes() + */ + public void setSelectedIndexes(int[] selections) + { + if (!multipleSelectionsAllowed) + { + throw new UnsupportedOperationException("not allowed"); + } + + this.selections = selections; + } + + /** + * Get the selected choices. + * + * @return the selected choices, represented as indexes into the choices list. + * @see #setSelectedIndexes(int[]) + */ + public int[] getSelectedIndexes() + { + return selections; + } + + private void setPrompt(String prompt) throws IllegalArgumentException + { + if ((prompt == null) || (prompt.length() == 0)) + { + throw new IllegalArgumentException("invalid prompt"); + } + this.prompt = prompt; + } + + private void setChoices(String[] choices) throws IllegalArgumentException + { + if (choices == null || choices.length == 0) + { + throw new IllegalArgumentException("invalid choices"); + } + for (int i = 0; i < choices.length; i++) + { + if (choices[i] == null || choices[i].length() == 0) + { + throw new IllegalArgumentException("invalid choice at index #"+i); + } + } + this.choices = choices; + } +} diff --git a/javax/security/auth/callback/ConfirmationCallback.java b/javax/security/auth/callback/ConfirmationCallback.java new file mode 100644 index 000000000..8abd393f5 --- /dev/null +++ b/javax/security/auth/callback/ConfirmationCallback.java @@ -0,0 +1,506 @@ +/* ConfirmationCallback.java -- callback for confirmations. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * Underlying security services instantiate and pass a + * <code>ConfirmationCallback</code> to the <code>handle()</code> method of a + * {@link CallbackHandler} to ask for YES/NO, OK/CANCEL, YES/NO/CANCEL or other + * similar confirmations. + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class ConfirmationCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * <p>Unspecified option type.</p> + * + * <p>The <code>getOptionType</code> method returns this value if this + * <code>ConfirmationCallback</code> was instantiated with <code>options</code> + * instead of an <code>optionType</code>.</p> + */ + public static final int UNSPECIFIED_OPTION = -1; + + /** + * <p>YES/NO confirmation option.</p> + * + * <p>An underlying security service specifies this as the <code>optionType</code> + * to a <code>ConfirmationCallback</code> constructor if it requires a + * confirmation which can be answered with either <code>YES</code> or + * <code>NO</code>.</p> + */ + public static final int YES_NO_OPTION = 0; + + /** + * <p>YES/NO/CANCEL confirmation confirmation option.</p> + * + * <p>An underlying security service specifies this as the <code>optionType</code> + * to a <code>ConfirmationCallback</code> constructor if it requires a + * confirmation which can be answered with either <code>YES</code>, + * <code>NO</code> or <code>CANCEL</code>. + */ + public static final int YES_NO_CANCEL_OPTION = 1; + + /** + * <p>OK/CANCEL confirmation confirmation option.</p> + * + * <p>An underlying security service specifies this as the <code>optionType</code> + * to a <code>ConfirmationCallback</code> constructor if it requires a + * confirmation which can be answered with either <code>OK</code> or + * <code>CANCEL</code>.</p> + */ + public static final int OK_CANCEL_OPTION = 2; + + /** + * <p>YES option.</p> + * + * <p>If an <code>optionType</code> was specified to this + * <code>ConfirmationCallback</code>, this option may be specified as a + * <code>defaultOption</code> or returned as the selected index.</p> + */ + public static final int YES = 0; + + /** + * <p>NO option.</p> + * + * <p>If an <code>optionType</code> was specified to this + * <code>ConfirmationCallback</code>, this option may be specified as a + * <code>defaultOption</code> or returned as the selected index.</p> + */ + public static final int NO = 1; + + /** + * <p>CANCEL option.</p> + * + * <p>If an <code>optionType</code> was specified to this + * <code>ConfirmationCallback</code>, this option may be specified as a + * <code>defaultOption</code> or returned as the selected index.</p> + */ + public static final int CANCEL = 2; + + /** + * <p>OK option.</p> + * + * <p>If an <code>optionType</code> was specified to this + * <code>ConfirmationCallback</code>, this option may be specified as a + * <code>defaultOption</code> or returned as the selected index.</p> + */ + public static final int OK = 3; + + /** INFORMATION message type. */ + public static final int INFORMATION = 0; + + /** WARNING message type. */ + public static final int WARNING = 1; + + /** ERROR message type. */ + public static final int ERROR = 2; + + /** + * @serial + * @since 1.4 + */ + private String prompt; + + /** + * @serial + * @since 1.4 + */ + private int messageType; + + /** + * @serial + * @since 1.4 + */ + private int optionType; + + /** + * @serial + * @since 1.4 + */ + private int defaultOption; + + /** + * @serial + * @since 1.4 + */ + private String[] options = null; + + /** + * @serial + * @since 1.4 + */ + private int selection; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * <p>Construct a <code>ConfirmationCallback</code> with a message type, an + * option type and a default option.</p> + * + * <p>Underlying security services use this constructor if they require + * either a YES/NO, YES/NO/CANCEL or OK/CANCEL confirmation.</p> + * + * @param messageType the message type (INFORMATION, WARNING or ERROR). + * @param optionType the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or + * OK_CANCEL_OPTION). + * @param defaultOption the default option from the provided optionType (YES, + * NO, CANCEL or OK). + * @throws IllegalArgumentException if <code>messageType</code> is not either + * <code>INFORMATION</code>, <code>WARNING</code>, or <code>ERROR</code>, if + * <code>optionType</code> is not either <code>YES_NO_OPTION</code>, + * <code>YES_NO_CANCEL_OPTION</code>, or <code>OK_CANCEL_OPTION</code>, or if + * <code>defaultOption</code> does not correspond to one of the options in + * <code>optionType</code>. + */ + public ConfirmationCallback(int messageType, int optionType, int defaultOption) + throws IllegalArgumentException + { + super(); + + setMessageType(messageType); + setOptionType(optionType, defaultOption); + this.defaultOption = defaultOption; + } + + /** + * <p>Construct a <code>ConfirmationCallback</code> with a message type, a + * list of options and a default option.</p> + * + * <p>Underlying security services use this constructor if they require a + * confirmation different from the available preset confirmations provided + * (for example, CONTINUE/ABORT or STOP/GO). The confirmation options are + * listed in the <code>options</code> array, and are displayed by the + * {@link CallbackHandler} implementation in a manner consistent with the + * way preset options are displayed.</p> + * + * @param messageType the message type (INFORMATION, WARNING or ERROR). + * @param options the list of confirmation options. + * @param defaultOption the default option, represented as an index into the + * <code>options</code> array. + * @throws IllegalArgumentException if <code>messageType</code> is not either + * <code>INFORMATION</code>, <code>WARNING</code>, or <code>ERROR</code>, if + * <code>options</code> is <code>null</code>, if <code>options</code> has a + * length of <code>0</code>, if any element from <code>options</code> is + * <code>null</code>, if any element from <code>options</code> has a length + * of <code>0</code>, or if <code>defaultOption</code> does not lie within + * the array boundaries of <code>options</code>. + */ + public ConfirmationCallback(int messageType, String[] options, int defaultOption) + { + super(); + + setMessageType(messageType); + setOptions(options, defaultOption); + this.defaultOption = defaultOption; + } + + /** + * <p>Construct a <code>ConfirmationCallback</code> with a prompt, message + * type, an option type and a default option.</p> + * + * <p>Underlying security services use this constructor if they require + * either a YES/NO, YES/NO/CANCEL or OK/CANCEL confirmation.</p> + * + * @param prompt the prompt used to describe the list of options. + * @param messageType the message type (INFORMATION, WARNING or ERROR). + * @param optionType the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or + * OK_CANCEL_OPTION). + * @param defaultOption the default option from the provided optionType (YES, + * NO, CANCEL or OK). + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>, + * if <code>prompt</code> has a length of <code>0</code>, if + * <code>messageType</code> is not either <ode>INFORMATION</code>, + * <code>WARNING</code>, or <code>ERROR</code>, if <code>optionType</code> is + * not either <code>YES_NO_OPTION</code>, <code>YES_NO_CANCEL_OPTION</code>, + * or <code>OK_CANCEL_OPTION</code>, or if <code>defaultOption</code> does + * not correspond to one of the options in <code>optionType</code>. + */ + public ConfirmationCallback(String prompt, int messageType, int optionType, + int defaultOption) + { + super(); + + setPrompt(prompt); + setMessageType(messageType); + setOptionType(optionType, defaultOption); + this.defaultOption = defaultOption; + } + + /** + * <p>Construct a <code>ConfirmationCallback</code> with a prompt, message + * type, a list of options and a default option.</p> + * + * <p>Underlying security services use this constructor if they require a + * confirmation different from the available preset confirmations provided + * (for example, CONTINUE/ABORT or STOP/GO). The confirmation options are + * listed in the <code>options</code> array, and are displayed by the + * {@link CallbackHandler} implementation in a manner consistent with the + * way preset options are displayed.</p> + * + * @param prompt the prompt used to describe the list of options. + * @param messageType the message type (INFORMATION, WARNING or ERROR). + * @param options the list of confirmation options. + * @param defaultOption the default option, represented as an index into the + * <code>options</code> array. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>, + * if <code>prompt</code> has a length of <code>0</code>, if + * <code>messageType</code> is not either <ode>INFORMATION</code>, + * <code>WARNING</code>, or <code>ERROR</code>, if <code>options</code> is + * <code>null</code>, if <code>options</code> has a length of <code>0</code>, + * if any element from <code>options</code> is <code>null</code>, if any + * element from <code>options</code> has a length of <code>0</code>, or if + * <code>defaultOption</code> does not lie within the array boundaries of + * <code>options</code>. + */ + public ConfirmationCallback(String prompt, int messageType, String[] options, + int defaultOption) + { + super(); + + setPrompt(prompt); + setMessageType(messageType); + setOptions(options, defaultOption); + this.defaultOption = defaultOption; + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the prompt. + * + * @return the prompt, or <code>null</code> if this + * <code>ConfirmationCallback</code> was instantiated without a prompt. + */ + public String getPrompt() + { + return prompt; + } + + /** + * Get the message type. + * + * @return the message type (INFORMATION, WARNING or ERROR). + */ + public int getMessageType() + { + return messageType; + } + + /** + * <p>Get the option type.</p> + * + * <p>If this method returns {@link #UNSPECIFIED_OPTION}, then this + * <code>ConfirmationCallback</code> was instantiated with <code>options</code> + * instead of an <code>optionType</code>. In this case, invoke the + * {@link #getOptions()} method to determine which confirmation options to + * display.</p> + * + * @return the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or + * OK_CANCEL_OPTION), or UNSPECIFIED_OPTION if this + * <code>ConfirmationCallback</code> was instantiated with <code>options</code> + * instead of an <code>optionType</code>. + */ + public int getOptionType() + { + if (options != null) + { + return UNSPECIFIED_OPTION; + } + return optionType; + } + + /** + * Get the confirmation options. + * + * @return the list of confirmation options, or <code>null</code> if this + * <code>ConfirmationCallback</code> was instantiated with an + * <code>optionType</code> instead of <code>options</code>. + */ + public String[] getOptions() + { + return options; + } + + /** + * Get the default option. + * + * @return the default option, represented as <code>YES</code>, <code>NO</code>, + * <code>OK</code> or <code>CANCEL</code> if an <code>optionType</code> was + * specified to the constructor of this <code>ConfirmationCallback</code>. + * Otherwise, this method returns the default option as an index into the + * <code>options</code> array specified to the constructor of this + * <code>ConfirmationCallback</code>. + */ + public int getDefaultOption() + { + return defaultOption; + } + + /** + * Set the selected confirmation option. + * + * @param selection the selection represented as <code>YES</code>, + * <code>NO</code>, <code>OK</code> or <code>CANCEL</code> if an + * <code>optionType</code> was specified to the constructor of this + * <code>ConfirmationCallback</code>. Otherwise, the <code>selection</code> + * represents the index into the <code>options</code> array specified to the + * constructor of this <code>ConfirmationCallback</code>. + * @see #getSelectedIndex() + */ + public void setSelectedIndex(int selection) + { + if (options != null) + { + setOptions(options, selection); + } + else + { + setOptionType(optionType, selection); + } + } + + /** + * Get the selected confirmation option. + * + * @return the selected confirmation option represented as <code>YES</code>, + * <code>NO</code>, <code>OK</code> or <code>CANCEL</code> if an + * <code>optionType</code> was specified to the constructor of this + * <code>ConfirmationCallback</code>. Otherwise, this method returns the + * selected confirmation option as an index into the <code>options</code> + * array specified to the constructor of this <code>ConfirmationCallback</code>. + * @see #setSelectedIndex(int) + */ + public int getSelectedIndex() + { + return this.selection; + } + + private void setMessageType(int messageType) throws IllegalArgumentException + { + switch (messageType) + { + case INFORMATION: + case WARNING: + case ERROR: this.messageType = messageType; break; + default: throw new IllegalArgumentException("illegal message type"); + } + } + + private void setOptionType(int optionType, int selectedOption) + throws IllegalArgumentException + { + switch (optionType) + { + case YES_NO_OPTION: + this.optionType = optionType; + switch (selectedOption) + { + case YES: + case NO: this.selection = selectedOption; break; + default: throw new IllegalArgumentException("invalid option"); + } + break; + case YES_NO_CANCEL_OPTION: + this.optionType = optionType; + switch (selectedOption) + { + case YES: + case NO: + case CANCEL: this.selection = selectedOption; break; + default: throw new IllegalArgumentException("invalid option"); + } + break; + case OK_CANCEL_OPTION: + this.optionType = optionType; + switch (selectedOption) + { + case OK: + case CANCEL: this.selection = selectedOption; break; + default: throw new IllegalArgumentException("invalid option"); + } + break; + default: + throw new IllegalArgumentException("illegal option type"); + } + } + + private void setOptions(String[] options, int selectedOption) + throws IllegalArgumentException + { + if ((selectedOption < 0) || (selectedOption > options.length - 1)) + { + throw new IllegalArgumentException("invalid selection"); + } + if ((options == null) || (options.length == 0)) + { + throw new IllegalArgumentException("options is null or empty"); + } + for (int i = 0; i < options.length; i++) + { + if ((options[i] == null) || (options[i].length() == 0)) + { + throw new IllegalArgumentException("options[" + i + "] is null or empty"); + } + } + this.options = options; + this.selection = selectedOption; + } + + private void setPrompt(String prompt) throws IllegalArgumentException + { + if ((prompt == null) || (prompt.length() == 0)) + { + throw new IllegalArgumentException("prompt is null or empty"); + } + this.prompt = prompt; + } +} diff --git a/javax/security/auth/callback/LanguageCallback.java b/javax/security/auth/callback/LanguageCallback.java new file mode 100644 index 000000000..71910632b --- /dev/null +++ b/javax/security/auth/callback/LanguageCallback.java @@ -0,0 +1,101 @@ +/* LanguageCallback.java -- callback for language choices. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; +import java.util.Locale; + +/** + * Underlying security services instantiate and pass a <code>LanguageCallback</code> + * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve + * the {@link Locale} used for localizing text. + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class LanguageCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial + * @since 1.4 + */ + private Locale locale; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** Construct a <code>LanguageCallback</code>. */ + public LanguageCallback() + { + super(); + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Set the retrieved Locale. + * + * @param locale the retrieved Locale. + * @see #getLocale() + */ + public void setLocale(Locale locale) + { + this.locale = locale; + } + + /** + * Get the retrieved Locale. + * + * @return the retrieved Locale, or <code>null</code> if no Locale could be + * retrieved. + * @see #setLocale(Locale) + */ + public Locale getLocale() + { + return locale; + } +} diff --git a/javax/security/auth/callback/NameCallback.java b/javax/security/auth/callback/NameCallback.java new file mode 100644 index 000000000..c98edfdbe --- /dev/null +++ b/javax/security/auth/callback/NameCallback.java @@ -0,0 +1,179 @@ +/* NameCallback.java -- callback for user names. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * Underlying security services instantiate and pass a <code>NameCallback</code> + * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve + * name information. + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class NameCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial + * @since 1.4 + */ + private String prompt; + + /** + * @serial + * @since 1.4 + */ + private String defaultName; + + /** + * @serial + * @since 1.4 + */ + private String inputName; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Construct a <code>NameCallback</code> with a prompt. + * + * @param prompt the prompt used to request the name. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or if <code>prompt</code> has a length of <code>0</code>. + */ + public NameCallback(String prompt) + { + super(); + + setPrompt(prompt); + } + + /** + * Construct a <code>NameCallback</code> with a prompt and default name. + * + * @param prompt the prompt used to request the information. + * @param defaultName the name to be used as the default name displayed with + * the prompt. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or if <code>prompt</code> has a length of <code>0</code>, if + * <code>defaultName</code> is <code>null</code>, or if <code>defaultName</code> + * has a length of <code>0</code>. + */ + public NameCallback(String prompt, String defaultName) + throws IllegalArgumentException + { + super(); + + setPrompt(prompt); + setDefaultName(defaultName); + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the prompt. + * + * @return the prompt. + */ + public String getPrompt() + { + return prompt; + } + + /** + * Get the default name. + * + * @return the default name, or <code>null</code> if this + * <code>NameCallback</code> was not instantiated with a + * <code>defaultName</code>. + */ + public String getDefaultName() + { + return defaultName; + } + + /** + * Set the retrieved name. + * + * @param name the retrieved name (which may be <code>null</code>). + * @see #getName() + */ + public void setName(String name) + { + this.inputName = name; + } + + /** + * Get the retrieved name. + * + * @return the retrieved name (which may be <code>null</code>) + * @see #setName(String) + */ + public String getName() + { + return inputName; + } + + private void setPrompt(String prompt) throws IllegalArgumentException + { + if ((prompt == null) || (prompt.length() == 0)) + { + throw new IllegalArgumentException("invalid prompt"); + } + this.prompt = prompt; + } + + private void setDefaultName(String defaultName) throws IllegalArgumentException + { + if ((defaultName == null) || (defaultName.length() == 0)) + { + throw new IllegalArgumentException("invalid default name"); + } + this.defaultName = defaultName; + } +} diff --git a/javax/security/auth/callback/PasswordCallback.java b/javax/security/auth/callback/PasswordCallback.java new file mode 100644 index 000000000..5620bc5cd --- /dev/null +++ b/javax/security/auth/callback/PasswordCallback.java @@ -0,0 +1,169 @@ +/* PasswordCallback.java -- callback for passwords. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * Underlying security services instantiate and pass a <code>PasswordCallback</code> + * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve + * password information. + * + * @see CallbackHandler, + * @version $Revision: 1.1 $ + */ +public class PasswordCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial + * @since 1.4 + */ + private String prompt; + + /** + * @serial + * @since 1.4 + */ + private boolean echoOn; + + /** + * @serial + * @since 1.4 + */ + private char[] inputPassword; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Construct a <code>PasswordCallback</code> with a prompt and a boolean + * specifying whether the password should be displayed as it is being typed. + * + * @param prompt the prompt used to request the password. + * @param echoOn <code>true</code> if the password should be displayed as it + * is being typed. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or if <code>prompt</code> has a length of <code>0</code>. + */ + public PasswordCallback(String prompt, boolean echoOn) + { + super(); + + setPrompt(prompt); + this.echoOn = echoOn; + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the prompt. + * + * @return the prompt. + */ + public String getPrompt() + { + return prompt; + } + + /** + * Return whether the password should be displayed as it is being typed. + * + * @return the whether the password should be displayed as it is being typed. + */ + public boolean isEchoOn() + { + return echoOn; + } + + /** + * <p>Set the retrieved password.</p> + * + * <p>This method makes a copy of the input password before storing it.</p> + * + * @param password the retrieved password, which may be <code>null</code>. + * @see #getPassword() + */ + public void setPassword(char[] password) + { + inputPassword = (password == null ? null : (char[]) password.clone()); + } + + /** + * <p>Get the retrieved password.</p> + * + * <p>This method returns a copy of the retrieved password.</p> + * + * @return the retrieved password, which may be <code>null</code>. + * @see #setPassword(char[]) + */ + public char[] getPassword() + { + return (inputPassword == null ? null : (char[]) inputPassword.clone()); + } + + /** Clear the retrieved password. */ + public void clearPassword() + { + if (inputPassword != null) + { + for (int i = 0; i < inputPassword.length; i++) + { + inputPassword[i] = '\0'; + } + inputPassword = null; + } + } + + private void setPrompt(String prompt) throws IllegalArgumentException + { + if ((prompt == null) || (prompt.length() == 0)) + { + throw new IllegalArgumentException("invalid prompt"); + } + this.prompt = prompt; + } +} diff --git a/javax/security/auth/callback/TextInputCallback.java b/javax/security/auth/callback/TextInputCallback.java new file mode 100644 index 000000000..55c1aa253 --- /dev/null +++ b/javax/security/auth/callback/TextInputCallback.java @@ -0,0 +1,178 @@ +/* TextInputCallback.java -- callbacks for user input. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * Underlying security services instantiate and pass a <code>TextInputCallback</code> + * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve + * generic text information. + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class TextInputCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial + * @since 1.4 + */ + private String prompt; + + /** + * @serial + * @since 1.4 + */ + private String defaultText; + + /** + * @serial + * @since 1.4 + */ + private String inputText; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Construct a <code>TextInputCallback</code> with a prompt. + * + * @param prompt the prompt used to request the information. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or if <code>prompt</code> has a length of <code>0</code>. + */ + public TextInputCallback(String prompt) throws IllegalArgumentException + { + super(); + + setPrompt(prompt); + } + + /** + * Construct a <code>TextInputCallback</code> with a prompt and default + * input value. + * + * @param prompt the prompt used to request the information. + * @param defaultText the text to be used as the default text displayed with + * the prompt. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>, + * if <code>prompt</code> has a length of <code>0</code>, if + * <code>defaultText</code> is <code>null</code> or if <code>defaultText</code> + * has a length of <code>0</code>. + */ + public TextInputCallback(String prompt, String defaultText) + throws IllegalArgumentException + { + super(); + + setPrompt(prompt); + setDefaultText(defaultText); + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the prompt. + * + * @return the prompt. + */ + public String getPrompt() + { + return prompt; + } + + /** + * Get the default text. + * + * @return the default text, or <code>null</code> if this + * <code>TextInputCallback</code> was not instantiated with + * <code>defaultText</code>. + */ + public String getDefaultText() + { + return defaultText; + } + + /** + * Set the retrieved text. + * + * @param text the retrieved text, which may be <code>null</code>. + */ + public void setText(String text) + { + this.inputText = text; + } + + /** + * Get the retrieved text. + * + * @return the retrieved text, which may be <code>null</code>. + */ + public String getText() + { + return inputText; + } + + private void setPrompt(String prompt) throws IllegalArgumentException + { + if ((prompt == null) || (prompt.length() == 0)) + { + throw new IllegalArgumentException("invalid prompt"); + } + this.prompt = prompt; + } + + private void setDefaultText(String defaultText) throws IllegalArgumentException + { + if ((defaultText == null) || (defaultText.length() == 0)) + { + throw new IllegalArgumentException("invalid default text"); + } + this.defaultText = defaultText; + } +} diff --git a/javax/security/auth/callback/TextOutputCallback.java b/javax/security/auth/callback/TextOutputCallback.java new file mode 100644 index 000000000..fac08874d --- /dev/null +++ b/javax/security/auth/callback/TextOutputCallback.java @@ -0,0 +1,141 @@ +/* TextOutputCallback.java -- callback for text output. + Copyright (C) 2003 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +import java.io.Serializable; + +/** + * <p>Underlying security services instantiate and pass a + * <code>TextOutputCallback</code> to the <code>handle()</code> method of a + * {@link CallbackHandler} to display information messages, warning messages and + * error messages.</p> + * + * @see CallbackHandler + * @version $Revision: 1.1 $ + */ +public class TextOutputCallback implements Callback, Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** Information message */ + public static final int INFORMATION = 0; + + /** Warning message */ + public static final int WARNING = 1; + + /** Error message */ + public static final int ERROR = 2; + + /** + * @serial + * @since 1.4 + */ + private int messageType; + + /** + * @serial + * @since 1.4 + */ + private String message; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * <p>Construct a <code>TextOutputCallback</code> with a message type and + * message to be displayed.</p> + * + * @param messageType the message type (INFORMATION, WARNING or ERROR). + * @param message the message to be displayed. + * @throws IllegalArgumentException if <code>messageType</code> is not either + * <code>INFORMATION</code>, <code>WARNING</code> or <code>ERROR</code>, if + * <code>message</code> is <code>null</code>, or if <code>message</code> has + * a length of <code>0</code>. + */ + public TextOutputCallback(int messageType, String message) + throws IllegalArgumentException + { + switch (messageType) + { + case INFORMATION: + case WARNING: + case ERROR: this.messageType = messageType; break; + default: throw new IllegalArgumentException("invalid message type"); + } + + setMessage(message); + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * <p>Returns the message's <code>messageType</code>.</p> + * + * @return the message type (INFORMATION, WARNING or ERROR). + */ + public int getMessageType() + { + return messageType; + } + + /** + * <p>Returns the <code>message</code> to be displayed.</p> + * + * @return the message to be displayed. + */ + public String getMessage() + { + return message; + } + + private void setMessage(String message) throws IllegalArgumentException + { + if ((message == null) || (message.length() == 0)) + { + throw new IllegalArgumentException("invalid message"); + } + this.message = message; + } +} diff --git a/javax/security/auth/callback/UnsupportedCallbackException.java b/javax/security/auth/callback/UnsupportedCallbackException.java new file mode 100644 index 000000000..215942c40 --- /dev/null +++ b/javax/security/auth/callback/UnsupportedCallbackException.java @@ -0,0 +1,102 @@ +/* UnsupportedCallbackException.java -- signals an unsupported callback type. + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.callback; + +/** + * Signals that a {@link CallbackHandler} does not recognize a particular + * {@link Callback}. + * + * @version $Revision: 1.1 $ + */ +public class UnsupportedCallbackException extends Exception +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** @serial */ + private Callback callback; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Constructs an <code>UnsupportedCallbackException</code> with no detail + * message. + * + * @param callback the unrecognized {@link Callback}. + */ + public UnsupportedCallbackException(Callback callback) + { + super(); + + this.callback = callback; + } + + /** + * Constructs an <code>UnsupportedCallbackException</code> with the specified + * detail message. A detail message is a {@link String} that describes this + * particular exception. + * + * @param callback the unrecognized {@link Callback}. + * @param msg the detail message. + */ + public UnsupportedCallbackException(Callback callback, String msg) + { + super(msg); + + this.callback = callback; + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Get the unrecognized {@link Callback}. + * + * @return the unrecognized {@link Callback}. + */ + public Callback getCallback() + { + return this.callback; + } +} diff --git a/javax/security/auth/login/AccountExpiredException.java b/javax/security/auth/login/AccountExpiredException.java new file mode 100644 index 000000000..e8e331347 --- /dev/null +++ b/javax/security/auth/login/AccountExpiredException.java @@ -0,0 +1,64 @@ +/* AccountExpiredException.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +/** + * An exception that signals that an attempt was made to login to an account + * that has expired. + */ +public class AccountExpiredException extends LoginException +{ + + // Constant. + // ------------------------------------------------------------------------- + + private static final long serialVersionUID = -6064064890162661560L; + + // Constructors. + // ------------------------------------------------------------------------- + + public AccountExpiredException() + { + } + + public AccountExpiredException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/login/AppConfigurationEntry.java b/javax/security/auth/login/AppConfigurationEntry.java new file mode 100644 index 000000000..1879a68c1 --- /dev/null +++ b/javax/security/auth/login/AppConfigurationEntry.java @@ -0,0 +1,135 @@ +/* AppConfigurationEntry.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class AppConfigurationEntry +{ + + // Fields. + // ------------------------------------------------------------------------- + + private final String loginModuleName; + private final LoginModuleControlFlag controlFlag; + private final Map options; + + // Constructor. + // ------------------------------------------------------------------------- + + public AppConfigurationEntry (final String loginModuleName, + final LoginModuleControlFlag controlFlag, + final Map options) + { + if (loginModuleName == null || loginModuleName.length() == 0) + throw new IllegalArgumentException ("module name cannot be null nor empty"); + if (LoginModuleControlFlag.OPTIONAL != controlFlag && + LoginModuleControlFlag.REQUIRED != controlFlag && + LoginModuleControlFlag.REQUISITE != controlFlag && + LoginModuleControlFlag.SUFFICIENT != controlFlag) + throw new IllegalArgumentException ("invalid controlFlag"); + if (options == null) + throw new IllegalArgumentException ("options cannot be null"); + this.loginModuleName = loginModuleName; + this.controlFlag = controlFlag; + this.options = Collections.unmodifiableMap (new HashMap (options)); + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public LoginModuleControlFlag getControlFlag() + { + return controlFlag; + } + + public String getLoginModuleName() + { + return loginModuleName; + } + + public Map getOptions() + { + return options; + } + +// Inner class. + // ------------------------------------------------------------------------- + + public static class LoginModuleControlFlag + { + + // Constants. + // ----------------------------------------------------------------------- + + public static final LoginModuleControlFlag OPTIONAL = new LoginModuleControlFlag(); + public static final LoginModuleControlFlag REQUIRED = new LoginModuleControlFlag(); + public static final LoginModuleControlFlag REQUISITE = new LoginModuleControlFlag(); + public static final LoginModuleControlFlag SUFFICIENT = new LoginModuleControlFlag(); + + // Constructor. + // ----------------------------------------------------------------------- + + private LoginModuleControlFlag() + { + } + + // Instance methods. + // ----------------------------------------------------------------------- + + public String toString() + { + StringBuffer buf = new StringBuffer (LoginModuleControlFlag.class.getName()); + buf.append ('.'); + if (this == OPTIONAL) + buf.append ("OPTIONAL"); + else if (this == REQUIRED) + buf.append ("REQUIRED"); + else if (this == REQUISITE) + buf.append ("REQUISITE"); + else if (this == SUFFICIENT) + buf.append ("SUFFICIENT"); + else + buf.append ("HARVEY_THE_RABBIT"); + return buf.toString(); + } + } +} diff --git a/javax/security/auth/login/Configuration.java b/javax/security/auth/login/Configuration.java new file mode 100644 index 000000000..4a55013ca --- /dev/null +++ b/javax/security/auth/login/Configuration.java @@ -0,0 +1,109 @@ +/* Configuration.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.Security; + +import javax.security.auth.AuthPermission; + +public abstract class Configuration +{ + + // Fields. + // ------------------------------------------------------------------------- + + private static Configuration config; + + // Constructors. + // ------------------------------------------------------------------------- + + protected Configuration() + { + } + + // Class methods. + // ------------------------------------------------------------------------- + + public static synchronized Configuration getConfiguration() + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission (new AuthPermission ("getLoginConfiguration")); + if (config == null) + { + String conf = (String) AccessController.doPrivileged + (new PrivilegedAction() + { + public Object run() + { + return Security.getProperty ("login.configuration.provider"); + } + }); + try + { + if (conf != null) + config = (Configuration) Class.forName (conf).newInstance(); + else + config = new NullConfiguration(); + } + catch (Exception x) + { + config = new NullConfiguration(); + } + } + return config; + } + + public static synchronized void setConfiguration (Configuration config) + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission (new AuthPermission ("setLoginConfiguration")); + Configuration.config = config; + } + + // Abstract methods. + // ------------------------------------------------------------------------- + + public abstract AppConfigurationEntry[] getAppConfigurationEntry (String applicationName); + + public abstract void refresh(); +} diff --git a/javax/security/auth/login/CredentialExpiredException.java b/javax/security/auth/login/CredentialExpiredException.java new file mode 100644 index 000000000..df643ba69 --- /dev/null +++ b/javax/security/auth/login/CredentialExpiredException.java @@ -0,0 +1,64 @@ +/* CredentialExpiredException.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +/** + * An exception that signals an attempt to login with a credential that + * has expired. + */ +public class CredentialExpiredException extends LoginException +{ + + // Constant. + // ------------------------------------------------------------------------- + + private static final long serialVersionUID = -5344739593859737937L; + + // Constructors. + // ------------------------------------------------------------------------- + + public CredentialExpiredException() + { + } + + public CredentialExpiredException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/login/FailedLoginException.java b/javax/security/auth/login/FailedLoginException.java new file mode 100644 index 000000000..384ade084 --- /dev/null +++ b/javax/security/auth/login/FailedLoginException.java @@ -0,0 +1,63 @@ +/* FailedLoginException.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +/** + * An exception that signals that an attempt to login was unsuccessful. + */ +public class FailedLoginException extends LoginException +{ + + // Constant. + // ------------------------------------------------------------------------- + + private static final long serialVersionUID = 802556922354616286L; + + // Constructors. + // ------------------------------------------------------------------------- + + public FailedLoginException() + { + } + + public FailedLoginException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/login/LoginContext.java b/javax/security/auth/login/LoginContext.java new file mode 100644 index 000000000..da88e8412 --- /dev/null +++ b/javax/security/auth/login/LoginContext.java @@ -0,0 +1,44 @@ +/* LoginContext.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +public class LoginContext +{ + +} diff --git a/javax/security/auth/login/LoginException.java b/javax/security/auth/login/LoginException.java new file mode 100644 index 000000000..878120381 --- /dev/null +++ b/javax/security/auth/login/LoginException.java @@ -0,0 +1,65 @@ +/* LoginException.java + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +import java.security.GeneralSecurityException; + +/** + * A general exception during authentication and authorization. + */ +public class LoginException extends GeneralSecurityException +{ + + // Constant. + // ------------------------------------------------------------------------- + + private static final long serialVersionUID = -4679091624035232488L; + + // Constructors. + // ------------------------------------------------------------------------- + + public LoginException() + { + } + + public LoginException (String message) + { + super (message); + } +} diff --git a/javax/security/auth/login/NullConfiguration.java b/javax/security/auth/login/NullConfiguration.java new file mode 100644 index 000000000..e1c99037f --- /dev/null +++ b/javax/security/auth/login/NullConfiguration.java @@ -0,0 +1,64 @@ +/* NullConfiguration.java -- no-op default login configuration. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.login; + +import javax.security.auth.AuthPermission; + +final class NullConfiguration extends Configuration +{ + + // Contructor. + // ------------------------------------------------------------------------- + + NullConfiguration() + { + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public AppConfigurationEntry[] getAppConfigurationEntry (String applicationName) + { + return null; + } + + public void refresh() + { + } +} diff --git a/javax/security/auth/x500/X500Principal.java b/javax/security/auth/x500/X500Principal.java index 6c7e79ee7..201a195cb 100644 --- a/javax/security/auth/x500/X500Principal.java +++ b/javax/security/auth/x500/X500Principal.java @@ -7,7 +7,7 @@ GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. - + GNU Classpath 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 @@ -38,16 +38,38 @@ exception statement from your version. */ package javax.security.auth.x500; -import gnu.java.security.x509.X500DistinguishedName; +import gnu.java.security.OID; +import gnu.java.security.der.BitString; +import gnu.java.security.der.DER; +import gnu.java.security.der.DEREncodingException; +import gnu.java.security.der.DERReader; +import gnu.java.security.der.DERValue; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.EOFException; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Reader; import java.io.Serializable; +import java.io.StringReader; + import java.security.Principal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + public final class X500Principal implements Principal, Serializable { private static final long serialVersionUID = -500463348111345721L; @@ -56,44 +78,66 @@ public final class X500Principal implements Principal, Serializable // ------------------------------------------------------------------------ public static final String CANONICAL = "CANONICAL"; - public static final String RFC1779 = "RFC1779"; - public static final String RFC2253 = "RFC2253"; - private transient X500DistinguishedName name; + private static final OID CN = new OID("2.5.4.3"); + private static final OID C = new OID("2.5.4.6"); + private static final OID L = new OID("2.5.4.7"); + private static final OID ST = new OID("2.5.4.8"); + private static final OID STREET = new OID("2.5.4.9"); + private static final OID O = new OID("2.5.4.10"); + private static final OID OU = new OID("2.5.4.11"); + private static final OID DC = new OID("0.9.2342.19200300.100.1.25"); + private static final OID UID = new OID("0.9.2342.19200300.100.1.1"); + + private transient List components; + private transient Map currentRdn; + private transient boolean fixed; + private transient byte[] encoded; // Constructors. // ------------------------------------------------------------------------ - public X500Principal(String name) + private X500Principal() { - if (name == null) - throw new NullPointerException(); - this.name = new X500DistinguishedName(name); + components = new LinkedList(); + currentRdn = new LinkedHashMap(); + components.add (currentRdn); } - public X500Principal(byte[] encoded) + public X500Principal (String name) { + this(); + if (name == null) + throw new NullPointerException(); try { - name = new X500DistinguishedName(encoded); + parseString (name); } catch (IOException ioe) { - throw new IllegalArgumentException(ioe.toString()); + IllegalArgumentException iae = new IllegalArgumentException("malformed name"); + iae.initCause (ioe); + throw iae; } } - public X500Principal(InputStream encoded) + public X500Principal (byte[] encoded) { + this(new ByteArrayInputStream (encoded)); + } + + public X500Principal (InputStream encoded) + { + this(); try { - name = new X500DistinguishedName(encoded); + parseDer (encoded); } catch (IOException ioe) { - throw new IllegalArgumentException(ioe.toString()); + throw new IllegalArgumentException (ioe.toString()); } } @@ -102,42 +146,389 @@ public final class X500Principal implements Principal, Serializable public boolean equals(Object o) { - return ((X500Principal) o).name.equals(name); + if (!(o instanceof X500Principal)) + return false; + if (size() != ((X500Principal) o).size()) + return false; + for (int i = 0; i < size(); i++) + { + Map m = (Map) components.get (i); + for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); ) + { + Map.Entry e = (Map.Entry) it2.next(); + OID oid = (OID) e.getKey(); + String v1 = (String) e.getValue(); + String v2 = ((X500Principal) o).getComponent (oid, i); + if (v2 == null) + return false; + if (!compressWS (v1).equalsIgnoreCase (compressWS (v2))) + return false; + } + } + return true; } public byte[] getEncoded() { - return name.getEncoded(); + if (encoded == null) + encodeDer(); + return (byte[]) encoded.clone(); } public String getName() { - return getName(RFC2253); + return getName (RFC2253); + } + + public String getName (final String format) + { + boolean rfc2253 = RFC2253.equalsIgnoreCase (format) || + CANONICAL.equalsIgnoreCase (format); + boolean rfc1779 = RFC1779.equalsIgnoreCase (format); + boolean canon = CANONICAL.equalsIgnoreCase (format); + if (! (rfc2253 || rfc1779 || canon)) + throw new IllegalArgumentException ("unsupported format " + format); + StringBuffer str = new StringBuffer(); + for (Iterator it = components.iterator(); it.hasNext(); ) + { + Map m = (Map) it.next(); + for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); ) + { + Map.Entry entry = (Map.Entry) it2.next(); + OID oid = (OID) entry.getKey(); + String value = (String) entry.getValue(); + if (oid.equals (CN)) + str.append ("CN"); + else if (oid.equals (C)) + str.append ("C"); + else if (oid.equals (L)) + str.append ("L"); + else if (oid.equals (ST)) + str.append ("ST"); + else if (oid.equals (STREET)) + str.append ("STREET"); + else if (oid.equals (O)) + str.append ("O"); + else if (oid.equals (OU)) + str.append ("OU"); + else if (oid.equals (DC) && rfc2253) + str.append ("DC"); + else if (oid.equals ("UID") && rfc2253) + str.append ("UID"); + else + str.append (oid.toString()); + str.append('='); + str.append(value); + if (it2.hasNext()) + str.append('+'); + } + if (it.hasNext()) + str.append(','); + } + if (canon) + return str.toString().toUpperCase (Locale.US).toLowerCase (Locale.US); + return str.toString(); } - public String getName(String format) + public String toString() { - if (format.equalsIgnoreCase(RFC2253)) - return name.toRFC2253(); - else if (format.equalsIgnoreCase(RFC1779)) - return name.toRFC1779(); - else if (format.equalsIgnoreCase(CANONICAL)) - return name.toCanonical(); - throw new IllegalArgumentException("unsupported format " + format); + return getName (RFC2253); } // Serialization methods. // ------------------------------------------------------------------------ - private void writeObject(ObjectOutputStream out) throws IOException + private void writeObject (ObjectOutputStream out) throws IOException { - out.writeObject(name.getEncoded()); + if (encoded != null) + encodeDer(); + out.writeObject (encoded); } - private void readObject(ObjectInputStream in) + private void readObject (ObjectInputStream in) throws IOException, NotActiveException, ClassNotFoundException { byte[] buf = (byte[]) in.readObject(); - name = new X500DistinguishedName(buf); + parseDer (new ByteArrayInputStream (buf)); + } + + // Own methods. + // ------------------------------------------------------------------------- + + private int size() + { + return components.size(); + } + + private String getComponent(OID oid, int rdn) + { + if (rdn >= size()) + return null; + return (String) ((Map) components.get (rdn)).get (oid); + } + + private void encodeDer() + { + ArrayList name = new ArrayList(components.size()); + for (Iterator it = components.iterator(); it.hasNext(); ) + { + Map m = (Map) it.next(); + if (m.isEmpty()) + continue; + Set rdn = new HashSet(); + for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); ) + { + Map.Entry e = (Map.Entry) it.next(); + ArrayList atav = new ArrayList(2); + atav.add(new DERValue(DER.OBJECT_IDENTIFIER, e.getKey())); + atav.add(new DERValue(DER.UTF8_STRING, e.getValue())); + rdn.add(new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, atav)); + } + name.add(new DERValue(DER.SET|DER.CONSTRUCTED, rdn)); + } + DERValue val = new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, name); + encoded = val.getEncoded(); + } + + private int sep; + + private void parseString(String str) throws IOException + { + Reader in = new StringReader(str); + while (true) + { + String key = readAttributeType(in); + if (key == null) + break; + String value = readAttributeValue(in); + putComponent(key, value); + if (sep == ',') + newRelativeDistinguishedName(); + } + } + + private String readAttributeType(Reader in) throws IOException + { + StringBuffer buf = new StringBuffer(); + int ch; + while ((ch = in.read()) != '=') + { + if (ch == -1) + { + if (buf.length() > 0) + throw new EOFException(); + return null; + } + if (ch > 127) + throw new IOException("Invalid char: " + (char) ch); + if (Character.isLetterOrDigit((char) ch) || ch == '-' || ch == '.') + buf.append((char) ch); + else + throw new IOException("Invalid char: " + (char) ch); + } + return buf.toString(); + } + + private String readAttributeValue(Reader in) throws IOException + { + StringBuffer buf = new StringBuffer(); + int ch = in.read(); + if (ch == '#') + { + while (true) + { + ch = in.read(); + if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') + || Character.isDigit((char) ch)) + buf.append((char) ch); + else if (ch == '+' || ch == ',') + { + sep = ch; + String hex = buf.toString(); + return new String(toByteArray(hex)); + } + else + throw new IOException("illegal character: " + (char) ch); + } + } + else if (ch == '"') + { + while (true) + { + ch = in.read(); + if (ch == '"') + break; + else if (ch == '\\') + { + ch = in.read(); + if (ch == -1) + throw new EOFException(); + if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') + || Character.isDigit((char) ch)) + { + int i = Character.digit((char) ch, 16) << 4; + ch = in.read(); + if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') + || Character.isDigit((char) ch))) + throw new IOException("illegal hex char"); + i |= Character.digit((char) ch, 16); + buf.append((char) i); + } + else + buf.append((char) ch); + } + else + buf.append((char) ch); + } + sep = in.read(); + if (sep != '+' || sep != ',') + throw new IOException("illegal character: " + (char) ch); + return buf.toString(); + } + else + { + while (true) + { + switch (ch) + { + case '+': + case ',': + sep = ch; + return buf.toString(); + case '\\': + ch = in.read(); + if (ch == -1) + throw new EOFException(); + if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') + || Character.isDigit((char) ch)) + { + int i = Character.digit((char) ch, 16) << 4; + ch = in.read(); + if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') + || Character.isDigit((char) ch))) + throw new IOException("illegal hex char"); + i |= Character.digit((char) ch, 16); + buf.append((char) i); + } + else + buf.append((char) ch); + break; + case '=': + case '<': + case '>': + case '#': + case ';': + throw new IOException("illegal character: " + (char) ch); + case -1: + throw new EOFException(); + default: + buf.append((char) ch); + } + } + } + } + + private void parseDer (InputStream encoded) throws IOException + { + DERReader der = new DERReader (encoded); + DERValue name = der.read(); + if (!name.isConstructed()) + throw new IOException ("malformed Name"); + this.encoded = name.getEncoded(); + int len = 0; + while (len < name.getLength()) + { + DERValue rdn = der.read(); + if (!rdn.isConstructed()) + throw new IOException ("badly formed RDNSequence"); + int len2 = 0; + while (len2 < rdn.getLength()) + { + DERValue atav = der.read(); + if (!atav.isConstructed()) + throw new IOException ("badly formed AttributeTypeAndValue"); + DERValue val = der.read(); + if (val.getTag() != DER.OBJECT_IDENTIFIER) + throw new IOException ("badly formed AttributeTypeAndValue"); + OID oid = (OID) val.getValue(); + val = der.read(); + if (!(val.getValue() instanceof String)) + throw new IOException ("badly formed AttributeTypeAndValue"); + String value = (String) val.getValue(); + putComponent(oid, value); + len2 += atav.getEncodedLength(); + } + len += rdn.getEncodedLength(); + if (len < name.getLength()) + newRelativeDistinguishedName(); + } + } + + private void newRelativeDistinguishedName() + { + currentRdn = new LinkedHashMap(); + components.add(currentRdn); + } + + private void putComponent(OID oid, String value) + { + currentRdn.put(oid, value); + } + + private void putComponent(String name, String value) + { + name = name.trim().toLowerCase(); + if (name.equals("cn")) + putComponent(CN, value); + else if (name.equals("c")) + putComponent(C, value); + else if (name.equals("l")) + putComponent(L, value); + else if (name.equals("street")) + putComponent(STREET, value); + else if (name.equals("st")) + putComponent(ST, value); + else if (name.equals("dc")) + putComponent(DC, value); + else if (name.equals("uid")) + putComponent(UID, value); + else + putComponent(new OID(name), value); + } + + private static String compressWS(String str) + { + StringBuffer buf = new StringBuffer(); + char lastChar = 0; + for (int i = 0; i < str.length(); i++) + { + char c = str.charAt(i); + if (Character.isWhitespace(c)) + { + if (!Character.isWhitespace(lastChar)) + buf.append(' '); + } + else + buf.append(c); + lastChar = c; + } + return buf.toString().trim(); + } + + private static byte[] toByteArray (String str) + { + int limit = str.length(); + byte[] result = new byte[((limit + 1) / 2)]; + int i = 0, j = 0; + if ((limit % 2) == 1) + { + result[j++] = (byte) Character.digit (str.charAt(i++), 16); + } + while (i < limit) + { + result[j ] = (byte) (Character.digit (str.charAt(i++), 16) << 4); + result[j++] |= (byte) Character.digit (str.charAt(i++), 16); + } + return result; } } diff --git a/javax/security/auth/x500/X500PrivateCredential.java b/javax/security/auth/x500/X500PrivateCredential.java new file mode 100644 index 000000000..fb3a5ef40 --- /dev/null +++ b/javax/security/auth/x500/X500PrivateCredential.java @@ -0,0 +1,148 @@ +/* X500PrivateCredential.java -- certificate and private key pair. + Copyright (C) 2003 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.auth.x500; + +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import javax.security.auth.Destroyable; + +/** + * A pairing of a {@link X509Certificate} and its corresponding {@link + * PrivateKey}, with an optional keystore alias. + */ +public final class X500PrivateCredential implements Destroyable +{ + + // Fields. + // ------------------------------------------------------------------------- + + private PrivateKey key; + private X509Certificate certificate; + private String alias; + + // Constructors. + // ------------------------------------------------------------------------- + + /** + * Creates a new private credential with no associated keystore alias. + * + * @param certificate The X.509 certificate. + * @param key The private key. + * @throws IllegalArgumentException If either parameter is null. + */ + public X500PrivateCredential (X509Certificate certificate, PrivateKey key) + { + if (certificate == null || key == null) + throw new IllegalArgumentException(); + this.certificate = certificate; + this.key = key; + } + + /** + * Creates a new private credential with a keystore alias. + * + * @param certificate The X.509 certificate. + * @param key The private key. + * @param alias The keystore alias for this credential. + * @throws IllegalArgumentException If any parameter is null. + */ + public X500PrivateCredential (X509Certificate certificate, PrivateKey key, + String alias) + { + this (certificate, key); + if (alias == null) + throw new IllegalArgumentException(); + this.alias = alias; + } + + // Instance methods. + // ------------------------------------------------------------------------- + + /** + * Returns the certificate of this credential. + * + * @return The certificate of this credential. + */ + public X509Certificate getCertificate() + { + return certificate; + } + + /** + * Returns the private key of this credential. + * + * @return The private key of this credential. + */ + public PrivateKey getPrivateKey() + { + return key; + } + + /** + * Returns the keystore alias of this credential, or null if not present. + * + * @return The keystore alias, or null. + */ + public String getAlias() + { + return alias; + } + + /** + * Destroy the sensitive data of this credential, setting the certificate, + * private key, and keystore alias to null. + */ + public void destroy() + { + certificate = null; + key = null; + alias = null; + } + + /** + * Tells whether or not this credential has been destroyed, and that + * the certificate and private key fields are null. + * + * @return True if this object has been destroyed. + */ + public boolean isDestroyed() + { + return certificate == null && key == null; + } +} diff --git a/javax/security/cert/Certificate.java b/javax/security/cert/Certificate.java new file mode 100644 index 000000000..8090817fc --- /dev/null +++ b/javax/security/cert/Certificate.java @@ -0,0 +1,176 @@ +/* Certificate.java -- base class of public-key certificates. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.SignatureException; + +import java.util.Arrays; +import java.util.zip.Adler32; + +/** + * <p>The base class for public-key certificates.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.Certificate} class. It should not be used in new + * applications.</b></p> + */ +public abstract class Certificate +{ + + // Constructors. + // ------------------------------------------------------------------------- + + public Certificate() + { + super(); + } + + // Instance methods. + // ------------------------------------------------------------------------- + + /** + * <p>Tests if this certificate equals another.</p> + * + * @param other The object to test. + * @return True if the certificates are equal. + */ + public boolean equals(Object other) + { + if (other == null || !(other instanceof Certificate)) + { + return false; + } + if (other == this) + { + return true; + } + try + { + return Arrays.equals(getEncoded(), ((Certificate) other).getEncoded()); + } + catch (CertificateEncodingException cee) + { + return false; + } + } + + /** + * <p>Computes a hash code for this certificate.</p> + * + * @return The hash code. + */ + public int hashCode() + { + try + { + Adler32 csum = new Adler32(); + csum.update(getEncoded()); + return (int) csum.getValue(); + } + catch (CertificateEncodingException cee) + { + return 0; + } + } + + // Abstract methods. + // ------------------------------------------------------------------------- + + /** + * <p>Return the encoded form of this certificate.</p> + * + * @return The encoded form. + * @throws CertificateEncodingException If the certificate could not be + * encoded. + */ + public abstract byte[] getEncoded() throws CertificateEncodingException; + + /** + * <p>Verifies the signature of this certificate.</p> + * + * @param key The signer's public key. + * @throws CertificateException + * @throws NoSuchAlgorithmException If the algorithm used to sign the + * certificate is not available. + * @throws InvalidKeyException If the supplied key is not appropriate for the + * certificate's signature algorithm. + * @throws NoSuchProviderException + * @throws SignatureException If the signature could not be verified. + */ + public abstract void verify(PublicKey key) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException; + + /** + * <p>Verifies the signature of this certificate, using the specified security + * provider.</p> + * + * @param key The signer's public key. + * @param sigProvider The name of the signature provider. + * @throws CertificateException + * @throws NoSuchAlgorithmException If the algorithm used to sign the + * certificate is not available. + * @throws InvalidKeyException If the supplied key is not appropriate for the + * certificate's signature algorithm. + * @throws NoSuchProviderException If <i>sigProvider</i> is not the name of an + * installed provider. + * @throws SignatureException If the signature could not be verified. + */ + public abstract void verify(PublicKey key, String sigProvider) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException; + + /** + * <p>Returns a printable representation of this certificate.</p> + * + * @return The string. + */ + public abstract String toString(); + + /** + * <p>Returns this certificate's public key.</p> + * + * @return The public key. + */ + public abstract PublicKey getPublicKey(); +} diff --git a/javax/security/cert/CertificateEncodingException.java b/javax/security/cert/CertificateEncodingException.java new file mode 100644 index 000000000..81c85dd9f --- /dev/null +++ b/javax/security/cert/CertificateEncodingException.java @@ -0,0 +1,60 @@ +/* CertificateEncodingException.java -- certificate encoding exception. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +/** + * <p>Signals a problem when encoding certificates.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.CertificateEncodingException} class. It should not be used + * in new applications.</b></p> + */ +public class CertificateEncodingException extends CertificateException +{ + + public CertificateEncodingException() + { + super(); + } + + public CertificateEncodingException(String msg) + { + super(msg); + } +} diff --git a/javax/security/cert/CertificateException.java b/javax/security/cert/CertificateException.java new file mode 100644 index 000000000..4e79a3120 --- /dev/null +++ b/javax/security/cert/CertificateException.java @@ -0,0 +1,60 @@ +/* CertificateException.java -- certificate exception. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +/** + * <p>Signals a generic problem with certificates.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.CertificateException} class. It should not be used in new + * applications.</b></p> + */ +public class CertificateException extends Exception +{ + + public CertificateException() + { + super(); + } + + public CertificateException(String msg) + { + super(msg); + } +} diff --git a/javax/security/cert/CertificateExpiredException.java b/javax/security/cert/CertificateExpiredException.java new file mode 100644 index 000000000..53b0cc007 --- /dev/null +++ b/javax/security/cert/CertificateExpiredException.java @@ -0,0 +1,60 @@ +/* CertificateExpiredException.java -- certificate expired exception. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +/** + * <p>Signals that a certificate has expired.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.CertificateExpiredException} class. It should not be used + * in new applications.</b></p> + */ +public class CertificateExpiredException extends CertificateException +{ + + public CertificateExpiredException() + { + super(); + } + + public CertificateExpiredException(String msg) + { + super(msg); + } +} diff --git a/javax/security/cert/CertificateNotYetValidException.java b/javax/security/cert/CertificateNotYetValidException.java new file mode 100644 index 000000000..56c8aeb7f --- /dev/null +++ b/javax/security/cert/CertificateNotYetValidException.java @@ -0,0 +1,60 @@ +/* CertificateNotYetValidException.java -- certificate not yet valid exception. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +/** + * <p>Signals that a certificate is not yet valid.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.CertificateNotYetValidException} class. It should not be + * used in new applications.</b></p> + */ +public class CertificateNotYetValidException extends CertificateException +{ + + public CertificateNotYetValidException() + { + super(); + } + + public CertificateNotYetValidException(String msg) + { + super(msg); + } +} diff --git a/javax/security/cert/CertificateParsingException.java b/javax/security/cert/CertificateParsingException.java new file mode 100644 index 000000000..17012e2f1 --- /dev/null +++ b/javax/security/cert/CertificateParsingException.java @@ -0,0 +1,59 @@ +/* CertificateParsingException.java -- certificate parsing exception. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +/** + * <p>Signals a parsing error when decoding a certificate.</p> + * + * <p><b>This class is deprecated. It should not be used in new + * applications.</b></p> + */ +public class CertificateParsingException extends CertificateException +{ + + public CertificateParsingException() + { + super(); + } + + public CertificateParsingException(String msg) + { + super(msg); + } +} diff --git a/javax/security/cert/X509CertBridge.java b/javax/security/cert/X509CertBridge.java new file mode 100644 index 000000000..1c075d6d5 --- /dev/null +++ b/javax/security/cert/X509CertBridge.java @@ -0,0 +1,203 @@ +/* X509CertBridge.java -- bridge between JDK and JSSE cert APIs. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +import java.math.BigInteger; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.Principal; +import java.security.SignatureException; + +import java.util.Date; + +/** + * <p>An implementation of the {@link X509Certificate} class that delegates + * calls to a {@link java.security.cert.X509Certificate}.</p> + */ +final class X509CertBridge extends X509Certificate +{ + + // Fields. + // ------------------------------------------------------------------------- + + private java.security.cert.X509Certificate cert; + + // Constructor. + // ------------------------------------------------------------------------- + + X509CertBridge(java.security.cert.X509Certificate cert) + { + this.cert = cert; + } + + // Instance methods. + // ------------------------------------------------------------------------- + + public byte[] getEncoded() throws CertificateEncodingException + { + try + { + return cert.getEncoded(); + } + catch (java.security.cert.CertificateEncodingException cee) + { + throw new CertificateEncodingException(cee.getMessage()); + } + } + + public void verify(PublicKey key) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException + { + try + { + cert.verify(key); + } + catch (java.security.cert.CertificateException ce) + { + throw new CertificateException(ce.getMessage()); + } + } + + public void verify(PublicKey key, String sigProvider) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException + { + try + { + cert.verify(key, sigProvider); + } + catch (java.security.cert.CertificateException ce) + { + throw new CertificateException(ce.getMessage()); + } + } + + public String toString() + { + return cert.toString(); + } + + public PublicKey getPublicKey() + { + return cert.getPublicKey(); + } + + public void checkValidity() + throws CertificateExpiredException, CertificateNotYetValidException + { + try + { + cert.checkValidity(); + } + catch (java.security.cert.CertificateExpiredException cee) + { + throw new CertificateExpiredException(cee.getMessage()); + } + catch (java.security.cert.CertificateNotYetValidException cnyve) + { + throw new CertificateNotYetValidException(cnyve.getMessage()); + } + } + + public void checkValidity(Date date) + throws CertificateExpiredException, CertificateNotYetValidException + { + try + { + cert.checkValidity(date); + } + catch (java.security.cert.CertificateExpiredException cee) + { + throw new CertificateExpiredException(cee.getMessage()); + } + catch (java.security.cert.CertificateNotYetValidException cnyve) + { + throw new CertificateNotYetValidException(cnyve.getMessage()); + } + } + + public int getVersion() + { + return cert.getVersion(); + } + + public BigInteger getSerialNumber() + { + return cert.getSerialNumber(); + } + + public Principal getIssuerDN() + { + return cert.getIssuerDN(); + } + + public Principal getSubjectDN() + { + return cert.getSubjectDN(); + } + + public Date getNotBefore() + { + return cert.getNotBefore(); + } + + public Date getNotAfter() + { + return cert.getNotAfter(); + } + + public String getSigAlgName() + { + return cert.getSigAlgName(); + } + + public String getSigAlgOID() + { + return cert.getSigAlgOID(); + } + + public byte[] getSigAlgParams() + { + return cert.getSigAlgParams(); + } +} diff --git a/javax/security/cert/X509Certificate.java b/javax/security/cert/X509Certificate.java new file mode 100644 index 000000000..2bf0b4e94 --- /dev/null +++ b/javax/security/cert/X509Certificate.java @@ -0,0 +1,191 @@ +/* X509Certificate.java -- base class of X.509 certificates. + Copyright (C) 2004 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.cert; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.IOException; + +import java.math.BigInteger; + +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.cert.CertificateFactory; + +import java.util.Date; + +/** + * <p>The base class of all X.509 certificates.</p> + * + * <p><b>This class is deprecated in favor of the {@link + * java.security.cert.X509Certificate} class. It should not be used in new + * applications.</b></p> + */ +public abstract class X509Certificate extends Certificate +{ + + // Class methods. + // ------------------------------------------------------------------------- + + /** + * <p>Get an instance of X509Certificate for the given encoded bytes.</p> + * + * @param encoded The encoded certificate. + * @return An instance of X509Certificate. + * @throws CertificateException If the encoded certificate cannot be parsed. + */ + public static X509Certificate getInstance(byte[] encoded) + throws CertificateException + { + return getInstance(new ByteArrayInputStream(encoded)); + } + + /** + * <p>Get an instance of X509Certificate for the given encoded stream.</p> + * + * @param encoded The encoded certificate stream.. + * @return An instance of X509Certificate. + * @throws CertificateException If the encoded certificate cannot be parsed. + */ + public static X509Certificate getInstance(InputStream encoded) + throws CertificateException + { + try + { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return new X509CertBridge((java.security.cert.X509Certificate) + cf.generateCertificate(encoded)); + } + catch (java.security.cert.CertificateException ce) + { + throw new CertificateException(ce.getMessage()); + } + } + + // Abstract methods. + // ------------------------------------------------------------------------- + + /** + * <p>Check if this certificate is valid now.</p> + * + * @throws CertificateExpiredException If the certificate has expired. + * @throws CertificateNotYetValidException If the certificate is not yet valid. + * @see #checkValidity(java.util.Date) + */ + public abstract void checkValidity() + throws CertificateExpiredException, CertificateNotYetValidException; + + /** + * <p>Check if this certificate is valid for the given date.</p> + * + * @param date The date to check. + * @throws CertificateExpiredException If the certificate has expired. + * @throws CertificateNotYetValidException If the certificate is not yet valid. + */ + public abstract void checkValidity(Date date) + throws CertificateExpiredException, CertificateNotYetValidException; + + /** + * <p>Returns the X.509 version number.</p> + * + * @return The version number. + */ + public abstract int getVersion(); + + /** + * <p>Returns this certificate's serial number.</p> + * + * @return The serial number. + */ + public abstract BigInteger getSerialNumber(); + + /** + * <p>Returns the distinguished name of this certificate's issuer.</p> + * + * @return The issuer's distinguished name. + */ + public abstract Principal getIssuerDN(); + + /** + * <p>Returns the distinguished name of this certificate's subject.</p> + * + * @return The subject's distinguished name. + */ + public abstract Principal getSubjectDN(); + + /** + * <p>Returns the <i>not before</i> portion of this certificate's validity + * period.</p> + * + * @return The not before date. + */ + public abstract Date getNotBefore(); + + /** + * <p>Returns the <i>not after</i> portion of this certificate's validity + * period.</p> + * + * @return The not after date. + */ + public abstract Date getNotAfter(); + + /** + * <p>Returns the name of this certificate's signature algorithm.</p> + * + * @return The name of the signature algorithm. + */ + public abstract String getSigAlgName(); + + /** + * <p>Returns the object identifier (OID) of this certificate's signature + * algorithm. The returned string is a sequence of integers separated by + * periods.</p> + * + * @return The signature OID. + */ + public abstract String getSigAlgOID(); + + /** + * <p>Returns the signature parameters. The returned byte array contains the + * raw DER-encoded parameters.</p> + * + * @return The signature parameters. + */ + public abstract byte[] getSigAlgParams(); +} diff --git a/javax/security/sasl/AuthenticationException.java b/javax/security/sasl/AuthenticationException.java new file mode 100644 index 000000000..1af2eb30a --- /dev/null +++ b/javax/security/sasl/AuthenticationException.java @@ -0,0 +1,105 @@ +/* AuthenticationException.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpathis free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpathis 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +/** + * <p>This exception is thrown by a SASL mechanism implementation to indicate + * that the SASL exchange has failed due to reasons related to authentication, + * such as an invalid identity, passphrase, or key.</p> + * + * <p>Note that the lack of an <code>AuthenticationException</code> does not + * mean that the failure was not due to an authentication error. A SASL + * mechanism implementation might throw the more general {@link SaslException} + * instead of <code>AuthenticationException</code> if it is unable to determine + * the nature of the failure, or if does not want to disclose the nature of the + * failure, for example, due to security reasons.</p> + */ +public class AuthenticationException extends SaslException +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Constructs a new instance of <code>AuthenticationException</code>. The + * root exception and the detailed message are <code>null</code>. + */ + public AuthenticationException() + { + super(); + } + + /** + * Constructs a new instance of <code>AuthenticationException</code> with a + * detailed message. The root exception is <code>null</code>. + * + * @param detail a possibly <code>null</code> string containing details of + * the exception. + * @see Throwable#getMessage() + */ + public AuthenticationException(String detail) + { + super(detail); + } + + /** + * Constructs a new instance of <code>AuthenticationException</code> with a + * detailed message and a root exception. + * + * @param detail a possibly <code>null</code> string containing details of + * the exception. + * @param ex a possibly <code>null</code> root exception that caused this + * exception. + * @see Throwable#getMessage() + * @see SaslException#getCause() + */ + public AuthenticationException(String detail, Throwable ex) + { + super(detail, ex); + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- +} diff --git a/javax/security/sasl/AuthorizeCallback.java b/javax/security/sasl/AuthorizeCallback.java new file mode 100644 index 000000000..77fe78698 --- /dev/null +++ b/javax/security/sasl/AuthorizeCallback.java @@ -0,0 +1,171 @@ +/* AuthorizeCallback.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpathis free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpathis 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import javax.security.auth.callback.Callback; + +/** + * This callback is used by {@link SaslServer} to determine whether one entity + * (identified by an authenticated authentication ID) can act on behalf of + * another entity (identified by an authorization ID). + */ +public class AuthorizeCallback implements Callback +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** @serial The (authenticated) authentication id to check. */ + private String authenticationID = null; + + /** @serial The authorization id to check. */ + private String authorizationID = null; + + /** + * @serial The id of the authorized entity. If null, the id of the authorized + * entity is authorizationID. + */ + private String authorizedID = null; + + /** + * @serial A flag indicating whether the authentication id is allowed to act + * on behalf of the authorization id. + */ + private boolean authorized = false; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Constructs an instance of <code>AuthorizeCallback</code>. + * + * @param authnID the (authenticated) authentication ID. + * @param authzID the authorization ID. + */ + public AuthorizeCallback(String authnID, String authzID) + { + super(); + + this.authenticationID = authnID; + this.authorizationID = authzID; + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Returns the authentication ID to check. + * + * @return the authentication ID to check + */ + public String getAuthenticationID() + { + return authenticationID; + } + + /** + * Returns the authorization ID to check. + * + * @return the authorization ID to check. + */ + public String getAuthorizationID() + { + return authorizationID; + } + + /** + * Determines if the identity represented by authentication ID is allowed to + * act on behalf of the authorization ID. + * + * @return <code>true</code> if authorization is allowed; <code>false</code> + * otherwise. + * @see #setAuthorized(boolean) + * @see #getAuthorizedID() + */ + public boolean isAuthorized() + { + return authorized; + } + + /** + * Sets if authorization is allowed or not. + * + * @param authorized <code>true</code> if authorization is allowed; + * <code>false</code> otherwise. + * @see #isAuthorized() + * @see #setAuthorizedID(String) + */ + public void setAuthorized(boolean authorized) + { + this.authorized = authorized; + } + + /** + * Returns the ID of the authorized user. + * + * @return the ID of the authorized user. <code>null</code> means the + * authorization failed. + * @see #setAuthorized(boolean) + * @see #setAuthorizedID(String) + */ + public String getAuthorizedID() + { + if (!authorized) + { + return null; + } + return (authorizedID != null ? authorizedID : authorizationID); + } + + /** + * Sets the ID of the authorized entity. Called by handler only when the ID + * is different from {@link #getAuthorizationID()}. For example, the ID might + * need to be canonicalized for the environment in which it will be used. + * + * @see #setAuthorized(boolean) + * @see #getAuthorizedID() + */ + public void setAuthorizedID(String id) + { + this.authorizedID = id; + } +} diff --git a/javax/security/sasl/RealmCallback.java b/javax/security/sasl/RealmCallback.java new file mode 100644 index 000000000..49bc08ae2 --- /dev/null +++ b/javax/security/sasl/RealmCallback.java @@ -0,0 +1,75 @@ +/* RealmCallback.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import javax.security.auth.callback.TextInputCallback; + +/** + * This callback is used by {@link SaslClient} and {@link SaslServer} to + * retrieve realm information. + */ +public class RealmCallback extends TextInputCallback +{ + + /** + * Constructs a <code>RealmCallback</code> with a prompt. + * + * @param prompt the non-null prompt to use to request the realm information. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or empty. + */ + public RealmCallback(String prompt) + { + super(prompt); + } + + /** + * Constructs a <code>RealmCallback</code> with a prompt and default realm + * information. + * + * @param prompt the non-null prompt to use to request the realm information. + * @param defaultRealmInfo the non-null default realm information to use. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or empty, or if <code>defaultRealm</code> is empty or <code>null</code>. + */ + public RealmCallback(String prompt, String defaultRealmInfo) + { + super(prompt, defaultRealmInfo); + } +} diff --git a/javax/security/sasl/RealmChoiceCallback.java b/javax/security/sasl/RealmChoiceCallback.java new file mode 100644 index 000000000..2e0040761 --- /dev/null +++ b/javax/security/sasl/RealmChoiceCallback.java @@ -0,0 +1,71 @@ +/* RealmChoiceCallback.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import javax.security.auth.callback.ChoiceCallback; + +/** + * This callback is used by {@link SaslClient} and {@link SaslServer} to obtain + * a realm given a list of realm choices. + */ +public class RealmChoiceCallback extends ChoiceCallback +{ + + /** + * Constructs a <code>RealmChoiceCallback</code> with a prompt, a list of + * choices and a default choice. + * + * @param prompt the non-null prompt to use to request the realm. + * @param choices the non-null list of realms to choose from. + * @param defaultChoice the choice to be used as the default when the list of + * choices is displayed. It is an index into the <code>choices</code> array. + * @param multiple <code>true</code> if multiple choices allowed; + * <code>false</code> otherwise. + * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code> + * or empty, if <code>choices</code> has a length of <code>0</code>, if any + * element from <code>choices</code> is <code>null</code> or empty, or if + * <code>defaultChoice</code> does not fall within the array boundary of + * <code>choices</code>. + */ + public RealmChoiceCallback(String prompt, String[] choices, int defaultChoice, + boolean multiple) + { + super(prompt, choices, defaultChoice, multiple); + } +} diff --git a/javax/security/sasl/Sasl.java b/javax/security/sasl/Sasl.java new file mode 100644 index 000000000..2174692f4 --- /dev/null +++ b/javax/security/sasl/Sasl.java @@ -0,0 +1,691 @@ +/* Sasl.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Vector; +import java.security.Security; +import java.security.Provider; + +import javax.security.auth.callback.CallbackHandler; + +/** + * <p>A static class for creating SASL clients and servers.</p> + * + * <p>This class defines the policy of how to locate, load, and instantiate SASL + * clients and servers.</p> + * + * <p>For example, an application or library gets a SASL client instance by + * doing something like:</p> + * + * <pre> + *SaslClient sc = + * Sasl.createSaslClient(mechanisms, authorizationID, protocol, + * serverName, props, callbackHandler); + * </pre> + * + * <p>It can then proceed to use the instance to create an authenticated + * connection.</p> + * + * <p>Similarly, a server gets a SASL server instance by using code that looks + * as follows:</p> + * + * <pre> + *SaslServer ss = + * Sasl.createSaslServer(mechanism, protocol, serverName, props, + * callbackHandler); + * </pre> + */ +public class Sasl +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * <p>The name of a property that specifies the quality-of-protection to use. + * The property contains a comma-separated, ordered list of quality-of- + * protection values that the client or server is willing to support. A qop + * value is one of:</p> + * + * <ul> + * <li><code>"auth"</code> - authentication only,</li> + * <li><code>"auth-int"</code> - authentication plus integrity + * protection,</li> + * <li><code>"auth-conf"</code> - authentication plus integrity and + * confidentiality protection.</li> + * </ul> + * + * <p>The order of the list specifies the preference order of the client or + * server.</p> + * + * <p>If this property is absent, the default qop is <code>"auth"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.qop"</code>.</p> + */ + public static final String QOP = "javax.security.sasl.qop"; + + /** + * <p>The name of a property that specifies the cipher strength to use. The + * property contains a comma-separated, ordered list of cipher strength + * values that the client or server is willing to support. A strength value + * is one of:</p> + * + * <ul> + * <li><code>"low"</code>,</li> + * <li><code>"medium"</code>,</li> + * <li><code>"high"</code>.</li> + * </ul> + * + * <p>The order of the list specifies the preference order of the client or + * server. An implementation should allow configuration of the meaning of + * these values. An application may use the Java Cryptography Extension (JCE) + * with JCE-aware mechanisms to control the selection of cipher suites that + * match the strength values.</p> + * + * <p>If this property is absent, the default strength is + * <code>"high,medium,low"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.strength"</code>. + * </p> + */ + public static final String STRENGTH = "javax.security.sasl.strength"; + + /** + * <p>The name of a property that specifies whether the server must authenticate + * to the client. The property contains <code>"true"</code> if the server + * must authenticate the to client; <code>"false"</code> otherwise. The + * default is <code>"false"</code>.</p> + * + * <p>The value of this constant is + * <code>"javax.security.sasl.server.authentication"</code>.</p> + */ + public static final String SERVER_AUTH = "javax.security.sasl.server.authentication"; + + /** + * <p>The name of a property that specifies the maximum size of the receive + * buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property + * contains the string representation of an integer.</p> + * + * <p>If this property is absent, the default size is defined by the + * mechanism.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.maxbuffer"</code>. + * </p> + */ + public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer"; + + /** + * <p>The name of a property that specifies the maximum size of the raw send + * buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property + * contains the string representation of an integer. The value of this + * property is negotiated between the client and server during the + * authentication exchange.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.rawsendsize"</code>. + * </p> + */ + public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize"; + + /** + * <p>The name of a property that specifies whether mechanisms susceptible + * to simple plain passive attacks (e.g., "PLAIN") are not permitted. The + * property contains <code>"true"</code> if such mechanisms are not + * permitted; <code>"false"</code> if such mechanisms are permitted. The + * default is <code>"false"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.noplaintext"</code>. + * </p> + */ + public static final String POLICY_NOPLAINTEXT = "javax.security.sasl.policy.noplaintext"; + + /** + * <p>The name of a property that specifies whether mechanisms susceptible to + * active (non-dictionary) attacks are not permitted. The property contains + * <code>"true"</code> if mechanisms susceptible to active attacks are not + * permitted; <code>"false"</code> if such mechanisms are permitted. The + * default is <code>"false"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.noactive"</code>. + * </p> + */ + public static final String POLICY_NOACTIVE = "javax.security.sasl.policy.noactive"; + + /** + * <p>The name of a property that specifies whether mechanisms susceptible to + * passive dictionary attacks are not permitted. The property contains + * <code>"true"</code> if mechanisms susceptible to dictionary attacks are + * not permitted; <code>"false"</code> if such mechanisms are permitted. The + * default is <code>"false"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.nodictionary"</code>. + * </p> + */ + public static final String POLICY_NODICTIONARY = "javax.security.sasl.policy.nodictionary"; + + /** + * <p>The name of a property that specifies whether mechanisms that accept + * anonymous login are not permitted. The property contains <code>"true"</code> + * if mechanisms that accept anonymous login are not permitted; <code>"false" + * </code> if such mechanisms are permitted. The default is <code>"false"</code>. + * </p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.noanonymous"</code>. + * </p> + */ + public static final String POLICY_NOANONYMOUS = "javax.security.sasl.policy.noanonymous"; + + /** + * The name of a property that specifies whether mechanisms that implement + * forward secrecy between sessions are required. Forward secrecy means that + * breaking into one session will not automatically provide information for + * breaking into future sessions. The property contains <code>"true"</code> + * if mechanisms that implement forward secrecy between sessions are + * required; <code>"false"</code> if such mechanisms are not required. The + * default is <code>"false"</code>.</p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.forward"</code>. + * </p> + */ + public static final String POLICY_FORWARD_SECRECY = "javax.security.sasl.policy.forward"; + + /** + * The name of a property that specifies whether mechanisms that pass client + * credentials are required. The property contains <code>"true"</code> if + * mechanisms that pass client credentials are required; <code>"false"</code> + * if such mechanisms are not required. The default is <code>"false"</code>. + * </p> + * + * <p>The value of this constant is <code>"javax.security.sasl.policy.credentials"</code>. + * </p> + */ + public static final String POLICY_PASS_CREDENTIALS = "javax.security.sasl.policy.credentials"; + + /** + * <p>The name of a property that specifies whether to reuse previously + * authenticated session information. The property contains <code>"true"</code> + * if the mechanism implementation may attempt to reuse previously + * authenticated session information; it contains <code>"false"</code> if the + * implementation must not reuse previously authenticated session information. + * A setting of <code>"true"</code> serves only as a hint; it does not + * necessarily entail actual reuse because reuse might not be possible due to + * a number of reasons, including, but not limited to, lack of mechanism + * support for reuse, expiration of reusable information, and the peer's + * refusal to support reuse. The property's default value is <code>"false"</code>. + * </p> + * + * <p>The value of this constant is <code>"javax.security.sasl.reuse"</code>. + * Note that all other parameters and properties required to create a SASL + * client/server instance must be provided regardless of whether this + * property has been supplied. That is, you cannot supply any less + * information in anticipation of reuse. Mechanism implementations that + * support reuse might allow customization of its implementation for factors + * such as cache size, timeouts, and criteria for reuseability. Such + * customizations are implementation-dependent.</p> + */ + public static final String REUSE = "javax.security.sasl.reuse"; + + private static final String CLIENT_FACTORY_SVC = "SaslClientFactory."; + private static final String SERVER_FACTORY_SVC = "SaslServerFactory."; + private static final String ALIAS = "Alg.Alias."; + + // Constructor(s) + // ------------------------------------------------------------------------- + + private Sasl() + { + super(); + } + + // Class methods + // ------------------------------------------------------------------------- + + /** + * <p>Creates a {@link SaslClient} for the specified mechanism.</p> + * + * <p>This method uses the JCA Security Provider Framework, described in the + * "Java Cryptography Architecture API Specification & Reference", for + * locating and selecting a {@link SaslClient} implementation.</p> + * + * <p>First, it obtains an ordered list of {@link SaslClientFactory} + * instances from the registered security providers for the + * <code>"SaslClientFactory"</code> service and the specified mechanism. It + * then invokes <code>createSaslClient()</code> on each factory instance on + * the list until one produces a non-null {@link SaslClient} instance. It + * returns the non-null {@link SaslClient} instance, or <code>null</code> if + * the search fails to produce a non-null {@link SaslClient} instance.</p> + * + * <p>A security provider for <code>SaslClientFactory</code> registers with + * the JCA Security Provider Framework keys of the form:</p> + * + * <pre> + * SaslClientFactory.mechanism_name + * </pre> + * + * <p>and values that are class names of implementations of {@link + * SaslClientFactory}.</p> + * + * <p>For example, a provider that contains a factory class, + * <code>com.wiz.sasl.digest.ClientFactory</code>, that supports the + * <code>"DIGEST-MD5"</code> mechanism would register the following entry + * with the JCA:</p> + * + * <pre> + * SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory + * </pre> + * + * <p>See the "Java Cryptography Architecture API Specification & + * Reference" for information about how to install and configure security + * service providers.</p> + * + * @param mechanisms the non-null list of mechanism names to try. Each is the + * IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5"). + * @param authorizationID the possibly <code>null</code> protocol-dependent + * identification to be used for authorization. If <code>null</code> or + * empty, the server derives an authorization ID from the client's + * authentication credentials. When the SASL authentication completes + * successfully, the specified entity is granted access. + * @param protocol the non-null string name of the protocol for which the + * authentication is being performed (e.g. "ldap"). + * @param serverName the non-null fully-qualified host name of the server to + * authenticate to. + * @param props the possibly null set of properties used to select the SASL + * mechanism and to configure the authentication exchange of the selected + * mechanism. For example, if props contains the {@link Sasl#POLICY_NOPLAINTEXT} + * property with the value <code>"true"</code>, then the selected SASL + * mechanism must not be susceptible to simple plain passive attacks. In + * addition to the standard properties declared in this class, other, + * possibly mechanism-specific, properties can be included. Properties not + * relevant to the selected mechanism are ignored. + * @param cbh the possibly <code>null</code> callback handler to used by the + * SASL mechanisms to get further information from the application/library to + * complete the authentication. For example, a SASL mechanism might require + * the authentication ID, password and realm from the caller. The + * authentication ID is requested by using a + * {@link javax.security.auth.callback.NameCallback}. The password is + * requested by using a {@link javax.security.auth.callback.PasswordCallback}. + * The realm is requested by using a {@link RealmChoiceCallback} if there is + * a list of realms to choose from, and by using a {@link RealmCallback} if + * the realm must be entered. + * @return a possibly <code>null</code> {@link SaslClient} created using the + * parameters supplied. If <code>null</code>, the method could not find a + * {@link SaslClientFactory} that will produce one. + * @throws SaslException if a {@link SaslClient} cannot be created because + * of an error. + */ + public static SaslClient createSaslClient(String[] mechanisms, + String authorizationID, + String protocol, + String serverName, Map props, + CallbackHandler cbh) + throws SaslException + { + if (mechanisms == null) + { + return null; + } + Provider[] providers = Security.getProviders(); + if (providers == null || providers.length == 0) + { + return null; + } + + SaslClient result = null; + SaslClientFactory factory = null; + String m, clazz = null, upper, alias; + int j; + Provider p; + for (int i = 0; i < mechanisms.length; i++) + { + m = mechanisms[i]; + if (m == null) + continue; + for (j = 0; j < providers.length; j++) + { + p = providers[j]; + if (p != null) + { + // try the name as is + clazz = p.getProperty(CLIENT_FACTORY_SVC + m); + if (clazz == null) // try all uppercase + { + upper = m.toUpperCase(); + clazz = p.getProperty(CLIENT_FACTORY_SVC + upper); + if (clazz == null) // try if it's an alias + { + alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + m); + if (alias == null) // try all-uppercase alias name + { + alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + upper); + if (alias == null) // spit the dummy + continue; + } + clazz = p.getProperty(CLIENT_FACTORY_SVC + alias); + } + } + if (clazz == null) + continue; + else + clazz = clazz.trim(); + } + + try + { + result = null; + factory = (SaslClientFactory) Class.forName(clazz).newInstance(); + result = factory.createSaslClient(mechanisms, authorizationID, + protocol, serverName, props, cbh); + } + catch (ClassCastException ignored) // ignore instantiation exceptions + { + } + catch (ClassNotFoundException ignored) + { + } + catch (InstantiationException ignored) + { + } + catch (IllegalAccessException ignored) + { + } + if (result != null) + return result; + } + } + return null; + } + + /** + * Gets an enumeration of known factories for producing a {@link SaslClient} + * instance. This method uses the same sources for locating factories as + * <code>createSaslClient()</code>. + * + * @return a non-null {@link Enumeration} of known factories for producing a + * {@link SaslClient} instance. + * @see #createSaslClient(String[],String,String,String,Map,CallbackHandler) + */ + public static Enumeration getSaslClientFactories() + { + Vector result = new Vector(); + HashSet names = new HashSet(); + Provider[] providers = Security.getProviders(); + Iterator it; + if (providers == null) + { + Provider p; + String key; + for (int i = 0; i < providers.length; i++) + { + p = providers[i]; + for (it = p.keySet().iterator(); it.hasNext(); ) + { + key = (String) it.next(); + // add key's binding (a) it is a class of a client factory, + // and (b) the key does not include blanks + if (key.startsWith(CLIENT_FACTORY_SVC) && key.indexOf(" ") == -1) + { + names.add(p.getProperty(key)); + break; + } + } + } + } + // we have the factory class names in names; instantiate and enumerate + String c; + for (it = names.iterator(); it.hasNext(); ) + { + c = (String) it.next(); + try + { + SaslClientFactory f = (SaslClientFactory) Class.forName(c).newInstance(); + if (f != null) + result.add(f); + } catch (ClassCastException ignored) { // ignore instantiation exceptions + } catch (ClassNotFoundException ignored) { + } catch (InstantiationException ignored) { + } catch (IllegalAccessException ignored) { + } + } + + return result.elements(); + } + + /** + * <p>Creates a {@link SaslServer} for the specified mechanism.</p> + * + * <p>This method uses the JCA Security Provider Framework, described in the + * "Java Cryptography Architecture API Specification & Reference", for + * locating and selecting a SaslServer implementation.</p> + * + * <p>First, it obtains an ordered list of {@link SaslServerFactory} + * instances from the registered security providers for the + * <code>"SaslServerFactory"</code> service and the specified mechanism. It + * then invokes <code>createSaslServer()</code> on each factory instance on + * the list until one produces a non-null {@link SaslServer} instance. It + * returns the non-null {@link SaslServer} instance, or <code>null</code> if + * the search fails to produce a non-null {@link SaslServer} instance.</p> + * + * <p>A security provider for {@link SaslServerFactory} registers with the + * JCA Security Provider Framework keys of the form:</p> + * + * <pre> + * SaslServerFactory.mechanism_name + * </pre> + * + * <p>and values that are class names of implementations of {@link + * SaslServerFactory}.</p> + * + * <p>For example, a provider that contains a factory class, + * <code>com.wiz.sasl.digest.ServerFactory</code>, that supports the + * <code>"DIGEST-MD5"</code> mechanism would register the following entry + * with the JCA:</p> + * + * <pre> + * SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory + * </pre></p> + * + * <p>See the "Java Cryptography Architecture API Specification & + * Reference" for information about how to install and configure security + * service providers.</p> + * + * @param mechanism the non-null mechanism name. It must be an + * IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5"). + * @param protocol the non-null string name of the protocol for which the + * authentication is being performed (e.g. "ldap"). + * @param serverName the non-null fully qualified host name of the server. + * @param props the possibly <code>null</code> set of properties used to + * select the SASL mechanism and to configure the authentication exchange of + * the selected mechanism. For example, if props contains the {@link + * Sasl#POLICY_NOPLAINTEXT} property with the value <code>"true"</code>, then + * the selected SASL mechanism must not be susceptible to simple plain + * passive attacks. In addition to the standard properties declared in this + * class, other, possibly mechanism-specific, properties can be included. + * Properties not relevant to the selected mechanism are ignored. + * @param cbh the possibly <code>null</code> callback handler to used by the + * SASL mechanisms to get further information from the application/library to + * complete the authentication. For example, a SASL mechanism might require + * the authentication ID, password and realm from the caller. The + * authentication ID is requested by using a + * {@link javax.security.auth.callback.NameCallback}. The password is + * requested by using a {@link javax.security.auth.callback.PasswordCallback}. + * The realm is requested by using a {@link RealmChoiceCallback} if there is + * a list of realms to choose from, and by using a {@link RealmCallback} if + * the realm must be entered. + * @return a possibly <code>null</code> {@link SaslServer} created using the + * parameters supplied. If <code>null</code>, the method cannot find a + * {@link SaslServerFactory} instance that will produce one. + * @throws SaslException if a {@link SaslServer} instance cannot be created + * because of an error. + */ + public static SaslServer createSaslServer(String mechanism, String protocol, + String serverName, + Map props, CallbackHandler cbh) + throws SaslException + { + if (mechanism == null) + return null; + Provider[] providers = Security.getProviders(); + if (providers == null || providers.length == 0) + return null; + + SaslServer result = null; + SaslServerFactory factory = null; + String clazz = null, upper, alias = null; + int j; + Provider p; + for (j = 0; j < providers.length; j++) + { + p = providers[j]; + if (p != null) + { + // try the name as is + clazz = p.getProperty(SERVER_FACTORY_SVC + mechanism); + if (clazz == null) // try all uppercase + { + upper = mechanism.toUpperCase(); + clazz = p.getProperty(SERVER_FACTORY_SVC + upper); + if (clazz == null) // try if it's an alias + { + alias = p.getProperty(ALIAS + SERVER_FACTORY_SVC + mechanism); + if (alias == null) // try all-uppercase alias name + { + alias = p.getProperty(ALIAS + SERVER_FACTORY_SVC + upper); + if (alias == null) // spit the dummy + continue; + } + } + clazz = p.getProperty(SERVER_FACTORY_SVC + alias); + } + } + if (clazz == null) + continue; + else + clazz = clazz.trim(); + + try + { + result = null; + factory = (SaslServerFactory) Class.forName(clazz).newInstance(); + result = + factory.createSaslServer(mechanism, protocol, serverName, props, cbh); + } + catch (ClassCastException ignored) // ignore instantiation exceptions + { + } + catch (ClassNotFoundException ignored) + { + } + catch (InstantiationException ignored) + { + } + catch (IllegalAccessException ignored) + { + } + if (result != null) + return result; + } + return null; + } + + /** + * Gets an enumeration of known factories for producing a {@link SaslServer} + * instance. This method uses the same sources for locating factories as + * <code>createSaslServer()</code>. + * + * @return a non-null {@link Enumeration} of known factories for producing a + * {@link SaslServer} instance. + * @see #createSaslServer(String,String,String,Map,CallbackHandler) + */ + public static Enumeration getSaslServerFactories() + { + Vector result = new Vector(); + HashSet names = new HashSet(); + Provider[] providers = Security.getProviders(); + Iterator it; + if (providers == null) + { + Provider p; + String key; + for (int i = 0; i < providers.length; i++) + { + p = providers[i]; + for (it = p.keySet().iterator(); it.hasNext(); ) + { + key = (String) it.next(); + // add key's binding (a) it is a class of a server factory, + // and (b) the key does not include blanks + if (key.startsWith(SERVER_FACTORY_SVC) && key.indexOf(" ") == -1) + { + names.add(p.getProperty(key)); + break; + } + } + } + } + // we have the factory class names in names; instantiate and enumerate + String c; + for (it = names.iterator(); it.hasNext(); ) + { + c = (String) it.next(); + try + { + SaslServerFactory f = (SaslServerFactory) Class.forName(c).newInstance(); + if (f != null) + result.add(f); + } + catch (ClassCastException ignored) // ignore instantiation exceptions + { + } + catch (ClassNotFoundException ignored) + { + } + catch (InstantiationException ignored) + { + } + catch (IllegalAccessException ignored) + { + } + } + + return result.elements(); + } +} diff --git a/javax/security/sasl/SaslClient.java b/javax/security/sasl/SaslClient.java new file mode 100644 index 000000000..ca95ced25 --- /dev/null +++ b/javax/security/sasl/SaslClient.java @@ -0,0 +1,231 @@ +/* SaslClient.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpathis free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpathis 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +/** + * <p>Performs SASL authentication as a client.</p> + * + * <p>A protocol library such as one for LDAP gets an instance of this class in + * order to perform authentication defined by a specific SASL mechanism. + * Invoking methods on the <code>SaslClient</code> instance process challenges + * and create responses according to the SASL mechanism implemented by the + * <code>SaslClient</code>. As the authentication proceeds, the instance + * encapsulates the state of a SASL client's authentication exchange.</p> + * + * <p>Here's an example of how an LDAP library might use a <code>SaslClient</code>. + * It first gets an instance of a SaslClient:</p> + * <pre> + *SaslClient sc = + * Sasl.createSaslClient(mechanisms, authorizationID, protocol, + * serverName, props, callbackHandler); + * </pre> + * + * <p>It can then proceed to use the client for authentication. For example, an + * LDAP library might use the client as follows:</p> + * <pre> + * // Get initial response and send to server + *byte[] response = sc.hasInitialResponse() + * ? sc.evaluateChallenge(new byte[0]) : null; + *LdapResult res = ldap.sendBindRequest(dn, sc.getName(), response); + *while (!sc.isComplete() + * && ((res.status == SASL_BIND_IN_PROGRESS) || (res.status == SUCCESS))) { + * response = sc.evaluateChallenge( res.getBytes() ); + * if (res.status == SUCCESS) { + * // we're done; don't expect to send another BIND + * if ( response != null ) { + * throw new SaslException( + * "Protocol error: attempting to send response after completion"); + * } + * break; + * } + * res = ldap.sendBindRequest(dn, sc.getName(), response); + *} + *if (sc.isComplete() && (res.status == SUCCESS) ) { + * String qop = (String)sc.getNegotiatedProperty(Sasl.QOP); + * if ((qop != null) + * && (qop.equalsIgnoreCase("auth-int") + * || qop.equalsIgnoreCase("auth-conf"))) { + * // Use SaslClient.wrap() and SaslClient.unwrap() for future + * // communication with server + * ldap.in = new SecureInputStream(sc, ldap.in); + * ldap.out = new SecureOutputStream(sc, ldap.out); + * } + *} + * </pre> + * + * <p>If the mechanism has an initial response, the library invokes + * {@link #evaluateChallenge(byte[])} with an empty challenge to get the initial + * response. Protocols such as IMAP4, which do not include an initial response + * with their first authentication command to the server, initiate the + * authentication without first calling {@link #hasInitialResponse()} or + * {@link #evaluateChallenge(byte[])}. When the server responds to the command, + * it sends an initial challenge. For a SASL mechanism in which the client sends + * data first, the server should have issued a challenge with no data. This will + * then result in a call (on the client) to {@link #evaluateChallenge(byte[])} + * with an empty challenge.</p> + * + * @see Sasl + * @see SaslClientFactory + * @version $Revision: 1.1 $ + */ +public interface SaslClient +{ + + /** + * Returns the IANA-registered mechanism name of this SASL client. (e.g. + * "CRAM-MD5", "GSSAPI"). + * + * @return a non-null string representing the IANA-registered mechanism name. + */ + String getMechanismName(); + + /** + * Determines if this mechanism has an optional initial response. If + * <code>true</code>, caller should call {@link #evaluateChallenge(byte[])} + * with an empty array to get the initial response. + * + * @return <code>true</code> if this mechanism has an initial response. + */ + boolean hasInitialResponse(); + + /** + * Evaluates the challenge data and generates a response. If a challenge is + * received from the server during the authentication process, this method is + * called to prepare an appropriate next response to submit to the server. + * + * @param challenge the non-null challenge sent from the server. The + * challenge array may have zero length. + * @return the possibly <code>null</code> reponse to send to the server. It + * is <code>null</code> if the challenge accompanied a "SUCCESS" status and + * the challenge only contains data for the client to update its state and no + * response needs to be sent to the server. The response is a zero-length + * byte array if the client is to send a response with no data. + * @throws SaslException if an error occurred while processing the challenge + * or generating a response. + */ + byte[] evaluateChallenge(byte[] challenge) throws SaslException; + + /** + * Determines if the authentication exchange has completed. This method may + * be called at any time, but typically, it will not be called until the + * caller has received indication from the server (in a protocol-specific + * manner) that the exchange has completed. + * + * @return <code>true</code> if the authentication exchange has completed; + * <code>false</code> otherwise. + */ + boolean isComplete(); + + /** + * <p>Unwraps a byte array received from the server. This method can be + * called only after the authentication exchange has completed (i.e., when + * {@link #isComplete()} returns <code>true</code>) and only if the + * authentication exchange has negotiated integrity and/or privacy as the + * quality of protection; otherwise, an {@link IllegalStateException} is + * thrown.</p> + * + * <p><code>incoming</code> is the contents of the SASL buffer as defined in + * RFC 2222 without the leading four octet field that represents the length. + * <code>offset</code> and <code>len</code> specify the portion of incoming + * to use.</p> + * + * @param incoming a non-null byte array containing the encoded bytes from + * the server. + * @param offset the starting position at <code>incoming</code> of the bytes + * to use. + * @param len the number of bytes from <code>incoming</code> to use. + * @return a non-null byte array containing the decoded bytes. + * @throws SaslException if <code>incoming</code> cannot be successfully + * unwrapped. + * @throws IllegalStateException if the authentication exchange has not + * completed, or if the negotiated quality of protection has neither + * integrity nor privacy. + */ + byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException; + + /** + * <p>Wraps a byte array to be sent to the server. This method can be called + * only after the authentication exchange has completed (i.e., when + * {@link #isComplete()} returns <code>true</code>) and only if the + * authentication exchange has negotiated integrity and/or privacy as the + * quality of protection; otherwise, an {@link IllegalStateException} is + * thrown.</p> + * + * <p>The result of this method will make up the contents of the SASL buffer + * as defined in RFC 2222 without the leading four octet field that + * represents the length. <code>offset</code> and <code>len</code> specify + * the portion of <code>outgoing</code> to use.</p> + * + * @param outgoing a non-null byte array containing the bytes to encode. + * @param offset the starting position at <code>outgoing</code> of the bytes + * to use. + * @param len the number of bytes from <code>outgoing</code> to use. + * @return a non-null byte array containing the encoded bytes. + * @throws SaslException if <code>outgoing</code> cannot be successfully + * wrapped. + * @throws IllegalStateException if the authentication exchange has not + * completed, or if the negotiated quality of protection has neither + * integrity nor privacy. + */ + byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException; + + /** + * Retrieves the negotiated property. This method can be called only after + * the authentication exchange has completed (i.e., when {@link #isComplete()} + * returns <code>true</code>); otherwise, an {@link IllegalStateException} is + * thrown. + * + * @param propName the non-null property name. + * @return the value of the negotiated property. If <code>null</code>, the + * property was not negotiated or is not applicable to this mechanism. + * @throws IllegalStateException if this authentication exchange has not + * completed. + */ + Object getNegotiatedProperty(String propName) throws SaslException; + + /** + * Disposes of any system resources or security-sensitive information the + * <code>SaslClient</code> might be using. Invoking this method invalidates + * the <code>SaslClient</code> instance. This method is idempotent. + * + * @throws SaslException if a problem was encountered while disposing of the + * resources. + */ + void dispose() throws SaslException; +} diff --git a/javax/security/sasl/SaslClientFactory.java b/javax/security/sasl/SaslClientFactory.java new file mode 100644 index 000000000..b67c7a324 --- /dev/null +++ b/javax/security/sasl/SaslClientFactory.java @@ -0,0 +1,117 @@ +/* SaslClientFactory.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import java.util.Map; + +import javax.security.auth.callback.CallbackHandler; + +/** + * <p>An interface for creating instances of {@link SaslClient}. A class that + * implements this interface must be thread-safe and handle multiple + * simultaneous requests. It must also have a public constructor that accepts + * no arguments.</p> + * + * <p>This interface is not normally accessed directly by a client, which will + * use the {@link Sasl} static methods to create a client instance instead. + * However, a particular environment may provide and install a new or different + * <code>SaslClientFactory</code>.</p> + * + * @see SaslClient + * @see Sasl + * @version $Revision: 1.1 $ + */ +public interface SaslClientFactory +{ + + /** + * Creates a {@link SaslClient} using the parameters supplied. + * + * @param mechanisms the non-null list of mechanism names to try. Each is the + * IANA-registered name of a SASL mechanism (e.g. "GSSAPI", "CRAM-MD5"). + * @param authorizationID the possibly null protocol-dependent identification + * to be used for authorization. If <code>null</code> or empty, the server + * derives an authorization ID from the client's authentication credentials. + * When the SASL authentication completes successfully, the specified entity + * is granted access. + * @param protocol the non-null string name of the protocol for which the + * authentication is being performed (e.g. "ldap"). + * @param serverName the non-null fully qualified host name of the server to + * authenticate to. + * @param props the possibly <code>null</code> set of properties used to + * select the SASL mechanism and to configure the authentication exchange of + * the selected mechanism. See the {@link Sasl} class for a list of standard + * properties. Other, possibly mechanism-specific, properties can be included. + * Properties not relevant to the selected mechanism are ignored. + * @param cbh the possibly <code>null</code> callback handler to used by the + * SASL mechanisms to get further information from the application/library to + * complete the authentication. For example, a SASL mechanism might require + * the authentication ID, password and realm from the caller. The + * authentication ID is requested by using a + * {@link javax.security.auth.callback.NameCallback}. The password is + * requested by using a {@link javax.security.auth.callback.PasswordCallback}. + * The realm is requested by using a {@link RealmChoiceCallback} if there is + * a list of realms to choose from, and by using a {@link RealmCallback} if + * the realm must be entered. + * @return a possibly <code>null</code> {@link SaslClient} created using the + * parameters supplied. If <code>null</code>, this factory cannot produce a + * {@link SaslClient} using the parameters supplied. + * @throws SaslException if a {@link SaslClient} instance cannot be created + * because of an error. + */ + SaslClient createSaslClient(String[] mechanisms, String authorizationID, + String protocol, String serverName, Map props, + CallbackHandler cbh) + throws SaslException; + + /** + * Returns an array of names of mechanisms that match the specified mechanism + * selection policies. + * + * @param props the possibly <code>null</code> set of properties used to + * specify the security policy of the SASL mechanisms. For example, if props + * contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value + * <code>"true"</code>, then the factory must not return any SASL mechanisms + * that are susceptible to simple plain passive attacks. See the {@link Sasl} + * class for a complete list of policy properties. Non-policy related + * properties, if present in props, are ignored. + * @return a non-null array containing IANA-registered SASL mechanism names. + */ + String[] getMechanismNames(Map props); +} diff --git a/javax/security/sasl/SaslException.java b/javax/security/sasl/SaslException.java new file mode 100644 index 000000000..9ff091d63 --- /dev/null +++ b/javax/security/sasl/SaslException.java @@ -0,0 +1,185 @@ +/* SaslException.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.Serializable; + +/** + * This class represents an error that has occurred when using SASL. + * + * @version $Revision: 1.1 $ + */ +public class SaslException extends IOException implements Serializable +{ + + // Constants and variables + // ------------------------------------------------------------------------- + + /** + * @serial The possibly null root cause exception. + */ + private Throwable _exception = null; + + // Constructor(s) + // ------------------------------------------------------------------------- + + /** + * Constructs a new instance of <code>SaslException</code>. The root + * exception and the detailed message are null. + */ + public SaslException() + { + super(); + } + + /** + * Constructs a new instance of <code>SaslException</code> with a detailed + * message. The <code>root</code> exception is <code>null</code>. + * + * @param detail a possibly null string containing details of the exception. + * @see Throwable#getMessage() + */ + public SaslException(String detail) + { + super(detail); + } + + /** + * Constructs a new instance of <code>SaslException</code> with a detailed + * message and a root exception. For example, a <code>SaslException</code> + * might result from a problem with the callback handler, which might throw a + * {@link javax.security.auth.callback.UnsupportedCallbackException} if it + * does not support the requested callback, or throw an {@link IOException} + * if it had problems obtaining data for the callback. The + * <code>SaslException</code>'s root exception would be then be the exception + * thrown by the callback handler. + * + * @param detail a possibly <code>null</code> string containing details of + * the exception. + * @param ex a possibly <code>null</code> root exception that caused this + * exception. + * @see Throwable#getMessage() + * @see #getCause() + */ + public SaslException(String detail, Throwable ex) + { + super(detail); + _exception = ex; + } + + // Class methods + // ------------------------------------------------------------------------- + + // Instance methods + // ------------------------------------------------------------------------- + + /** + * Returns the cause of this throwable or <code>null</code> if the cause is + * nonexistent or unknown. The cause is the throwable that caused this + * exception to be thrown. + * + * @return the possibly <code>null</code> exception that caused this exception. + */ + public Throwable getCause() + { + return _exception; + } + + /** + * Prints this exception's stack trace to <code>System.err</code>. If this + * exception has a root exception; the stack trace of the root exception is + * also printed to <code>System.err</code>. + */ + public void printStackTrace() + { + super.printStackTrace(); + if (_exception != null) + _exception.printStackTrace(); + } + + /** + * Prints this exception's stack trace to a print stream. If this exception + * has a root exception; the stack trace of the root exception is also + * printed to the print stream. + * + * @param ps the non-null print stream to which to print. + */ + public void printStackTrace(PrintStream ps) + { + super.printStackTrace(ps); + if (_exception != null) + _exception.printStackTrace(ps); + } + + /** + * Prints this exception's stack trace to a print writer. If this exception + * has a root exception; the stack trace of the root exception is also + * printed to the print writer. + * + * @param pw the non-null print writer to use for output. + */ + public void printStackTrace(PrintWriter pw) + { + super.printStackTrace(pw); + if (_exception != null) + _exception.printStackTrace(pw); + } + + /** + * Returns the string representation of this exception. The string + * representation contains this exception's class name, its detailed + * messsage, and if it has a root exception, the string representation of the + * root exception. This string representation is meant for debugging and not + * meant to be interpreted programmatically. + * + * @return the non-null string representation of this exception. + * @see Throwable#getMessage() + */ + public String toString() + { + StringBuffer sb = new StringBuffer(this.getClass().getName()) + .append(": ").append(super.toString()); + if (_exception != null) + sb.append("; caused by: ").append(_exception.toString()); + return sb.toString(); + } +} diff --git a/javax/security/sasl/SaslServer.java b/javax/security/sasl/SaslServer.java new file mode 100644 index 000000000..3f0d79d44 --- /dev/null +++ b/javax/security/sasl/SaslServer.java @@ -0,0 +1,226 @@ +/* SasServer.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +/** + * <p>Performs SASL authentication as a server.</p> + * + * <p>A server such as an LDAP server gets an instance of this class in order to + * perform authentication defined by a specific SASL mechanism. Invoking methods + * on the <code>SaslServer</code> instance generates challenges corresponding to + * the SASL mechanism implemented by the <code>SaslServer</code> instance. As + * the authentication proceeds, the instance encapsulates the state of a SASL + * server's authentication exchange.</p> + * + * <p>Here's an example of how an LDAP server might use a <code>SaslServer</code> + * instance. It first gets an instance of a <code>SaslServer</code> for the SASL + * mechanism requested by the client:</p> + * + * <pre> + *SaslServer ss = + * Sasl.createSaslServer(mechanism, "ldap", myFQDN, props, callbackHandler); + * </pre> + * + * <p>It can then proceed to use the server for authentication. For example, + * suppose the LDAP server received an LDAP BIND request containing the name of + * the SASL mechanism and an (optional) initial response. It then might use the + * server as follows:</p> + * + * <pre> + *while (!ss.isComplete()) { + * try { + * byte[] challenge = ss.evaluateResponse(response); + * if (ss.isComplete()) { + * status = ldap.sendBindResponse(mechanism, challenge, SUCCESS); + * } else { + * status = ldap.sendBindResponse(mechanism, challenge, SASL_BIND_IN_PROGRESS); + * response = ldap.readBindRequest(); + * } + * } catch (SaslException x) { + * status = ldap.sendErrorResponse(x); + * break; + * } + *} + *if (ss.isComplete() && (status == SUCCESS)) { + * String qop = (String) sc.getNegotiatedProperty(Sasl.QOP); + * if (qop != null + * && (qop.equalsIgnoreCase("auth-int") + * || qop.equalsIgnoreCase("auth-conf"))) { + * // Use SaslServer.wrap() and SaslServer.unwrap() for future + * // communication with client + * ldap.in = new SecureInputStream(ss, ldap.in); + * ldap.out = new SecureOutputStream(ss, ldap.out); + * } + *} + * </pre> + * + * @see Sasl + * @see SaslServerFactory + * @version $Revision: 1.1 $ + */ +public interface SaslServer +{ + + /** + * Returns the IANA-registered mechanism name of this SASL server (e.g. + * "CRAM-MD5", "GSSAPI"). + * + * @return a non-null string representing the IANA-registered mechanism name. + */ + String getMechanismName(); + + /** + * Evaluates the response data and generates a challenge. If a response is + * received from the client during the authentication process, this method is + * called to prepare an appropriate next challenge to submit to the client. + * The challenge is <code>null</code> if the authentication has succeeded and + * no more challenge data is to be sent to the client. It is non-null if the + * authentication must be continued by sending a challenge to the client, or + * if the authentication has succeeded but challenge data needs to be + * processed by the client. {@link #isComplete()} should be called after each + * call to <code>evaluateResponse()</code>,to determine if any further + * response is needed from the client. + * + * @param response the non-null (but possibly empty) response sent by the + * client. + * @return the possibly <code>null</code> challenge to send to the client. + * It is <code>null</code> if the authentication has succeeded and there is + * no more challenge data to be sent to the client. + * @throws SaslException if an error occurred while processing the response + * or generating a challenge. + */ + byte[] evaluateResponse(byte[] response) throws SaslException; + + /** + * Determines if the authentication exchange has completed. This method is + * typically called after each invocation of {@link #evaluateResponse(byte[])} + * to determine whether the authentication has completed successfully or + * should be continued. + * + * @return <code>true</code> if the authentication exchange has completed; + * <code>false</code> otherwise. + */ + boolean isComplete(); + + /** + * Reports the authorization ID in effect for the client of this session This + * method can only be called if {@link #isComplete()} returns <code>true</code>. + * + * @return the authorization ID of the client. + * @throws IllegalStateException if this authentication session has not + * completed. + */ + String getAuthorizationID(); + + /** + * <p>Unwraps a byte array received from the client. This method can be called + * only after the authentication exchange has completed (i.e., when + * {@link #isComplete()} returns <code>true</code>) and only if the + * authentication exchange has negotiated integrity and/or privacy as the + * quality of protection; otherwise, an {@link IllegalStateException} is + * thrown.</p> + * + * <p><code>incoming</code> is the contents of the SASL buffer as defined in + * RFC 2222 without the leading four octet field that represents the length. + * <code>offset</code> and <code>len</code> specify the portion of incoming + * to use.</p> + * + * @param incoming a non-null byte array containing the encoded bytes from + * the client. + * @param offset the starting position at <code>incoming</code> of the bytes + * to use. + * @param len the number of bytes from <code>incoming</code> to use. + * @return a non-null byte array containing the decoded bytes. + * @throws SaslException if <code>incoming</code> cannot be successfully + * unwrapped. + * @throws IllegalStateException if the authentication exchange has not + * completed, or if the negotiated quality of protection has neither + * integrity nor privacy. + */ + byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException; + + /** + * <p>Wraps a byte array to be sent to the client. This method can be called + * only after the authentication exchange has completed (i.e., when + * {@link #isComplete()} returns <code>true</code>) and only if the + * authentication exchange has negotiated integrity and/or privacy as the + * quality of protection; otherwise, an {@link IllegalStateException} is + * thrown.</p> + * + * <p>The result of this method will make up the contents of the SASL buffer + * as defined in RFC 2222 without the leading four octet field that + * represents the length. <code>offset</code> and <code>len</code> specify + * the portion of <code>outgoing</code> to use. + * + * @param outgoing a non-null byte array containing the bytes to encode. + * @param offset the starting position at <code>outgoing</code> of the bytes + * to use. + * @param len the number of bytes from <code>outgoing</code> to use. + * @return a non-null byte array containing the encoded bytes. + * @throws SaslException if <code>outgoing</code> cannot be successfully + * wrapped. + * @throws IllegalStateException if the authentication exchange has not + * completed, or if the negotiated quality of protection has neither + * integrity nor privacy. + */ + byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException; + + /** + * Retrieves the negotiated property. This method can be called only after + * the authentication exchange has completed (i.e., when + * {@link #isComplete()} returns <code>true</code>); otherwise, an + * {@link IllegalStateException} is thrown. + * + * @return the value of the negotiated property. If <code>null</code>, the + * property was not negotiated or is not applicable to this mechanism. + * @throws IllegalStateException if this authentication exchange has not + * completed. + */ + Object getNegotiatedProperty(String propName) throws SaslException; + + /** + * Disposes of any system resources or security-sensitive information the + * <code>SaslServer</code> might be using. Invoking this method invalidates + * the <code>SaslServer</code> instance. This method is idempotent. + * + * @throws SaslException if a problem was encountered while disposing of the + * resources. + */ + void dispose() throws SaslException; +} diff --git a/javax/security/sasl/SaslServerFactory.java b/javax/security/sasl/SaslServerFactory.java new file mode 100644 index 000000000..b9387bbee --- /dev/null +++ b/javax/security/sasl/SaslServerFactory.java @@ -0,0 +1,114 @@ +/* SaslServerFactory.java + Copyright (C) 2003, Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath 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 for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307 USA + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package javax.security.sasl; + +import java.util.Map; + +import javax.security.auth.callback.CallbackHandler; + +/** + * <p>An interface for creating instances of {@link SaslServer}. A class that + * implements this interface must be thread-safe and handle multiple + * simultaneous requests. It must also have a public constructor that accepts + * no arguments.</p> + * + * This interface is not normally accessed directly by a server, which will use + * the {@link Sasl} static methods to create a {@link SaslServer} instance + * instead. However, a particular environment may provide and install a new or + * different <code>SaslServerFactory</code>.</p> + * + * @see SaslServer + * @see Sasl + * @version $Revision: 1.1 $ + */ +public interface SaslServerFactory +{ + + /** + * Creates a {@link SaslServer} instance using the parameters supplied. It + * returns <code>null</code> if no {@link SaslServer} instance can be created + * using the parameters supplied. Throws {@link SaslException} if it cannot + * create a {@link SaslServer} because of an error. + * + * @param mechanism the non-null IANA-registered name of a SASL mechanism + * (e.g. "GSSAPI", "CRAM-MD5"). + * @param protocol the non-null string name of the protocol for which the + * authentication is being performed (e.g. "ldap"). + * @param serverName the non-null fully qualified host name of the server to + * authenticate to. + * @param props the possibly null set of properties used to select the SASL + * mechanism and to configure the authentication exchange of the selected + * mechanism. See the {@link Sasl} class for a list of standard properties. + * Other, possibly mechanism-specific, properties can be included. Properties + * not relevant to the selected mechanism are ignored. + * @param cbh the possibly null callback handler to used by the SASL + * mechanisms to get further information from the application/library to + * complete the authentication. For example, a SASL mechanism might require + * the authentication ID, password and realm from the caller. The + * authentication ID is requested by using a + * {@link javax.security.auth.callback.NameCallback}. The password is + * requested by using a {@link javax.security.auth.callback.PasswordCallback}. + * The realm is requested by using a {@link RealmChoiceCallback} if there is + * a list of realms to choose from, and by using a {@link RealmCallback} if + * the realm must be entered. + * @return a possibly null {@link SaslServer} created using the parameters + * supplied. If <code>null</code> is returned, it means that this factory + * cannot produce a {@link SaslServer} using the parameters supplied. + * @throws SaslException if a SaslServer instance cannot be created because + * of an error. + */ + SaslServer createSaslServer(String mechanism, String protocol, + String serverName, Map props, CallbackHandler cbh) + throws SaslException; + + /** + * Returns an array of names of mechanisms that match the specified mechanism + * selection policies. + * + * @param props the possibly <code>null</code> set of properties used to + * specify the security policy of the SASL mechanisms. For example, if props + * contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value + * <code>"true"</code>, then the factory must not return any SASL mechanisms + * that are susceptible to simple plain passive attacks. See the {@link Sasl} + * class for a complete list of policy properties. Non-policy related + * properties, if present in props, are ignored. + * @return a non-null array containing IANA-registered SASL mechanism names. + */ + String[] getMechanismNames(Map props); +} |