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.

395 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. accesstoken=$(_azure_getaccess_token "$AZUREDNS_MANAGEDIDENTITY" "$AZUREDNS_TENANTID" "$AZUREDNS_APPID" "$AZUREDNS_CLIENTSECRET")
  180. if ! _get_root "$fulldomain" "$AZUREDNS_SUBSCRIPTIONID" "$accesstoken"; then
  181. _err "invalid domain"
  182. return 1
  183. fi
  184. _debug _domain_id "$_domain_id"
  185. _debug _sub_domain "$_sub_domain"
  186. _debug _domain "$_domain"
  187. acmeRecordURI="https://management.azure.com$(printf '%s' "$_domain_id" | sed 's/\\//g')/TXT/$_sub_domain?api-version=2017-09-01"
  188. _debug "$acmeRecordURI"
  189. # Get existing TXT record
  190. _azure_rest GET "$acmeRecordURI" "" "$accesstoken"
  191. timestamp="$(_time)"
  192. if [ "$_code" = "200" ]; then
  193. vlist="$(echo "$response" | _egrep_o "\"value\"\\s*:\\s*\\[\\s*\"[^\"]*\"\\s*]" | cut -d : -f 2 | tr -d "[]\"" | grep -v -- "$txtvalue")"
  194. values=""
  195. comma=""
  196. for v in $vlist; do
  197. values="$values$comma{\"value\":[\"$v\"]}"
  198. comma=","
  199. done
  200. if [ -z "$values" ]; then
  201. # No values left remove record
  202. _debug "removing validation record completely $acmeRecordURI"
  203. _azure_rest DELETE "$acmeRecordURI" "" "$accesstoken"
  204. if [ "$_code" = "200" ] || [ "$_code" = '204' ]; then
  205. _info "validation record removed"
  206. else
  207. _err "error removing validation record ($_code)"
  208. return 1
  209. fi
  210. else
  211. # Remove only txtvalue from the TXT Record
  212. body="{\"properties\":{\"metadata\":{\"acmetscheck\":\"$timestamp\"},\"TTL\":10, \"TXTRecords\":[$values]}}"
  213. _azure_rest PUT "$acmeRecordURI" "$body" "$accesstoken"
  214. if [ "$_code" = "200" ] || [ "$_code" = '201' ]; then
  215. _info "validation value removed"
  216. return 0
  217. else
  218. _err "error removing validation value ($_code)"
  219. return 1
  220. fi
  221. fi
  222. fi
  223. }
  224. ################### Private functions below ##################################
  225. _azure_rest() {
  226. m=$1
  227. ep="$2"
  228. data="$3"
  229. accesstoken="$4"
  230. MAX_REQUEST_RETRY_TIMES=5
  231. _request_retry_times=0
  232. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  233. _debug3 _request_retry_times "$_request_retry_times"
  234. export _H1="authorization: Bearer $accesstoken"
  235. export _H2="accept: application/json"
  236. export _H3="Content-Type: application/json"
  237. # clear headers from previous request to avoid getting wrong http code on timeouts
  238. : >"$HTTP_HEADER"
  239. _debug "$ep"
  240. if [ "$m" != "GET" ]; then
  241. _secure_debug2 "data $data"
  242. response="$(_post "$data" "$ep" "" "$m")"
  243. else
  244. response="$(_get "$ep")"
  245. fi
  246. _ret="$?"
  247. _secure_debug2 "response $response"
  248. _code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\\r\\n")"
  249. _debug "http response code $_code"
  250. if [ "$_code" = "401" ]; then
  251. # we have an invalid access token set to expired
  252. _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "0"
  253. _err "access denied make sure your Azure settings are correct. See $WIKI"
  254. return 1
  255. fi
  256. # See https://docs.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific#general-rest-and-retry-guidelines for retryable HTTP codes
  257. if [ "$_ret" != "0" ] || [ -z "$_code" ] || [ "$_code" = "408" ] || [ "$_code" = "500" ] || [ "$_code" = "503" ] || [ "$_code" = "504" ]; then
  258. _request_retry_times="$(_math "$_request_retry_times" + 1)"
  259. _info "REST call error $_code retrying $ep in $_request_retry_times s"
  260. _sleep "$_request_retry_times"
  261. continue
  262. fi
  263. break
  264. done
  265. if [ "$_request_retry_times" = "$MAX_REQUEST_RETRY_TIMES" ]; then
  266. _err "Error Azure REST called was retried $MAX_REQUEST_RETRY_TIMES times."
  267. _err "Calling $ep failed."
  268. return 1
  269. fi
  270. response="$(echo "$response" | _normalizeJson)"
  271. return 0
  272. }
  273. ## Ref: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-service-to-service#request-an-access-token
  274. _azure_getaccess_token() {
  275. managedIdentity=$1
  276. tenantID=$2
  277. clientID=$3
  278. clientSecret=$4
  279. accesstoken="${AZUREDNS_BEARERTOKEN:-$(_readaccountconf_mutable AZUREDNS_BEARERTOKEN)}"
  280. expires_on="${AZUREDNS_TOKENVALIDTO:-$(_readaccountconf_mutable AZUREDNS_TOKENVALIDTO)}"
  281. # can we reuse the bearer token?
  282. if [ -n "$accesstoken" ] && [ -n "$expires_on" ]; then
  283. if [ "$(_time)" -lt "$expires_on" ]; then
  284. # brearer token is still valid - reuse it
  285. _debug "reusing bearer token"
  286. printf "%s" "$accesstoken"
  287. return 0
  288. else
  289. _debug "bearer token expired"
  290. fi
  291. fi
  292. _debug "getting new bearer token"
  293. if [ "$managedIdentity" = true ]; then
  294. # https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http
  295. export _H1="Metadata: true"
  296. response="$(_get http://169.254.169.254/metadata/identity/oauth2/token\?api-version=2018-02-01\&resource=https://management.azure.com/)"
  297. response="$(echo "$response" | _normalizeJson)"
  298. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  299. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  300. else
  301. export _H1="accept: application/json"
  302. export _H2="Content-Type: application/x-www-form-urlencoded"
  303. 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"
  304. _secure_debug2 "data $body"
  305. response="$(_post "$body" "https://login.microsoftonline.com/$tenantID/oauth2/token" "" "POST")"
  306. _ret="$?"
  307. _secure_debug2 "response $response"
  308. response="$(echo "$response" | _normalizeJson)"
  309. accesstoken=$(echo "$response" | _egrep_o "\"access_token\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  310. expires_on=$(echo "$response" | _egrep_o "\"expires_on\":\"[^\"]*\"" | _head_n 1 | cut -d : -f 2 | tr -d \")
  311. fi
  312. if [ -z "$accesstoken" ]; then
  313. _err "no acccess token received. Check your Azure settings see $WIKI"
  314. return 1
  315. fi
  316. if [ "$_ret" != "0" ]; then
  317. _err "error $response"
  318. return 1
  319. fi
  320. _saveaccountconf_mutable AZUREDNS_BEARERTOKEN "$accesstoken"
  321. _saveaccountconf_mutable AZUREDNS_TOKENVALIDTO "$expires_on"
  322. printf "%s" "$accesstoken"
  323. return 0
  324. }
  325. _get_root() {
  326. domain=$1
  327. subscriptionId=$2
  328. accesstoken=$3
  329. i=1
  330. p=1
  331. ## Ref: https://docs.microsoft.com/en-us/rest/api/dns/zones/list
  332. ## returns up to 100 zones in one response therefore handling more results is not not implemented
  333. ## (ZoneListResult with continuation token for the next page of results)
  334. ## Per https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits#dns-limits you are limited to 100 Zone/subscriptions anyways
  335. ##
  336. _azure_rest GET "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Network/dnszones?\$top=500&api-version=2017-09-01" "" "$accesstoken"
  337. # Find matching domain name in Json response
  338. while true; do
  339. h=$(printf "%s" "$domain" | cut -d . -f $i-100)
  340. _debug2 "Checking domain: $h"
  341. if [ -z "$h" ]; then
  342. #not valid
  343. _err "Invalid domain"
  344. return 1
  345. fi
  346. if _contains "$response" "\"name\":\"$h\"" >/dev/null; then
  347. _domain_id=$(echo "$response" | _egrep_o "\\{\"id\":\"[^\"]*\\/$h\"" | head -n 1 | cut -d : -f 2 | tr -d \")
  348. if [ "$_domain_id" ]; then
  349. if [ "$i" = 1 ]; then
  350. #create the record at the domain apex (@) if only the domain name was provided as --domain-alias
  351. _sub_domain="@"
  352. else
  353. _sub_domain=$(echo "$domain" | cut -d . -f 1-$p)
  354. fi
  355. _domain=$h
  356. return 0
  357. fi
  358. return 1
  359. fi
  360. p=$i
  361. i=$(_math "$i" + 1)
  362. done
  363. return 1
  364. }