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