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.

419 lines
16 KiB

3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
7 years ago
7 years ago
7 years ago
3 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
4 months ago
3 months ago
3 months ago
7 years ago
7 years ago
4 years ago
7 years ago
3 months ago
7 years ago
7 years ago
3 months ago
2 months ago
2 months 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. AZUREDNS_BEARERTOKEN Optional Bearer Token. Used instead of service principal credentials or managed identity
  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. export _H1="Metadata: true"
  317. response="$(_get http://169.254.169.254/metadata/identity/oauth2/token\?api-version=2018-02-01\&resource=https://management.azure.com/)"
  318. response="$(echo "$response" | _normalizeJson)"
  319. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  320. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  321. else
  322. export _H1="accept: application/json"
  323. export _H2="Content-Type: application/x-www-form-urlencoded"
  324. 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"
  325. _secure_debug2 "data $body"
  326. response="$(_post "$body" "https://login.microsoftonline.com/$tenantID/oauth2/token" "" "POST")"
  327. _ret="$?"
  328. _secure_debug2 "response $response"
  329. response="$(echo "$response" | _normalizeJson)"
  330. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  331. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  332. fi
  333. if [ -z "$accesstoken" ]; then
  334. _err "No acccess token received. Check your Azure settings. See: $wiki"
  335. return 1
  336. fi
  337. if [ "$_ret" != "0" ]; then
  338. _err "error $response"
  339. return 1
  340. fi
  341. _saveaccountconf_mutable AZUREDNS_ACCESSTOKEN "$accesstoken"
  342. _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "$expires_on"
  343. printf "%s" "$accesstoken"
  344. return 0
  345. }
  346. _get_root() {
  347. domain=$1
  348. subscriptionId=$2
  349. accesstoken=$3
  350. i=1
  351. p=1
  352. ## Ref: https://learn.microsoft.com/en-us/rest/api/dns/zones/list?view=rest-dns-2018-05-01&tabs=HTTP
  353. ## returns up to 100 zones in one response. Handling more results is not implemented
  354. ## (ZoneListResult with continuation token for the next page of results)
  355. ##
  356. ## TODO: handle more than 100 results, as per:
  357. ## https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#azure-dns-limits
  358. ## The new limit is 250 Public DNS zones per subscription, while the old limit was only 100
  359. ##
  360. _azure_rest GET "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Network/dnszones?\$top=500&api-version=2017-09-01" "" "$accesstoken"
  361. # Find matching domain name in Json response
  362. while true; do
  363. h=$(printf "%s" "$domain" | cut -d . -f "$i"-100)
  364. _debug2 "Checking domain: $h"
  365. if [ -z "$h" ]; then
  366. #not valid
  367. _err "Invalid domain"
  368. return 1
  369. fi
  370. if _contains "$response" "\"name\":\"$h\"" >/dev/null; then
  371. _domain_id=$(echo "$response" | _egrep_o "\\{\"id\":\"[^\"]*\\/$h\"" | head -n 1 | cut -d : -f 2 | tr -d \")
  372. if [ "$_domain_id" ]; then
  373. if [ "$i" = 1 ]; then
  374. #create the record at the domain apex (@) if only the domain name was provided as --domain-alias
  375. _sub_domain="@"
  376. else
  377. _sub_domain=$(echo "$domain" | cut -d . -f 1-"$p")
  378. fi
  379. _domain=$h
  380. return 0
  381. fi
  382. return 1
  383. fi
  384. p=$i
  385. i=$(_math "$i" + 1)
  386. done
  387. return 1
  388. }