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.

229 lines
10 KiB

5 years ago
  1. #!/bin/bash
  2. ################################################################################
  3. # ACME.sh 3rd party deploy plugin for Synology DSM
  4. ################################################################################
  5. # Authors: Brian Hartvigsen (creator), https://github.com/tresni
  6. # Martin Arndt (contributor), https://troublezone.net/
  7. # Updated: 2023-07-03
  8. # Issues: https://github.com/acmesh-official/acme.sh/issues/2727
  9. ################################################################################
  10. # Usage:
  11. # 1. export SYNO_Username="adminUser"
  12. # 2. export SYNO_Password="adminPassword"
  13. # Optional exports (shown values are the defaults):
  14. # - export SYNO_Certificate="" to replace a specific certificate via description
  15. # - export SYNO_Scheme="http"
  16. # - export SYNO_Hostname="localhost"
  17. # - export SYNO_Port="5000"
  18. # - export SYNO_Device_Name="CertRenewal" - required for skipping 2FA-OTP
  19. # - export SYNO_Device_ID="" - required for skipping 2FA-OTP
  20. # 3. acme.sh --deploy --deploy-hook synology_dsm -d example.com
  21. ################################################################################
  22. # Dependencies:
  23. # - jq & curl
  24. ################################################################################
  25. # Return value:
  26. # 0 means success, otherwise error.
  27. ################################################################################
  28. ########## Public functions ####################################################
  29. #domain keyfile certfile cafile fullchain
  30. synology_dsm_deploy() {
  31. _cdomain="$1"
  32. _ckey="$2"
  33. _ccert="$3"
  34. _cca="$4"
  35. _debug _cdomain "$_cdomain"
  36. # Get username & password, but don't save until we authenticated successfully
  37. _getdeployconf SYNO_Username
  38. _getdeployconf SYNO_Password
  39. _getdeployconf SYNO_Create
  40. _getdeployconf SYNO_DID
  41. _getdeployconf SYNO_TOTP_SECRET
  42. _getdeployconf SYNO_Device_Name
  43. _getdeployconf SYNO_Device_ID
  44. if [ -z "${SYNO_Username:-}" ] || [ -z "${SYNO_Password:-}" ]; then
  45. _err "SYNO_Username & SYNO_Password must be set"
  46. return 1
  47. fi
  48. if [ -n "${SYNO_Device_Name:-}" ] && [ -z "${SYNO_Device_ID:-}" ]; then
  49. _err "SYNO_Device_Name set, but SYNO_Device_ID is empty"
  50. return 1
  51. fi
  52. _debug2 SYNO_Username "$SYNO_Username"
  53. _secure_debug2 SYNO_Password "$SYNO_Password"
  54. _debug2 SYNO_Create "$SYNO_Create"
  55. _debug2 SYNO_Device_Name "$SYNO_Device_Name"
  56. _secure_debug2 SYNO_Device_ID "$SYNO_Device_ID"
  57. # Optional scheme, hostname & port for Synology DSM
  58. _getdeployconf SYNO_Scheme
  59. _getdeployconf SYNO_Hostname
  60. _getdeployconf SYNO_Port
  61. # Default values for scheme, hostname & port
  62. # Defaulting to localhost & http, because it's localhost…
  63. [ -n "${SYNO_Scheme}" ] || SYNO_Scheme="http"
  64. [ -n "${SYNO_Hostname}" ] || SYNO_Hostname="localhost"
  65. [ -n "${SYNO_Port}" ] || SYNO_Port="5000"
  66. _savedeployconf SYNO_Scheme "$SYNO_Scheme"
  67. _savedeployconf SYNO_Hostname "$SYNO_Hostname"
  68. _savedeployconf SYNO_Port "$SYNO_Port"
  69. _debug2 SYNO_Scheme "$SYNO_Scheme"
  70. _debug2 SYNO_Hostname "$SYNO_Hostname"
  71. _debug2 SYNO_Port "$SYNO_Port"
  72. # Get the certificate description, but don't save it until we verify it's real
  73. _getdeployconf SYNO_Certificate
  74. _debug SYNO_Certificate "${SYNO_Certificate:-}"
  75. # shellcheck disable=SC1003 # We are not trying to escape a single quote
  76. if printf "%s" "$SYNO_Certificate" | grep '\\'; then
  77. _err "Do not use a backslash (\) in your certificate description"
  78. return 1
  79. fi
  80. _base_url="$SYNO_Scheme://$SYNO_Hostname:$SYNO_Port"
  81. _debug _base_url "$_base_url"
  82. _debug "Getting API version"
  83. response=$(_get "$_base_url/webapi/query.cgi?api=SYNO.API.Info&version=1&method=query&query=SYNO.API.Auth")
  84. api_path=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"path" *: *"\([^"]*\)".*/\1/p')
  85. api_version=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"maxVersion" *: *\([0-9]*\).*/\1/p')
  86. _debug3 response "$response"
  87. _debug3 api_path "$api_path"
  88. _debug3 api_version "$api_version"
  89. # Login, get the session ID & SynoToken from JSON
  90. _info "Logging into $SYNO_Hostname:$SYNO_Port"
  91. encoded_username="$(printf "%s" "$SYNO_Username" | _url_encode)"
  92. encoded_password="$(printf "%s" "$SYNO_Password" | _url_encode)"
  93. otp_code=""
  94. # START - DEPRECATED, only kept for legacy compatibility reasons
  95. if [ -n "$SYNO_TOTP_SECRET" ]; then
  96. _info "WARNING: Usage of SYNO_TOTP_SECRET is deprecated!"
  97. _info " See synology_dsm.sh script or ACME.sh Wiki page for details:"
  98. _info " https://github.com/acmesh-official/acme.sh/wiki/Synology-NAS-Guide"
  99. DEPRECATED_otp_code=""
  100. if _exists oathtool; then
  101. DEPRECATED_otp_code="$(oathtool --base32 --totp "${SYNO_TOTP_SECRET}" 2>/dev/null)"
  102. else
  103. _err "oathtool could not be found, install oathtool to use SYNO_TOTP_SECRET"
  104. return 1
  105. fi
  106. if [ -n "$SYNO_DID" ]; then
  107. _H1="Cookie: did=$SYNO_DID"
  108. export _H1
  109. _debug3 H1 "${_H1}"
  110. fi
  111. response=$(_post "method=login&account=$encoded_username&passwd=$encoded_password&api=SYNO.API.Auth&version=$api_version&enable_syno_token=yes&otp_code=$DEPRECATED_otp_code&device_name=certrenewal&device_id=$SYNO_DID" "$_base_url/webapi/auth.cgi?enable_syno_token=yes")
  112. _debug3 response "$response"
  113. # END - DEPRECATED, only kept for legacy compatibility reasons
  114. # Get device ID if still empty first, otherwise log in right away
  115. elif [ -z "${SYNO_Device_ID:-}" ]; then
  116. printf "Enter OTP code for user '%s': " "$SYNO_Username"
  117. read -r otp_code
  118. if [ -z "${SYNO_Device_Name:-}" ]; then
  119. printf "Enter device name or leave empty for default (CertRenewal): "
  120. read -r SYNO_Device_Name
  121. [ -n "${SYNO_Device_Name}" ] || SYNO_Device_Name="CertRenewal"
  122. fi
  123. response=$(_get "$_base_url/webapi/$api_path?api=SYNO.API.Auth&version=$api_version&method=login&format=sid&account=$encoded_username&passwd=$encoded_password&otp_code=$otp_code&enable_syno_token=yes&enable_device_token=yes&device_name=$SYNO_Device_Name")
  124. _secure_debug3 response "$response"
  125. id_property='device_id'
  126. [ "${api_version}" -gt '6' ] || id_property='did'
  127. SYNO_Device_ID=$(echo "$response" | grep "$id_property" | sed -n 's/.*"'$id_property'" *: *"\([^"]*\).*/\1/p')
  128. _secure_debug2 SYNO_Device_ID "$SYNO_Device_ID"
  129. else
  130. response=$(_get "$_base_url/webapi/$api_path?api=SYNO.API.Auth&version=$api_version&method=login&format=sid&account=$encoded_username&passwd=$encoded_password&enable_syno_token=yes&device_name=$SYNO_Device_Name&device_id=$SYNO_Device_ID")
  131. _debug3 response "$response"
  132. fi
  133. sid=$(echo "$response" | grep "sid" | sed -n 's/.*"sid" *: *"\([^"]*\).*/\1/p')
  134. token=$(echo "$response" | grep "synotoken" | sed -n 's/.*"synotoken" *: *"\([^"]*\).*/\1/p')
  135. _debug "Session ID" "$sid"
  136. _debug SynoToken "$token"
  137. if [ -z "$SYNO_DID" ] && [ -z "$SYNO_Device_ID" ] || [ -z "$sid" ] || [ -z "$token" ]; then
  138. _err "Unable to authenticate to $_base_url - check your username & password."
  139. _err "If two-factor authentication is enabled for the user, set SYNO_Device_ID."
  140. return 1
  141. fi
  142. _H1="X-SYNO-TOKEN: $token"
  143. export _H1
  144. _debug2 H1 "${_H1}"
  145. # Now that we know the username & password are good, save them
  146. _savedeployconf SYNO_Username "$SYNO_Username"
  147. _savedeployconf SYNO_Password "$SYNO_Password"
  148. _savedeployconf SYNO_Device_Name "$SYNO_Device_Name"
  149. _savedeployconf SYNO_Device_ID "$SYNO_Device_ID"
  150. _info "Getting certificates in Synology DSM"
  151. response=$(_post "api=SYNO.Core.Certificate.CRT&method=list&version=1&_sid=$sid" "$_base_url/webapi/entry.cgi")
  152. _debug3 response "$response"
  153. escaped_certificate="$(printf "%s" "$SYNO_Certificate" | sed 's/\([].*^$[]\)/\\\1/g;s/"/\\\\"/g')"
  154. _debug escaped_certificate "$escaped_certificate"
  155. id=$(echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\"id\":\"\([^\"]*\).*/\1/p")
  156. _debug2 id "$id"
  157. if [ -z "$id" ] && [ -z "${SYNO_Create:-}" ]; then
  158. _err "Unable to find certificate: $SYNO_Certificate & \$SYNO_Create is not set"
  159. return 1
  160. fi
  161. # We've verified this certificate description is a thing, so save it
  162. _savedeployconf SYNO_Certificate "$SYNO_Certificate" "base64"
  163. _info "Generate form POST request"
  164. nl="\0015\0012"
  165. delim="--------------------------$(_utc_date | tr -d -- '-: ')"
  166. content="--$delim${nl}Content-Disposition: form-data; name=\"key\"; filename=\"$(basename "$_ckey")\"${nl}Content-Type: application/octet-stream${nl}${nl}$(cat "$_ckey")\0012"
  167. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"cert\"; filename=\"$(basename "$_ccert")\"${nl}Content-Type: application/octet-stream${nl}${nl}$(cat "$_ccert")\0012"
  168. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"inter_cert\"; filename=\"$(basename "$_cca")\"${nl}Content-Type: application/octet-stream${nl}${nl}$(cat "$_cca")\0012"
  169. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"id\"${nl}${nl}$id"
  170. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"desc\"${nl}${nl}${SYNO_Certificate}"
  171. if echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\([^{]*\).*/\1/p" | grep -- 'is_default":true' >/dev/null; then
  172. _debug2 default "This is the default certificate"
  173. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"as_default\"${nl}${nl}true"
  174. else
  175. _debug2 default "This is NOT the default certificate"
  176. fi
  177. content="$content${nl}--$delim--${nl}"
  178. content="$(printf "%b_" "$content")"
  179. content="${content%_}" # protect trailing \n
  180. _info "Upload certificate to the Synology DSM"
  181. response=$(_post "$content" "$_base_url/webapi/entry.cgi?api=SYNO.Core.Certificate&method=import&version=1&SynoToken=$token&_sid=$sid" "" "POST" "multipart/form-data; boundary=${delim}")
  182. _debug3 response "$response"
  183. if ! echo "$response" | grep '"error":' >/dev/null; then
  184. if echo "$response" | grep '"restart_httpd":true' >/dev/null; then
  185. _info "Restarting HTTP services succeeded"
  186. else
  187. _info "Restarting HTTP services failed"
  188. fi
  189. _logout
  190. return 0
  191. else
  192. _err "Unable to update certificate, error code $response"
  193. _logout
  194. return 1
  195. fi
  196. }
  197. #################### Private functions below ##################################
  198. _logout() {
  199. # Logout CERT user only to not occupy a permanent session, e.g. in DSM's "Connected Users" widget (based on previous variables)
  200. response=$(_get "$_base_url/webapi/$api_path?api=SYNO.API.Auth&version=$api_version&method=logout&_sid=$sid")
  201. _debug3 response "$response"
  202. }