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

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