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.

393 lines
15 KiB

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