130n@calvinlai.com
  • About Calvin Lai (fkclai)
  • My Work
  • Cyber Security
    • Cyber Security Centre (CSC)
      • Why we need a CSC
      • CSC Team Structure: Roles, Functions, and Tools
        • Key Function & Role
        • Tools & Platforms
        • People
        • Outsource Strategy
      • HRMC Executive Paper
  • Detection and Response
    • Playbook: Threat Prioritization & Automated Response Strategies
      • Scenario: Detecting and Mitigating a Ransomware Attack
      • Scenario: DC Sync Attack Detected and Mitigated
      • Scenario: Pass-the-Hash (PtH) Attack Detected and Contained
      • Scenario: Phishing Campaign with Malware / Credential Theft Detected and Mitigated
  • Application Architecture
    • Comparison of MVC , N-tier and Microservice Architecture
  • Application Security
    • OAuth, SAML, and OpenID Connect: Key Differences and Use Cases
    • Secure Coding Principles
    • HTTP Header Security Principles
    • Mitigating Broken Object Level Authorization (BOLA)
    • Spring Boot Validation
    • Output Encoding in JavaServer Faces (JSF)
    • Session Management Security Issues
    • Common API Security Problems
      • Broken Authentication
      • Excessive Data Exposure
      • Lack of Resources & Rate Limiting
      • Broken Function Level Authorization
      • Unsafe Consumption of APIs
    • JAVA Exception Handling
    • File Upload Validation
    • OAuth 2.0 Security
      • Insecure Storage of Access Tokens
    • Microservice Security
      • Sample Coding Demo
        • Service Implementation
        • Client Interaction
      • Security Solution for Microservices Architecture
    • Modifying and Protecting Java Class Files
      • Modify a Class File Inside a WAR File
      • Direct Bytecode Editing
        • Steps to Directly Edit a Java Class File
          • Update: Java Bytecode Editing Tools
      • Techniques to Protect Java Class Files
        • Runtime Decryption in WebLogic
    • JAVA Program
      • Secure, Concurrent Web Access Using Java and Tor
      • Creating a Maven Java project in Visual Studio Code
  • Exploit/CVE PoC
    • ZeroLogon Exploit
    • Remote Retrieved Chrome saved Encrypted Password
    • Twitter Control an RCE attack
  • Hacking Report (HTB)
    • Hits & Summary
      • Tools & Cheat Sheet
    • Windows Machine
      • Love 10.10.10.239
      • Blackfield 10.10.10.192
      • Remote 10.10.10.180
      • Sauna 10.10.10.175
      • Forest 10.10.10.161
      • Sniper
      • Json
      • Heist
      • Blue
      • Legacy
      • Resolute
      • Cascade
    • Linux Machine
      • Photobomb 10.10.11.182
      • Pandora 10.10.11.136
      • BountyHunter 10.10.11.100
      • CAP 10.10.10.245
      • Spectra 10.10.10.229
      • Ready 10.10.10.220
      • Doctor 10.10.10.209
      • Bucket 10.10.10.212
      • Blunder 10.10.10.191
      • Registry 10.10.10.159
      • Magic
      • Tabby
  • Penetration Testing
    • Web Application PenTest
    • Network/System PenTest
    • Mobile Penetration Test
      • Certificate Pinning
        • Certificate Pinning Bypass (Android)
          • Root a Android Device
          • Setup Proxy Tool - Burp Suite
      • Checklist
  • Threat Intelligence
    • Advanced Persistent Threat (APT) groups
      • North Korean APT Groups
      • Chinese APT Groups
      • Russian APT Groups
      • Other APT
  • Red Team (Windows)
    • 01 Reconnaissance
    • 02 Privileges Escalation
    • 03 Lateral Movement
    • 04 AD Attacks
      • DCSync
    • 05 Bypass-Evasion
    • 06 Kerberos Attack
    • 99 Basic Command
  • Exploitation Guide
    • 01 Reconnaissance
    • 02 Port Enumeration
    • 03 Web Enumeration
    • 04 Windows Enum & Exploit
      • Windows Credential Dumping
        • Credential Dumping: SAM
        • Credential Dumping: DCSync
      • Kerberos Attack
      • RDP
    • 05 File Enumeration
    • 06 Reverse Shell Cheat Sheet
      • Windows Reverse Shell
      • Linux Reverse Shell
    • 07 SQL Injection
    • 08 BruteForce
    • 09 XSS Bypass Checklist
    • 10 Spring Boot
    • 11 WPA
    • 12 Payload list
  • Vuln Hub (Writeup)
    • MrRobot
    • CYBERRY
    • MATRIX 1
    • Node-1
    • DPwwn-1
    • DC7
    • AiWeb-2
    • AiWeb-1
    • BrainPan
  • CTF (Writeup & Tips)
    • CTF Tools & Tips
    • Hacker One
    • CTF Learn
    • P.W.N. University - CTF 2018
    • HITCON
    • Pwnable
      • 01 Start
  • Useful Command/Tools
    • Kali
    • Windows
    • Linux
  • Offensive Security Lab & Exam
    • Lab
    • Tools for an Offensive Certification
      • Strategy for an Offensive Exam Certification
        • CVEs
        • Privilege Escalation
        • Commands
        • Impacket
  • ISO 27001
    • Disclaimer
    • What is ISO 27001
      • Implementation
    • Documentation
    • Common Mistake
    • Q&A
      • Can internal audit to replace the risk assessment
      • Is it sufficient for only the IT department head to support the ISO 27001 program
      • Does the Business Continuity Plan (BCP) and a Disaster Recovery Plan (DRP) are the same?
    • ISO 27001 Controls and Domains
      • 1. Information Security Policies
      • 2. Organization of Information Security
      • 3. Human Resource Security
      • 4. Asset Management
      • 5. Access Control
      • 6. Cryptographic Controls
      • 7. Physical and Environmental Security
      • 8: Operational Security
      • 9. Communications Security
      • 10. System Acquisition, Development, and Maintenance
      • 11. Supplier Relationships
      • 12: Information Security Incident Management
      • 13. Information Security Aspects of Business Continuity Management
      • 14. Compliance
Powered by GitBook
On this page

Was this helpful?

  1. Application Security

File Upload Validation

Ensuring the security of file uploads is crucial for protecting applications from malicious content. Validating file content using file signatures is a robust method to achieve this. File signatures, or magic numbers, are unique identifiers found at the beginning of files that indicate their type. By verifying these signatures during the upload process, we can ensure that the files are what they claim to be and not harmful.

Spring Security can be integrated with custom logic to achieve this. Here’s an example of how to validate file content using file signatures in a Spring Boot application.

Step-by-Step Implementation:

  1. Add Dependencies: Make sure to include the necessary dependencies in your pom.xml for Spring Boot and Spring Security.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  2. File Signature Checker Utility: Create a utility class to check the file signatures. This example uses common file types like PDF, PNG, JPG, and others.

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    public class FileSignatureChecker {
    
        private static final Map<String, String> FILE_SIGNATURES = new HashMap<>();
    
        static {
            FILE_SIGNATURES.put("25504446", "pdf"); // PDF
            FILE_SIGNATURES.put("89504E47", "png"); // PNG
            FILE_SIGNATURES.put("FFD8FF", "jpg"); // JPEG
            FILE_SIGNATURES.put("504B0304", "zip"); // ZIP
            FILE_SIGNATURES.put("47494638", "gif"); // GIF
            FILE_SIGNATURES.put("49492A00", "tiff"); // TIFF
            FILE_SIGNATURES.put("424D", "bmp"); // BMP
            FILE_SIGNATURES.put("52617221", "rar"); // RAR
            FILE_SIGNATURES.put("494433", "mp3"); // MP3
            FILE_SIGNATURES.put("52494646", "wav"); // WAV, AVI
            FILE_SIGNATURES.put("00000018", "mp4"); // MP4
            FILE_SIGNATURES.put("00000020", "mov"); // MOV
            // Add more file signatures as needed
        }
    
        public static String getFileType(InputStream inputStream) throws IOException {
            byte[] bytes = new byte[8];
            inputStream.read(bytes, 0, bytes.length);
            StringBuilder builder = new StringBuilder();
            for (byte b : bytes) {
                builder.append(String.format("%02X", b));
            }
            String fileSignature = builder.toString();
            for (Map.Entry<String, String> entry : FILE_SIGNATURES.entrySet()) {
                if (fileSignature.startsWith(entry.getKey())) {
                    return entry.getValue();
                }
            }
            return "unknown";
        }
    }
    
  3. Controller to Handle File Upload: Create a controller to handle file upload and validate the file content.

    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.access.annotation.Secured;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    
    @RestController
    public class FileUploadController {
    
        @PostMapping("/upload")
        @Secured("ROLE_USER")
        public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
            try (InputStream inputStream = file.getInputStream()) {
                String fileType = FileSignatureChecker.getFileType(inputStream);
                if ("unknown".equals(fileType)) {
                    return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
                            .body("Unsupported file type");
                }
                // Process the file based on its type
                return ResponseEntity.ok("File uploaded successfully: " + fileType);
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("Error processing file");
            }
        }
    }
  4. Security Configuration: Configure Spring Security to secure your file upload endpoint.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                .antMatchers("/upload").authenticated()
                .and()
                .csrf().disable(); // Disable CSRF for simplicity
        }
    }

This example demonstrates how to validate file content during upload by checking file signatures with Spring Security. Adjust and expand the FileSignatureChecker class to include more file types as needed. Remember to handle security concerns like CSRF and authentication according to your application’s requirements.

PreviousJAVA Exception HandlingNextOAuth 2.0 Security

Last updated 5 months ago

Was this helpful?