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.

391 lines
15 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #!/usr/bin/env sh
  2. ## Name: dns_pleskxml.sh
  3. ## Created by Stilez.
  4. ## Also uses some code from PR#1832 by @romanlum (https://github.com/Neilpang/acme.sh/pull/1832/files)
  5. ## This DNS01 method uses the Plesk XML API described at:
  6. ## https://docs.plesk.com/en-US/12.5/api-rpc/about-xml-api.28709
  7. ## and more specifically: https://docs.plesk.com/en-US/12.5/api-rpc/reference.28784
  8. ## Note: a DNS ID with host = empty string is OK for this API, see
  9. ## https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-dns/managing-dns-records/adding-dns-record.34798
  10. ## For example, to add a TXT record to DNS alias domain "acme-alias.com" would be a valid Plesk action.
  11. ## So this API module can handle such a request, if needed.
  12. ## The plesk plugin uses the xml api to add and remvoe the dns records. Therefore the url, username
  13. ## and password have to be configured by the user before this module is called.
  14. ##
  15. ## ```
  16. ## export pleskxml_uri="https://YOUR_PLESK_URI_HERE:8443/enterprise/control/agent.php"
  17. ## (or probably something similar)
  18. ## export pleskxml_user="plesk username"
  19. ## export pleskxml_pass="plesk password"
  20. ## ```
  21. ## Ok, let's issue a cert now:
  22. ## ```
  23. ## acme.sh --issue --dns dns_pleskxml -d example.com -d www.example.com
  24. ## ```
  25. ##
  26. ## The `pleskxml_uri`, `pleskxml_user` and `pleskxml_pass` will be saved in `~/.acme.sh/account.conf` and reused when needed.
  27. #################### INTERNAL VARIABLES + NEWLINE + API TEMPLATES ##################################
  28. pleskxml_init_checks_done=0
  29. # Variable containing bare newline - not a style issue
  30. # shellcheck disable=SC1004
  31. NEWLINE='\
  32. '
  33. pleskxml_tplt_get_domains="<packet><customer><get-domain-list><filter/></get-domain-list></customer></packet>"
  34. # Get a list of domains that PLESK can manage, so we can check root domain + host for acme.sh
  35. # Also used to test credentials and URI.
  36. # No args.
  37. pleskxml_tplt_get_dns_records="<packet><dns><get_rec><filter><site-id>%s</site-id></filter></get_rec></dns></packet>"
  38. # Get all DNS records for a Plesk domain ID.
  39. # ARG = Plesk domain id to query
  40. pleskxml_tplt_add_txt_record="<packet><dns><add_rec><site-id>%s</site-id><type>TXT</type><host>%s</host><value>%s</value></add_rec></dns></packet>"
  41. # Add a TXT record to a domain.
  42. # ARGS = (1) Plesk internal domain ID, (2) "hostname" for the new record, eg '_acme_challenge', (3) TXT record value
  43. pleskxml_tplt_rmv_dns_record="<packet><dns><del_rec><filter><id>%s</id></filter></del_rec></dns></packet>"
  44. # Add a TXT record to a domain.
  45. # ARG = the Plesk internal ID for the dns record to be deleted
  46. #################### Public functions ##################################
  47. #Usage: add _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
  48. dns_pleskxml_add() {
  49. fulldomain=$1
  50. txtvalue=$2
  51. _info "Entering dns_pleskxml_add() to add TXT record '$2' to domain '$1'..."
  52. # Get credentials if not already checked, and confirm we can log in to Plesk XML API
  53. if ! _credential_check; then
  54. return 1
  55. fi
  56. # Get root and subdomain details, and Plesk domain ID
  57. if ! _pleskxml_get_root_domain "$fulldomain"; then
  58. return 1
  59. fi
  60. _debug 'Credentials OK, and domain identified. Calling Plesk XML API to add TXT record'
  61. # printf using template in a variable - not a style issue
  62. # shellcheck disable=SC2059
  63. request="$(printf "$pleskxml_tplt_add_txt_record" "$root_domain_id" "$sub_domain_name" "$txtvalue")"
  64. if ! _call_api "$request"; then
  65. return 1
  66. fi
  67. # OK, we should have added a TXT record. Let's check and return success if so.
  68. # All that should be left in the result, is one section, containing <result><status>ok</status><id>NEW_DNS_RECORD_ID</id></result>
  69. results="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>')"
  70. if ! _value "$results" | grep '<status>ok</status>' | grep -qE '<id>[0-9]+</id>'; then
  71. # Error - doesn't contain expected string. Something's wrong.
  72. _err 'Error when calling Plesk XML API.'
  73. _err 'The result did not contain the expected <id>XXXXX</id> section, or contained other values as well.'
  74. _err 'This is unexpected: something has gone wrong.'
  75. _err 'The full response was:\n' "$pleskxml_prettyprint_result"
  76. return 1
  77. fi
  78. recid="$(_value "$results" | grep -E '<id>[0-9]+</id>' | sed -E 's/^.*<id>([0-9]+)<\/id>.*$/\1/')"
  79. _info "Success. TXT record appears to be correctly added (Plesk record ID=$recid). Exiting dns_pleskxml_add()."
  80. return 0
  81. }
  82. #Usage: rm _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
  83. dns_pleskxml_rm() {
  84. fulldomain=$1
  85. txtvalue=$2
  86. _info "Entering dns_pleskxml_rm() to remove TXT record '$2' from domain '$1'..."
  87. # Get credentials if not already checked, and confirm we can log in to Plesk XML API
  88. if ! _credential_check; then
  89. return 1
  90. fi
  91. # Get root and subdomain details, and Plesk domain ID
  92. if ! _pleskxml_get_root_domain "$fulldomain"; then
  93. return 1
  94. fi
  95. _debug 'Credentials OK, and domain identified. Calling Plesk XML API to get list of TXT records and their IDs'
  96. # printf using template in a variable - not a style issue
  97. # shellcheck disable=SC2059
  98. request="$(printf "$pleskxml_tplt_get_dns_records" "$root_domain_id")"
  99. if ! _call_api "$request"; then
  100. return 1
  101. fi
  102. # Reduce output to one line per DNS record, filtered for TXT records with a record ID only (which they should all have)
  103. reclist="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>ok</status>' \
  104. | grep "<site-id>${root_domain_id}</site-id>" \
  105. | grep -E '<id>[0-9]+</id>' \
  106. | grep '<type>TXT</type>'
  107. )"
  108. if [ -z "$reclist" ]; then
  109. _err "No TXT records found for root domain ${root_domain_name} (Plesk domain ID ${root_domain_id}). Exiting."
  110. return 1
  111. fi
  112. _debug "Got list of DNS TXT records for root domain '$root_domain_name'"':\n'"$reclist"
  113. recid="$(_value "$reclist" \
  114. | grep "<host>$1.</host>" \
  115. | grep "<value>$txtvalue</value>" \
  116. | sed -E 's/(^.*<id>|<\/id>.*$)//g'
  117. )"
  118. _debug "List of DNS TXT records for host:"'\n'"$(_value "$reclist" | grep "<host>$1.</host>")"
  119. if ! _value "$recid" | grep -Eq '^[0-9]+$'; then
  120. _err "DNS records for root domain '${root_domain_name}' (Plesk ID ${root_domain_id}) + host '${sub_domain_name}' do not contain the TXT record '${txtvalue}'"
  121. _err "Cannot delete TXT record. Exiting."
  122. return 1
  123. fi
  124. _debug "Found Plesk record ID for target text string '${txtvalue}': ID=${recid}"
  125. _debug 'Calling Plesk XML API to remove TXT record'
  126. # printf using template in a variable - not a style issue
  127. # shellcheck disable=SC2059
  128. request="$(printf "$pleskxml_tplt_rmv_dns_record" "$recid")"
  129. if ! _call_api "$request"; then
  130. return 1
  131. fi
  132. # OK, we should have removed a TXT record. Let's check and return success if so.
  133. # All that should be left in the result, is one section, containing <result><status>ok</status><id>PLESK_DELETED_DNS_RECORD_ID</id></result>
  134. results="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>')"
  135. if ! _value "$results" | grep '<status>ok</status>' | grep -qE '<id>[0-9]+</id>'; then
  136. # Error - doesn't contain expected string. Something's wrong.
  137. _err 'Error when calling Plesk XML API.'
  138. _err 'The result did not contain the expected <id>XXXXX</id> section, or contained other values as well.'
  139. _err 'This is unexpected: something has gone wrong.'
  140. _err 'The full response was:\n' "$pleskxml_prettyprint_result"
  141. return 1
  142. fi
  143. _info "Success. TXT record appears to be correctly removed. Exiting dns_pleskxml_rm()."
  144. return 0
  145. }
  146. #################### Private functions below ##################################
  147. # Outputs value of a variable
  148. _value() {
  149. printf '%s' "$1"
  150. }
  151. # Outputs value of a variable (FQDN) and cuts it at 2 delimiters
  152. # $1, $2 = where to cut
  153. # $3 = FQDN
  154. _valuecut() {
  155. printf '%s' "$3" | cut -d . -f "${1}-${2}"
  156. }
  157. # Cleans up an API response, splits it "per item" and greps for a string to validate useful lines
  158. # $1 - result string from API
  159. # $2 - tag to resplit on (usually "result" or "domain")
  160. # $3 - regex to recognise useful return lines
  161. _api_response_split() {
  162. printf '%s' "$1" \
  163. | sed -E 's/(^[[:space:]]+|[[:space:]]+$)//g' \
  164. | tr -d '\n\r' \
  165. | sed -E "s/<\/?$2>/${NEWLINE}/g" \
  166. | grep -E "$3"
  167. }
  168. # Calls Plesk XML API, and checks results for obvious issues
  169. _call_api() {
  170. request="$1"
  171. errtext=''
  172. _debug 'Entered _call_api(). Calling Plesk XML API with request:\n' "'${request}'"
  173. export _H1="HTTP_AUTH_LOGIN: $pleskxml_user"
  174. export _H2="HTTP_AUTH_PASSWD: $pleskxml_pass"
  175. export _H3="content-Type: text/xml"
  176. export _H4="HTTP_PRETTY_PRINT: true"
  177. pleskxml_prettyprint_result="$(_post "${request}" "$pleskxml_uri" "" "POST")"
  178. pleskxml_retcode="$?"
  179. _debug "acme _post() returned retcode=$pleskxml_retcode. Literal response:" '\n' "'${pleskxml_prettyprint_result}'"
  180. # Error handling
  181. # Detect any <status> that isn't "ok". None of the used calls should fail if the API is working correctly.
  182. # Also detect if there simply aren't any status lines (null result?) and report that, as well.
  183. statuslines="$(echo "$pleskxml_prettyprint_result" | grep -E '^[[:space:]]*<status>[^<]*</status>[[:space:]]*$')"
  184. if _value "$statuslines" | grep -qv '<status>ok</status>'; then
  185. # We have some status lines that aren't "ok". Get the details
  186. errtext="$(_value "$pleskxml_prettyprint_result" \
  187. | grep -iE "(<status>|<errcode>|<errtext>)" \
  188. | sed -E 's/(^[[:space:]]+|<\/[a-z]+$)//g' \
  189. | sed -E 's/^<([a-z]+)>/\1: /'
  190. )"
  191. elif ! _value "$statuslines" | grep -q '<status>ok</status>'; then
  192. # We have no status lines at all. Results are empty
  193. errtext='The Plesk XML API unexpectedly returned an empty set of results for this call.'
  194. fi
  195. if [ "$pleskxml_retcode" -ne 0 ] || [ "$errtext" != "" ]; then
  196. _err "The Plesk XML API call failed."
  197. _err "The return code for the POST request was $pleskxml_retcode (0=success)."
  198. if [ "$errtext" != "" ]; then
  199. _err 'Status and error messages received from the Plesk server:\n' "$errtext"
  200. else
  201. _err "No additional error messages were received back from the Plesk server"
  202. fi
  203. return 1
  204. fi
  205. _debug "Leaving _call_api(). Successful call."
  206. return 0
  207. }
  208. # Startup checks (credentials, URI)
  209. _credential_check() {
  210. _debug "Checking Plesk XML API login credentials and URI..."
  211. if [ "$pleskxml_init_checks_done" -eq 1 ]; then
  212. _debug "Initial checks already done, no need to repeat. Skipped."
  213. return 0
  214. fi
  215. pleskxml_user="${pleskxml_user:-$(_readaccountconf_mutable pleskxml_user)}"
  216. pleskxml_pass="${pleskxml_pass:-$(_readaccountconf_mutable pleskxml_pass)}"
  217. pleskxml_uri="${pleskxml_uri:-$(_readaccountconf_mutable pleskxml_uri)}"
  218. _debug "Credentials - User: '${pleskxml_user}' Passwd: ****** URI: '${pleskxml_uri}'"
  219. if [ -z "$pleskxml_user" ] || [ -z "$pleskxml_pass" ] || [ -z "$pleskxml_uri" ]; then
  220. pleskxml_user=""
  221. pleskxml_pass=""
  222. pleskxml_uri=""
  223. _err "You didn't specify one or more of the Plesk XML API username, password, or URI."
  224. _err "Please create these and try again."
  225. _err "Instructions are in the module source code."
  226. return 1
  227. fi
  228. # Test the API is usable, by trying to read the list of managed domains...
  229. _call_api "$pleskxml_tplt_get_domains"
  230. if [ "$pleskxml_retcode" -ne 0 ]; then
  231. _err '\nFailed to access Plesk XML API.'
  232. _err "Please check your login credentials and Plesk URI, and that the URI is reachable, and try again."
  233. return 1
  234. fi
  235. _saveaccountconf_mutable pleskxml_uri "$pleskxml_uri"
  236. _saveaccountconf_mutable pleskxml_user "$pleskxml_user"
  237. _saveaccountconf_mutable pleskxml_pass "$pleskxml_pass"
  238. _debug "Test login to Plesk XML API successful. Login credentials and URI successfully saved to the acme.sh configuration file for future use."
  239. pleskxml_init_checks_done=1
  240. return 0
  241. }
  242. # For a FQDN, identify the root domain managed by Plesk, its domain ID in Plesk, and the host if any.
  243. # IMPORTANT NOTE: a result with host = empty string is OK for this API, see
  244. # https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-dns/managing-dns-records/adding-dns-record.34798
  245. # See notes at top of this file
  246. _pleskxml_get_root_domain() {
  247. _debug "Identifying DNS root domain for '$1' that is managed by the Plesk account."
  248. # test if the domain is valid for splitting.
  249. if _value "$root_domain_name" | grep -qvE '^[^.]+\.[^.]+\.[^.]'; then
  250. _err "Invalid domain. The ACME domain must contain at least two parts (aa.bb) to identify a domain and tld for the TXT record."
  251. return 1
  252. fi
  253. _debug "Querying Plesk server for list of managed domains..."
  254. _call_api "$pleskxml_tplt_get_domains"
  255. if [ "$pleskxml_retcode" -ne 0 ]; then
  256. return 1
  257. fi
  258. # Generate a hacked list of domains known to this Plesk account.
  259. # We convert <ascii-name> tags to <name> so it'll flag on a hit with either <name> or <ascii-name> fields,
  260. # for non-Western character sets.
  261. # Output will be one line per known domain, containing 1 or 2 <name> tages and an <id> tag
  262. # We don't actually need to check for type, name, *and* id, but it guarantees only usable lines are returned.
  263. output="$(_api_response_split "$pleskxml_prettyprint_result" 'domain' '<type>domain</type>' | sed -E 's/<(\/?)ascii-name>/<\1name>/g' | grep '<name>' | grep '<id>')"
  264. _debug 'Domains managed by Plesk server are (ignore the hacked output):\n' "$output"
  265. # loop and test if domain, or any parent domain, is managed by Plesk
  266. # Loop until we don't have any '.' in the sring we're testing as a root domain
  267. root_domain_name="$1"
  268. doneloop=0
  269. while _contains "$root_domain_name" '\.'; do
  270. _debug "Checking if '$root_domain_name' is managed by the Plesk server..."
  271. root_domain_id="$(_value "$output" | grep "<name>$root_domain_name</name>" | _head_n 1 | sed -E 's/^.*<id>([0-9]+)<\/id>.*$/\1/')"
  272. if [ -n "$root_domain_id" ]; then
  273. # Found a match
  274. # SEE IMPORTANT NOTE ABOVE - THIS FUNCTION CAN RETURN HOST='', AND THAT'S OK FOR PLESK XML API WHICH ALLOWS IT.
  275. # SO WE HANDLE IT AND DON'T PREVENT IT
  276. sub_domain_name="$(_value "$1" | sed -E "s/\.?${root_domain_name}"'$//')"
  277. _info "Matched host '$1' to: DOMAIN '${root_domain_name}' (Plesk ID '${root_domain_id}'), HOST '${sub_domain_name}'. Returning."
  278. return 0
  279. fi
  280. # No match, try next parent up (if any)...
  281. if _contains "$root_domain_name" '\.[^.]+\.'; then
  282. _debug "No match, trying next parent up..."
  283. else
  284. _debug "No match,and next parent would be a TLD..."
  285. fi
  286. root_domain_name="$(_valuecut 2 1000 "$root_domain_name")"
  287. doneloop=1
  288. done
  289. # if we get here, we failed to find a root domain match in the list of domains managed by Plesk.
  290. # if we never ran the loop a first time, $1 wasn't at least a 2 level domain (domain.tld) and wasn't valid anyway
  291. if [ -z $doneloop ]; then
  292. _err "'$1' isn't a valid domain for ACME DNS. Exiting."
  293. else
  294. _err "Cannot find '$1' or any parent domain of it, in Plesk."
  295. _err "Are you sure that this domain is managed by this Plesk server?"
  296. fi
  297. return 1
  298. }