Requests Let's Encrypt certificates using a user-supplied DNS hook
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dehydrated 66KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. #!/usr/bin/env bash
  2. # dehydrated by lukas2511
  3. # Source: https://dehydrated.io
  4. #
  5. # This script is licensed under The MIT License (see LICENSE for more information).
  6. set -e
  7. set -u
  8. set -o pipefail
  9. [[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO && set -o NULL_GLOB && set -o noglob
  10. [[ -z "${ZSH_VERSION:-}" ]] && shopt -s nullglob && set -f
  11. umask 077 # paranoid umask, we're creating private keys
  12. # Close weird external file descriptors
  13. exec 3>&-
  14. exec 4>&-
  15. VERSION="0.6.5"
  16. # Find directory in which this script is stored by traversing all symbolic links
  17. SOURCE="${0}"
  18. while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  19. DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  20. SOURCE="$(readlink "$SOURCE")"
  21. [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
  22. done
  23. SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  24. BASEDIR="${SCRIPTDIR}"
  25. ORIGARGS="$@"
  26. # Create (identifiable) temporary files
  27. _mktemp() {
  28. # shellcheck disable=SC2068
  29. mktemp ${@:-} "${TMPDIR:-/tmp}/dehydrated-XXXXXX"
  30. }
  31. # Check for script dependencies
  32. check_dependencies() {
  33. # just execute some dummy and/or version commands to see if required tools exist and are actually usable
  34. "${OPENSSL}" version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
  35. _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
  36. command -v grep > /dev/null 2>&1 || _exiterr "This script requires grep."
  37. command -v mktemp > /dev/null 2>&1 || _exiterr "This script requires mktemp."
  38. command -v diff > /dev/null 2>&1 || _exiterr "This script requires diff."
  39. # curl returns with an error code in some ancient versions so we have to catch that
  40. set +e
  41. CURL_VERSION="$(curl -V 2>&1 | head -n1 | awk '{print $2}')"
  42. retcode="$?"
  43. set -e
  44. if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
  45. _exiterr "This script requires curl."
  46. fi
  47. }
  48. store_configvars() {
  49. __KEY_ALGO="${KEY_ALGO}"
  50. __OCSP_MUST_STAPLE="${OCSP_MUST_STAPLE}"
  51. __PRIVATE_KEY_RENEW="${PRIVATE_KEY_RENEW}"
  52. __KEYSIZE="${KEYSIZE}"
  53. __CHALLENGETYPE="${CHALLENGETYPE}"
  54. __HOOK="${HOOK}"
  55. __WELLKNOWN="${WELLKNOWN}"
  56. __HOOK_CHAIN="${HOOK_CHAIN}"
  57. __OPENSSL_CNF="${OPENSSL_CNF}"
  58. __RENEW_DAYS="${RENEW_DAYS}"
  59. __IP_VERSION="${IP_VERSION}"
  60. }
  61. reset_configvars() {
  62. KEY_ALGO="${__KEY_ALGO}"
  63. OCSP_MUST_STAPLE="${__OCSP_MUST_STAPLE}"
  64. PRIVATE_KEY_RENEW="${__PRIVATE_KEY_RENEW}"
  65. KEYSIZE="${__KEYSIZE}"
  66. CHALLENGETYPE="${__CHALLENGETYPE}"
  67. HOOK="${__HOOK}"
  68. WELLKNOWN="${__WELLKNOWN}"
  69. HOOK_CHAIN="${__HOOK_CHAIN}"
  70. OPENSSL_CNF="${__OPENSSL_CNF}"
  71. RENEW_DAYS="${__RENEW_DAYS}"
  72. IP_VERSION="${__IP_VERSION}"
  73. }
  74. hookscript_bricker_hook() {
  75. # Hook scripts should ignore any hooks they don't know.
  76. # Calling a random hook to make this clear to the hook script authors...
  77. if [[ -n "${HOOK}" ]]; then
  78. "${HOOK}" "this_hookscript_is_broken__dehydrated_is_working_fine__please_ignore_unknown_hooks_in_your_script"
  79. fi
  80. }
  81. # verify configuration values
  82. verify_config() {
  83. [[ "${CHALLENGETYPE}" == "http-01" || "${CHALLENGETYPE}" == "dns-01" || "${CHALLENGETYPE}" == "tls-alpn-01" ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... cannot continue."
  84. if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
  85. _exiterr "Challenge type dns-01 needs a hook script for deployment... cannot continue."
  86. fi
  87. if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" && ! "${COMMAND:-}" = "register" ]]; then
  88. _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
  89. fi
  90. [[ "${KEY_ALGO}" == "rsa" || "${KEY_ALGO}" == "prime256v1" || "${KEY_ALGO}" == "secp384r1" ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... cannot continue."
  91. if [[ -n "${IP_VERSION}" ]]; then
  92. [[ "${IP_VERSION}" = "4" || "${IP_VERSION}" = "6" ]] || _exiterr "Unknown IP version ${IP_VERSION}... cannot continue."
  93. fi
  94. [[ "${API}" == "auto" || "${API}" == "1" || "${API}" == "2" ]] || _exiterr "Unsupported API version defined in config: ${API}"
  95. [[ "${OCSP_DAYS}" =~ ^[0-9]+$ ]] || _exiterr "OCSP_DAYS must be a number"
  96. }
  97. # Setup default config values, search for and load configuration files
  98. load_config() {
  99. # Check for config in various locations
  100. if [[ -z "${CONFIG:-}" ]]; then
  101. for check_config in "/etc/dehydrated" "/usr/local/etc/dehydrated" "${PWD}" "${SCRIPTDIR}"; do
  102. if [[ -f "${check_config}/config" ]]; then
  103. BASEDIR="${check_config}"
  104. CONFIG="${check_config}/config"
  105. break
  106. fi
  107. done
  108. fi
  109. # Default values
  110. CA="https://acme-v02.api.letsencrypt.org/directory"
  111. OLDCA=
  112. CERTDIR=
  113. ALPNCERTDIR=
  114. ACCOUNTDIR=
  115. CHALLENGETYPE="http-01"
  116. CONFIG_D=
  117. CURL_OPTS=
  118. DOMAINS_D=
  119. DOMAINS_TXT=
  120. HOOK=
  121. HOOK_CHAIN="no"
  122. RENEW_DAYS="30"
  123. KEYSIZE="4096"
  124. WELLKNOWN=
  125. PRIVATE_KEY_RENEW="yes"
  126. PRIVATE_KEY_ROLLOVER="no"
  127. KEY_ALGO=rsa
  128. OPENSSL=openssl
  129. OPENSSL_CNF=
  130. CONTACT_EMAIL=
  131. LOCKFILE=
  132. OCSP_MUST_STAPLE="no"
  133. OCSP_FETCH="no"
  134. OCSP_DAYS=5
  135. IP_VERSION=
  136. CHAINCACHE=
  137. AUTO_CLEANUP="no"
  138. DEHYDRATED_USER=
  139. DEHYDRATED_GROUP=
  140. API="auto"
  141. if [[ -z "${CONFIG:-}" ]]; then
  142. echo "#" >&2
  143. echo "# !! WARNING !! No main config file found, using default config!" >&2
  144. echo "#" >&2
  145. elif [[ -f "${CONFIG}" ]]; then
  146. echo "# INFO: Using main config file ${CONFIG}"
  147. BASEDIR="$(dirname "${CONFIG}")"
  148. # shellcheck disable=SC1090
  149. . "${CONFIG}"
  150. else
  151. _exiterr "Specified config file doesn't exist."
  152. fi
  153. if [[ -n "${CONFIG_D}" ]]; then
  154. if [[ ! -d "${CONFIG_D}" ]]; then
  155. _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory."
  156. fi
  157. # Allow globbing
  158. [[ -n "${ZSH_VERSION:-}" ]] && set +o noglob || set +f
  159. for check_config_d in "${CONFIG_D}"/*.sh; do
  160. if [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
  161. echo "# INFO: Using additional config file ${check_config_d}"
  162. # shellcheck disable=SC1090
  163. . "${check_config_d}"
  164. else
  165. _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all."
  166. fi
  167. done
  168. # Disable globbing
  169. [[ -n "${ZSH_VERSION:-}" ]] && set -o noglob || set -f
  170. fi
  171. # Check if we are running & are allowed to run as root
  172. if [[ -n "$DEHYDRATED_USER" ]]; then
  173. command -v sudo > /dev/null 2>&1 || _exiterr "DEHYDRATED_USER set but sudo not available. Please install sudo."
  174. command -v getent > /dev/null 2>&1 || _exiterr "DEHYDRATED_USER set but getent not available. Please install getent."
  175. TARGET_UID="$(getent passwd "${DEHYDRATED_USER}" | cut -d':' -f3)"
  176. if [[ -z "${DEHYDRATED_GROUP}" ]]; then
  177. if [[ "${EUID}" != "${TARGET_UID}" ]]; then
  178. echo "# INFO: Running $0 as ${DEHYDRATED_USER}"
  179. exec sudo -u "${DEHYDRATED_USER}" "${0}" ${ORIGARGS}
  180. fi
  181. else
  182. TARGET_GID="$(getent group "${DEHYDRATED_GROUP}" | cut -d':' -f3)"
  183. if [[ -z "${EGID:-}" ]]; then
  184. command -v id > /dev/null 2>&1 || _exiterr "DEHYDRATED_GROUP set, don't know current gid and 'id' not available... Please provide 'id' binary."
  185. EGID="$(id -g)"
  186. fi
  187. if [[ "${EUID}" != "${TARGET_UID}" ]] || [[ "${EGID}" != "${TARGET_GID}" ]]; then
  188. echo "# INFO: Running $0 as ${DEHYDRATED_USER}/${DEHYDRATED_GROUP}"
  189. exec sudo -u "${DEHYDRATED_USER}" -g "${DEHYDRATED_GROUP}" "${0}" ${ORIGARGS}
  190. fi
  191. fi
  192. elif [[ -n "${DEHYDRATED_GROUP}" ]]; then
  193. _exiterr "DEHYDRATED_GROUP can only be used in combination with DEHYDRATED_USER."
  194. fi
  195. # Check for missing dependencies
  196. check_dependencies
  197. # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
  198. [[ "$BASEDIR" != "/" ]] && BASEDIR="${BASEDIR%%/}"
  199. # Check BASEDIR and set default variables
  200. [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
  201. if [[ -z "${OLDCA}" ]] && [[ "${CA}" = "https://acme-v02.api.letsencrypt.org/directory" ]]; then
  202. OLDCA="https://acme-v01.api.letsencrypt.org/directory"
  203. fi
  204. # Create new account directory or symlink to account directory from old CA
  205. CAHASH="$(echo "${CA}" | urlbase64)"
  206. [[ -z "${ACCOUNTDIR}" ]] && ACCOUNTDIR="${BASEDIR}/accounts"
  207. if [[ ! -e "${ACCOUNTDIR}/${CAHASH}" ]]; then
  208. OLDCAHASH="$(echo "${OLDCA}" | urlbase64)"
  209. mkdir -p "${ACCOUNTDIR}"
  210. if [[ -n "${OLDCA}" ]] && [[ -e "${ACCOUNTDIR}/${OLDCAHASH}" ]]; then
  211. echo "! Reusing account from ${OLDCA}"
  212. ln -s "${OLDCAHASH}" "${ACCOUNTDIR}/${CAHASH}"
  213. else
  214. mkdir "${ACCOUNTDIR}/${CAHASH}"
  215. fi
  216. fi
  217. [[ -f "${ACCOUNTDIR}/${CAHASH}/config" ]] && . "${ACCOUNTDIR}/${CAHASH}/config"
  218. ACCOUNT_KEY="${ACCOUNTDIR}/${CAHASH}/account_key.pem"
  219. ACCOUNT_KEY_JSON="${ACCOUNTDIR}/${CAHASH}/registration_info.json"
  220. ACCOUNT_ID_JSON="${ACCOUNTDIR}/${CAHASH}/account_id.json"
  221. if [[ -f "${BASEDIR}/private_key.pem" ]] && [[ ! -f "${ACCOUNT_KEY}" ]]; then
  222. echo "! Moving private_key.pem to ${ACCOUNT_KEY}"
  223. mv "${BASEDIR}/private_key.pem" "${ACCOUNT_KEY}"
  224. fi
  225. if [[ -f "${BASEDIR}/private_key.json" ]] && [[ ! -f "${ACCOUNT_KEY_JSON}" ]]; then
  226. echo "! Moving private_key.json to ${ACCOUNT_KEY_JSON}"
  227. mv "${BASEDIR}/private_key.json" "${ACCOUNT_KEY_JSON}"
  228. fi
  229. [[ -z "${CERTDIR}" ]] && CERTDIR="${BASEDIR}/certs"
  230. [[ -z "${ALPNCERTDIR}" ]] && ALPNCERTDIR="${BASEDIR}/alpn-certs"
  231. [[ -z "${CHAINCACHE}" ]] && CHAINCACHE="${BASEDIR}/chains"
  232. [[ -z "${DOMAINS_TXT}" ]] && DOMAINS_TXT="${BASEDIR}/domains.txt"
  233. [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="/var/www/dehydrated"
  234. [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
  235. [[ -z "${OPENSSL_CNF}" ]] && OPENSSL_CNF="$("${OPENSSL}" version -d | cut -d\" -f2)/openssl.cnf"
  236. [[ -n "${PARAM_LOCKFILE_SUFFIX:-}" ]] && LOCKFILE="${LOCKFILE}-${PARAM_LOCKFILE_SUFFIX}"
  237. [[ -n "${PARAM_NO_LOCK:-}" ]] && LOCKFILE=""
  238. [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
  239. [[ -n "${PARAM_CERTDIR:-}" ]] && CERTDIR="${PARAM_CERTDIR}"
  240. [[ -n "${PARAM_ALPNCERTDIR:-}" ]] && ALPNCERTDIR="${PARAM_ALPNCERTDIR}"
  241. [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
  242. [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
  243. [[ -n "${PARAM_OCSP_MUST_STAPLE:-}" ]] && OCSP_MUST_STAPLE="${PARAM_OCSP_MUST_STAPLE}"
  244. [[ -n "${PARAM_IP_VERSION:-}" ]] && IP_VERSION="${PARAM_IP_VERSION}"
  245. if [ ! "${1:-}" = "noverify" ]; then
  246. verify_config
  247. fi
  248. store_configvars
  249. }
  250. # Initialize system
  251. init_system() {
  252. load_config
  253. # Lockfile handling (prevents concurrent access)
  254. if [[ -n "${LOCKFILE}" ]]; then
  255. LOCKDIR="$(dirname "${LOCKFILE}")"
  256. [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
  257. ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
  258. remove_lock() { rm -f "${LOCKFILE}"; }
  259. trap 'remove_lock' EXIT
  260. fi
  261. # Get CA URLs
  262. CA_DIRECTORY="$(http_request get "${CA}")"
  263. # Automatic discovery of API version
  264. if [[ "${API}" = "auto" ]]; then
  265. grep -q newOrder <<< "${CA_DIRECTORY}" && API=2 || API=1
  266. fi
  267. if [[ ${API} -eq 1 ]]; then
  268. # shellcheck disable=SC2015
  269. CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
  270. CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
  271. CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
  272. CA_TERMS="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value terms-of-service)" &&
  273. CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
  274. _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
  275. # Since reg URI is missing from directory we will assume it is the same as CA_NEW_REG without the new part
  276. CA_REG=${CA_NEW_REG/new-reg/reg}
  277. else
  278. # shellcheck disable=SC2015
  279. CA_NEW_ORDER="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value newOrder)" &&
  280. CA_NEW_NONCE="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value newNonce)" &&
  281. CA_NEW_ACCOUNT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value newAccount)" &&
  282. CA_TERMS="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value termsOfService)" &&
  283. CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revokeCert)" ||
  284. _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
  285. # Since acct URI is missing from directory we will assume it is the same as CA_NEW_ACCOUNT without the new part
  286. CA_ACCOUNT=${CA_NEW_ACCOUNT/new-acct/acct}
  287. fi
  288. # Export some environment variables to be used in hook script
  289. export WELLKNOWN BASEDIR CERTDIR ALPNCERTDIR CONFIG COMMAND
  290. # Checking for private key ...
  291. register_new_key="no"
  292. if [[ -n "${PARAM_ACCOUNT_KEY:-}" ]]; then
  293. # a private key was specified from the command line so use it for this run
  294. echo "Using private key ${PARAM_ACCOUNT_KEY} instead of account key"
  295. ACCOUNT_KEY="${PARAM_ACCOUNT_KEY}"
  296. ACCOUNT_KEY_JSON="${PARAM_ACCOUNT_KEY}.json"
  297. ACCOUNT_ID_JSON="${PARAM_ACCOUNT_KEY}_id.json"
  298. [ "${COMMAND:-}" = "register" ] && register_new_key="yes"
  299. else
  300. # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
  301. if [[ ! -e "${ACCOUNT_KEY}" ]]; then
  302. if [[ ! "${PARAM_ACCEPT_TERMS:-}" = "yes" ]]; then
  303. printf '\n' >&2
  304. printf 'To use dehydrated with this certificate authority you have to agree to their terms of service which you can find here: %s\n\n' "${CA_TERMS}" >&2
  305. printf 'To accept these terms of service run `%s --register --accept-terms`.\n' "${0}" >&2
  306. exit 1
  307. fi
  308. echo "+ Generating account key..."
  309. local tmp_account_key="$(_mktemp)"
  310. _openssl genrsa -out "${tmp_account_key}" "${KEYSIZE}"
  311. cat "${tmp_account_key}" > "${ACCOUNT_KEY}"
  312. rm "${tmp_account_key}"
  313. register_new_key="yes"
  314. fi
  315. fi
  316. "${OPENSSL}" rsa -in "${ACCOUNT_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Account key is not valid, cannot continue."
  317. # Get public components from private key and calculate thumbprint
  318. pubExponent64="$(printf '%x' "$("${OPENSSL}" rsa -in "${ACCOUNT_KEY}" -noout -text | awk '/publicExponent/ {print $2}')" | hex2bin | urlbase64)"
  319. pubMod64="$("${OPENSSL}" rsa -in "${ACCOUNT_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
  320. thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | "${OPENSSL}" dgst -sha256 -binary | urlbase64)"
  321. # If we generated a new private key in the step above we have to register it with the acme-server
  322. if [[ "${register_new_key}" = "yes" ]]; then
  323. echo "+ Registering account key with ACME server..."
  324. FAILED=false
  325. if [[ ${API} -eq 1 && -z "${CA_NEW_REG}" ]] || [[ ${API} -eq 2 && -z "${CA_NEW_ACCOUNT}" ]]; then
  326. echo "Certificate authority doesn't allow registrations."
  327. FAILED=true
  328. fi
  329. # If an email for the contact has been provided then adding it to the registration request
  330. if [[ "${FAILED}" = "false" ]]; then
  331. if [[ ${API} -eq 1 ]]; then
  332. if [[ -n "${CONTACT_EMAIL}" ]]; then
  333. (signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"${CA_TERMS}"'"}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
  334. else
  335. (signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"${CA_TERMS}"'"}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
  336. fi
  337. else
  338. if [[ -n "${CONTACT_EMAIL}" ]]; then
  339. (signed_request "${CA_NEW_ACCOUNT}" '{"contact":["mailto:'"${CONTACT_EMAIL}"'"], "termsOfServiceAgreed": true}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
  340. else
  341. (signed_request "${CA_NEW_ACCOUNT}" '{"termsOfServiceAgreed": true}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
  342. fi
  343. fi
  344. fi
  345. if [[ "${FAILED}" = "true" ]]; then
  346. echo >&2
  347. echo >&2
  348. echo "Error registering account key. See message above for more information." >&2
  349. rm "${ACCOUNT_KEY}" "${ACCOUNT_KEY_JSON}"
  350. exit 1
  351. fi
  352. elif [[ "${COMMAND:-}" = "register" ]]; then
  353. echo "+ Account already registered!"
  354. exit 0
  355. fi
  356. # Read account information or request from CA if missing
  357. if [[ -e "${ACCOUNT_KEY_JSON}" ]]; then
  358. if [[ ${API} -eq 1 ]]; then
  359. ACCOUNT_ID="$(cat "${ACCOUNT_KEY_JSON}" | get_json_int_value id)"
  360. ACCOUNT_URL="${CA_REG}/${ACCOUNT_ID}"
  361. else
  362. if [[ -e "${ACCOUNT_ID_JSON}" ]]; then
  363. ACCOUNT_ID="$(cat "${ACCOUNT_ID_JSON}" | get_json_string_value id)"
  364. else
  365. echo "+ Fetching account ID..."
  366. ACCOUNT_URL="$(signed_request "${CA_NEW_ACCOUNT}" '{"onlyReturnExisting": true}' 4>&1 | grep -i ^Location: | awk '{print $2}' | tr -d '\r\n')"
  367. ACCOUNT_ID="${ACCOUNT_URL##*/}"
  368. if [[ -z "${ACCOUNT_ID}" ]]; then
  369. _exiterr "Unknown error on fetching account information"
  370. fi
  371. echo '{"id": "'"${ACCOUNT_ID}"'"}' > "${ACCOUNT_ID_JSON}"
  372. fi
  373. ACCOUNT_URL="${CA_ACCOUNT}/${ACCOUNT_ID}"
  374. fi
  375. else
  376. echo "Fetching missing account information from CA..."
  377. if [[ ${API} -eq 1 ]]; then
  378. _exiterr "This is not implemented for ACMEv1! Consider switching to ACMEv2 :)"
  379. else
  380. ACCOUNT_URL="$(signed_request "${CA_NEW_ACCOUNT}" '{"onlyReturnExisting": true}' 4>&1 | grep -i ^Location: | awk '{print $2}' | tr -d '\r\n')"
  381. ACCOUNT_INFO="$(signed_request "${ACCOUNT_URL}" '{}')"
  382. fi
  383. ACCOUNT_ID="${ACCOUNT_URL##*/}"
  384. echo "${ACCOUNT_INFO}" > "${ACCOUNT_KEY_JSON}"
  385. fi
  386. }
  387. # Different sed version for different os types...
  388. _sed() {
  389. if [[ "${OSTYPE}" = "Linux" || "${OSTYPE:0:5}" = "MINGW" ]]; then
  390. sed -r "${@}"
  391. else
  392. sed -E "${@}"
  393. fi
  394. }
  395. # Print error message and exit with error
  396. _exiterr() {
  397. echo "ERROR: ${1}" >&2
  398. [[ -n "${HOOK:-}" ]] && "${HOOK}" "exit_hook" "${1}" || true
  399. exit 1
  400. }
  401. # Remove newlines and whitespace from json
  402. clean_json() {
  403. tr -d '\r\n' | _sed -e 's/ +/ /g' -e 's/\{ /{/g' -e 's/ \}/}/g' -e 's/\[ /[/g' -e 's/ \]/]/g'
  404. }
  405. # Encode data as url-safe formatted base64
  406. urlbase64() {
  407. # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
  408. "${OPENSSL}" base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
  409. }
  410. # Convert hex string to binary data
  411. hex2bin() {
  412. # Remove spaces, add leading zero, escape as hex string and parse with printf
  413. printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
  414. }
  415. # Get string value from json dictionary
  416. get_json_string_value() {
  417. local filter
  418. filter=$(printf 's/.*"%s": *"\([^"]*\)".*/\\1/p' "$1")
  419. sed -n "${filter}"
  420. }
  421. # Get array value from json dictionary
  422. get_json_array_value() {
  423. local filter
  424. filter=$(printf 's/.*"%s": *\\[\([^]]*\)\\].*/\\1/p' "$1")
  425. sed -n "${filter}"
  426. }
  427. # Get sub-dictionary from json
  428. get_json_dict_value() {
  429. local filter
  430. filter=$(printf 's/.*"%s": *{\([^}]*\)}.*/\\1/p' "$1")
  431. sed -n "${filter}"
  432. }
  433. # Get integer value from json
  434. get_json_int_value() {
  435. local filter
  436. filter=$(printf 's/.*"%s": *\([0-9]*\).*/\\1/p' "$1")
  437. sed -n "${filter}"
  438. }
  439. rm_json_arrays() {
  440. local filter
  441. filter='s/\[[^][]*\]/null/g'
  442. # remove three levels of nested arrays
  443. sed -e "${filter}" -e "${filter}" -e "${filter}"
  444. }
  445. # OpenSSL writes to stderr/stdout even when there are no errors. So just
  446. # display the output if the exit code was != 0 to simplify debugging.
  447. _openssl() {
  448. set +e
  449. out="$("${OPENSSL}" "${@}" 2>&1)"
  450. res=$?
  451. set -e
  452. if [[ ${res} -ne 0 ]]; then
  453. echo " + ERROR: failed to run $* (Exitcode: ${res})" >&2
  454. echo >&2
  455. echo "Details:" >&2
  456. echo "${out}" >&2
  457. echo >&2
  458. exit ${res}
  459. fi
  460. }
  461. # Send http(s) request with specified method
  462. http_request() {
  463. tempcont="$(_mktemp)"
  464. tempheaders="$(_mktemp)"
  465. if [[ -n "${IP_VERSION:-}" ]]; then
  466. ip_version="-${IP_VERSION}"
  467. fi
  468. set +e
  469. if [[ "${1}" = "head" ]]; then
  470. statuscode="$(curl ${ip_version:-} ${CURL_OPTS} -A "dehydrated/${VERSION} curl/${CURL_VERSION}" -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
  471. touch "${tempheaders}"
  472. curlret="${?}"
  473. elif [[ "${1}" = "get" ]]; then
  474. statuscode="$(curl ${ip_version:-} ${CURL_OPTS} -A "dehydrated/${VERSION} curl/${CURL_VERSION}" -L -s -w "%{http_code}" -o "${tempcont}" -D "${tempheaders}" "${2}")"
  475. curlret="${?}"
  476. elif [[ "${1}" = "post" ]]; then
  477. statuscode="$(curl ${ip_version:-} ${CURL_OPTS} -A "dehydrated/${VERSION} curl/${CURL_VERSION}" -s -w "%{http_code}" -o "${tempcont}" "${2}" -D "${tempheaders}" -H 'Content-Type: application/jose+json' -d "${3}")"
  478. curlret="${?}"
  479. else
  480. set -e
  481. _exiterr "Unknown request method: ${1}"
  482. fi
  483. set -e
  484. if [[ ! "${curlret}" = "0" ]]; then
  485. _exiterr "Problem connecting to server (${1} for ${2}; curl returned with ${curlret})"
  486. fi
  487. if [[ ! "${statuscode:0:1}" = "2" ]]; then
  488. # check for existing registration warning
  489. if [[ "${API}" = "1" ]] && [[ -n "${CA_NEW_REG:-}" ]] && [[ "${2}" = "${CA_NEW_REG:-}" ]] && [[ "${statuscode}" = "409" ]] && grep -q "Registration key is already in use" "${tempcont}"; then
  490. # do nothing
  491. :
  492. # check for already-revoked warning
  493. elif [[ -n "${CA_REVOKE_CERT:-}" ]] && [[ "${2}" = "${CA_REVOKE_CERT:-}" ]] && [[ "${statuscode}" = "409" ]]; then
  494. grep -q "Certificate already revoked" "${tempcont}" && return
  495. else
  496. echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
  497. echo >&2
  498. echo "Details:" >&2
  499. cat "${tempheaders}" >&2
  500. cat "${tempcont}" >&2
  501. echo >&2
  502. echo >&2
  503. # An exclusive hook for the {1}-request error might be useful (e.g., for sending an e-mail to admins)
  504. if [[ -n "${HOOK}" ]]; then
  505. errtxt="$(cat ${tempcont})"
  506. errheaders="$(cat ${tempheaders})"
  507. "${HOOK}" "request_failure" "${statuscode}" "${errtxt}" "${1}" "${errheaders}"
  508. fi
  509. rm -f "${tempcont}"
  510. rm -f "${tempheaders}"
  511. # remove temporary domains.txt file if used
  512. [[ "${COMMAND:-}" = "sign_domains" && -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
  513. exit 1
  514. fi
  515. fi
  516. if { true >&4; } 2>/dev/null; then
  517. cat "${tempheaders}" >&4
  518. fi
  519. cat "${tempcont}"
  520. rm -f "${tempcont}"
  521. rm -f "${tempheaders}"
  522. }
  523. # Send signed request
  524. signed_request() {
  525. # Encode payload as urlbase64
  526. payload64="$(printf '%s' "${2}" | urlbase64)"
  527. # Retrieve nonce from acme-server
  528. if [[ ${API} -eq 1 ]]; then
  529. nonce="$(http_request head "${CA}" | grep -i ^Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
  530. else
  531. nonce="$(http_request head "${CA_NEW_NONCE}" | grep -i ^Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
  532. fi
  533. # Build header with just our public key and algorithm information
  534. header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
  535. if [[ ${API} -eq 1 ]]; then
  536. # Build another header which also contains the previously received nonce and encode it as urlbase64
  537. protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
  538. protected64="$(printf '%s' "${protected}" | urlbase64)"
  539. else
  540. # Build another header which also contains the previously received nonce and url and encode it as urlbase64
  541. if [[ -n "${ACCOUNT_URL:-}" ]]; then
  542. protected='{"alg": "RS256", "kid": "'"${ACCOUNT_URL}"'", "url": "'"${1}"'", "nonce": "'"${nonce}"'"}'
  543. else
  544. protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "url": "'"${1}"'", "nonce": "'"${nonce}"'"}'
  545. fi
  546. protected64="$(printf '%s' "${protected}" | urlbase64)"
  547. fi
  548. # Sign header with nonce and our payload with our private key and encode signature as urlbase64
  549. signed64="$(printf '%s' "${protected64}.${payload64}" | "${OPENSSL}" dgst -sha256 -sign "${ACCOUNT_KEY}" | urlbase64)"
  550. if [[ ${API} -eq 1 ]]; then
  551. # Send header + extended header + payload + signature to the acme-server
  552. data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
  553. else
  554. # Send extended header + payload + signature to the acme-server
  555. data='{"protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
  556. fi
  557. http_request post "${1}" "${data}"
  558. }
  559. # Extracts all subject names from a CSR
  560. # Outputs either the CN, or the SANs, one per line
  561. extract_altnames() {
  562. csr="${1}" # the CSR itself (not a file)
  563. if ! <<<"${csr}" "${OPENSSL}" req -verify -noout 2>/dev/null; then
  564. _exiterr "Certificate signing request isn't valid"
  565. fi
  566. reqtext="$( <<<"${csr}" "${OPENSSL}" req -noout -text )"
  567. if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
  568. # SANs used, extract these
  569. altnames="$( <<<"${reqtext}" awk '/X509v3 Subject Alternative Name:/{print;getline;print;}' | tail -n1 )"
  570. # split to one per line:
  571. # shellcheck disable=SC1003
  572. altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
  573. # we can only get DNS: ones signed
  574. if grep -qEv '^(DNS|othername):' <<<"${altnames}"; then
  575. _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
  576. fi
  577. # strip away the DNS: prefix
  578. altnames="$( <<<"${altnames}" _sed -e 's/^(DNS:|othername:<unsupported>)//' )"
  579. printf "%s" "${altnames}" | tr '\n' ' '
  580. else
  581. # No SANs, extract CN
  582. altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN ?= ?([^ /,]*).*/\1/' )"
  583. printf "%s" "${altnames}"
  584. fi
  585. }
  586. # Create certificate for domain(s) and outputs it FD 3
  587. sign_csr() {
  588. csr="${1}" # the CSR itself (not a file)
  589. if { true >&3; } 2>/dev/null; then
  590. : # fd 3 looks OK
  591. else
  592. _exiterr "sign_csr: FD 3 not open"
  593. fi
  594. shift 1 || true
  595. export altnames="${*}"
  596. if [[ ${API} -eq 1 ]]; then
  597. if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
  598. _exiterr "Certificate authority doesn't allow certificate signing"
  599. fi
  600. elif [[ ${API} -eq 2 ]] && [[ -z "${CA_NEW_ORDER}" ]]; then
  601. _exiterr "Certificate authority doesn't allow certificate signing"
  602. fi
  603. if [[ -n "${ZSH_VERSION:-}" ]]; then
  604. local -A challenge_names challenge_uris challenge_tokens authorizations keyauths deploy_args
  605. else
  606. local -a challenge_names challenge_uris challenge_tokens authorizations keyauths deploy_args
  607. fi
  608. # Initial step: Find which authorizations we're dealing with
  609. if [[ ${API} -eq 2 ]]; then
  610. # Request new order and store authorization URIs
  611. local challenge_identifiers=""
  612. for altname in ${altnames}; do
  613. challenge_identifiers+="$(printf '{"type": "dns", "value": "%s"}, ' "${altname}")"
  614. done
  615. challenge_identifiers="[${challenge_identifiers%, }]"
  616. echo " + Requesting new certificate order from CA..."
  617. result="$(signed_request "${CA_NEW_ORDER}" '{"identifiers": '"${challenge_identifiers}"'}')"
  618. order_authorizations="$(echo ${result} | get_json_array_value authorizations)"
  619. finalize="$(echo "${result}" | get_json_string_value finalize)"
  620. local idx=0
  621. for uri in ${order_authorizations}; do
  622. authorizations[${idx}]="$(echo "${uri}" | _sed -e 's/\"(.*)".*/\1/')"
  623. idx=$((idx+1))
  624. done
  625. echo " + Received ${idx} authorizations URLs from the CA"
  626. else
  627. # Copy $altnames to $authorizations (just doing this to reduce duplicate code later on)
  628. local idx=0
  629. for altname in ${altnames}; do
  630. authorizations[${idx}]="${altname}"
  631. idx=$((idx+1))
  632. done
  633. fi
  634. # Check if authorizations are valid and gather challenge information for pending authorizations
  635. local idx=0
  636. for authorization in ${authorizations[*]}; do
  637. if [[ "${API}" -eq 2 ]]; then
  638. # Receive authorization ($authorization is authz uri)
  639. response="$(signed_request "$(echo "${authorization}" | _sed -e 's/\"(.*)".*/\1/')" "" | clean_json)"
  640. identifier="$(echo "${response}" | get_json_dict_value identifier | get_json_string_value value)"
  641. echo " + Handling authorization for ${identifier}"
  642. else
  643. # Request new authorization ($authorization is altname)
  644. identifier="${authorization}"
  645. echo " + Requesting authorization for ${identifier}..."
  646. response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${identifier}"'"}}' | clean_json)"
  647. fi
  648. # Check if authorization has already been validated
  649. if [ "$(echo "${response}" | _sed 's/"challenges": \[\{.*\}\]//' | get_json_string_value status)" = "valid" ] && [ ! "${PARAM_FORCE:-no}" = "yes" ]; then
  650. echo " + Found valid authorization for ${identifier}"
  651. continue
  652. fi
  653. # Find challenge in authorization
  654. challenges="$(echo "${response}" | _sed 's/.*"challenges": \[(\{.*\})\].*/\1/')"
  655. challenge="$(<<<"${challenges}" _sed -e 's/^[^\[]+\[(.+)\]$/\1/' -e 's/\}(, (\{)|(\]))/}\'$'\n''\2/g' | grep \""${CHALLENGETYPE}"\" || true)"
  656. if [ -z "${challenge}" ]; then
  657. allowed_validations="$(grep -Eo '"type": "[^"]+"' <<< "${challenges}" | grep -Eo ' "[^"]+"' | _sed -e 's/"//g' -e 's/^ //g')"
  658. _exiterr "Validating this certificate is not possible using ${CHALLENGETYPE}. Possible validation methods are: ${allowed_validations}"
  659. fi
  660. # Gather challenge information
  661. challenge_names[${idx}]="${identifier}"
  662. challenge_tokens[${idx}]="$(echo "${challenge}" | get_json_string_value token)"
  663. if [[ ${API} -eq 2 ]]; then
  664. challenge_uris[${idx}]="$(echo "${challenge}" | _sed 's/"validationRecord": ?\[[^]]+\]//g' | get_json_string_value url)"
  665. else
  666. challenge_uris[${idx}]="$(echo "${challenge}" | _sed 's/"validationRecord": ?\[[^]]+\]//g' | get_json_string_value uri)"
  667. fi
  668. # Prepare challenge tokens and deployment parameters
  669. keyauth="${challenge_tokens[${idx}]}.${thumbprint}"
  670. case "${CHALLENGETYPE}" in
  671. "http-01")
  672. # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
  673. printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_tokens[${idx}]}"
  674. chmod a+r "${WELLKNOWN}/${challenge_tokens[${idx}]}"
  675. keyauth_hook="${keyauth}"
  676. ;;
  677. "dns-01")
  678. # Generate DNS entry content for dns-01 validation
  679. keyauth_hook="$(printf '%s' "${keyauth}" | "${OPENSSL}" dgst -sha256 -binary | urlbase64)"
  680. ;;
  681. "tls-alpn-01")
  682. keyauth_hook="$(printf '%s' "${keyauth}" | "${OPENSSL}" dgst -sha256 -c -hex | awk '{print $2}')"
  683. generate_alpn_certificate "${identifier}" "${keyauth_hook}"
  684. ;;
  685. esac
  686. keyauths[${idx}]="${keyauth}"
  687. deploy_args[${idx}]="${identifier} ${challenge_tokens[${idx}]} ${keyauth_hook}"
  688. idx=$((idx+1))
  689. done
  690. local num_pending_challenges=${idx}
  691. echo " + ${num_pending_challenges} pending challenge(s)"
  692. # Deploy challenge tokens
  693. if [[ ${num_pending_challenges} -ne 0 ]]; then
  694. echo " + Deploying challenge tokens..."
  695. if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]]; then
  696. "${HOOK}" "deploy_challenge" ${deploy_args[@]}
  697. elif [[ -n "${HOOK}" ]]; then
  698. # Run hook script to deploy the challenge token
  699. local idx=0
  700. while [ ${idx} -lt ${num_pending_challenges} ]; do
  701. "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
  702. idx=$((idx+1))
  703. done
  704. fi
  705. fi
  706. # Validate pending challenges
  707. local idx=0
  708. while [ ${idx} -lt ${num_pending_challenges} ]; do
  709. echo " + Responding to challenge for ${challenge_names[${idx}]} authorization..."
  710. # Ask the acme-server to verify our challenge and wait until it is no longer pending
  711. if [[ ${API} -eq 1 ]]; then
  712. result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauths[${idx}]}"'"}' | clean_json)"
  713. else
  714. result="$(signed_request "${challenge_uris[${idx}]}" '{"keyAuthorization": "'"${keyauths[${idx}]}"'"}' | clean_json)"
  715. fi
  716. reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
  717. while [[ "${reqstatus}" = "pending" ]]; do
  718. sleep 1
  719. if [[ "${API}" -eq 2 ]]; then
  720. result="$(signed_request "${challenge_uris[${idx}]}" "")"
  721. else
  722. result="$(http_request get "${challenge_uris[${idx}]}")"
  723. fi
  724. reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
  725. done
  726. [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
  727. [[ "${CHALLENGETYPE}" = "tls-alpn-01" ]] && rm -f "${ALPNCERTDIR}/${challenge_names[${idx}]}.crt.pem" "${ALPNCERTDIR}/${challenge_names[${idx}]}.key.pem"
  728. if [[ "${reqstatus}" = "valid" ]]; then
  729. echo " + Challenge is valid!"
  730. else
  731. [[ -n "${HOOK}" ]] && "${HOOK}" "invalid_challenge" "${altname}" "${result}"
  732. break
  733. fi
  734. idx=$((idx+1))
  735. done
  736. if [[ ${num_pending_challenges} -ne 0 ]]; then
  737. echo " + Cleaning challenge tokens..."
  738. # Clean challenge tokens using chained hook
  739. [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
  740. # Clean remaining challenge tokens if validation has failed
  741. local idx=0
  742. while [ ${idx} -lt ${num_pending_challenges} ]; do
  743. # Delete challenge file
  744. [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
  745. # Delete alpn verification certificates
  746. [[ "${CHALLENGETYPE}" = "tls-alpn-01" ]] && rm -f "${ALPNCERTDIR}/${challenge_names[${idx}]}.crt.pem" "${ALPNCERTDIR}/${challenge_names[${idx}]}.key.pem"
  747. # Clean challenge token using non-chained hook
  748. [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
  749. idx=$((idx+1))
  750. done
  751. if [[ "${reqstatus}" != "valid" ]]; then
  752. echo " + Challenge validation has failed :("
  753. _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
  754. fi
  755. fi
  756. # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
  757. echo " + Requesting certificate..."
  758. csr64="$( <<<"${csr}" "${OPENSSL}" req -config "${OPENSSL_CNF}" -outform DER | urlbase64)"
  759. if [[ ${API} -eq 1 ]]; then
  760. crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | "${OPENSSL}" base64 -e)"
  761. crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
  762. else
  763. result="$(signed_request "${finalize}" '{"csr": "'"${csr64}"'"}' | clean_json | get_json_string_value certificate)"
  764. crt="$(signed_request "${result}" "")"
  765. fi
  766. # Try to load the certificate to detect corruption
  767. echo " + Checking certificate..."
  768. _openssl x509 -text <<<"${crt}"
  769. echo "${crt}" >&3
  770. unset challenge_token
  771. echo " + Done!"
  772. }
  773. # grep issuer cert uri from certificate
  774. get_issuer_cert_uri() {
  775. certificate="${1}"
  776. "${OPENSSL}" x509 -in "${certificate}" -noout -text | (grep 'CA Issuers - URI:' | cut -d':' -f2-) || true
  777. }
  778. get_issuer_hash() {
  779. certificate="${1}"
  780. "${OPENSSL}" x509 -in "${certificate}" -noout -issuer_hash
  781. }
  782. get_ocsp_url() {
  783. certificate="${1}"
  784. "${OPENSSL}" x509 -in "${certificate}" -noout -ocsp_uri
  785. }
  786. # walk certificate chain, retrieving all intermediate certificates
  787. walk_chain() {
  788. local certificate
  789. certificate="${1}"
  790. local issuer_cert_uri
  791. issuer_cert_uri="${2:-}"
  792. if [[ -z "${issuer_cert_uri}" ]]; then issuer_cert_uri="$(get_issuer_cert_uri "${certificate}")"; fi
  793. if [[ -n "${issuer_cert_uri}" ]]; then
  794. # create temporary files
  795. local tmpcert
  796. local tmpcert_raw
  797. tmpcert_raw="$(_mktemp)"
  798. tmpcert="$(_mktemp)"
  799. # download certificate
  800. http_request get "${issuer_cert_uri}" > "${tmpcert_raw}"
  801. # PEM
  802. if grep -q "BEGIN CERTIFICATE" "${tmpcert_raw}"; then mv "${tmpcert_raw}" "${tmpcert}"
  803. # DER
  804. elif "${OPENSSL}" x509 -in "${tmpcert_raw}" -inform DER -out "${tmpcert}" -outform PEM 2> /dev/null > /dev/null; then :
  805. # PKCS7
  806. elif "${OPENSSL}" pkcs7 -in "${tmpcert_raw}" -inform DER -out "${tmpcert}" -outform PEM -print_certs 2> /dev/null > /dev/null; then :
  807. # Unknown certificate type
  808. else _exiterr "Unknown certificate type in chain"
  809. fi
  810. local next_issuer_cert_uri
  811. next_issuer_cert_uri="$(get_issuer_cert_uri "${tmpcert}")"
  812. if [[ -n "${next_issuer_cert_uri}" ]]; then
  813. printf "\n%s\n" "${issuer_cert_uri}"
  814. cat "${tmpcert}"
  815. walk_chain "${tmpcert}" "${next_issuer_cert_uri}"
  816. fi
  817. rm -f "${tmpcert}" "${tmpcert_raw}"
  818. fi
  819. }
  820. # Generate ALPN verification certificate
  821. generate_alpn_certificate() {
  822. local altname="${1}"
  823. local acmevalidation="${2}"
  824. local alpncertdir="${ALPNCERTDIR}"
  825. if [[ ! -e "${alpncertdir}" ]]; then
  826. echo " + Creating new directory ${alpncertdir} ..."
  827. mkdir -p "${alpncertdir}" || _exiterr "Unable to create directory ${alpncertdir}"
  828. fi
  829. echo " + Generating ALPN certificate and key for ${1}..."
  830. tmp_openssl_cnf="$(_mktemp)"
  831. cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
  832. printf "[SAN]\nsubjectAltName=DNS:%s\n" "${altname}" >> "${tmp_openssl_cnf}"
  833. printf "1.3.6.1.5.5.7.1.31=critical,DER:04:20:${acmevalidation}\n" >> "${tmp_openssl_cnf}"
  834. SUBJ="/CN=${altname}/"
  835. [[ "${OSTYPE:0:5}" = "MINGW" ]] && SUBJ="/${SUBJ}"
  836. _openssl req -x509 -new -sha256 -nodes -newkey rsa:2048 -keyout "${alpncertdir}/${altname}.key.pem" -out "${alpncertdir}/${altname}.crt.pem" -subj "${SUBJ}" -extensions SAN -config "${tmp_openssl_cnf}"
  837. }
  838. # Create certificate for domain(s)
  839. sign_domain() {
  840. local certdir="${1}"
  841. shift
  842. timestamp="${1}"
  843. shift
  844. domain="${1}"
  845. altnames="${*}"
  846. export altnames
  847. echo " + Signing domains..."
  848. if [[ ${API} -eq 1 ]]; then
  849. if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
  850. _exiterr "Certificate authority doesn't allow certificate signing"
  851. fi
  852. elif [[ ${API} -eq 2 ]] && [[ -z "${CA_NEW_ORDER}" ]]; then
  853. _exiterr "Certificate authority doesn't allow certificate signing"
  854. fi
  855. local privkey="privkey.pem"
  856. if [[ ! -e "${certdir}/cert-${timestamp}.csr" ]]; then
  857. # generate a new private key if we need or want one
  858. if [[ ! -r "${certdir}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
  859. echo " + Generating private key..."
  860. privkey="privkey-${timestamp}.pem"
  861. local tmp_privkey="$(_mktemp)"
  862. case "${KEY_ALGO}" in
  863. rsa) _openssl genrsa -out "${tmp_privkey}" "${KEYSIZE}";;
  864. prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${tmp_privkey}";;
  865. esac
  866. cat "${tmp_privkey}" > "${certdir}/privkey-${timestamp}.pem"
  867. rm "${tmp_privkey}"
  868. fi
  869. # move rolloverkey into position (if any)
  870. if [[ -r "${certdir}/privkey.pem" && -r "${certdir}/privkey.roll.pem" && "${PRIVATE_KEY_RENEW}" = "yes" && "${PRIVATE_KEY_ROLLOVER}" = "yes" ]]; then
  871. echo " + Moving Rolloverkey into position.... "
  872. mv "${certdir}/privkey.roll.pem" "${certdir}/privkey-tmp.pem"
  873. mv "${certdir}/privkey-${timestamp}.pem" "${certdir}/privkey.roll.pem"
  874. mv "${certdir}/privkey-tmp.pem" "${certdir}/privkey-${timestamp}.pem"
  875. fi
  876. # generate a new private rollover key if we need or want one
  877. if [[ ! -r "${certdir}/privkey.roll.pem" && "${PRIVATE_KEY_ROLLOVER}" = "yes" && "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
  878. echo " + Generating private rollover key..."
  879. case "${KEY_ALGO}" in
  880. rsa) _openssl genrsa -out "${certdir}/privkey.roll.pem" "${KEYSIZE}";;
  881. prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${certdir}/privkey.roll.pem";;
  882. esac
  883. fi
  884. # delete rolloverkeys if disabled
  885. if [[ -r "${certdir}/privkey.roll.pem" && ! "${PRIVATE_KEY_ROLLOVER}" = "yes" ]]; then
  886. echo " + Removing Rolloverkey (feature disabled)..."
  887. rm -f "${certdir}/privkey.roll.pem"
  888. fi
  889. # Generate signing request config and the actual signing request
  890. echo " + Generating signing request..."
  891. SAN=""
  892. for altname in ${altnames}; do
  893. SAN="${SAN}DNS:${altname}, "
  894. done
  895. SAN="${SAN%%, }"
  896. local tmp_openssl_cnf
  897. tmp_openssl_cnf="$(_mktemp)"
  898. cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
  899. printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
  900. if [ "${OCSP_MUST_STAPLE}" = "yes" ]; then
  901. printf "\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "${tmp_openssl_cnf}"
  902. fi
  903. SUBJ="/CN=${domain}/"
  904. if [[ "${OSTYPE:0:5}" = "MINGW" ]]; then
  905. # The subject starts with a /, so MSYS will assume it's a path and convert
  906. # it unless we escape it with another one:
  907. SUBJ="/${SUBJ}"
  908. fi
  909. "${OPENSSL}" req -new -sha256 -key "${certdir}/${privkey}" -out "${certdir}/cert-${timestamp}.csr" -subj "${SUBJ}" -reqexts SAN -config "${tmp_openssl_cnf}"
  910. rm -f "${tmp_openssl_cnf}"
  911. fi
  912. crt_path="${certdir}/cert-${timestamp}.pem"
  913. # shellcheck disable=SC2086
  914. sign_csr "$(< "${certdir}/cert-${timestamp}.csr")" ${altnames} 3>"${crt_path}"
  915. # Create fullchain.pem
  916. echo " + Creating fullchain.pem..."
  917. if [[ ${API} -eq 1 ]]; then
  918. cat "${crt_path}" > "${certdir}/fullchain-${timestamp}.pem"
  919. local issuer_hash
  920. issuer_hash="$(get_issuer_hash "${crt_path}")"
  921. if [ -e "${CHAINCACHE}/${issuer_hash}.chain" ]; then
  922. echo " + Using cached chain!"
  923. cat "${CHAINCACHE}/${issuer_hash}.chain" > "${certdir}/chain-${timestamp}.pem"
  924. else
  925. echo " + Walking chain..."
  926. local issuer_cert_uri
  927. issuer_cert_uri="$(get_issuer_cert_uri "${crt_path}" || echo "unknown")"
  928. (walk_chain "${crt_path}" > "${certdir}/chain-${timestamp}.pem") || _exiterr "Walking chain has failed, your certificate has been created and can be found at ${crt_path}, the corresponding private key at ${privkey}. If you want you can manually continue on creating and linking all necessary files. If this error occurs again you should manually generate the certificate chain and place it under ${CHAINCACHE}/${issuer_hash}.chain (see ${issuer_cert_uri})"
  929. cat "${certdir}/chain-${timestamp}.pem" > "${CHAINCACHE}/${issuer_hash}.chain"
  930. fi
  931. cat "${certdir}/chain-${timestamp}.pem" >> "${certdir}/fullchain-${timestamp}.pem"
  932. else
  933. tmpcert="$(_mktemp)"
  934. tmpchain="$(_mktemp)"
  935. awk '{print >out}; /----END CERTIFICATE-----/{out=tmpchain}' out="${tmpcert}" tmpchain="${tmpchain}" "${certdir}/cert-${timestamp}.pem"
  936. mv "${certdir}/cert-${timestamp}.pem" "${certdir}/fullchain-${timestamp}.pem"
  937. cat "${tmpcert}" > "${certdir}/cert-${timestamp}.pem"
  938. cat "${tmpchain}" > "${certdir}/chain-${timestamp}.pem"
  939. rm "${tmpcert}" "${tmpchain}"
  940. fi
  941. # Wait for hook script to sync the files before creating the symlinks
  942. [[ -n "${HOOK}" ]] && "${HOOK}" "sync_cert" "${certdir}/privkey-${timestamp}.pem" "${certdir}/cert-${timestamp}.pem" "${certdir}/fullchain-${timestamp}.pem" "${certdir}/chain-${timestamp}.pem" "${certdir}/cert-${timestamp}.csr"
  943. # Update symlinks
  944. [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${certdir}/privkey.pem"
  945. ln -sf "chain-${timestamp}.pem" "${certdir}/chain.pem"
  946. ln -sf "fullchain-${timestamp}.pem" "${certdir}/fullchain.pem"
  947. ln -sf "cert-${timestamp}.csr" "${certdir}/cert.csr"
  948. ln -sf "cert-${timestamp}.pem" "${certdir}/cert.pem"
  949. # Wait for hook script to clean the challenge and to deploy cert if used
  950. [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${certdir}/privkey.pem" "${certdir}/cert.pem" "${certdir}/fullchain.pem" "${certdir}/chain.pem" "${timestamp}"
  951. unset challenge_token
  952. echo " + Done!"
  953. }
  954. # Usage: --version (-v)
  955. # Description: Print version information
  956. command_version() {
  957. load_config noverify
  958. echo "Dehydrated by Lukas Schauer"
  959. echo "https://dehydrated.io"
  960. echo ""
  961. echo "Dehydrated version: ${VERSION}"
  962. revision="$(cd "${SCRIPTDIR}"; git rev-parse HEAD 2>/dev/null || echo "unknown")"
  963. echo "GIT-Revision: ${revision}"
  964. echo ""
  965. if [[ "${OSTYPE}" =~ "BSD" ]]; then
  966. echo "OS: $(uname -sr)"
  967. else
  968. echo "OS: $(cat /etc/issue | grep -v ^$ | head -n1 | _sed 's/\\(r|n|l) .*//g')"
  969. fi
  970. echo "Used software:"
  971. [[ -n "${BASH_VERSION:-}" ]] && echo " bash: ${BASH_VERSION}"
  972. [[ -n "${ZSH_VERSION:-}" ]] && echo " zsh: ${ZSH_VERSION}"
  973. echo " curl: $(curl --version 2>&1 | head -n1 | cut -d" " -f1-2)"
  974. if [[ "${OSTYPE}" =~ "BSD" ]]; then
  975. echo " awk, sed, mktemp, grep, diff: BSD base system versions"
  976. else
  977. echo " awk: $(awk -W version 2>&1 | head -n1)"
  978. echo " sed: $(sed --version 2>&1 | head -n1)"
  979. echo " mktemp: $(mktemp --version 2>&1 | head -n1)"
  980. echo " grep: $(grep --version 2>&1 | head -n1)"
  981. echo " diff: $(diff --version 2>&1 | head -n1)"
  982. fi
  983. echo " openssl: $("${OPENSSL}" version 2>&1)"
  984. exit 0
  985. }
  986. # Usage: --register
  987. # Description: Register account key
  988. command_register() {
  989. init_system
  990. echo "+ Done!"
  991. exit 0
  992. }
  993. # Usage: --account
  994. # Description: Update account contact information
  995. command_account() {
  996. init_system
  997. FAILED=false
  998. NEW_ACCOUNT_KEY_JSON="$(_mktemp)"
  999. # Check if we have the registration id
  1000. if [[ -z "${ACCOUNT_ID}" ]]; then
  1001. _exiterr "Error retrieving registration id."
  1002. fi
  1003. echo "+ Updating registration id: ${ACCOUNT_ID} contact information..."
  1004. if [[ ${API} -eq 1 ]]; then
  1005. # If an email for the contact has been provided then adding it to the registered account
  1006. if [[ -n "${CONTACT_EMAIL}" ]]; then
  1007. (signed_request "${ACCOUNT_URL}" '{"resource": "reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"]}' > "${NEW_ACCOUNT_KEY_JSON}") || FAILED=true
  1008. else
  1009. (signed_request "${ACCOUNT_URL}" '{"resource": "reg", "contact":[]}' > "${NEW_ACCOUNT_KEY_JSON}") || FAILED=true
  1010. fi
  1011. else
  1012. # If an email for the contact has been provided then adding it to the registered account
  1013. if [[ -n "${CONTACT_EMAIL}" ]]; then
  1014. (signed_request "${ACCOUNT_URL}" '{"contact":["mailto:'"${CONTACT_EMAIL}"'"]}' > "${NEW_ACCOUNT_KEY_JSON}") || FAILED=true
  1015. else
  1016. (signed_request "${ACCOUNT_URL}" '{"contact":[]}' > "${NEW_ACCOUNT_KEY_JSON}") || FAILED=true
  1017. fi
  1018. fi
  1019. if [[ "${FAILED}" = "true" ]]; then
  1020. rm "${NEW_ACCOUNT_KEY_JSON}"
  1021. _exiterr "Error updating account information. See message above for more information."
  1022. fi
  1023. if diff -q "${NEW_ACCOUNT_KEY_JSON}" "${ACCOUNT_KEY_JSON}" > /dev/null; then
  1024. echo "+ Account information was the same after the update"
  1025. rm "${NEW_ACCOUNT_KEY_JSON}"
  1026. else
  1027. ACCOUNT_KEY_JSON_BACKUP="${ACCOUNT_KEY_JSON%.*}-$(date +%s).json"
  1028. echo "+ Backup ${ACCOUNT_KEY_JSON} as ${ACCOUNT_KEY_JSON_BACKUP}"
  1029. cp -p "${ACCOUNT_KEY_JSON}" "${ACCOUNT_KEY_JSON_BACKUP}"
  1030. echo "+ Populate ${ACCOUNT_KEY_JSON}"
  1031. mv "${NEW_ACCOUNT_KEY_JSON}" "${ACCOUNT_KEY_JSON}"
  1032. fi
  1033. echo "+ Done!"
  1034. exit 0
  1035. }
  1036. # Usage: --cron (-c)
  1037. # Description: Sign/renew non-existent/changed/expiring certificates.
  1038. command_sign_domains() {
  1039. init_system
  1040. hookscript_bricker_hook
  1041. # Call startup hook
  1042. [[ -n "${HOOK}" ]] && "${HOOK}" "startup_hook"
  1043. if [ ! -d "${CHAINCACHE}" ]; then
  1044. echo " + Creating chain cache directory ${CHAINCACHE}"
  1045. mkdir "${CHAINCACHE}"
  1046. fi
  1047. if [[ -n "${PARAM_DOMAIN:-}" ]]; then
  1048. DOMAINS_TXT="$(_mktemp)"
  1049. if [[ -n "${PARAM_ALIAS:-}" ]]; then
  1050. printf -- "${PARAM_DOMAIN} > ${PARAM_ALIAS}" > "${DOMAINS_TXT}"
  1051. else
  1052. printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
  1053. fi
  1054. elif [[ -e "${DOMAINS_TXT}" ]]; then
  1055. if [[ ! -r "${DOMAINS_TXT}" ]]; then
  1056. _exiterr "domains.txt found but not readable"
  1057. fi
  1058. else
  1059. _exiterr "domains.txt not found and --domain not given"
  1060. fi
  1061. # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
  1062. ORIGIFS="${IFS}"
  1063. IFS=$'\n'
  1064. for line in $(<"${DOMAINS_TXT}" tr -d '\r' | awk '{print tolower($0)}' | _sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e 's/[[:space:]]+/ /g' -e 's/([^ ])>/\1 >/g' -e 's/> />/g' | (grep -vE '^(#|$)' || true)); do
  1065. reset_configvars
  1066. IFS="${ORIGIFS}"
  1067. alias="$(grep -Eo '>[^ ]+' <<< "${line}" || true)"
  1068. line="$(_sed -e 's/>[^ ]+[ ]*//g' <<< "${line}")"
  1069. aliascount="$(grep -Eo '>' <<< "${alias}" | awk 'END {print NR}' || true )"
  1070. [ ${aliascount} -gt 1 ] && _exiterr "Only one alias per line is allowed in domains.txt!"
  1071. domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
  1072. morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
  1073. [ ${aliascount} -lt 1 ] && alias="${domain}" || alias="${alias#>}"
  1074. export alias
  1075. if [[ -z "${morenames}" ]];then
  1076. echo "Processing ${domain}"
  1077. else
  1078. echo "Processing ${domain} with alternative names: ${morenames}"
  1079. fi
  1080. if [ "${alias:0:2}" = "*." ]; then
  1081. _exiterr "Please define a valid alias for your ${domain} wildcard-certificate. See domains.txt-documentation for more details."
  1082. fi
  1083. local certdir="${CERTDIR}/${alias}"
  1084. cert="${certdir}/cert.pem"
  1085. chain="${certdir}/chain.pem"
  1086. force_renew="${PARAM_FORCE:-no}"
  1087. timestamp="$(date +%s)"
  1088. # If there is no existing certificate directory => make it
  1089. if [[ ! -e "${certdir}" ]]; then
  1090. echo " + Creating new directory ${certdir} ..."
  1091. mkdir -p "${certdir}" || _exiterr "Unable to create directory ${certdir}"
  1092. fi
  1093. # read cert config
  1094. # for now this loads the certificate specific config in a subshell and parses a diff of set variables.
  1095. # we could just source the config file but i decided to go this way to protect people from accidentally overriding
  1096. # variables used internally by this script itself.
  1097. if [[ -n "${DOMAINS_D}" ]]; then
  1098. certconfig="${DOMAINS_D}/${alias}"
  1099. else
  1100. certconfig="${certdir}/config"
  1101. fi
  1102. if [ -f "${certconfig}" ]; then
  1103. echo " + Using certificate specific config file!"
  1104. ORIGIFS="${IFS}"
  1105. IFS=$'\n'
  1106. for cfgline in $(
  1107. beforevars="$(_mktemp)"
  1108. aftervars="$(_mktemp)"
  1109. set > "${beforevars}"
  1110. # shellcheck disable=SC1090
  1111. . "${certconfig}"
  1112. set > "${aftervars}"
  1113. diff -u "${beforevars}" "${aftervars}" | grep -E '^\+[^+]'
  1114. rm "${beforevars}"
  1115. rm "${aftervars}"
  1116. ); do
  1117. config_var="$(echo "${cfgline:1}" | cut -d'=' -f1)"
  1118. config_value="$(echo "${cfgline:1}" | cut -d'=' -f2-)"
  1119. case "${config_var}" in
  1120. KEY_ALGO|OCSP_MUST_STAPLE|PRIVATE_KEY_RENEW|PRIVATE_KEY_ROLLOVER|KEYSIZE|CHALLENGETYPE|HOOK|WELLKNOWN|HOOK_CHAIN|OPENSSL_CNF|RENEW_DAYS)
  1121. echo " + ${config_var} = ${config_value}"
  1122. declare -- "${config_var}=${config_value}"
  1123. ;;
  1124. _) ;;
  1125. *) echo " ! Setting ${config_var} on a per-certificate base is not (yet) supported" >&2
  1126. esac
  1127. done
  1128. IFS="${ORIGIFS}"
  1129. fi
  1130. verify_config
  1131. hookscript_bricker_hook
  1132. export WELLKNOWN CHALLENGETYPE KEY_ALGO PRIVATE_KEY_ROLLOVER
  1133. skip="no"
  1134. # Allow for external CSR generation
  1135. local csr=""
  1136. if [[ -n "${HOOK}" ]]; then
  1137. csr="$("${HOOK}" "generate_csr" "${domain}" "${certdir}" "${domain} ${morenames}")"
  1138. if grep -qE "\-----BEGIN (NEW )?CERTIFICATE REQUEST-----" <<< "${csr}"; then
  1139. altnames="$(extract_altnames "${csr}")"
  1140. domain="$(cut -d' ' -f1 <<< "${altnames}")"
  1141. morenames="$(cut -s -d' ' -f2- <<< "${altnames}")"
  1142. echo " + Using CSR from hook script (real names: ${altnames})"
  1143. else
  1144. csr=""
  1145. fi
  1146. fi
  1147. # Check domain names of existing certificate
  1148. if [[ -e "${cert}" ]]; then
  1149. printf " + Checking domain name(s) of existing cert..."
  1150. certnames="$("${OPENSSL}" x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
  1151. givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
  1152. if [[ "${certnames}" = "${givennames}" ]]; then
  1153. echo " unchanged."
  1154. else
  1155. echo " changed!"
  1156. echo " + Domain name(s) are not matching!"
  1157. echo " + Names in old certificate: ${certnames}"
  1158. echo " + Configured names: ${givennames}"
  1159. echo " + Forcing renew."
  1160. force_renew="yes"
  1161. fi
  1162. fi
  1163. # Check expire date of existing certificate
  1164. if [[ -e "${cert}" ]]; then
  1165. echo " + Checking expire date of existing cert..."
  1166. valid="$("${OPENSSL}" x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
  1167. printf " + Valid till %s " "${valid}"
  1168. if "${OPENSSL}" x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
  1169. printf "(Longer than %d days). " "${RENEW_DAYS}"
  1170. if [[ "${force_renew}" = "yes" ]]; then
  1171. echo "Ignoring because renew was forced!"
  1172. else
  1173. # Certificate-Names unchanged and cert is still valid
  1174. echo "Skipping renew!"
  1175. [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${certdir}/privkey.pem" "${certdir}/cert.pem" "${certdir}/fullchain.pem" "${certdir}/chain.pem"
  1176. skip="yes"
  1177. fi
  1178. else
  1179. echo "(Less than ${RENEW_DAYS} days). Renewing!"
  1180. fi
  1181. fi
  1182. local update_ocsp
  1183. update_ocsp="no"
  1184. # Sign certificate for this domain
  1185. if [[ ! "${skip}" = "yes" ]]; then
  1186. update_ocsp="yes"
  1187. [[ -z "${csr}" ]] || printf "%s" "${csr}" > "${certdir}/cert-${timestamp}.csr"
  1188. if [[ "${PARAM_KEEP_GOING:-}" = "yes" ]]; then
  1189. sign_domain "${certdir}" ${timestamp} ${domain} ${morenames} &
  1190. wait $! || true
  1191. else
  1192. sign_domain "${certdir}" ${timestamp} ${domain} ${morenames}
  1193. fi
  1194. fi
  1195. if [[ "${OCSP_FETCH}" = "yes" ]]; then
  1196. local ocsp_url
  1197. ocsp_url="$(get_ocsp_url "${cert}")"
  1198. if [[ ! -e "${certdir}/ocsp.der" ]]; then
  1199. update_ocsp="yes"
  1200. elif ! ("${OPENSSL}" ocsp -no_nonce -issuer "${chain}" -verify_other "${chain}" -cert "${cert}" -respin "${certdir}/ocsp.der" -status_age $((OCSP_DAYS*24*3600)) 2>&1 | grep -q "${cert}: good"); then
  1201. update_ocsp="yes"
  1202. fi
  1203. if [[ "${update_ocsp}" = "yes" ]]; then
  1204. echo " + Updating OCSP stapling file"
  1205. ocsp_timestamp="$(date +%s)"
  1206. if grep -qE "^(0|(1\.0))\." <<< "$(${OPENSSL} version | awk '{print $2}')"; then
  1207. ocsp_log="$("${OPENSSL}" ocsp -no_nonce -issuer "${chain}" -verify_other "${chain}" -cert "${cert}" -respout "${certdir}/ocsp-${ocsp_timestamp}.der" -url "${ocsp_url}" -header "HOST" "$(echo "${ocsp_url}" | _sed -e 's/^http(s?):\/\///' -e 's/\/.*$//g')" 2>&1)" || _exiterr "Error while fetching OCSP information: ${ocsp_log}"
  1208. else
  1209. ocsp_log="$("${OPENSSL}" ocsp -no_nonce -issuer "${chain}" -verify_other "${chain}" -cert "${cert}" -respout "${certdir}/ocsp-${ocsp_timestamp}.der" -url "${ocsp_url}" 2>&1)" || _exiterr "Error while fetching OCSP information: ${ocsp_log}"
  1210. fi
  1211. ln -sf "ocsp-${ocsp_timestamp}.der" "${certdir}/ocsp.der"
  1212. [[ -n "${HOOK}" ]] && altnames="${domain} ${morenames}" "${HOOK}" "deploy_ocsp" "${domain}" "${certdir}/ocsp.der" "${ocsp_timestamp}"
  1213. else
  1214. echo " + OSCP stapling file is still valid (skipping update)"
  1215. fi
  1216. fi
  1217. done
  1218. reset_configvars
  1219. # remove temporary domains.txt file if used
  1220. [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
  1221. [[ -n "${HOOK}" ]] && "${HOOK}" "exit_hook"
  1222. if [[ "${AUTO_CLEANUP}" == "yes" ]]; then
  1223. echo "+ Running automatic cleanup"
  1224. command_cleanup noinit
  1225. fi
  1226. exit 0
  1227. }
  1228. # Usage: --signcsr (-s) path/to/csr.pem
  1229. # Description: Sign a given CSR, output CRT on stdout (advanced usage)
  1230. command_sign_csr() {
  1231. # redirect stdout to stderr
  1232. # leave stdout over at fd 3 to output the cert
  1233. exec 3>&1 1>&2
  1234. init_system
  1235. # load csr
  1236. csrfile="${1}"
  1237. if [ ! -r "${csrfile}" ]; then
  1238. _exiterr "Could not read certificate signing request ${csrfile}"
  1239. fi
  1240. csr="$(cat "${csrfile}")"
  1241. # extract names
  1242. altnames="$(extract_altnames "${csr}")"
  1243. # gen cert
  1244. certfile="$(_mktemp)"
  1245. sign_csr "${csr}" ${altnames} 3> "${certfile}"
  1246. # print cert
  1247. echo "# CERT #" >&3
  1248. cat "${certfile}" >&3
  1249. echo >&3
  1250. # print chain
  1251. if [ -n "${PARAM_FULL_CHAIN:-}" ]; then
  1252. # get and convert ca cert
  1253. chainfile="$(_mktemp)"
  1254. tmpchain="$(_mktemp)"
  1255. http_request get "$("${OPENSSL}" x509 -in "${certfile}" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${tmpchain}"
  1256. if grep -q "BEGIN CERTIFICATE" "${tmpchain}"; then
  1257. mv "${tmpchain}" "${chainfile}"
  1258. else
  1259. "${OPENSSL}" x509 -in "${tmpchain}" -inform DER -out "${chainfile}" -outform PEM
  1260. rm "${tmpchain}"
  1261. fi
  1262. echo "# CHAIN #" >&3
  1263. cat "${chainfile}" >&3
  1264. rm "${chainfile}"
  1265. fi
  1266. # cleanup
  1267. rm "${certfile}"
  1268. exit 0
  1269. }
  1270. # Usage: --revoke (-r) path/to/cert.pem
  1271. # Description: Revoke specified certificate
  1272. command_revoke() {
  1273. init_system
  1274. [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
  1275. cert="${1}"
  1276. if [[ -L "${cert}" ]]; then
  1277. # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
  1278. local link_target
  1279. link_target="$(readlink -n "${cert}")"
  1280. if [[ "${link_target}" =~ ^/ ]]; then
  1281. cert="${link_target}"
  1282. else
  1283. cert="$(dirname "${cert}")/${link_target}"
  1284. fi
  1285. fi
  1286. [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
  1287. echo "Revoking ${cert}"
  1288. cert64="$("${OPENSSL}" x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
  1289. if [[ ${API} -eq 1 ]]; then
  1290. response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}' | clean_json)"
  1291. else
  1292. response="$(signed_request "${CA_REVOKE_CERT}" '{"certificate": "'"${cert64}"'"}' | clean_json)"
  1293. fi
  1294. # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
  1295. # so if we are here, it is safe to assume the request was successful
  1296. echo " + Done."
  1297. echo " + Renaming certificate to ${cert}-revoked"
  1298. mv -f "${cert}" "${cert}-revoked"
  1299. }
  1300. # Usage: --cleanup (-gc)
  1301. # Description: Move unused certificate files to archive directory
  1302. command_cleanup() {
  1303. if [ ! "${1:-}" = "noinit" ]; then
  1304. load_config
  1305. fi
  1306. # Create global archive directory if not existent
  1307. if [[ ! -e "${BASEDIR}/archive" ]]; then
  1308. mkdir "${BASEDIR}/archive"
  1309. fi
  1310. # Allow globbing
  1311. [[ -n "${ZSH_VERSION:-}" ]] && set +o noglob || set +f
  1312. # Loop over all certificate directories
  1313. for certdir in "${CERTDIR}/"*; do
  1314. # Skip if entry is not a folder
  1315. [[ -d "${certdir}" ]] || continue
  1316. # Get certificate name
  1317. certname="$(basename "${certdir}")"
  1318. # Create certificates archive directory if not existent
  1319. archivedir="${BASEDIR}/archive/${certname}"
  1320. if [[ ! -e "${archivedir}" ]]; then
  1321. mkdir "${archivedir}"
  1322. fi
  1323. # Loop over file-types (certificates, keys, signing-requests, ...)
  1324. for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem ocsp.der; do
  1325. # Skip if symlink is broken
  1326. [[ -r "${certdir}/${filetype}" ]] || continue
  1327. # Look up current file in use
  1328. current="$(basename "$(readlink "${certdir}/${filetype}")")"
  1329. # Split filetype into name and extension
  1330. filebase="$(echo "${filetype}" | cut -d. -f1)"
  1331. fileext="$(echo "${filetype}" | cut -d. -f2)"
  1332. # Loop over all files of this type
  1333. for file in "${certdir}/${filebase}-"*".${fileext}" "${certdir}/${filebase}-"*".${fileext}-revoked"; do
  1334. # Check if current file is in use, if unused move to archive directory
  1335. filename="$(basename "${file}")"
  1336. if [[ ! "${filename}" = "${current}" ]]; then
  1337. echo "Moving unused file to archive directory: ${certname}/${filename}"
  1338. mv "${certdir}/${filename}" "${archivedir}/${filename}"
  1339. fi
  1340. done
  1341. done
  1342. done
  1343. exit 0
  1344. }
  1345. # Usage: --help (-h)
  1346. # Description: Show help text
  1347. command_help() {
  1348. printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
  1349. printf "Default command: help\n\n"
  1350. echo "Commands:"
  1351. grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
  1352. if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
  1353. _exiterr "Error generating help text."
  1354. fi
  1355. printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
  1356. done
  1357. printf -- "\nParameters:\n"
  1358. grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
  1359. if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
  1360. _exiterr "Error generating help text."
  1361. fi
  1362. printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
  1363. done
  1364. }
  1365. # Usage: --env (-e)
  1366. # Description: Output configuration variables for use in other scripts
  1367. command_env() {
  1368. echo "# dehydrated configuration"
  1369. load_config
  1370. typeset -p CA CERTDIR ALPNCERTDIR CHALLENGETYPE DOMAINS_D DOMAINS_TXT HOOK HOOK_CHAIN RENEW_DAYS ACCOUNT_KEY ACCOUNT_KEY_JSON ACCOUNT_ID_JSON KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
  1371. }
  1372. # Main method (parses script arguments and calls command_* methods)
  1373. main() {
  1374. COMMAND=""
  1375. set_command() {
  1376. [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
  1377. COMMAND="${1}"
  1378. }
  1379. check_parameters() {
  1380. if [[ -z "${1:-}" ]]; then
  1381. echo "The specified command requires additional parameters. See help:" >&2
  1382. echo >&2
  1383. command_help >&2
  1384. exit 1
  1385. elif [[ "${1:0:1}" = "-" ]]; then
  1386. _exiterr "Invalid argument: ${1}"
  1387. fi
  1388. }
  1389. # shellcheck disable=SC2199
  1390. [[ -z "${@}" ]] && eval set -- "--help"
  1391. while (( ${#} )); do
  1392. case "${1}" in
  1393. --help|-h)
  1394. command_help
  1395. exit 0
  1396. ;;
  1397. --env|-e)
  1398. set_command env
  1399. ;;
  1400. --cron|-c)
  1401. set_command sign_domains
  1402. ;;
  1403. --register)
  1404. set_command register
  1405. ;;
  1406. --account)
  1407. set_command account
  1408. ;;
  1409. # PARAM_Usage: --accept-terms
  1410. # PARAM_Description: Accept CAs terms of service
  1411. --accept-terms)
  1412. PARAM_ACCEPT_TERMS="yes"
  1413. ;;
  1414. --signcsr|-s)
  1415. shift 1
  1416. set_command sign_csr
  1417. check_parameters "${1:-}"
  1418. PARAM_CSR="${1}"
  1419. ;;
  1420. --revoke|-r)
  1421. shift 1
  1422. set_command revoke
  1423. check_parameters "${1:-}"
  1424. PARAM_REVOKECERT="${1}"
  1425. ;;
  1426. --version|-v)
  1427. set_command version
  1428. ;;
  1429. --cleanup|-gc)
  1430. set_command cleanup
  1431. ;;
  1432. # PARAM_Usage: --full-chain (-fc)
  1433. # PARAM_Description: Print full chain when using --signcsr
  1434. --full-chain|-fc)
  1435. PARAM_FULL_CHAIN="1"
  1436. ;;
  1437. # PARAM_Usage: --ipv4 (-4)
  1438. # PARAM_Description: Resolve names to IPv4 addresses only
  1439. --ipv4|-4)
  1440. PARAM_IP_VERSION="4"
  1441. ;;
  1442. # PARAM_Usage: --ipv6 (-6)
  1443. # PARAM_Description: Resolve names to IPv6 addresses only
  1444. --ipv6|-6)
  1445. PARAM_IP_VERSION="6"
  1446. ;;
  1447. # PARAM_Usage: --domain (-d) domain.tld
  1448. # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
  1449. --domain|-d)
  1450. shift 1
  1451. check_parameters "${1:-}"
  1452. if [[ -z "${PARAM_DOMAIN:-}" ]]; then
  1453. PARAM_DOMAIN="${1}"
  1454. else
  1455. PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
  1456. fi
  1457. ;;
  1458. # PARAM_Usage: --alias certalias
  1459. # PARAM_Description: Use specified name for certificate directory (and per-certificate config) instead of the primary domain (only used if --domain is specified)
  1460. --alias)
  1461. shift 1
  1462. check_parameters "${1:-}"
  1463. [[ -n "${PARAM_ALIAS:-}" ]] && _exiterr "Alias can only be specified once!"
  1464. PARAM_ALIAS="${1}"
  1465. ;;
  1466. # PARAM_Usage: --keep-going (-g)
  1467. # PARAM_Description: Keep going after encountering an error while creating/renewing multiple certificates in cron mode
  1468. --keep-going|-g)
  1469. PARAM_KEEP_GOING="yes"
  1470. ;;
  1471. # PARAM_Usage: --force (-x)
  1472. # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
  1473. --force|-x)
  1474. PARAM_FORCE="yes"
  1475. ;;
  1476. # PARAM_Usage: --no-lock (-n)
  1477. # PARAM_Description: Don't use lockfile (potentially dangerous!)
  1478. --no-lock|-n)
  1479. PARAM_NO_LOCK="yes"
  1480. ;;
  1481. # PARAM_Usage: --lock-suffix example.com
  1482. # PARAM_Description: Suffix lockfile name with a string (useful for with -d)
  1483. --lock-suffix)
  1484. shift 1
  1485. check_parameters "${1:-}"
  1486. PARAM_LOCKFILE_SUFFIX="${1}"
  1487. ;;
  1488. # PARAM_Usage: --ocsp
  1489. # PARAM_Description: Sets option in CSR indicating OCSP stapling to be mandatory
  1490. --ocsp)
  1491. PARAM_OCSP_MUST_STAPLE="yes"
  1492. ;;
  1493. # PARAM_Usage: --privkey (-p) path/to/key.pem
  1494. # PARAM_Description: Use specified private key instead of account key (useful for revocation)
  1495. --privkey|-p)
  1496. shift 1
  1497. check_parameters "${1:-}"
  1498. PARAM_ACCOUNT_KEY="${1}"
  1499. ;;
  1500. # PARAM_Usage: --config (-f) path/to/config
  1501. # PARAM_Description: Use specified config file
  1502. --config|-f)
  1503. shift 1
  1504. check_parameters "${1:-}"
  1505. CONFIG="${1}"
  1506. ;;
  1507. # PARAM_Usage: --hook (-k) path/to/hook.sh
  1508. # PARAM_Description: Use specified script for hooks
  1509. --hook|-k)
  1510. shift 1
  1511. check_parameters "${1:-}"
  1512. PARAM_HOOK="${1}"
  1513. ;;
  1514. # PARAM_Usage: --out (-o) certs/directory
  1515. # PARAM_Description: Output certificates into the specified directory
  1516. --out|-o)
  1517. shift 1
  1518. check_parameters "${1:-}"
  1519. PARAM_CERTDIR="${1}"
  1520. ;;
  1521. # PARAM_Usage: --alpn alpn-certs/directory
  1522. # PARAM_Description: Output alpn verification certificates into the specified directory
  1523. --alpn)
  1524. shift 1
  1525. check_parameters "${1:-}"
  1526. PARAM_ALPNCERTDIR="${1}"
  1527. ;;
  1528. # PARAM_Usage: --challenge (-t) http-01|dns-01
  1529. # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
  1530. --challenge|-t)
  1531. shift 1
  1532. check_parameters "${1:-}"
  1533. PARAM_CHALLENGETYPE="${1}"
  1534. ;;
  1535. # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
  1536. # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
  1537. --algo|-a)
  1538. shift 1
  1539. check_parameters "${1:-}"
  1540. PARAM_KEY_ALGO="${1}"
  1541. ;;
  1542. *)
  1543. echo "Unknown parameter detected: ${1}" >&2
  1544. echo >&2
  1545. command_help >&2
  1546. exit 1
  1547. ;;
  1548. esac
  1549. shift 1
  1550. done
  1551. case "${COMMAND}" in
  1552. env) command_env;;
  1553. sign_domains) command_sign_domains;;
  1554. register) command_register;;
  1555. account) command_account;;
  1556. sign_csr) command_sign_csr "${PARAM_CSR}";;
  1557. revoke) command_revoke "${PARAM_REVOKECERT}";;
  1558. cleanup) command_cleanup;;
  1559. version) command_version;;
  1560. *) command_help; exit 1;;
  1561. esac
  1562. }
  1563. # Determine OS type
  1564. OSTYPE="$(uname)"
  1565. if [[ ! "${DEHYDRATED_NOOP:-}" = "NOOP" ]]; then
  1566. # Run script
  1567. main "${@:-}"
  1568. fi