KHAGAN AYDIN

OWASP 2017 A10: Insufficient Logging and Monitoring

Equifax's monitoring went blind for months. Marriott found its intruder four years late.

· 11 min read

Insufficient Logging & Monitoring is a security vulnerability in which an application does not record attacks or raise an alarm about them, so an intruder can stay for months unnoticed. It is number ten on the 2017 Top 10 from the Open Web Application Security Project (OWASP). It is the only item on the list that describes something missing rather than something broken. No request exploits it. A scanner cannot find it. It decides how long an attacker who found one of the other nine gets to stay.

That time is long. The OWASP text cites a 2016 IBM study: on average, identifying a breach took 191 days. Half a year in which an attacker reads, copies and moves, while every system reports that all is well. Too often the first sign comes from outside: a bank noticing fraud, a customer, a stranger offering your data for sale. By then the question is no longer how to stop the attack but how much of it you can reconstruct.

What changed from 2013

This item is new. The 2013 list had nothing like it. For 2017, OWASP combined vulnerability data with a survey of practitioners, and two items came from the survey rather than the data: Insecure Deserialization and this one. To make room, Cross-Site Request Forgery (CSRF) dropped off, because many frameworks now defend against it, and Unvalidated Redirects and Forwards lost its place to XML External Entities.

The reason it had to come from a survey is the reason it matters. Vulnerability data is built from bugs that testers find, and nobody files a finding that says “if this happened, you would not have noticed.” OWASP gives it the hardest detectability rating on its scale. A survey of the people doing the work could capture what bug counts never will.

Two cases

Equifax, 2017. The attackers came in through an unpatched web framework, the subject of the previous essay in this series. What let them stay was monitoring that had quietly switched itself off. According to the House Oversight Committee report of December 2018:

  • Equifax inspected encrypted traffic with devices that needed a valid digital certificate to read it. The certificate on the device watching the consumer dispute portal had expired in January 2016, and the committee found it went unrenewed for nineteen months. All that time, the portal’s traffic passed uninspected.
  • The problem was known. An internal tracker entry from January 2017 noted that the devices were missing certificates and could not see web attacks. At the time of the breach, at least 324 certificates had expired, 79 of them on devices monitoring business-critical domains.
  • No file integrity monitoring, which raises an alarm when files on a server change, ran on the application or web servers. Investigators found 30 web shells, small backdoor scripts the attackers planted to run commands, and said file monitoring could have caught their creation.
  • From May 13 to July 30, 2017, the attackers ran about 9,000 queries against dozens of databases.

On July 29, after the certificate was replaced, the security team quickly spotted the suspicious traffic and blocked it. The attackers had been inside for seventy-six days; once the sensor could see again, they were caught almost at once. About 148 million people were affected. The root cause of the long stay was not a missing tool. It was a tool that failed silently, and a known gap nobody closed.

Marriott, disclosed November 30, 2018. On September 8, 2018, an internal security tool raised an alert about an attempt to access the guest reservation database of Starwood, the hotel group Marriott had acquired two years earlier. The investigation found that someone had had access to the Starwood network since 2014. The intruder had copied and encrypted data and taken steps to remove it; Marriott decrypted it on November 19 and confirmed it came from the reservation database. On January 4, 2019, Marriott revised its first estimate of up to 500 million guests to at most 383 million guest records, including about 5.25 million unencrypted passport numbers and 8.6 million encrypted payment cards.

Marriott’s statements do not explain why four years passed. What is public is how it ended: one alert, on one attempt to reach the most valuable database. That alert worked. The years before it are the cost of not having alerts like it everywhere else.

What to log

Log security events, not just errors. Each entry needs who (user ID, or a hash of the submitted name when there is no user), what, when (in Coordinated Universal Time, UTC), where from (network address and browser) and a request ID to tie entries together.

Event Why it matters
Logins, successful and failed, and lockouts Password guessing and stolen credentials show up here first.
Password, email and second-factor changes The first things an attacker changes after taking over an account.
Access denied by an authorization check A user requesting other people’s records is probing, not browsing.
Server-side validation failures See below. These are the most underrated signal you have.
Admin actions: role changes, new users, configuration Attackers who get in try to stay in.
High-value transactions: payments, payee changes, bulk exports The actions the attack exists to perform.

The validation point is the one most teams miss. A normal browser cannot produce certain inputs: a dropdown value that is not in the list, a changed hidden field, an account ID that was never shown to this user. When the server sees one, someone is editing requests by hand. That is close to a zero false positive signal, and most applications reject it with a polite error message and log nothing. OWASP’s AppSensor project catalogs detection points like these.

What never to log

Log the fact, never the secret.

  • Passwords. Including on failed logins. People regularly type their password into the username box, so logging the submitted username of a failed login writes real passwords into your logs. Record a keyed hash of it instead: enough to group attempts, useless to whoever reads the log.
  • Session IDs, access tokens, Application Programming Interface (API) keys. Anyone who can read the log can become the user.
  • Full card numbers. At most the last four digits.
  • Password reset links. Web server access logs record the full address, query string included. If a reset token or session ID travels in the URL, it is in your access log right now. Check.

Logs are copied, shipped, indexed and read by more people than the database. Treat them as data you will one day have to defend.

Log injection

If a log is plain text and an attacker controls part of a line, the attacker can write lines of their own.

Vulnerable code

import logging

logging.basicConfig(filename='security.log', level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(message)s')
log = logging.getLogger('auth')

def on_failed_login(username):
    log.warning('Login failed for user %s', username)

Submit this as the username, with a real newline after alice:

alice
2019-01-22 10:15:02,114 INFO Login succeeded for user admin

The log now reads:

2019-01-22 10:14:59,870 WARNING Login failed for user alice
2019-01-22 10:15:02,114 INFO Login succeeded for user admin

An investigator searching this file sees a successful admin login that never happened. Worse cases exist. Escape sequences, control codes a terminal treats as commands, can reach the terminal of the administrator who views the log: the web server nginx 0.7.64 was assigned the public vulnerability identifier CVE-2009-4487 for writing them to its logs unfiltered. And if your logs end up in a web dashboard, a script hidden in the browser’s User-Agent header becomes cross-site scripting against your own security team.

Fixed code: write one JavaScript Object Notation (JSON) object per line. The encoder turns a newline into the two characters \n and escapes every other control character, so no input can start a new entry.

import hashlib
import hmac
import json
import logging
import time

LOG_HASH_KEY = b'load-this-from-your-secret-store'


class JsonFormatter(logging.Formatter):
    def format(self, record):
        entry = {
            'time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(record.created)),
            'level': record.levelname,
            'event': record.getMessage(),
        }
        entry.update(getattr(record, 'fields', {}))
        return json.dumps(entry, sort_keys=True)


handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
security_log = logging.getLogger('security')
security_log.addHandler(handler)
security_log.setLevel(logging.INFO)
security_log.propagate = False


def username_hash(submitted):
    digest = hmac.new(LOG_HASH_KEY, submitted.encode('utf-8'), hashlib.sha256)
    return digest.hexdigest()[:16]


def on_failed_login(submitted_username, user_id, reason, source_ip, user_agent, request_id):
    security_log.warning('login_failed', extra={'fields': {
        'user_id': user_id,
        'username_hash': username_hash(submitted_username),
        'reason': reason,
        'source_ip': source_ip,
        'user_agent': user_agent[:200],
        'request_id': request_id,
    }})

A failed login now produces one line that every log tool can search by field:

{"event": "login_failed", "level": "WARNING", "reason": "bad_password", "request_id": "f3a9c2", "source_ip": "203.0.113.7", "time": "2019-01-22T10:15:02Z", "user_agent": "curl/7.58.0", "user_id": 1042, "username_hash": "9b1f0c27d4e8a6b3"}

The submitted name never appears, so a password typed into the wrong box never reaches the log. The handler writes to standard output, which your platform ships to central storage. The user agent is cut to 200 characters, so nobody fills your disk with one header.

On Java with Logback, if you cannot move to JSON yet, neutralize control characters in the pattern itself, so every message is covered without touching code:

<encoder>
  <pattern>%d{ISO8601} %-5level %logger %replace(%msg){'\p{Cntrl}', '_'}%n</pattern>
</encoder>

The same forged username now lands on one line, with underscores where the newlines were.

Protect the logs

An attacker with control of a server will edit its logs. Assume it.

  • Ship logs off the host as they are written. OWASP lists logs stored only locally as a sign of this weakness. A copy on another system, under other credentials, survives the server.
  • Let the application append, never edit. For an audit table in a PostgreSQL database, take the rights away from the application’s account:
REVOKE UPDATE, DELETE, TRUNCATE ON audit_log FROM app_user;
  • Keep logs long enough. If detection takes 191 days on average, ninety days of retention means the evidence of a typical breach is gone before anyone looks. Keep security events searchable for at least a year.

Alerts someone actually reads

A log nobody reads is an archive. OWASP’s own example: a large US retailer’s malware sandbox flagged suspicious software and nobody acted, until a bank noticed fraudulent card transactions. The alert existed. The response did not.

Start with three alerts. Each has an owner and a written first step.

  1. Password spraying. Attackers try one common password against thousands of accounts, so each account sees only one failure and no lockout ever triggers. Count distinct accounts failing from one address, not failures per account.
  2. A canary account. Create an admin-looking account nobody uses. Any login attempt against it is an attack. False positives: none.
  3. Silence. Equifax’s monitoring did not raise an alarm. It went quiet. If the login events stop arriving, the logging is broken, and that is an incident.

All three fit in one script, run every ten minutes over the last window of JSON events:

import json
import sys
from collections import defaultdict

SPRAY_THRESHOLD = 20       # distinct accounts failing from one address
CANARY_USER_ID = 31337     # the admin-looking account nobody uses

failed = defaultdict(set)
login_events = 0
alerts = []

for line in sys.stdin:
    try:
        event = json.loads(line)
    except ValueError:
        alerts.append('Unparseable log line: logging may be broken or tampered with.')
        continue
    if event.get('event') not in ('login_failed', 'login_succeeded'):
        continue
    login_events += 1
    if event.get('user_id') == CANARY_USER_ID:
        alerts.append('Canary account login from {0}'.format(event.get('source_ip')))
    if event['event'] == 'login_failed':
        account = event.get('user_id') or event.get('username_hash')
        failed[event.get('source_ip')].add(account)

if login_events == 0:
    alerts.append('No login events in this window. Is logging broken?')
for ip, accounts in failed.items():
    if len(accounts) >= SPRAY_THRESHOLD:
        alerts.append('Password spray from {0}: {1} accounts'.format(ip, len(accounts)))

for alert in alerts:
    print('ALERT ' + alert)
sys.exit(1 if alerts else 0)

Wire the exit code to whatever pages a person. Tune the threshold on real traffic. If an alert fires every week and nobody acts on it, fix it or delete it: an alert people have learned to ignore is worse than none, because it looks like coverage.

Test detection by attacking yourself

You cannot know your monitoring works until an attack crosses it. OWASP’s own suggestion: after a penetration test, read the logs and check that the testers’ actions were recorded well enough to see what they did. Then go further, with permission, against production or a copy that ships logs the same way:

  1. Spray. From one test address, fail a login on 25 accounts. Did the alert fire? How long until a person looked?
  2. Touch the canary. Try one login against the canary account. Same questions.
  3. Tamper. Change a hidden field, submit a dropdown value that is not in the list, request another user’s record. Is each logged, with your user ID?
  4. Inject. Put a newline and the text of a fake log line in a username. Does the log stay one entry per event?
  5. Scan. Run OWASP ZAP (Zed Attack Proxy) or any web scanner against the application. OWASP lists scans that trigger no alert as a sign of this weakness. Thousands of malformed requests should wake somebody up.
  6. Go dark. Stop the log shipper for an hour. Does the silence alert fire?
  7. Search for secrets. Grep a day of logs for password, token, Authorization and runs of 16 digits.

Write down the time from each action to a human response. That number is your real detection time, and it is the one worth improving.

Checklist

  • Log logins, failures, access denials, validation failures, admin actions and high-value transactions, with user, source and request ID.
  • Never log passwords, tokens, session IDs or full card numbers. Hash failed usernames with a key.
  • One JSON object per line, UTC timestamps, consistent field names.
  • Neutralize control characters in anything an attacker can influence.
  • Ship logs off the host at once; make audit records append-only.
  • Keep security logs searchable for at least a year.
  • Alert on spraying, on canary accounts and on silence. Give every alert an owner.
  • Attack yourself on a schedule and time the response.

Every other item on the Top 10 asks how an attacker gets in. This one asks when you find out. Equifax had the tools and let one go blind; Marriott found its intruder with a single alert four years late. Neither failure shows up in a scan. You find it only by attacking your own system and timing how long it takes someone to notice.