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.

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