github-advanced-security[bot] commented on code in PR #1360: URL: https://github.com/apache/syncope/pull/1360#discussion_r3137509260
########## core/idrepo/logic/src/main/java/org/apache/syncope/core/logic/MfaLogic.java: ########## @@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.syncope.core.logic; + +import dev.samstevens.totp.code.CodeVerifier; +import dev.samstevens.totp.code.HashingAlgorithm; +import dev.samstevens.totp.qr.QrData; +import dev.samstevens.totp.qr.QrGenerator; +import dev.samstevens.totp.recovery.RecoveryCodeGenerator; +import dev.samstevens.totp.secret.SecretGenerator; +import dev.samstevens.totp.util.Utils; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.commons.lang3.StringUtils; +import org.apache.syncope.common.keymaster.client.api.DomainOps; +import org.apache.syncope.common.keymaster.client.api.KeymasterException; +import org.apache.syncope.common.keymaster.client.api.model.Domain; +import org.apache.syncope.common.lib.SyncopeClientException; +import org.apache.syncope.common.lib.SyncopeConstants; +import org.apache.syncope.common.lib.to.EntityTO; +import org.apache.syncope.common.lib.types.CipherAlgorithm; +import org.apache.syncope.common.lib.types.ClientExceptionType; +import org.apache.syncope.common.lib.types.IdRepoEntitlement; +import org.apache.syncope.common.lib.types.Mfa; +import org.apache.syncope.common.lib.types.MfaCheck; +import org.apache.syncope.core.persistence.api.EncryptorManager; +import org.apache.syncope.core.persistence.api.dao.NotFoundException; +import org.apache.syncope.core.persistence.api.dao.UserDAO; +import org.apache.syncope.core.persistence.api.utils.RealmUtils; +import org.apache.syncope.core.provisioning.api.data.UserDataBinder; +import org.apache.syncope.core.spring.security.AuthContextUtils; +import org.apache.syncope.core.spring.security.SecurityProperties; +import org.springframework.security.access.prepost.PreAuthorize; + +public class MfaLogic extends AbstractLogic<EntityTO> { + + protected final UserDataBinder userDataBinder; + + protected final UserDAO userDAO; + + protected final EncryptorManager encryptorManager; + + protected final DomainOps domainOps; + + protected final SecretGenerator totpSecretGenerator; + + protected final QrGenerator totpQrGenerator; + + protected final HashingAlgorithm totpHashingAlgorithm; + + protected final RecoveryCodeGenerator totpRecoveryCodeGenerator; + + protected final CodeVerifier totpCodeVerifier; + + protected final SecurityProperties securityProperties; + + public MfaLogic( + final UserDataBinder userDataBinder, + final UserDAO userDAO, + final EncryptorManager encryptorManager, + final DomainOps domainOps, + final SecretGenerator totpSecretGenerator, + final QrGenerator totpQrGenerator, + final HashingAlgorithm totpHashingAlgorithm, + final RecoveryCodeGenerator totpRecoveryCodeGenerator, + final CodeVerifier totpCodeVerifier, + final SecurityProperties securityProperties) { + + this.userDataBinder = userDataBinder; + this.userDAO = userDAO; + this.encryptorManager = encryptorManager; + this.domainOps = domainOps; + this.totpSecretGenerator = totpSecretGenerator; + this.totpQrGenerator = totpQrGenerator; + this.totpHashingAlgorithm = totpHashingAlgorithm; + this.totpRecoveryCodeGenerator = totpRecoveryCodeGenerator; + this.totpCodeVerifier = totpCodeVerifier; + this.securityProperties = securityProperties; + } + + @PreAuthorize("hasRole('" + IdRepoEntitlement.ANONYMOUS + "')") + public Mfa generate(final String username) { + Mfa generated; + try { + String secret = totpSecretGenerator.generate(); + + QrData qr = new QrData.Builder(). + secret(secret). + issuer("Apache Syncope"). + label("Apache Syncope " + AuthContextUtils.getDomain() + ":" + username). + algorithm(totpHashingAlgorithm). + build(); + String dataUri = Utils.getDataUriForImage(totpQrGenerator.generate(qr), totpQrGenerator.getImageMimeType()); + + List<String> recoveryCodes = securityProperties.getAdminUser().equals(username) + ? List.of() + : Stream.of(totpRecoveryCodeGenerator.generateCodes(10)).collect(Collectors.toList()); + + generated = new Mfa(secret, dataUri, recoveryCodes); + } catch (Exception e) { + LOG.error("While generating MFA secret for {}", username, e); Review Comment: ## CodeQL / Log Injection This log entry depends on a [user-provided value](1). [Show more details](https://github.com/apache/syncope/security/code-scanning/2607) ########## core/spring/src/main/java/org/apache/syncope/core/spring/security/UsernamePasswordAuthenticationProvider.java: ########## @@ -59,127 +57,98 @@ final DomainOps domainOps, final AuthDataAccessor dataAccessor, final UserProvisioningManager provisioningManager, - final DefaultCredentialChecker credentialChecker, final SecurityProperties securityProperties, final EncryptorManager encryptorManager) { this.domainOps = domainOps; this.dataAccessor = dataAccessor; this.provisioningManager = provisioningManager; - this.credentialChecker = credentialChecker; this.securityProperties = securityProperties; this.encryptorManager = encryptorManager; } @Override public Authentication authenticate(final Authentication authentication) { - String domainKey; + String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain(); Optional<Domain> domain; - if (SyncopeConstants.MASTER_DOMAIN.equals( - SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain())) { - - domainKey = SyncopeConstants.MASTER_DOMAIN; + if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) { domain = Optional.empty(); } else { - domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain(); try { domain = Optional.of(domainOps.read(domainKey)); } catch (NotFoundException | KeymasterException e) { throw new BadCredentialsException("Could not find domain " + domainKey, e); } } + AuthDataAccessor.UsernamePasswordAuthResult authResult = AuthContextUtils.callAsAdmin( + domainKey, + () -> dataAccessor.authenticate(domain, authentication)); + Mutable<String> username = new MutableObject<>(); - Boolean authenticated; - Mutable<String> delegationKey = new MutableObject<>(); - - if (securityProperties.getAnonymousUser().equals(authentication.getName())) { - username.setValue(securityProperties.getAnonymousUser()); - credentialChecker.checkIsDefaultAnonymousKeyInUse(); - authenticated = authentication.getCredentials().toString().equals(securityProperties.getAnonymousKey()); - } else if (securityProperties.getAdminUser().equals(authentication.getName())) { - username.setValue(securityProperties.getAdminUser()); - if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) { - credentialChecker.checkIsDefaultAdminPasswordInUse(); - authenticated = encryptorManager.getInstance().verify( - authentication.getCredentials().toString(), - securityProperties.getAdminPasswordAlgorithm(), - securityProperties.getAdminPassword()); - } else if (domain.isPresent()) { - authenticated = encryptorManager.getInstance().verify( - authentication.getCredentials().toString(), - domain.get().getAdminCipherAlgorithm(), - domain.get().getAdminPassword()); - } else { - LOG.error("Could not read admin credentials for domain {}", domainKey); - authenticated = false; - } - } else { - AuthDataAccessor.UsernamePasswordAuthResult authResult = AuthContextUtils.callAsAdmin( - domainKey, - () -> dataAccessor.authenticate(domainKey, authentication)); - authenticated = authResult.authenticated(); - if (authResult.user() != null && authResult.authenticated() != null) { - username.setValue(authResult.user().getUsername()); - - if (!authenticated) { - AuthContextUtils.runAsAdmin(domainKey, () -> provisioningManager.internalSuspend( - authResult.user().getKey(), securityProperties.getAdminUser(), "Failed authentication")); - } + if (authResult.user() != null) { + username.setValue(authResult.user().getUsername()); + + if (!authResult.isSuccess()) { + AuthContextUtils.runAsAdmin(domainKey, () -> provisioningManager.internalSuspend( + authResult.user().getKey(), securityProperties.getAdminUser(), "Failed authentication")); } - delegationKey.setValue(authResult.delegationKey()); } + if (username.get() == null) { username.setValue(authentication.getPrincipal().toString()); } return finalizeAuthentication( - authenticated, domainKey, username.get(), delegationKey.get(), authentication); + domainKey, + username.get(), + authResult, + authentication); } protected Authentication finalizeAuthentication( - final Boolean authenticated, final String domain, final String username, - final String delegationKey, + final AuthDataAccessor.UsernamePasswordAuthResult authResult, final Authentication authentication) { - UsernamePasswordAuthenticationToken token; - if (BooleanUtils.isTrue(authenticated)) { - token = AuthContextUtils.callAsAdmin(domain, () -> { + if (authResult.isSuccess()) { + UsernamePasswordAuthenticationToken token = AuthContextUtils.callAsAdmin(domain, () -> { UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken( username, null, - dataAccessor.getAuthorities(username, delegationKey)); + authResult.authorities()); upat.setDetails(authentication.getDetails()); dataAccessor.audit( domain, username, - delegationKey, + authResult.delegationKey(), OpEvent.Outcome.SUCCESS, true, authentication, - "Successfully authenticated, with entitlements: " + upat.getAuthorities()); + "Successfully authenticated, with entitlements: " + authResult.authorities()); return upat; }); - LOG.debug("User {} successfully authenticated, with entitlements {}", username, token.getAuthorities()); - } else { - dataAccessor.audit( - domain, - username, - delegationKey, - OpEvent.Outcome.FAILURE, - false, - authentication, - "Not authenticated"); - - LOG.debug("User {} not authenticated", username); - - throw new BadCredentialsException("User " + username + " not authenticated"); + LOG.debug("User {} successfully authenticated, with entitlements {}", username, authResult.authorities()); Review Comment: ## CodeQL / Insertion of sensitive information into log files This [potentially sensitive information](1) is written to a log file. [Show more details](https://github.com/apache/syncope/security/code-scanning/2608) ########## common/idrepo/rest-api/src/main/java/org/apache/syncope/common/rest/api/service/MfaService.java: ########## @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.syncope.common.rest.api.service; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.headers.Header; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.constraints.NotNull; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.HEAD; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.apache.syncope.common.lib.types.Mfa; +import org.apache.syncope.common.lib.types.MfaCheck; +import org.apache.syncope.common.rest.api.RESTHeaders; + +/** + * REST operations for MFA management. + */ +@Tag(name = "MFA") +@Path("mfa") +public interface MfaService extends JAXRSService { Review Comment: ## CodeQL / Constant interface anti-pattern Type MfaService implements constant interface [JAXRSService](1). [Show more details](https://github.com/apache/syncope/security/code-scanning/2609) ########## core/spring/src/test/java/org/apache/syncope/core/spring/security/MfaTest.java: ########## @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.syncope.core.spring.security; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.samstevens.totp.code.CodeGenerator; +import dev.samstevens.totp.code.CodeVerifier; +import dev.samstevens.totp.code.DefaultCodeGenerator; +import dev.samstevens.totp.code.DefaultCodeVerifier; +import dev.samstevens.totp.code.HashingAlgorithm; +import dev.samstevens.totp.exceptions.CodeGenerationException; +import dev.samstevens.totp.secret.DefaultSecretGenerator; +import dev.samstevens.totp.secret.SecretGenerator; +import dev.samstevens.totp.time.SystemTimeProvider; +import dev.samstevens.totp.time.TimeProvider; +import java.time.Instant; +import org.junit.jupiter.api.Test; + +public class MfaTest { + + @Test + public void check() throws CodeGenerationException { + SecretGenerator totpSecretGenerator = new DefaultSecretGenerator(64); + String secret = totpSecretGenerator.generate(); + + CodeGenerator codeGenerator = new DefaultCodeGenerator(HashingAlgorithm.SHA512); + String otp = codeGenerator.generate(secret, Math.floorDiv(Instant.now().getEpochSecond(), 30)); + + TimeProvider timeProvider = new SystemTimeProvider(); + CodeVerifier verifier = new DefaultCodeVerifier(codeGenerator, timeProvider); + + assertTrue(verifier.isValidCode(secret, otp)); + assertFalse(verifier.isValidCode(secret, String.valueOf(Integer.parseInt(otp) - 1))); Review Comment: ## CodeQL / Missing catch of NumberFormatException Potential uncaught 'java.lang.NumberFormatException'. [Show more details](https://github.com/apache/syncope/security/code-scanning/2611) ########## client/idrepo/enduser/src/main/java/org/apache/syncope/client/enduser/pages/SelfPasswordReset.java: ########## @@ -52,6 +54,9 @@ protected static final String SELF_PWD_RESET = "page.selfPwdReset"; + @SpringBean + protected ConfParamOps confParamOps; Review Comment: ## CodeQL / Field masks field in super class This field shadows another field called [confParamOps](1) in a superclass. [Show more details](https://github.com/apache/syncope/security/code-scanning/2610) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
