java-best-practices-security-audit
Performs comprehensive security audits of Java code against OWASP Top 10 and best practices. Use when auditing security, checking for vulnerabilities, analyzing SQL injection risks, preventing XSS attacks, reviewing authentication/authorization, detecting sensitive data exposure, checking dependency vulnerabilities, ensuring OWASP compliance, or hardening Java applications. Works with Java web applications, REST APIs, Spring applications, and any Java codebase.
What this skill does
# Java Security Audit
## Table of Contents
- [Purpose](#purpose)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Instructions](#instructions)
- [Examples](#examples)
- [Requirements](#requirements)
- [Security Audit Checklist](#security-audit-checklist)
- [Output Format](#output-format)
- [Error Handling](#error-handling)
## Purpose
Conducts comprehensive security audits of Java applications, identifying vulnerabilities based on OWASP Top 10, analyzing code for injection flaws, authentication issues, sensitive data exposure, and dependency vulnerabilities. Provides actionable remediation guidance.
## When to Use
Use this skill when you need to:
- Audit Java applications for security vulnerabilities
- Check for SQL injection vulnerabilities
- Detect XSS (Cross-Site Scripting) risks
- Review authentication and authorization implementation
- Identify sensitive data exposure issues
- Scan dependencies for known CVEs
- Ensure OWASP Top 10 compliance
- Review cryptographic implementations
- Check for insecure deserialization
- Audit session management security
- Detect hardcoded credentials or secrets
- Review access control mechanisms
- Perform pre-deployment security validation
- Conduct security code reviews
## Quick Start
Point to any Java codebase for immediate security analysis:
```bash
# Audit entire project
Perform security audit on this Java project
# Audit specific components
Security audit for src/main/java/com/example/controller/
# Check for specific vulnerability
Check for SQL injection vulnerabilities in this codebase
```
## Instructions
### Step 1: Identify Audit Scope
Determine what to audit:
**Full Application Audit:**
- All Java source files
- Configuration files (application.yml, application.properties)
- Dependencies (pom.xml, build.gradle)
- Database access layers
- Authentication/authorization code
- API endpoints and controllers
**Targeted Audit:**
- Specific vulnerability type (SQL injection, XSS, etc.)
- Specific component (authentication, payment processing)
- Recent changes (git diff for new code)
### Step 2: OWASP Top 10 Checklist
#### A01:2021 - Broken Access Control
**What to Check:**
- Authorization checks on every endpoint
- Horizontal privilege escalation (user accessing other user's data)
- Vertical privilege escalation (user accessing admin functions)
- CORS misconfiguration
- Missing function-level access control
**Red Flags:**
```java
// BAD: No authorization check
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
// BAD: Using user input directly without validation
@GetMapping("/users/{id}/orders")
public List<Order> getOrders(@PathVariable Long id) {
return orderRepository.findByUserId(id); // Any user can access any user's orders!
}
```
**Good Patterns:**
```java
@GetMapping("/users/{id}")
@PreAuthorize("#id == authentication.principal.id or hasRole('ADMIN')")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElseThrow();
}
@GetMapping("/users/me/orders")
public List<Order> getMyOrders(@AuthenticationPrincipal UserDetails user) {
return orderRepository.findByUserId(user.getId());
}
```
#### A02:2021 - Cryptographic Failures
**What to Check:**
- Passwords stored in plaintext
- Weak hashing algorithms (MD5, SHA1)
- Sensitive data transmitted over HTTP
- Hardcoded encryption keys
- Sensitive data in logs
**Red Flags:**
```java
// BAD: Plaintext password
user.setPassword(request.getPassword());
// BAD: Weak hashing
String hash = DigestUtils.md5Hex(password);
// BAD: Hardcoded secret
String secret = "mySecretKey123";
```
**Good Patterns:**
```java
// Use BCrypt for password hashing
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
user.setPassword(passwordEncoder.encode(request.getPassword()));
// Externalize secrets
@Value("${jwt.secret}")
private String jwtSecret;
// Encrypt sensitive data at rest
@Convert(converter = SensitiveDataConverter.class)
private String socialSecurityNumber;
```
#### A03:2021 - Injection
**What to Check:**
- SQL injection in dynamic queries
- Command injection in Runtime.exec()
- LDAP injection
- XML injection
- Expression Language injection
**SQL Injection Red Flags:**
```java
// BAD: String concatenation in SQL
String sql = "SELECT * FROM users WHERE email = '" + email + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// BAD: Using + in JPA queries
String jpql = "SELECT u FROM User u WHERE u.email = '" + email + "'";
Query query = em.createQuery(jpql);
// BAD: String format in queries
String sql = String.format("SELECT * FROM users WHERE id = %s", userId);
```
**Good Patterns:**
```java
// GOOD: PreparedStatement with parameters
String sql = "SELECT * FROM users WHERE email = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();
// GOOD: Named parameters in JPA
@Query("SELECT u FROM User u WHERE u.email = :email")
User findByEmail(@Param("email") String email);
// GOOD: Spring Data JPA method names
User findByEmail(String email);
```
#### A04:2021 - Insecure Design
**What to Check:**
- Missing rate limiting
- No account lockout after failed attempts
- Weak session management
- Missing security headers
- Inadequate logging and monitoring
**Red Flags:**
```java
// BAD: No rate limiting on sensitive endpoints
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
// Attacker can brute force passwords
return authenticate(request);
}
// BAD: Predictable session IDs
String sessionId = userId + "_" + timestamp;
```
**Good Patterns:**
```java
// Rate limiting with bucket4j
@PostMapping("/login")
@RateLimiter(name = "loginRateLimit", fallbackMethod = "loginFallback")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
return authenticate(request);
}
// Account lockout
@Service
public class LoginAttemptService {
private final LoadingCache<String, Integer> attemptsCache;
public void loginFailed(String username) {
int attempts = attemptsCache.get(username);
attemptsCache.put(username, attempts + 1);
}
public boolean isBlocked(String username) {
return attemptsCache.get(username) >= MAX_ATTEMPTS;
}
}
```
#### A05:2021 - Security Misconfiguration
**What to Check:**
- Default credentials still active
- Unnecessary features enabled
- Stack traces exposed to users
- Missing security headers
- Outdated framework versions
- Excessive error details in responses
**Red Flags:**
```java
// BAD: Detailed error messages to clients
catch (Exception e) {
return ResponseEntity.status(500).body(e.getMessage());
}
// BAD: Debug mode in production
spring.devtools.enabled=true
// BAD: Allowing all CORS origins
@CrossOrigin(origins = "*")
```
**Good Patterns:**
```java
// Security headers configuration
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.headers(headers -> headers
.xssProtection(xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK))
.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
.frameOptions(frame -> frame.deny())
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000))
);
return http.build();
}
}
// Generic error responses
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception e) {
log.error("Error occurred", e); // Log details server-side
return ResponseEntity.status(500)
.body(new ErrorResponse("An error occurred")); // Generic message to client
}
```
#### A06:2021 - Vulnerable aRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.