Skip to content

Commit

Permalink
Merge pull request #596 from kagemomiji/issue-fix-lazy-di
Browse files Browse the repository at this point in the history
Fix circular reference
  • Loading branch information
kagemomiji authored Sep 18, 2024
2 parents 7b56e48 + 624f06b commit a228ac8
Show file tree
Hide file tree
Showing 10 changed files with 195 additions and 164 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import org.airsonic.player.command.CredentialsManagementCommand.CredentialsCommand;
import org.airsonic.player.domain.User;
import org.airsonic.player.domain.UserCredential.App;
import org.airsonic.player.security.GlobalSecurityConfig;
import org.airsonic.player.security.PasswordEncoderConfig;
import org.airsonic.player.service.SecurityService;
import org.airsonic.player.service.SettingsService;
import org.airsonic.player.validator.CredentialsManagementValidators.CredentialCreateChecks;
Expand Down Expand Up @@ -63,11 +63,11 @@ protected void displayForm(Authentication user, ModelMap map) {
c.addDisplayComment("migratecred");
}

if (GlobalSecurityConfig.OPENTEXT_ENCODERS.contains(c.getEncoder())) {
if (PasswordEncoderConfig.OPENTEXT_ENCODERS.contains(c.getEncoder())) {
c.addDisplayComment("opentextcred");
}

if (GlobalSecurityConfig.DECODABLE_ENCODERS.contains(c.getEncoder())) {
if (PasswordEncoderConfig.DECODABLE_ENCODERS.contains(c.getEncoder())) {
c.addDisplayComment("decodablecred");
} else {
c.addDisplayComment("nondecodablecred");
Expand All @@ -88,8 +88,8 @@ protected void displayForm(Authentication user, ModelMap map) {
map.addAttribute("apps", EnumSet.allOf(App.class));
map.addAttribute("appsMap", EnumSet.allOf(App.class).stream().collect(toMap(a -> a, a -> new BeanMap(a))));

map.addAttribute("decodableEncoders", GlobalSecurityConfig.NONLEGACY_DECODABLE_ENCODERS);
map.addAttribute("nonDecodableEncoders", GlobalSecurityConfig.NONLEGACY_NONDECODABLE_ENCODERS);
map.addAttribute("decodableEncoders", PasswordEncoderConfig.NONLEGACY_DECODABLE_ENCODERS);
map.addAttribute("nonDecodableEncoders", PasswordEncoderConfig.NONLEGACY_NONDECODABLE_ENCODERS);
map.addAttribute("encoderAliases", ENCODER_ALIASES);

map.addAttribute("preferredEncoderNonDecodableAllowed", securityService.getPreferredPasswordEncoder(true));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.airsonic.player.domain;

import org.airsonic.player.security.GlobalSecurityConfig;
import org.airsonic.player.security.PasswordDecoder;
import org.airsonic.player.security.PasswordEncoderConfig;
import org.springframework.util.StringUtils;

import jakarta.persistence.Column;
Expand Down Expand Up @@ -245,16 +245,16 @@ public boolean updateEncoder(String newEncoder, boolean reencodePlaintextNewCred
}
if (!this.encoder.equals(newEncoder) || reencodePlaintextNewCreds) {
if (reencodePlaintextNewCreds) {
String newCredential = GlobalSecurityConfig.ENCODERS.get(newEncoder).encode(this.credential);
String newCredential = PasswordEncoderConfig.ENCODERS.get(newEncoder).encode(this.credential);
if (!this.credential.equals(newCredential)) {
this.credential = newCredential;
this.setUpdated(Instant.now().truncatedTo(ChronoUnit.MICROS));
}
} else if (GlobalSecurityConfig.DECODABLE_ENCODERS.contains(this.encoder)) {
} else if (PasswordEncoderConfig.DECODABLE_ENCODERS.contains(this.encoder)) {
try {
PasswordDecoder decoder = (PasswordDecoder) GlobalSecurityConfig.ENCODERS.get(this.encoder);
PasswordDecoder decoder = (PasswordDecoder) PasswordEncoderConfig.ENCODERS.get(this.encoder);
String decodedCredential = decoder.decode(this.credential);
this.credential = GlobalSecurityConfig.ENCODERS.get(newEncoder).encode(decodedCredential);
this.credential = PasswordEncoderConfig.ENCODERS.get(newEncoder).encode(decodedCredential);
this.setUpdated(Instant.now().truncatedTo(ChronoUnit.MICROS));
} catch (Exception e) {
return false;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
package org.airsonic.player.security;

import com.google.common.collect.ImmutableMap;
import org.airsonic.player.service.JWTSecurityService;
import org.airsonic.player.service.SecurityService;
import org.airsonic.player.service.SettingsService;
import org.airsonic.player.service.sonos.SonosLinkSecurityInterceptor.SonosJWTVerification;
import org.apache.commons.codec.binary.Base16;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AbstractAuthenticationToken;
Expand All @@ -25,13 +21,6 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
Expand All @@ -42,12 +31,6 @@
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.airsonic.player.security.MultipleCredsMatchingAuthenticationProvider.SALT_TOKEN_MECHANISM_SPECIALIZATION;

@Configuration
@EnableWebSecurity
Expand All @@ -57,117 +40,20 @@ public class GlobalSecurityConfig {

static final String FAILURE_URL = "/login?error";

@SuppressWarnings("deprecation")
public static final Map<String, PasswordEncoder> ENCODERS = new HashMap<>(ImmutableMap
.<String, PasswordEncoder>builderWithExpectedSize(19)
.put("bcrypt", new BCryptPasswordEncoder())
.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder())
.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder())
.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"))
.put("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8())
.put("scrypt", SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8())
.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"))
.put("SHA-256", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"))
.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder())
.put("argon2", Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8())

// base decodable encoders
.put("noop", new PasswordEncoderDecoderWrapper(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance(), p -> p))
.put("hex", new HexPasswordEncoder())
.put("encrypted-AES-GCM", new AesGcmPasswordEncoder()) // placeholder (real instance created below)

// base decodable encoders that rely on salt+token being passed in (not stored in db with this type)
.put("noop" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(p -> p))
.put("hex" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(new HexPasswordEncoder()))
.put("encrypted-AES-GCM" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(new AesGcmPasswordEncoder())) // placeholder (real instance created below)

// TODO: legacy marked base encoders, to be upgraded to one-way formats at breaking version change
.put("legacynoop", new PasswordEncoderDecoderWrapper(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance(), p -> p))
.put("legacyhex", new HexPasswordEncoder())

.put("legacynoop" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(p -> p))
.put("legacyhex" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(new HexPasswordEncoder()))
.build());

public static final Set<String> OPENTEXT_ENCODERS = Set.of("noop", "hex", "legacynoop", "legacyhex");
public static final Set<String> DECODABLE_ENCODERS = Set.of("noop", "hex", "logacynoop", "encrypted-AES-GCM");
public static final Set<String> NONLEGACY_ENCODERS = ENCODERS.keySet().stream()
.filter(e -> !StringUtils.containsAny(e, "legacy", SALT_TOKEN_MECHANISM_SPECIALIZATION))
.collect(Collectors.toSet());
public static final Set<String> NONLEGACY_DECODABLE_ENCODERS = SetUtils.intersection(DECODABLE_ENCODERS, NONLEGACY_ENCODERS);
public static final Set<String> NONLEGACY_NONDECODABLE_ENCODERS = SetUtils.difference(NONLEGACY_ENCODERS, DECODABLE_ENCODERS);

@Autowired
private CsrfSecurityRequestMatcher csrfSecurityRequestMatcher;

@Autowired
private SecurityService securityService;

@Autowired
SettingsService settingsService;
private SettingsService settingsService;

@Lazy
@Autowired
MultipleCredsMatchingAuthenticationProvider multipleCredsProvider;
private MultipleCredsMatchingAuthenticationProvider multipleCredsProvider;

@Autowired
SonosJWTVerification sonosJwtVerification;

@Bean
public PasswordEncoder passwordEncoder() {
boolean generatedKeys = false;

String encryptionKeyPass = settingsService.getEncryptionPassword();
if (StringUtils.isBlank(encryptionKeyPass)) {
LOG.warn("Generating new encryption key password");
encryptionKeyPass = JWTSecurityService.generateKey();
settingsService.setEncryptionPassword(encryptionKeyPass);
generatedKeys = true;
}

String encryptionKeySalt = settingsService.getEncryptionSalt();
if (StringUtils.isBlank(encryptionKeySalt)) {
LOG.warn("Generating new encryption key salt");
Base16 base16 = new Base16();
encryptionKeySalt = base16.encodeToString(KeyGenerators.secureRandom(16).generateKey());
settingsService.setEncryptionSalt(encryptionKeySalt);
generatedKeys = true;
}

if (generatedKeys) {
settingsService.save();
}

AesGcmPasswordEncoder encoder = new AesGcmPasswordEncoder(encryptionKeyPass, encryptionKeySalt);
ENCODERS.put("encrypted-AES-GCM", encoder);
ENCODERS.put("encrypted-AES-GCM" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(encoder));

DelegatingPasswordEncoder pEncoder = new DelegatingPasswordEncoder(settingsService.getNonDecodablePasswordEncoder(), ENCODERS) {
@Override
public boolean upgradeEncoding(String prefixEncodedPassword) {
PasswordEncoder encoder = ENCODERS.get(StringUtils.substringBetween(prefixEncodedPassword, "{", "}"));
if (encoder != null) {
return encoder.upgradeEncoding(StringUtils.substringAfter(prefixEncodedPassword, "}"));
}

return false;
}
};

pEncoder.setDefaultPasswordEncoderForMatches(new PasswordEncoder() {
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return false;
}

@Override
public String encode(CharSequence rawPassword) {
return null;
}
});

return pEncoder;
}
private SonosJWTVerification sonosJwtVerification;

@EventListener
public void loginFailureListener(AbstractAuthenticationFailureEvent event) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package org.airsonic.player.security;

import com.google.common.collect.ImmutableMap;
import org.airsonic.player.service.JWTSecurityService;
import org.airsonic.player.service.SettingsService;
import org.apache.commons.codec.binary.Base16;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.airsonic.player.security.MultipleCredsMatchingAuthenticationProvider.SALT_TOKEN_MECHANISM_SPECIALIZATION;

@Configuration
public class PasswordEncoderConfig {

private static final Logger LOG = LoggerFactory.getLogger(PasswordEncoderConfig.class);

@Autowired
private SettingsService settingsService;

@SuppressWarnings("deprecation")
public static final Map<String, PasswordEncoder> ENCODERS = new HashMap<>(ImmutableMap
.<String, PasswordEncoder>builderWithExpectedSize(19)
.put("bcrypt", new BCryptPasswordEncoder())
.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder())
.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder())
.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"))
.put("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8())
.put("scrypt", SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8())
.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"))
.put("SHA-256", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"))
.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder())
.put("argon2", Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8())

// base decodable encoders
.put("noop",
new PasswordEncoderDecoderWrapper(
org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance(), p -> p))
.put("hex", new HexPasswordEncoder())
.put("encrypted-AES-GCM", new AesGcmPasswordEncoder()) // placeholder (real instance created below)

// base decodable encoders that rely on salt+token being passed in (not stored
// in db with this type)
.put("noop" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(p -> p))
.put("hex" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(new HexPasswordEncoder()))
.put("encrypted-AES-GCM" + SALT_TOKEN_MECHANISM_SPECIALIZATION,
new SaltedTokenPasswordEncoder(new AesGcmPasswordEncoder())) // placeholder (real instance created
// below)

// TODO: legacy marked base encoders, to be upgraded to one-way formats at
// breaking version change
.put("legacynoop",
new PasswordEncoderDecoderWrapper(
org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance(), p -> p))
.put("legacyhex", new HexPasswordEncoder())

.put("legacynoop" + SALT_TOKEN_MECHANISM_SPECIALIZATION, new SaltedTokenPasswordEncoder(p -> p))
.put("legacyhex" + SALT_TOKEN_MECHANISM_SPECIALIZATION,
new SaltedTokenPasswordEncoder(new HexPasswordEncoder()))
.build());

public static final Set<String> NONLEGACY_ENCODERS = ENCODERS.keySet().stream()
.filter(e -> !StringUtils.containsAny(e, "legacy", SALT_TOKEN_MECHANISM_SPECIALIZATION))
.collect(Collectors.toSet());
public static final Set<String> DECODABLE_ENCODERS = Set.of("noop", "hex", "logacynoop", "encrypted-AES-GCM");
public static final Set<String> NONLEGACY_DECODABLE_ENCODERS = SetUtils.intersection(DECODABLE_ENCODERS,
NONLEGACY_ENCODERS);
public static final Set<String> NONLEGACY_NONDECODABLE_ENCODERS = SetUtils.difference(NONLEGACY_ENCODERS,
DECODABLE_ENCODERS);

public static final Set<String> OPENTEXT_ENCODERS = Set.of("noop", "hex", "legacynoop", "legacyhex");

@Bean
public PasswordEncoder passwordEncoder() {
boolean generatedKeys = false;

String encryptionKeyPass = settingsService.getEncryptionPassword();
if (StringUtils.isBlank(encryptionKeyPass)) {
LOG.warn("Generating new encryption key password");
encryptionKeyPass = JWTSecurityService.generateKey();
settingsService.setEncryptionPassword(encryptionKeyPass);
generatedKeys = true;
}

String encryptionKeySalt = settingsService.getEncryptionSalt();
if (StringUtils.isBlank(encryptionKeySalt)) {
LOG.warn("Generating new encryption key salt");
Base16 base16 = new Base16();
encryptionKeySalt = base16.encodeToString(KeyGenerators.secureRandom(16).generateKey());
settingsService.setEncryptionSalt(encryptionKeySalt);
generatedKeys = true;
}

if (generatedKeys) {
settingsService.save();
}

AesGcmPasswordEncoder encoder = new AesGcmPasswordEncoder(encryptionKeyPass, encryptionKeySalt);
ENCODERS.put("encrypted-AES-GCM", encoder);
ENCODERS.put("encrypted-AES-GCM" + SALT_TOKEN_MECHANISM_SPECIALIZATION,
new SaltedTokenPasswordEncoder(encoder));

DelegatingPasswordEncoder pEncoder = new DelegatingPasswordEncoder(
settingsService.getNonDecodablePasswordEncoder(), ENCODERS) {
@Override
public boolean upgradeEncoding(String prefixEncodedPassword) {
PasswordEncoder encoder = ENCODERS.get(StringUtils.substringBetween(prefixEncodedPassword, "{", "}"));
if (encoder != null) {
return encoder.upgradeEncoding(StringUtils.substringAfter(prefixEncodedPassword, "}"));
}

return false;
}
};

pEncoder.setDefaultPasswordEncoderForMatches(new PasswordEncoder() {
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return false;
}

@Override
public String encode(CharSequence rawPassword) {
return null;
}
});

return pEncoder;
}

}
Loading

0 comments on commit a228ac8

Please sign in to comment.