dns_azure.sh 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. #!/usr/bin/env sh
  2. # shellcheck disable=SC2034
  3. dns_azure_info='Azure
  4. Site: Azure.microsoft.com
  5. Docs: github.com/acmesh-official/acme.sh/wiki/dnsapi#dns_azure
  6. Options:
  7. AZUREDNS_SUBSCRIPTIONID Subscription ID
  8. AZUREDNS_TENANTID Tenant ID
  9. AZUREDNS_APPID App ID. App ID of the service principal
  10. AZUREDNS_CLIENTSECRET Client Secret. Secret from creating the service principal
  11. AZUREDNS_MANAGEDIDENTITY Use Managed Identity. Use Managed Identity assigned to a resource instead of a service principal. "true"/"false"
  12. AZUREDNS_BEARERTOKEN Bearer Token. Used instead of service principal credentials or managed identity. Optional.
  13. '
  14. wiki=https://github.com/acmesh-official/acme.sh/wiki/How-to-use-Azure-DNS
  15. ######## Public functions #####################
  16. # Usage: add _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
  17. # Used to add txt record
  18. #
  19. # Ref: https://learn.microsoft.com/en-us/rest/api/dns/record-sets/create-or-update?view=rest-dns-2018-05-01&tabs=HTTP
  20. #
  21. dns_azure_add() {
  22. fulldomain=$1
  23. txtvalue=$2
  24. AZUREDNS_SUBSCRIPTIONID="${AZUREDNS_SUBSCRIPTIONID:-$(_readaccountconf_mutable AZUREDNS_SUBSCRIPTIONID)}"
  25. if [ -z "$AZUREDNS_SUBSCRIPTIONID" ]; then
  26. AZUREDNS_SUBSCRIPTIONID=""
  27. AZUREDNS_TENANTID=""
  28. AZUREDNS_APPID=""
  29. AZUREDNS_CLIENTSECRET=""
  30. AZUREDNS_BEARERTOKEN=""
  31. _err "You didn't specify the Azure Subscription ID"
  32. return 1
  33. fi
  34. #save subscription id to account conf file.
  35. _saveaccountconf_mutable AZUREDNS_SUBSCRIPTIONID "$AZUREDNS_SUBSCRIPTIONID"
  36. AZUREDNS_MANAGEDIDENTITY="${AZUREDNS_MANAGEDIDENTITY:-$(_readaccountconf_mutable AZUREDNS_MANAGEDIDENTITY)}"
  37. if [ "$AZUREDNS_MANAGEDIDENTITY" = true ]; then
  38. _info "Using Azure managed identity"
  39. #save managed identity as preferred authentication method, clear service principal credentials from conf file.
  40. _saveaccountconf_mutable AZUREDNS_MANAGEDIDENTITY "$AZUREDNS_MANAGEDIDENTITY"
  41. _saveaccountconf_mutable AZUREDNS_TENANTID ""
  42. _saveaccountconf_mutable AZUREDNS_APPID ""
  43. _saveaccountconf_mutable AZUREDNS_CLIENTSECRET ""
  44. _saveaccountconf_mutable AZUREDNS_BEARERTOKEN ""
  45. else
  46. _info "You didn't ask to use Azure managed identity, checking service principal credentials or provided bearer token"
  47. AZUREDNS_TENANTID="${AZUREDNS_TENANTID:-$(_readaccountconf_mutable AZUREDNS_TENANTID)}"
  48. AZUREDNS_APPID="${AZUREDNS_APPID:-$(_readaccountconf_mutable AZUREDNS_APPID)}"
  49. AZUREDNS_CLIENTSECRET="${AZUREDNS_CLIENTSECRET:-$(_readaccountconf_mutable AZUREDNS_CLIENTSECRET)}"
  50. AZUREDNS_BEARERTOKEN="${AZUREDNS_BEARERTOKEN:-$(_readaccountconf_mutable AZUREDNS_BEARERTOKEN)}"
  51. if [ -z "$AZUREDNS_BEARERTOKEN" ]; then
  52. if [ -z "$AZUREDNS_TENANTID" ]; then
  53. AZUREDNS_SUBSCRIPTIONID=""
  54. AZUREDNS_TENANTID=""
  55. AZUREDNS_APPID=""
  56. AZUREDNS_CLIENTSECRET=""
  57. AZUREDNS_BEARERTOKEN=""
  58. _err "You didn't specify the Azure Tenant ID "
  59. return 1
  60. fi
  61. if [ -z "$AZUREDNS_APPID" ]; then
  62. AZUREDNS_SUBSCRIPTIONID=""
  63. AZUREDNS_TENANTID=""
  64. AZUREDNS_APPID=""
  65. AZUREDNS_CLIENTSECRET=""
  66. AZUREDNS_BEARERTOKEN=""
  67. _err "You didn't specify the Azure App ID"
  68. return 1
  69. fi
  70. if [ -z "$AZUREDNS_CLIENTSECRET" ]; then
  71. AZUREDNS_SUBSCRIPTIONID=""
  72. AZUREDNS_TENANTID=""
  73. AZUREDNS_APPID=""
  74. AZUREDNS_CLIENTSECRET=""
  75. AZUREDNS_BEARERTOKEN=""
  76. _err "You didn't specify the Azure Client Secret"
  77. return 1
  78. fi
  79. else
  80. _info "Using provided bearer token"
  81. fi
  82. #save account details to account conf file, don't opt in for azure manages identity check.
  83. _saveaccountconf_mutable AZUREDNS_MANAGEDIDENTITY "false"
  84. _saveaccountconf_mutable AZUREDNS_TENANTID "$AZUREDNS_TENANTID"
  85. _saveaccountconf_mutable AZUREDNS_APPID "$AZUREDNS_APPID"
  86. _saveaccountconf_mutable AZUREDNS_CLIENTSECRET "$AZUREDNS_CLIENTSECRET"
  87. _saveaccountconf_mutable AZUREDNS_BEARERTOKEN "$AZUREDNS_BEARERTOKEN"
  88. fi
  89. if [ -z "$AZUREDNS_BEARERTOKEN" ]; then
  90. accesstoken=$(_azure_getaccess_token "$AZUREDNS_MANAGEDIDENTITY" "$AZUREDNS_TENANTID" "$AZUREDNS_APPID" "$AZUREDNS_CLIENTSECRET")
  91. else
  92. accesstoken=$(echo "$AZUREDNS_BEARERTOKEN" | sed "s/Bearer //g")
  93. fi
  94. if ! _get_root "$fulldomain" "$AZUREDNS_SUBSCRIPTIONID" "$accesstoken"; then
  95. _err "invalid domain"
  96. return 1
  97. fi
  98. _debug _domain_id "$_domain_id"
  99. _debug _sub_domain "$_sub_domain"
  100. _debug _domain "$_domain"
  101. acmeRecordURI="https://management.azure.com$(printf '%s' "$_domain_id" | sed 's/\\//g')/TXT/$_sub_domain?api-version=2017-09-01"
  102. _debug "$acmeRecordURI"
  103. # Get existing TXT record
  104. _azure_rest GET "$acmeRecordURI" "" "$accesstoken"
  105. values="{\"value\":[\"$txtvalue\"]}"
  106. timestamp="$(_time)"
  107. if [ "$_code" = "200" ]; then
  108. vlist="$(echo "$response" | _egrep_o "\"value\"\\s*:\\s*\\[\\s*\"[^\"]*\"\\s*]" | cut -d : -f 2 | tr -d "[]\"")"
  109. _debug "existing TXT found"
  110. _debug "$vlist"
  111. existingts="$(echo "$response" | _egrep_o "\"acmetscheck\"\\s*:\\s*\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d "\"")"
  112. if [ -z "$existingts" ]; then
  113. # the record was not created by acme.sh. Copy the exisiting entires
  114. existingts=$timestamp
  115. fi
  116. _diff="$(_math "$timestamp - $existingts")"
  117. _debug "existing txt age: $_diff"
  118. # only use recently added records and discard if older than 2 hours because they are probably orphaned
  119. if [ "$_diff" -lt 7200 ]; then
  120. _debug "existing txt value: $vlist"
  121. for v in $vlist; do
  122. values="$values ,{\"value\":[\"$v\"]}"
  123. done
  124. fi
  125. fi
  126. # Add the txtvalue TXT Record
  127. body="{\"properties\":{\"metadata\":{\"acmetscheck\":\"$timestamp\"},\"TTL\":10, \"TXTRecords\":[$values]}}"
  128. _azure_rest PUT "$acmeRecordURI" "$body" "$accesstoken"
  129. if [ "$_code" = "200" ] || [ "$_code" = '201' ]; then
  130. _info "validation value added"
  131. return 0
  132. else
  133. _err "error adding validation value ($_code)"
  134. return 1
  135. fi
  136. }
  137. # Usage: fulldomain txtvalue
  138. # Used to remove the txt record after validation
  139. #
  140. # Ref: https://learn.microsoft.com/en-us/rest/api/dns/record-sets/delete?view=rest-dns-2018-05-01&tabs=HTTP
  141. #
  142. dns_azure_rm() {
  143. fulldomain=$1
  144. txtvalue=$2
  145. AZUREDNS_SUBSCRIPTIONID="${AZUREDNS_SUBSCRIPTIONID:-$(_readaccountconf_mutable AZUREDNS_SUBSCRIPTIONID)}"
  146. if [ -z "$AZUREDNS_SUBSCRIPTIONID" ]; then
  147. AZUREDNS_SUBSCRIPTIONID=""
  148. AZUREDNS_TENANTID=""
  149. AZUREDNS_APPID=""
  150. AZUREDNS_CLIENTSECRET=""
  151. AZUREDNS_BEARERTOKEN=""
  152. _err "You didn't specify the Azure Subscription ID "
  153. return 1
  154. fi
  155. AZUREDNS_MANAGEDIDENTITY="${AZUREDNS_MANAGEDIDENTITY:-$(_readaccountconf_mutable AZUREDNS_MANAGEDIDENTITY)}"
  156. if [ "$AZUREDNS_MANAGEDIDENTITY" = true ]; then
  157. _info "Using Azure managed identity"
  158. else
  159. _info "You didn't ask to use Azure managed identity, checking service principal credentials or provided bearer token"
  160. AZUREDNS_TENANTID="${AZUREDNS_TENANTID:-$(_readaccountconf_mutable AZUREDNS_TENANTID)}"
  161. AZUREDNS_APPID="${AZUREDNS_APPID:-$(_readaccountconf_mutable AZUREDNS_APPID)}"
  162. AZUREDNS_CLIENTSECRET="${AZUREDNS_CLIENTSECRET:-$(_readaccountconf_mutable AZUREDNS_CLIENTSECRET)}"
  163. AZUREDNS_BEARERTOKEN="${AZUREDNS_BEARERTOKEN:-$(_readaccountconf_mutable AZUREDNS_BEARERTOKEN)}"
  164. if [ -z "$AZUREDNS_BEARERTOKEN" ]; then
  165. if [ -z "$AZUREDNS_TENANTID" ]; then
  166. AZUREDNS_SUBSCRIPTIONID=""
  167. AZUREDNS_TENANTID=""
  168. AZUREDNS_APPID=""
  169. AZUREDNS_CLIENTSECRET=""
  170. AZUREDNS_BEARERTOKEN=""
  171. _err "You didn't specify the Azure Tenant ID "
  172. return 1
  173. fi
  174. if [ -z "$AZUREDNS_APPID" ]; then
  175. AZUREDNS_SUBSCRIPTIONID=""
  176. AZUREDNS_TENANTID=""
  177. AZUREDNS_APPID=""
  178. AZUREDNS_CLIENTSECRET=""
  179. AZUREDNS_BEARERTOKEN=""
  180. _err "You didn't specify the Azure App ID"
  181. return 1
  182. fi
  183. if [ -z "$AZUREDNS_CLIENTSECRET" ]; then
  184. AZUREDNS_SUBSCRIPTIONID=""
  185. AZUREDNS_TENANTID=""
  186. AZUREDNS_APPID=""
  187. AZUREDNS_CLIENTSECRET=""
  188. AZUREDNS_BEARERTOKEN=""
  189. _err "You didn't specify the Azure Client Secret"
  190. return 1
  191. fi
  192. else
  193. _info "Using provided bearer token"
  194. fi
  195. fi
  196. if [ -z "$AZUREDNS_BEARERTOKEN" ]; then
  197. accesstoken=$(_azure_getaccess_token "$AZUREDNS_MANAGEDIDENTITY" "$AZUREDNS_TENANTID" "$AZUREDNS_APPID" "$AZUREDNS_CLIENTSECRET")
  198. else
  199. accesstoken=$(echo "$AZUREDNS_BEARERTOKEN" | sed "s/Bearer //g")
  200. fi
  201. if ! _get_root "$fulldomain" "$AZUREDNS_SUBSCRIPTIONID" "$accesstoken"; then
  202. _err "invalid domain"
  203. return 1
  204. fi
  205. _debug _domain_id "$_domain_id"
  206. _debug _sub_domain "$_sub_domain"
  207. _debug _domain "$_domain"
  208. acmeRecordURI="https://management.azure.com$(printf '%s' "$_domain_id" | sed 's/\\//g')/TXT/$_sub_domain?api-version=2017-09-01"
  209. _debug "$acmeRecordURI"
  210. # Get existing TXT record
  211. _azure_rest GET "$acmeRecordURI" "" "$accesstoken"
  212. timestamp="$(_time)"
  213. if [ "$_code" = "200" ]; then
  214. vlist="$(echo "$response" | _egrep_o "\"value\"\\s*:\\s*\\[\\s*\"[^\"]*\"\\s*]" | cut -d : -f 2 | tr -d "[]\"" | grep -v -- "$txtvalue")"
  215. values=""
  216. comma=""
  217. for v in $vlist; do
  218. values="$values$comma{\"value\":[\"$v\"]}"
  219. comma=","
  220. done
  221. if [ -z "$values" ]; then
  222. # No values left remove record
  223. _debug "removing validation record completely $acmeRecordURI"
  224. _azure_rest DELETE "$acmeRecordURI" "" "$accesstoken"
  225. if [ "$_code" = "200" ] || [ "$_code" = '204' ]; then
  226. _info "validation record removed"
  227. else
  228. _err "error removing validation record ($_code)"
  229. return 1
  230. fi
  231. else
  232. # Remove only txtvalue from the TXT Record
  233. body="{\"properties\":{\"metadata\":{\"acmetscheck\":\"$timestamp\"},\"TTL\":10, \"TXTRecords\":[$values]}}"
  234. _azure_rest PUT "$acmeRecordURI" "$body" "$accesstoken"
  235. if [ "$_code" = "200" ] || [ "$_code" = '201' ]; then
  236. _info "validation value removed"
  237. return 0
  238. else
  239. _err "error removing validation value ($_code)"
  240. return 1
  241. fi
  242. fi
  243. fi
  244. }
  245. ################### Private functions below ##################################
  246. _azure_rest() {
  247. m=$1
  248. ep="$2"
  249. data="$3"
  250. accesstoken="$4"
  251. MAX_REQUEST_RETRY_TIMES=5
  252. _request_retry_times=0
  253. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  254. _debug3 _request_retry_times "$_request_retry_times"
  255. export _H1="authorization: Bearer $accesstoken"
  256. export _H2="accept: application/json"
  257. export _H3="Content-Type: application/json"
  258. # clear headers from previous request to avoid getting wrong http code on timeouts
  259. : >"$HTTP_HEADER"
  260. _debug "$ep"
  261. if [ "$m" != "GET" ]; then
  262. _secure_debug2 "data $data"
  263. response="$(_post "$data" "$ep" "" "$m")"
  264. else
  265. response="$(_get "$ep")"
  266. fi
  267. _ret="$?"
  268. _secure_debug2 "response $response"
  269. _code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\\r\\n")"
  270. _debug "http response code $_code"
  271. if [ "$_code" = "401" ]; then
  272. # we have an invalid access token set to expired
  273. _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "0"
  274. _err "Access denied. Invalid access token. Make sure your Azure settings are correct. See: $wiki"
  275. return 1
  276. fi
  277. # See https://learn.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific#general-rest-and-retry-guidelines for retryable HTTP codes
  278. if [ "$_ret" != "0" ] || [ -z "$_code" ] || [ "$_code" = "408" ] || [ "$_code" = "500" ] || [ "$_code" = "503" ] || [ "$_code" = "504" ]; then
  279. _request_retry_times="$(_math "$_request_retry_times" + 1)"
  280. _info "REST call error $_code retrying $ep in $_request_retry_times s"
  281. _sleep "$_request_retry_times"
  282. continue
  283. fi
  284. break
  285. done
  286. if [ "$_request_retry_times" = "$MAX_REQUEST_RETRY_TIMES" ]; then
  287. _err "Error Azure REST called was retried $MAX_REQUEST_RETRY_TIMES times."
  288. _err "Calling $ep failed."
  289. return 1
  290. fi
  291. response="$(echo "$response" | _normalizeJson)"
  292. return 0
  293. }
  294. ## Ref: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#request-an-access-token
  295. _azure_getaccess_token() {
  296. managedIdentity=$1
  297. tenantID=$2
  298. clientID=$3
  299. clientSecret=$4
  300. accesstoken="${AZUREDNS_ACCESSTOKEN:-$(_readaccountconf_mutable AZUREDNS_ACCESSTOKEN)}"
  301. expires_on="${AZUREDNS_TOKENVALIDTO:-$(_readaccountconf_mutable AZUREDNS_TOKENVALIDTO)}"
  302. # can we reuse the bearer token?
  303. if [ -n "$accesstoken" ] && [ -n "$expires_on" ]; then
  304. if [ "$(_time)" -lt "$expires_on" ]; then
  305. # brearer token is still valid - reuse it
  306. _debug "reusing bearer token"
  307. printf "%s" "$accesstoken"
  308. return 0
  309. else
  310. _debug "bearer token expired"
  311. fi
  312. fi
  313. _debug "getting new bearer token"
  314. if [ "$managedIdentity" = true ]; then
  315. # https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http
  316. if [ -n "$IDENTITY_ENDPOINT" ]; then
  317. # Some Azure environments may set IDENTITY_ENDPOINT (formerly MSI_ENDPOINT) to have an alternative metadata endpoint
  318. url="$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=https://management.azure.com/"
  319. headers="X-IDENTITY-HEADER: $IDENTITY_HEADER"
  320. else
  321. url="http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"
  322. headers="Metadata: true"
  323. fi
  324. export _H1="$headers"
  325. response="$(_get "$url")"
  326. response="$(echo "$response" | _normalizeJson)"
  327. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  328. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  329. else
  330. export _H1="accept: application/json"
  331. export _H2="Content-Type: application/x-www-form-urlencoded"
  332. 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"
  333. _secure_debug2 "data $body"
  334. response="$(_post "$body" "https://login.microsoftonline.com/$tenantID/oauth2/token" "" "POST")"
  335. _ret="$?"
  336. _secure_debug2 "response $response"
  337. response="$(echo "$response" | _normalizeJson)"
  338. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  339. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  340. fi
  341. if [ -z "$accesstoken" ]; then
  342. _err "No acccess token received. Check your Azure settings. See: $wiki"
  343. return 1
  344. fi
  345. if [ "$_ret" != "0" ]; then
  346. _err "error $response"
  347. return 1
  348. fi
  349. _saveaccountconf_mutable AZUREDNS_ACCESSTOKEN "$accesstoken"
  350. _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "$expires_on"
  351. printf "%s" "$accesstoken"
  352. return 0
  353. }
  354. _get_root() {
  355. domain=$1
  356. subscriptionId=$2
  357. accesstoken=$3
  358. i=1
  359. p=1
  360. ## Ref: https://learn.microsoft.com/en-us/rest/api/dns/zones/list?view=rest-dns-2018-05-01&tabs=HTTP
  361. ## returns up to 100 zones in one response. Handling more results is not implemented
  362. ## (ZoneListResult with continuation token for the next page of results)
  363. ##
  364. ## TODO: handle more than 100 results, as per:
  365. ## https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#azure-dns-limits
  366. ## The new limit is 250 Public DNS zones per subscription, while the old limit was only 100
  367. ##
  368. _azure_rest GET "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Network/dnszones?\$top=500&api-version=2017-09-01" "" "$accesstoken"
  369. # Find matching domain name in Json response
  370. while true; do
  371. h=$(printf "%s" "$domain" | cut -d . -f "$i"-100)
  372. _debug2 "Checking domain: $h"
  373. if [ -z "$h" ]; then
  374. #not valid
  375. _err "Invalid domain"
  376. return 1
  377. fi
  378. if _contains "$response" "\"name\":\"$h\"" >/dev/null; then
  379. _domain_id=$(echo "$response" | _egrep_o "\\{\"id\":\"[^\"]*\\/$h\"" | head -n 1 | cut -d : -f 2 | tr -d \")
  380. if [ "$_domain_id" ]; then
  381. if [ "$i" = 1 ]; then
  382. #create the record at the domain apex (@) if only the domain name was provided as --domain-alias
  383. _sub_domain="@"
  384. else
  385. _sub_domain=$(echo "$domain" | cut -d . -f 1-"$p")
  386. fi
  387. _domain=$h
  388. return 0
  389. fi
  390. return 1
  391. fi
  392. p=$i
  393. i=$(_math "$i" + 1)
  394. done
  395. return 1
  396. }