revised includes edited user entity

This commit is contained in:
heyethereum
2024-07-11 00:22:27 +08:00
parent 878c8e2349
commit ccd6baf0d7
24 changed files with 635 additions and 15 deletions

View File

@@ -0,0 +1,50 @@
package com.safeqr.app.qrcode.service;
import com.safeqr.app.qrcode.dto.QRCodePayload;
import com.safeqr.app.qrcode.entity.QRCodeType;
import com.safeqr.app.qrcode.repository.QRCodeTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@Service
public class QRCodeTypeService {
@Autowired
private QRCodeTypeRepository qrCodeTypeRepository;
@Autowired
private SafeBrowsingService safeBrowsingService;
public List<QRCodeType> getAllTypes() {
return qrCodeTypeRepository.findAll();
}
public Mono<String> detectType(QRCodePayload payload) {
String data = payload.getData();
List<QRCodeType> configs = qrCodeTypeRepository.findAll();
for (QRCodeType config : configs) {
if (data.startsWith(config.getPrefix())) {
if ("URL".equals(config.getType())) {
try
{
return safeBrowsingService.isSafeUrl(data)
.map(isSafe -> isSafe ? "Safe URL" : "Unsafe URL");
} catch (NoSuchAlgorithmException e)
{
// TODO Auto-generated catch block
return Mono.just("Error checking URL safety: " + e.getMessage());
}
}
return Mono.just(config.getType());
}
}
return Mono.just("Unknown");
}
}

View File

@@ -0,0 +1,26 @@
package com.safeqr.app.qrcode.service;
import com.safeqr.app.qrcode.dto.QRCodePayload;
import com.safeqr.app.qrcode.dto.RedirectCountResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class RedirectCountService {
public Mono<RedirectCountResponse> countRedirects(QRCodePayload payload) {
String url = payload.getData();
return WebClient.create()
.get()
.uri(url)
.exchangeToMono(response -> {
RedirectCountResponse redirectCountResponse = new RedirectCountResponse();
redirectCountResponse.setRedirectCount(response.cookies().size());
redirectCountResponse.setMessage("Redirect count calculated.");
return Mono.just(redirectCountResponse);
});
}
}

View File

@@ -0,0 +1,101 @@
package com.safeqr.app.qrcode.service;
import com.safeqr.app.qrcode.dto.SafeBrowsingRequest;
import com.safeqr.app.qrcode.dto.SafeBrowsingResponse;
import com.safeqr.app.qrcode.entity.SafeBrowsingCache;
import com.safeqr.app.qrcode.repository.SafeBrowsingCacheRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class SafeBrowsingService {
@Value("${google.safebrowsing.api.key}")
private String apiKey;
private final WebClient webClient;
private final SafeBrowsingCacheRepository cacheRepository;
public SafeBrowsingService(WebClient.Builder webClientBuilder, SafeBrowsingCacheRepository cacheRepository) {
this.webClient = webClientBuilder.baseUrl("https://safebrowsing.googleapis.com/v4/threatMatches:find").build();
this.cacheRepository = cacheRepository;
}
@PostConstruct
public void initializeCache() {
// Fetch the full list of hashes from Google and store them in the local database.
// This is a placeholder method. You need to implement the logic to fetch and store the hashes.
fetchAndStoreFullHashes();
}
public Mono<Boolean> isSafeUrl(String url) throws NoSuchAlgorithmException {
String hashPrefix = getHashPrefix(url);
Optional<SafeBrowsingCache> cachedResult = cacheRepository.findByHashPrefix(hashPrefix);
if (cachedResult.isPresent()) {
return Mono.just(cachedResult.get().getFullHash().isEmpty());
}
// If not in cache, call Google Safe Browsing API
String requestUrl = "?key=" + apiKey;
SafeBrowsingRequest request = new SafeBrowsingRequest(
new SafeBrowsingRequest.Client("safeqr-fyp-24", "1.0"),
new SafeBrowsingRequest.ThreatInfo(
List.of("MALWARE", "SOCIAL_ENGINEERING"),
List.of("WINDOWS"),
List.of("URL"),
List.of(new SafeBrowsingRequest.ThreatInfo.ThreatEntry(url))
)
);
return webClient.post()
.uri(requestUrl)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.bodyValue(request)
.retrieve()
.bodyToMono(SafeBrowsingResponse.class)
.map(response -> {
boolean isSafe = response.getMatches() == null || response.getMatches().isEmpty();
if (!isSafe) {
SafeBrowsingResponse.ThreatMatch match = response.getMatches().get(0);
SafeBrowsingCache cache = new SafeBrowsingCache();
cache.setId(UUID.randomUUID());
cache.setHashPrefix(hashPrefix);
cache.setThreatType(match.getThreatType());
cache.setPlatformType(match.getPlatformType());
cache.setThreatEntryType(match.getThreatEntryType());
cache.setFullHash(match.getThreat().getHash());
cacheRepository.save(cache);
}
return isSafe;
});
}
private String getHashPrefix(String url) throws NoSuchAlgorithmException {
// Compute hash prefix of the URL (first 4 bytes of SHA-256)
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(url.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash).substring(0, 4);
}
private void fetchAndStoreFullHashes() {
// Implement the logic to fetch and store the full list of hashes from Google Safe Browsing API
// This could involve using the threatListUpdates:fetch endpoint
}
}

View File

@@ -0,0 +1,28 @@
package com.safeqr.app.qrcode.service;
import com.safeqr.app.qrcode.dto.QRCodePayload;
import com.safeqr.app.qrcode.dto.URLVerificationResponse;
import org.springframework.stereotype.Service;
@Service
public class URLVerificationService {
public URLVerificationResponse verifyURL(QRCodePayload payload) {
URLVerificationResponse response = new URLVerificationResponse();
try {
java.net.URL url = new java.net.URL(payload.getData());
String protocol = url.getProtocol();
if ("https".equalsIgnoreCase(protocol)) {
response.setSecure(true);
response.setMessage("The connection is secure.");
} else {
response.setSecure(false);
response.setMessage("The connection is not secure.");
}
} catch (Exception e) {
response.setSecure(false);
response.setMessage("Invalid URL.");
}
return response;
}
}

View File

@@ -0,0 +1,92 @@
package com.safeqr.app.qrcode.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.safeqr.app.qrcode.dto.QRCodePayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
@Service
public class VirusTotalService {
private static final Logger logger = LoggerFactory.getLogger(VirusTotalService.class);
@Value("${virustotal.api.key}")
private String apiKey;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public VirusTotalService() {
this.restTemplate = new RestTemplate();
this.objectMapper = new ObjectMapper();
}
public String scanURL(QRCodePayload payload) {
String urlToScan = payload.getData();
logger.info("Scanning URL: {}", urlToScan);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.virustotal.com/api/v3/urls");
HttpHeaders headers = new HttpHeaders();
headers.set("accept", "application/json");
headers.set("content-type", "application/x-www-form-urlencoded");
headers.set("x-apikey", apiKey);
String body = "url=" + urlToScan;
HttpEntity<String> request = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(builder.toUriString(), request, String.class);
logger.info("Response from VirusTotal scan: {}", response.getBody());
try {
Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
return (String) data.get("id");
} catch (Exception e) {
logger.error("Error parsing response from VirusTotal scan", e);
throw new RuntimeException("Error parsing response from VirusTotal scan", e);
}
}
public boolean getAnalysis(String analysisId) {
logger.info("Retrieving analysis for ID: {}", analysisId);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://www.virustotal.com/api/v3/analyses/" + analysisId);
HttpHeaders headers = new HttpHeaders();
headers.set("accept", "application/json");
headers.set("x-apikey", apiKey);
HttpEntity<Void> request = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, String.class);
logger.info("Response from VirusTotal analysis: {}", response.getBody());
try {
Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
Map<String, Object> attributes = (Map<String, Object>) data.get("attributes");
Map<String, Integer> stats = (Map<String, Integer>) attributes.get("stats");
return evaluateSafety(stats);
} catch (Exception e) {
logger.error("Error parsing response from VirusTotal analysis", e);
throw new RuntimeException("Error parsing response from VirusTotal analysis", e);
}
}
private boolean evaluateSafety(Map<String, Integer> stats) {
int malicious = stats.getOrDefault("malicious", 0);
int suspicious = stats.getOrDefault("suspicious", 0);
return malicious < 5 && suspicious < 5;
}
}