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.

275 lines
13 KiB

1 year ago
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. # - Create temp admin user automatically:
  12. # export SYNO_USE_TEMP_ADMIN=1
  13. # - Or provide your own admin user credential:
  14. # 1. export SYNO_Username="adminUser"
  15. # 2. export SYNO_Password="adminPassword"
  16. # Optional exports (shown values are the defaults):
  17. # - export SYNO_Certificate="" - to replace a specific certificate via description
  18. # - export SYNO_Scheme="http"
  19. # - export SYNO_Hostname="localhost"
  20. # - export SYNO_Port="5000"
  21. # - export SYNO_Create=1 - to allow creating the certificate if it doesn't exist
  22. # - export SYNO_Device_Name="CertRenewal" - required if 2FA-OTP enabled
  23. # - export SYNO_Device_ID="" - required for skipping 2FA-OTP
  24. # 3. acme.sh --deploy --deploy-hook synology_dsm -d example.com
  25. ################################################################################
  26. # Dependencies:
  27. # - jq & curl
  28. # - synouser & synogroup (When available and SYNO_USE_TEMP_ADMIN is set)
  29. ################################################################################
  30. # Return value:
  31. # 0 means success, otherwise error.
  32. ################################################################################
  33. ########## Public functions ####################################################
  34. #domain keyfile certfile cafile fullchain
  35. synology_dsm_deploy() {
  36. _cdomain="$1"
  37. _ckey="$2"
  38. _ccert="$3"
  39. _cca="$4"
  40. _debug _cdomain "$_cdomain"
  41. # Get username & password, but don't save until we authenticated successfully
  42. _getdeployconf SYNO_USE_TEMP_ADMIN
  43. _getdeployconf SYNO_Username
  44. _getdeployconf SYNO_Password
  45. _getdeployconf SYNO_Create
  46. _getdeployconf SYNO_DID
  47. _getdeployconf SYNO_TOTP_SECRET
  48. _getdeployconf SYNO_Device_Name
  49. _getdeployconf SYNO_Device_ID
  50. # Prepare temp admin user info if SYNO_USE_TEMP_ADMIN is set
  51. if [ -n "${SYNO_USE_TEMP_ADMIN:-}" ]; then
  52. if ! _exists synouser; then
  53. if ! _exists synogroup; then
  54. _err "Tools are missing for creating temp admin user, please set SYNO_Username & SYNO_Password instead."
  55. return 1
  56. fi
  57. fi
  58. _debug "Setting temp admin user credential..."
  59. SYNO_Username=sc-acmesh-tmp
  60. SYNO_Password=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16)
  61. # Ignore 2FA-OTP settings which won't be needed.
  62. SYNO_Device_Name=
  63. SYNO_Device_ID=
  64. fi
  65. if [ -z "${SYNO_Username:-}" ] || [ -z "${SYNO_Password:-}" ]; then
  66. _err "You must set either SYNO_USE_TEMP_ADMIN, or set both SYNO_Username and SYNO_Password."
  67. return 1
  68. fi
  69. _debug2 SYNO_Username "$SYNO_Username"
  70. _secure_debug2 SYNO_Password "$SYNO_Password"
  71. _debug2 SYNO_Create "$SYNO_Create"
  72. _debug2 SYNO_Device_Name "$SYNO_Device_Name"
  73. _secure_debug2 SYNO_Device_ID "$SYNO_Device_ID"
  74. # Optional scheme, hostname & port for Synology DSM
  75. _getdeployconf SYNO_Scheme
  76. _getdeployconf SYNO_Hostname
  77. _getdeployconf SYNO_Port
  78. # Default values for scheme, hostname & port
  79. # Defaulting to localhost & http, because it's localhost…
  80. [ -n "${SYNO_Scheme}" ] || SYNO_Scheme="http"
  81. [ -n "${SYNO_Hostname}" ] || SYNO_Hostname="localhost"
  82. [ -n "${SYNO_Port}" ] || SYNO_Port="5000"
  83. _savedeployconf SYNO_USE_TEMP_ADMIN "$SYNO_USE_TEMP_ADMIN"
  84. _savedeployconf SYNO_Scheme "$SYNO_Scheme"
  85. _savedeployconf SYNO_Hostname "$SYNO_Hostname"
  86. _savedeployconf SYNO_Port "$SYNO_Port"
  87. _debug2 SYNO_Scheme "$SYNO_Scheme"
  88. _debug2 SYNO_Hostname "$SYNO_Hostname"
  89. _debug2 SYNO_Port "$SYNO_Port"
  90. # Get the certificate description, but don't save it until we verify it's real
  91. _getdeployconf SYNO_Certificate
  92. _debug SYNO_Certificate "${SYNO_Certificate:-}"
  93. # shellcheck disable=SC1003 # We are not trying to escape a single quote
  94. if printf "%s" "$SYNO_Certificate" | grep '\\'; then
  95. _err "Do not use a backslash (\) in your certificate description"
  96. return 1
  97. fi
  98. _base_url="$SYNO_Scheme://$SYNO_Hostname:$SYNO_Port"
  99. _debug _base_url "$_base_url"
  100. _debug "Getting API version"
  101. response=$(_get "$_base_url/webapi/query.cgi?api=SYNO.API.Info&version=1&method=query&query=SYNO.API.Auth")
  102. api_path=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"path" *: *"\([^"]*\)".*/\1/p')
  103. api_version=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"maxVersion" *: *\([0-9]*\).*/\1/p')
  104. _debug3 response "$response"
  105. _debug3 api_path "$api_path"
  106. _debug3 api_version "$api_version"
  107. # Login, get the session ID & SynoToken from JSON
  108. _info "Logging into $SYNO_Hostname:$SYNO_Port"
  109. encoded_username="$(printf "%s" "$SYNO_Username" | _url_encode)"
  110. encoded_password="$(printf "%s" "$SYNO_Password" | _url_encode)"
  111. otp_code=""
  112. # START - DEPRECATED, only kept for legacy compatibility reasons
  113. if [ -n "$SYNO_TOTP_SECRET" ]; then
  114. _info "WARNING: Usage of SYNO_TOTP_SECRET is deprecated!"
  115. _info " See synology_dsm.sh script or ACME.sh Wiki page for details:"
  116. _info " https://github.com/acmesh-official/acme.sh/wiki/Synology-NAS-Guide"
  117. if ! _exists oathtool; then
  118. _err "oathtool could not be found, install oathtool to use SYNO_TOTP_SECRET"
  119. return 1
  120. fi
  121. DEPRECATED_otp_code="$(oathtool --base32 --totp "${SYNO_TOTP_SECRET}" 2>/dev/null)"
  122. if [ -n "$SYNO_DID" ]; then
  123. _H1="Cookie: did=$SYNO_DID"
  124. export _H1
  125. _debug3 H1 "${_H1}"
  126. fi
  127. 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")
  128. _debug3 response "$response"
  129. # END - DEPRECATED, only kept for legacy compatibility reasons
  130. # If SYNO_DeviceDevice_ID & SYNO_Device_Name both empty, just log in normally
  131. elif [ -z "${SYNO_Device_ID:-}" ] && [ -z "${SYNO_Device_Name:-}" ]; then
  132. if [ -n "$SYNO_USE_TEMP_ADMIN" ]; then
  133. _debug "Creating temp admin user in Synology DSM"
  134. synouser --del "$SYNO_Username" >/dev/null 2>/dev/null
  135. synouser --add "$SYNO_Username" "$SYNO_Password" "" 0 "" 0 >/dev/null
  136. synogroup --memberadd administrators "$SYNO_Username" >/dev/null
  137. fi
  138. response=$(_get "$_base_url/webapi/entry.cgi?api=SYNO.API.Auth&version=$api_version&method=login&format=sid&account=$encoded_username&passwd=$encoded_password&enable_syno_token=yes")
  139. _debug3 response "$response"
  140. # Get device ID if still empty first, otherwise log in right away
  141. # If SYNO_Device_Name is set, we treat that account enabled two-factor authorization, consider SYNO_Device_ID is not set, so it won't be able to login without requiring the OTP code.
  142. elif [ -n "${SYNO_Device_Name:-}" ] && [ -z "${SYNO_Device_ID:-}" ]; then
  143. printf "Enter OTP code for user '%s': " "$SYNO_Username"
  144. read -r otp_code
  145. 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")
  146. _secure_debug3 response "$response"
  147. id_property='device_id'
  148. [ "${api_version}" -gt '6' ] || id_property='did'
  149. SYNO_Device_ID=$(echo "$response" | grep "$id_property" | sed -n 's/.*"'$id_property'" *: *"\([^"]*\).*/\1/p')
  150. _secure_debug2 SYNO_Device_ID "$SYNO_Device_ID"
  151. # Otherwise, if SYNO_Device_ID is set, we can just use it to login.
  152. else
  153. if [ -z "${SYNO_Device_Name:-}" ]; then
  154. printf "Enter device name or leave empty for default (CertRenewal): "
  155. read -r SYNO_Device_Name
  156. [ -n "${SYNO_Device_Name}" ] || SYNO_Device_Name="CertRenewal"
  157. fi
  158. 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")
  159. _secure_debug3 response "$response"
  160. fi
  161. sid=$(echo "$response" | grep "sid" | sed -n 's/.*"sid" *: *"\([^"]*\).*/\1/p')
  162. token=$(echo "$response" | grep "synotoken" | sed -n 's/.*"synotoken" *: *"\([^"]*\).*/\1/p')
  163. _debug "Session ID" "$sid"
  164. _debug SynoToken "$token"
  165. if [ -z "$sid" ] || [ -z "$token" ]; then
  166. _err "Unable to authenticate to $_base_url - check your username & password."
  167. _err "If two-factor authentication is enabled for the user:"
  168. _err "- set SYNO_Device_Name then input *correct* OTP-code manually"
  169. _err "- get & set SYNO_Device_ID via your browser cookies"
  170. _remove_temp_admin "$SYNO_USE_TEMP_ADMIN" "$SYNO_Username"
  171. return 1
  172. fi
  173. _H1="X-SYNO-TOKEN: $token"
  174. export _H1
  175. _debug2 H1 "${_H1}"
  176. # Now that we know the username & password are good, save them
  177. _savedeployconf SYNO_Username "$SYNO_Username"
  178. _savedeployconf SYNO_Password "$SYNO_Password"
  179. if [ -z "${SYNO_USE_TEMP_ADMIN:-}" ]; then
  180. _savedeployconf SYNO_Device_Name "$SYNO_Device_Name"
  181. _savedeployconf SYNO_Device_ID "$SYNO_Device_ID"
  182. fi
  183. _info "Getting certificates in Synology DSM"
  184. response=$(_post "api=SYNO.Core.Certificate.CRT&method=list&version=1&_sid=$sid" "$_base_url/webapi/entry.cgi")
  185. _debug3 response "$response"
  186. escaped_certificate="$(printf "%s" "$SYNO_Certificate" | sed 's/\([].*^$[]\)/\\\1/g;s/"/\\\\"/g')"
  187. _debug escaped_certificate "$escaped_certificate"
  188. id=$(echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\"id\":\"\([^\"]*\).*/\1/p")
  189. _debug2 id "$id"
  190. if [ -z "$id" ] && [ -z "${SYNO_Create:-}" ]; then
  191. _err "Unable to find certificate: $SYNO_Certificate & \$SYNO_Create is not set"
  192. _remove_temp_admin "$SYNO_USE_TEMP_ADMIN" "$SYNO_Username"
  193. return 1
  194. fi
  195. # We've verified this certificate description is a thing, so save it
  196. _savedeployconf SYNO_Certificate "$SYNO_Certificate" "base64"
  197. _info "Generate form POST request"
  198. nl="\0015\0012"
  199. delim="--------------------------$(_utc_date | tr -d -- '-: ')"
  200. content="--$delim${nl}Content-Disposition: form-data; name=\"key\"; filename=\"$(basename "$_ckey")\"${nl}Content-Type: application/octet-stream${nl}${nl}$(cat "$_ckey")\0012"
  201. 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"
  202. 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"
  203. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"id\"${nl}${nl}$id"
  204. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"desc\"${nl}${nl}${SYNO_Certificate}"
  205. if echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\([^{]*\).*/\1/p" | grep -- 'is_default":true' >/dev/null; then
  206. _debug2 default "This is the default certificate"
  207. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"as_default\"${nl}${nl}true"
  208. else
  209. _debug2 default "This is NOT the default certificate"
  210. fi
  211. content="$content${nl}--$delim--${nl}"
  212. content="$(printf "%b_" "$content")"
  213. content="${content%_}" # protect trailing \n
  214. _info "Upload certificate to the Synology DSM"
  215. 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}")
  216. _debug3 response "$response"
  217. if ! echo "$response" | grep '"error":' >/dev/null; then
  218. if echo "$response" | grep '"restart_httpd":true' >/dev/null; then
  219. _info "Restarting HTTP services succeeded"
  220. else
  221. _info "Restarting HTTP services failed"
  222. fi
  223. _remove_temp_admin "$SYNO_USE_TEMP_ADMIN" "$SYNO_Username"
  224. _logout
  225. return 0
  226. else
  227. _remove_temp_admin "$SYNO_USE_TEMP_ADMIN" "$SYNO_Username"
  228. _err "Unable to update certificate, error code $response"
  229. _logout
  230. return 1
  231. fi
  232. }
  233. #################### Private functions below ##################################
  234. _logout() {
  235. # Logout CERT user only to not occupy a permanent session, e.g. in DSM's "Connected Users" widget (based on previous variables)
  236. response=$(_get "$_base_url/webapi/$api_path?api=SYNO.API.Auth&version=$api_version&method=logout&_sid=$sid")
  237. _debug3 response "$response"
  238. }
  239. _remove_temp_admin() {
  240. flag=$1
  241. username=$2
  242. if [ -n "${flag}" ]; then
  243. _debug "Removing temp admin user in Synology DSM"
  244. synouser --del "$username" >/dev/null
  245. fi
  246. }