Skip to content

Commit

Permalink
Format java files in o.e.equinox.security
Browse files Browse the repository at this point in the history
This was achieved by running:
eclipse -consolelog -nosplash -application org.eclipse.jdt.core.JavaCodeFormatter \
  -config .settings/org.eclipse.jdt.core.prefs . -data `mktemp -d`

Signed-off-by: Torbjörn SVENSSON <[email protected]>
  • Loading branch information
Torbjorn-Svensson authored and akurtakov committed Oct 12, 2023
1 parent b7fd2c9 commit 7a73837
Show file tree
Hide file tree
Showing 35 changed files with 756 additions and 556 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ public class AuthPlugin implements BundleActivator {
public static boolean DEBUG_LOGIN_FRAMEWORK = false;

/*
* Returns the singleton for this Activator. Callers should be aware that
* this will return null if the bundle is not active.
* Returns the singleton for this Activator. Callers should be aware that this
* will return null if the bundle is not active.
*/
public static AuthPlugin getDefault() {
return singleton;
Expand All @@ -68,7 +68,8 @@ public void start(BundleContext context) throws Exception {
if (DEBUG)
DEBUG_LOGIN_FRAMEWORK = getBooleanOption(PI_AUTH + "/debug/loginFramework", false); //$NON-NLS-1$

// SecurePlatformInternal is started lazily when first SecureContext is created (this reduces
// SecurePlatformInternal is started lazily when first SecureContext is created
// (this reduces
// time spend in the bundle activator).
}

Expand Down Expand Up @@ -159,7 +160,8 @@ public EnvironmentInfo getEnvironmentInfoService() {
* in the bundle dependency stack is really sub-optimal.
*
* In particular, logging with RuntimeLog on shutdown doesn't work as Platform
* shuts down (removing listeners from RuntimeLog) before this bundle shuts down.
* shuts down (removing listeners from RuntimeLog) before this bundle shuts
* down.
*
* As such, until there is improved logging, the errors that occur on shutdown
* should use this method. However, errors occuring during normal operations
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
public class ConfigurationFederator extends Configuration {

// TODO this usage needs to be changed. We should retrieve federatedConfigs
// from the "ConfigurationFactory" every time we are asked; the "ConfigurationFactory"
// shoudl keep a cache that corresponds to what's in the registry and update it on registry
// from the "ConfigurationFactory" every time we are asked; the
// "ConfigurationFactory"
// shoudl keep a cache that corresponds to what's in the registry and update it
// on registry
// events
private Configuration[] federatedConfigs = null;

Expand All @@ -42,7 +44,8 @@ public synchronized AppConfigurationEntry[] getAppConfigurationEntry(String name
if (returnValue != null)
return returnValue;

// Note: adding default config provider last; extension-point based configs are queried first
// Note: adding default config provider last; extension-point based configs are
// queried first
Configuration[] configs = getFederatedConfigs();
Configuration[] allConfigs = configs;
if (defaultConfiguration != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public SecureContext(String configugationName, URL configFile, CallbackHandler h
configName = configugationName;
SecurePlatformInternal platform = SecurePlatformInternal.getInstance();
if (configFile != null)
platform.addConfigURL(configFile); // this call MUST be done before start()
platform.addConfigURL(configFile); // this call MUST be done before start()
platform.start();
this.handler = handler;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,23 @@ public CallbackHandler loadCallbackHandler(String configurationName) {
}

/**
* Java docs specify that if multiple config files are passed in, they will be merged into one file.
* Hence, aside from implementation details, no priority information is specified by the order
* of config files. In this implementation we add customer's config file to the end of the list.
* Java docs specify that if multiple config files are passed in, they will be
* merged into one file. Hence, aside from implementation details, no priority
* information is specified by the order of config files. In this implementation
* we add customer's config file to the end of the list.
*
* This method substitutes default login configuration:
* Configuration Inquiries -> ConfigurationFederator ->
* 1) Extension Point supplied config providers;
* 2) default Java config provider ("login.configuration.provider")
* This method substitutes default login configuration: Configuration Inquiries
* -> ConfigurationFederator -> 1) Extension Point supplied config providers; 2)
* default Java config provider ("login.configuration.provider")
*/
public void start() {
if (running)
return;

// Kludge for the bug 215828 "JAAS and server-side Eclipse": for the time being configuration
// substitution is turned off if running on a server. It is likely possible to work around
// Kludge for the bug 215828 "JAAS and server-side Eclipse": for the time being
// configuration
// substitution is turned off if running on a server. It is likely possible to
// work around
// configuration substitution using Java 5 methods, but not Java 1.4
BundleContext context = AuthPlugin.getDefault().getBundleContext();
String vmType = context.getProperty(VM_PROPERTY);
Expand Down Expand Up @@ -108,7 +110,8 @@ public boolean addConfigURL(URL url) {
continue;
String path;
try {
// in case URL is contained in a JARed bundle, this will extract it into a file system
// in case URL is contained in a JARed bundle, this will extract it into a file
// system
path = FileLocator.toFileURL(url).toExternalForm();
} catch (IOException e) {
path = url.toExternalForm();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
import org.eclipse.osgi.util.NLS;

/**
* Expected usage pattern: this method is called infrequently (a few times per life cycle;
* most likely once). As such, no internal caches are maintained and it simply goes
* to the registry and retrieves information when asked.
* Expected usage pattern: this method is called infrequently (a few times per
* life cycle; most likely once). As such, no internal caches are maintained and
* it simply goes to the registry and retrieves information when asked.
*/
public class ExtLoginModuleLoader {

Expand Down Expand Up @@ -71,10 +71,11 @@ private static LoginModule readEntry(IConfigurationElement element) {
try {
LoginModule module = (LoginModule) element.createExecutableExtension(ATTR_MODULE_CLASS);
return module;
// future expandability: description is stored in the attribute "description"
// future expandability: description is stored in the attribute "description"
} catch (CoreException e) {
String supplier = element.getContributor().getName();
String message = NLS.bind(SecAuthMessages.instantiationFailed, element.getAttribute(ATTR_MODULE_CLASS), supplier);
String message = NLS.bind(SecAuthMessages.instantiationFailed, element.getAttribute(ATTR_MODULE_CLASS),
supplier);
AuthPlugin.getDefault().logError(message, e);
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
* This is an implementation of Base64 encoding allowing byte sequences to be
* converted into strings - safe to be stored in basic Java structures.
* <p>
* This Base64 encoding does not insert end-of-line characters
* (but can properly decode strings with EOLs inserted).
* This Base64 encoding does not insert end-of-line characters (but can properly
* decode strings with EOLs inserted).
* </p>
*/
public class Base64 {

final static private char[] encodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); //$NON-NLS-1$
final static private char[] encodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" //$NON-NLS-1$
.toCharArray();

final static private byte BASE64_PADDING = 126;
final static private byte BASE64_INVALID = 127;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@
import org.eclipse.osgi.util.NLS;

/**
* Note that algorithm detection skips aliases:
* Alg.Alias.Cipher.ABC
* only a few aliases are useful and it will be harder to separate human-readable
* aliases from internal ones.
* Note that algorithm detection skips aliases: Alg.Alias.Cipher.ABC only a few
* aliases are useful and it will be harder to separate human-readable aliases
* from internal ones.
*
*/
public class JavaEncryption {
Expand Down Expand Up @@ -101,7 +100,8 @@ protected void internalInitialize() throws StorageException {
if (cipherAlgorithm != null && keyFactoryAlgorithm != null) {
if (roundtrip(cipherAlgorithm, keyFactoryAlgorithm))
return;
// this is a bad situation - JVM cipher no longer available. Both log and throw an exception
// this is a bad situation - JVM cipher no longer available. Both log and throw
// an exception
String msg = NLS.bind(SecAuthMessages.noAlgorithm, cipherAlgorithm);
StorageException e = new StorageException(StorageException.INTERNAL_ERROR, msg);
AuthPlugin.getDefault().logError(msg, e);
Expand All @@ -110,7 +110,8 @@ protected void internalInitialize() throws StorageException {
if (cipherAlgorithm == null || keyFactoryAlgorithm == null) {
IEclipsePreferences eclipseNode = ConfigurationScope.INSTANCE.getNode(AuthPlugin.PI_AUTH);
cipherAlgorithm = eclipseNode.get(IStorageConstants.CIPHER_KEY, IStorageConstants.DEFAULT_CIPHER);
keyFactoryAlgorithm = eclipseNode.get(IStorageConstants.KEY_FACTORY_KEY, IStorageConstants.DEFAULT_KEY_FACTORY);
keyFactoryAlgorithm = eclipseNode.get(IStorageConstants.KEY_FACTORY_KEY,
IStorageConstants.DEFAULT_KEY_FACTORY);
}
if (roundtrip(cipherAlgorithm, keyFactoryAlgorithm))
return;
Expand Down Expand Up @@ -147,20 +148,21 @@ private CryptoData internalEncrypt(PasswordExt passwordExt, byte[] clearText) th
c.init(Cipher.ENCRYPT_MODE, key, entropy);
byte[] iv = null;

//check if IV is required by PBE algorithm
// check if IV is required by PBE algorithm
AlgorithmParameterSpec paramSpec;
try {
paramSpec = c.getParameters().getParameterSpec(PBEParameterSpec.class).getParameterSpec();
if (paramSpec != null && paramSpec instanceof IvParameterSpec) {
iv = c.getIV();
}
} catch (InvalidParameterSpecException e) {
/*do nothing*/
/* do nothing */
}

byte[] result = c.doFinal(clearText);
return new CryptoData(passwordExt.getModuleID(), salt, result, iv);
} catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
} catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
| BadPaddingException e) {
handle(e, StorageException.ENCRYPTION_ERROR);
return null;
} catch (InvalidKeySpecException | NoSuchPaddingException | NoSuchAlgorithmException e) {
Expand All @@ -169,12 +171,14 @@ private CryptoData internalEncrypt(PasswordExt passwordExt, byte[] clearText) th
}
}

public byte[] decrypt(PasswordExt passwordExt, CryptoData encryptedData) throws StorageException, IllegalStateException, IllegalBlockSizeException, BadPaddingException {
public byte[] decrypt(PasswordExt passwordExt, CryptoData encryptedData)
throws StorageException, IllegalStateException, IllegalBlockSizeException, BadPaddingException {
init();
return internalDecrypt(passwordExt, encryptedData);
}

private byte[] internalDecrypt(PasswordExt passwordExt, CryptoData encryptedData) throws StorageException, IllegalStateException, IllegalBlockSizeException, BadPaddingException {
private byte[] internalDecrypt(PasswordExt passwordExt, CryptoData encryptedData)
throws StorageException, IllegalStateException, IllegalBlockSizeException, BadPaddingException {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(keyFactoryAlgorithm);
SecretKey key = keyFactory.generateSecret(passwordExt.getPassword());
Expand All @@ -196,7 +200,8 @@ private byte[] internalDecrypt(PasswordExt passwordExt, CryptoData encryptedData

byte[] result = c.doFinal(encryptedData.getData());
return result;
} catch (InvalidAlgorithmParameterException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException | NoSuchAlgorithmException e) {
} catch (InvalidAlgorithmParameterException | InvalidKeyException | InvalidKeySpecException
| NoSuchPaddingException | NoSuchAlgorithmException e) {
handle(e, StorageException.INTERNAL_ERROR);
return null;
}
Expand All @@ -213,8 +218,7 @@ private void handle(Exception e, int internalCode) throws StorageException {
// Algorithm detection

/**
* Result: Map:
* <String>cipher -> <String>keyFactory
* Result: Map: <String>cipher -> <String>keyFactory
*/
public HashMap<String, String> detect() {
IUICallbacks callback = CallbacksProvider.getDefault().getCallback();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ static public void setupRecovery(String[][] challengeResponse, String moduleID,
// create password from mixing and boiling answers
String internalPassword = mashPassword(challengeResponse[1]);

PasswordExt internalPasswordExt = new PasswordExt(new PBEKeySpec(internalPassword.toCharArray()), RECOVERY_PSEUDO_ID);
PasswordExt internalPasswordExt = new PasswordExt(new PBEKeySpec(internalPassword.toCharArray()),
RECOVERY_PSEUDO_ID);
PasswordExt password;
try {
password = root.getPassword(moduleID, container, false);
Expand Down Expand Up @@ -126,7 +127,8 @@ static public String recoverPassword(String[] answers, SecurePreferencesRoot roo
String internalPassword = mashPassword(answers); // create recovery password from answers

SecurePreferences node = recoveryNode(root, moduleID);
PasswordExt internalPasswordExt = new PasswordExt(new PBEKeySpec(internalPassword.toCharArray()), RECOVERY_PSEUDO_ID);
PasswordExt internalPasswordExt = new PasswordExt(new PBEKeySpec(internalPassword.toCharArray()),
RECOVERY_PSEUDO_ID);
try {
CryptoData encryptedData = new CryptoData(node.internalGet(PASSWORD_RECOVERY_KEY));
byte[] data = root.getCipher().decrypt(internalPasswordExt, encryptedData);
Expand All @@ -141,14 +143,14 @@ static private SecurePreferences recoveryNode(SecurePreferences root, String mod
}

/**
* Produces password from a list of answers:
* - all answers are put into one string
* - characters from alternating ends of the string are taken to form "mashed up" recovery
* password
* - the secure digest of the "mashed up" string is created
* Produces password from a list of answers: - all answers are put into one
* string - characters from alternating ends of the string are taken to form
* "mashed up" recovery password - the secure digest of the "mashed up" string
* is created
*
* This procedure should improve quality of the recovery password - even if answers
* are dictionary words, digested "mashed up" password should be of a reasonable good quality
* This procedure should improve quality of the recovery password - even if
* answers are dictionary words, digested "mashed up" password should be of a
* reasonable good quality
*/
static private String mashPassword(String[] answers) {
// form a string composing answers
Expand All @@ -173,7 +175,8 @@ static private String mashPassword(String[] answers) {
byte[] digested = digest.digest(StorageUtils.getBytes(mix.toString()));
internalPassword = EncodingUtils.encodeBase64(digested);
} catch (NoSuchAlgorithmException e) {
// just use the text as is; it is nicer to use digest but in this case no big deal
// just use the text as is; it is nicer to use digest but in this case no big
// deal
String msg = NLS.bind(SecAuthMessages.noDigest, DIGEST_ALGORITHM);
AuthPlugin.getDefault().logMessage(msg);
internalPassword = mix.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ public class ExtStorageModule {
public String description;
public List<String> hints;

public ExtStorageModule(String id, String obsoleteID, IConfigurationElement element, int priority, String name, String description, List<String> hints) {
public ExtStorageModule(String id, String obsoleteID, IConfigurationElement element, int priority, String name,
String description, List<String> hints) {
super();
this.element = element;
this.moduleID = id;
Expand Down Expand Up @@ -149,14 +150,16 @@ public List<ExtStorageModule> findAvailableModules(String expectedID) {
Object clazz;
try {
clazz = element.createExecutableExtension(CLASS_NAME);
// Bug 537833 - on some systems, the password provider does not work (e.g. Linux with KDE desktop) so these
// Bug 537833 - on some systems, the password provider does not work (e.g. Linux
// with KDE desktop) so these
// providers will request validation
if (clazz instanceof IValidatingPasswordProvider && !((IValidatingPasswordProvider) clazz).isValid())
continue;
} catch (CoreException e) {
continue;
}
allAvailableModules.add(new ExtStorageModule(moduleID, obsoletes, element, priority, name, description, suppliedHints));
allAvailableModules.add(
new ExtStorageModule(moduleID, obsoletes, element, priority, name, description, suppliedHints));
}

Collections.sort(allAvailableModules, (o1, o2) -> {
Expand Down Expand Up @@ -188,13 +191,15 @@ public PasswordProviderModuleExt findStorageModule(String expectedID) throws Sto
try {
clazz = module.element.createExecutableExtension(CLASS_NAME);
} catch (CoreException e) {
reportError(SecAuthMessages.instantiationFailed, module.element.getAttribute(CLASS_NAME), module.element, e);
reportError(SecAuthMessages.instantiationFailed, module.element.getAttribute(CLASS_NAME),
module.element, e);
continue;
}
if (!(clazz instanceof PasswordProvider))
continue;

PasswordProviderModuleExt result = new PasswordProviderModuleExt((PasswordProvider) clazz, module.moduleID, module.obsoleteID);
PasswordProviderModuleExt result = new PasswordProviderModuleExt((PasswordProvider) clazz, module.moduleID,
module.obsoleteID);

// cache the result
synchronized (modules) {
Expand Down Expand Up @@ -222,7 +227,7 @@ private void reportError(String template, String arg, IConfigurationElement elem
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Synch local cache with the registry
// Synch local cache with the registry
@Override
public void added(IExtension[] extensions) {
clearCaches();
Expand All @@ -244,7 +249,8 @@ public void removed(IExtensionPoint[] extensionPoints) {
}

/**
* Clear whole cache as priorities might have changed after new modules were added.
* Clear whole cache as priorities might have changed after new modules were
* added.
*/
public void clearCaches() {
synchronized (modules) {
Expand All @@ -264,10 +270,11 @@ public boolean isLoggedIn() {
}

protected HashSet<String> getDisabledModules() {
IScopeContext[] scopes = {ConfigurationScope.INSTANCE, DefaultScope.INSTANCE};
IScopeContext[] scopes = { ConfigurationScope.INSTANCE, DefaultScope.INSTANCE };
String defaultPreferenceValue = ""; //$NON-NLS-1$
IPreferencesService preferencesService = getPreferencesService();
String tmp = preferencesService.getString(AuthPlugin.PI_AUTH, IStorageConstants.DISABLED_PROVIDERS_KEY, defaultPreferenceValue, scopes);
String tmp = preferencesService.getString(AuthPlugin.PI_AUTH, IStorageConstants.DISABLED_PROVIDERS_KEY,
defaultPreferenceValue, scopes);
if (tmp == null || tmp.length() == 0)
return null;
HashSet<String> disabledModules = new HashSet<>();
Expand Down
Loading

0 comments on commit 7a73837

Please sign in to comment.