cronsentry-lite 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cronsentry_lite-0.1.0.dist-info/METADATA +177 -0
- cronsentry_lite-0.1.0.dist-info/RECORD +7 -0
- cronsentry_lite-0.1.0.dist-info/WHEEL +5 -0
- cronsentry_lite-0.1.0.dist-info/entry_points.txt +2 -0
- cronsentry_lite-0.1.0.dist-info/licenses/LICENSE +21 -0
- cronsentry_lite-0.1.0.dist-info/top_level.txt +1 -0
- cronsentry_lite.py +268 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cronsentry-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Audit crontab silent failures: missing final newline, CRLF and unescaped %. Read-only, stdlib only.
|
|
5
|
+
Author: Alessio Auretto
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/alessio1999xx-debug/cronsentry-lite
|
|
8
|
+
Project-URL: Pro version, https://py-forge.com/products/cronsentry-cron-preflight-auditor
|
|
9
|
+
Keywords: cron,crontab,cronjob,crontab-lint,silent-failures,vixie-cron,cronie,sysadmin,devops,stdlib
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: Operating System :: POSIX
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: System :: Systems Administration
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# cronsentry-lite: audit crontab silent failures, read-only
|
|
29
|
+
|
|
30
|
+
cronsentry-lite helps with a quick audit of crontab silent failures on one file: it reads one crontab and flags a missing final newline, CRLF line endings, and unescaped `%` signs that make cron skip or truncate jobs without a clear error. It prints a plain-text report, exits `1` when something is flagged (so it fits a CI step or a pre-deploy check), and never edits the file or runs a job. One file, Python 3.9+ standard library only, MIT.
|
|
31
|
+
|
|
32
|
+
Need to scan `/etc/cron.d`, catch run-parts filename traps, or check that the script behind `sudo`/`timeout`/`nice` is executable and on cron's `PATH`? That is the full [CronSentry Cron Preflight Auditor](https://py-forge.com/products/cronsentry-cron-preflight-auditor?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite) (one-time payment, yours to keep, no subscription). A table later in this README lists what lite does and what the paid tool adds. Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite) ($99, one payment).
|
|
33
|
+
|
|
34
|
+
- Download the one file, or `pip install` it from this repo. No config, no state, no network access.
|
|
35
|
+
- Reads one crontab: `--file PATH`, `--file -` for stdin, or (with no `--file`) the output of `crontab -l` for the current user. Nothing is written.
|
|
36
|
+
- Byte-accurate checks: the file is read as raw bytes, so a missing final newline or a stray `\r` is not hidden by text-mode newline handling.
|
|
37
|
+
- Flags: `--file`, `--system` / `--user`, `--demo`, `--version`. After `pip install`, use `cronsentry-lite` in place of `python3 cronsentry_lite.py`.
|
|
38
|
+
|
|
39
|
+

|
|
40
|
+
|
|
41
|
+
Recorded on December 1, 2026 with asciinema + agg; real commands and output against the files in `fixtures/`, no simulated results. [Recording source](docs/demo.cast) · [Capture script](docs/record-demo.py).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
Download the single file (Python 3.9+, stdlib only, no extra packages):
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/cronsentry-lite/main/cronsentry_lite.py
|
|
49
|
+
python3 cronsentry_lite.py --help
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Or install the `cronsentry-lite` command from this repo:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install git+https://github.com/alessio1999xx-debug/cronsentry-lite.git
|
|
56
|
+
cronsentry-lite --help
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## See the output first (offline demo)
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
python3 cronsentry_lite.py --demo
|
|
63
|
+
# cronsentry-lite 0.1.0: demo (built-in sample crontab) (user crontab, 5 job line(s))
|
|
64
|
+
#
|
|
65
|
+
# FLAG line 1: CRON002_CRLF_LINE_ENDINGS
|
|
66
|
+
# carriage return (\r, Windows CRLF): cron keeps the \r in the command, so the job can fail
|
|
67
|
+
# lines: 1, 6
|
|
68
|
+
# fix: convert to Unix LF line endings (dos2unix, or tr -d '\r')
|
|
69
|
+
# FLAG line 4: CRON009_UNESCAPED_PERCENT
|
|
70
|
+
# unescaped % (1): cron cuts the command at the first one and sends the rest to stdin
|
|
71
|
+
# command: tar czf /backup/www-$(date +%F).tgz /var/www
|
|
72
|
+
# fix: escape each % as \% (quotes do not protect it), e.g. date +\%F
|
|
73
|
+
# FLAG line 7: CRON001_NO_TRAILING_NEWLINE
|
|
74
|
+
# file does not end with a newline; classic Vixie cron can silently drop the last line
|
|
75
|
+
# last line: 30 4 * * 0 /usr/local/bin/weekly-report.sh
|
|
76
|
+
# fix: add a newline at the end of the file
|
|
77
|
+
#
|
|
78
|
+
# 3 finding(s).
|
|
79
|
+
# Read-only: the file was not changed and no job was run.
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The demo uses a small built-in sample crontab; nothing on your system is read.
|
|
83
|
+
|
|
84
|
+
## Audit a crontab for silent failures
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
python3 cronsentry_lite.py # your own `crontab -l` output
|
|
88
|
+
python3 cronsentry_lite.py --file deploy/crontab # a crontab file in your repo
|
|
89
|
+
sudo python3 cronsentry_lite.py --file /etc/crontab # system crontab (user field auto-detected)
|
|
90
|
+
sudo python3 cronsentry_lite.py --file /etc/cron.d/backup # one file under /etc/cron.d
|
|
91
|
+
crontab -l -u deploy | python3 cronsentry_lite.py --file - # stdin
|
|
92
|
+
python3 cronsentry_lite.py --file ops/cron.d/app --system # force system format (user field)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`/etc/crontab` and files under `/etc/cron.d/` are treated as system crontabs (`<schedule> <user> <command>`); everything else as a user crontab (`<schedule> <command>`). Use `--system` or `--user` to override. The format only matters for the `%` check, which looks at the command part of each job line; comments and `NAME=value` lines are skipped.
|
|
96
|
+
|
|
97
|
+
## What gets flagged
|
|
98
|
+
|
|
99
|
+
| Finding | Meaning |
|
|
100
|
+
| --- | --- |
|
|
101
|
+
| `CRON001_NO_TRAILING_NEWLINE` | The file does not end with a newline. Classic Vixie cron silently drops the last line; modern `crontab` refuses to install such a file, but a file copied straight into `/etc/cron.d` or the spool can still be affected |
|
|
102
|
+
| `CRON002_CRLF_LINE_ENDINGS` | The file contains carriage returns (Windows CRLF or a lone `\r`). Cron keeps the `\r` at the end of the command, so the job fails with a confusing "not found" or is ignored. All affected line numbers are listed |
|
|
103
|
+
| `CRON009_UNESCAPED_PERCENT` | A job command contains a `%` that is not escaped as `\%`. Cron turns the first one into a newline and feeds the rest to the command's stdin, so the command is cut there. Quotes do not protect it, because cron handles `%` before the shell sees the line |
|
|
104
|
+
|
|
105
|
+
These are the same codes the full CronSentry uses for the same checks. Lite does not report anything else (no schedule syntax, no users, no file permissions).
|
|
106
|
+
|
|
107
|
+
## Exit codes for CI
|
|
108
|
+
|
|
109
|
+
| Exit code | Meaning |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `0` | No findings |
|
|
112
|
+
| `1` | At least one finding (any of the three, including unescaped `%`) |
|
|
113
|
+
| `2` | File not readable, `crontab -l` failed or not installed, or bad arguments |
|
|
114
|
+
|
|
115
|
+
```yaml
|
|
116
|
+
# example CI step: fail the build if the crontab you ship has one of these traps
|
|
117
|
+
- run: python3 cronsentry_lite.py --file deploy/crontab
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Already using chkcrontab?
|
|
121
|
+
|
|
122
|
+
[lyda/chkcrontab](https://github.com/lyda/chkcrontab) (PyPI `chkcrontab`, also a Rust port) wins for general crontab linting: schedule syntax, users, a missing trailing newline, bare `%`, and Debian `cron.d` filenames. Keep using it if that is what you need. As far as we can tell from its source, it does not flag CRLF line endings. [alphapialpha/cronlint](https://github.com/alphapialpha/cronlint) is a POSIX shell script that does flag CRLF and a missing final newline. `crontab -T` / `crontab -n` (where available) and `man 5 crontab` remain the references for install-time syntax.
|
|
123
|
+
|
|
124
|
+
cronsentry-lite is not a chkcrontab replacement. Its niche is narrow: one Python file, no extra package, that checks those three silent-skip traps together and returns a CI exit code.
|
|
125
|
+
|
|
126
|
+
## Did it run vs will it run: cronpulse-lite
|
|
127
|
+
|
|
128
|
+
cronsentry-lite asks "will this crontab run as written?" before you deploy it. [cronpulse-lite](https://github.com/alessio1999xx-debug/cronpulse-lite) asks "did the job run, and did it succeed?" at run time: it wraps a job, records its exit code and output, and alerts a webhook when it fails. They do different jobs and work well together.
|
|
129
|
+
|
|
130
|
+
## cronsentry-lite vs CronSentry
|
|
131
|
+
|
|
132
|
+
cronsentry-lite reads one crontab and checks three file-level traps. That's it.
|
|
133
|
+
|
|
134
|
+
The full [CronSentry Cron Preflight Auditor](https://py-forge.com/products/cronsentry-cron-preflight-auditor?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite) audits a whole directory such as `/etc/cron.d` (`--dir`), flags Debian run-parts filename traps (files with a dot in the name are silently ignored), parses schedules and reports unknown `@` shortcuts and missing fields, unwraps `sudo`, `timeout`, `nice` and similar wrappers to check the real script (executable bit, shebang with CRLF, interpreter present, command on cron's `PATH`), clusters cron failures from syslog or journal output (`--syslog`), and can write JSON (`--json`). It never runs your jobs either. One-time payment, yours to keep. No subscription.
|
|
135
|
+
|
|
136
|
+
Lite is not a strict subset: the `crontab -l` / stdin input, `--demo`, and exit code `1` on an unescaped `%` are lite-only (the paid tool reports `%` as a warning and exits `0` unless there are errors).
|
|
137
|
+
|
|
138
|
+
| Capability | Lite (free) | Paid CronSentry |
|
|
139
|
+
| --- | --- | --- |
|
|
140
|
+
| One crontab file (`--file`) | Yes | Yes |
|
|
141
|
+
| Missing final newline, CRLF, unescaped `%` | Yes | Yes |
|
|
142
|
+
| `crontab -l` output or stdin as input | Yes | No |
|
|
143
|
+
| Directory scan, e.g. `/etc/cron.d` (`--dir`) | No | Yes |
|
|
144
|
+
| Debian run-parts filename traps | No | Yes |
|
|
145
|
+
| Schedule syntax: unknown `@` shortcuts, missing fields | No | Yes |
|
|
146
|
+
| `sudo` / `timeout` / `nice` unwrapping, executable bit, shebang, interpreter, cron `PATH` | No | Yes |
|
|
147
|
+
| Syslog / journal failure clustering (`--syslog`) | No | Yes |
|
|
148
|
+
| Output | Plain text | Text or JSON (`--json`) |
|
|
149
|
+
| Exit code `1` on an unescaped `%` alone | Yes | No (warning, exit `0`) |
|
|
150
|
+
|
|
151
|
+
Neither version edits your crontab or runs your jobs.
|
|
152
|
+
|
|
153
|
+
> Need the full version? **CronSentry Cron Preflight Auditor** on PyForge:
|
|
154
|
+
> [py-forge.com/products/cronsentry-cron-preflight-auditor](https://py-forge.com/products/cronsentry-cron-preflight-auditor?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite)
|
|
155
|
+
>
|
|
156
|
+
> Or get every PyForge tool, current and future, with the All-Access Pass ($99, one payment):
|
|
157
|
+
> [py-forge.com/pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite)
|
|
158
|
+
|
|
159
|
+
## FAQ
|
|
160
|
+
|
|
161
|
+
**Is there a write-up of these traps?** Yes: [How to Audit Crontabs and Catch Silent Cron Failures in Linux](https://dev.to/alessio99xx/how-to-audit-crontabs-and-catch-silent-cron-failures-in-linux-l42) on dev.to.
|
|
162
|
+
|
|
163
|
+
**Does it fix my crontab?** No. It only reports. The `fix:` line in each finding tells you what to change.
|
|
164
|
+
|
|
165
|
+
**Is it a cron monitoring tool?** No. It checks the file before cron reads it; it does not watch jobs run. For run-time failure alerts see cronpulse-lite above.
|
|
166
|
+
|
|
167
|
+
## Tests
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
python3 test_cronsentry_lite.py
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The tests are offline and use the sample crontabs in `fixtures/` plus a fake `crontab` command for the `crontab -l` path. CI runs them on Ubuntu (Python 3.9 and 3.12) and macOS.
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT (this lite version). The full CronSentry is sold separately under its own license.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
cronsentry_lite.py,sha256=s1RfA6bpslq96ji4kqevaD5kx2pBej5MiAaxpozc5ZY,9802
|
|
2
|
+
cronsentry_lite-0.1.0.dist-info/licenses/LICENSE,sha256=hHuiZGVU1W0vbSggaTAy28kRUnwp6e85CqEFKsatpcE,1087
|
|
3
|
+
cronsentry_lite-0.1.0.dist-info/METADATA,sha256=q_Wdb3FXGg3LMTrk3sc-nWnBGzHSg5bRFSIYriwrzvU,11414
|
|
4
|
+
cronsentry_lite-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
cronsentry_lite-0.1.0.dist-info/entry_points.txt,sha256=8A-Cs_R9ZHWe4m2cqRJigC2hUYEcDboCJD2loFa2Wcg,57
|
|
6
|
+
cronsentry_lite-0.1.0.dist-info/top_level.txt,sha256=NRPPMxT7bmNTNKy5wunQOEfFl5AD3GmGN7R4MvhmwRk,16
|
|
7
|
+
cronsentry_lite-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PyForge (https://py-forge.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cronsentry_lite
|
cronsentry_lite.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""cronsentry-lite: audit one crontab file for silent failures (read-only).
|
|
3
|
+
|
|
4
|
+
Reads one crontab file (--file PATH, --file - for stdin, or, with no --file,
|
|
5
|
+
the output of `crontab -l` for the current user) and flags three file-level
|
|
6
|
+
traps that make cron skip or truncate a job without a clear error:
|
|
7
|
+
|
|
8
|
+
CRON001_NO_TRAILING_NEWLINE the file does not end with a newline
|
|
9
|
+
CRON002_CRLF_LINE_ENDINGS the file contains carriage returns (\\r, CRLF)
|
|
10
|
+
CRON009_UNESCAPED_PERCENT a job command contains an unescaped %
|
|
11
|
+
|
|
12
|
+
It prints a plain-text report and never edits the file or runs any job.
|
|
13
|
+
|
|
14
|
+
Python 3.9+ standard library only. MIT license.
|
|
15
|
+
|
|
16
|
+
Exit codes: 0 = no findings, 1 = at least one finding,
|
|
17
|
+
2 = error (file not readable, no crontab, bad arguments).
|
|
18
|
+
|
|
19
|
+
Full version (directory scans such as /etc/cron.d, run-parts filename traps,
|
|
20
|
+
sudo/timeout/nice unwrapping with executable/shebang/PATH checks, syslog
|
|
21
|
+
failure clustering, JSON report):
|
|
22
|
+
https://py-forge.com/products/cronsentry-cron-preflight-auditor?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
from typing import List, NamedTuple, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
|
|
34
|
+
PRO_URL = (
|
|
35
|
+
"https://py-forge.com/products/cronsentry-cron-preflight-auditor"
|
|
36
|
+
"?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite"
|
|
37
|
+
)
|
|
38
|
+
PASS_URL = (
|
|
39
|
+
"https://py-forge.com/pass"
|
|
40
|
+
"?utm_source=github&utm_medium=readme&utm_campaign=cronsentry-lite"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
CODE_NEWLINE = "CRON001_NO_TRAILING_NEWLINE"
|
|
44
|
+
CODE_CRLF = "CRON002_CRLF_LINE_ENDINGS"
|
|
45
|
+
CODE_PERCENT = "CRON009_UNESCAPED_PERCENT"
|
|
46
|
+
|
|
47
|
+
# NAME=value lines (environment settings); % has no special meaning there.
|
|
48
|
+
ENV_LINE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\s*=")
|
|
49
|
+
|
|
50
|
+
DEMO_CRONTAB = (
|
|
51
|
+
b"# demo crontab (built in)\r\n"
|
|
52
|
+
b"MAILTO=ops@example.com\n"
|
|
53
|
+
b"*/5 * * * * /usr/local/bin/healthcheck.sh\n"
|
|
54
|
+
b"0 3 * * * tar czf /backup/www-$(date +%F).tgz /var/www\n"
|
|
55
|
+
b"15 3 * * * echo \"done at $(date +\\%H:\\%M)\" >> /var/log/backup.log\n"
|
|
56
|
+
b"@daily /usr/local/bin/rotate-logs.sh\r\n"
|
|
57
|
+
b"30 4 * * 0 /usr/local/bin/weekly-report.sh"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Finding(NamedTuple):
|
|
62
|
+
code: str
|
|
63
|
+
line: int
|
|
64
|
+
message: str
|
|
65
|
+
detail: str
|
|
66
|
+
fix: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_system_crontab(path: str) -> bool:
|
|
70
|
+
"""/etc/crontab and files under /etc/cron.d have a user field."""
|
|
71
|
+
norm = os.path.normpath(os.path.abspath(path))
|
|
72
|
+
parts = norm.split(os.sep)
|
|
73
|
+
if norm == os.path.join(os.sep, "etc", "crontab"):
|
|
74
|
+
return True
|
|
75
|
+
return len(parts) >= 3 and parts[1] == "etc" and parts[2] == "cron.d"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def find_unescaped_percents(command: str) -> List[int]:
|
|
79
|
+
"""Positions of % not preceded by an odd number of backslashes."""
|
|
80
|
+
found = []
|
|
81
|
+
for i, ch in enumerate(command):
|
|
82
|
+
if ch != "%":
|
|
83
|
+
continue
|
|
84
|
+
backslashes = 0
|
|
85
|
+
k = i - 1
|
|
86
|
+
while k >= 0 and command[k] == "\\":
|
|
87
|
+
backslashes += 1
|
|
88
|
+
k -= 1
|
|
89
|
+
if backslashes % 2 == 0:
|
|
90
|
+
found.append(i)
|
|
91
|
+
return found
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def split_lines(raw: bytes) -> List[bytes]:
|
|
95
|
+
"""Split on LF only, so carriage returns stay visible in each line."""
|
|
96
|
+
if not raw:
|
|
97
|
+
return []
|
|
98
|
+
lines = raw.split(b"\n")
|
|
99
|
+
if raw.endswith(b"\n"):
|
|
100
|
+
lines.pop()
|
|
101
|
+
return lines
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def job_command(line: str, system: bool) -> Optional[str]:
|
|
105
|
+
"""Return the command part of a job line, or None if it is not a job."""
|
|
106
|
+
stripped = line.strip()
|
|
107
|
+
if not stripped or stripped.startswith("#") or ENV_LINE.match(stripped):
|
|
108
|
+
return None
|
|
109
|
+
if stripped.startswith("@"):
|
|
110
|
+
parts = stripped.split(None, 2 if system else 1)
|
|
111
|
+
want = 3 if system else 2
|
|
112
|
+
else:
|
|
113
|
+
parts = stripped.split(None, 6 if system else 5)
|
|
114
|
+
want = 7 if system else 6
|
|
115
|
+
if len(parts) < want:
|
|
116
|
+
return None
|
|
117
|
+
return parts[-1]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def shorten(text: str, width: int = 70) -> str:
|
|
121
|
+
text = text.replace("\r", "\\r")
|
|
122
|
+
return text if len(text) <= width else text[: width - 3] + "..."
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def audit_bytes(raw: bytes, system: bool = False) -> Tuple[List[Finding], int]:
|
|
126
|
+
"""Audit crontab bytes. Returns (findings, number of job lines)."""
|
|
127
|
+
findings: List[Finding] = []
|
|
128
|
+
lines = split_lines(raw)
|
|
129
|
+
|
|
130
|
+
if raw and not raw.endswith(b"\n"):
|
|
131
|
+
last = lines[-1].decode("utf-8", "replace") if lines else ""
|
|
132
|
+
findings.append(Finding(
|
|
133
|
+
CODE_NEWLINE, len(lines),
|
|
134
|
+
"file does not end with a newline; classic Vixie cron can silently "
|
|
135
|
+
"drop the last line",
|
|
136
|
+
"last line: " + shorten(last),
|
|
137
|
+
"add a newline at the end of the file",
|
|
138
|
+
))
|
|
139
|
+
|
|
140
|
+
cr_lines = [n for n, b in enumerate(lines, start=1) if b"\r" in b]
|
|
141
|
+
if cr_lines:
|
|
142
|
+
shown = ", ".join(str(n) for n in cr_lines[:10])
|
|
143
|
+
if len(cr_lines) > 10:
|
|
144
|
+
shown += ", ... (%d lines in total)" % len(cr_lines)
|
|
145
|
+
findings.append(Finding(
|
|
146
|
+
CODE_CRLF, cr_lines[0],
|
|
147
|
+
"carriage return (\\r, Windows CRLF): cron keeps the \\r in the "
|
|
148
|
+
"command, so the job can fail",
|
|
149
|
+
"lines: " + shown,
|
|
150
|
+
"convert to Unix LF line endings (dos2unix, or tr -d '\\r')",
|
|
151
|
+
))
|
|
152
|
+
|
|
153
|
+
jobs = 0
|
|
154
|
+
for n, b in enumerate(lines, start=1):
|
|
155
|
+
line = b.decode("utf-8", "replace").replace("\r", "")
|
|
156
|
+
cmd = job_command(line, system)
|
|
157
|
+
if cmd is None:
|
|
158
|
+
continue
|
|
159
|
+
jobs += 1
|
|
160
|
+
pcts = find_unescaped_percents(cmd)
|
|
161
|
+
if pcts:
|
|
162
|
+
findings.append(Finding(
|
|
163
|
+
CODE_PERCENT, n,
|
|
164
|
+
"unescaped %% (%d): cron cuts the command at the first one and "
|
|
165
|
+
"sends the rest to stdin" % len(pcts),
|
|
166
|
+
"command: " + shorten(cmd),
|
|
167
|
+
"escape each % as \\% (quotes do not protect it), e.g. date +\\%F",
|
|
168
|
+
))
|
|
169
|
+
|
|
170
|
+
findings.sort(key=lambda f: (f.line, f.code))
|
|
171
|
+
return findings, jobs
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def format_report(source: str, findings: List[Finding], jobs: int,
|
|
175
|
+
system: bool, demo: bool = False) -> str:
|
|
176
|
+
kind = "system crontab" if system else "user crontab"
|
|
177
|
+
title = "demo (built-in sample crontab)" if demo else source
|
|
178
|
+
out = ["cronsentry-lite %s: %s (%s, %d job line(s))" % (__version__, title, kind, jobs), ""]
|
|
179
|
+
if not findings:
|
|
180
|
+
out.append(" OK no missing final newline, no CRLF, no unescaped %")
|
|
181
|
+
for f in findings:
|
|
182
|
+
out.append(" FLAG line %d: %s" % (f.line, f.code))
|
|
183
|
+
out.append(" %s" % f.message)
|
|
184
|
+
out.append(" %s" % f.detail)
|
|
185
|
+
out.append(" fix: %s" % f.fix)
|
|
186
|
+
out.append("")
|
|
187
|
+
out.append("%d finding(s)." % len(findings))
|
|
188
|
+
out.append("Read-only: the file was not changed and no job was run.")
|
|
189
|
+
return "\n".join(out)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def read_source(path: Optional[str]) -> Tuple[str, bytes]:
|
|
193
|
+
"""Return (label, bytes). Raises OSError / RuntimeError on failure."""
|
|
194
|
+
if path == "-":
|
|
195
|
+
return "<stdin>", sys.stdin.buffer.read()
|
|
196
|
+
if path:
|
|
197
|
+
with open(path, "rb") as fh:
|
|
198
|
+
return path, fh.read()
|
|
199
|
+
try:
|
|
200
|
+
proc = subprocess.run(["crontab", "-l"], stdout=subprocess.PIPE,
|
|
201
|
+
stderr=subprocess.PIPE, check=False)
|
|
202
|
+
except FileNotFoundError:
|
|
203
|
+
raise RuntimeError("`crontab` command not found; pass --file PATH")
|
|
204
|
+
if proc.returncode != 0:
|
|
205
|
+
msg = proc.stderr.decode("utf-8", "replace").strip() or "crontab -l failed"
|
|
206
|
+
raise RuntimeError("%s (pass --file PATH to audit a file)" % msg)
|
|
207
|
+
return "crontab -l", proc.stdout
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
211
|
+
parser = argparse.ArgumentParser(
|
|
212
|
+
prog="cronsentry-lite",
|
|
213
|
+
description=(
|
|
214
|
+
"Audit one crontab for silent failures: missing final newline,\n"
|
|
215
|
+
"CRLF line endings and unescaped %. Read-only, never runs jobs."
|
|
216
|
+
),
|
|
217
|
+
epilog=(
|
|
218
|
+
"With no --file, the output of `crontab -l` is audited.\n"
|
|
219
|
+
"Exit codes: 0 = no findings, 1 = findings, 2 = error.\n\n"
|
|
220
|
+
"Full version (--dir, run-parts traps, sudo/timeout/nice unwrapping,\n"
|
|
221
|
+
"executable/shebang/PATH checks, --syslog, --json):\n"
|
|
222
|
+
+ PRO_URL
|
|
223
|
+
),
|
|
224
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
225
|
+
)
|
|
226
|
+
parser.add_argument("--file", "-f", metavar="PATH",
|
|
227
|
+
help="crontab file to audit ('-' reads stdin)")
|
|
228
|
+
group = parser.add_mutually_exclusive_group()
|
|
229
|
+
group.add_argument("--system", action="store_true",
|
|
230
|
+
help="treat the file as a system crontab (user field after the schedule)")
|
|
231
|
+
group.add_argument("--user", action="store_true",
|
|
232
|
+
help="treat the file as a user crontab (no user field)")
|
|
233
|
+
parser.add_argument("--demo", action="store_true",
|
|
234
|
+
help="audit a built-in sample crontab and exit")
|
|
235
|
+
parser.add_argument("--version", action="version",
|
|
236
|
+
version="cronsentry-lite %s" % __version__)
|
|
237
|
+
return parser
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
241
|
+
args = build_parser().parse_args(argv)
|
|
242
|
+
|
|
243
|
+
if args.demo:
|
|
244
|
+
system = bool(args.system)
|
|
245
|
+
findings, jobs = audit_bytes(DEMO_CRONTAB, system)
|
|
246
|
+
print(format_report("demo", findings, jobs, system, demo=True))
|
|
247
|
+
return 1 if findings else 0
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
label, raw = read_source(args.file)
|
|
251
|
+
except (OSError, RuntimeError) as exc:
|
|
252
|
+
print("cronsentry-lite: error: %s" % exc, file=sys.stderr)
|
|
253
|
+
return 2
|
|
254
|
+
|
|
255
|
+
if args.system:
|
|
256
|
+
system = True
|
|
257
|
+
elif args.user:
|
|
258
|
+
system = False
|
|
259
|
+
else:
|
|
260
|
+
system = bool(args.file) and args.file != "-" and is_system_crontab(args.file)
|
|
261
|
+
|
|
262
|
+
findings, jobs = audit_bytes(raw, system)
|
|
263
|
+
print(format_report(label, findings, jobs, system))
|
|
264
|
+
return 1 if findings else 0
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
if __name__ == "__main__":
|
|
268
|
+
sys.exit(main())
|