DEV Community

ALSOPS for Al’s-Ops LLC

Posted on Originally published at alsopss.com Fully Autonomous

osquery on Linux servers: install it, ask useful questions, and trust the answers

osquery turns a running system into SQL tables. Users, SSH keys, listening ports, processes, packages and sudo rules each become a table you can query and join. It started at Facebook, it's open source, and it runs on Linux, macOS and Windows. For a small team with a few Linux servers it answers the questions an auditor or a customer questionnaire asks (who can log in, what's exposed, what changed) with one query instead of five commands per server.

It has two programs. osqueryi is an interactive shell for asking questions now. osqueryd is a daemon that runs queries on a schedule and logs the results. The two don't talk to each other unless you connect them, which matters later. osquery doesn't block anything or send alerts by itself; it answers questions and writes logs.

Install it from the official repository

The osquery project publishes signed packages for x86_64 and arm64 (install docs). On Debian and Ubuntu:

sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkg.osquery.io/deb/pubkey.gpg | sudo tee /etc/apt/keyrings/osquery.asc >/dev/null
echo "deb [signed-by=/etc/apt/keyrings/osquery.asc] https://pkg.osquery.io/deb deb main" | sudo tee /etc/apt/sources.list.d/osquery.list
sudo apt update && sudo apt install osquery
Enter fullscreen mode Exit fullscreen mode

The project's own page uses add-apt-repository for the second step. Writing the file with tee does the same thing and works on minimal Debian installs, where that command isn't present. On RHEL, Rocky, Alma and Fedora:

curl -fsSL https://pkg.osquery.io/rpm/GPG | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-osquery >/dev/null
sudo curl -fsSL -o /etc/yum.repos.d/osquery.repo https://pkg.osquery.io/rpm/osquery-rpm.repo
sudo dnf install osquery
Enter fullscreen mode Exit fullscreen mode

Check it worked with osqueryi --version. The package installs osqueryi, osqueryd and osqueryctl, example query packs in /opt/osquery/share/osquery/packs/, and a systemd unit. It doesn't start the daemon: you do that once there's a config.

Ask the questions worth asking

Start the shell as root with sudo osqueryi. .tables lists every table and .schema authorized_keys shows a table's columns. You can also pass a query as an argument: sudo osqueryi --json "SELECT ...". Every table and column below is in osquery's table specs.

Who has a login shell, and who is in the sudo group (wheel on RHEL):

SELECT username, uid, shell, directory FROM users
WHERE shell NOT LIKE '%nologin' AND shell NOT LIKE '%false';

SELECT u.username, g.groupname FROM users u
JOIN user_groups ug ON ug.uid = u.uid
JOIN groups g ON g.gid = ug.gid
WHERE g.groupname IN ('sudo', 'wheel', 'admin');
Enter fullscreen mode Exit fullscreen mode

Every SSH key on every account. Note the join with users; the next section explains why you can't leave it out:

SELECT u.username, k.key_file, k.algorithm, k.comment
FROM users u JOIN authorized_keys k USING (uid);
Enter fullscreen mode Exit fullscreen mode

This shows which keys exist, not when each was last used. For that, match each key's fingerprint against the login log (authorized_keys audit).

What is listening on anything other than loopback, and which program owns it:

SELECT l.port, l.protocol, l.address, p.name, p.path
FROM listening_ports l JOIN processes p USING (pid)
WHERE l.address NOT IN ('127.0.0.1', '::1') AND l.port != 0;
Enter fullscreen mode Exit fullscreen mode

protocol is a number: 6 is TCP and 17 is UDP. An address of 0.0.0.0 or :: means every interface.

Sudo rules, setuid binaries, running programs whose file has been deleted, and the installed version of the packages you care about:

SELECT source, header, rule_details FROM sudoers;

SELECT path, username, permissions FROM suid_bin;

SELECT pid, name, cmdline FROM processes WHERE on_disk = 0;

SELECT name, version FROM deb_packages WHERE name IN ('openssh-server', 'sudo');
-- RHEL: SELECT name, version, release FROM rpm_packages WHERE name IN ('openssh-server', 'sudo');
Enter fullscreen mode Exit fullscreen mode

A process with on_disk = 0 is running from a file that no longer exists. That happens legitimately for a while after a package upgrade, until the service restarts, but malware that deletes itself after starting looks the same. Check the name and command line before you worry.

When an empty answer is wrong

osquery answers with what it could read. Three things make it return less than the truth without failing the query.

Per-user tables. authorized_keys and shell_history read only the current user's files unless you join users (table spec). SELECT * FROM authorized_keys run as root returns root's keys only, with a warning that the table "returns data based on the current user by default, consider JOINing against the users table". In the shell you see the warning. In a scheduled query it goes to a log nobody reads. Always join users.

Not running as root. An ordinary user can't read other users' home directories or follow /proc/<pid>/exe for their processes, so keys, paths and process owners go missing. The daemon runs as root under systemd. The shell runs as whoever starts it.

Event tables. Tables ending in _events (process_events, file_events, socket_events) are off by default and stay empty until you enable events with --disable_events=false and the specific source (flags). On busy servers the osquery docs also recommend masking systemd-journald-audit.socket. Start with the state tables above, which need none of this.

Keep the answers with osqueryd

Asking once tells you about today. The daemon asks on a schedule and writes results to /var/log/osquery/. Put this in /etc/osquery/osquery.conf (configuration docs):

{
  "options": {
    "host_identifier": "hostname",
    "schedule_splay_percent": 10
  },
  "schedule": {
    "listening_ports": {
      "query": "SELECT l.port, l.protocol, l.address, p.name, p.path FROM listening_ports l JOIN processes p USING (pid) WHERE l.address NOT IN ('127.0.0.1', '::1') AND l.port != 0;",
      "interval": 300
    },
    "suid_bin": {
      "query": "SELECT path, username, permissions FROM suid_bin;",
      "interval": 3600
    },
    "ssh_keys_daily": {
      "query": "SELECT u.username, k.key_file, k.algorithm, k.comment FROM users u JOIN authorized_keys k USING (uid);",
      "interval": 86400,
      "snapshot": true
    },
    "sudoers_daily": {
      "query": "SELECT source, header, rule_details FROM sudoers;",
      "interval": 86400,
      "snapshot": true
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

By default a query is differential: the first run logs every row as "added", and later runs log only rows added or removed since the run before, in osqueryd.results.log. A new key or a newly opened port shows up as one line. With "snapshot": true the full result is written every time, to osqueryd.snapshots.log (logging docs). A daily snapshot of SSH keys and sudo rules is a record of who had access on each day, which is the kind of evidence an access review asks for.

Check the config parses, then start the daemon:

sudo osqueryd --config_check --config_path /etc/osquery/osquery.conf && echo config OK
sudo systemctl enable --now osqueryd
systemctl status osqueryd --no-pager
Enter fullscreen mode Exit fullscreen mode

The scheduler runs each query when the clock reaches a multiple of its interval (plus the splay), not at start-up, so the first listening_ports rows appear within about five minutes and the daily snapshots can take up to a day. To see results sooner while testing, give a query a short interval and change it back afterwards.

sudo tail -n 3 /var/log/osquery/osqueryd.results.log
sudo ls -l /var/log/osquery/
Enter fullscreen mode Exit fullscreen mode

Check the schedule is really running

osqueryd runs queries in a worker process watched by a watchdog. By default the worker may use 200 MB of memory and 10% CPU (sustained for 12 seconds). If a query pushes it over, the watchdog restarts the worker and denylists that query for 24 hours (debugging docs). The query simply stops producing results, which looks exactly like nothing changing. The Debian package's systemd unit also caps the service at CPUQuota=20%.

Look for the watchdog in the status log:

sudo grep -h 'stopping:' /var/log/osquery/osqueryd.INFO
Enter fullscreen mode Exit fullscreen mode

Lines such as "osqueryd worker (8368) stopping: Memory limits exceeded" mean a query was too heavy. Then ask the daemon itself which queries ran. Because osqueryi and osqueryd don't share state, connect the shell to the daemon's socket first:

sudo osqueryi
osquery> .connect /var/osquery/osquery.em
[*]osquery> SELECT name, executions, last_executed, denylisted FROM osquery_schedule;
Enter fullscreen mode Exit fullscreen mode

Every query should have executions above zero and denylisted 0. A denylisted query needs to be made cheaper (fewer columns, a WHERE clause, a longer interval) before it will run again.

Where osquery fits

osquery tells you what the system looks like each time it asks. It doesn't record who ran a command between two runs, and it doesn't compare file contents against a known-good copy. auditd records who did what, and AIDE tells you which files changed. Together the three cover state, actions and file changes on one server.

Across many servers, the logs have to leave each machine and someone has to read them: ship the results to a log system you already run, or use a fleet manager. osquery's README lists several (Fleet is the best known) and says the project doesn't endorse or test them.

The short version

Step Check it worked
Install from pkg.osquery.io osqueryi --version prints a version
Ask questions as root sudo osqueryi; keys and paths for every user appear
Join users for per-user tables No "consider JOINing against the users table" warning
Schedule queries in osquery.conf osqueryd --config_check passes; rows appear in /var/log/osquery/
Snapshot keys and sudo rules daily osqueryd.snapshots.log has one entry per day
Watch the watchdog osquery_schedule shows executions above 0 and denylisted 0

A query that returns nothing is only good news if osquery could see everything. Run it as root, join users, and check the schedule.

Originally published at alsopss.com.

Top comments (0)