HIGH data exposureaws

Data Exposure on Aws

How Data Exposure Manifests in Aws

Data exposure in Aws applications occurs when sensitive information is unintentionally accessible to unauthorized users. This manifests through several Aws-specific patterns that developers should recognize.

One common scenario involves improper handling of database query results. When fetching user data, developers might inadvertently return entire objects containing sensitive fields like passwords, API keys, or personal information. In Aws, this often happens when using the built-in database drivers without explicitly selecting only required fields.

// Vulnerable: returns entire user object including password hash
const getUser = async (userId) => {
  const db = await openDatabase();
  const user = await db.query(`SELECT * FROM users WHERE id = ?`, [userId]);
  return user; // Exposes password, API keys, etc.
};

// Secure: explicitly select only needed fields
const getUser = async (userId) => {
  const db = await openDatabase();
  const user = await db.query(`SELECT id, name, email FROM users WHERE id = ?`, [userId]);
  return user; // Only returns explicitly requested fields
};

Another Aws-specific pattern involves response serialization. Aws automatically serializes objects to JSON for HTTP responses, but this can expose internal properties or methods that shouldn't be public.

// Vulnerable: exposes internal properties via JSON serialization
class User {
  constructor(id, name, email, passwordHash) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.passwordHash = passwordHash;
    this.internalId = generateInternalId(); // Exposed unintentionally
  }
}

// Secure: use serialization control or data transfer objects
class User {
  constructor(id, name, email, passwordHash) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.passwordHash = passwordHash;
  }
  
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      email: this.email
    };
  }
}

Environment variable exposure is another critical issue. Aws applications often read configuration from environment variables, but these can be accidentally logged or included in error responses.

// Vulnerable: logs sensitive configuration
app.use((err, req, res, next) => {
  console.error(err); // May log DATABASE_URL, API keys
  res.status(500).send('Internal Server Error');
});

// Secure: sanitize logs and error responses
app.use((err, req, res, next) => {
  console.error('Error occurred:', err.message); // Only log message
  res.status(500).send({
    error: 'Internal Server Error',
    requestId: req.id
  });
});

Aws's error handling can also inadvertently expose stack traces and internal implementation details. The framework's default error pages often include file paths, database queries, and other sensitive debugging information.

// Vulnerable: exposes stack trace and internal details
app.get('/api/users/:id', async (req, res) => {
  try {
    const user = await getUser(req.params.id);
    res.json(user);
  } catch (err) {
    res.status(500).json({
      error: err.message, // Exposes internal error details
      stack: err.stack // Full stack trace exposure
    });
  }
});

// Secure: sanitize error responses
app.get('/api/users/:id', async (req, res) => {
  try {
    const user = await getUser(req.params.id);
    res.json(user);
  } catch (err) {
    console.error('User retrieval failed:', err);
    res.status(500).json({
      error: 'Unable to retrieve user information',
      requestId: req.id
    });
  }
});

Aws-Specific Detection

Detecting data exposure in Aws applications requires both static analysis and runtime scanning. middleBrick's Aws-specific scanning identifies these vulnerabilities through automated testing of your API endpoints.

middleBrick performs black-box scanning of your Aws API endpoints, testing for data exposure without requiring source code access. The scanner automatically identifies endpoints that return excessive data and maps findings to OWASP API Security Top 10 categories.

For Aws applications, middleBrick specifically tests:

  • Authentication bypass scenarios that could expose user data
  • Property authorization violations where users access data they shouldn't see
  • Input validation failures that could lead to data leakage
  • Rate limiting bypasses that enable data scraping
  • Encryption weaknesses that expose data in transit

The scanner generates a security score (0-100) with letter grades (A-F) and provides per-category breakdowns. For data exposure specifically, middleBrick identifies which endpoints return sensitive information and provides severity ratings based on the type of data exposed.

middleBrick's CLI tool allows Aws developers to scan their APIs directly from the terminal:

npm install -g middlebrick
middlebrick scan https://api.your-aws-app.com --output json

For CI/CD integration, middleBrick's GitHub Action can automatically scan Aws APIs in your deployment pipeline:

- name: Scan API Security
  uses: middlebrick/middlebrick-action@v1
  with:
    url: https://api.your-aws-app.com
    fail-on-score-below: 80

The scanner tests unauthenticated attack surfaces, making it particularly effective for identifying data exposure vulnerabilities that don't require authentication. This approach catches issues like information disclosure through error messages, missing rate limiting, and unprotected data endpoints.

middleBrick also analyzes OpenAPI/Swagger specifications for Aws applications, cross-referencing API definitions with runtime findings to identify discrepancies between documented and actual behavior. This helps catch cases where API documentation suggests certain data is protected when it's actually exposed.

Aws-Specific Remediation

Remediating data exposure in Aws applications involves implementing proper data access controls and serialization practices. The framework provides several native features to help secure data exposure.

First, implement proper data access controls using Aws's built-in middleware and decorators. The framework supports property-level authorization that prevents unauthorized data access at the field level.

// Using Aws's property authorization
const getUser = async (userId, auth) => {
  const db = await openDatabase();
  const user = await db.query(`SELECT * FROM users WHERE id = ?`, [userId]);
  
  // Only allow access to authorized fields
  if (!auth.canViewEmail) {
    delete user.email;
  }
  if (!auth.isAdmin) {
    delete user.role;
    delete user.lastLogin;
  }
  
  return user;
};

Aws provides serialization control through its response formatting system. Use the toJSON method or response transformers to control exactly what data is sent to clients.

// Using Aws's response transformers
app.get('/api/users/:id', async (req, res) => {
  const user = await getUser(req.params.id);
  
  // Transform response to exclude sensitive data
  res.transform(user, {
    exclude: ['passwordHash', 'apiKey', 'internalId'],
    include: ['id', 'name', 'email', 'createdAt']
  });
});

Implement comprehensive error handling with Aws's error middleware to prevent stack trace and internal information leakage.

// Custom error handling middleware
app.use((err, req, res, next) => {
  const errorResponse = {
    error: 'An error occurred processing your request',
    requestId: req.id,
    timestamp: new Date().toISOString()
  };
  
  // Log full error details server-side
  console.error({
    message: err.message,
    stack: err.stack,
    requestId: req.id,
    url: req.url
  });
  
  res.status(err.status || 500).json(errorResponse);
});

Use Aws's built-in validation and sanitization features to prevent data exposure through injection attacks and malformed requests.

// Input validation and sanitization
app.post('/api/users', async (req, res) => {
  const { name, email, password } = req.body;
  
  // Validate and sanitize inputs
  const sanitized = {
    name: sanitizeString(name),
    email: sanitizeEmail(email),
    password: sanitizePassword(password)
  };
  
  // Only use validated data
  const user = await createUser(sanitized);
  res.json({
    id: user.id,
    name: user.name,
    email: user.email
  });
});

Implement rate limiting at the application level to prevent data scraping attacks that could expose large amounts of user data.

// Rate limiting middleware
app.use(rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP'
}));

For database queries, use parameterized statements and explicit field selection to prevent both SQL injection and data exposure.

// Secure database queries
const getUserProfile = async (userId, auth) => {
  const db = await openDatabase();
  
  // Only select explicitly needed fields
  const query = `
    SELECT 
      id, 
      name, 
      email, 
      ${auth.isAdmin ? 'role, lastLogin' : ''}
    FROM users 
    WHERE id = ?
  `;
  
  const user = await db.query(query, [userId]);
  return user;
};

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

How does middleBrick detect data exposure in Aws applications?
middleBrick performs black-box scanning of Aws API endpoints, testing for data exposure without requiring source code access. It automatically identifies endpoints that return excessive data, tests authentication bypass scenarios, and maps findings to OWASP API Security Top 10 categories. The scanner generates a security score (0-100) with letter grades and provides per-category breakdowns specifically for data exposure vulnerabilities.
What's the difference between data exposure and data leakage in Aws?
Data exposure refers to intentionally returning sensitive data through API endpoints, while data leakage is unintentional disclosure through error messages, stack traces, or improper serialization. In Aws, data exposure often occurs through improper field selection in database queries or inadequate response filtering, whereas data leakage typically happens through error handling or logging mechanisms that inadvertently include sensitive information.