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.

387 lines
14 KiB

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