Welcome to the final lesson in our Server-Side Request Forgery (SSRF) Prevention in Java Web Applications course! In this lesson, we'll explore security logging and monitoring using Spring Boot. Effective logging and monitoring are crucial components of a comprehensive security strategy, as they help you detect, investigate, and respond to security incidents promptly. Let's dive in and discover how to implement these practices in your Spring Boot applications! 📊
The Role of Security Logging
Security logging is the practice of recording events related to security concerns within your application. Properly implemented logs serve multiple purposes:
Detecting Security Incidents: Logs can reveal suspicious activities that may indicate ongoing attacks.
Investigating Breaches: After a security incident, logs provide valuable data for forensic analysis.
Compliance Requirements: Many regulatory frameworks require specific logging practices.
System Auditing: Logs help track user activities and system changes over time.
Let's implement a comprehensive logging system using Spring Boot with SLF4J and Logback (which Spring Boot includes by default).
Setting Up Request Logging with Spring Boot Filters
Spring Boot makes it easy to create filters for logging HTTP requests. Here's how to implement a request logging filter:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configurationpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
3. Create WebSocket Endpoint
When building a WebSocket endpoint that handles multiple concurrent connections, we need thread-safe collection management. We use CopyOnWriteArraySet for storing active sessions because:
Thread Safety: Multiple clients can connect and disconnect simultaneously, requiring safe concurrent access
Optimized for Read-Heavy Operations: Broadcasting logs to all clients is a read operation that happens frequently, while adding/removing sessions (write operations) is relatively rare
No Locking Required: The collection handles synchronization internally, preventing ConcurrentModificationException when iterating during broadcasts
Trade-off: Write operations (add/remove) are slower due to copying, but this is acceptable since connections/disconnections are infrequent compared to log broadcasts
A regular HashSet would throw ConcurrentModificationException if a client disconnects while we're broadcasting to all sessions. Other alternatives like Collections.synchronizedSet() would require explicit locking during iteration, making the code more complex.
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;import java.time.LocalDateTime;import java.util.*;import java.util.concurrent.ConcurrentHashMap;@Servicepublic class LogAlerter { private static final Logger logger = LoggerFactory.getLogger(LogAlerter.class); @Autowired private JavaMailSender mailSender; @Value("${admin.email:admin@example.com}") private String adminEmail; @Value("${spring.mail.username}") private String fromEmail; private final Map<SecurityEventType, List<Long>> eventTimestamps = new ConcurrentHashMap<>(); private final Map<SecurityEventType, Long> lastAlert = new ConcurrentHashMap<>(); // Configuration thresholds private final int ssrfThreshold = 3; private final long ssrfWindowMillis = 10 * 60 * 1000; // 10 minutes public void recordEvent(SecurityEventType type) { eventTimestamps.computeIfAbsent(type, k -> Collections.synchronizedList(new ArrayList<>())) .add(System.currentTimeMillis()); } @Scheduled(fixedRate = 60000) // Check every minute public void checkAlerts() { long now = System.currentTimeMillis(); // Check SSRF attempt pattern List<Long> ssrfEvents = eventTimestamps.getOrDefault( SecurityEventType.POTENTIAL_SSRF_ATTEMPT, new ArrayList<>() ); // Remove old events outside the time window ssrfEvents.removeIf(ts -> ts < now - ssrfWindowMillis); // Check if threshold is exceeded and we haven't alerted recently if (ssrfEvents.size() >= ssrfThreshold && (lastAlert.getOrDefault(SecurityEventType.POTENTIAL_SSRF_ATTEMPT, 0L) < now - ssrfWindowMillis)) { sendAlert(SecurityEventType.POTENTIAL_SSRF_ATTEMPT, ssrfEvents.size()); lastAlert.put(SecurityEventType.POTENTIAL_SSRF_ATTEMPT, now); } } private void sendAlert(SecurityEventType type, int count) { String subject = "SECURITY ALERT: " + type.name().replace("_", " "); String body = String.format( "Detected %d instances of %s in the last 10 minutes.\n" + "Please investigate immediately.\n\n" + "Timestamp: %s", count, type.name(), LocalDateTime.now() ); try { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(fromEmail); message.setTo(adminEmail); message.setSubject(subject); message.setText(body); mailSender.send(message); logger.error("Alert sent: {}", subject); } catch (Exception e) { logger.error("Failed to send alert email", e); } }}
Enable Scheduling
Add to your main application class:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
Integration Example
@RestControllerpublic class SecureController { @Autowired private LogAlerter alerter; @PostMapping("/api/secure-action") public ResponseEntity<?> secureAction(@RequestBody Map<String, String> data) { if (isSuspicious(data)) { // Record the event for alerting alerter.recordEvent(SecurityEventType.POTENTIAL_SSRF_ATTEMPT); return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(Map.of("error", "Access denied")); } return ResponseEntity.ok(Map.of("success", true)); } private boolean isSuspicious(Map<String, String> data) { // Your validation logic return false; }}
Conclusion
In this lesson, we explored how to implement security logging and monitoring in Spring Boot applications. We learned how to:
Set up request logging using Spring Boot filters
Configure Logback for structured security logging
Implement real-time log monitoring using Spring WebSocket
Create pattern-based alerting using Spring's JavaMailSender and scheduled tasks
Throughout this course, we've covered the fundamentals of SSRF, prevention techniques in Spring Boot, incident response, and comprehensive monitoring. These skills will help you build more secure applications and protect your users' data from potential threats.
Remember that security is an ongoing process, not a one-time implementation. Continue to stay informed about emerging threats and best practices to ensure your applications remain secure in an ever-evolving landscape. Thank you for joining us on this journey to better security! 🚀