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.

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