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.

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