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.

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