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.

407 lines
16 KiB

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