]> git.proxmox.com Git - mirror_acme.sh.git/blob - dnsapi/dns_azure.sh
Merge pull request #1319 from TigerP/master
[mirror_acme.sh.git] / dnsapi / dns_azure.sh
1 #!/usr/bin/env sh
2
3 WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-use-Azure-DNS"
4
5 ######## Public functions #####################
6
7 # Usage: add _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
8 # Used to add txt record
9 #
10 # Ref: https://docs.microsoft.com/en-us/rest/api/dns/recordsets/createorupdate
11 #
12 dns_azure_add() {
13 fulldomain=$1
14 txtvalue=$2
15
16 AZUREDNS_SUBSCRIPTIONID="${AZUREDNS_SUBSCRIPTIONID:-$(_readaccountconf_mutable AZUREDNS_SUBSCRIPTIONID)}"
17 AZUREDNS_TENANTID="${AZUREDNS_TENANTID:-$(_readaccountconf_mutable AZUREDNS_TENANTID)}"
18 AZUREDNS_APPID="${AZUREDNS_APPID:-$(_readaccountconf_mutable AZUREDNS_APPID)}"
19 AZUREDNS_CLIENTSECRET="${AZUREDNS_CLIENTSECRET:-$(_readaccountconf_mutable AZUREDNS_CLIENTSECRET)}"
20
21 if [ -z "$AZUREDNS_SUBSCRIPTIONID" ]; then
22 AZUREDNS_SUBSCRIPTIONID=""
23 AZUREDNS_TENANTID=""
24 AZUREDNS_APPID=""
25 AZUREDNS_CLIENTSECRET=""
26 _err "You didn't specify the Azure Subscription ID "
27 return 1
28 fi
29
30 if [ -z "$AZUREDNS_TENANTID" ]; then
31 AZUREDNS_SUBSCRIPTIONID=""
32 AZUREDNS_TENANTID=""
33 AZUREDNS_APPID=""
34 AZUREDNS_CLIENTSECRET=""
35 _err "You didn't specify the Azure Tenant ID "
36 return 1
37 fi
38
39 if [ -z "$AZUREDNS_APPID" ]; then
40 AZUREDNS_SUBSCRIPTIONID=""
41 AZUREDNS_TENANTID=""
42 AZUREDNS_APPID=""
43 AZUREDNS_CLIENTSECRET=""
44 _err "You didn't specify the Azure App ID"
45 return 1
46 fi
47
48 if [ -z "$AZUREDNS_CLIENTSECRET" ]; then
49 AZUREDNS_SUBSCRIPTIONID=""
50 AZUREDNS_TENANTID=""
51 AZUREDNS_APPID=""
52 AZUREDNS_CLIENTSECRET=""
53 _err "You didn't specify the Azure Client Secret"
54 return 1
55 fi
56 #save account details to account conf file.
57 _saveaccountconf_mutable AZUREDNS_SUBSCRIPTIONID "$AZUREDNS_SUBSCRIPTIONID"
58 _saveaccountconf_mutable AZUREDNS_TENANTID "$AZUREDNS_TENANTID"
59 _saveaccountconf_mutable AZUREDNS_APPID "$AZUREDNS_APPID"
60 _saveaccountconf_mutable AZUREDNS_CLIENTSECRET "$AZUREDNS_CLIENTSECRET"
61
62 accesstoken=$(_azure_getaccess_token "$AZUREDNS_TENANTID" "$AZUREDNS_APPID" "$AZUREDNS_CLIENTSECRET")
63
64 if ! _get_root "$fulldomain" "$AZUREDNS_SUBSCRIPTIONID" "$accesstoken"; then
65 _err "invalid domain"
66 return 1
67 fi
68 _debug _domain_id "$_domain_id"
69 _debug _sub_domain "$_sub_domain"
70 _debug _domain "$_domain"
71
72 acmeRecordURI="https://management.azure.com$(printf '%s' "$_domain_id" | sed 's/\\//g')/TXT/$_sub_domain?api-version=2017-09-01"
73 _debug "$acmeRecordURI"
74 # Get existing TXT record
75 _azure_rest GET "$acmeRecordURI" "" "$accesstoken"
76 values="{\"value\":[\"$txtvalue\"]}"
77 timestamp="$(_time)"
78 if [ "$_code" = "200" ]; then
79 vlist="$(echo "$response" | _egrep_o "\"value\"\s*:\s*\[\s*\"[^\"]*\"\s*]" | cut -d : -f 2 | tr -d "[]\"")"
80 _debug "existing TXT found"
81 _debug "$vlist"
82 existingts="$(echo "$response" | _egrep_o "\"acmetscheck\"\s*:\s*\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d "\"")"
83 if [ -z "$existingts" ]; then
84 # the record was not created by acme.sh. Copy the exisiting entires
85 existingts=$timestamp
86 fi
87 _diff="$(_math "$timestamp - $existingts")"
88 _debug "existing txt age: $_diff"
89 # only use recently added records and discard if older than 2 hours because they are probably orphaned
90 if [ "$_diff" -lt 7200 ]; then
91 _debug "existing txt value: $vlist"
92 for v in $vlist; do
93 values="$values ,{\"value\":[\"$v\"]}"
94 done
95 fi
96 fi
97 # Add the txtvalue TXT Record
98 body="{\"properties\":{\"metadata\":{\"acmetscheck\":\"$timestamp\"},\"TTL\":10, \"TXTRecords\":[$values]}}"
99 _azure_rest PUT "$acmeRecordURI" "$body" "$accesstoken"
100 if [ "$_code" = "200" ] || [ "$_code" = '201' ]; then
101 _info "validation value added"
102 else
103 _err "error adding validation value ($_code)"
104 return 1
105 fi
106 }
107
108 # Usage: fulldomain txtvalue
109 # Used to remove the txt record after validation
110 #
111 # Ref: https://docs.microsoft.com/en-us/rest/api/dns/recordsets/delete
112 #
113 dns_azure_rm() {
114 fulldomain=$1
115 txtvalue=$2
116
117 AZUREDNS_SUBSCRIPTIONID="${AZUREDNS_SUBSCRIPTIONID:-$(_readaccountconf_mutable AZUREDNS_SUBSCRIPTIONID)}"
118 AZUREDNS_TENANTID="${AZUREDNS_TENANTID:-$(_readaccountconf_mutable AZUREDNS_TENANTID)}"
119 AZUREDNS_APPID="${AZUREDNS_APPID:-$(_readaccountconf_mutable AZUREDNS_APPID)}"
120 AZUREDNS_CLIENTSECRET="${AZUREDNS_CLIENTSECRET:-$(_readaccountconf_mutable AZUREDNS_CLIENTSECRET)}"
121
122 if [ -z "$AZUREDNS_SUBSCRIPTIONID" ]; then
123 AZUREDNS_SUBSCRIPTIONID=""
124 AZUREDNS_TENANTID=""
125 AZUREDNS_APPID=""
126 AZUREDNS_CLIENTSECRET=""
127 _err "You didn't specify the Azure Subscription ID "
128 return 1
129 fi
130
131 if [ -z "$AZUREDNS_TENANTID" ]; then
132 AZUREDNS_SUBSCRIPTIONID=""
133 AZUREDNS_TENANTID=""
134 AZUREDNS_APPID=""
135 AZUREDNS_CLIENTSECRET=""
136 _err "You didn't specify the Azure Tenant ID "
137 return 1
138 fi
139
140 if [ -z "$AZUREDNS_APPID" ]; then
141 AZUREDNS_SUBSCRIPTIONID=""
142 AZUREDNS_TENANTID=""
143 AZUREDNS_APPID=""
144 AZUREDNS_CLIENTSECRET=""
145 _err "You didn't specify the Azure App ID"
146 return 1
147 fi
148
149 if [ -z "$AZUREDNS_CLIENTSECRET" ]; then
150 AZUREDNS_SUBSCRIPTIONID=""
151 AZUREDNS_TENANTID=""
152 AZUREDNS_APPID=""
153 AZUREDNS_CLIENTSECRET=""
154 _err "You didn't specify the Azure Client Secret"
155 return 1
156 fi
157
158 accesstoken=$(_azure_getaccess_token "$AZUREDNS_TENANTID" "$AZUREDNS_APPID" "$AZUREDNS_CLIENTSECRET")
159
160 if ! _get_root "$fulldomain" "$AZUREDNS_SUBSCRIPTIONID" "$accesstoken"; then
161 _err "invalid domain"
162 return 1
163 fi
164 _debug _domain_id "$_domain_id"
165 _debug _sub_domain "$_sub_domain"
166 _debug _domain "$_domain"
167
168 acmeRecordURI="https://management.azure.com$(printf '%s' "$_domain_id" | sed 's/\\//g')/TXT/$_sub_domain?api-version=2017-09-01"
169 _debug "$acmeRecordURI"
170 # Get existing TXT record
171 _azure_rest GET "$acmeRecordURI" "" "$accesstoken"
172 timestamp="$(_time)"
173 if [ "$_code" = "200" ]; then
174 vlist="$(echo "$response" | _egrep_o "\"value\"\s*:\s*\[\s*\"[^\"]*\"\s*]" | cut -d : -f 2 | tr -d "[]\"" | grep -v "$txtvalue")"
175 values=""
176 comma=""
177 for v in $vlist; do
178 values="$values$comma{\"value\":[\"$v\"]}"
179 comma=","
180 done
181 if [ -z "$values" ]; then
182 # No values left remove record
183 _debug "removing validation record completely $acmeRecordURI"
184 _azure_rest DELETE "$acmeRecordURI" "" "$accesstoken"
185 if [ "$_code" = "200" ] || [ "$_code" = '204' ]; then
186 _info "validation record removed"
187 else
188 _err "error removing validation record ($_code)"
189 return 1
190 fi
191 else
192 # Remove only txtvalue from the TXT Record
193 body="{\"properties\":{\"metadata\":{\"acmetscheck\":\"$timestamp\"},\"TTL\":10, \"TXTRecords\":[$values]}}"
194 _azure_rest PUT "$acmeRecordURI" "$body" "$accesstoken"
195 if [ "$_code" = "200" ] || [ "$_code" = '201' ]; then
196 _info "validation value removed"
197 else
198 _err "error removing validation value ($_code)"
199 return 1
200 fi
201 fi
202 fi
203 }
204
205 ################### Private functions below ##################################
206
207 _azure_rest() {
208 m=$1
209 ep="$2"
210 data="$3"
211 accesstoken="$4"
212
213 MAX_REQUEST_RETRY_TIMES=5
214 _request_retry_times=0
215 while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
216 _debug3 _request_retry_times "$_request_retry_times"
217 export _H1="authorization: Bearer $accesstoken"
218 export _H2="accept: application/json"
219 export _H3="Content-Type: application/json"
220 # clear headers from previous request to avoid getting wrong http code on timeouts
221 :>"$HTTP_HEADER"
222 _debug "$ep"
223 if [ "$m" != "GET" ]; then
224 _secure_debug2 "data $data"
225 response="$(_post "$data" "$ep" "" "$m")"
226 else
227 response="$(_get "$ep")"
228 fi
229 _secure_debug2 "response $response"
230 _code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
231 _debug "http response code $_code"
232 if [ "$_code" = "401" ]; then
233 # we have an invalid access token set to expired
234 _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "0"
235 _err "access denied make sure your Azure settings are correct. See $WIKI"
236 return 1
237 fi
238 # See https://docs.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific#general-rest-and-retry-guidelines for retryable HTTP codes
239 if [ "$?" != "0" ] || [ -z "$_code" ] || [ "$_code" = "408" ] || [ "$_code" = "500" ] || [ "$_code" = "503" ] || [ "$_code" = "504" ]; then
240 _request_retry_times="$(_math "$_request_retry_times" + 1)"
241 _info "REST call error $_code retrying $ep in $_request_retry_times s"
242 _sleep "$_request_retry_times"
243 continue
244 fi
245 break
246 done
247 if [ "$_request_retry_times" = "$MAX_REQUEST_RETRY_TIMES" ]; then
248 _err "Error Azure REST called was retried $MAX_REQUEST_RETRY_TIMES times."
249 _err "Calling $ep failed."
250 return 1
251 fi
252 response="$(echo "$response" | _normalizeJson)"
253 return 0
254 }
255
256 ## Ref: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-service-to-service#request-an-access-token
257 _azure_getaccess_token() {
258 tenantID=$1
259 clientID=$2
260 clientSecret=$3
261
262 accesstoken="${AZUREDNS_BEARERTOKEN:-$(_readaccountconf_mutable AZUREDNS_BEARERTOKEN)}"
263 expires_on="${AZUREDNS_TOKENVALIDTO:-$(_readaccountconf_mutable AZUREDNS_TOKENVALIDTO)}"
264
265 # can we reuse the bearer token?
266 if [ -n "$accesstoken" ] && [ -n "$expires_on" ]; then
267 if [ "$(_time)" -lt "$expires_on" ]; then
268 # brearer token is still valid - reuse it
269 _debug "reusing bearer token"
270 printf "%s" "$accesstoken"
271 return 0
272 else
273 _debug "bearer token expired"
274 fi
275 fi
276 _debug "getting new bearer token"
277
278 export _H1="accept: application/json"
279 export _H2="Content-Type: application/x-www-form-urlencoded"
280
281 body="resource=$(printf "%s" 'https://management.core.windows.net/' | _url_encode)&client_id=$(printf "%s" "$clientID" | _url_encode)&client_secret=$(printf "%s" "$clientSecret" | _url_encode)&grant_type=client_credentials"
282 _secure_debug2 "data $body"
283 response="$(_post "$body" "https://login.microsoftonline.com/$tenantID/oauth2/token" "" "POST")"
284 _secure_debug2 "response $response"
285 response="$(echo "$response" | _normalizeJson)"
286 accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
287 expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
288
289 if [ -z "$accesstoken" ]; then
290 _err "no acccess token received. Check your Azure settings see $WIKI"
291 return 1
292 fi
293 if [ "$?" != "0" ]; then
294 _err "error $response"
295 return 1
296 fi
297 _saveaccountconf_mutable AZUREDNS_BEARERTOKEN "$accesstoken"
298 _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "$expires_on"
299 printf "%s" "$accesstoken"
300 return 0
301 }
302
303 _get_root() {
304 domain=$1
305 subscriptionId=$2
306 accesstoken=$3
307 i=2
308 p=1
309
310 ## Ref: https://docs.microsoft.com/en-us/rest/api/dns/zones/list
311 ## returns up to 100 zones in one response therefore handling more results is not not implemented
312 ## (ZoneListResult with continuation token for the next page of results)
313 ## Per https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits#dns-limits you are limited to 100 Zone/subscriptions anyways
314 ##
315 _azure_rest GET "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Network/dnszones?api-version=2017-09-01" "" "$accesstoken"
316 # Find matching domain name is Json response
317 while true; do
318 h=$(printf "%s" "$domain" | cut -d . -f $i-100)
319 _debug2 "Checking domain: $h"
320 if [ -z "$h" ]; then
321 #not valid
322 _err "Invalid domain"
323 return 1
324 fi
325
326 if _contains "$response" "\"name\":\"$h\"" >/dev/null; then
327 _domain_id=$(echo "$response" | _egrep_o "\{\"id\":\"[^\"]*$h\"" | head -n 1 | cut -d : -f 2 | tr -d \")
328 if [ "$_domain_id" ]; then
329 _sub_domain=$(printf "%s" "$domain" | cut -d . -f 1-$p)
330 _domain=$h
331 return 0
332 fi
333 return 1
334 fi
335 p=$i
336 i=$(_math "$i" + 1)
337 done
338 return 1
339 }