How One Command Helped Me Catch a Hidden Malware File?
It's 2:49 AM. A SOC analyst at a mid-size fintech company just got paged — EDR flagged unusual outbound traffic from a Linux web server. No time to wait for a full disk image. No time for a slow find / crawl across a 2TB filesystem. The analyst needs answers in seconds, not minutes. So they type one word: locate.
Within half a second, a list of every .php webshell candidate, every recently touched .log file, and every hidden .env file on the box scrolls across the terminal. That's the power of the locate command — and it's exactly why it deserves a permanent spot in every Linux user's, sysadmin's, and incident responder's toolkit.
This guide breaks down the locate command from the ground up, but with a twist: instead of treating it as a dry manual page, we'll look at it the way a real security practitioner does — as a rapid file-discovery weapon for both attackers and defenders.
Table of Contents
- What Is the locate Command?
- Why locate Matters in Cybersecurity Investigations
- Real-World Scenario: Hunting a Webshell with locate
- locate Command Reference (With Practical Use Cases)
- Detection & Prevention: What Defenders Should Know
- Expert Tips From the Field
- Related Articles
- FAQ
- Conclusion
What Is the locate Command?
locate is a Linux utility that searches a pre-built index (database) of filenames across the entire filesystem, rather than scanning directories live like find does. This index is called mlocate.db (or plocate.db on newer systems) and is typically refreshed once a day via a cron job, or manually using updatedb.
Because it queries a database instead of walking the disk in real time, locate is dramatically faster than find — often returning results across hundreds of thousands of files in under a second. That speed is exactly why it matters in security work: when you're triaging a live incident, seconds count.
Why locate Matters in Cybersecurity Investigations?
Security professionals — from SOC analysts to penetration testers — rely on fast file discovery constantly. A few real scenarios where locate earns its place in the toolkit:
- Incident response: Quickly locating suspicious scripts, webshells, or dropped payloads across a compromised server.
- Penetration testing: After gaining shell access, attackers (and red teamers) commonly use
locateto enumerate configuration files, credentials, backup files, and sensitive data like.envorid_rsa. - Digital forensics: Investigators use it to identify all files matching a known malicious filename pattern across a large filesystem.
- Compliance audits: Quickly verifying whether sensitive file types (like
.pem,.key, or.conf) exist in locations they shouldn't.
It's worth noting: this dual-use nature is exactly why blue teams need to understand it as well as red teams do. If an attacker can enumerate your entire filesystem for secrets in under a second, your defense strategy needs to assume that reconnaissance step will happen — and happen fast.
Real-World Scenario: Hunting a Webshell with locate
Picture this: a U.S.-based e-commerce company detects abnormal CPU spikes on a production Linux server. The SOC team suspects a webshell has been dropped somewhere inside the web root, but the directory structure is a mess — thousands of nested folders from years of unmanaged deployments.
Instead of running a slow recursive find across the entire /var/www directory, the analyst runs:
locate "*.php" | grep -i "tmp\|cache\|upload"
Within moments, a suspicious file surfaces: /var/www/html/uploads/images/thumb_cache.php — a PHP file sitting inside an image upload directory, something that should never contain executable code. That single locate query, combined with basic filtering, cut triage time from what could have been 20+ minutes of manual searching down to a few seconds.
This is a pattern seen repeatedly in real U.S. enterprise incident response: attackers plant webshells inside upload directories, temp folders, or cache paths because those locations are often excluded from manual review. Fast file enumeration tools like locate are how defenders catch up.
locate Command Reference (With Practical Use Cases)
1. Find a Specific File
locate file.txt
What it does: Searches the entire indexed filesystem for any file named file.txt.
When to use it: When you know the exact filename and need its full path immediately.
Expected output: One or more full paths where the file exists, such as /home/user/documents/file.txt.
2. Search by Keyword
locate backup
What it does: Lists every file or directory containing the word "backup" anywhere in its path.
When to use it: Useful during incident response to quickly find backup archives that may contain sensitive data or leftover credentials.
Expected output: A list of paths like /opt/backup/db_backup.sql.
3. Update the locate Database
sudo updatedb
What it does: Rebuilds the mlocate/plocate database with the current state of the filesystem.
When to use it: Before running an investigation, since locate only searches its last-updated index — a stale database can hide recently dropped malicious files.
Expected output: No output on success; the database is refreshed silently.
Security note: This is a critical operational detail. If malware was dropped after the last
updatedbrun (often scheduled nightly via cron),locatewon't find it until the database is refreshed. Always runsudo updatedbmanually during active investigations, or fall back tofindfor real-time results.
4. Case-Insensitive Search
locate -i document
What it does: Matches "document," "Document," "DOCUMENT," etc.
When to use it: When you're unsure how a filename was cased by an attacker or a legacy system.
Expected output: All matching paths regardless of letter case.
5. Limit the Number of Results
locate -n 5 filename
What it does: Returns only the first 5 matches.
When to use it: When a search term is common and you just need a quick sample rather than a flood of output.
Expected output: Exactly 5 file paths (or fewer if fewer exist).
6. Count Matching Files
locate -c filename
What it does: Returns only the total count of matches, not the file paths themselves.
When to use it: Useful for quick audits — for example, checking how many .bak files exist across a fleet of servers without needing the full list.
Expected output: A single number, e.g., 47.
7. Show Only Existing Files
locate -e filename
What it does: Filters out results for files that were indexed previously but have since been deleted.
When to use it: Prevents wasted investigation time chasing files that no longer exist on disk.
Expected output: Only paths to files currently present on the filesystem.
8. Use Regular Expressions
locate -r ".*\.log$"
What it does: Uses a regex pattern to match all files ending in .log.
When to use it: When you need precise pattern control beyond basic wildcards — for example, matching filenames with strict extension boundaries.
Expected output: Every log file path indexed on the system.
9. Search for PDF Files
locate "*.pdf"
What it does: Finds all indexed PDF files.
When to use it: Useful in data-loss investigations or checking for leaked/exfiltrated documents.
Expected output: A list of all .pdf file paths.
10. Search for Shell Scripts
locate "*.sh"
What it does: Finds all shell script files on the system.
When to use it: Critical during malware hunts — attackers frequently drop .sh persistence or dropper scripts in temp directories.
Expected output: Paths to every .sh file indexed.
11. Search Hidden Files
locate ".env"
What it does: Finds hidden configuration files named .env.
When to use it: .env files often contain database credentials, API keys, and cloud secrets — a top target in both red team engagements and real breaches.
Expected output: Full paths to any .env file on the system.
12. Search Configuration Files
locate "*.conf"
What it does: Lists all configuration files.
When to use it: Useful for auditing service configs (Nginx, Apache, SSH, etc.) for misconfigurations after an incident.
Expected output: Paths like /etc/nginx/nginx.conf.
13. Search Log Files
locate "*.log"
What it does: Finds every log file indexed on the system.
When to use it: First step in almost any forensic timeline reconstruction.
Expected output: A full list of log file paths across the OS and applications.
14. Search Python Files
locate "*.py"
What it does: Lists all Python source files.
When to use it: Useful when hunting for malicious Python-based scripts or backdoors planted by an attacker.
Expected output: Paths to all .py files on disk.
15. Search Directories by Name
locate Downloads
What it does: Finds files and directories named "Downloads."
When to use it: Common in data exfiltration investigations, since downloaded tools often land in predictable folders.
Expected output: Paths to matching directories and files.
16. Search Multiple Keywords
locate report backup
What it does: Searches for files matching either term.
When to use it: Speeds up investigations when you're not sure of the exact filename but know related keywords.
Expected output: Combined results matching either search term.
17. Display Database Statistics
locate -S
What it does: Shows metadata about the locate database — number of directories, files indexed, and database size.
When to use it: Useful to verify how current and complete your index is before relying on it during an investigation.
Expected output: Stats such as total file count and database file size.
18. Match Base Filename Only
locate -b filename
What it does: Matches only the filename itself, ignoring the full directory path.
When to use it: Prevents false positives when a search term also appears in unrelated directory names.
Expected output: Paths where the base filename exactly matches the search term.
19. Wildcard Pattern Search
locate "*config*"
What it does: Finds any file or directory containing "config" anywhere in the name.
When to use it: Broad sweep during audits of configuration sprawl across a server.
Expected output: All matching paths containing "config."
20. Paginate Results for Review
locate filename | less
What it does: Pipes output into a pager for easier scrolling.
When to use it: Essential when a query returns thousands of results and you need to review them methodically instead of having them flood the terminal.
Expected output: Interactive, page-by-page results.
Detection & Prevention: What Defenders Should Know
Because locate is a built-in, "living off the land" utility, its use rarely triggers antivirus alerts — which is exactly why attackers favor it during post-exploitation reconnaissance. Here's how defenders should respond:
- Monitor process execution logs: Track invocations of
locate, especially combined with sensitive search terms like.env,id_rsa,.pem, orpassword, using auditd or EDR command-line logging. - Correlate with user context: A web server process (like
www-data) suddenly runninglocateis a strong anomaly indicator — legitimate application processes rarely need to enumerate the filesystem this way. - Restrict updatedb scope: Configure
/etc/updatedb.confto exclude sensitive directories (like/etc/sslor application secrets folders) from being indexed in the first place, limiting what an attacker can discover vialocate. - Harden file permissions: The
mlocate.dbfile itself can leak filesystem structure if improperly permissioned — ensure it's restricted to appropriate users only. - Use auditd rules: Add specific audit rules to log execution of
/usr/bin/locatefor visibility in SIEM dashboards.
Expert Tips From the Field
- Always cross-check
locateresults withfindduring active incidents — the database might be outdated by hours or days. - Combine
locatewithgrep,xargs, and file-hashing tools for a fast triage pipeline instead of manual review. - During red team engagements, expect
locatecommands to be logged if the target has command-line auditing enabled — treat it as a detectable action, not a stealthy one. - For forensic-grade investigations, don't rely solely on
locate; it reflects filenames only, not content or timestamps — pair it withstatand timeline tools.
Related Cybersecurity Topics You Should Explore
- The Linux find Command: A SOC Analyst's Guide to Hunting Hackers
- mv Command Guide: How SOC Analysts Use It Safely (2026)
- I Found a Hacker Hiding in a Single Linux cp Command
- Kali Linux 2026.2 Released: 9 New Hacking Tools & Major Upgrades
- rm Command in Linux: The Tutorial (And the Mistake That Kills Servers)
- rmdir vs rm -r: The Linux Command Mistake That Costs Evidence
- How Attackers Abuse mkdir to Hide Malware on Linux Servers
- cd Command in Linux: Complete Guide for SOC & Incident Response
FAQ
1. Is locate faster than find?
Yes. locate queries a pre-built database, making it far faster than find, which scans the live filesystem in real time.
2. Why does locate sometimes miss recently created files?
Because its database is only as current as the last updatedb run, typically scheduled once daily via cron.
3. Can locate find hidden files like .env or .bash_history?
Yes, as long as those files were indexed. This is exactly why sensitive files should be excluded from the index or protected with strict permissions.
4. Is using locate considered malicious activity?
Not inherently — it's a standard system utility. Context matters: unusual processes or accounts invoking it against sensitive file patterns is what raises red flags.
5. How can I exclude directories from the locate database?
Edit /etc/updatedb.conf and add sensitive paths to the PRUNEPATHS variable, then run sudo updatedb to apply changes.
6. Does locate work the same on all Linux distributions?
Most modern distributions use either mlocate or the faster plocate package; command syntax is largely compatible across both.
7. Can locate replace find entirely for forensic work?
No. It's excellent for speed but lacks real-time accuracy and metadata detail. Use both tools together for thorough investigations.
Conclusion
The locate command looks simple on the surface — a quick way to find a file by name. But in the hands of a security professional, it becomes a rapid reconnaissance and triage tool capable of surfacing webshells, leaked credentials, and forgotten backups in seconds rather than minutes. At the same time, its speed and stealth make it equally valuable to attackers, which is exactly why understanding it from both sides — offense and defense — is non-negotiable for any modern SOC analyst, penetration tester, or Linux administrator.
Master the syntax, understand its limitations, and most importantly, treat every locate execution on a production system as a signal worth investigating.






