#!/bin/sh # Cyber Rakshak error monitoring for shell scripts, version 1.1.0 # Docs: https://app.cyberrakshak.ai/sdk/README.md # Copyright Laabam One Business Solutions (OPC) Private Limited # Released under the MIT licence: https://app.cyberrakshak.ai/sdk/LICENSE # # One POSIX sh file; needs curl and awk. Reports a failed command or a message to your site's Errors page in the # Cyber Rakshak console. Secrets are scrubbed here before anything leaves (email addresses, tokens and keys, # password=... values, query strings, card numbers). # # export CR_MONITOR_KEY=crk_... # your site's app key (Security scan tab); never printed # cr-report.sh run -- ./backup.sh --target s3://... # runs it as ever; if it fails, reports it # cr-report.sh message "Nightly import skipped 3 rows" # level warning; --level error for an error # cr-report.sh scrub < some.log # prints what would be sent, scrubbed # # run: the command's output passes through and the script exits with the command's own code. When the code is not 0, # what is sent is the command's name (never its arguments: they may hold secrets), the code and the last 20 lines of # its standard error, scrubbed. (Standard error goes through a pipe on its way to you, so a command that colours its # errors only on a terminal shows them plain.) Ctrl-C is not reported. # # Settings, from the environment: CR_MONITOR_KEY (needed), CR_MONITOR_ENDPOINT, CR_MONITOR_RELEASE, # CR_MONITOR_ENVIRONMENT, CR_MONITOR_ENABLED (0 or false: nothing is sent), CR_MONITOR_SAMPLE_RATE (0..1), # CR_MONITOR_CONTEXT (k=v,k2=v2: sent every time), CR_MONITOR_SCRUB_NAMES (name1,name2: names of your own whose values # are removed, like password=; only added to the built-in rules), CR_MONITOR_BEFORE_SEND (a command that gets the problem's JSON on # standard input and prints it, changed, or prints nothing to drop it), CR_MONITOR_DEBUG (1: say what happens, on # standard error), CR_MONITOR_PLATFORM (script unless you say server, desktop or other), CR_MONITOR_SPOOL (the folder # where what could not be sent waits for the next run; default ~/.cache/cyberrakshak-monitor). # Options of run and message: --route NAME, --context k=v (again for more), --level warning|error. # # A send takes at most 5 s. When the console asks to wait (429) or cannot be reached, the report waits in the spool # folder and goes with a later run. Nothing in here may change what your script does: a monitor that fails must never # become the script's second problem. (It also starts as few programs as it can: a report is about five.) CR_VERSION=1.1.0 CR_DEFAULT_ENDPOINT=https://app.cyberrakshak.ai/api/v1/app-reports # Scrubbing (the same rules, in the same order, as every Cyber Rakshak library) and the problem's JSON, in awk. # (In this quoted program a single quote is written \047.) CR_AWK_PROGRAM=' function setup( i) { for (i = 1; i < 256; i++) ORD[sprintf("%c", i)] = i extra_setup() } # CR_MONITOR_SCRUB_NAMES (comma-separated): names of your own whose values go, as whole words, like the built-in ones. # Each 1 to 40 of A-Z a-z 0-9 _ . -, at most 50; anything else is left out (cr_setup says so when CR_MONITOR_DEBUG is on). function extra_setup( n, parts, i, name, kept) { XRE = ""; kept = 0 n = split(ENVIRON["CR_MONITOR_SCRUB_NAMES"], parts, ",") for (i = 1; i <= n && kept < 50; i++) { name = tolower(parts[i]); gsub(/^[ ]+|[ ]+$/, "", name) if (name == "" || length(name) > 40 || name ~ /[^a-z0-9_.-]/) continue gsub(/[.]/, "[.]", name) XRE = XRE (XRE == "" ? "" : "|") name; kept++ } if (XRE != "") XRE = "(" XRE ")" } # Text as it may be sent: no terminal colour codes, no control characters but tab and newline, valid UTF-8. function clean(s) { gsub(/\033\[[0-9;?]*[ -\/]*[@-~]/, "", s) gsub(/\033\][^\007\033]*(\007|\033\\)/, "", s) gsub(/[\001-\010\013-\037\177]/, "", s) return utf8(s) } # Valid UTF-8 as it is (one pass of a regular expression); otherwise each byte that is not part of a character # becomes U+FFFD. function utf8(s, out, valid) { if (!match(s, /[\200-\377]/)) return s valid = "^([\001-\177]|[\302-\337][\200-\277]|\340[\240-\277][\200-\277]|[\341-\354\356\357][\200-\277][\200-\277]|\355[\200-\237][\200-\277]|\360[\220-\277][\200-\277][\200-\277]|[\361-\363][\200-\277][\200-\277][\200-\277]|\364[\200-\217][\200-\277][\200-\277])*" out = "" while (s != "") { match(s, valid) out = out substr(s, 1, RLENGTH) s = substr(s, RLENGTH + 1) if (s != "") { out = out "\357\277\275"; s = substr(s, 2) } } return out } # At most n bytes, never cut inside a character: the first n (clipb) or the last n (tailb). function clipb(s, n, k) { if (length(s) <= n) return s k = n while (k > 0 && ORD[substr(s, k + 1, 1)] >= 128 && ORD[substr(s, k + 1, 1)] <= 191) k-- return substr(s, 1, k) } function tailb(s, n, k) { if (length(s) <= n) return s k = length(s) - n + 1 while (k <= length(s) && ORD[substr(s, k, 1)] >= 128 && ORD[substr(s, k, 1)] <= 191) k++ return substr(s, k) } function luhn(d, i, n, sum, dbl) { sum = 0; dbl = 0 for (i = length(d); i >= 1; i--) { n = substr(d, i, 1) + 0 if (dbl) { n *= 2; if (n > 9) n -= 9 } sum += n; dbl = !dbl } return sum % 10 == 0 } # 1. A query string: ?name=... up to a space or quote. function r_query(s, out) { out = "" while (match(s, /\?[A-Za-z0-9_.%-]+[=&][^ \t\r#"\047<>]*/)) { out = out substr(s, 1, RSTART - 1); s = substr(s, RSTART + RLENGTH) } return out s } # 2. Authorization values: Bearer/Basic (any case), spaces, 8 or more token characters holding a digit, an upper-case # letter or one of . _ ~ + / =. function r_auth(s, out, low, st, ln, m, sch, v) { out = "" while (1) { low = tolower(s) if (!match(low, /(bearer|basic) +[a-z0-9._~+\/=-]+/)) break st = RSTART; ln = RLENGTH; m = substr(s, st, ln) sch = substr(low, st, 6) == "bearer" ? 6 : 5 v = substr(m, sch + 1); sub(/^ +/, "", v) if (length(v) < 8) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } out = out substr(s, 1, st - 1) (v ~ /[0-9A-Z._~+\/=]/ ? substr(m, 1, sch) " [token]" : m) s = substr(s, st + ln) } return out s } # 3. password=..., "client_secret": "...", x-api-key: ...: from the word on (any case), at most 40 more name characters, # the separator; the value goes. function r_secret(s, out, low, st, ln, m, k, suf, sep) { out = "" while (1) { low = tolower(s) if (!match(low, /(password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|session[_-]?id)[a-z0-9_-]*\\?["\047]?[ ]*[=:][ ]*\\?["\047]?[^ \t\r&,;"\047<>\\]+/)) break st = RSTART; ln = RLENGTH; m = substr(s, st, ln) match(substr(low, st), /^(password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|session[_-]?id)/); k = RLENGTH match(substr(m, k + 1), /^[A-Za-z0-9_-]*/); suf = RLENGTH if (suf > 40) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } match(substr(m, k + suf + 1), /^\\?["\047]?[ ]*[=:][ ]*\\?["\047]?/); sep = RLENGTH out = out substr(s, 1, st - 1) substr(m, 1, k + suf + sep) "[removed]" s = substr(s, st + ln) } return out s } # 4. JSON Web Tokens (a header of at most 500 characters). function r_jwt(s, out, st, ln, m) { out = "" while (match(s, /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)?/)) { st = RSTART; ln = RLENGTH; m = substr(s, st, ln) if (index(m, ".") - 4 > 500) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } out = out substr(s, 1, st - 1) "[token]"; s = substr(s, st + ln) } return out s } # 5. Keys that say what they are, not right after a letter or digit, with 10 or more characters after the prefix. function r_prefixed(s, out, st, ln, m, p) { out = "" while (match(s, /(crk_|crw_|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xoxb-|xoxp-|xoxa-|AKIA|ASIA|AIza)[A-Za-z0-9_-]+/)) { st = RSTART; ln = RLENGTH; m = substr(s, st, ln) match(m, /^(crk_|crw_|sk_live_|sk_test_|pk_live_|pk_test_|rk_live_|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xoxb-|xoxp-|xoxa-|AKIA|ASIA|AIza)/); p = RLENGTH if ((st > 1 && substr(s, st - 1, 1) ~ /[A-Za-z0-9]/) || ln - p < 10) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } out = out substr(s, 1, st - 1) "[token]"; s = substr(s, st + ln) } return out s } # 6. Email addresses (at most 64 characters before the @: more are kept as they are). function r_email(s, out, st, ln, m, at) { out = "" while (match(s, /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z][A-Za-z]+/)) { st = RSTART; ln = RLENGTH; m = substr(s, st, ln) at = index(m, "@") - 1 out = out substr(s, 1, st - 1) (at > 64 ? substr(m, 1, at - 64) : "") "[email]" s = substr(s, st + ln) } return out s } # 7. IBANs: two capital letters, two digits, then 11 to 30 capitals or digits (or the same in groups of four, single # spaces between), 15 to 34 in all, not touching a letter or digit, passing the ISO 13616 mod-97 check. Before cards. function iban_ok(c, s, i, v, rest, moved) { s = c; gsub(/ /, "", s) if (length(s) < 15 || length(s) > 34) return 0 moved = substr(s, 5) substr(s, 1, 4); rest = 0 for (i = 1; i <= length(moved); i++) { v = ORD[substr(moved, i, 1)] v = v >= 65 ? v - 55 : v - 48 rest = v > 9 ? (rest * 100 + v) % 97 : (rest * 10 + v) % 97 } return rest == 1 } # The IBAN-shaped start of m (capitals and digits in tokens split by single spaces), or "": the first token alone # (4 + 11 to 30 characters), or the first token of 4 then 2 to 7 groups of 4 and perhaps one of 1 to 4. after is the # character after m: an IBAN may not run into a letter or digit. function iban_cand(m, after, n, tok, i, g, cand, last) { n = split(m, tok, " ") if (length(tok[1]) > 4) { if (length(tok[1]) < 15 || length(tok[1]) > 34) return "" if (n == 1 && after ~ /[A-Za-z0-9]/) return "" return tok[1] } if (length(tok[1]) != 4) return "" cand = tok[1]; g = 0 for (i = 2; i <= n && g < 7 && length(tok[i]) == 4; i++) { cand = cand " " tok[i]; g++ } last = "" if (i <= n && length(tok[i]) <= 4) last = tok[i] if (last != "") { if (i < n || after !~ /[A-Za-z0-9]/) return g >= 2 ? cand " " last : "" } else if (i <= n || after !~ /[A-Za-z0-9]/) { return g >= 2 ? cand : "" } # It runs into a letter or digit: one group less, as a regular expression would back off. if (last == "") { sub(/ [A-Z0-9]+$/, "", cand); g-- } return g >= 2 ? cand : "" } function r_iban(s, out, st, ln, m, cand) { out = "" while (match(s, /[A-Z][A-Z][0-9][0-9][A-Z0-9]*( [A-Z0-9]+)*/)) { st = RSTART; ln = RLENGTH; m = substr(s, st, ln) cand = (st > 1 && substr(s, st - 1, 1) ~ /[A-Za-z0-9]/) ? "" : iban_cand(m, substr(s, st + ln, 1)) if (cand == "") { out = out substr(s, 1, st); s = substr(s, st + 1); continue } out = out substr(s, 1, st - 1) (iban_ok(cand) ? "[iban]" : cand) s = substr(s, st + length(cand)) } return out s } # 8. Card numbers: 13 to 19 digits (single spaces or dashes between), not right after a digit, passing the Luhn check. function r_card(s, out, st, ln, m, d, i, c, cut) { out = "" while (match(s, /[0-9]([ -]?[0-9])*/)) { st = RSTART; ln = RLENGTH; m = substr(s, st, ln) d = m; gsub(/[^0-9]/, "", d) if ((st > 1 && substr(s, st - 1, 1) ~ /[0-9]/) || length(d) < 13) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } if (length(d) > 19) { c = 0 for (i = 1; i <= ln; i++) if (substr(m, i, 1) ~ /[0-9]/ && ++c == 19) { cut = i; break } m = substr(m, 1, cut); ln = cut; d = substr(d, 1, 19) } out = out substr(s, 1, st - 1) (luhn(d) ? "[card]" : m) s = substr(s, st + ln) } return out s } # 9. pin: 1234, "iban": "...", set-cookie: ..., x-tink-signature=...: these names only as whole words (not right after a # letter or digit, the separator right after the name), so company:, spinning: and japan: stay; the value goes as in # rule 3. After IBANs and cards, so a value with spaces in it has gone whole already. A value of Bearer or Basic and a # space was handled in rule 2. function r_named(s, out, low, st, ln, m, k, sep, v) { out = "" while (1) { low = tolower(s) if (!match(low, /(authorization|cookie|signature|otp|pin|cvv|cvc|iban|bban|pan|account[_-]?(no|number|num)|sort[_-]?code|card[_-]?number|bank[_-]?auth[_-]?id)\\?["\047]?[ ]*[=:][ ]*\\?["\047]?[^ \t\r&,;"\047<>\\]+/)) break st = RSTART; ln = RLENGTH; m = substr(s, st, ln) match(substr(low, st), /^(authorization|cookie|signature|otp|pin|cvv|cvc|iban|bban|pan|account[_-]?(no|number|num)|sort[_-]?code|card[_-]?number|bank[_-]?auth[_-]?id)/); k = RLENGTH match(substr(m, k + 1), /^\\?["\047]?[ ]*[=:][ ]*\\?["\047]?/); sep = RLENGTH v = tolower(substr(m, k + sep + 1)) if ((st > 1 && substr(s, st - 1, 1) ~ /[A-Za-z0-9]/) || ((v == "bearer" || v == "basic") && substr(s, st + ln, 1) == " ")) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } out = out substr(s, 1, st - 1) substr(m, 1, k + sep) "[removed]" s = substr(s, st + ln) } return out s } # 10. Runs of 32 or more hex digits. function r_hex(s, out) { out = "" while (match(s, /[0-9a-fA-F]+/)) { out = out substr(s, 1, RSTART - 1) (RLENGTH >= 32 ? "[token]" : substr(s, RSTART, RLENGTH)) s = substr(s, RSTART + RLENGTH) } return out s } # 11. Runs of 40 or more of A-Z a-z 0-9 + _ - holding a digit, an upper-case and a lower-case letter. function r_long(s, out, m) { out = "" while (match(s, /[A-Za-z0-9+_-]+/)) { m = substr(s, RSTART, RLENGTH) out = out substr(s, 1, RSTART - 1) (RLENGTH >= 40 && m ~ /[0-9]/ && m ~ /[A-Z]/ && m ~ /[a-z]/ ? "[token]" : m) s = substr(s, RSTART + RLENGTH) } return out s } # Then CR_MONITOR_SCRUB_NAMES: only added to the rules above, which always run. function r_extra(s, out, low, st, k, rest, v, sep) { if (XRE == "") return s out = "" while (1) { low = tolower(s) if (!match(low, XRE)) break st = RSTART; k = RLENGTH; rest = substr(s, st + k) if ((st > 1 && substr(s, st - 1, 1) ~ /[A-Za-z0-9]/) || !match(rest, /^\\?["\047]?[ ]*[=:][ ]*\\?["\047]?[^ \t\r&,;"\047<>\\]+/)) { out = out substr(s, 1, st); s = substr(s, st + 1); continue } v = RLENGTH match(rest, /^\\?["\047]?[ ]*[=:][ ]*\\?["\047]?/); sep = RLENGTH out = out substr(s, 1, st - 1) substr(s, st, k + sep) "[removed]" s = substr(s, st + k + v) } return out s } # A context name that says its value is a secret: the words of rule 3 anywhere in it, a whole-word name of rule 9 or # of CR_MONITOR_SCRUB_NAMES at its end (user_pin, x-tink-signature; not spinning). function secret_key(k, low) { low = tolower(k) if (low ~ /(password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|session[_-]?id)/) return 1 if (low ~ /(^|[^a-z0-9])(authorization|cookie|signature|otp|pin|cvv|cvc|iban|bban|pan|account[_-]?(no|number|num)|sort[_-]?code|card[_-]?number|bank[_-]?auth[_-]?id)$/) return 1 return XRE != "" && low ~ ("(^|[^a-z0-9])" XRE "$") } function scrub_line(s) { return r_extra(r_long(r_hex(r_named(r_card(r_iban(r_email(r_prefixed(r_jwt(r_secret(r_auth(r_query(s)))))))))))) } function scrub(s, n, parts, i, out) { n = split(s, parts, "\n") out = "" for (i = 1; i <= n; i++) out = out (i > 1 ? "\n" : "") scrub_line(parts[i]) return out } function jstr(s, out, c) { out = "" while (match(s, /[\\"\t\n\r]/)) { c = substr(s, RSTART, 1) out = out substr(s, 1, RSTART - 1) (c == "\\" ? "\\\\" : c == "\"" ? "\\\"" : c == "\t" ? "\\t" : c == "\n" ? "\\n" : "\\r") s = substr(s, RSTART + 1) } return "\"" out s "\"" } function text(s, n) { return clipb(scrub(clipb(clean(clipb(s, n * 4)), n * 2)), n) } # The end of a standard error is what matters most: when it is too long, its last bytes are kept. function text_end(s, n) { return tailb(scrub(tailb(clean(tailb(s, n * 4)), n * 2)), n) } BEGIN { setup() } mode == "scrub" { print scrub_line($0); next } # The problem: its standard error is the input, of which the last 20 lines are kept. mode == "problem" { ring[NR % 20] = $0; next } END { if (mode != "problem") exit first = NR > 20 ? NR - 19 : 1 for (i = first; i <= NR; i++) stack = stack (i > first ? "\n" : "") ring[i % 20] msg = text(ENVIRON["CR__MESSAGE"], 4000) if (msg !~ /[^ \t\n]/) msg = "(no message)" out = "{\"kind\":" jstr(ENVIRON["CR__KIND"]) ",\"message\":" jstr(msg) ",\"level\":" jstr(ENVIRON["CR__LEVEL"]) ",\"count\":1,\"at\":" jstr(ENVIRON["CR__AT"]) stack = text_end(stack, 12000) if (stack ~ /[^ \t\n]/) out = out ",\"stack\":" jstr(stack) route = ENVIRON["CR__ROUTE"]; sub(/[?#].*/, "", route); gsub(/\n/, " ", route); route = text(route, 200) if (route != "") out = out ",\"route\":" jstr(route) n = split(ENVIRON["CR__CONTEXT"], pairs, "\n"); kept = 0; ctx = "" for (i = 1; i <= n && kept < 20; i++) { eq = index(pairs[i], "="); if (eq < 2) continue k = clipb(clean(substr(pairs[i], 1, eq - 1)), 40); v = substr(pairs[i], eq + 1) if (k in seen) continue seen[k] = 1; kept++ ctx = ctx (ctx == "" ? "" : ",") jstr(k) ":" (secret_key(k) ? jstr("[removed]") : v ~ /^-?(0|[1-9][0-9]*)$/ && length(v) <= 15 ? v : jstr(text(v, 300))) } if (ctx != "") out = out ",\"context\":{" ctx "}" print out "}" } ' cr_debug() { case ${CR_MONITOR_DEBUG:-} in 1 | true | yes) printf '[cyberrakshak-monitor] %s\n' "$*" >&2 ;; esac return 0 } # CR_MONITOR_SCRUB_NAMES, checked as awk will use it, so that what is left out is said (with CR_MONITOR_DEBUG on). cr_scrub_names() { cr_names=${CR_MONITOR_SCRUB_NAMES:-} cr_kept=0 while [ -n "$cr_names" ]; do cr_name=${cr_names%%,*} case $cr_names in *,*) cr_names=${cr_names#*,} ;; *) cr_names= ;; esac while :; do case $cr_name in ' '*) cr_name=${cr_name# } ;; *' ') cr_name=${cr_name% } ;; *) break ;; esac; done if [ -z "$cr_name" ] || [ "${#cr_name}" -gt 40 ] || case $cr_name in *[!A-Za-z0-9_.-]*) true ;; *) false ;; esac; then cr_debug "CR_MONITOR_SCRUB_NAMES: a name was left out: only A-Z a-z 0-9 _ . - (1 to 40)" continue fi cr_kept=$((cr_kept + 1)) if [ "$cr_kept" -gt 50 ]; then cr_debug "CR_MONITOR_SCRUB_NAMES: only the first 50 are used" break fi done return 0 } # The time, read once: CR_NOW (seconds since 1970) and CR_AT (ISO 8601, UTC). cr_clock() { # shellcheck disable=SC2046 set -- $(date -u '+%s %Y-%m-%dT%H:%M:%SZ' 2>/dev/null) CR_NOW=${1:-} CR_AT=${2:-1970-01-01T00:00:00Z} case $CR_NOW in '' | *[!0-9]*) CR_NOW=$(awk 'BEGIN { srand(); print srand() }') ;; esac } # Private scratch files, made in one go: cr_files a b sets CR_F_a and CR_F_b. cr_files() { ( umask 077 set -C for cr_n in "$@"; do cr_p="${TMPDIR:-/tmp}/cr-report.$$.$cr_n" rm -f "$cr_p" 2>/dev/null : >"$cr_p" || exit 1 done ) 2>/dev/null || return 1 for cr_n in "$@"; do eval "CR_F_$cr_n=\"\${TMPDIR:-/tmp}/cr-report.\$\$.$cr_n\"" done return 0 } # Reads a number kept in a file into the variable named $2 (0 when there is none). cr_number() { cr_v= [ -f "$1" ] && IFS= read -r cr_v <"$1" 2>/dev/null case $cr_v in '' | *[!0-9]*) cr_v=0 ;; esac eval "$2=\$cr_v" } cr_runtime() { if [ -n "${BASH_VERSION:-}" ]; then cr_minor=${BASH_VERSION#*.} CR_RUNTIME="bash ${BASH_VERSION%%.*}.${cr_minor%%.*}" elif [ -n "${ZSH_VERSION:-}" ]; then CR_RUNTIME="zsh $ZSH_VERSION" elif [ -n "${KSH_VERSION:-}" ]; then CR_RUNTIME=ksh else CR_RUNTIME=sh fi case $CR_RUNTIME in *[!A-Za-z0-9._\ -]*) CR_RUNTIME=sh ;; esac } # The settings, checked without starting a program. Fails when nothing is to be sent. cr_setup() { case ${CR_MONITOR_ENABLED:-1} in 0 | false | no | off) return 1 ;; esac CR_KEY=${CR_MONITOR_KEY:-} cr_rest=${CR_KEY#crk_} if [ "${#CR_KEY}" -ne 36 ] || [ "$cr_rest" = "$CR_KEY" ] || case $cr_rest in *[!A-Za-z0-9]*) true ;; *) false ;; esac; then cr_debug "not sent: CR_MONITOR_KEY must be your site's crk_ app key (its Security scan tab, Apps, servers and scripts)" return 1 fi cr_scrub_names CR_ENDPOINT=${CR_MONITOR_ENDPOINT:-$CR_DEFAULT_ENDPOINT} case $CR_ENDPOINT in *[[:space:]\"\\]*) CR_ENDPOINT=$CR_DEFAULT_ENDPOINT ;; http://?* | https://?*) ;; *) CR_ENDPOINT=$CR_DEFAULT_ENDPOINT ;; esac CR_RELEASE=${CR_MONITOR_RELEASE:-} if [ -n "$CR_RELEASE" ]; then case $CR_RELEASE in *[!A-Za-z0-9._+-]*) CR_RELEASE= ;; esac [ "${#CR_RELEASE}" -gt 60 ] && CR_RELEASE= [ -z "$CR_RELEASE" ] && cr_debug "release left out: it may hold only A-Z a-z 0-9 . _ + - (at most 60)" fi CR_ENVIRONMENT=${CR_MONITOR_ENVIRONMENT:-} case $CR_ENVIRONMENT in *[A-Z]*) CR_ENVIRONMENT=$(printf '%s' "$CR_ENVIRONMENT" | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz') ;; esac if [ -n "$CR_ENVIRONMENT" ]; then case $CR_ENVIRONMENT in *[!a-z0-9_-]*) CR_ENVIRONMENT= ;; esac [ "${#CR_ENVIRONMENT}" -gt 30 ] && CR_ENVIRONMENT= [ -z "$CR_ENVIRONMENT" ] && cr_debug "environment left out: it may hold only a-z 0-9 _ - (at most 30)" fi case ${CR_MONITOR_PLATFORM:-script} in mobile | server | script | desktop | other) CR_PLATFORM=${CR_MONITOR_PLATFORM:-script} ;; *) CR_PLATFORM=script ;; esac case ${CR_MONITOR_SAMPLE_RATE:-1} in 1 | 1.0 | 1.00) ;; 0 | 0.0 | 0.00) return 1 ;; *) awk -v r="$CR_MONITOR_SAMPLE_RATE" -v seed="$$" 'BEGIN { srand(); s = srand(); srand(s * 1000 + seed); exit !(r + 0 >= 1 || rand() < r + 0) }' || return 1 ;; esac cr_runtime # The spool: one folder, made the first time it is needed. CR_SPOOL=${CR_MONITOR_SPOOL:-${XDG_CACHE_HOME:-${HOME:-/tmp}/.cache}/cyberrakshak-monitor} if [ ! -d "$CR_SPOOL" ]; then (umask 077 && mkdir -p "$CR_SPOOL") 2>/dev/null || CR_SPOOL= fi [ -n "$CR_SPOOL" ] && [ ! -w "$CR_SPOOL" ] && CR_SPOOL= return 0 } # One POST of the file $1: sets CR_STATUS (0: no answer) and CR_RETRY_AFTER (seconds, or empty). cr_post() { CR_STATUS=0 CR_RETRY_AFTER= # The key goes to curl on standard input, never on its command line (where other users could see it). CR_STATUS=$(curl -s -o /dev/null -w '%{http_code}' -D "$CR_F_head" --max-time 5 --connect-timeout 3 -X POST \ -H 'Content-Type: application/json' -H "User-Agent: cyberrakshak-shell/$CR_VERSION" --data-binary @"$1" -K - "$CR_ENDPOINT" 2>/dev/null </dev/null && mv -f "$cr_name.part" "$cr_name.json" 2>/dev/null printf '%s\n' "$2" >"$CR_SPOOL/not-before" 2>/dev/null set -- "$CR_SPOOL"/*.json if [ $# -gt 50 ]; then cr_drop=$(($# - 50)) cr_old= for cr_f in "$@"; do [ "$cr_drop" -gt 0 ] || break cr_old="$cr_old $cr_f" cr_drop=$((cr_drop - 1)) done # shellcheck disable=SC2086 rm -f $cr_old fi } # What the console's answer means for the body $1: 0 taken (or dropped for good), 1 kept, or refused: stop for now. cr_answer() { if [ "$CR_STATUS" -ge 200 ] && [ "$CR_STATUS" -lt 300 ]; then [ -n "$CR_SPOOL" ] && [ -f "$CR_SPOOL/backoff" ] && : >"$CR_SPOOL/backoff" return 0 fi if [ "$CR_STATUS" -eq 0 ] || [ "$CR_STATUS" -eq 429 ] || [ "$CR_STATUS" -ge 500 ]; then if [ -n "$CR_RETRY_AFTER" ]; then cr_wait=$CR_RETRY_AFTER else cr_number "$CR_SPOOL/backoff" cr_wait if [ "$cr_wait" -lt 2 ]; then cr_wait=2; else cr_wait=$((cr_wait * 2)); fi [ "$cr_wait" -gt 300 ] && cr_wait=300 [ -n "$CR_SPOOL" ] && printf '%s\n' "$cr_wait" >"$CR_SPOOL/backoff" 2>/dev/null fi [ "$cr_wait" -gt 86400 ] && cr_wait=86400 cr_keep "$1" "$((CR_NOW + cr_wait))" cr_shown=$CR_STATUS [ "$CR_STATUS" -eq 0 ] && cr_shown=nothing cr_debug "the console answered $cr_shown; kept for a later run (in $cr_wait s at the earliest)" return 1 fi if [ "$CR_STATUS" -eq 401 ] || [ "$CR_STATUS" -eq 403 ]; then if [ -n "$CR_SPOOL" ]; then printf '%s\n' "$((CR_NOW + 3600))" >"$CR_SPOOL/blocked-until" 2>/dev/null set -- "$CR_SPOOL"/*.json [ -e "$1" ] && rm -f "$@" fi cr_debug "the console answered $CR_STATUS: nothing is sent for an hour" return 1 fi cr_debug "the console answered $CR_STATUS: the report was dropped" return 0 } # Up to 3 reports that waited in the spool, oldest first, once the console's wait is over. cr_drain() { [ -n "$CR_SPOOL" ] || return 0 cr_number "$CR_SPOOL/not-before" cr_nb [ "$cr_nb" -gt "$CR_NOW" ] && return 0 cr_sent=0 for cr_file in "$CR_SPOOL"/*.json; do [ -f "$cr_file" ] || continue [ "$cr_sent" -lt 3 ] || break cr_sent=$((cr_sent + 1)) mv -f "$cr_file" "$CR_F_body" 2>/dev/null || continue cr_post "$CR_F_body" cr_answer "$CR_F_body" || break done return 0 } # Sends the problem whose JSON is $1 (cr_setup and cr_files body head done), then what waited in the spool. cr_send() { cr_problem=$1 if [ -n "${CR_MONITOR_BEFORE_SEND:-}" ]; then cr_problem=$(printf '%s' "$cr_problem" | sh -c "$CR_MONITOR_BEFORE_SEND" 2>/dev/null) || cr_problem= if [ -z "$cr_problem" ]; then cr_debug "CR_MONITOR_BEFORE_SEND dropped the report" return 0 fi fi if [ -n "$CR_SPOOL" ]; then cr_number "$CR_SPOOL/blocked-until" cr_blocked if [ "$cr_blocked" -gt "$CR_NOW" ]; then cr_debug "not sent: the console refused this key less than an hour ago" return 0 fi fi { printf '{"sdk":{"name":"cyberrakshak-shell","version":"%s"},"platform":"%s","runtime":"%s"' "$CR_VERSION" "$CR_PLATFORM" "$CR_RUNTIME" [ -n "$CR_RELEASE" ] && printf ',"release":"%s"' "$CR_RELEASE" [ -n "$CR_ENVIRONMENT" ] && printf ',"environment":"%s"' "$CR_ENVIRONMENT" printf ',"errors":[%s]}' "$cr_problem" } >"$CR_F_body" if [ -n "$CR_SPOOL" ]; then cr_number "$CR_SPOOL/not-before" cr_nb if [ "$cr_nb" -gt "$CR_NOW" ]; then cr_keep "$CR_F_body" "$cr_nb" cr_debug "kept for a later run: the console asked to wait" return 0 fi fi cr_post "$CR_F_body" cr_answer "$CR_F_body" && cr_drain return 0 } # The problem's JSON: $1 kind, $2 level, $3 message, $4 route, $5 its standard error (a file, or empty). cr_problem() { # Straight to awk (assignments before a shell function need not reach the programs it runs). # BINMODE=3: gawk on Windows would otherwise drop the CR of a CRLF; any other awk ignores the variable. CR__KIND=$1 CR__LEVEL=$2 CR__MESSAGE=$3 CR__ROUTE=$4 CR__AT=$CR_AT CR__CONTEXT=$CR__CONTEXT \ LC_ALL=C ${CR_MONITOR_AWK:-awk} -v BINMODE=3 -v mode=problem "$CR_AWK_PROGRAM" "${5:-/dev/null}" } cr_usage() { cat >&2 <<'CR_USAGE' usage: cr-report.sh run [--route NAME] [--context k=v]... -- command [arguments...] cr-report.sh message [--level warning|error] [--route NAME] [--context k=v]... "text" cr-report.sh scrub (standard input to standard output, scrubbed) cr-report.sh --version CR_USAGE } # Options shared by run and message: sets CR_ROUTE, CR_LEVEL, CR__CONTEXT and CR_SHIFT (how many arguments they took). cr_options() { CR_ROUTE= CR_LEVEL= CR__CONTEXT= cr_c=${CR_MONITOR_CONTEXT:-} while [ -n "$cr_c" ]; do CR__CONTEXT="$CR__CONTEXT ${cr_c%%,*}" case $cr_c in *,*) cr_c=${cr_c#*,} ;; *) cr_c= ;; esac done CR_SHIFT=0 while [ $# -gt 0 ]; do case $1 in --route | --level | --context) [ $# -ge 2 ] || break case $1 in --route) CR_ROUTE=$2 ;; --level) CR_LEVEL=$2 ;; --context) CR__CONTEXT="$CR__CONTEXT $2" ;; esac CR_SHIFT=$((CR_SHIFT + 2)) shift 2 ;; --) CR_SHIFT=$((CR_SHIFT + 1)) break ;; *) break ;; esac done } cr_main() { case ${1:-} in run) shift cr_options "$@" shift "$CR_SHIFT" if [ $# -eq 0 ]; then cr_usage return 2 fi cr_command=${1##*/} cr_interrupted= trap 'cr_interrupted=1' INT TERM if cr_files err code body head; then # The command's standard output goes straight through; its standard error through tee, which keeps a copy. { { "$@"; echo $? >"$CR_F_code"; } 2>&1 1>&3 3>&- | tee "$CR_F_err" 1>&2 3>&-; } 3>&1 cr_code= IFS= read -r cr_code <"$CR_F_code" else "$@" cr_code=$? CR_F_err= fi case $cr_code in '' | *[!0-9]*) cr_code=1 ;; esac trap - INT TERM if [ "$cr_code" -ne 0 ] && [ -z "$cr_interrupted" ] && [ -n "$CR_F_err" ] && cr_setup && command -v curl >/dev/null 2>&1; then cr_clock CR__CONTEXT="$CR__CONTEXT exit_code=$cr_code" cr_json=$(cr_problem script error "$cr_command exited with code $cr_code" "${CR_ROUTE:-$cr_command}" "$CR_F_err") [ -n "$cr_json" ] && cr_send "$cr_json" elif [ "$cr_code" -eq 0 ] && [ -n "$CR_F_err" ]; then # Went well: if reports wait in the spool, they go now (no request when none wait). cr_spool=${CR_MONITOR_SPOOL:-${XDG_CACHE_HOME:-${HOME:-/tmp}/.cache}/cyberrakshak-monitor} for cr_f in "$cr_spool"/*.json; do if [ -f "$cr_f" ] && cr_setup && command -v curl >/dev/null 2>&1; then cr_clock cr_drain fi break done fi [ -n "$CR_F_err" ] && rm -f "$CR_F_err" "$CR_F_code" "$CR_F_body" "$CR_F_head" return "$cr_code" ;; message) shift cr_options "$@" shift "$CR_SHIFT" if [ $# -eq 0 ]; then cr_usage return 2 fi case $CR_LEVEL in error | warning) ;; *) CR_LEVEL=warning ;; esac if cr_setup && command -v curl >/dev/null 2>&1 && cr_files body head; then cr_clock cr_json=$(cr_problem log "$CR_LEVEL" "$*" "$CR_ROUTE" "") [ -n "$cr_json" ] && cr_send "$cr_json" rm -f "$CR_F_body" "$CR_F_head" fi return 0 ;; scrub) LC_ALL=C ${CR_MONITOR_AWK:-awk} -v BINMODE=3 -v mode=scrub "$CR_AWK_PROGRAM" return 0 ;; --version | version) printf 'cr-report.sh (cyberrakshak-shell) %s\n' "$CR_VERSION" return 0 ;; *) cr_usage return 2 ;; esac } cr_main "$@" exit $?