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.

399 lines
15 KiB

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