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.

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