]> git.proxmox.com Git - mirror_acme.sh.git/blob - dnsapi/dns_pleskxml.sh
basic regex's to use \+
[mirror_acme.sh.git] / dnsapi / dns_pleskxml.sh
1 #!/usr/bin/env sh
2
3 ## Name: dns_pleskxml.sh
4 ## Created by Stilez.
5 ## Also uses some code from PR#1832 by @romanlum (https://github.com/Neilpang/acme.sh/pull/1832/files)
6
7 ## This DNS-01 method uses the Plesk XML API described at:
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
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):
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
37 pleskxml_init_checks_done=0
38
39 # Variable containing bare newline - not a style issue
40 # shellcheck disable=SC1004
41 NEWLINE='\
42 '
43
44 pleskxml_tplt_get_domains="<packet><customer><get-domain-list><filter/></get-domain-list></customer></packet>"
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
49 pleskxml_tplt_get_dns_records="<packet><dns><get_rec><filter><site-id>%s</site-id></filter></get_rec></dns></packet>"
50 # Get all DNS records for a Plesk domain ID.
51 # PARAM = Plesk domain id to query
52
53 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>"
54 # Add a TXT record to a domain.
55 # PARAMS = (1) Plesk internal domain ID, (2) "hostname" for the new record, eg '_acme_challenge', (3) TXT record value
56
57 pleskxml_tplt_rmv_dns_record="<packet><dns><del_rec><filter><id>%s</id></filter></del_rec></dns></packet>"
58 # Delete a specific TXT record from a domain.
59 # PARAM = the Plesk internal ID for the DNS record to be deleted
60
61 #################### Public functions ##################################
62
63 #Usage: dns_pleskxml_add _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
64 dns_pleskxml_add() {
65 fulldomain=$1
66 txtvalue=$2
67
68 _info "Entering dns_pleskxml_add() to add TXT record '$txtvalue' to domain '$fulldomain'..."
69
70 # Get credentials if not already checked, and confirm we can log in to Plesk XML API
71 if ! _credential_check; then
72 return 1
73 fi
74
75 # Get root and subdomain details, and Plesk domain ID
76 if ! _pleskxml_get_root_domain "$fulldomain"; then
77 return 1
78 fi
79
80 _debug 'Credentials OK, and domain identified. Calling Plesk XML API to add TXT record'
81
82 # printf using template in a variable - not a style issue
83 # shellcheck disable=SC2059
84 request="$(printf "$pleskxml_tplt_add_txt_record" "$root_domain_id" "$sub_domain_name" "$txtvalue")"
85 if ! _call_api "$request"; then
86 return 1
87 fi
88
89 # OK, we should have added a TXT record. Let's check and return success if so.
90 # All that should be left in the result, is one section, containing <result><status>ok</status><id>NEW_DNS_RECORD_ID</id></result>
91
92 results="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>')"
93
94 if ! _value "$results" | grep '<status>ok</status>' | grep -q '<id>[0-9]\+</id>'; then
95 # Error - doesn't contain expected string. Something's wrong.
96 _err 'Error when calling Plesk XML API.'
97 _err 'The result did not contain the expected <id>XXXXX</id> section, or contained other values as well.'
98 _err 'This is unexpected: something has gone wrong.'
99 _err 'The full response was:\n' "$pleskxml_prettyprint_result"
100 return 1
101 fi
102
103 recid="$(_value "$results" | grep '<id>[0-9]\+</id>' | sed -r 's/^.*<id>([0-9]+)<\/id>.*$/\1/')"
104
105 _info "Success. TXT record appears to be correctly added (Plesk record ID=$recid). Exiting dns_pleskxml_add()."
106
107 return 0
108 }
109
110 #Usage: dns_pleskxml_rm _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
111 dns_pleskxml_rm() {
112 fulldomain=$1
113 txtvalue=$2
114
115 _info "Entering dns_pleskxml_rm() to remove TXT record '$txtvalue' from domain '$fulldomain'..."
116
117 # Get credentials if not already checked, and confirm we can log in to Plesk XML API
118 if ! _credential_check; then
119 return 1
120 fi
121
122 # Get root and subdomain details, and Plesk domain ID
123 if ! _pleskxml_get_root_domain "$fulldomain"; then
124 return 1
125 fi
126
127 _debug 'Credentials OK, and domain identified. Calling Plesk XML API to get list of TXT records and their IDs'
128
129 # printf using template in a variable - not a style issue
130 # shellcheck disable=SC2059
131 request="$(printf "$pleskxml_tplt_get_dns_records" "$root_domain_id")"
132 if ! _call_api "$request"; then
133 return 1
134 fi
135
136 # Reduce output to one line per DNS record, filtered for TXT records with a record ID only (which they should all have)
137 reclist="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>ok</status>' \
138 | grep "<site-id>${root_domain_id}</site-id>" \
139 | grep '<id>[0-9]\+</id>' \
140 | grep '<type>TXT</type>'
141 )"
142
143 if [ -z "$reclist" ]; then
144 _err "No TXT records found for root domain ${root_domain_name} (Plesk domain ID ${root_domain_id}). Exiting."
145 return 1
146 fi
147
148 _debug "Got list of DNS TXT records for root domain '$root_domain_name'"':\n'"$reclist"
149
150 recid="$(_value "$reclist" \
151 | grep "<host>$1.</host>" \
152 | grep "<value>$txtvalue</value>" \
153 | sed -r 's/(^.*<id>|<\/id>.*$)//g'
154 )"
155
156 _debug "List of DNS TXT records for host:"'\n'"$(_value "$reclist" | grep "<host>$1.</host>")"
157
158 if ! _value "$recid" | grep -q '^[0-9]\+$'; then
159 _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}'"
160 _err "Cannot delete TXT record. Exiting."
161 return 1
162 fi
163
164 _debug "Found Plesk record ID for target text string '${txtvalue}': ID=${recid}"
165 _debug 'Calling Plesk XML API to remove TXT record'
166
167 # printf using template in a variable - not a style issue
168 # shellcheck disable=SC2059
169 request="$(printf "$pleskxml_tplt_rmv_dns_record" "$recid")"
170 if ! _call_api "$request"; then
171 return 1
172 fi
173
174 # OK, we should have removed a TXT record. Let's check and return success if so.
175 # All that should be left in the result, is one section, containing <result><status>ok</status><id>PLESK_DELETED_DNS_RECORD_ID</id></result>
176
177 results="$(_api_response_split "$pleskxml_prettyprint_result" 'result' '<status>')"
178
179 if ! _value "$results" | grep '<status>ok</status>' | grep -q '<id>[0-9]\+</id>'; then
180 # Error - doesn't contain expected string. Something's wrong.
181 _err 'Error when calling Plesk XML API.'
182 _err 'The result did not contain the expected <id>XXXXX</id> section, or contained other values as well.'
183 _err 'This is unexpected: something has gone wrong.'
184 _err 'The full response was:\n' "$pleskxml_prettyprint_result"
185 return 1
186 fi
187
188 _info "Success. TXT record appears to be correctly removed. Exiting dns_pleskxml_rm()."
189 return 0
190 }
191
192 #################### Private functions below (utility functions) ##################################
193
194 # Outputs value of a variable without additional newlines etc
195 _value() {
196 printf '%s' "$1"
197 }
198
199 # Outputs value of a variable (FQDN) and cuts it at 2 specified '.' delimiters, returning the text in between
200 # $1, $2 = where to cut
201 # $3 = FQDN
202 _valuecut() {
203 printf '%s' "$3" | cut -d . -f "${1}-${2}"
204 }
205
206 # Counts '.' present in a domain name
207 # $1 = domain name
208 _countdots() {
209 _value "$1" | tr -dc '.' | wc -c
210 }
211
212 # 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
213 # $1 - result string from API
214 # $2 - tag to resplit on (usually "result" or "domain")
215 # $3 - basic regex to recognise useful return lines
216 # note: $3 matches via basic NOT extended regex (BRE), as extended regex capabilities not needed at the moment.
217 # Last line could change to <sed -rn '/.../p'> instead, with suitablew ewscaping of ['"/$],
218 # if future Plesk XML API changes ever require extended regex
219 _api_response_split() {
220 printf '%s' "$1" \
221 | sed -r 's/(^ +| +$)//g' \
222 | tr -d '\n\r' \
223 | sed -r "s/<\/?$2>/${NEWLINE}/g" \
224 | grep "$3"
225 }
226
227 #################### Private functions below (DNS functions) ##################################
228
229 # Calls Plesk XML API, and checks results for obvious issues
230 _call_api() {
231 request="$1"
232 errtext=''
233
234 _debug 'Entered _call_api(). Calling Plesk XML API with request:\n' "'${request}'"
235
236 export _H1="HTTP_AUTH_LOGIN: $pleskxml_user"
237 export _H2="HTTP_AUTH_PASSWD: $pleskxml_pass"
238 export _H3="content-Type: text/xml"
239 export _H4="HTTP_PRETTY_PRINT: true"
240 pleskxml_prettyprint_result="$(_post "${request}" "$pleskxml_uri" "" "POST")"
241 pleskxml_retcode="$?"
242 _debug 'The responses from the Plesk XML server were:\n' "retcode=$pleskxml_retcode. Literal response:"'\n' "'$pleskxml_prettyprint_result'"
243
244 # Detect any <status> that isn't "ok". None of the used calls should fail if the API is working correctly.
245 # Also detect if there simply aren't any status lines (null result?) and report that, as well.
246
247 statuslines="$(echo "$pleskxml_prettyprint_result" | grep '^ *<status>[^<]*</status> *$')"
248
249 if _value "$statuslines" | grep -qv '<status>ok</status>'; then
250
251 # We have some status lines that aren't "ok". Get the details
252 errtext="$(_value "$pleskxml_prettyprint_result" \
253 | sed -rn 's/^ *<(status|errcode|errtext)>([^<]+)<\/(status|errcode|errtext)> *$/\1: \2/p'
254 )"
255
256 elif ! _value "$statuslines" | grep -q '<status>ok</status>'; then
257
258 # We have no status lines at all. Results are empty
259 errtext='The Plesk XML API unexpectedly returned an empty set of results for this call.'
260
261 fi
262
263 if [ "$pleskxml_retcode" -ne 0 ] || [ "$errtext" != "" ]; then
264 # Call failed, for reasons either in the retcode or the response text...
265
266 if [ "$pleskxml_retcode" -eq 0 ]; then
267 _err "The POST request was successfully sent to the Plesk server."
268 else
269 _err "The return code for the POST request was $pleskxml_retcode (non-zero = could not submit request to server)."
270 fi
271
272 if [ "$errtext" != "" ]; then
273 _err 'The error responses received from the Plesk server were:\n' "$errtext"
274 else
275 _err "No additional error messages were received back from the Plesk server"
276 fi
277
278 _err "The Plesk XML API call failed."
279 return 1
280
281 fi
282
283 _debug "Leaving _call_api(). Successful call."
284
285 return 0
286 }
287
288 # Startup checks (credentials, URI)
289 _credential_check() {
290 _debug "Checking Plesk XML API login credentials and URI..."
291
292 if [ "$pleskxml_init_checks_done" -eq 1 ]; then
293 _debug "Initial checks already done, no need to repeat. Skipped."
294 return 0
295 fi
296
297 pleskxml_user="${pleskxml_user:-$(_readaccountconf_mutable pleskxml_user)}"
298 pleskxml_pass="${pleskxml_pass:-$(_readaccountconf_mutable pleskxml_pass)}"
299 pleskxml_uri="${pleskxml_uri:-$(_readaccountconf_mutable pleskxml_uri)}"
300
301 if [ -z "$pleskxml_user" ] || [ -z "$pleskxml_pass" ] || [ -z "$pleskxml_uri" ]; then
302 pleskxml_user=""
303 pleskxml_pass=""
304 pleskxml_uri=""
305 _err "You didn't specify one or more of the Plesk XML API username, password, or URI."
306 _err "Please create these and try again."
307 _err "Instructions are in the 'dns_pleskxml' plugin source code or in the acme.sh documentation."
308 return 1
309 fi
310
311 # Test the API is usable, by trying to read the list of managed domains...
312 _call_api "$pleskxml_tplt_get_domains"
313 if [ "$pleskxml_retcode" -ne 0 ]; then
314 _err '\nFailed to access Plesk XML API.'
315 _err "Please check your login credentials and Plesk URI, and that the URI is reachable, and try again."
316 return 1
317 fi
318
319 _saveaccountconf_mutable pleskxml_uri "$pleskxml_uri"
320 _saveaccountconf_mutable pleskxml_user "$pleskxml_user"
321 _saveaccountconf_mutable pleskxml_pass "$pleskxml_pass"
322
323 _debug "Test login to Plesk XML API successful. Login credentials and URI successfully saved to the acme.sh configuration file for future use."
324
325 pleskxml_init_checks_done=1
326
327 return 0
328 }
329
330 # For a FQDN, identify the root domain managed by Plesk, its domain ID in Plesk, and the host if any.
331
332 # IMPORTANT NOTE: a result with host = empty string is OK for this API, see
333 # https://docs.plesk.com/en-US/obsidian/api-rpc/about-xml-api/reference/managing-dns/managing-dns-records/adding-dns-record.34798
334 # See notes at top of this file
335
336 _pleskxml_get_root_domain() {
337 _debug "Identifying DNS root domain for '$1' that is managed by the Plesk account."
338 original_full_domain_name="$1"
339 root_domain_name="$1"
340
341 # test if the domain as provided is valid for splitting.
342
343 if ! _countdots "$root_domain_name"; then
344 _err "Invalid domain. The ACME domain must contain at least two parts (aa.bb) to identify a domain and tld for the TXT record."
345 return 1
346 fi
347
348 _debug "Querying Plesk server for list of managed domains..."
349
350 _call_api "$pleskxml_tplt_get_domains"
351 if [ "$pleskxml_retcode" -ne 0 ]; then
352 return 1
353 fi
354
355 # Generate a crude list of domains known to this Plesk account.
356 # We convert <ascii-name> tags to <name> so it'll flag on a hit with either <name> or <ascii-name> fields,
357 # for non-Western character sets.
358 # Output will be one line per known domain, containing 2 <name> tages and a single <id> tag
359 # We don't actually need to check for type, name, *and* id, but it guarantees only usable lines are returned.
360
361 output="$(_api_response_split "$pleskxml_prettyprint_result" 'domain' '<type>domain</type>' | sed -r 's/<(\/?)ascii-name>/<\1name>/g' | grep '<name>' | grep '<id>')"
362
363 _debug 'Domains managed by Plesk server are (ignore the hacked output):\n' "$output"
364
365 # loop and test if domain, or any parent domain, is managed by Plesk
366 # Loop until we don't have any '.' in the string we're testing as a candidate Plesk-managed domain
367
368 while true; do
369
370 _debug "Checking if '$root_domain_name' is managed by the Plesk server..."
371
372 root_domain_id="$(_value "$output" | grep "<name>$root_domain_name</name>" | _head_n 1 | sed -r 's/^.*<id>([0-9]+)<\/id>.*$/\1/')"
373
374 if [ -n "$root_domain_id" ]; then
375 # Found a match
376 # SEE IMPORTANT NOTE ABOVE - THIS FUNCTION CAN RETURN HOST='', AND THAT'S OK FOR PLESK XML API WHICH ALLOWS IT.
377 # SO WE HANDLE IT AND DON'T PREVENT IT
378 sub_domain_name="$(_value "$original_full_domain_name" | sed -r "s/\.?${root_domain_name}"'$//')"
379 _info "Success. Matched host '$original_full_domain_name' to: DOMAIN '${root_domain_name}' (Plesk ID '${root_domain_id}'), HOST '${sub_domain_name}'. Returning."
380 return 0
381 fi
382
383 # No match, try next parent up (if any)...
384
385 root_domain_name="$(_valuecut 2 1000 "$root_domain_name")"
386
387 if ! _countdots "$root_domain_name"; then
388 _debug "No match, and next parent would be a TLD..."
389 _err "Cannot find '$original_full_domain_name' or any parent domain of it, in Plesk."
390 _err "Are you sure that this domain is managed by this Plesk server?"
391 return 1
392 fi
393
394 _debug "No match, trying next parent up..."
395
396 done
397 }