caucase.sh 31.1 KB
Newer Older
1 2
#!/bin/sh
# This file is part of caucase
3
# Copyright (C) 2017-2019  Nexedi
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#     Vincent Pelletier <vincent@nexedi.com>
#
# caucase is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# caucase is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with caucase.  If not, see <http://www.gnu.org/licenses/>.
set -u

str2json () {
  # Convert some text into a json string.
  # Usage: str2json < str

  # Note: using $() to strip the trailing newline added by jq.
  printf "%s" "$(jq --raw-input --slurp .)"
}

pairs2obj () {
  # Convert pairs of arguments into keys & values of a json objet.
  # Usage: pairs2obj <key0> <value0> [...]
  # Outputs: {"key0":value0}
  # No sanity checks on keys nor values.
  # Keys are expected unquoted, as they must be strings anyway.
  # Values are expected in json.
  # If arg count is odd, last argument is ignored.
36
  # shellcheck disable=SC2039
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  local first=1
  printf '{'
  while [ $# -ge 2 ]; do
    if [ $first -eq 1 ]; then
      first=0
    else
      printf ','
    fi
    printf '"%s":%s' "$1" "$2"
    shift 2
  done
  printf '}'
}

forEachJSONListItem () {
  # Usage: <command> [<arg> ...] < json
  # <command> is receives each item in json as input.
  # If <command> exit status is non-zero, enumeration stops.
55 56 57 58 59
  # shellcheck disable=SC2039
  local list index
  list="$(cat)"
  for index in $(seq 0 $(($(printf "%s\\n" "$list" | jq length) - 1))); do
    printf "%s\\n" "$list" | jq ".[$index]" | "$@" || return $?
60 61 62 63 64 65
  done
}

wrap () {
  # Wrap payload in a format suitable for caucase and sign it
  # Usage: wrap <key file> <digest> < payload > wrapped
66 67 68
  # shellcheck disable=SC2039
  local digest="$2" payload
  payload="$(cat)"
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  # Note: $() looses trailing newlines, so payload should not need to end with
  # any newline.
  pairs2obj \
    "digest" "$(printf "%s" "$digest" | str2json)" \
    "payload" "$(printf "%s" "$payload" | str2json)" \
    "signature" "$(
      printf "%s%s " "$payload" "$digest" \
      | openssl dgst \
        -"$digest" \
        -binary \
        -sign "$1" \
        -sigopt rsa_padding_mode:pss \
        -sigopt rsa_pss_saltlen:-2 \
        -sigopt digest:"$digest" \
      | base64 -w 0 \
      | str2json
    )"
}

nullWrap () {
  # Wrap payload in a format suitable for caucase without signing it
  # Usage: nullWrap < payload > wrapped
  pairs2obj digest null payload "$(str2json)"
}

unwrap () {
  # Usage: unwrap <command> [...] < wrapped > payload
  # <command> must output the x509 certificate to use to verify the signature.
  # It receives the payload being unwrapped.
98 99 100
  # shellcheck disable=SC2039
  local wrapped status json_digest digest signature_file payload pubkey_file
  wrapped="$(cat)"
101

102
  json_digest="$(printf "%s\\n" "$wrapped" | jq .digest)"
103 104 105 106
  if [ "$json_digest" = "null" ]; then
    return 1
  fi
  digest="$(
107
    printf "%s\\n" "$json_digest" | jq --raw-output ascii_downcase
108 109 110 111 112 113 114 115 116 117 118 119 120
  )"
  case "$digest" in
    sha256|sha384|sha512)
    ;;
    *)
      # Note: printing json-encoded digest so it is safe to print
      # (especially, ESC is encoded as \u001b, avoiding shell escape code
      # injections).
      echo "Unhandled digest: $json_digest" >&2
      return 1
    ;;
  esac
  signature_file="$(mktemp --suffix=unwrap.sig)"
121
  printf "%s\\n" "$wrapped" | jq --raw-output .signature | \
122
    base64 -d > "$signature_file"
123
  payload="$(printf "%s\\n" "$wrapped" | jq --raw-output .payload)"
124
  pubkey_file="$(mktemp --suffix=unwrap.pub)"
125
  if printf "%s\\n" "$payload" "$@" | openssl x509 -pubkey -noout > "$pubkey_file"; then
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    printf "%s%s " "$payload" "$digest" \
    | openssl dgst \
      -"$digest" \
      -verify "$pubkey_file" \
      -sigopt rsa_padding_mode:pss \
      -sigopt rsa_pss_saltlen:-2 \
      -sigopt digest:"$digest" \
      -signature "$signature_file" > /dev/null
    status=$?
  else
    status=2
  fi
  rm "$signature_file" "$pubkey_file"
  test $status -eq 0 && printf "%s" "$payload"
  return $status
}

nullUnwrap () {
  # Usage: nullUnwrap < wrapped > payload
145 146 147 148
  # shellcheck disable=SC2039
  local wrapped
  wrapped="$(cat)"
  if [ "$(printf "%s\\n" "$wrapped" | jq '.digest')" != "null" ]; then
149 150
    return 1
  fi
151
  printf "%s\\n" "$wrapped" | jq .payload
152 153 154 155 156
}

writeCertKey () {
  # Write given certificate and key to file(s).
  # Usage: writeCertKey <crt data> <crt path> <key data> <key path>
157
  # shellcheck disable=SC2039
158 159 160 161 162 163 164
  local crt_path="$1" crt_data="$2" key_path="$3" key_data="$4" need_chmod
  test ! -e "$key_path"
  need_chmod=$?
  # Empty both files first, as they may be the same.
  : > "$crt_path"
  : > "$key_path"
  test $need_chmod -eq 0 && chmod go= "$key_path"
165 166
  printf "%s\\n" "$key_data" >> "$key_path"
  printf "%s\\n" "$crt_data" >> "$crt_path"
167 168 169 170 171 172 173 174
}

alias CURL='curl --silent'
alias PUT='CURL --upload-file -'

PUTNoOut () {
  # For when PUT does not provide a response body, so the only way to check
  # for issues is checking HTTP status.
175
  # shellcheck disable=SC2039
176
  local result
177
  if result="$(
178
    PUT \
179
      --write-out "\\n%{http_code}\\n" \
180
      "$@"
181 182 183
  )"; then
    :
  else
184 185
    return 3
  fi
186
  case "$(printf "%s\\n" "$result" | tail -n 1)" in
187 188 189 190
    2?? )
      return 0
    ;;
    401 )
191
      printf "Unauthorized\\n" >&2
192 193 194
      return 2
    ;;
    409 )
195
      printf "Found\\n" >&2
196 197 198
      return 4
    ;;
    * )
199
      printf "%s\\n" "$result" | head -n -1 >&2
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
      return 1
    ;;
  esac
}

_matchCertificateBoundary () {
  test "$1" = "-----END CERTIFICATE-----"
  return $?
}

_matchPrivateKeyBoundary () {
  case "$1" in
    "-----END PRIVATE KEY-----" | "-----END RSA PRIVATE KEY-----")
      return 0
    ;;
  esac
  return 1
}

_forEachPEM () {
  # Iterate over components of a PEM file, piping each to <command>
  # Usage: _forEachPEM <type tester> <command> [<arg> ...] < pem
  # <type tester> is called with the end boundary as argument
  # <command> receives each matching PEM element as input.
  # If <command> exit status is non-zero, enumeration stops.
225
  # shellcheck disable=SC2039
226 227 228 229 230 231
  local tester="$1" current=""
  shift
  while IFS= read -r line; do
    if [ -z "$current" ]; then
      current="$line"
    else
232
      current="$(printf "%s\\n%s" "$current" "$line")"
233 234 235 236
    fi
    case "$line" in
      "-----END "*"-----")
        if "$tester" "$line"; then
237
          printf "%s\\n" "$current" | "$@" || return $?
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        fi
        current=""
        ;;
    esac
  done
}

alias forEachCertificate="_forEachPEM _matchCertificateBoundary"
# Iterate over certificate of a PEM file, piping each to <command>
# Usage: _forEachPEM <command> [<arg> ...] < pem

alias forEachPrivateKey="_forEachPEM _matchPrivateKeyBoundary"
# Iterate over private key of a PEM file, piping each to <command>
# Usage: _forEachPEM <command> [<arg> ...] < pem

alias pem2fingerprint="openssl x509 -fingerprint -noout"

pemFingerprintIs () {
  # Usage: pemFingerprintIs <fingerprint> < certificate
  # Return 1 when certificate's fingerprint matches argument
  test "$1" = "$(pem2fingerprint)" && return 1
}

expiresBefore () {
  # Tests whether certificate is expired at given date
  # Usage: expiresBefore <date> < certificate > certificate
  # <date> must be a unix timestamp (date +%s)
265 266 267
  # shellcheck disable=SC2039
  local enddate
  enddate="$(openssl x509 -enddate -noout | sed "s/^[^=]*=//")"
268 269 270 271 272 273 274 275 276
  test $? -ne 0 && return 1
  test "$(date --date="$enddate" +%s)" -lt "$1"
  return $?
}

printIfExpiresAfter () {
  # Print certificate if it expires after given date
  # Usage: printIfExpiresAfter <date> < certificate > certificate
  # <date> must be a unix timestamp (date +%s)
277 278 279 280
  # shellcheck disable=SC2039
  local crt
  crt="$(cat)"
  printf "%s\\n" "$crt" | expiresBefore "$1" || printf "%s\\n" "$crt"
281 282 283 284 285 286 287
}

appendValidCA () {
  # TODO: test
  # Append CA to given file if it is signed by a CA we know of already.
  # Usage: _appendValidCA <ca path> < json
  # Appends valid certificates to the file at <ca path>
288
  # shellcheck disable=SC2039
289
  local ca="$1" payload cert
290 291 292
  if payload=$(unwrap jq --raw-output .old_pem); then
    :
  else
293 294 295
    printf "Bad signature, something is very wrong" >&2
    return 1
  fi
296 297
  cert="$(printf "%s\\n" "$payload" | jq --raw-output .old_pem)"
  forEachCertificate \
298
    pemFingerprintIs \
299
    "$(printf "%s\\n" "$cert" | pem2fingerprint)" < "$ca"
300
  if [ $? -eq 1 ]; then
301
    printf "%s\\n" "$cert" >> "$ca"
302 303 304 305 306 307 308 309
  fi
}

checkCertificateMatchesKey () {
  # Usage: checkCertificateMatchesKey <crt> <key>
  # Returns 0 if certificate's public key matches private key's public key,
  # 1 otherwise.
  test "$(
310
    printf "%s\\n" "$1" | openssl x509 -modulus -noout | sed "s/^Modulus=//"
311 312 313 314 315 316 317
  )" = "$(
    echo "$2" | openssl rsa -modulus -noout | sed "s/^Modulus=//"
  )"
  return $?
}

checkDeps () {
318
  # shellcheck disable=SC2039
319 320 321 322 323 324 325 326 327 328 329
  local missingdeps="" dep
  # Expected builtins & keywords:
  #   alias local if then else elif fi for in do done case esac return [ test
  #   shift set
  for dep in jq openssl printf echo curl sed base64 cat date; do
    command -v $dep > /dev/null || missingdeps="$missingdeps $dep"
  done
  if [ -n "$missingdeps" ]; then
    echo "Missing dependencies: $missingdeps" >&2
    return 1
  fi
330
  if [ ! -r /dev/null ] || [ ! -w /dev/null ]; then
331 332 333 334 335 336 337 338 339 340 341 342 343
    echo "Cannot read from & write to /dev/null" >&2
    return 1
  fi
}

renewCertificate () {
  # Usage: <url> <old key> <new key len> <new crt> <new key> < old crt
  # <new key> and <new crt> are created.
  # Given paths may be identical in any combination.
  # If "new" path are the same as "old" paths, old content will be overwritten
  # on success.
  # If created, key file permissions will be set so group and other have no
  # access.
344
  # shellcheck disable=SC2039
345
  local url="$1" oldkey="$2" bits="$3" newcrt="$4" newkey="$5" emptyreqcnf
346
  # shellcheck disable=SC2039
347 348
  local newkeydata newcrtdata

349 350 351 352 353 354 355 356 357 358 359 360 361
  emptyreqcnf="$(mktemp --suffix=emptyreq.cnf)"
  cat > "$emptyreqcnf" << EOF
[ req ]
distinguished_name = req_distinguished_name
string_mask = utf8only
req_extensions = v3_req

[ req_distinguished_name ]
CN = Common Name

[ v3_req ]
basicConstraints = CA:FALSE
EOF
362 363 364
  newkeydata="$(
    openssl genpkey \
      -algorithm rsa \
365
      -pkeyopt "rsa_keygen_bits:$bits" \
366 367
      -outform PEM 2> /dev/null
  )"
368
  if newcrtdata="$(
369 370 371 372 373 374 375 376
    pairs2obj \
      "crt_pem" "$(str2json)" \
      "renew_csr_pem" "$(
        echo "$newkeydata" \
        | openssl req \
          -new \
          -key - \
          -subj "/CN=dummy" \
377
          -config "$emptyreqcnf" \
378 379 380 381 382 383
        | str2json
      )" \
    | wrap "$oldkey" "sha256" \
    | PUT --insecure \
      --header "Content-Type: application/json" \
      "$url/crt/renew/"
384
  )"; then
385
    if [ \
386
      "x$(printf "%s\\n" "$newcrtdata" | head -n 1)" \
387 388 389 390 391
      = \
      "x-----BEGIN CERTIFICATE-----" \
    ]; then
      if checkCertificateMatchesKey "$newcrtdata" "$newkeydata"; then
        writeCertKey "$newcrt" "$newcrtdata" "$newkey" "$newkeydata"
392
        rm "$emptyreqcnf"
393 394
        return 0
      fi
395
      printf "Certificate does not match private key\\n" >&2
396 397 398 399
    else
      printf "%s" "$newcrtdata" >&2
    fi
  fi
400
  rm "$emptyreqcnf"
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  return 1
}

revokeCertificate () {
  # Usage: <url> <key_path> < crt
  pairs2obj "revoke_crt_pem" "$(str2json)" \
  | wrap "$2" "sha256" \
  | PUTNoOut \
    --header "Content-Type: application/json" \
    --insecure \
    "$1/crt/revoke/"
  return $?
}

revokeCRTWithoutKey () {
  # Usage: <url> <ca> <user crt> < crt
  pairs2obj "revoke_crt_pem" "$(str2json)" \
  | nullWrap \
  | PUTNoOut \
    --cert "$3" \
    --header "Content-Type: application/json" \
    --cacert "$2" \
    "$1/crt/revoke/"
  return $?
}

revokeSerial () {
  # Usage: <url> <ca> <user crt> <serial>
  pairs2obj "revoke_serial" "$4" \
  | nullWrap \
  | PUTNoOut \
    --cert "$3" \
    --header "Content-Type: application/json" \
    --cacert "$2" \
    "$1/crt/revoke/"
  return $?
}

updateCACertificate () {
  # Usage: <url> <cas_ca> <ca>
441
  # shellcheck disable=SC2039
442 443 444 445 446 447 448 449 450 451 452
  local url="$1" cas_ca="$2" ca="$3" future_ca status orig_ca valid_ca
  orig_ca="$(
    if [ -e "$ca" ]; then
      cat "$ca"
    else
      CURL --insecure "$url/crt/ca.crt.pem"
    fi
  )"
  status=$?
  test $status -ne 0 && return 1
  valid_ca="$(
453
    printf "%s\\n" "$orig_ca" \
454 455 456 457
    | forEachCertificate printIfExpiresAfter "$(date +%s)"
  )"
  status=$?
  test $status -ne 0 && return 1
458
  printf "%s\\n" "$valid_ca" > "$ca"
459 460 461 462 463
  if [ ! -r "$cas_ca" ]; then
    # Should never be reached, as this function should be run once with
    # cas_ca == ca (to update CAS' CA), in which case cas_ca exists by this
    # point. CAU's CA should only be updated after, and by that point CAS' CA
    # already exists.
464
    printf "%s does not exist\\n" "$cas_ca"
465 466 467 468 469
    return 1
  fi
  future_ca="$(CURL --cacert "$cas_ca" "$url/crt/ca.crt.json")"
  status=$?
  test $status -ne 0 && return 1
470
  printf "%s\\n" "$future_ca" | forEachJSONListItem appendValidCA "$ca"
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
}

getCertificateRevocationList () {
  # Usage: <url> <ca>
  CURL --insecure "$1/crl" | openssl crl -CAfile "$2" 2> /dev/null
  return $?
}

getCertificateSigningRequest () {
  # Usage: <url> <csr id>
  CURL --insecure "$1/csr/$2"
  return $?
}

getPendingCertificateRequestList () {
  # Usage: <url> <ca> <user crt>
  CURL --cert "$3" --cacert "$2" "$1/csr"
  return $?
}

createCertificateSigningRequest () {
  # Usage: <url> < csr > csr id
  PUT --insecure --header "Content-Type: application/pkcs10" "$1/csr" \
    --dump-header - | while IFS= read -r line; do
    # Note: $line contains trailing \r, which will not get stripped by $().
    # So strip it with sed instead.
    case "$line" in
      "Location: "*)
499
        printf "%s\\n" "$line" | sed "s/^Location: \\(\\S*\\).*/\\1/"
500 501 502 503 504 505 506 507 508 509 510 511 512 513
      ;;
    esac
  done
  return $?
}

deletePendingCertificateRequest () {
  # Usage: <url> <ca> <user crt> <csr id>
  CURL --request DELETE --cert "$3" --cacert "$2" "$1/csr/$4"
  return $?
}

getCertificate () {
  # Usage: <url> <csr id>
514
  # shellcheck disable=SC2039
515 516 517 518
  local status
  CURL --fail --insecure "$1/crt/$2"
  status=$?
  if [ $status -ne 0 ]; then
519
    printf "Certificate %s not found (not signed yet or rejected)\\n" "$2" >&2
520 521 522 523 524 525
    return 1
  fi
}

createCertificate () {
  # Usage: <url> <ca> <user crt> <csr id>
526
  # shellcheck disable=SC2039
527 528 529 530
  local result
  PUTNoOut --cert "$3" --cacert "$2" "$1/crt/$4" < /dev/null
  result=$?
  if [ $result -ne 0 ]; then
531
    printf "%s: No such pending signing request\\n" "$4" >&2
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  fi
  return $result
}

createCertificateWith () {
  # Usage: <url> <ca> <user crt> <csr id> < csr
  PUTNoOut --cert "$3" --cacert "$2" \
    --header "Content-Type: application/pkcs10" "$1/crt/$4"
  return $?
}

if [ $# -ne 0 ]; then
  _usage () {
    cat << EOF
Usage: $0 <caucase url> [--ca-crt PATH] --ca-url URL [...]

caucase client
Certificate Authority for Users, Certificate Authority for SErvices

Arguments are taken into account in given order, options overriding any
previous occurrence and actions being executed in given order.

General options
--ca-url URL
  Required. Base URL of the caucase service to access.
  Ex: http://caucase.example.com:8000
--ca-crt PATH
  Default: cas.crt.pem
  Path of the service CA certificate file. Updated on each run.
--user-ca-crt PATH
  Default: cau.crt.pem
  Path of the user CA certificate file. See --update-user .
--crl PATH
  Default: cas.crl.pem
  Path of the service revocation list. Updated on each run.
--user-crl PATH
  Default: cau.crl.pem
  Path of the service revocation list. See --update-user .
--threshold DAYS
  Default: 31
  Skip renewal when certificate is still valid for this many days.
  See --renew-crt .
--key-len BITS
  Default: 2048
  Size of the private key to generate. See --renew-crt .
577 578 579
--user-key PATH
  A file containing a private key and corresponding certificate, to
  authenticate as a caucase user.
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
--mode {service|user}
  Default: service
  Caucase personality to query.

Anonymous actions
--send-csr PATH
  Submit given certificate signing request, and print the identifier under which
  the server accepted it (see --get-crt and --get-csr).
--get-crt CSR_ID CRT_PATH
  Retrieve the certificate corresponding to the signing request with identifier
  CSR_ID, and store it in CRT_PATH.
  If CRT_PATH exists and contains a private key, verifies it matches received
  certificate, and exit before modifying the file if it does not match.
  See also --get-csr .
--revoke-crt CRT_PATH KEY_PATH
  Revoke the certificate at CRT_PATH. Revocation request must be signed with
  corresponding private key, read from KEY_PATH.
  Both paths may point at the same file.
--renew-crt CRT_PATH KEY_PATH
  Renew the certificate from CRT_PATH with a new private key. Upon success,
  write resulting certificate in CRT_PATH and key in KEY_PATH.
  Both paths may point at the same file.
--get-csr CSR_ID CSR_PATH
  Retrieve the signing request with identifier CSR_ID, and store it in CSR_PATH.
  Allows checking whether a signature request is still pending if --get-crt
  failed, or if it has been rejected.
--update-user
  In addition to updating CA certificate and revocation list for service more,
  also update the equivalents for user mode. You should not need this.

Authenticated actions
611
These options require --user-key .
612 613 614 615 616 617 618
--list-csr
  List pending certificate signing requests.
--sign-csr CSR_ID
  Sign the pending request with identifier CSR_ID.
--sign-csr-with CSR_ID CSR_PATH
  Sign the pending request with identifier CSR_ID, replacing its extensions with
  the ones from CSR_PATH.
619
--reject-csr
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  Reject pending request with identifier CSR_ID.
--revoke-other-crt CRT_PATH
  Revoke certificate read from CRT_PATH, without requiring access to its private
  key.
--revoke-serial SERIAL
  Revoke certificate with given serial. When not even the original certificate
  is available for revocation.

Special actions
--help
  Display this help and exit.
EOF
  }

  _argUsage () {
635
    printf "%s: %s\\n" "$arg" "$1" >&2
636 637 638 639 640
    _usage >&2
  }

  _needArg () {
    if [ "$argc" -lt "$1" ]; then
641
      printf "%s\\n" "$arg needs $1 arguments" >&2
642 643 644 645 646 647 648
      _usage >&2
      return 1
    fi
  }

  _needURLAndArg () {
    if [ -z "$ca_anon_url" ]; then
649
      printf "%s\\n" "--ca-url must be provided before $arg" >&2
650 651 652 653 654 655 656
      return 1
    fi
    _needArg "$1" || return 1
  }

  _needAuthURLAndArg () {
    if [ -z "$user_key" ]; then
657
      printf "%s\\n" "--user-key must be provided before $arg" >&2
658 659 660 661 662 663 664
      return 1
    fi
    _needURLAndArg "$1" || return 1
  }

  _checkCertficateMatchesOneKey () {
    # Called from _main, sets global "key_found".
665
    test "$key_found" -ne 0 && return 2
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    key_found=1
    checkCertificateMatchesKey "$1" "$(cat)" || return 1
  }

  _printOneKey () {
    # Called from _main, sets global "key_found".
    if [ $key_found -ne 0 ]; then
      _argUsage "Multiple private keys"
      return 1
    fi
    key_found=1
    cat
  }

  _printOneCert () {
    # Called indirectly from _main, sets global "crt_found".
682
    if [ "$crt_found" -ne 0 ]; then
683 684 685 686 687 688 689 690 691
      _argUsage "Multiple certificates"
      return 1
    fi
    crt_found=1
    cat
  }

  _printOneMatchingCert () {
    # Called indirectly from _main, sets global "crt_found".
692 693 694
    # shellcheck disable=SC2039
    local crt
    crt="$(cat)"
695 696 697 698 699
    if [ $crt_found -ne 0 ]; then
      _argUsage "Multiple certificates"
      return 1
    fi
    crt_found=1
700
    checkCertificateMatchesKey "$crt" "$1" && printf "%s\\n" "$crt"
701 702 703 704 705
  }

  _matchOneKeyAndPrintOneMatchingCert () {
    # Usage: _matchOneKeyAndPrintOneMatchingCert <crt path> <key path>
    # Sets globals "crt_found" and "key_found"
706
    # shellcheck disable=SC2039
707 708 709 710 711 712 713 714 715 716 717 718 719
    local crt
    key_found=0
    key="$(forEachPrivateKey _printOneKey < "$2")"
    status=$?
    test $status -ne 0 && return $status
    crt_found=0
    crt="$(forEachCertificate _printOneMatchingCert "$key" < "$1")"
    status=$?
    test $status -ne 0 && return $status
    if [ -z "$crt" ]; then
      _argUsage "No certificate matches private key"
      return 1
    fi
720
    printf "%s\\n" "$crt"
721 722 723
  }

  _printPendingCSR () {
724 725 726 727 728 729
    # shellcheck disable=SC2039
    local json
    json="$(cat)"
    printf "%20s | %s\\n" \
      "$(printf "%s\\n" "$json" | jq --raw-output .id)" \
      "$(printf "%s\\n" "$json" | jq --raw-output .csr \
730 731 732 733 734 735
        | openssl req -subject -noout | sed "s/^subject=//")"
  }

  _main() {
    checkDeps || return 1

736
    # shellcheck disable=SC2039
737 738 739 740 741 742 743 744 745 746 747 748 749 750
    local ca_anon_url="" \
      ca_auth_url \
      mode="service" \
      mode_path="cas" \
      cas_ca="cas.crt.pem" \
      cau_ca="cau.crt.pem" \
      cas_crl="cas.crl.pem" \
      cau_crl="cau.crl.pem" \
      key_len=2048 \
      update_user=0 \
      user_key="" \
      threshold=31 \
      status arg argc \
      ca_netloc ca_address ca_port ca_path \
751
      csr_id csr csr_path crl crt crt_path crt_dir key_path key serial \
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
      csr_list_json

    while test $# -gt 0; do
      arg="$1"
      shift
      argc=$#
      case "$arg" in
        --help)
          _usage
          return
        ;;
        --ca-url)
          _needArg 1 || return 1
          ca_anon_url="$1"
          shift
          case "$ca_anon_url" in
            https://*)
              ca_auth_url="$ca_anon_url"
            ;;
            http://*)
              ca_netloc="$(
773
                printf "%s\\n" "$ca_anon_url" | sed "s!^http://\\([^/?#]*\\).*!\\1!"
774 775
              )"
              ca_path="$(
776
                printf "%s\\n" "$ca_anon_url" | sed "s!^http://[^/?#]*!!"
777 778 779 780
              )"
              ca_port=80
              # Note: too bad there is no portable case fall-through...
              case "$ca_netloc" in
781
                *\]:*)
782 783
                  # Bracket-enclosed address, which may contain colons
                  ca_address="$(
784
                    printf "%s\\n" "$ca_netloc" | sed "s!^\\(.*\\]\\).*!\\1!"
785 786
                  )"
                  ca_port="$(
787
                    printf "%s\\n" "$ca_netloc" | sed "s!.*\\]:!!"
788 789
                  )"
                ;;
790
                *\]*)
791 792
                  # Bracket-enclosed address, which may contain colons
                  ca_address="$(
793
                    printf "%s\\n" "$ca_netloc" | sed "s!^\\(.*\\]\\).*!\\1!"
794 795 796 797 798
                  )"
                ;;
                *:*)
                  # No bracket-encosed address, rely on colon
                  ca_address="$(
799
                    printf "%s\\n" "$ca_netloc" | sed "s!^\\([^:]*\\).*!\\1!"
800 801
                  )"
                  ca_port="$(
802
                    printf "%s\\n" "$ca_netloc" | sed "s!^[^:]*:!!"
803 804 805 806 807
                  )"
                ;;
                *)
                  # No bracket-encosed address, rely on colon
                  ca_address="$(
808
                    printf "%s\\n" "$ca_netloc" | sed "s!^\\([^:]*\\).*!\\1!"
809 810 811 812 813 814
                  )"
                ;;
              esac
              if [ "$ca_port" -eq 80 ]; then
                ca_port=""
              else
815
                ca_port=":$((ca_port + 1))"
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
              fi
              ca_auth_url="https://${ca_address}${ca_port}${ca_path}"
            ;;
            *)
              _argUsage "Unrecognised URL scheme"
              return 1
            ;;
          esac
          updateCACertificate "${ca_anon_url}/cas" "$cas_ca" "$cas_ca"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --ca-crt)
          _needArg 1 || return 1
          if [ -n "$ca_anon_url" ]; then
            _argUsage "$ARG must be provided once, before --ca-url"
            return 1
          fi
          cas_ca="$1"
          shift
        ;;
        --user-ca-crt)
          _needArg 1 || return 1
          cau_ca="$1"
          shift
        ;;
        --crl)
          _needArg 1 || return 1
          cas_crl="$1"
          shift
        ;;
        --user-crl)
          _needArg 1 || return 1
          cau_crl="$1"
          shift
        ;;
        --threshold)
          _needArg 1 || return 1
          threshold="$1"
          shift
856 857 858
          if [ "$threshold" -eq "$threshold" ] 2> /dev/null ; then
            :
          else
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
            _argUsage "Argument must be an integer"
            return 1
          fi
        ;;
        --key-len)
          _needArg 1 || return 1
          # XXX: check key length ?
          key_len="$1"
          shift
        ;;
        --user-key)
          _needArg 1 || return 1
          user_key="$1"
          shift
        ;;
        --mode)
          _needArg 1 || return 1
          mode="$1"
          shift
          case "$mode" in
            service)
              mode_path="cas"
            ;;
            user)
              mode_path="cau"
            ;;
            *)
              _argUsage "Invalid mode"
              return 1
            ;;
          esac
        ;;
        # Anonymous actions
        --send-csr)
          _needURLAndArg 1 || return 1
          if [ ! -r "$1" ]; then
            _argUsage "$1 is not readable"
            return 1
          fi
          csr_id="$(
            createCertificateSigningRequest "${ca_anon_url}/${mode_path}" < "$1"
          )"
          status=$?
          test $status -ne 0 && return $status
903
          printf "%s %s\\n" "$csr_id" "$1"
904 905 906 907 908 909 910
          shift
        ;;
        --get-crt)
          _needURLAndArg 2 || return 1
          csr_id="$1"
          crt_path="$2"
          shift 2
911 912 913 914 915 916 917 918
          crt_dir="$(dirname "$crt_path")"
          if [ "x$crt_path" = "x-" ]; then # stdin & stdout
            :
          elif [ -w "$crt_path" ] && [ -r "$crt_path" ]; then # existing file
            :
          elif [ -w "$crt_dir" ] && [ -x "$crt_dir" ]; then # containing directory
            :
          else
919 920 921 922 923 924 925 926
            _argUsage \
              "$crt_path is not writeable (and/or not readable if exists)"
            return 1
          fi
          crt="$(getCertificate "${ca_anon_url}/${mode_path}" "$csr_id")"
          status=$?
          test $status -ne 0 && return $status
          if [ "$crt_path" = "-" ]; then
927
            printf "%s\\n" "$crt"
928 929 930 931 932 933 934 935 936 937 938 939 940 941
          else
            if [ -e "$crt_path" ]; then
              key_found=0
              forEachPrivateKey _checkCertficateMatchesOneKey "$crt" \
                < "$crt_path"
              status=$?
              if [ $status -eq 1 ]; then
                _argUsage "Certificate does not match private key"
                return 1
              elif [ $status -eq 2 ]; then
                _argUsage "Multiple private keys"
                return 1
              fi
            fi
942
            printf "%s\\n" "$crt" >> "$crt_path"
943 944 945 946 947 948 949 950 951 952
          fi
        ;;
        --revoke-crt)
          _needURLAndArg 2 || return 1
          crt_path="$1"
          key_path="$2"
          shift 2
          crt="$(_matchOneKeyAndPrintOneMatchingCert "$crt_path" "$key_path")"
          status=$?
          test $status -ne 0 && return $status
953
          printf "%s\\n" "$crt" \
954 955 956 957 958 959 960 961 962 963 964 965
          | revokeCertificate "${ca_anon_url}/${mode_path}" "$key_path"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --renew-crt)
          _needURLAndArg 2 || return 1
          crt_path="$1"
          key_path="$2"
          shift 2
          crt="$(_matchOneKeyAndPrintOneMatchingCert "$crt_path" "$key_path")"
          status=$?
          test $status -ne 0 && return $status
966
          if printf "%s\\n" "$crt" \
967
          | expiresBefore "$(date --date="$threshold days" +%s)"; then
968
            printf "%s\\n" "$crt" \
969 970 971 972 973 974 975
            | renewCertificate "${ca_anon_url}/${mode_path}" \
              "$key_path" \
              "$key_len" \
              "$crt_path" "$key_path"
            status=$?
            test $status -ne 0 && return $status
          else
976
            printf "%s did not reach renew threshold, not renewing\\n" \
977 978 979 980 981 982 983 984 985 986 987 988 989 990
              "$crt_path" >&2
          fi
        ;;
        --get-csr)
          _needURLAndArg 2 || return 1
          csr_id="$1"
          csr_path="$2"
          shift 2
          csr="$(
            getCertificateSigningRequest "${ca_anon_url}/${mode_path}" "$csr_id"
          )"
          status=$?
          test $status -ne 0 && return $status
          if [ "$csr_path" = "-" ]; then
991
            printf "%s\\n" "$csr"
992
          else
993
            printf "%s\\n" "$csr" > "$csr_path"
994 995 996 997 998 999 1000 1001 1002
          fi
        ;;
        --update-user)
          update_user=1
        ;;

        # Authenticated actions
        --list-csr)
          _needAuthURLAndArg 0 || return 1
1003
          printf "%s\\n" "-- pending $mode CSRs --"
1004
          printf \
1005
            "%20s | subject preview (fetch csr and check full content !)\\n" \
1006 1007 1008 1009 1010 1011 1012 1013
            "csr_id"
          csr_list_json="$(
            getPendingCertificateRequestList "${ca_auth_url}/${mode_path}" \
              "$cas_ca" "$user_key"
          )"
          status=$?
          test $status -ne 0 && return $status
          printf "%s" "$csr_list_json" | forEachJSONListItem _printPendingCSR
1014
          printf "%s\\n" "-- end of pending $mode CSRs --"
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        ;;
        --sign-csr)
          _needAuthURLAndArg 1 || return 1
          csr_id="$1"
          shift
          createCertificate "${ca_auth_url}/${mode_path}" \
            "$cas_ca" "$user_key" "$csr_id"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --sign-csr-with)
          _needAuthURLAndArg 2 || return 1
          csr_id="$1"
          csr="$2"
          shift
          createCertificateWith "${ca_auth_url}/${mode_path}" \
            "$cas_ca" "$user_key" "$csr_id" < "$csr"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --reject-csr)
          _needAuthURLAndArg 1 || return 1
          csr_id="$1"
          shift
          deletePendingCertificateRequest "${ca_auth_url}/${mode_path}" \
            "$cas_ca" "$user_key" "$csr_id"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --revoke-other-crt)
          _needAuthURLAndArg 1 || return 1
          crt_path="$1"
          shift
          crt_found=0
          crt="$(forEachCertificate _printOneCert < "$crt_path")"
          status=$?
          test $status -ne 0 && return $status
1052
          printf "%s\\n" "$crt" | revokeCRTWithoutKey \
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
            "${ca_auth_url}/${mode_path}" "$cas_ca" "$user_key"
          status=$?
          test $status -ne 0 && return $status
        ;;
        --revoke-serial)
          _needAuthURLAndArg 1 || return 1
          serial="$1"
          shift
          revokeSerial "${ca_auth_url}/${mode_path}" \
            "$cas_ca" "$user_key" "$serial"
          status=$?
          test $status -ne 0 && return $status
        ;;

        *)
          _argUsage "Unknown argument"
          return 1
        ;;
      esac
    done
1073 1074
    if [ -n "$ca_anon_url" ] && [ -r "$cas_ca" ]; then
      if crl="$(
1075
        getCertificateRevocationList "${ca_anon_url}/cas" "$cas_ca"
1076 1077
      )"; then
      printf "%s\\n" "$crl" > "$cas_crl"
1078
    else
1079
      printf "Received CAS CRL was not signed by CAS CA certificate, skipping\\n"
1080 1081 1082 1083 1084
    fi
      if [ $update_user -eq 1 ]; then
        updateCACertificate "${ca_anon_url}/cau" "$cas_ca" "$cau_ca"
        status=$?
        test $status -ne 0 && return $status
1085
        if crl="$(
1086
          getCertificateRevocationList "${ca_anon_url}/cau" "$cau_ca"
1087 1088
        )"; then
          printf "%s\\n" "$crl" > "$cau_crl"
1089 1090
        else
          printf \
1091
            "Received CAU CRL was not signed by CAU CA certificate, skipping\\n"
1092 1093 1094 1095 1096 1097
        fi
      fi
    fi
  }
  _main "$@"
fi