提交 a921badd 编写于 作者: T tbell

Merge

...@@ -390,7 +390,7 @@ clean:: ...@@ -390,7 +390,7 @@ clean::
LOCALES_GEN_SH = localelist.sh LOCALES_GEN_SH = localelist.sh
$(GENSRCDIR)/sun/util/CoreResourceBundleControl.java: \ $(GENSRCDIR)/sun/util/CoreResourceBundleControl.java: \
$(SHARE_SRC)/classes/sun/util/CoreResourceBundleControl-XLocales.java $(LOCALES_GEN_SH) $(SHARE_SRC)/classes/sun/util/CoreResourceBundleControl-XLocales.java.template $(LOCALES_GEN_SH)
@$(prep-target) @$(prep-target)
NAWK="$(NAWK)" SED="$(SED)" $(SH) $(LOCALES_GEN_SH) "$(JRE_NONEXIST_LOCALES)" \ NAWK="$(NAWK)" SED="$(SED)" $(SH) $(LOCALES_GEN_SH) "$(JRE_NONEXIST_LOCALES)" \
$< $@ $< $@
......
...@@ -68,7 +68,7 @@ NonEuro_Resources_properties := $(FILES_compiled_properties) ...@@ -68,7 +68,7 @@ NonEuro_Resources_properties := $(FILES_compiled_properties)
FILES_java := $(FILES_java_orig) FILES_java := $(FILES_java_orig)
FILES_compiled_properties := $(FILES_compiled_properties_orig) FILES_compiled_properties := $(FILES_compiled_properties_orig)
LocaleDataMetaInfo_Src=$(SHARE_SRC)/classes/sun/util/LocaleDataMetaInfo-XLocales.java LocaleDataMetaInfo_Src=$(SHARE_SRC)/classes/sun/util/LocaleDataMetaInfo-XLocales.java.template
LocaleDataMetaInfo_Dest=$(GENSRCDIR)/sun/util/LocaleDataMetaInfo.java LocaleDataMetaInfo_Dest=$(GENSRCDIR)/sun/util/LocaleDataMetaInfo.java
LOCALEGEN_SH=localegen.sh LOCALEGEN_SH=localegen.sh
RESOURCE_NAMES="FormatData CollationData TimeZoneNames LocaleNames CurrencyNames CalendarData" RESOURCE_NAMES="FormatData CollationData TimeZoneNames LocaleNames CurrencyNames CalendarData"
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
# #
# This script is to generate the supported locale list string and replace the # This script is to generate the supported locale list string and replace the
# LocaleDataMetaInfo-XLocales.java in <ws>/src/share/classes/sun/util # LocaleDataMetaInfo-XLocales.java.template in <ws>/src/share/classes/sun/util
# #
# SORT, NAWK & SED is passed in as environment variables. # SORT, NAWK & SED is passed in as environment variables.
# #
......
...@@ -96,6 +96,7 @@ OTHER_CPPFLAGS += $(LIBARCH_DEFINES) ...@@ -96,6 +96,7 @@ OTHER_CPPFLAGS += $(LIBARCH_DEFINES)
ifneq ($(PLATFORM), windows) # UNIX systems ifneq ($(PLATFORM), windows) # UNIX systems
LD_RUNPATH_EXTRAS += ..
LIB_LOCATION = $(LIBDIR)/$(LIBARCH)/jli LIB_LOCATION = $(LIBDIR)/$(LIBARCH)/jli
# Note: its important to keep this order meaning -lc is the # Note: its important to keep this order meaning -lc is the
# last library otherwise it could cause compatibility issues # last library otherwise it could cause compatibility issues
......
...@@ -61,8 +61,5 @@ OTHER_CPPFLAGS += -DLAUNCHER_NAME='"$(LAUNCHER_NAME)"' ...@@ -61,8 +61,5 @@ OTHER_CPPFLAGS += -DLAUNCHER_NAME='"$(LAUNCHER_NAME)"'
ifeq ($(PLATFORM), solaris) ifeq ($(PLATFORM), solaris)
LDFLAGS += -R$(OPENWIN_LIB) LDFLAGS += -R$(OPENWIN_LIB)
endif
ifeq ($(PLATFORM), solaris)
LDFLAGS += -M mapfile-$(ARCH) LDFLAGS += -M mapfile-$(ARCH)
endif endif
...@@ -834,7 +834,7 @@ $(SCH_GEN)/SocketOptionRegistry.java: $(GENSOR_EXE) ...@@ -834,7 +834,7 @@ $(SCH_GEN)/SocketOptionRegistry.java: $(GENSOR_EXE)
GENCSSRC = $(BUILDDIR)/tools/CharsetMapping GENCSSRC = $(BUILDDIR)/tools/CharsetMapping
CHARSETMAPPING_JARFILE = $(BUILDTOOLJARDIR)/charsetmapping.jar CHARSETMAPPING_JARFILE = $(BUILDTOOLJARDIR)/charsetmapping.jar
$(FILES_gensbcs_out): $(GENCSSRC)/SingleByte-X.java $(GENCSSRC)/sbcs $(FILES_gensbcs_out): $(GENCSSRC)/SingleByte-X.java.template $(GENCSSRC)/sbcs
@$(prep-target) @$(prep-target)
$(BOOT_JAVA_CMD) -jar $(CHARSETMAPPING_JARFILE) $(GENCSSRC) $(SCS_GEN) sbcs $(BOOT_JAVA_CMD) -jar $(CHARSETMAPPING_JARFILE) $(GENCSSRC) $(SCS_GEN) sbcs
......
...@@ -194,10 +194,8 @@ endif ...@@ -194,10 +194,8 @@ endif
# For backwards compatability, make a link of the 32-bit client JVM to $(LIBDIR) # For backwards compatability, make a link of the 32-bit client JVM to $(LIBDIR)
IMPORT_LIST += $(LIB_LOCATION)/$(JVM_NAME) IMPORT_LIST += $(LIB_LOCATION)/$(JVM_NAME)
# create a link from lib/libjvm.so to client/libjvm.so
$(LIB_LOCATION)/$(JVM_NAME): $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVM_NAME) $(LIB_LOCATION)/$(JVM_NAME): $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVM_NAME)
@$(prep-target) @$(prep-target)
$(LN) -s $(CLIENT_LOCATION)/$(JVM_NAME) $@
# solaris ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ solaris # solaris ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ solaris
endif # 32bit solaris endif # 32bit solaris
......
...@@ -411,7 +411,7 @@ Creating your own NetBeans project ...@@ -411,7 +411,7 @@ Creating your own NetBeans project
java/util/regex/,\ java/util/regex/,\
java/util/spi/,\ java/util/spi/,\
java/util/zip/,\ java/util/zip/,\
**/*-XLocales.java **/*-XLocales.java.template
jtreg.tests=\ jtreg.tests=\
java/util/**/*Collection/ \ java/util/**/*Collection/ \
java/util/**/*Map/ \ java/util/**/*Map/ \
......
...@@ -82,7 +82,9 @@ $(FILES_DAT): $(FILES_MAP) ...@@ -82,7 +82,9 @@ $(FILES_DAT): $(FILES_MAP)
$(FILES_MAP) $(FILES_DAT) sjis0213 $(FILES_MAP) $(FILES_DAT) sjis0213
$(FILES_genout_extcs): $(GENCSDATASRC)/SingleByte-X.java $(GENCSDATASRC)/DoubleByte-X.java \ $(FILES_genout_extcs): \
$(GENCSDATASRC)/SingleByte-X.java.template \
$(GENCSDATASRC)/DoubleByte-X.java.template \
$(GENCSDATASRC)/extsbcs $(GENCSDATASRC)/dbcs $(GENCSDATASRC)/extsbcs $(GENCSDATASRC)/dbcs
@$(prep-target) @$(prep-target)
$(RM) -r $(GENCSEXT) $(RM) -r $(GENCSEXT)
......
...@@ -63,7 +63,7 @@ public class GenerateDBCS { ...@@ -63,7 +63,7 @@ public class GenerateDBCS {
int b2Min = toInteger(fields[8]); int b2Min = toInteger(fields[8]);
int b2Max = toInteger(fields[9]); int b2Max = toInteger(fields[9]);
System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName); System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName);
genClass(args[0], args[1], "DoubleByte-X.java", genClass(args[0], args[1], "DoubleByte-X.java.template",
clzName, csName, hisName, pkgName, clzName, csName, hisName, pkgName,
isASCII, type, isASCII, type,
b1Min, b1Max, b2Min, b2Max); b1Min, b1Max, b2Min, b2Max);
......
...@@ -55,7 +55,7 @@ public class GenerateSBCS { ...@@ -55,7 +55,7 @@ public class GenerateSBCS {
String pkgName = fields[4]; String pkgName = fields[4];
System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName); System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName);
genClass(args[0], args[1], "SingleByte-X.java", genClass(args[0], args[1], "SingleByte-X.java.template",
clzName, csName, hisName, pkgName, isASCII); clzName, csName, hisName, pkgName, isASCII);
} }
} }
......
/* /*
* Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright 1995-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -41,15 +41,13 @@ ...@@ -41,15 +41,13 @@
* options are turned into "-foo" options to the vm. This option * options are turned into "-foo" options to the vm. This option
* filtering is handled in a number of places in the launcher, some of * filtering is handled in a number of places in the launcher, some of
* it in machine-dependent code. In this file, the function * it in machine-dependent code. In this file, the function
* CheckJVMType removes vm style options and TranslateApplicationArgs * CheckJvmType removes vm style options and TranslateApplicationArgs
* removes "-J" prefixes. On unix platforms, the * removes "-J" prefixes. The CreateExecutionEnvironment function processes
* CreateExecutionEnvironment function from the unix java_md.c file * and removes -d<n> options. On unix, there is a possibility that the running
* processes and removes -d<n> options. However, in case * data model may not match to the desired data model, in this case an exec is
* CreateExecutionEnvironment does not need to exec because * required to start the desired model. If the data models match, then
* LD_LIBRARY_PATH is set acceptably and the data model does not need * ParseArguments will remove the -d<n> flags. If the data models do not match
* to be changed, ParseArguments will screen out the redundant -d<n> * the CreateExecutionEnviroment will remove the -d<n> flags.
* options and prevent them from being passed to the vm; this is done
* by RemovableOption.
*/ */
...@@ -1891,11 +1889,11 @@ DumpState() ...@@ -1891,11 +1889,11 @@ DumpState()
* Return JNI_TRUE for an option string that has no effect but should * Return JNI_TRUE for an option string that has no effect but should
* _not_ be passed on to the vm; return JNI_FALSE otherwise. On * _not_ be passed on to the vm; return JNI_FALSE otherwise. On
* Solaris SPARC, this screening needs to be done if: * Solaris SPARC, this screening needs to be done if:
* 1) LD_LIBRARY_PATH does _not_ need to be reset and * -d32 or -d64 is passed to a binary with an unmatched data model
* 2) -d32 or -d64 is passed to a binary with a matching data model * (the exec in CreateExecutionEnvironment removes -d<n> options and points the
* (the exec in SetLibraryPath removes -d<n> options and points the * exec to the proper binary). In the case of when the data model and the
* exec to the proper binary). When this exec is not done, these options * requested version is matched, an exec would not occur, and these options
* would end up getting passed onto the vm. * were erroneously passed to the vm.
*/ */
jboolean jboolean
RemovableOption(char * option) RemovableOption(char * option)
......
...@@ -36,7 +36,7 @@ import java.security.spec.*; ...@@ -36,7 +36,7 @@ import java.security.spec.*;
/** /**
* This class constitutes the core of HMAC-<MD> algorithms, where * This class constitutes the core of HMAC-<MD> algorithms, where
* <MD> can be SHA1 or MD5, etc. * <MD> can be SHA1 or MD5, etc. See RFC 2104 for spec.
* *
* It also contains the implementation classes for the SHA-256, * It also contains the implementation classes for the SHA-256,
* SHA-384, and SHA-512 HMACs. * SHA-384, and SHA-512 HMACs.
...@@ -116,7 +116,7 @@ final class HmacCore implements Cloneable { ...@@ -116,7 +116,7 @@ final class HmacCore implements Cloneable {
} }
byte[] secret = key.getEncoded(); byte[] secret = key.getEncoded();
if (secret == null || secret.length == 0) { if (secret == null) {
throw new InvalidKeyException("Missing key data"); throw new InvalidKeyException("Missing key data");
} }
......
/* /*
* Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. * Copyright 2005-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,21 +25,19 @@ ...@@ -25,21 +25,19 @@
package com.sun.crypto.provider; package com.sun.crypto.provider;
import java.io.*; import java.io.ObjectStreamException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.CharBuffer; import java.nio.CharBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Arrays; import java.util.Arrays;
import java.security.KeyRep; import java.security.KeyRep;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import javax.crypto.Mac; import javax.crypto.Mac;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/** /**
* This class represents a PBE key derived using PBKDF2 defined * This class represents a PBE key derived using PBKDF2 defined
...@@ -123,7 +121,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { ...@@ -123,7 +121,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength); this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength);
} }
private static byte[] deriveKey(Mac prf, byte[] password, byte[] salt, private static byte[] deriveKey(final Mac prf, final byte[] password, byte[] salt,
int iterCount, int keyLengthInBit) { int iterCount, int keyLengthInBit) {
int keyLength = keyLengthInBit/8; int keyLength = keyLengthInBit/8;
byte[] key = new byte[keyLength]; byte[] key = new byte[keyLength];
...@@ -133,7 +131,34 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { ...@@ -133,7 +131,34 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
int intR = keyLength - (intL - 1)*hlen; // residue int intR = keyLength - (intL - 1)*hlen; // residue
byte[] ui = new byte[hlen]; byte[] ui = new byte[hlen];
byte[] ti = new byte[hlen]; byte[] ti = new byte[hlen];
SecretKey macKey = new SecretKeySpec(password, prf.getAlgorithm()); // SecretKeySpec cannot be used, since password can be empty here.
SecretKey macKey = new SecretKey() {
@Override
public String getAlgorithm() {
return prf.getAlgorithm();
}
@Override
public String getFormat() {
return "RAW";
}
@Override
public byte[] getEncoded() {
return password;
}
@Override
public int hashCode() {
return Arrays.hashCode(password) * 41 +
prf.getAlgorithm().toLowerCase().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (this.getClass() != obj.getClass()) return false;
SecretKey sk = (SecretKey)obj;
return prf.getAlgorithm().equalsIgnoreCase(sk.getAlgorithm()) &&
Arrays.equals(password, sk.getEncoded());
}
};
prf.init(macKey); prf.init(macKey);
byte[] ibytes = new byte[4]; byte[] ibytes = new byte[4];
...@@ -230,7 +255,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { ...@@ -230,7 +255,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
* @throws ObjectStreamException if a new object representing * @throws ObjectStreamException if a new object representing
* this PBE key could not be created * this PBE key could not be created
*/ */
private Object writeReplace() throws java.io.ObjectStreamException { private Object writeReplace() throws ObjectStreamException {
return new KeyRep(KeyRep.Type.SECRET, getAlgorithm(), return new KeyRep(KeyRep.Type.SECRET, getAlgorithm(),
getFormat(), getEncoded()); getFormat(), getEncoded());
} }
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package com.sun.jmx.mbeanserver; package com.sun.jmx.mbeanserver;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.ref.SoftReference;
import java.lang.reflect.AnnotatedElement; import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
...@@ -33,8 +34,13 @@ import java.lang.reflect.Modifier; ...@@ -33,8 +34,13 @@ import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException; import java.lang.reflect.UndeclaredThrowableException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.WeakHashMap;
import javax.management.Descriptor; import javax.management.Descriptor;
import javax.management.DescriptorKey; import javax.management.DescriptorKey;
...@@ -506,11 +512,25 @@ public class Introspector { ...@@ -506,11 +512,25 @@ public class Introspector {
} else { } else {
// Java Beans introspection // Java Beans introspection
// //
BeanInfo bi = java.beans.Introspector.getBeanInfo(complex.getClass()); Class<?> clazz = complex.getClass();
PropertyDescriptor[] pds = bi.getPropertyDescriptors(); Method readMethod = null;
for (PropertyDescriptor pd : pds) if (BeansHelper.isAvailable()) {
if (pd.getName().equals(element)) Object bi = BeansHelper.getBeanInfo(clazz);
return pd.getReadMethod().invoke(complex); Object[] pds = BeansHelper.getPropertyDescriptors(bi);
for (Object pd: pds) {
if (BeansHelper.getPropertyName(pd).equals(element)) {
readMethod = BeansHelper.getReadMethod(pd);
break;
}
}
} else {
// Java Beans not available so use simple introspection
// to locate method
readMethod = SimpleIntrospector.getReadMethod(clazz, element);
}
if (readMethod != null)
return readMethod.invoke(complex);
throw new AttributeNotFoundException( throw new AttributeNotFoundException(
"Could not find the getter method for the property " + "Could not find the getter method for the property " +
element + " using the Java Beans introspector"); element + " using the Java Beans introspector");
...@@ -524,4 +544,235 @@ public class Introspector { ...@@ -524,4 +544,235 @@ public class Introspector {
new AttributeNotFoundException(e.getMessage()), e); new AttributeNotFoundException(e.getMessage()), e);
} }
} }
/**
* A simple introspector that uses reflection to analyze a class and
* identify its "getter" methods. This class is intended for use only when
* Java Beans is not present (which implies that there isn't explicit
* information about the bean available).
*/
private static class SimpleIntrospector {
private SimpleIntrospector() { }
private static final String GET_METHOD_PREFIX = "get";
private static final String IS_METHOD_PREFIX = "is";
// cache to avoid repeated lookups
private static final Map<Class<?>,SoftReference<List<Method>>> cache =
Collections.synchronizedMap(
new WeakHashMap<Class<?>,SoftReference<List<Method>>> ());
/**
* Returns the list of methods cached for the given class, or {@code null}
* if not cached.
*/
private static List<Method> getCachedMethods(Class<?> clazz) {
// return cached methods if possible
SoftReference<List<Method>> ref = cache.get(clazz);
if (ref != null) {
List<Method> cached = ref.get();
if (cached != null)
return cached;
}
return null;
}
/**
* Returns {@code true} if the given method is a "getter" method (where
* "getter" method is a public method of the form getXXX or "boolean
* isXXX")
*/
static boolean isReadMethod(Method method) {
// ignore static methods
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers))
return false;
String name = method.getName();
Class<?>[] paramTypes = method.getParameterTypes();
int paramCount = paramTypes.length;
if (paramCount == 0 && name.length() > 2) {
// boolean isXXX()
if (name.startsWith(IS_METHOD_PREFIX))
return (method.getReturnType() == boolean.class);
// getXXX()
if (name.length() > 3 && name.startsWith(GET_METHOD_PREFIX))
return (method.getReturnType() != void.class);
}
return false;
}
/**
* Returns the list of "getter" methods for the given class. The list
* is ordered so that isXXX methods appear before getXXX methods - this
* is for compatability with the JavaBeans Introspector.
*/
static List<Method> getReadMethods(Class<?> clazz) {
// return cached result if available
List<Method> cachedResult = getCachedMethods(clazz);
if (cachedResult != null)
return cachedResult;
// get list of public methods, filtering out methods that have
// been overridden to return a more specific type.
List<Method> methods =
StandardMBeanIntrospector.getInstance().getMethods(clazz);
methods = MBeanAnalyzer.eliminateCovariantMethods(methods);
// filter out the non-getter methods
List<Method> result = new LinkedList<Method>();
for (Method m: methods) {
if (isReadMethod(m)) {
// favor isXXX over getXXX
if (m.getName().startsWith(IS_METHOD_PREFIX)) {
result.add(0, m);
} else {
result.add(m);
}
}
}
// add result to cache
cache.put(clazz, new SoftReference<List<Method>>(result));
return result;
}
/**
* Returns the "getter" to read the given property from the given class or
* {@code null} if no method is found.
*/
static Method getReadMethod(Class<?> clazz, String property) {
// first character in uppercase (compatability with JavaBeans)
property = property.substring(0, 1).toUpperCase(Locale.ENGLISH) +
property.substring(1);
String getMethod = GET_METHOD_PREFIX + property;
String isMethod = IS_METHOD_PREFIX + property;
for (Method m: getReadMethods(clazz)) {
String name = m.getName();
if (name.equals(isMethod) || name.equals(getMethod)) {
return m;
}
}
return null;
}
}
/**
* A class that provides access to the JavaBeans Introspector and
* PropertyDescriptors without creating a static dependency on java.beans.
*/
private static class BeansHelper {
private static final Class<?> introspectorClass =
getClass("java.beans.Introspector");
private static final Class<?> beanInfoClass =
(introspectorClass == null) ? null : getClass("java.beans.BeanInfo");
private static final Class<?> getPropertyDescriptorClass =
(beanInfoClass == null) ? null : getClass("java.beans.PropertyDescriptor");
private static final Method getBeanInfo =
getMethod(introspectorClass, "getBeanInfo", Class.class);
private static final Method getPropertyDescriptors =
getMethod(beanInfoClass, "getPropertyDescriptors");
private static final Method getPropertyName =
getMethod(getPropertyDescriptorClass, "getName");
private static final Method getReadMethod =
getMethod(getPropertyDescriptorClass, "getReadMethod");
private static Class<?> getClass(String name) {
try {
return Class.forName(name, true, null);
} catch (ClassNotFoundException e) {
return null;
}
}
private static Method getMethod(Class<?> clazz,
String name,
Class<?>... paramTypes)
{
if (clazz != null) {
try {
return clazz.getMethod(name, paramTypes);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
} else {
return null;
}
}
private BeansHelper() { }
/**
* Returns {@code true} if java.beans is available.
*/
static boolean isAvailable() {
return introspectorClass != null;
}
/**
* Invokes java.beans.Introspector.getBeanInfo(Class)
*/
static Object getBeanInfo(Class<?> clazz) throws Exception {
try {
return getBeanInfo.invoke(null, clazz);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception)
throw (Exception)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
/**
* Invokes java.beans.BeanInfo.getPropertyDescriptors()
*/
static Object[] getPropertyDescriptors(Object bi) {
try {
return (Object[])getPropertyDescriptors.invoke(bi);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
/**
* Invokes java.beans.PropertyDescriptor.getName()
*/
static String getPropertyName(Object pd) {
try {
return (String)getPropertyName.invoke(pd);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
/**
* Invokes java.beans.PropertyDescriptor.getReadMethod()
*/
static Method getReadMethod(Object pd) {
try {
return (Method)getReadMethod.invoke(pd);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
}
} }
...@@ -175,7 +175,7 @@ abstract class MBeanIntrospector<M> { ...@@ -175,7 +175,7 @@ abstract class MBeanIntrospector<M> {
/** /**
* Get the methods to be analyzed to build the MBean interface. * Get the methods to be analyzed to build the MBean interface.
*/ */
List<Method> getMethods(final Class<?> mbeanType) throws Exception { List<Method> getMethods(final Class<?> mbeanType) {
return Arrays.asList(mbeanType.getMethods()); return Arrays.asList(mbeanType.getMethods());
} }
......
...@@ -34,8 +34,6 @@ import java.util.*; ...@@ -34,8 +34,6 @@ import java.util.*;
import java.security.AccessController; import java.security.AccessController;
import java.security.CodeSource; import java.security.CodeSource;
import java.security.Identity;
import java.security.IdentityScope;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.Permission; import java.security.Permission;
...@@ -267,7 +265,7 @@ public class PolicyFile extends javax.security.auth.Policy { ...@@ -267,7 +265,7 @@ public class PolicyFile extends javax.security.auth.Policy {
private boolean initialized = false; private boolean initialized = false;
private boolean expandProperties = true; private boolean expandProperties = true;
private boolean ignoreIdentityScope = false; private boolean ignoreIdentityScope = true;
// for use with the reflection API // for use with the reflection API
...@@ -459,9 +457,6 @@ public class PolicyFile extends javax.security.auth.Policy { ...@@ -459,9 +457,6 @@ public class PolicyFile extends javax.security.auth.Policy {
} }
} }
/** the scope to check */
private static IdentityScope scope = null;
/** /**
* Checks public key. If it is marked as trusted in * Checks public key. If it is marked as trusted in
* the identity database, add it to the policy * the identity database, add it to the policy
......
...@@ -99,4 +99,58 @@ public interface ExtendedGSSContext extends GSSContext { ...@@ -99,4 +99,58 @@ public interface ExtendedGSSContext extends GSSContext {
*/ */
public Object inquireSecContext(InquireType type) public Object inquireSecContext(InquireType type)
throws GSSException; throws GSSException;
/**
* Requests that the delegation policy be respected. When a true value is
* requested, the underlying context would use the delegation policy
* defined by the environment as a hint to determine whether credentials
* delegation should be performed. This request can only be made on the
* context initiator's side and it has to be done prior to the first
* call to <code>initSecContext</code>.
* <p>
* When this flag is false, delegation will only be tried when the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* is true.
* <p>
* When this flag is true but the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* is false, delegation will be only tried if the delegation policy permits
* delegation.
* <p>
* When both this flag and the
* {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag}
* are true, delegation will be always tried. However, if the delegation
* policy does not permit delegation, the value of
* {@link #getDelegPolicyState} will be false, even
* if delegation is performed successfully.
* <p>
* In any case, if the delegation is not successful, the value returned
* by {@link GSSContext#getCredDelegState()} is false, and the value
* returned by {@link #getDelegPolicyState()} is also false.
* <p>
* Not all mechanisms support delegation policy. Therefore, the
* application should check to see if the request was honored with the
* {@link #getDelegPolicyState() getDelegPolicyState} method. When
* delegation policy is not supported, <code>requestDelegPolicy</code>
* should return silently without throwing an exception.
* <p>
* Note: for the Kerberos 5 mechanism, the delegation policy is expressed
* through the OK-AS-DELEGATE flag in the service ticket. When it's true,
* the KDC permits delegation to the target server. In a cross-realm
* environment, in order for delegation be permitted, all cross-realm TGTs
* on the authentication path must also have the OK-AS-DELAGATE flags set.
* @param state true if the policy should be respected
* @throws GSSException containing the following
* major error codes:
* {@link GSSException#FAILURE GSSException.FAILURE}
*/
public void requestDelegPolicy(boolean state) throws GSSException;
/**
* Returns the delegation policy response. Called after a security context
* is established. This method can be only called on the initiator's side.
* See {@link ExtendedGSSContext#requestDelegPolicy}.
* @return the delegation policy response
*/
public boolean getDelegPolicyState();
} }
...@@ -57,7 +57,10 @@ public class JavaStatic { ...@@ -57,7 +57,10 @@ public class JavaStatic {
id = ((JavaObjectRef)value).getId(); id = ((JavaObjectRef)value).getId();
} }
value = value.dereference(snapshot, field); value = value.dereference(snapshot, field);
if (value.isHeapAllocated()) { if (value.isHeapAllocated() &&
clazz.getLoader() == snapshot.getNullThing()) {
// static fields are only roots if they are in classes
// loaded by the root classloader.
JavaHeapObject ho = (JavaHeapObject) value; JavaHeapObject ho = (JavaHeapObject) value;
String s = "Static reference from " + clazz.getName() String s = "Static reference from " + clazz.getName()
+ "." + field.getName(); + "." + field.getName();
......
...@@ -4,7 +4,10 @@ package com.sun.tracing; ...@@ -4,7 +4,10 @@ package com.sun.tracing;
import java.util.HashSet; import java.util.HashSet;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.logging.Logger; import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.security.action.GetPropertyAction;
import sun.tracing.NullProviderFactory; import sun.tracing.NullProviderFactory;
import sun.tracing.PrintStreamProviderFactory; import sun.tracing.PrintStreamProviderFactory;
...@@ -52,23 +55,17 @@ public abstract class ProviderFactory { ...@@ -52,23 +55,17 @@ public abstract class ProviderFactory {
HashSet<ProviderFactory> factories = new HashSet<ProviderFactory>(); HashSet<ProviderFactory> factories = new HashSet<ProviderFactory>();
// Try to instantiate a DTraceProviderFactory // Try to instantiate a DTraceProviderFactory
String prop = null; String prop = AccessController.doPrivileged(
try { prop = System.getProperty("com.sun.tracing.dtrace"); } new GetPropertyAction("com.sun.tracing.dtrace"));
catch (java.security.AccessControlException e) {
Logger.getAnonymousLogger().fine(
"Cannot access property com.sun.tracing.dtrace");
}
if ( (prop == null || !prop.equals("disable")) && if ( (prop == null || !prop.equals("disable")) &&
DTraceProviderFactory.isSupported() ) { DTraceProviderFactory.isSupported() ) {
factories.add(new DTraceProviderFactory()); factories.add(new DTraceProviderFactory());
} }
// Try to instantiate an output stream factory // Try to instantiate an output stream factory
try { prop = System.getProperty("sun.tracing.stream"); } prop = AccessController.doPrivileged(
catch (java.security.AccessControlException e) { new GetPropertyAction("sun.tracing.stream"));
Logger.getAnonymousLogger().fine(
"Cannot access property sun.tracing.stream");
}
if (prop != null) { if (prop != null) {
for (String spec : prop.split(",")) { for (String spec : prop.split(",")) {
PrintStream ps = getPrintStreamFromSpec(spec); PrintStream ps = getPrintStreamFromSpec(spec);
...@@ -89,22 +86,29 @@ public abstract class ProviderFactory { ...@@ -89,22 +86,29 @@ public abstract class ProviderFactory {
} }
} }
private static PrintStream getPrintStreamFromSpec(String spec) { private static PrintStream getPrintStreamFromSpec(final String spec) {
try { try {
// spec is in the form of <class>.<field>, where <class> is // spec is in the form of <class>.<field>, where <class> is
// a fully specified class name, and <field> is a static member // a fully specified class name, and <field> is a static member
// in that class. The <field> must be a 'PrintStream' or subtype // in that class. The <field> must be a 'PrintStream' or subtype
// in order to be used. // in order to be used.
int fieldpos = spec.lastIndexOf('.'); final int fieldpos = spec.lastIndexOf('.');
Class<?> cls = Class.forName(spec.substring(0, fieldpos)); final Class<?> cls = Class.forName(spec.substring(0, fieldpos));
Field f = cls.getField(spec.substring(fieldpos + 1));
Class<?> fieldType = f.getType(); Field f = AccessController.doPrivileged(new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return cls.getField(spec.substring(fieldpos + 1));
}
});
return (PrintStream)f.get(null); return (PrintStream)f.get(null);
} catch (Exception e) { } catch (ClassNotFoundException e) {
Logger.getAnonymousLogger().warning( throw new AssertionError(e);
"Could not parse sun.tracing.stream property: " + e); } catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (PrivilegedActionException e) {
throw new AssertionError(e);
} }
return null;
} }
} }
...@@ -175,15 +175,8 @@ import sun.security.util.SecurityConstants; ...@@ -175,15 +175,8 @@ import sun.security.util.SecurityConstants;
public abstract class ClassLoader { public abstract class ClassLoader {
private static native void registerNatives(); private static native void registerNatives();
// Set of classes which are registered as parallel capable class loaders
private static final Set<Class<? extends ClassLoader>> parallelLoaders
= Collections.newSetFromMap(Collections.synchronizedMap
(new WeakHashMap<Class<? extends ClassLoader>, Boolean>()));
static { static {
registerNatives(); registerNatives();
parallelLoaders.add(ClassLoader.class);
} }
// The parent class loader for delegation // The parent class loader for delegation
...@@ -191,6 +184,52 @@ public abstract class ClassLoader { ...@@ -191,6 +184,52 @@ public abstract class ClassLoader {
// must be added *after* it. // must be added *after* it.
private final ClassLoader parent; private final ClassLoader parent;
/**
* Encapsulates the set of parallel capable loader types.
*/
private static class ParallelLoaders {
private ParallelLoaders() {}
// the set of parallel capable loader types
private static final Set<Class<? extends ClassLoader>> loaderTypes =
Collections.newSetFromMap(
new WeakHashMap<Class<? extends ClassLoader>, Boolean>());
static {
synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
}
/**
* Registers the given class loader type as parallel capabale.
* Returns {@code true} is successfully registered; {@code false} if
* loader's super class is not registered.
*/
static boolean register(Class<? extends ClassLoader> c) {
synchronized (loaderTypes) {
if (loaderTypes.contains(c.getSuperclass())) {
// register the class loader as parallel capable
// if and only if all of its super classes are.
// Note: given current classloading sequence, if
// the immediate super class is parallel capable,
// all the super classes higher up must be too.
loaderTypes.add(c);
return true;
} else {
return false;
}
}
}
/**
* Returns {@code true} if the given class loader type is
* registered as parallel capable.
*/
static boolean isRegistered(Class<? extends ClassLoader> c) {
synchronized (loaderTypes) {
return loaderTypes.contains(c);
}
}
}
// Maps class name to the corresponding lock object when the current // Maps class name to the corresponding lock object when the current
// class loader is parallel capable. // class loader is parallel capable.
// Note: VM also uses this field to decide if the current class loader // Note: VM also uses this field to decide if the current class loader
...@@ -237,7 +276,7 @@ public abstract class ClassLoader { ...@@ -237,7 +276,7 @@ public abstract class ClassLoader {
private ClassLoader(Void unused, ClassLoader parent) { private ClassLoader(Void unused, ClassLoader parent) {
this.parent = parent; this.parent = parent;
if (parallelLoaders.contains(this.getClass())) { if (ParallelLoaders.isRegistered(this.getClass())) {
parallelLockMap = new ConcurrentHashMap<String, Object>(); parallelLockMap = new ConcurrentHashMap<String, Object>();
package2certs = new ConcurrentHashMap<String, Certificate[]>(); package2certs = new ConcurrentHashMap<String, Certificate[]>();
domains = domains =
...@@ -1194,24 +1233,7 @@ public abstract class ClassLoader { ...@@ -1194,24 +1233,7 @@ public abstract class ClassLoader {
* @since 1.7 * @since 1.7
*/ */
protected static boolean registerAsParallelCapable() { protected static boolean registerAsParallelCapable() {
Class<? extends ClassLoader> caller = getCaller(1); return ParallelLoaders.register(getCaller(1));
Class superCls = caller.getSuperclass();
boolean result = false;
// Explicit synchronization needed for composite action
synchronized (parallelLoaders) {
if (!parallelLoaders.contains(caller)) {
if (parallelLoaders.contains(superCls)) {
// register the immediate caller as parallel capable
// if and only if all of its super classes are.
// Note: given current classloading sequence, if
// the immediate super class is parallel capable,
// all the super classes higher up must be too.
result = true;
parallelLoaders.add(caller);
}
} else result = true;
}
return result;
} }
/** /**
...@@ -2174,4 +2196,3 @@ class SystemClassLoaderAction ...@@ -2174,4 +2196,3 @@ class SystemClassLoaderAction
return sys; return sys;
} }
} }
...@@ -619,6 +619,20 @@ public final class System { ...@@ -619,6 +619,20 @@ public final class System {
return props; return props;
} }
/**
* Returns the system-dependent line separator string. It always
* returns the same value - the initial value of the {@linkplain
* #getProperty(String) system property} {@code line.separator}.
*
* <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
* Windows systems it returns {@code "\r\n"}.
*/
public static String lineSeparator() {
return lineSeparator;
}
private static String lineSeparator;
/** /**
* Sets the system properties to the <code>Properties</code> * Sets the system properties to the <code>Properties</code>
* argument. * argument.
...@@ -1104,6 +1118,7 @@ public final class System { ...@@ -1104,6 +1118,7 @@ public final class System {
private static void initializeSystemClass() { private static void initializeSystemClass() {
props = new Properties(); props = new Properties();
initProperties(props); initProperties(props);
lineSeparator = props.getProperty("line.separator");
sun.misc.Version.init(); sun.misc.Version.init();
// Workaround until DownloadManager initialization is revisited. // Workaround until DownloadManager initialization is revisited.
...@@ -1192,7 +1207,7 @@ public final class System { ...@@ -1192,7 +1207,7 @@ public final class System {
} }
/* returns the class of the caller. */ /* returns the class of the caller. */
static Class getCallerClass() { static Class<?> getCallerClass() {
// NOTE use of more generic Reflection.getCallerClass() // NOTE use of more generic Reflection.getCallerClass()
return Reflection.getCallerClass(3); return Reflection.getCallerClass(3);
} }
......
...@@ -30,6 +30,7 @@ import java.util.List; ...@@ -30,6 +30,7 @@ import java.util.List;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.io.IOException; import java.io.IOException;
import sun.util.logging.PlatformLogger;
/** /**
* CookieManager provides a concrete implementation of {@link CookieHandler}, * CookieManager provides a concrete implementation of {@link CookieHandler},
...@@ -263,6 +264,7 @@ public class CookieManager extends CookieHandler ...@@ -263,6 +264,7 @@ public class CookieManager extends CookieHandler
if (cookieJar == null) if (cookieJar == null)
return; return;
PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
for (String headerKey : responseHeaders.keySet()) { for (String headerKey : responseHeaders.keySet()) {
// RFC 2965 3.2.2, key must be 'Set-Cookie2' // RFC 2965 3.2.2, key must be 'Set-Cookie2'
// we also accept 'Set-Cookie' here for backward compatibility // we also accept 'Set-Cookie' here for backward compatibility
...@@ -277,7 +279,16 @@ public class CookieManager extends CookieHandler ...@@ -277,7 +279,16 @@ public class CookieManager extends CookieHandler
for (String headerValue : responseHeaders.get(headerKey)) { for (String headerValue : responseHeaders.get(headerKey)) {
try { try {
List<HttpCookie> cookies = HttpCookie.parse(headerValue); List<HttpCookie> cookies;
try {
cookies = HttpCookie.parse(headerValue);
} catch (IllegalArgumentException e) {
// Bogus header, make an empty list and log the error
cookies = java.util.Collections.EMPTY_LIST;
if (logger.isLoggable(PlatformLogger.SEVERE)) {
logger.severe("Invalid cookie for " + uri + ": " + headerValue);
}
}
for (HttpCookie cookie : cookies) { for (HttpCookie cookie : cookies) {
if (cookie.getPath() == null) { if (cookie.getPath() == null) {
// If no path is specified, then by default // If no path is specified, then by default
......
...@@ -1036,7 +1036,7 @@ public final class HttpCookie implements Cloneable { ...@@ -1036,7 +1036,7 @@ public final class HttpCookie implements Cloneable {
int version = Integer.parseInt(attrValue); int version = Integer.parseInt(attrValue);
cookie.setVersion(version); cookie.setVersion(version);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
throw new IllegalArgumentException("Illegal cookie version attribute"); // Just ignore bogus version, it will default to 0 or 1
} }
} }
}); });
...@@ -1147,12 +1147,15 @@ public final class HttpCookie implements Cloneable { ...@@ -1147,12 +1147,15 @@ public final class HttpCookie implements Cloneable {
} }
private static String stripOffSurroundingQuote(String str) { private static String stripOffSurroundingQuote(String str) {
if (str != null && str.length() > 0 && if (str != null && str.length() > 2 &&
str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') { str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') {
return str.substring(1, str.length() - 1); return str.substring(1, str.length() - 1);
} else {
return str;
} }
if (str != null && str.length() > 2 &&
str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'') {
return str.substring(1, str.length() - 1);
}
return str;
} }
private static boolean equalsIgnoreCase(String s, String t) { private static boolean equalsIgnoreCase(String s, String t) {
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
package java.nio.channels; package java.nio.channels;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.nio.channels.spi.SelectorProvider; import java.nio.channels.spi.SelectorProvider;
import java.util.Set; import java.util.Set;
...@@ -202,7 +203,7 @@ import java.util.Set; ...@@ -202,7 +203,7 @@ import java.util.Set;
* @see SelectionKey * @see SelectionKey
*/ */
public abstract class Selector { public abstract class Selector implements Closeable {
/** /**
* Initializes a new instance of this class. * Initializes a new instance of this class.
......
...@@ -2552,9 +2552,6 @@ public final class Formatter implements Closeable, Flushable { ...@@ -2552,9 +2552,6 @@ public final class Formatter implements Closeable, Flushable {
private boolean dt = false; private boolean dt = false;
private char c; private char c;
// cache the line separator
private String ls;
private int index(String s) { private int index(String s) {
if (s != null) { if (s != null) {
try { try {
...@@ -2702,9 +2699,7 @@ public final class Formatter implements Closeable, Flushable { ...@@ -2702,9 +2699,7 @@ public final class Formatter implements Closeable, Flushable {
printHashCode(arg); printHashCode(arg);
break; break;
case Conversion.LINE_SEPARATOR: case Conversion.LINE_SEPARATOR:
if (ls == null) a.append(System.lineSeparator());
ls = System.getProperty("line.separator");
a.append(ls);
break; break;
case Conversion.PERCENT_SIGN: case Conversion.PERCENT_SIGN:
a.append('%'); a.append('%');
......
...@@ -318,7 +318,7 @@ class Deflater { ...@@ -318,7 +318,7 @@ class Deflater {
/** /**
* Compresses the input data and fills specified buffer with compressed * Compresses the input data and fills specified buffer with compressed
* data. Returns actual number of bytes of compressed data. A return value * data. Returns actual number of bytes of compressed data. A return value
* of 0 indicates that {@link needsInput() needsInput} should be called * of 0 indicates that {@link #needsInput() needsInput} should be called
* in order to determine if more input data is required. * in order to determine if more input data is required.
* *
* <p>This method uses {@link #NO_FLUSH} as its compression flush mode. * <p>This method uses {@link #NO_FLUSH} as its compression flush mode.
...@@ -339,7 +339,7 @@ class Deflater { ...@@ -339,7 +339,7 @@ class Deflater {
/** /**
* Compresses the input data and fills specified buffer with compressed * Compresses the input data and fills specified buffer with compressed
* data. Returns actual number of bytes of compressed data. A return value * data. Returns actual number of bytes of compressed data. A return value
* of 0 indicates that {@link needsInput() needsInput} should be called * of 0 indicates that {@link #needsInput() needsInput} should be called
* in order to determine if more input data is required. * in order to determine if more input data is required.
* *
* <p>This method uses {@link #NO_FLUSH} as its compression flush mode. * <p>This method uses {@link #NO_FLUSH} as its compression flush mode.
......
...@@ -66,7 +66,7 @@ class DeflaterOutputStream extends FilterOutputStream { ...@@ -66,7 +66,7 @@ class DeflaterOutputStream extends FilterOutputStream {
* @param def the compressor ("deflater") * @param def the compressor ("deflater")
* @param size the output buffer size * @param size the output buffer size
* @param syncFlush * @param syncFlush
* if {@code true} the {@link flush()} method of this * if {@code true} the {@link #flush()} method of this
* instance flushes the compressor with flush mode * instance flushes the compressor with flush mode
* {@link Deflater#SYNC_FLUSH} before flushing the output * {@link Deflater#SYNC_FLUSH} before flushing the output
* stream, otherwise only flushes the output stream * stream, otherwise only flushes the output stream
...@@ -114,7 +114,7 @@ class DeflaterOutputStream extends FilterOutputStream { ...@@ -114,7 +114,7 @@ class DeflaterOutputStream extends FilterOutputStream {
* @param out the output stream * @param out the output stream
* @param def the compressor ("deflater") * @param def the compressor ("deflater")
* @param syncFlush * @param syncFlush
* if {@code true} the {@link flush()} method of this * if {@code true} the {@link #flush()} method of this
* instance flushes the compressor with flush mode * instance flushes the compressor with flush mode
* {@link Deflater#SYNC_FLUSH} before flushing the output * {@link Deflater#SYNC_FLUSH} before flushing the output
* stream, otherwise only flushes the output stream * stream, otherwise only flushes the output stream
...@@ -151,7 +151,7 @@ class DeflaterOutputStream extends FilterOutputStream { ...@@ -151,7 +151,7 @@ class DeflaterOutputStream extends FilterOutputStream {
* *
* @param out the output stream * @param out the output stream
* @param syncFlush * @param syncFlush
* if {@code true} the {@link flush()} method of this * if {@code true} the {@link #flush()} method of this
* instance flushes the compressor with flush mode * instance flushes the compressor with flush mode
* {@link Deflater#SYNC_FLUSH} before flushing the output * {@link Deflater#SYNC_FLUSH} before flushing the output
* stream, otherwise only flushes the output stream * stream, otherwise only flushes the output stream
...@@ -262,10 +262,10 @@ class DeflaterOutputStream extends FilterOutputStream { ...@@ -262,10 +262,10 @@ class DeflaterOutputStream extends FilterOutputStream {
/** /**
* Flushes the compressed output stream. * Flushes the compressed output stream.
* *
* If {@link DeflaterOutputStream(OutputStream, Deflater, int, boolean) * If {@link #DeflaterOutputStream(OutputStream, Deflater, int, boolean)
* syncFlush} is {@code true} when this compressed output stream is * syncFlush} is {@code true} when this compressed output stream is
* constructed this method flushes the underlying {@code compressor} * constructed, this method first flushes the underlying {@code compressor}
* first with the flush mode {@link Deflater#SYNC_FLUSH} to force * with the flush mode {@link Deflater#SYNC_FLUSH} to force
* all pending data to be flushed out to the output stream and then * all pending data to be flushed out to the output stream and then
* flushes the output stream. Otherwise this method only flushes the * flushes the output stream. Otherwise this method only flushes the
* output stream without flushing the {@code compressor}. * output stream without flushing the {@code compressor}.
......
/* /*
* Copyright 1999-2005 Sun Microsystems, Inc. All Rights Reserved. * Copyright 1999-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -198,6 +198,8 @@ public class InitialContext implements Context { ...@@ -198,6 +198,8 @@ public class InitialContext implements Context {
* *
* <p> This constructor will not modify <tt>environment</tt> * <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone. * or save a reference to it, but may save a clone.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
* *
* @param environment * @param environment
* environment used to create the initial context. * environment used to create the initial context.
......
/* /*
* Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. * Copyright 1999-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -86,6 +86,8 @@ public class InitialDirContext extends InitialContext implements DirContext { ...@@ -86,6 +86,8 @@ public class InitialDirContext extends InitialContext implements DirContext {
* *
* <p> This constructor will not modify <tt>environment</tt> * <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone. * or save a reference to it, but may save a clone.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
* *
* @param environment * @param environment
* environment used to create the initial DirContext. * environment used to create the initial DirContext.
......
/* /*
* Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. * Copyright 1999-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -110,6 +110,8 @@ public class InitialLdapContext extends InitialDirContext implements LdapContext ...@@ -110,6 +110,8 @@ public class InitialLdapContext extends InitialDirContext implements LdapContext
* *
* <p> This constructor will not modify its parameters or * <p> This constructor will not modify its parameters or
* save references to them, but may save a clone or copy. * save references to them, but may save a clone or copy.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
* *
* <p> <tt>connCtls</tt> is used as the underlying context instance's * <p> <tt>connCtls</tt> is used as the underlying context instance's
* connection request controls. See the class description * connection request controls. See the class description
......
...@@ -40,7 +40,6 @@ import java.security.PrivilegedExceptionAction; ...@@ -40,7 +40,6 @@ import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException; import java.security.PrivilegedActionException;
import java.security.ProtectionDomain; import java.security.ProtectionDomain;
import sun.security.util.ResourcesMgr; import sun.security.util.ResourcesMgr;
import sun.security.util.SecurityConstants;
/** /**
* <p> A <code>Subject</code> represents a grouping of related information * <p> A <code>Subject</code> represents a grouping of related information
...@@ -239,7 +238,7 @@ public final class Subject implements java.io.Serializable { ...@@ -239,7 +238,7 @@ public final class Subject implements java.io.Serializable {
public void setReadOnly() { public void setReadOnly() {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(new AuthPermission("setReadOnly")); sm.checkPermission(AuthPermissionHolder.SET_READ_ONLY_PERMISSION);
} }
this.readOnly = true; this.readOnly = true;
...@@ -285,7 +284,7 @@ public final class Subject implements java.io.Serializable { ...@@ -285,7 +284,7 @@ public final class Subject implements java.io.Serializable {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(new AuthPermission("getSubject")); sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION);
} }
if (acc == null) { if (acc == null) {
...@@ -343,7 +342,7 @@ public final class Subject implements java.io.Serializable { ...@@ -343,7 +342,7 @@ public final class Subject implements java.io.Serializable {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PERMISSION); sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
} }
if (action == null) if (action == null)
throw new NullPointerException throw new NullPointerException
...@@ -402,7 +401,7 @@ public final class Subject implements java.io.Serializable { ...@@ -402,7 +401,7 @@ public final class Subject implements java.io.Serializable {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PERMISSION); sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
} }
if (action == null) if (action == null)
...@@ -456,7 +455,7 @@ public final class Subject implements java.io.Serializable { ...@@ -456,7 +455,7 @@ public final class Subject implements java.io.Serializable {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION); sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
} }
if (action == null) if (action == null)
...@@ -520,7 +519,7 @@ public final class Subject implements java.io.Serializable { ...@@ -520,7 +519,7 @@ public final class Subject implements java.io.Serializable {
java.lang.SecurityManager sm = System.getSecurityManager(); java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) { if (sm != null) {
sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION); sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
} }
if (action == null) if (action == null)
...@@ -1044,16 +1043,13 @@ public final class Subject implements java.io.Serializable { ...@@ -1044,16 +1043,13 @@ public final class Subject implements java.io.Serializable {
if (sm != null) { if (sm != null) {
switch (which) { switch (which) {
case Subject.PRINCIPAL_SET: case Subject.PRINCIPAL_SET:
sm.checkPermission(new AuthPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
("modifyPrincipals"));
break; break;
case Subject.PUB_CREDENTIAL_SET: case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission(new AuthPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
("modifyPublicCredentials"));
break; break;
default: default:
sm.checkPermission(new AuthPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
("modifyPrivateCredentials"));
break; break;
} }
} }
...@@ -1073,16 +1069,13 @@ public final class Subject implements java.io.Serializable { ...@@ -1073,16 +1069,13 @@ public final class Subject implements java.io.Serializable {
if (sm != null) { if (sm != null) {
switch (which) { switch (which) {
case Subject.PRINCIPAL_SET: case Subject.PRINCIPAL_SET:
sm.checkPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
(new AuthPermission("modifyPrincipals"));
break; break;
case Subject.PUB_CREDENTIAL_SET: case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
(new AuthPermission("modifyPublicCredentials"));
break; break;
default: default:
sm.checkPermission sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
(new AuthPermission("modifyPrivateCredentials"));
break; break;
} }
} }
...@@ -1405,4 +1398,27 @@ public final class Subject implements java.io.Serializable { ...@@ -1405,4 +1398,27 @@ public final class Subject implements java.io.Serializable {
return set.add(o); return set.add(o);
} }
} }
static class AuthPermissionHolder {
static final AuthPermission DO_AS_PERMISSION =
new AuthPermission("doAs");
static final AuthPermission DO_AS_PRIVILEGED_PERMISSION =
new AuthPermission("doAsPrivileged");
static final AuthPermission SET_READ_ONLY_PERMISSION =
new AuthPermission("setReadOnly");
static final AuthPermission GET_SUBJECT_PERMISSION =
new AuthPermission("getSubject");
static final AuthPermission MODIFY_PRINCIPALS_PERMISSION =
new AuthPermission("modifyPrincipals");
static final AuthPermission MODIFY_PUBLIC_CREDENTIALS_PERMISSION =
new AuthPermission("modifyPublicCredentials");
static final AuthPermission MODIFY_PRIVATE_CREDENTIALS_PERMISSION =
new AuthPermission("modifyPrivateCredentials");
}
} }
/* /*
* Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved. * Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -678,7 +678,7 @@ public interface GSSContext { ...@@ -678,7 +678,7 @@ public interface GSSContext {
* are not definitive then the method will attempt to treat all * are not definitive then the method will attempt to treat all
* available bytes as part of the token.<p> * available bytes as part of the token.<p>
* *
* Other than the possible blocking behaviour described above, this * Other than the possible blocking behavior described above, this
* method is equivalent to the byte array based {@link #unwrap(byte[], * method is equivalent to the byte array based {@link #unwrap(byte[],
* int, int, MessageProp) unwrap} method.<p> * int, int, MessageProp) unwrap} method.<p>
* *
...@@ -826,7 +826,7 @@ public interface GSSContext { ...@@ -826,7 +826,7 @@ public interface GSSContext {
* are not definitive then the method will attempt to treat all * are not definitive then the method will attempt to treat all
* available bytes as part of the token.<p> * available bytes as part of the token.<p>
* *
* Other than the possible blocking behaviour described above, this * Other than the possible blocking behavior described above, this
* method is equivalent to the byte array based {@link #verifyMIC(byte[], * method is equivalent to the byte array based {@link #verifyMIC(byte[],
* int, int, byte[], int, int, MessageProp) verifyMIC} method.<p> * int, int, byte[], int, int, MessageProp) verifyMIC} method.<p>
* *
...@@ -917,7 +917,7 @@ public interface GSSContext { ...@@ -917,7 +917,7 @@ public interface GSSContext {
* getMutualAuthState} method.<p> * getMutualAuthState} method.<p>
* *
* @param state a boolean value indicating whether mutual * @param state a boolean value indicating whether mutual
* authentication shouls be used or not. * authentication should be used or not.
* @see #getMutualAuthState() * @see #getMutualAuthState()
* *
* @throws GSSException containing the following * @throws GSSException containing the following
...@@ -928,7 +928,7 @@ public interface GSSContext { ...@@ -928,7 +928,7 @@ public interface GSSContext {
/** /**
* Requests that replay detection be enabled for the * Requests that replay detection be enabled for the
* per-message security services after context establishemnt. This * per-message security services after context establishment. This
* request can only be made on the context initiator's side and it has * request can only be made on the context initiator's side and it has
* to be done prior to the first call to * to be done prior to the first call to
* <code>initSecContext</code>. During context establishment replay * <code>initSecContext</code>. During context establishment replay
...@@ -958,7 +958,7 @@ public interface GSSContext { ...@@ -958,7 +958,7 @@ public interface GSSContext {
/** /**
* Requests that sequence checking be enabled for the * Requests that sequence checking be enabled for the
* per-message security services after context establishemnt. This * per-message security services after context establishment. This
* request can only be made on the context initiator's side and it has * request can only be made on the context initiator's side and it has
* to be done prior to the first call to * to be done prior to the first call to
* <code>initSecContext</code>. During context establishment sequence * <code>initSecContext</code>. During context establishment sequence
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
package sun.net.www.protocol.http.spnego; package sun.net.www.protocol.http.spnego;
import com.sun.security.jgss.ExtendedGSSContext;
import java.io.IOException; import java.io.IOException;
import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSContext;
...@@ -100,15 +101,10 @@ public class NegotiatorImpl extends Negotiator { ...@@ -100,15 +101,10 @@ public class NegotiatorImpl extends Negotiator {
null, null,
GSSContext.DEFAULT_LIFETIME); GSSContext.DEFAULT_LIFETIME);
// In order to support credential delegation in HTTP/SPNEGO, // Always respect delegation policy in HTTP/SPNEGO.
// we always request it before initSecContext. The current if (context instanceof ExtendedGSSContext) {
// implementation will check the OK-AS-DELEGATE flag inside ((ExtendedGSSContext)context).requestDelegPolicy(true);
// the service ticket of the web server, and only enable }
// delegation when this flag is set. This check is only
// performed when the GSS caller is CALLER_HTTP_NEGOTIATE,
// so all other normal GSS-API calls are not affected.
context.requestCredDeleg(true);
oneToken = context.initSecContext(new byte[0], 0, 0); oneToken = context.initSecContext(new byte[0], 0, 0);
} }
......
...@@ -89,7 +89,8 @@ import com.sun.security.jgss.*; ...@@ -89,7 +89,8 @@ import com.sun.security.jgss.*;
*/ */
class GSSContextImpl implements ExtendedGSSContext { class GSSContextImpl implements ExtendedGSSContext {
private GSSManagerImpl gssManager = null; private final GSSManagerImpl gssManager;
private final boolean initiator;
// private flags for the context state // private flags for the context state
private static final int PRE_INIT = 1; private static final int PRE_INIT = 1;
...@@ -99,14 +100,12 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -99,14 +100,12 @@ class GSSContextImpl implements ExtendedGSSContext {
// instance variables // instance variables
private int currentState = PRE_INIT; private int currentState = PRE_INIT;
private boolean initiator;
private GSSContextSpi mechCtxt = null; private GSSContextSpi mechCtxt = null;
private Oid mechOid = null; private Oid mechOid = null;
private ObjectIdentifier objId = null; private ObjectIdentifier objId = null;
private GSSCredentialImpl myCred = null; private GSSCredentialImpl myCred = null;
private GSSCredentialImpl delegCred = null;
private GSSNameImpl srcName = null; private GSSNameImpl srcName = null;
private GSSNameImpl targName = null; private GSSNameImpl targName = null;
...@@ -121,6 +120,7 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -121,6 +120,7 @@ class GSSContextImpl implements ExtendedGSSContext {
private boolean reqSequenceDetState = true; private boolean reqSequenceDetState = true;
private boolean reqCredDelegState = false; private boolean reqCredDelegState = false;
private boolean reqAnonState = false; private boolean reqAnonState = false;
private boolean reqDelegPolicyState = false;
/** /**
* Creates a GSSContextImp on the context initiator's side. * Creates a GSSContextImp on the context initiator's side.
...@@ -221,6 +221,7 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -221,6 +221,7 @@ class GSSContextImpl implements ExtendedGSSContext {
mechCtxt.requestSequenceDet(reqSequenceDetState); mechCtxt.requestSequenceDet(reqSequenceDetState);
mechCtxt.requestAnonymity(reqAnonState); mechCtxt.requestAnonymity(reqAnonState);
mechCtxt.setChannelBinding(channelBindings); mechCtxt.setChannelBinding(channelBindings);
mechCtxt.requestDelegPolicy(reqDelegPolicyState);
objId = new ObjectIdentifier(mechOid.toString()); objId = new ObjectIdentifier(mechOid.toString());
...@@ -465,42 +466,42 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -465,42 +466,42 @@ class GSSContextImpl implements ExtendedGSSContext {
} }
public void requestMutualAuth(boolean state) throws GSSException { public void requestMutualAuth(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqMutualAuthState = state; reqMutualAuthState = state;
} }
public void requestReplayDet(boolean state) throws GSSException { public void requestReplayDet(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqReplayDetState = state; reqReplayDetState = state;
} }
public void requestSequenceDet(boolean state) throws GSSException { public void requestSequenceDet(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqSequenceDetState = state; reqSequenceDetState = state;
} }
public void requestCredDeleg(boolean state) throws GSSException { public void requestCredDeleg(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqCredDelegState = state; reqCredDelegState = state;
} }
public void requestAnonymity(boolean state) throws GSSException { public void requestAnonymity(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqAnonState = state; reqAnonState = state;
} }
public void requestConf(boolean state) throws GSSException { public void requestConf(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqConfState = state; reqConfState = state;
} }
public void requestInteg(boolean state) throws GSSException { public void requestInteg(boolean state) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqIntegState = state; reqIntegState = state;
} }
public void requestLifetime(int lifetime) throws GSSException { public void requestLifetime(int lifetime) throws GSSException {
if (mechCtxt == null) if (mechCtxt == null && initiator)
reqLifetime = lifetime; reqLifetime = lifetime;
} }
...@@ -630,6 +631,8 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -630,6 +631,8 @@ class GSSContextImpl implements ExtendedGSSContext {
targName = null; targName = null;
} }
// ExtendedGSSContext methods:
@Override @Override
public Object inquireSecContext(InquireType type) throws GSSException { public Object inquireSecContext(InquireType type) throws GSSException {
SecurityManager security = System.getSecurityManager(); SecurityManager security = System.getSecurityManager();
...@@ -641,4 +644,18 @@ class GSSContextImpl implements ExtendedGSSContext { ...@@ -641,4 +644,18 @@ class GSSContextImpl implements ExtendedGSSContext {
} }
return mechCtxt.inquireSecContext(type); return mechCtxt.inquireSecContext(type);
} }
@Override
public void requestDelegPolicy(boolean state) throws GSSException {
if (mechCtxt == null && initiator)
reqDelegPolicyState = state;
}
@Override
public boolean getDelegPolicyState() {
if (mechCtxt != null)
return mechCtxt.getDelegPolicyState();
else
return reqDelegPolicyState;
}
} }
...@@ -85,32 +85,39 @@ abstract class InitialToken extends Krb5Token { ...@@ -85,32 +85,39 @@ abstract class InitialToken extends Krb5Token {
int size = CHECKSUM_LENGTH_SIZE + CHECKSUM_BINDINGS_SIZE + int size = CHECKSUM_LENGTH_SIZE + CHECKSUM_BINDINGS_SIZE +
CHECKSUM_FLAGS_SIZE; CHECKSUM_FLAGS_SIZE;
if (!tgt.isForwardable()) {
context.setCredDelegState(false);
context.setDelegPolicyState(false);
} else if (context.getCredDelegState()) {
if (context.getDelegPolicyState()) {
if (!serviceTicket.checkDelegate()) {
// delegation not permitted by server policy, mark it
context.setDelegPolicyState(false);
}
}
} else if (context.getDelegPolicyState()) {
if (serviceTicket.checkDelegate()) {
context.setCredDelegState(true);
} else {
context.setDelegPolicyState(false);
}
}
if (context.getCredDelegState()) { if (context.getCredDelegState()) {
if (context.getCaller() instanceof HttpCaller && KrbCred krbCred = null;
!serviceTicket.getFlags()[Krb5.TKT_OPTS_DELEGATE]) { CipherHelper cipherHelper =
// When the caller is HTTP/SPNEGO and OK-AS-DELEGATE context.getCipherHelper(serviceTicket.getSessionKey());
// is not present in the service ticket, delegation if (useNullKey(cipherHelper)) {
// is disabled. krbCred = new KrbCred(tgt, serviceTicket,
context.setCredDelegState(false); EncryptionKey.NULL_KEY);
} else if (!tgt.isForwardable()) {
// XXX log this resetting of delegation state
context.setCredDelegState(false);
} else { } else {
KrbCred krbCred = null; krbCred = new KrbCred(tgt, serviceTicket,
CipherHelper cipherHelper = serviceTicket.getSessionKey());
context.getCipherHelper(serviceTicket.getSessionKey());
if (useNullKey(cipherHelper)) {
krbCred = new KrbCred(tgt, serviceTicket,
EncryptionKey.NULL_KEY);
} else {
krbCred = new KrbCred(tgt, serviceTicket,
serviceTicket.getSessionKey());
}
krbCredMessage = krbCred.getMessage();
size += CHECKSUM_DELEG_OPT_SIZE +
CHECKSUM_DELEG_LGTH_SIZE +
krbCredMessage.length;
} }
krbCredMessage = krbCred.getMessage();
size += CHECKSUM_DELEG_OPT_SIZE +
CHECKSUM_DELEG_LGTH_SIZE +
krbCredMessage.length;
} }
checksumBytes = new byte[size]; checksumBytes = new byte[size];
...@@ -296,6 +303,7 @@ abstract class InitialToken extends Krb5Token { ...@@ -296,6 +303,7 @@ abstract class InitialToken extends Krb5Token {
return delegCreds; return delegCreds;
} }
// Only called by acceptor
public void setContextFlags(Krb5Context context) { public void setContextFlags(Krb5Context context) {
// default for cred delegation is false // default for cred delegation is false
if ((flags & CHECKSUM_DELEG_FLAG) > 0) if ((flags & CHECKSUM_DELEG_FLAG) > 0)
......
...@@ -78,6 +78,7 @@ class Krb5Context implements GSSContextSpi { ...@@ -78,6 +78,7 @@ class Krb5Context implements GSSContextSpi {
private boolean sequenceDetState = true; private boolean sequenceDetState = true;
private boolean confState = true; private boolean confState = true;
private boolean integState = true; private boolean integState = true;
private boolean delegPolicyState = false;
private int mySeqNumber; private int mySeqNumber;
private int peerSeqNumber; private int peerSeqNumber;
...@@ -299,6 +300,21 @@ class Krb5Context implements GSSContextSpi { ...@@ -299,6 +300,21 @@ class Krb5Context implements GSSContextSpi {
return sequenceDetState || replayDetState; return sequenceDetState || replayDetState;
} }
/**
* Requests that the deleg policy be respected.
*/
public final void requestDelegPolicy(boolean value) {
if (state == STATE_NEW && isInitiator())
delegPolicyState = value;
}
/**
* Is deleg policy respected?
*/
public final boolean getDelegPolicyState() {
return delegPolicyState;
}
/* /*
* Anonymity is a little different in that after an application * Anonymity is a little different in that after an application
* requests anonymity it will want to know whether the mechanism * requests anonymity it will want to know whether the mechanism
...@@ -422,6 +438,10 @@ class Krb5Context implements GSSContextSpi { ...@@ -422,6 +438,10 @@ class Krb5Context implements GSSContextSpi {
integState = state; integState = state;
} }
final void setDelegPolicyState(boolean state) {
delegPolicyState = state;
}
/** /**
* Sets the channel bindings to be used during context * Sets the channel bindings to be used during context
* establishment. * establishment.
......
...@@ -124,6 +124,8 @@ public interface GSSContextSpi { ...@@ -124,6 +124,8 @@ public interface GSSContextSpi {
public void requestInteg(boolean state) throws GSSException; public void requestInteg(boolean state) throws GSSException;
public void requestDelegPolicy(boolean state) throws GSSException;
public void setChannelBinding(ChannelBinding cb) throws GSSException; public void setChannelBinding(ChannelBinding cb) throws GSSException;
public boolean getCredDelegState(); public boolean getCredDelegState();
...@@ -136,6 +138,8 @@ public interface GSSContextSpi { ...@@ -136,6 +138,8 @@ public interface GSSContextSpi {
public boolean getAnonymityState(); public boolean getAnonymityState();
public boolean getDelegPolicyState();
public boolean isTransferable() throws GSSException; public boolean isTransferable() throws GSSException;
public boolean isProtReady(); public boolean isProtReady();
......
...@@ -63,6 +63,7 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -63,6 +63,7 @@ public class SpNegoContext implements GSSContextSpi {
private boolean sequenceDetState = true; private boolean sequenceDetState = true;
private boolean confState = true; private boolean confState = true;
private boolean integState = true; private boolean integState = true;
private boolean delegPolicyState = false;
private GSSNameSpi peerName = null; private GSSNameSpi peerName = null;
private GSSNameSpi myName = null; private GSSNameSpi myName = null;
...@@ -153,6 +154,14 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -153,6 +154,14 @@ public class SpNegoContext implements GSSContextSpi {
integState = value; integState = value;
} }
/**
* Requests that deleg policy be respected.
*/
public final void requestDelegPolicy(boolean value) throws GSSException {
if (state == STATE_NEW && isInitiator())
delegPolicyState = value;
}
/** /**
* Is integrity available? * Is integrity available?
*/ */
...@@ -160,6 +169,19 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -160,6 +169,19 @@ public class SpNegoContext implements GSSContextSpi {
return integState; return integState;
} }
/**
* Is deleg policy respected?
*/
public final boolean getDelegPolicyState() {
if (isInitiator() && mechContext != null &&
mechContext instanceof ExtendedGSSContext &&
(state == STATE_IN_PROCESS || state == STATE_DONE)) {
return ((ExtendedGSSContext)mechContext).getDelegPolicyState();
} else {
return delegPolicyState;
}
}
/** /**
* Requests that credential delegation be done during context * Requests that credential delegation be done during context
* establishment. * establishment.
...@@ -173,7 +195,7 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -173,7 +195,7 @@ public class SpNegoContext implements GSSContextSpi {
* Is credential delegation enabled? * Is credential delegation enabled?
*/ */
public final boolean getCredDelegState() { public final boolean getCredDelegState() {
if (mechContext != null && if (isInitiator() && mechContext != null &&
(state == STATE_IN_PROCESS || state == STATE_DONE)) { (state == STATE_IN_PROCESS || state == STATE_DONE)) {
return mechContext.getCredDelegState(); return mechContext.getCredDelegState();
} else { } else {
...@@ -201,30 +223,6 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -201,30 +223,6 @@ public class SpNegoContext implements GSSContextSpi {
return mutualAuthState; return mutualAuthState;
} }
final void setCredDelegState(boolean state) {
credDelegState = state;
}
final void setMutualAuthState(boolean state) {
mutualAuthState = state;
}
final void setReplayDetState(boolean state) {
replayDetState = state;
}
final void setSequenceDetState(boolean state) {
sequenceDetState = state;
}
final void setConfState(boolean state) {
confState = state;
}
final void setIntegState(boolean state) {
integState = state;
}
/** /**
* Returns the mechanism oid. * Returns the mechanism oid.
* *
...@@ -319,14 +317,9 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -319,14 +317,9 @@ public class SpNegoContext implements GSSContextSpi {
mechToken = GSS_initSecContext(null); mechToken = GSS_initSecContext(null);
errorCode = GSSException.DEFECTIVE_TOKEN; errorCode = GSSException.DEFECTIVE_TOKEN;
byte[] micToken = null;
if (!GSSUtil.useMSInterop()) {
// calculate MIC only in normal mode
micToken = generateMechListMIC(DER_mechTypes);
}
// generate SPNEGO token // generate SPNEGO token
initToken = new NegTokenInit(DER_mechTypes, getContextFlags(), initToken = new NegTokenInit(DER_mechTypes, getContextFlags(),
mechToken, micToken); mechToken, null);
if (DEBUG) { if (DEBUG) {
System.out.println("SpNegoContext.initSecContext: " + System.out.println("SpNegoContext.initSecContext: " +
"sending token of type = " + "sending token of type = " +
...@@ -585,15 +578,9 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -585,15 +578,9 @@ public class SpNegoContext implements GSSContextSpi {
"negotiated result = " + negoResult); "negotiated result = " + negoResult);
} }
// calculate MIC only in normal mode
byte[] micToken = null;
if (!GSSUtil.useMSInterop() && valid) {
micToken = generateMechListMIC(DER_mechTypes);
}
// generate SPNEGO token // generate SPNEGO token
NegTokenTarg targToken = new NegTokenTarg(negoResult.ordinal(), NegTokenTarg targToken = new NegTokenTarg(negoResult.ordinal(),
mech_wanted, accept_token, micToken); mech_wanted, accept_token, null);
if (DEBUG) { if (DEBUG) {
System.out.println("SpNegoContext.acceptSecContext: " + System.out.println("SpNegoContext.acceptSecContext: " +
"sending token of type = " + "sending token of type = " +
...@@ -653,6 +640,10 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -653,6 +640,10 @@ public class SpNegoContext implements GSSContextSpi {
throw gssException; throw gssException;
} }
if (state == STATE_DONE) {
// now set the context flags for acceptor
setContextFlags();
}
return retVal; return retVal;
} }
...@@ -703,36 +694,39 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -703,36 +694,39 @@ public class SpNegoContext implements GSSContextSpi {
return out; return out;
} }
// Only called on acceptor side. On the initiator side, most flags
// are already set at request. For those that might get chanegd,
// state from mech below is used.
private void setContextFlags() { private void setContextFlags() {
if (mechContext != null) { if (mechContext != null) {
// default for cred delegation is false // default for cred delegation is false
if (mechContext.getCredDelegState()) { if (mechContext.getCredDelegState()) {
setCredDelegState(true); credDelegState = true;
} }
// default for the following are true // default for the following are true
if (!mechContext.getMutualAuthState()) { if (!mechContext.getMutualAuthState()) {
setMutualAuthState(false); mutualAuthState = false;
} }
if (!mechContext.getReplayDetState()) { if (!mechContext.getReplayDetState()) {
setReplayDetState(false); replayDetState = false;
} }
if (!mechContext.getSequenceDetState()) { if (!mechContext.getSequenceDetState()) {
setSequenceDetState(false); sequenceDetState = false;
} }
if (!mechContext.getIntegState()) { if (!mechContext.getIntegState()) {
setIntegState(false); integState = false;
} }
if (!mechContext.getConfState()) { if (!mechContext.getConfState()) {
setConfState(false); confState = false;
} }
} }
} }
/** /**
* generate MIC on mechList * generate MIC on mechList. Not used at the moment.
*/ */
private byte[] generateMechListMIC(byte[] mechTypes) /*private byte[] generateMechListMIC(byte[] mechTypes)
throws GSSException { throws GSSException {
// sanity check the required input // sanity check the required input
...@@ -769,7 +763,7 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -769,7 +763,7 @@ public class SpNegoContext implements GSSContextSpi {
} }
} }
return mic; return mic;
} }*/
/** /**
* verify MIC on MechList * verify MIC on MechList
...@@ -837,6 +831,10 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -837,6 +831,10 @@ public class SpNegoContext implements GSSContextSpi {
mechContext.requestMutualAuth(mutualAuthState); mechContext.requestMutualAuth(mutualAuthState);
mechContext.requestReplayDet(replayDetState); mechContext.requestReplayDet(replayDetState);
mechContext.requestSequenceDet(sequenceDetState); mechContext.requestSequenceDet(sequenceDetState);
if (mechContext instanceof ExtendedGSSContext) {
((ExtendedGSSContext)mechContext).requestDelegPolicy(
delegPolicyState);
}
} }
// pass token // pass token
...@@ -1202,5 +1200,5 @@ public class SpNegoContext implements GSSContextSpi { ...@@ -1202,5 +1200,5 @@ public class SpNegoContext implements GSSContextSpi {
"inquireSecContext not supported by underlying mech."); "inquireSecContext not supported by underlying mech.");
} }
} }
} }
...@@ -57,6 +57,12 @@ public final class SpNegoMechFactory implements MechanismFactory { ...@@ -57,6 +57,12 @@ public final class SpNegoMechFactory implements MechanismFactory {
GSSName.NT_HOSTBASED_SERVICE, GSSName.NT_HOSTBASED_SERVICE,
GSSName.NT_EXPORT_NAME}; GSSName.NT_EXPORT_NAME};
// The default underlying mech of SPNEGO, must not be SPNEGO itself.
private static final Oid DEFAULT_SPNEGO_MECH_OID =
ProviderList.DEFAULT_MECH_OID.equals(GSS_SPNEGO_MECH_OID)?
GSSUtil.GSS_KRB5_MECH_OID:
ProviderList.DEFAULT_MECH_OID;
// Use an instance of a GSSManager whose provider list // Use an instance of a GSSManager whose provider list
// does not include native provider // does not include native provider
final GSSManagerImpl manager; final GSSManagerImpl manager;
...@@ -100,18 +106,27 @@ public final class SpNegoMechFactory implements MechanismFactory { ...@@ -100,18 +106,27 @@ public final class SpNegoMechFactory implements MechanismFactory {
availableMechs[j++] = mechs[i]; availableMechs[j++] = mechs[i];
} }
} }
// Move the preferred mech to first place
for (int i=0; i<availableMechs.length; i++) {
if (availableMechs[i].equals(DEFAULT_SPNEGO_MECH_OID)) {
if (i != 0) {
availableMechs[i] = availableMechs[0];
availableMechs[0] = DEFAULT_SPNEGO_MECH_OID;
}
break;
}
}
} }
public GSSNameSpi getNameElement(String nameStr, Oid nameType) public GSSNameSpi getNameElement(String nameStr, Oid nameType)
throws GSSException { throws GSSException {
// get NameElement for the default Mechanism return manager.getNameElement(
return manager.getNameElement(nameStr, nameType, null); nameStr, nameType, DEFAULT_SPNEGO_MECH_OID);
} }
public GSSNameSpi getNameElement(byte[] name, Oid nameType) public GSSNameSpi getNameElement(byte[] name, Oid nameType)
throws GSSException { throws GSSException {
// get NameElement for the default Mechanism return manager.getNameElement(name, nameType, DEFAULT_SPNEGO_MECH_OID);
return manager.getNameElement(name, nameType, null);
} }
public GSSCredentialSpi getCredentialElement(GSSNameSpi name, public GSSCredentialSpi getCredentialElement(GSSNameSpi name,
......
...@@ -549,6 +549,9 @@ class NativeGSSContext implements GSSContextSpi { ...@@ -549,6 +549,9 @@ class NativeGSSContext implements GSSContextSpi {
public void requestInteg(boolean state) throws GSSException { public void requestInteg(boolean state) throws GSSException {
changeFlags(GSS_C_INTEG_FLAG, state); changeFlags(GSS_C_INTEG_FLAG, state);
} }
public void requestDelegPolicy(boolean state) throws GSSException {
// Not supported, ignore
}
public void requestLifetime(int lifetime) throws GSSException { public void requestLifetime(int lifetime) throws GSSException {
if (isInitiator && pContext == 0) { if (isInitiator && pContext == 0) {
this.lifetime = lifetime; this.lifetime = lifetime;
...@@ -590,6 +593,9 @@ class NativeGSSContext implements GSSContextSpi { ...@@ -590,6 +593,9 @@ class NativeGSSContext implements GSSContextSpi {
public boolean getIntegState() { public boolean getIntegState() {
return checkFlags(GSS_C_INTEG_FLAG); return checkFlags(GSS_C_INTEG_FLAG);
} }
public boolean getDelegPolicyState() {
return false;
}
public int getLifetime() { public int getLifetime() {
return cStub.getContextTime(pContext); return cStub.getContextTime(pContext);
} }
......
...@@ -234,7 +234,19 @@ public class Credentials { ...@@ -234,7 +234,19 @@ public class Credentials {
* @return true if OK-AS_DELEGATE flag is set, otherwise, return false. * @return true if OK-AS_DELEGATE flag is set, otherwise, return false.
*/ */
public boolean checkDelegate() { public boolean checkDelegate() {
return (flags.get(Krb5.TKT_OPTS_DELEGATE)); return flags.get(Krb5.TKT_OPTS_DELEGATE);
}
/**
* Reset TKT_OPTS_DELEGATE to false, called at credentials acquirement
* when one of the cross-realm TGTs does not have the OK-AS-DELEGATE
* flag set. This info must be preservable and restorable through
* the Krb5Util.credsToTicket/ticketToCreds() methods so that even if
* the service ticket is cached it still remembers the cross-realm
* authentication result.
*/
public void resetDelegate() {
flags.set(Krb5.TKT_OPTS_DELEGATE, false);
} }
public Credentials renew() throws KrbException, IOException { public Credentials renew() throws KrbException, IOException {
......
/* /*
* Portions Copyright 2001-2004 Sun Microsystems, Inc. All Rights Reserved. * Portions Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -117,6 +117,7 @@ rs. ...@@ -117,6 +117,7 @@ rs.
// Get a list of realms to traverse // Get a list of realms to traverse
String[] realms = Realm.getRealmsList(localRealm, serviceRealm); String[] realms = Realm.getRealmsList(localRealm, serviceRealm);
boolean okAsDelegate = true;
if (realms == null || realms.length == 0) if (realms == null || realms.length == 0)
{ {
...@@ -194,6 +195,15 @@ rs. ...@@ -194,6 +195,15 @@ rs.
*/ */
newTgtRealm = newTgt.getServer().getInstanceComponent(); newTgtRealm = newTgt.getServer().getInstanceComponent();
if (okAsDelegate && !newTgt.checkDelegate()) {
if (DEBUG)
{
System.out.println(">>> Credentials acquireServiceCreds: " +
"global OK-AS-DELEGATE turned off at " +
newTgt.getServer());
}
okAsDelegate = false;
}
if (DEBUG) if (DEBUG)
{ {
...@@ -283,6 +293,9 @@ rs. ...@@ -283,6 +293,9 @@ rs.
System.out.println(">>> Credentials acquireServiceCreds: returning creds:"); System.out.println(">>> Credentials acquireServiceCreds: returning creds:");
Credentials.printDebug(theCreds); Credentials.printDebug(theCreds);
} }
if (!okAsDelegate) {
theCreds.resetDelegate();
}
return theCreds; return theCreds;
} }
throw new KrbApErrException(Krb5.KRB_AP_ERR_GEN_CRED, throw new KrbApErrException(Krb5.KRB_AP_ERR_GEN_CRED,
......
...@@ -44,7 +44,6 @@ import sun.security.util.*; ...@@ -44,7 +44,6 @@ import sun.security.util.*;
import sun.security.x509.AlgorithmId; import sun.security.x509.AlgorithmId;
import sun.security.x509.X509Key; import sun.security.x509.X509Key;
import sun.security.x509.X500Name; import sun.security.x509.X500Name;
import sun.security.x509.X500Signer;
/** /**
* A PKCS #10 certificate request is created and sent to a Certificate * A PKCS #10 certificate request is created and sent to a Certificate
...@@ -183,13 +182,13 @@ public class PKCS10 { ...@@ -183,13 +182,13 @@ public class PKCS10 {
* Create the signed certificate request. This will later be * Create the signed certificate request. This will later be
* retrieved in either string or binary format. * retrieved in either string or binary format.
* *
* @param requester identifies the signer (by X.500 name) * @param subject identifies the signer (by X.500 name).
* and provides the private key used to sign. * @param signature private key and signing algorithm to use.
* @exception IOException on errors. * @exception IOException on errors.
* @exception CertificateException on certificate handling errors. * @exception CertificateException on certificate handling errors.
* @exception SignatureException on signature handling errors. * @exception SignatureException on signature handling errors.
*/ */
public void encodeAndSign(X500Signer requester) public void encodeAndSign(X500Name subject, Signature signature)
throws CertificateException, IOException, SignatureException { throws CertificateException, IOException, SignatureException {
DerOutputStream out, scratch; DerOutputStream out, scratch;
byte[] certificateRequestInfo; byte[] certificateRequestInfo;
...@@ -198,7 +197,7 @@ public class PKCS10 { ...@@ -198,7 +197,7 @@ public class PKCS10 {
if (encoded != null) if (encoded != null)
throw new SignatureException("request is already signed"); throw new SignatureException("request is already signed");
subject = requester.getSigner(); this.subject = subject;
/* /*
* Encode cert request info, wrap in a sequence for signing * Encode cert request info, wrap in a sequence for signing
...@@ -217,14 +216,20 @@ public class PKCS10 { ...@@ -217,14 +216,20 @@ public class PKCS10 {
/* /*
* Sign it ... * Sign it ...
*/ */
requester.update(certificateRequestInfo, 0, signature.update(certificateRequestInfo, 0,
certificateRequestInfo.length); certificateRequestInfo.length);
sig = requester.sign(); sig = signature.sign();
/* /*
* Build guts of SIGNED macro * Build guts of SIGNED macro
*/ */
requester.getAlgorithmId().encode(scratch); // sig algorithm AlgorithmId algId = null;
try {
algId = AlgorithmId.getAlgorithmId(signature.getAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SignatureException(nsae);
}
algId.encode(scratch); // sig algorithm
scratch.putBitString(sig); // sig scratch.putBitString(sig); // sig
/* /*
......
/*
* Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.io.*;
import java.util.*;
import java.security.*;
/**
* An implementation of IdentityScope as a persistent identity
* database.
*
* @see Identity
* @see Key
*
* @author Benjamin Renaud
*/
public
class IdentityDatabase extends IdentityScope implements Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 4923799573357658384L;
/* Are we debugging? */
private static final boolean debug = false;
/* Are we printing out error messages? */
private static final boolean error = true;
/* The source file, if any, for this database.*/
File sourceFile;
/* The private representation of the database.*/
Hashtable<String, Identity> identities;
IdentityDatabase() throws InvalidParameterException {
this("restoring...");
}
/**
* Construct a new, empty database with a specified source file.
*
* @param file the source file.
*/
public IdentityDatabase(File file) throws InvalidParameterException {
this(file.getName());
sourceFile = file;
}
/**
* Construct a new, empty database.
*/
public IdentityDatabase(String name) throws InvalidParameterException {
super(name);
identities = new Hashtable<String, Identity>();
}
/**
* Initialize an identity database from a stream. The stream should
* contain data to initialized a serialized IdentityDatabase
* object.
*
* @param is the input stream from which to restore the database.
*
* @exception IOException if a stream IO exception occurs
*/
public static IdentityDatabase fromStream(InputStream is)
throws IOException {
IdentityDatabase db = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
db = (IdentityDatabase)ois.readObject();
} catch (ClassNotFoundException e) {
// this can't happen.
debug("This should not be happening.", e);
error(
"The version of the database is obsolete. Cannot initialize.");
} catch (InvalidClassException e) {
// this may happen in developers workspaces happen.
debug("This should not be happening.", e);
error("Unable to initialize system identity scope: " +
" InvalidClassException. \nThis is most likely due to " +
"a serialization versioning problem: a class used in " +
"key management was obsoleted");
} catch (StreamCorruptedException e) {
debug("The serialization stream is corrupted. Unable to load.", e);
error("Unable to initialize system identity scope." +
" StreamCorruptedException.");
}
if (db == null) {
db = new IdentityDatabase("uninitialized");
}
return db;
}
/**
* Initialize an IdentityDatabase from file.
*
* @param f the filename where the identity database is stored.
*
* @exception IOException a file-related exception occurs (e.g.
* the directory of the file passed does not exists, etc.
*
* @IOException if a file IO exception occurs.
*/
public static IdentityDatabase fromFile(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
IdentityDatabase edb = fromStream(fis);
edb.sourceFile = f;
return edb;
}
/**
* @return the number of identities in the database.
*/
public int size() {
return identities.size();
}
/**
* @param name the name of the identity to be retrieved.
*
* @return the identity named name, or null if there are
* no identities named name in the database.
*/
public Identity getIdentity(String name) {
Identity id = identities.get(name);
if (id instanceof Signer) {
localCheck("get.signer");
}
return id;
}
/**
* Get an identity by key.
*
* @param name the key of the identity to be retrieved.
*
* @return the identity with a given key, or null if there are no
* identities with that key in the database.
*/
public Identity getIdentity(PublicKey key) {
if (key == null) {
return null;
}
Enumeration<Identity> e = identities();
while (e.hasMoreElements()) {
Identity i = e.nextElement();
PublicKey k = i.getPublicKey();
if (k != null && keyEqual(k, key)) {
if (i instanceof Signer) {
localCheck("get.signer");
}
return i;
}
}
return null;
}
private boolean keyEqual(Key key1, Key key2) {
if (key1 == key2) {
return true;
} else {
return MessageDigest.isEqual(key1.getEncoded(), key2.getEncoded());
}
}
/**
* Adds an identity to the database.
*
* @param identity the identity to be added.
*
* @exception KeyManagementException if a name or key clash
* occurs, or if another exception occurs.
*/
public void addIdentity(Identity identity)
throws KeyManagementException {
localCheck("add.identity");
Identity byName = getIdentity(identity.getName());
Identity byKey = getIdentity(identity.getPublicKey());
String msg = null;
if (byName != null) {
msg = "name conflict";
}
if (byKey != null) {
msg = "key conflict";
}
if (msg != null) {
throw new KeyManagementException(msg);
}
identities.put(identity.getName(), identity);
}
/**
* Removes an identity to the database.
*/
public void removeIdentity(Identity identity)
throws KeyManagementException {
localCheck("remove.identity");
String name = identity.getName();
if (identities.get(name) == null) {
throw new KeyManagementException("there is no identity named " +
name + " in " + this);
}
identities.remove(name);
}
/**
* @return an enumeration of all identities in the database.
*/
public Enumeration<Identity> identities() {
return identities.elements();
}
/**
* Set the source file for this database.
*/
void setSourceFile(File f) {
sourceFile = f;
}
/**
* @return the source file for this database.
*/
File getSourceFile() {
return sourceFile;
}
/**
* Save the database in its current state to an output stream.
*
* @param os the output stream to which the database should be serialized.
*
* @exception IOException if an IO exception is raised by stream
* operations.
*/
public void save(OutputStream os) throws IOException {
try {
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(this);
oos.flush();
} catch (InvalidClassException e) {
debug("This should not be happening.", e);
return;
}
}
/**
* Save the database to a file.
*
* @exception IOException if an IO exception is raised by stream
* operations.
*/
void save(File f) throws IOException {
setSourceFile(f);
FileOutputStream fos = new FileOutputStream(f);
save(fos);
}
/**
* Saves the database to the default source file.
*
* @exception KeyManagementException when there is no default source
* file specified for this database.
*/
public void save() throws IOException {
if (sourceFile == null) {
throw new IOException("this database has no source file");
}
save(sourceFile);
}
/**
* This method returns the file from which to initialize the
* system database.
*/
private static File systemDatabaseFile() {
// First figure out where the identity database is hiding, if anywhere.
String dbPath = Security.getProperty("identity.database");
// if nowhere, it's the canonical place.
if (dbPath == null) {
dbPath = System.getProperty("user.home") + File.separatorChar +
"identitydb.obj";
}
return new File(dbPath);
}
/* This block initializes the system database, if there is one. */
static {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
initializeSystem();
return null;
}
});
}
/**
* This method initializes the system's identity database. The
* canonical location is
* <user.home>/identitydatabase.obj. This is settable through
* the identity.database property. */
private static void initializeSystem() {
IdentityDatabase systemDatabase;
File dbFile = systemDatabaseFile();
// Second figure out if it's there, and if it isn't, create one.
try {
if (dbFile.exists()) {
debug("loading system database from file: " + dbFile);
systemDatabase = fromFile(dbFile);
} else {
systemDatabase = new IdentityDatabase(dbFile);
}
IdentityScope.setSystemScope(systemDatabase);
debug("System database initialized: " + systemDatabase);
} catch (IOException e) {
debug("Error initializing identity database: " + dbFile, e);
return;
} catch (InvalidParameterException e) {
debug("Error trying to instantiate a system identities db in " +
dbFile, e);
return;
}
}
/*
private static File securityPropFile(String filename) {
// maybe check for a system property which will specify where to
// look.
String sep = File.separator;
return new File(System.getProperty("java.home") +
sep + "lib" + sep + "security" +
sep + filename);
}
*/
public String toString() {
return "sun.security.provider.IdentityDatabase, source file: " +
sourceFile;
}
private static void debug(String s) {
if (debug) {
System.err.println(s);
}
}
private static void debug(String s, Throwable t) {
if (debug) {
t.printStackTrace();
System.err.println(s);
}
}
private static void error(String s) {
if (error) {
System.err.println(s);
}
}
void localCheck(String directive) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
directive = this.getClass().getName() + "." +
directive + "." + localFullName();
security.checkSecurityAccess(directive);
}
}
/**
* Returns a parsable name for identity: identityName.scopeName
*/
String localFullName() {
String parsable = getName();
if (getScope() != null) {
parsable += "." +getScope().getName();
}
return parsable;
}
/**
* Serialization write.
*/
private synchronized void writeObject (java.io.ObjectOutputStream stream)
throws IOException {
localCheck("serialize.identity.database");
stream.writeObject(identities);
stream.writeObject(sourceFile);
}
}
...@@ -295,16 +295,13 @@ public class PolicyFile extends java.security.Policy { ...@@ -295,16 +295,13 @@ public class PolicyFile extends java.security.Policy {
private static final int DEFAULT_CACHE_SIZE = 1; private static final int DEFAULT_CACHE_SIZE = 1;
/** the scope to check */
private static IdentityScope scope = null;
// contains the policy grant entries, PD cache, and alias mapping // contains the policy grant entries, PD cache, and alias mapping
private AtomicReference<PolicyInfo> policyInfo = private AtomicReference<PolicyInfo> policyInfo =
new AtomicReference<PolicyInfo>(); new AtomicReference<PolicyInfo>();
private boolean constructed = false; private boolean constructed = false;
private boolean expandProperties = true; private boolean expandProperties = true;
private boolean ignoreIdentityScope = false; private boolean ignoreIdentityScope = true;
private boolean allowSystemProperties = true; private boolean allowSystemProperties = true;
private boolean notUtf8 = false; private boolean notUtf8 = false;
private URL url; private URL url;
...@@ -2024,85 +2021,9 @@ public class PolicyFile extends java.security.Policy { ...@@ -2024,85 +2021,9 @@ public class PolicyFile extends java.security.Policy {
private boolean checkForTrustedIdentity(final Certificate cert, private boolean checkForTrustedIdentity(final Certificate cert,
PolicyInfo myInfo) PolicyInfo myInfo)
{ {
if (cert == null)
return false;
// see if we are ignoring the identity scope or not
if (ignoreIdentityScope)
return false;
// try to initialize scope
synchronized(PolicyFile.class) {
if (scope == null) {
IdentityScope is = IdentityScope.getSystemScope();
if (is instanceof sun.security.provider.IdentityDatabase) {
scope = is;
} else {
// leave scope null
}
}
}
if (scope == null) {
ignoreIdentityScope = true;
return false;
}
// need privileged block for getIdentity in case we are trying
// to get a signer
final Identity id = AccessController.doPrivileged(
new java.security.PrivilegedAction<Identity>() {
public Identity run() {
return scope.getIdentity(cert.getPublicKey());
}
});
if (isTrusted(id)) {
if (debug != null) {
debug.println("Adding policy entry for trusted Identity: ");
//needed for identity toString!
AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
debug.println(" identity = " + id);
return null;
}
});
debug.println("");
}
// add it to the policy for future reference
Certificate certs[] = new Certificate[] {cert};
PolicyEntry pe = new PolicyEntry(new CodeSource(null, certs));
pe.add(SecurityConstants.ALL_PERMISSION);
myInfo.identityPolicyEntries.add(pe);
// add it to the mapping as well so
// we don't have to go through this again
myInfo.aliasMapping.put(cert, id.getName());
return true;
}
return false; return false;
} }
private static boolean isTrusted(Identity id) {
if (id instanceof SystemIdentity) {
SystemIdentity sysid = (SystemIdentity)id;
if (sysid.isTrusted()) {
return true;
}
} else if (id instanceof SystemSigner) {
SystemSigner sysid = (SystemSigner)id;
if (sysid.isTrusted()) {
return true;
}
}
return false;
}
/** /**
* Each entry in the policy configuration file is represented by a * Each entry in the policy configuration file is represented by a
* PolicyEntry object. <p> * PolicyEntry object. <p>
......
/*
* Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.io.Serializable;
import java.util.Enumeration;
import java.security.*;
/**
* An identity with a very simple trust mechanism.
*
* @author Benjamin Renaud
*/
public class SystemIdentity extends Identity implements Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 9060648952088498478L;
/* This should be changed to ACL */
boolean trusted = false;
/* Free form additional information about this identity. */
private String info;
public SystemIdentity(String name, IdentityScope scope)
throws InvalidParameterException, KeyManagementException {
super(name, scope);
}
/**
* Is this identity trusted by sun.* facilities?
*/
public boolean isTrusted() {
return trusted;
}
/**
* Set the trust status of this identity.
*/
protected void setTrusted(boolean trusted) {
this.trusted = trusted;
}
void setIdentityInfo(String info) {
super.setInfo(info);
}
String getIndentityInfo() {
return super.getInfo();
}
/**
* Call back method into a protected method for package friends.
*/
void setIdentityPublicKey(PublicKey key) throws KeyManagementException {
setPublicKey(key);
}
/**
* Call back method into a protected method for package friends.
*/
void addIdentityCertificate(Certificate cert)
throws KeyManagementException {
addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
Certificate[] certs = certificates();
for (int i = 0; i < certs.length; i++) {
removeCertificate(certs[i]);
}
}
public String toString() {
String trustedString = "not trusted";
if (trusted) {
trustedString = "trusted";
}
return super.toString() + "[" + trustedString + "]";
}
}
/*
* Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.util.*;
import java.security.*;
/**
* SunSecurity signer. Like SystemIdentity, it has a trust bit, which
* can be set by SunSecurity classes, and a set of accessors for other
* classes in sun.security.*.
*
* @author Benjamin Renaud
*/
public class SystemSigner extends Signer {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -2127743304301557711L;
/* Is this signer trusted */
private boolean trusted = false;
/**
* Construct a signer with a given name.
*/
public SystemSigner(String name) {
super(name);
}
/**
* Construct a signer with a name and a scope.
*
* @param name the signer's name.
*
* @param scope the scope for this signer.
*/
public SystemSigner(String name, IdentityScope scope)
throws KeyManagementException {
super(name, scope);
}
/* Set the trust status of this signer */
void setTrusted(boolean trusted) {
this.trusted = trusted;
}
/**
* Returns true if this signer is trusted.
*/
public boolean isTrusted() {
return trusted;
}
/* friendly callback for set keys */
void setSignerKeyPair(KeyPair pair)
throws InvalidParameterException, KeyException {
setKeyPair(pair);
}
/* friendly callback for getting private keys */
PrivateKey getSignerPrivateKey() {
return getPrivateKey();
}
void setSignerInfo(String s) {
setInfo(s);
}
/**
* Call back method into a protected method for package friends.
*/
void addSignerCertificate(Certificate cert) throws KeyManagementException {
addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
Certificate[] certs = certificates();
for (int i = 0; i < certs.length; i++) {
removeCertificate(certs[i]);
}
}
public String toString() {
String trustedString = "not trusted";
if (trusted) {
trustedString = "trusted";
}
return super.toString() + "[" + trustedString + "]";
}
}
...@@ -335,10 +335,13 @@ class OCSPChecker extends PKIXCertPathChecker { ...@@ -335,10 +335,13 @@ class OCSPChecker extends PKIXCertPathChecker {
response = OCSP.check(Collections.singletonList(certId), uri, response = OCSP.check(Collections.singletonList(certId), uri,
responderCert, pkixParams.getDate()); responderCert, pkixParams.getDate());
} catch (Exception e) { } catch (Exception e) {
// Wrap all exceptions in CertPathValidatorException so that if (e instanceof CertPathValidatorException) {
// we can fallback to CRLs, if enabled. throw (CertPathValidatorException) e;
throw new CertPathValidatorException } else {
("Unable to send OCSP request", e); // Wrap exceptions in CertPathValidatorException so that
// we can fallback to CRLs, if enabled.
throw new CertPathValidatorException(e);
}
} }
RevocationStatus rs = (RevocationStatus) response.getSingleResponse(certId); RevocationStatus rs = (RevocationStatus) response.getSingleResponse(certId);
......
...@@ -118,8 +118,6 @@ public class JarSigner { ...@@ -118,8 +118,6 @@ public class JarSigner {
KeyStore store; // the keystore specified by -keystore KeyStore store; // the keystore specified by -keystore
// or the default keystore, never null // or the default keystore, never null
IdentityScope scope;
String keystore; // key store file String keystore; // key store file
boolean nullStream = false; // null keystore input stream (NONE) boolean nullStream = false; // null keystore input stream (NONE)
boolean token = false; // token-based keystore boolean token = false; // token-based keystore
...@@ -212,7 +210,6 @@ public class JarSigner { ...@@ -212,7 +210,6 @@ public class JarSigner {
if (verify) { if (verify) {
try { try {
loadKeyStore(keystore, false); loadKeyStore(keystore, false);
scope = IdentityScope.getSystemScope();
} catch (Exception e) { } catch (Exception e) {
if ((keystore != null) || (storepass != null)) { if ((keystore != null) || (storepass != null)) {
System.out.println(rb.getString("jarsigner error: ") + System.out.println(rb.getString("jarsigner error: ") +
...@@ -984,13 +981,6 @@ public class JarSigner { ...@@ -984,13 +981,6 @@ public class JarSigner {
result |= IN_KEYSTORE; result |= IN_KEYSTORE;
} }
} }
if (!found && (scope != null)) {
Identity id = scope.getIdentity(c.getPublicKey());
if (id != null) {
result |= IN_SCOPE;
storeHash.put(c, "[" + id.getName() + "]");
}
}
if (ckaliases.contains(alias)) { if (ckaliases.contains(alias)) {
result |= SIGNED_BY_ALIAS; result |= SIGNED_BY_ALIAS;
} }
......
...@@ -40,7 +40,6 @@ import java.security.UnrecoverableEntryException; ...@@ -40,7 +40,6 @@ import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException; import java.security.UnrecoverableKeyException;
import java.security.Principal; import java.security.Principal;
import java.security.Provider; import java.security.Provider;
import java.security.Identity;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
...@@ -57,9 +56,6 @@ import java.net.URLClassLoader; ...@@ -57,9 +56,6 @@ import java.net.URLClassLoader;
import sun.misc.BASE64Encoder; import sun.misc.BASE64Encoder;
import sun.security.util.ObjectIdentifier; import sun.security.util.ObjectIdentifier;
import sun.security.pkcs.PKCS10; import sun.security.pkcs.PKCS10;
import sun.security.provider.IdentityDatabase;
import sun.security.provider.SystemSigner;
import sun.security.provider.SystemIdentity;
import sun.security.provider.X509Factory; import sun.security.provider.X509Factory;
import sun.security.util.DerOutputStream; import sun.security.util.DerOutputStream;
import sun.security.util.Password; import sun.security.util.Password;
...@@ -1163,18 +1159,16 @@ public final class KeyTool { ...@@ -1163,18 +1159,16 @@ public final class KeyTool {
Signature signature = Signature.getInstance(sigAlgName); Signature signature = Signature.getInstance(sigAlgName);
signature.initSign(privateKey); signature.initSign(privateKey);
X500Signer signer = new X500Signer(signature, issuer);
X509CertInfo info = new X509CertInfo(); X509CertInfo info = new X509CertInfo();
info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff)); new java.util.Random().nextInt() & 0x7fffffff));
info.set(X509CertInfo.VERSION, info.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V3)); new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.ALGORITHM_ID, info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(signer.getAlgorithmId())); new CertificateAlgorithmId(
info.set(X509CertInfo.ISSUER, AlgorithmId.getAlgorithmId(sigAlgName)));
new CertificateIssuerName(signer.getSigner())); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedReader reader = new BufferedReader(new InputStreamReader(in));
boolean canRead = false; boolean canRead = false;
...@@ -1249,7 +1243,7 @@ public final class KeyTool { ...@@ -1249,7 +1243,7 @@ public final class KeyTool {
request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS, request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS,
new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext)); new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext));
// Construct an X500Signer object, so that we can sign the request // Construct a Signature object, so that we can sign the request
if (sigAlgName == null) { if (sigAlgName == null) {
sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm()); sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm());
} }
...@@ -1259,10 +1253,9 @@ public final class KeyTool { ...@@ -1259,10 +1253,9 @@ public final class KeyTool {
X500Name subject = dname == null? X500Name subject = dname == null?
new X500Name(((X509Certificate)cert).getSubjectDN().toString()): new X500Name(((X509Certificate)cert).getSubjectDN().toString()):
new X500Name(dname); new X500Name(dname);
X500Signer signer = new X500Signer(signature, subject);
// Sign the request and base-64 encode it // Sign the request and base-64 encode it
request.encodeAndSign(signer); request.encodeAndSign(subject, signature);
request.print(out); request.print(out);
} }
...@@ -1564,75 +1557,8 @@ public final class KeyTool { ...@@ -1564,75 +1557,8 @@ public final class KeyTool {
private void doImportIdentityDatabase(InputStream in) private void doImportIdentityDatabase(InputStream in)
throws Exception throws Exception
{ {
byte[] encoded; System.err.println(rb.getString
ByteArrayInputStream bais; ("No entries from identity database added"));
java.security.cert.X509Certificate newCert;
java.security.cert.Certificate[] chain = null;
PrivateKey privKey;
boolean modified = false;
IdentityDatabase idb = IdentityDatabase.fromStream(in);
for (Enumeration<Identity> enum_ = idb.identities();
enum_.hasMoreElements();) {
Identity id = enum_.nextElement();
newCert = null;
// only store trusted identities in keystore
if ((id instanceof SystemSigner && ((SystemSigner)id).isTrusted())
|| (id instanceof SystemIdentity
&& ((SystemIdentity)id).isTrusted())) {
// ignore if keystore entry with same alias name already exists
if (keyStore.containsAlias(id.getName())) {
MessageFormat form = new MessageFormat
(rb.getString("Keystore entry for <id.getName()> already exists"));
Object[] source = {id.getName()};
System.err.println(form.format(source));
continue;
}
java.security.Certificate[] certs = id.certificates();
if (certs!=null && certs.length>0) {
// we can only store one user cert per identity.
// convert old-style to new-style cert via the encoding
DerOutputStream dos = new DerOutputStream();
certs[0].encode(dos);
encoded = dos.toByteArray();
bais = new ByteArrayInputStream(encoded);
newCert = (X509Certificate)cf.generateCertificate(bais);
bais.close();
// if certificate is self-signed, make sure it verifies
if (isSelfSigned(newCert)) {
PublicKey pubKey = newCert.getPublicKey();
try {
newCert.verify(pubKey);
} catch (Exception e) {
// ignore this cert
continue;
}
}
if (id instanceof SystemSigner) {
MessageFormat form = new MessageFormat(rb.getString
("Creating keystore entry for <id.getName()> ..."));
Object[] source = {id.getName()};
System.err.println(form.format(source));
if (chain==null) {
chain = new java.security.cert.Certificate[1];
}
chain[0] = newCert;
privKey = ((SystemSigner)id).getPrivateKey();
keyStore.setKeyEntry(id.getName(), privKey, storePass,
chain);
} else {
keyStore.setCertificateEntry(id.getName(), newCert);
}
kssave = true;
}
}
}
if (!kssave) {
System.err.println(rb.getString
("No entries from identity database added"));
}
} }
/** /**
......
...@@ -33,7 +33,6 @@ import java.security.Permission; ...@@ -33,7 +33,6 @@ import java.security.Permission;
import java.security.BasicPermission; import java.security.BasicPermission;
import java.security.SecurityPermission; import java.security.SecurityPermission;
import java.security.AllPermission; import java.security.AllPermission;
import javax.security.auth.AuthPermission;
/** /**
* Permission constants and string constants used to create permissions * Permission constants and string constants used to create permissions
...@@ -259,12 +258,4 @@ public final class SecurityConstants { ...@@ -259,12 +258,4 @@ public final class SecurityConstants {
// java.lang.SecurityManager // java.lang.SecurityManager
public static final SocketPermission LOCAL_LISTEN_PERMISSION = public static final SocketPermission LOCAL_LISTEN_PERMISSION =
new SocketPermission("localhost:1024-", SOCKET_LISTEN_ACTION); new SocketPermission("localhost:1024-", SOCKET_LISTEN_ACTION);
// javax.security.auth.Subject
public static final AuthPermission DO_AS_PERMISSION =
new AuthPermission("doAs");
// javax.security.auth.Subject
public static final AuthPermission DO_AS_PRIVILEGED_PERMISSION =
new AuthPermission("doAsPrivileged");
} }
...@@ -150,9 +150,17 @@ public final class PKIXValidator extends Validator { ...@@ -150,9 +150,17 @@ public final class PKIXValidator extends Validator {
("null or zero-length certificate chain"); ("null or zero-length certificate chain");
} }
if (TRY_VALIDATOR) { if (TRY_VALIDATOR) {
// check if chain contains trust anchor // check that chain is in correct order and check if chain contains
// trust anchor
X500Principal prevIssuer = null;
for (int i = 0; i < chain.length; i++) { for (int i = 0; i < chain.length; i++) {
if (trustedCerts.contains(chain[i])) { X509Certificate cert = chain[i];
if (i != 0 &&
!cert.getSubjectX500Principal().equals(prevIssuer)) {
// chain is not ordered correctly, call builder instead
return doBuild(chain, otherCerts);
}
if (trustedCerts.contains(cert)) {
if (i == 0) { if (i == 0) {
return new X509Certificate[] {chain[0]}; return new X509Certificate[] {chain[0]};
} }
...@@ -161,6 +169,7 @@ public final class PKIXValidator extends Validator { ...@@ -161,6 +169,7 @@ public final class PKIXValidator extends Validator {
System.arraycopy(chain, 0, newChain, 0, i); System.arraycopy(chain, 0, newChain, 0, i);
return doValidate(newChain); return doValidate(newChain);
} }
prevIssuer = cert.getIssuerX500Principal();
} }
// apparently issued by trust anchor? // apparently issued by trust anchor?
...@@ -303,5 +312,4 @@ public final class PKIXValidator extends Validator { ...@@ -303,5 +312,4 @@ public final class PKIXValidator extends Validator {
("PKIX path building failed: " + e.toString(), e); ("PKIX path building failed: " + e.toString(), e);
} }
} }
} }
...@@ -189,41 +189,6 @@ public final class CertAndKeyGen { ...@@ -189,41 +189,6 @@ public final class CertAndKeyGen {
} }
/**
* Returns a self-signed X.509v1 certificate for the public key.
* The certificate is immediately valid.
*
* <P>Such certificates normally are used to identify a "Certificate
* Authority" (CA). Accordingly, they will not always be accepted by
* other parties. However, such certificates are also useful when
* you are bootstrapping your security infrastructure, or deploying
* system prototypes.
*
* @deprecated Use the new <a href =
* "#getSelfCertificate(sun.security.x509.X500Name, long)">
*
* @param myname X.500 name of the subject (who is also the issuer)
* @param validity how long the certificate should be valid, in seconds
*/
@Deprecated
public X509Cert getSelfCert (X500Name myname, long validity)
throws InvalidKeyException, SignatureException, NoSuchAlgorithmException
{
X509Certificate cert;
try {
cert = getSelfCertificate(myname, validity);
return new X509Cert(cert.getEncoded());
} catch (CertificateException e) {
throw new SignatureException(e.getMessage());
} catch (NoSuchProviderException e) {
throw new NoSuchAlgorithmException(e.getMessage());
} catch (IOException e) {
throw new SignatureException(e.getMessage());
}
}
/** /**
* Returns a self-signed X.509v3 certificate for the public key. * Returns a self-signed X.509v3 certificate for the public key.
* The certificate is immediately valid. No extensions. * The certificate is immediately valid. No extensions.
...@@ -248,13 +213,10 @@ public final class CertAndKeyGen { ...@@ -248,13 +213,10 @@ public final class CertAndKeyGen {
throws CertificateException, InvalidKeyException, SignatureException, throws CertificateException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException, NoSuchProviderException NoSuchAlgorithmException, NoSuchProviderException
{ {
X500Signer issuer;
X509CertImpl cert; X509CertImpl cert;
Date lastDate; Date lastDate;
try { try {
issuer = getSigner (myname);
lastDate = new Date (); lastDate = new Date ();
lastDate.setTime (firstDate.getTime () + validity * 1000); lastDate.setTime (firstDate.getTime () + validity * 1000);
...@@ -267,14 +229,13 @@ public final class CertAndKeyGen { ...@@ -267,14 +229,13 @@ public final class CertAndKeyGen {
new CertificateVersion(CertificateVersion.V3)); new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff)); new java.util.Random().nextInt() & 0x7fffffff));
AlgorithmId algID = issuer.getAlgorithmId(); AlgorithmId algID = AlgorithmId.getAlgorithmId(sigAlg);
info.set(X509CertInfo.ALGORITHM_ID, info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(algID)); new CertificateAlgorithmId(algID));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname));
info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey)); info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.ISSUER, info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname));
new CertificateIssuerName(issuer.getSigner()));
cert = new X509CertImpl(info); cert = new X509CertImpl(info);
cert.sign(privateKey, this.sigAlg); cert.sign(privateKey, this.sigAlg);
...@@ -315,7 +276,9 @@ public final class CertAndKeyGen { ...@@ -315,7 +276,9 @@ public final class CertAndKeyGen {
PKCS10 req = new PKCS10 (publicKey); PKCS10 req = new PKCS10 (publicKey);
try { try {
req.encodeAndSign (getSigner (myname)); Signature signature = Signature.getInstance(sigAlg);
signature.initSign (privateKey);
req.encodeAndSign(myname, signature);
} catch (CertificateException e) { } catch (CertificateException e) {
throw new SignatureException (sigAlg + " CertificateException"); throw new SignatureException (sigAlg + " CertificateException");
...@@ -330,18 +293,6 @@ public final class CertAndKeyGen { ...@@ -330,18 +293,6 @@ public final class CertAndKeyGen {
return req; return req;
} }
private X500Signer getSigner (X500Name me)
throws InvalidKeyException, NoSuchAlgorithmException
{
Signature signature = Signature.getInstance(sigAlg);
// XXX should have a way to pass prng to the signature
// algorithm ... appropriate for DSS/DSA, not RSA
signature.initSign (privateKey);
return new X500Signer (signature, me);
}
private SecureRandom prng; private SecureRandom prng;
private String sigAlg; private String sigAlg;
private KeyPairGenerator keyGen; private KeyPairGenerator keyGen;
......
/*
* Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.x509;
import java.security.Signature;
import java.security.SignatureException;
import java.security.Signer;
import java.security.NoSuchAlgorithmException;
/**
* This class provides a binding between a Signature object and an
* authenticated X.500 name (from an X.509 certificate chain), which
* is needed in many public key signing applications.
*
* <P>The name of the signer is important, both because knowing it is the
* whole point of the signature, and because the associated X.509 certificate
* is always used to verify the signature.
*
* <P><em>The X.509 certificate chain is temporarily not associated with
* the signer, but this omission will be resolved.</em>
*
*
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public final class X500Signer extends Signer
{
private static final long serialVersionUID = -8609982645394364834L;
/**
* Called for each chunk of the data being signed. That
* is, you can present the data in many chunks, so that
* it doesn't need to be in a single sequential buffer.
*
* @param buf buffer holding the next chunk of the data to be signed
* @param offset starting point of to-be-signed data
* @param len how many bytes of data are to be signed
* @exception SignatureException on errors.
*/
public void update(byte buf[], int offset, int len)
throws SignatureException {
sig.update (buf, offset, len);
}
/**
* Produces the signature for the data processed by update().
*
* @exception SignatureException on errors.
*/
public byte[] sign() throws SignatureException {
return sig.sign();
}
/**
* Returns the algorithm used to sign.
*/
public AlgorithmId getAlgorithmId() {
return algid;
}
/**
* Returns the name of the signing agent.
*/
public X500Name getSigner() {
return agent;
}
/*
* Constructs a binding between a signature and an X500 name
* from an X.509 certificate.
*/
// package private ----hmmmmm ?????
public X500Signer(Signature sig, X500Name agent) {
if (sig == null || agent == null)
throw new IllegalArgumentException ("null parameter");
this.sig = sig;
this.agent = agent;
try {
this.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("internal error! " + e.getMessage());
}
}
private Signature sig;
private X500Name agent; // XXX should be X509CertChain
private AlgorithmId algid;
}
/*
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.tools.jar;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;
import java.security.cert.Certificate;
import java.security.AccessController;
import java.security.cert.X509Certificate;
import java.security.PublicKey;
import java.security.Principal;
import sun.security.provider.SystemIdentity;
/**
* This is OBSOLETE. DO NOT USE THIS. Use
* java.util.jar.JarEntry.getCertificates instead. It has to stay here
* because some apps (namely HJ and HJV) call directly into it.
*
* This class is stripped down greatly from JDK 1.1.x.
*
* @author Roland Schemers
*/
public class JarVerifierStream extends ZipInputStream {
private JarEntry current;
private Hashtable<String, Vector<SystemIdentity>> verified
= new Hashtable<String, Vector<SystemIdentity>>();
private JarInputStream jis;
private sun.tools.jar.Manifest man = null;
/**
* construct a JarVerfierStream from an input stream.
*/
public JarVerifierStream(InputStream is)
throws IOException
{
super(is);
jis = new JarInputStream(is);
}
public void close()
throws IOException
{
jis.close();
}
public void closeEntry() throws IOException {
jis.closeEntry();
}
/**
* This method scans to see which entry we're parsing and
* keeps various state information depending on what type of
* file is being parsed. Files it treats specially are: <ul>
*
* <li>Manifest files. At any point, this stream can be queried
* for a manifest. If it is present, a Manifest object will be
* returned.
*
* <li>Block Signature file. Like with the manifest, the stream
* can be queried at any time for all blocks parsed thus far.
*
* </ul>
*/
public synchronized ZipEntry getNextEntry() throws IOException {
current = (JarEntry) jis.getNextEntry();
return current;
}
/**
* read a single byte.
*/
public int read() throws IOException {
int n = jis.read();
if (n == -1) {
addIds();
}
return n;
}
/**
* read an array of bytes.
*/
public int read(byte[] b, int off, int len) throws IOException {
int n = jis.read(b, off, len);
if (n == -1) {
addIds();
}
return n;
}
private void addIds()
{
if (current != null) {
Certificate[] certs = current.getCertificates();
if (certs != null) {
Vector<SystemIdentity> ids = getIds(certs);
if (ids != null) {
verified.put(current.getName(), ids);
}
}
}
}
/**
* Returns a Hashtable mapping filenames to vectors of identities.
*/
public Hashtable getVerifiedSignatures() {
/* we may want to return a copy of this at some point.
For now we simply trust the caller */
if (verified.isEmpty())
return null;
else
return verified;
}
/**
* Returns an enumeration of PKCS7 blocks. This looks bogus,
* but Hotjava just checks to see if enumeration is not null
* to see if anything was signed!
*/
public Enumeration getBlocks() {
if (verified.isEmpty()) {
return null;
} else {
return new Enumeration() {
public boolean hasMoreElements() { return false; }
public Object nextElement() { return null; }
};
}
}
/**
* This method used to be called by various versions of
* AppletResourceLoader, even though they didn't do anything with
* the result. We leave them and return null for backwards compatability.
*/
public Hashtable getNameToHash() {
return null;
}
/**
* Convert java.util.jar.Manifest object to a sun.tools.jar.Manifest
* object.
*/
public sun.tools.jar.Manifest getManifest() {
if (man == null) {
try {
java.util.jar.Manifest jman = jis.getManifest();
if (jman == null)
return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
jman.write(baos);
byte[] data = baos.toByteArray();
man = new sun.tools.jar.Manifest(data);
} catch (IOException ioe) {
// return null
}
}
return man;
}
static class CertCache {
Certificate [] certs;
Vector<SystemIdentity> ids;
boolean equals(Certificate[] certs) {
if (this.certs == null) {
if (certs!= null)
return false;
else
return true;
}
if (certs == null)
return false;
boolean match;
for (int i = 0; i < certs.length; i++) {
match = false;
for (int j = 0; j < this.certs.length; j++) {
if (certs[i].equals(this.certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
for (int i = 0; i < this.certs.length; i++) {
match = false;
for (int j = 0; j < certs.length; j++) {
if (this.certs[i].equals(certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
return true;
}
}
private ArrayList<CertCache> certCache = null;
/**
* Returns the Identity vector for the given array of Certificates
*/
protected Vector<SystemIdentity> getIds(Certificate[] certs) {
if (certs == null)
return null;
if (certCache == null)
certCache = new ArrayList<CertCache>();
CertCache cc;
for (int i = 0; i < certCache.size(); i++) {
cc = certCache.get(i);
if (cc.equals(certs)) {
return cc.ids;
}
}
cc = new CertCache();
cc.certs = certs;
if (certs.length > 0) {
for (int i=0; i<certs.length; i++) {
try {
X509Certificate cert = (X509Certificate) certs[i];
Principal tmpName = cert.getSubjectDN();
final SystemIdentity id = new SystemIdentity(
tmpName.getName(),
null);
byte[] encoded = cert.getEncoded();
final java.security.Certificate oldC =
new sun.security.x509.X509Cert(encoded);
try {
AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<Void>() {
public Void run()
throws java.security.KeyManagementException
{
id.addCertificate(oldC);
return null;
}
});
} catch (java.security.PrivilegedActionException pae) {
throw (java.security.KeyManagementException)
pae.getException();
}
if (cc.ids == null)
cc.ids = new Vector<SystemIdentity>();
cc.ids.addElement(id);
} catch (java.security.KeyManagementException kme) {
// ignore if we can't create Identity
} catch (IOException ioe) {
// ignore if we can't parse
} catch (java.security.cert.CertificateEncodingException cee) {
// ignore if we can't encode
}
}
}
certCache.add(cc);
return cc.ids;
}
}
...@@ -30,7 +30,6 @@ import java.lang.reflect.InvocationTargetException; ...@@ -30,7 +30,6 @@ import java.lang.reflect.InvocationTargetException;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
import com.sun.tracing.ProviderFactory; import com.sun.tracing.ProviderFactory;
import com.sun.tracing.Provider; import com.sun.tracing.Provider;
...@@ -65,13 +64,7 @@ public class MultiplexProviderFactory extends ProviderFactory { ...@@ -65,13 +64,7 @@ public class MultiplexProviderFactory extends ProviderFactory {
providers.add(factory.createProvider(cls)); providers.add(factory.createProvider(cls));
} }
MultiplexProvider provider = new MultiplexProvider(cls, providers); MultiplexProvider provider = new MultiplexProvider(cls, providers);
try { provider.init();
provider.init();
} catch (Exception e) {
// Probably a permission problem (can't get declared members)
Logger.getAnonymousLogger().warning(
"Could not initialize tracing provider: " + e.getMessage());
}
return provider.newProxyInstance(); return provider.newProxyInstance();
} }
} }
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册