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