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.

384 lines
17 KiB

2 years 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. # 1. Set required environment variables:
  12. # - use automatically created temp admin user to authenticate
  13. # `export SYNO_UseTempAdmin=1`
  14. # - or provide your own admin user credential to authenticate
  15. # 1. `export SYNO_Username="adminUser"`
  16. # 2. `export SYNO_Password="adminPassword"`
  17. # 2. Set optional environment variables (shown values are the defaults)
  18. # - common optional variables
  19. # - `export SYNO_Scheme="http"`
  20. # - `export SYNO_Hostname="localhost"`
  21. # - `export SYNO_Port="5000"`
  22. # - `export SYNO_Create=1` - to allow creating the cert if it doesn't exist
  23. # - `export SYNO_Certificate=""` - to replace a specific cert by its
  24. # description
  25. # - 2FA-OTP optional variables (with your own admin user)
  26. # - `export SYNO_DeviceName=""` - required for 2FA-OTP, script won't require
  27. # interactive input the device name if set.
  28. # - `export SYNO_OTPCode=""` - required for 2FA-OTP, script won't require
  29. # interactive input the code if set.
  30. # - `export SYNO_DeviceID=""` - required for omitting 2FA-OTP (might be
  31. # deprecated, auth with OTP code instead)
  32. # 3. Run command:
  33. # `acme.sh --deploy --deploy-hook synology_dsm -d example.com``
  34. ################################################################################
  35. # Dependencies:
  36. # - curl
  37. # - synouser & synogroup (When available and SYNO_UseTempAdmin is set)
  38. ################################################################################
  39. # Return value:
  40. # 0 means success, otherwise error.
  41. ################################################################################
  42. ########## Public functions ####################################################
  43. #domain keyfile certfile cafile fullchain
  44. synology_dsm_deploy() {
  45. _cdomain="$1"
  46. _ckey="$2"
  47. _ccert="$3"
  48. _cca="$4"
  49. _debug _cdomain "$_cdomain"
  50. # Get username and password, but don't save until we authenticated successfully
  51. _getdeployconf SYNO_Username
  52. _getdeployconf SYNO_Password
  53. _getdeployconf SYNO_DeviceID
  54. _getdeployconf SYNO_DeviceName
  55. # ## START ## - DEPRECATED, for backward compatibility
  56. _getdeployconf SYNO_Device_ID
  57. _getdeployconf SYNO_Device_Name
  58. [ -n "$SYNO_DeviceID" ] || SYNO_DeviceID="${SYNO_Device_ID:-}"
  59. [ -n "$SYNO_DeviceName" ] || SYNO_DeviceName="${SYNO_Device_Name:-}"
  60. # ## END ## - DEPRECATED, for backward compatibility
  61. # Prepare to use temp admin if SYNO_UseTempAdmin is set
  62. _getdeployconf SYNO_UseTempAdmin
  63. _debug2 SYNO_UseTempAdmin "$SYNO_UseTempAdmin"
  64. # Back to use existing admin user if explicitly requested
  65. if [ "$SYNO_UseTempAdmin" == "0" ]; then
  66. _debug2 "Back to use existing user rather than temp admin user."
  67. SYNO_UseTempAdmin=""
  68. fi
  69. if [ -n "$SYNO_UseTempAdmin" ]; then
  70. if ! _exists synouser || ! _exists synogroup; then
  71. _err "Tools are missing for creating temp admin user, please set SYNO_Username and SYNO_Password instead."
  72. return 1
  73. fi
  74. [ -n "$SYNO_Username" ] || _savedeployconf SYNO_Username ""
  75. [ -n "$SYNO_Password" ] || _savedeployconf SYNO_Password ""
  76. _debug "Setting temp admin user credential..."
  77. SYNO_Username=sc-acmesh-tmp
  78. SYNO_Password=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16)
  79. # Set 2FA-OTP settings to empty consider they won't be needed.
  80. SYNO_DeviceID=
  81. SYNO_DeviceName=
  82. SYNO_OTPCode=
  83. # Pre-delete temp admin user if already exists.
  84. synouser --del "$SYNO_Username" >/dev/null 2>/dev/null
  85. else
  86. _debug2 SYNO_Username "$SYNO_Username"
  87. _secure_debug2 SYNO_Password "$SYNO_Password"
  88. _debug2 SYNO_DeviceName "$SYNO_DeviceName"
  89. _secure_debug2 SYNO_DeviceID "$SYNO_DeviceID"
  90. fi
  91. if [ -z "$SYNO_Username" ] || [ -z "$SYNO_Password" ]; then
  92. _err "You must set either SYNO_UseTempAdmin, or set both SYNO_Username and SYNO_Password."
  93. return 1
  94. fi
  95. # Optional scheme, hostname and port for Synology DSM
  96. _getdeployconf SYNO_Scheme
  97. _getdeployconf SYNO_Hostname
  98. _getdeployconf SYNO_Port
  99. # Default values for scheme, hostname and port
  100. # Defaulting to localhost and http, because it's localhost…
  101. [ -n "$SYNO_Scheme" ] || SYNO_Scheme="http"
  102. [ -n "$SYNO_Hostname" ] || SYNO_Hostname="localhost"
  103. [ -n "$SYNO_Port" ] || SYNO_Port="5000"
  104. _savedeployconf SYNO_Scheme "$SYNO_Scheme"
  105. _savedeployconf SYNO_Hostname "$SYNO_Hostname"
  106. _savedeployconf SYNO_Port "$SYNO_Port"
  107. _debug2 SYNO_Scheme "$SYNO_Scheme"
  108. _debug2 SYNO_Hostname "$SYNO_Hostname"
  109. _debug2 SYNO_Port "$SYNO_Port"
  110. # Get the certificate description, but don't save it until we verify it's real
  111. _getdeployconf SYNO_Certificate
  112. _debug SYNO_Certificate "${SYNO_Certificate:-}"
  113. # shellcheck disable=SC1003 # We are not trying to escape a single quote
  114. if printf "%s" "$SYNO_Certificate" | grep '\\'; then
  115. _err "Do not use a backslash (\) in your certificate description"
  116. return 1
  117. fi
  118. _debug "Getting API version..."
  119. _base_url="$SYNO_Scheme://$SYNO_Hostname:$SYNO_Port"
  120. _debug _base_url "$_base_url"
  121. response=$(_get "$_base_url/webapi/query.cgi?api=SYNO.API.Info&version=1&method=query&query=SYNO.API.Auth")
  122. api_path=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"path" *: *"\([^"]*\)".*/\1/p')
  123. api_version=$(echo "$response" | grep "SYNO.API.Auth" | sed -n 's/.*"maxVersion" *: *\([0-9]*\).*/\1/p')
  124. _debug3 response "$response"
  125. _debug3 api_path "$api_path"
  126. _debug3 api_version "$api_version"
  127. # Login, get the session ID and SynoToken from JSON
  128. _info "Logging into $SYNO_Hostname:$SYNO_Port..."
  129. encoded_username="$(printf "%s" "$SYNO_Username" | _url_encode)"
  130. encoded_password="$(printf "%s" "$SYNO_Password" | _url_encode)"
  131. # ## START ## - DEPRECATED, for backward compatibility
  132. _getdeployconf SYNO_TOTP_SECRET
  133. if [ -n "$SYNO_TOTP_SECRET" ]; then
  134. _info "WARNING: Usage of SYNO_TOTP_SECRET is deprecated!"
  135. _info " See synology_dsm.sh script or ACME.sh Wiki page for details:"
  136. _info " https://github.com/acmesh-official/acme.sh/wiki/Synology-NAS-Guide"
  137. if ! _exists oathtool; then
  138. _err "oathtool could not be found, install oathtool to use SYNO_TOTP_SECRET"
  139. return 1
  140. fi
  141. DEPRECATED_otp_code="$(oathtool --base32 --totp "$SYNO_TOTP_SECRET" 2>/dev/null)"
  142. if [ -z "$SYNO_DeviceID" ]; then
  143. _getdeployconf SYNO_DID
  144. [ -n "$SYNO_DID" ] || SYNO_DeviceID="$SYNO_DID"
  145. fi
  146. if [ -n "$SYNO_DeviceID" ]; then
  147. _H1="Cookie: did=$SYNO_DeviceID"
  148. export _H1
  149. _debug3 H1 "${_H1}"
  150. fi
  151. 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_DeviceID" "$_base_url/webapi/auth.cgi?enable_syno_token=yes")
  152. _debug3 response "$response"
  153. # ## END ## - DEPRECATED, for backward compatibility
  154. # If SYNO_DeviceID or SYNO_OTPCode is set, we treat current account enabled 2FA-OTP.
  155. # Notice that if SYNO_UseTempAdmin=1, both variables will be unset
  156. else
  157. if [ -n "$SYNO_DeviceID" ] || [ -n "$SYNO_OTPCode" ]; then
  158. response='{"error":{"code":403}}'
  159. # Assume the current account disabled 2FA-OTP, try to log in right away.
  160. else
  161. if [ -n "$SYNO_UseTempAdmin" ]; then
  162. _debug "Creating temp admin user in Synology DSM..."
  163. synouser --add "$SYNO_Username" "$SYNO_Password" "" 0 "scruelt@hotmail.com" 0 >/dev/null
  164. if synogroup --help | grep -q '\-\-memberadd'; then
  165. synogroup --memberadd administrators "$SYNO_Username" >/dev/null
  166. else
  167. # For supporting DSM 6.x which only has `--member` parameter.
  168. cur_admins=$(synogroup --get administrators | awk -F '[][]' '/Group Members/,0{if(NF>1)printf "%s ", $2}')
  169. _secure_debug3 admin_users "$cur_admins$SYNO_Username"
  170. # shellcheck disable=SC2086
  171. synogroup --member administrators $cur_admins $SYNO_Username >/dev/null
  172. fi
  173. # havig a workaround to temporary disable enforce 2FA-OTP
  174. otp_enforce_option=$(synogetkeyvalue /etc/synoinfo.conf otp_enforce_option)
  175. if [ -n "$otp_enforce_option" ] && [ "${otp_enforce_option:-"none"}" != "none" ]; then
  176. synosetkeyvalue /etc/synoinfo.conf otp_enforce_option none
  177. _info "Temporary disabled enforce 2FA-OTP to complete authentication."
  178. _info "previous_otp_enforce_option" "$otp_enforce_option"
  179. else
  180. otp_enforce_option=""
  181. fi
  182. fi
  183. 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")
  184. if [ -n "$SYNO_UseTempAdmin" ] && [ -n "$otp_enforce_option" ]; then
  185. synosetkeyvalue /etc/synoinfo.conf otp_enforce_option "$otp_enforce_option"
  186. _info "Restored previous enforce 2FA-OTP option."
  187. fi
  188. _debug3 response "$response"
  189. fi
  190. fi
  191. error_code=$(echo "$response" | grep '"error"' | grep -oP '(?<="code":)\d+')
  192. # Account has 2FA-OTP enabled, since error 403 reported.
  193. # https://global.download.synology.com/download/Document/Software/DeveloperGuide/Firmware/DSM/All/enu/Synology_DiskStation_Administration_CLI_Guide.pdf
  194. if [ "$error_code" == "403" ]; then
  195. if [ -z "$SYNO_DeviceName" ]; then
  196. printf "Enter device name or leave empty for default (CertRenewal): "
  197. read -r SYNO_DeviceName
  198. [ -n "$SYNO_DeviceName" ] || SYNO_DeviceName="CertRenewal"
  199. fi
  200. if [ -n "$SYNO_DeviceID" ]; then
  201. # Omit OTP code with SYNO_DeviceID.
  202. 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_DeviceName&device_id=$SYNO_DeviceID")
  203. _secure_debug3 response "$response"
  204. else
  205. # Require the OTP code if still unset.
  206. if [ -z "$SYNO_OTPCode" ]; then
  207. printf "Enter OTP code for user '%s': " "$SYNO_Username"
  208. read -r SYNO_OTPCode
  209. fi
  210. if [ -z "$SYNO_OTPCode" ]; then
  211. response='{"error":{"code":404}}'
  212. else
  213. 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&enable_device_token=yes&device_name=$SYNO_DeviceName&otp_code=$SYNO_OTPCode")
  214. _secure_debug3 response "$response"
  215. id_property='device_id'
  216. [ "${api_version}" -gt '6' ] || id_property='did'
  217. SYNO_DeviceID=$(echo "$response" | grep "$id_property" | sed -n 's/.*"'$id_property'" *: *"\([^"]*\).*/\1/p')
  218. _secure_debug2 SYNO_DeviceID "$SYNO_DeviceID"
  219. fi
  220. fi
  221. error_code=$(echo "$response" | grep '"error"' | grep -oP '(?<="code":)\d+')
  222. fi
  223. if [ -n "$error_code" ]; then
  224. if [ "$error_code" == "403" ] && [ -n "$SYNO_DeviceID" ]; then
  225. _savedeployconf SYNO_DeviceID ""
  226. _err "Failed to authenticate with SYNO_DeviceID (may expired or invalid), please try again in a new terminal window."
  227. elif [ "$error_code" == "404" ]; then
  228. _err "Failed to authenticate with provided 2FA-OTP code, please try again in a new terminal window."
  229. elif [ "$error_code" == "406" ]; then
  230. if [ -n "$SYNO_UseTempAdmin" ]; then
  231. _err "SYNO_UseTempAdmin=1 is not supported if enforce auth with 2FA-OTP is enabled."
  232. else
  233. _err "Enforce auth with 2FA-OTP enabled, please configure the user to enable 2FA-OTP to continue."
  234. fi
  235. elif [ "$error_code" == "400" ] || [ "$error_code" == "401" ] || [ "$error_code" == "408" ] || [ "$error_code" == "409" ] || [ "$error_code" == "410" ]; then
  236. _err "Failed to authenticate with a non-existent or disabled account, or the account password is incorrect or has expired."
  237. else
  238. _err "Failed to authenticate with error: $error_code."
  239. fi
  240. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  241. return 1
  242. fi
  243. sid=$(echo "$response" | grep "sid" | sed -n 's/.*"sid" *: *"\([^"]*\).*/\1/p')
  244. token=$(echo "$response" | grep "synotoken" | sed -n 's/.*"synotoken" *: *"\([^"]*\).*/\1/p')
  245. _debug "Session ID" "$sid"
  246. _debug SynoToken "$token"
  247. if [ -z "$sid" ] || [ -z "$token" ]; then
  248. # Still can't get necessary info even got no errors, may Synology have API updated?
  249. _err "Unable to authenticate to $_base_url, you may report the full log to the community."
  250. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  251. return 1
  252. fi
  253. _H1="X-SYNO-TOKEN: $token"
  254. export _H1
  255. _debug2 H1 "${_H1}"
  256. # Now that we know the username and password are good, save them if not in temp admin mode.
  257. if [ -n "$SYNO_UseTempAdmin" ]; then
  258. _savedeployconf SYNO_Username ""
  259. _savedeployconf SYNO_Password ""
  260. _savedeployconf SYNO_UseTempAdmin "$SYNO_UseTempAdmin"
  261. else
  262. _savedeployconf SYNO_Username "$SYNO_Username"
  263. _savedeployconf SYNO_Password "$SYNO_Password"
  264. fi
  265. _savedeployconf SYNO_DeviceID "$SYNO_DeviceID"
  266. _savedeployconf SYNO_DeviceName "$SYNO_DeviceName"
  267. _info "Getting certificates in Synology DSM..."
  268. response=$(_post "api=SYNO.Core.Certificate.CRT&method=list&version=1&_sid=$sid" "$_base_url/webapi/entry.cgi")
  269. _debug3 response "$response"
  270. escaped_certificate="$(printf "%s" "$SYNO_Certificate" | sed 's/\([].*^$[]\)/\\\1/g;s/"/\\\\"/g')"
  271. _debug escaped_certificate "$escaped_certificate"
  272. id=$(echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\"id\":\"\([^\"]*\).*/\1/p")
  273. _debug2 id "$id"
  274. error_code=$(echo "$response" | grep '"error"' | grep -oP '(?<="code":)\d+')
  275. if [ -n "$error_code" ]; then
  276. if [ "$error_code" -eq 105 ]; then
  277. _err "Current user is not administrator and does not have sufficient permission for deploying."
  278. else
  279. _err "Failed to fetch certificate info with error: $error_code, contact Synology for more info about it."
  280. fi
  281. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  282. return 1
  283. fi
  284. _getdeployconf SYNO_Create
  285. _debug2 SYNO_Create "$SYNO_Create"
  286. [ -n "$SYNO_Create" ] || SYNO_Create=1
  287. if [ -z "$id" ] && [ -z "$SYNO_Create" ]; then
  288. _err "Unable to find certificate: $SYNO_Certificate and $SYNO_Create is not set."
  289. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  290. return 1
  291. fi
  292. # We've verified this certificate description is a thing, so save it
  293. _savedeployconf SYNO_Certificate "$SYNO_Certificate" "base64"
  294. _info "Generating form POST request..."
  295. nl="\0015\0012"
  296. delim="--------------------------$(_utc_date | tr -d -- '-: ')"
  297. content="--$delim${nl}Content-Disposition: form-data; name=\"key\"; filename=\"$(basename "$_ckey")\"${nl}Content-Type: application/octet-stream${nl}${nl}$(cat "$_ckey")\0012"
  298. 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"
  299. 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"
  300. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"id\"${nl}${nl}$id"
  301. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"desc\"${nl}${nl}${SYNO_Certificate}"
  302. if echo "$response" | sed -n "s/.*\"desc\":\"$escaped_certificate\",\([^{]*\).*/\1/p" | grep -- 'is_default":true' >/dev/null; then
  303. _debug2 default "This is the default certificate"
  304. content="$content${nl}--$delim${nl}Content-Disposition: form-data; name=\"as_default\"${nl}${nl}true"
  305. else
  306. _debug2 default "This is NOT the default certificate"
  307. fi
  308. content="$content${nl}--$delim--${nl}"
  309. content="$(printf "%b_" "$content")"
  310. content="${content%_}" # protect trailing \n
  311. _info "Upload certificate to the Synology DSM."
  312. 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}")
  313. _debug3 response "$response"
  314. if ! echo "$response" | grep '"error":' >/dev/null; then
  315. if echo "$response" | grep '"restart_httpd":true' >/dev/null; then
  316. _info "Restart HTTP services succeeded."
  317. else
  318. _info "Restart HTTP services failed."
  319. fi
  320. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  321. _logout
  322. return 0
  323. else
  324. _temp_admin_cleanup "$SYNO_UseTempAdmin" "$SYNO_Username"
  325. _err "Unable to update certificate, got error response: $response."
  326. _logout
  327. return 1
  328. fi
  329. }
  330. #################### Private functions below ##################################
  331. _logout() {
  332. # Logout CERT user only to not occupy a permanent session, e.g. in DSM's "Connected Users" widget (based on previous variables)
  333. response=$(_get "$_base_url/webapi/$api_path?api=SYNO.API.Auth&version=$api_version&method=logout&_sid=$sid")
  334. _debug3 response "$response"
  335. }
  336. _temp_admin_cleanup() {
  337. flag=$1
  338. username=$2
  339. if [ -n "${flag}" ]; then
  340. _debug "Cleanuping temp admin info..."
  341. synouser --del "$username" >/dev/null
  342. fi
  343. }