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.

392 lines
15 KiB

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