CWE-359 in APIs
- CWE ID
- CWE-359
- Category
- Data Exposure
- Severity
- HIGH
- Short Name
- PII Exposure
What is CWE-359?
CWE-359 describes exposure of private personal information (PII) to an unauthorized actor. This weakness occurs when sensitive data that should be kept confidential is inadvertently exposed to individuals or systems that lack proper authorization to access it.
The weakness manifests in various ways:
- Returning PII in API responses when the requester lacks authorization
- Logging sensitive information without proper access controls
- Exposing PII through error messages or stack traces
- Including personal data in URLs or query parameters that can be logged or cached
- Sending PII over unencrypted channels
Common examples of exposed PII include names, addresses, phone numbers, email addresses, social security numbers, financial account details, and biometric data. The impact ranges from privacy violations and regulatory non-compliance to identity theft and financial fraud.
CWE-359 in API Contexts
APIs present unique challenges for protecting PII due to their stateless nature and the difficulty of tracking data flow across multiple endpoints. Several API-specific scenarios commonly lead to CWE-359 vulnerabilities:
- Improper Authorization Checks: APIs that fail to verify whether the requesting user has permission to view specific data records. For example, an API endpoint that returns user profiles without checking if the requester is the profile owner or has admin privileges.
- Excessive Data Exposure: Returning entire user objects when only basic information is needed, or including PII in list endpoints where it's unnecessary.
- Indirect Object Reference (IDOR) Flaws: Allowing users to manipulate identifiers in requests to access other users' data. For instance, changing a user ID parameter to view someone else's profile.
- Logging and Monitoring Issues: API logging mechanisms that capture request/response bodies containing PII without proper access controls or data retention policies.
- Metadata Exposure: Including PII in HTTP headers, response metadata, or error details that might be visible to unauthorized parties.
Consider this vulnerable API endpoint:
GET /api/users/{userId}/profile
Authorization: Bearer [token]If the implementation doesn't verify that the authenticated user matches the requested userId or has appropriate permissions, any authenticated user could access any profile by simply changing the userId parameter.
Detection
Detecting CWE-359 requires both manual code review and automated scanning. Here are effective approaches:
Manual Detection Methods
- Code Review: Examine authorization logic around data access points. Look for missing permission checks before returning user data.
- Input Manipulation Testing: Test API endpoints by modifying identifiers (user IDs, record IDs) to see if you can access other users' data.
- Response Analysis: Review API responses to identify unnecessary PII exposure. Check if endpoints return full user objects when only limited data is required.
- Network Traffic Inspection: Use tools like Wireshark or browser dev tools to verify that PII isn't transmitted over unencrypted channels.
Automated Scanning with middleBrick
middleBrick provides comprehensive CWE-359 detection through its black-box scanning approach:
# Scan an API endpoint for PII exposure
middlebrick scan https://api.example.com/users/123/profileThe scanner tests for:
- Authentication bypass attempts to access restricted data
- Authorization flaws where authenticated users can access other users' data
- Data exposure in API responses and error messages
- Encryption verification for data in transit
middleBrick's Property Authorization check specifically examines whether API endpoints properly restrict access to sensitive data fields. The scanner provides a security score with detailed findings, including severity levels and remediation guidance for any CWE-359 vulnerabilities discovered.
For continuous monitoring, the Pro plan can scan your APIs on a schedule and alert you if new PII exposure vulnerabilities are detected, helping you maintain compliance with regulations like GDPR, HIPAA, and PCI-DSS.
Remediation
Fixing CWE-359 vulnerabilities requires a defense-in-depth approach. Here are code-level remediation strategies:
1. Implement Proper Authorization Checks
@GetMapping("/api/users/{userId}/profile")
public UserProfile getProfile(@PathVariable Long userId, @AuthenticationPrincipal User currentUser) {
// Verify the user has permission to access this profile
if (!currentUser.getId().equals(userId) && !currentUser.hasRole("ADMIN")) {
throw new AccessDeniedException("You can only view your own profile");
}
return userService.findById(userId);
}2. Apply Data Minimization Principles
// Instead of returning entire User objects, return only necessary data
public class UserProfileDTO {
private Long id;
private String username;
private String email; // Only if the user is viewing their own profile
// Constructor, getters, etc.
}
// Service method
public UserProfileDTO getUserProfile(Long userId, User requester) {
User user = userRepository.findById(userId).orElseThrow();
UserProfileDTO profile = new UserProfileDTO();
profile.setId(user.getId());
profile.setUsername(user.getUsername());
// Only include email if requester is the owner or admin
if (requester.equals(user) || requester.hasRole("ADMIN")) {
profile.setEmail(user.getEmail());
}
return profile;
}3. Implement Object-Level Security
// Using Spring Security's @PostAuthorize for method-level security
@PostAuthorize("returnObject.owner.id == principal.id or hasRole('ADMIN')")
public UserProfile getProfile(@PathVariable Long userId) {
return userService.findById(userId);
}4. Secure Logging Practices
// Avoid logging sensitive data
logger.info("User {} accessed profile {}", currentUser.getId(), userId);
// If you must log PII, use encryption and strict access controls
String encryptedPII = encrypt(user.getEmail());
logger.debug("User email (encrypted): {}", encryptedPII);
5. Validate and Sanitize Input/Output
// Validate that requested IDs belong to accessible resources
public UserProfile getProfile(@PathVariable Long userId, @AuthenticationPrincipal User currentUser) {
// Check if the user exists and is accessible
if (!userRepository.existsByIdAndAccessibleBy(userId, currentUser)) {
throw new ResourceNotFoundException("Profile not found or inaccessible");
}
return userService.findById(userId);
}6. Use HTTPS Everywhere
// Configure Spring Security to require HTTPS
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requiresChannel()
.anyRequest()
.requiresSecure();
}For comprehensive protection, integrate these fixes with middleBrick's continuous scanning. The GitHub Action can automatically scan your staging API before deployment, failing the build if CWE-359 vulnerabilities are detected:
name: API Security Scan
on: [pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick scan
run: |
npx middlebrick scan https://staging.example.com/api
env:
MIDDLEBRICK_API_KEY: ${{ secrets.MIDDLEBRICK_API_KEY }}
This ensures CWE-359 vulnerabilities are caught early in the development lifecycle before reaching production.