From 2b11d338e059275ccb074c0f08a0019cac6b78ea Mon Sep 17 00:00:00 2001
From: jack <jack.su@pollex.com.tw>
Date: 星期二, 12 九月 2023 15:49:10 +0800
Subject: [PATCH] [UPDATE] 解決弱點Unlogged security exception

---
 pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java |  104 +++++++++------------------------------------------
 1 files changed, 19 insertions(+), 85 deletions(-)

diff --git a/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java b/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java
index afef2d0..355bfcf 100644
--- a/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java
+++ b/pamapi/src/main/java/com/pollex/pam/security/provider/EServiceAuthenticationProvider.java
@@ -1,26 +1,19 @@
 package com.pollex.pam.security.provider;
 
-import com.fasterxml.jackson.core.JsonProcessingException;
+import com.pollex.pam.business.domain.Consultant;
+import com.pollex.pam.business.enums.ConsultantDetailEnum;
+import com.pollex.pam.business.repository.ConsultantRepository;
+import com.pollex.pam.business.service.EServiceConnectService;
+import com.pollex.pam.business.service.dto.EServiceResponse;
+import com.pollex.pam.business.web.errors.ConsultantDisableException;
+import com.pollex.pam.business.config.AppProperties;
+import com.pollex.pam.business.security.token.EServiceAuthenticationToken;
+import com.pollex.pam.business.web.errors.EServiceErrorException;
 import com.pollex.pam.config.ApplicationProperties;
-import com.pollex.pam.domain.Consultant;
-import com.pollex.pam.enums.ConsultantDetailEnum;
-import com.pollex.pam.repository.ConsultantRepository;
-import com.pollex.pam.security.token.EServiceAuthenticationToken;
-import com.pollex.pam.service.dto.EServiceResponse;
-import com.pollex.pam.web.rest.errors.ConsultantDisableException;
-import com.pollex.pam.web.rest.errors.EServiceErrorException;
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.ssl.SSLContexts;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.*;
-import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
-import org.springframework.http.converter.HttpMessageConverter;
-import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.AuthenticationException;
@@ -28,19 +21,9 @@
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.stereotype.Component;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.util.UriComponentsBuilder;
 
-import javax.net.ssl.SSLContext;
 import java.security.GeneralSecurityException;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-import java.time.Instant;
 import java.util.*;
-
-import static com.pollex.pam.enums.ConsultantStatusEnum.DISABLE;
 
 @Component
 public class EServiceAuthenticationProvider {
@@ -49,21 +32,24 @@
     private static final Logger log = LoggerFactory.getLogger(EServiceAuthenticationProvider.class);
 
     @Autowired
-    ApplicationProperties applicationProperty;
+    ApplicationProperties applicationProperties;
 
     @Autowired
     ConsultantRepository consultantRepository;
+
+    @Autowired
+    EServiceConnectService eServiceConnectService;
 
     public Authentication authenticate(EServiceAuthenticationToken authenticationToken) throws AuthenticationException {
         String account = authenticationToken.getPrincipal();
         String credentials = authenticationToken.getCredentials();
 
-        if(applicationProperty.isMockLogin()){
+        if(applicationProperties.isMockLogin()){
             return getConsultantTokenAndRecordLoginTime(account, credentials);
         }
 
         try {
-            ResponseEntity<EServiceResponse> responseEntity = loginByEService(account, credentials);
+            ResponseEntity<EServiceResponse> responseEntity = eServiceConnectService.loginByEService(account, credentials);
             if(HttpStatus.OK.equals(responseEntity.getStatusCode())) {
                 EServiceResponse eServiceResponse = responseEntity.getBody();
                 log.debug("eService response = {}", eServiceResponse);
@@ -72,27 +58,20 @@
                     return getConsultantTokenAndRecordLoginTime(account, credentials);
                 }
                 else {
-                    throw new EServiceErrorException(eServiceResponse.getMsg());
+                	log.debug("account:{},error:{}",account,eServiceResponse.getMsg());
+                    throw new EServiceErrorException("撣唾��Ⅳ�隤�");
                 }
             }
 
             throw new RuntimeException("eService http error!, response http status code = " + responseEntity.getStatusCode());
-        } catch (JsonProcessingException e) {
-            throw new RuntimeException("convert to json processing error!");
         } catch (GeneralSecurityException e) {
+        	log.error("General Security SSL error!",e);
             throw new RuntimeException("General Security SSL error!");
         }
     }
 
     private UsernamePasswordAuthenticationToken getConsultantTokenAndRecordLoginTime(String account, String credential) throws ConsultantDisableException {
-        Consultant consultant = consultantRepository.findOneByAgentNo(account).orElseThrow(() -> new UsernameNotFoundException("閰脤“����蒂銝��慦�像�蝟餌絞銝�"));
-
-        if(consultant.getStatus() == DISABLE) {
-            throw new ConsultantDisableException();
-        }
-
-        consultant.setLatestLoginTime(Instant.now());
-        consultantRepository.save(consultant);
+        Consultant consultant = consultantRepository.findOneByAgentNo(account).orElseThrow(() -> new UsernameNotFoundException("撣唾��Ⅳ�隤�"));
 
         List<GrantedAuthority> grantedAuths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
         UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account, credential, grantedAuths);
@@ -104,50 +83,5 @@
         authenticationToken.setDetails(details);
 
         return authenticationToken;
-    }
-
-    private ResponseEntity<EServiceResponse> loginByEService(String account, String paxxword) throws JsonProcessingException, GeneralSecurityException {
-        RestTemplate restTemplate = getTrustAllRestTemplate();
-        settingMessageConvertersToSpecifyType(restTemplate, MediaType.ALL);
-
-        String urlTemplate = UriComponentsBuilder.fromHttpUrl(applicationProperty.geteServiceLoginUrl())
-            .queryParam("func", applicationProperty.geteServiceLoginFunc())
-            .queryParam("id", account)
-            .queryParam("pin", paxxword)
-            .queryParam("pwd", paxxword)
-            .queryParam("sys", applicationProperty.geteServiceLoginSys())
-            .queryParam("transactionId", UUID.randomUUID().toString())
-            .encode().toUriString();
-
-        log.debug("http get loginByEService, url = {}", urlTemplate);
-
-        HttpHeaders headers = new HttpHeaders();
-        headers.setContentType(MediaType.APPLICATION_JSON);
-
-        HttpEntity<String> entity = new HttpEntity<>(headers);
-        return restTemplate.exchange(urlTemplate, HttpMethod.GET, entity, EServiceResponse.class);
-    }
-
-    private RestTemplate getTrustAllRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
-        SSLContext sslContext = SSLContexts.custom()
-            .loadTrustMaterial(null, (X509Certificate[] x509Certs, String s) -> true)
-            .build();
-        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
-        CloseableHttpClient httpClient = HttpClients.custom()
-            .setSSLSocketFactory(csf)
-            .build();
-        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
-        requestFactory.setHttpClient(httpClient);
-        requestFactory.setConnectTimeout(300000);
-        requestFactory.setReadTimeout(300000);
-        return new RestTemplate(requestFactory);
-    }
-
-    private void settingMessageConvertersToSpecifyType(RestTemplate restTemplate, MediaType mediaType) {
-        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
-        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
-        converter.setSupportedMediaTypes(Collections.singletonList(mediaType));
-        messageConverters.add(converter);
-        restTemplate.setMessageConverters(messageConverters);
     }
 }

--
Gitblit v1.8.0