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.

403 lines
15 KiB

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