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.

380 lines
12 KiB

7 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
8 years ago
8 years ago
1 month ago
1 month ago
6 years ago
10 months ago
10 months ago
10 months ago
4 years ago
4 years ago
4 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. #!/usr/bin/env sh
  2. # shellcheck disable=SC2034
  3. dns_aws_info='Amazon AWS Route53 domain API
  4. Site: docs.aws.amazon.com/route53/
  5. Docs: github.com/acmesh-official/acme.sh/wiki/dnsapi#dns_aws
  6. Options:
  7. AWS_ACCESS_KEY_ID API Key ID
  8. AWS_SECRET_ACCESS_KEY API Secret
  9. '
  10. # All `_sleep` commands are included to avoid Route53 throttling, see
  11. # https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-requests
  12. AWS_HOST="route53.amazonaws.com"
  13. AWS_URL="https://$AWS_HOST"
  14. AWS_WIKI="https://github.com/acmesh-official/acme.sh/wiki/How-to-use-Amazon-Route53-API"
  15. ######## Public functions #####################
  16. #Usage: dns_myapi_add _acme-challenge.www.domain.com "XKrxpRBosdIKFzxW_CT3KLZNf6q0HG9i01zxXp5CPBs"
  17. dns_aws_add() {
  18. fulldomain=$1
  19. txtvalue=$2
  20. AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-$(_readaccountconf_mutable AWS_ACCESS_KEY_ID)}"
  21. AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-$(_readaccountconf_mutable AWS_SECRET_ACCESS_KEY)}"
  22. AWS_DNS_SLOWRATE="${AWS_DNS_SLOWRATE:-$(_readaccountconf_mutable AWS_DNS_SLOWRATE)}"
  23. if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
  24. _use_container_role || _use_instance_role
  25. fi
  26. if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
  27. AWS_ACCESS_KEY_ID=""
  28. AWS_SECRET_ACCESS_KEY=""
  29. _err "You haven't specified the aws route53 api key id and and api key secret yet."
  30. _err "Please create your key and try again. see $(__green $AWS_WIKI)"
  31. return 1
  32. fi
  33. #save for future use, unless using a role which will be fetched as needed
  34. if [ -z "$_using_role" ]; then
  35. _saveaccountconf_mutable AWS_ACCESS_KEY_ID "$AWS_ACCESS_KEY_ID"
  36. _saveaccountconf_mutable AWS_SECRET_ACCESS_KEY "$AWS_SECRET_ACCESS_KEY"
  37. _saveaccountconf_mutable AWS_DNS_SLOWRATE "$AWS_DNS_SLOWRATE"
  38. fi
  39. _debug "First detect the root zone"
  40. if ! _get_root "$fulldomain"; then
  41. _err "invalid domain"
  42. _sleep 1
  43. return 1
  44. fi
  45. _debug _domain_id "$_domain_id"
  46. _debug _sub_domain "$_sub_domain"
  47. _debug _domain "$_domain"
  48. _info "Getting existing records for $fulldomain"
  49. if ! aws_rest GET "2013-04-01$_domain_id/rrset" "name=$fulldomain&type=TXT"; then
  50. _sleep 1
  51. return 1
  52. fi
  53. if _contains "$response" "<Name>$fulldomain.</Name>"; then
  54. _resource_record="$(echo "$response" | sed 's/<ResourceRecordSet>/"/g' | tr '"' "\n" | grep "<Name>$fulldomain.</Name>" | _egrep_o "<ResourceRecords.*</ResourceRecords>" | sed "s/<ResourceRecords>//" | sed "s#</ResourceRecords>##")"
  55. _debug "_resource_record" "$_resource_record"
  56. else
  57. _debug "single new add"
  58. fi
  59. if [ "$_resource_record" ] && _contains "$response" "$txtvalue"; then
  60. _info "The TXT record already exists. Skipping."
  61. _sleep 1
  62. return 0
  63. fi
  64. _debug "Adding records"
  65. _aws_tmpl_xml="<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\"><ChangeBatch><Changes><Change><Action>UPSERT</Action><ResourceRecordSet><Name>$fulldomain</Name><Type>TXT</Type><TTL>300</TTL><ResourceRecords>$_resource_record<ResourceRecord><Value>\"$txtvalue\"</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>"
  66. if aws_rest POST "2013-04-01$_domain_id/rrset/" "" "$_aws_tmpl_xml" && _contains "$response" "ChangeResourceRecordSetsResponse"; then
  67. _info "TXT record updated successfully."
  68. if [ -n "$AWS_DNS_SLOWRATE" ]; then
  69. _info "Slow rate activated: sleeping for $AWS_DNS_SLOWRATE seconds"
  70. _sleep "$AWS_DNS_SLOWRATE"
  71. else
  72. _sleep 1
  73. fi
  74. return 0
  75. fi
  76. _sleep 1
  77. return 1
  78. }
  79. #fulldomain txtvalue
  80. dns_aws_rm() {
  81. fulldomain=$1
  82. txtvalue=$2
  83. AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-$(_readaccountconf_mutable AWS_ACCESS_KEY_ID)}"
  84. AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-$(_readaccountconf_mutable AWS_SECRET_ACCESS_KEY)}"
  85. AWS_DNS_SLOWRATE="${AWS_DNS_SLOWRATE:-$(_readaccountconf_mutable AWS_DNS_SLOWRATE)}"
  86. if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
  87. _use_container_role || _use_instance_role
  88. fi
  89. _debug "First detect the root zone"
  90. if ! _get_root "$fulldomain"; then
  91. _err "invalid domain"
  92. _sleep 1
  93. return 1
  94. fi
  95. _debug _domain_id "$_domain_id"
  96. _debug _sub_domain "$_sub_domain"
  97. _debug _domain "$_domain"
  98. _info "Getting existing records for $fulldomain"
  99. if ! aws_rest GET "2013-04-01$_domain_id/rrset" "name=$fulldomain&type=TXT"; then
  100. _sleep 1
  101. return 1
  102. fi
  103. if _contains "$response" "<Name>$fulldomain.</Name>"; then
  104. _resource_record="$(echo "$response" | sed 's/<ResourceRecordSet>/"/g' | tr '"' "\n" | grep "<Name>$fulldomain.</Name>" | _egrep_o "<ResourceRecords.*</ResourceRecords>" | sed "s/<ResourceRecords>//" | sed "s#</ResourceRecords>##")"
  105. _debug "_resource_record" "$_resource_record"
  106. else
  107. _debug "no records exist, skip"
  108. _sleep 1
  109. return 0
  110. fi
  111. _aws_tmpl_xml="<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><ResourceRecords>$_resource_record</ResourceRecords><Name>$fulldomain.</Name><Type>TXT</Type><TTL>300</TTL></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>"
  112. if aws_rest POST "2013-04-01$_domain_id/rrset/" "" "$_aws_tmpl_xml" && _contains "$response" "ChangeResourceRecordSetsResponse"; then
  113. _info "TXT record deleted successfully."
  114. if [ -n "$AWS_DNS_SLOWRATE" ]; then
  115. _info "Slow rate activated: sleeping for $AWS_DNS_SLOWRATE seconds"
  116. _sleep "$AWS_DNS_SLOWRATE"
  117. else
  118. _sleep 1
  119. fi
  120. return 0
  121. fi
  122. _sleep 1
  123. return 1
  124. }
  125. #################### Private functions below ##################################
  126. _get_root() {
  127. domain=$1
  128. i=1
  129. p=1
  130. # iterate over names (a.b.c.d -> b.c.d -> c.d -> d)
  131. while true; do
  132. h=$(printf "%s" "$domain" | cut -d . -f "$i"-100 | sed 's/\./\\./g')
  133. _debug "Checking domain: $h"
  134. if [ -z "$h" ]; then
  135. _error "invalid domain"
  136. return 1
  137. fi
  138. # iterate over paginated result for list_hosted_zones
  139. aws_rest GET "2013-04-01/hostedzone"
  140. while true; do
  141. if _contains "$response" "<Name>$h.</Name>"; then
  142. hostedzone="$(echo "$response" | tr -d '\n' | sed 's/<HostedZone>/#&/g' | tr '#' '\n' | _egrep_o "<HostedZone><Id>[^<]*<.Id><Name>$h.<.Name>.*<PrivateZone>false<.PrivateZone>.*<.HostedZone>")"
  143. _debug hostedzone "$hostedzone"
  144. if [ "$hostedzone" ]; then
  145. _domain_id=$(printf "%s\n" "$hostedzone" | _egrep_o "<Id>.*<.Id>" | head -n 1 | _egrep_o ">.*<" | tr -d "<>")
  146. if [ "$_domain_id" ]; then
  147. _sub_domain=$(printf "%s" "$domain" | cut -d . -f 1-"$p")
  148. _domain=$h
  149. return 0
  150. fi
  151. _err "Can't find domain with id: $h"
  152. return 1
  153. fi
  154. fi
  155. if _contains "$response" "<IsTruncated>true</IsTruncated>" && _contains "$response" "<NextMarker>"; then
  156. _debug "IsTruncated"
  157. _nextMarker="$(echo "$response" | _egrep_o "<NextMarker>.*</NextMarker>" | cut -d '>' -f 2 | cut -d '<' -f 1)"
  158. _debug "NextMarker" "$_nextMarker"
  159. else
  160. break
  161. fi
  162. _debug "Checking domain: $h - Next Page "
  163. aws_rest GET "2013-04-01/hostedzone" "marker=$_nextMarker"
  164. done
  165. p=$i
  166. i=$(_math "$i" + 1)
  167. done
  168. return 1
  169. }
  170. _use_container_role() {
  171. # automatically set if running inside ECS
  172. if [ -z "$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" ]; then
  173. _debug "No ECS environment variable detected"
  174. return 1
  175. fi
  176. _use_metadata "169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
  177. }
  178. _use_instance_role() {
  179. _instance_role_name_url="http://169.254.169.254/latest/meta-data/iam/security-credentials/"
  180. if _get "$_instance_role_name_url" true 1 | _head_n 1 | grep -Fq 401; then
  181. _debug "Using IMDSv2"
  182. _token_url="http://169.254.169.254/latest/api/token"
  183. export _H1="X-aws-ec2-metadata-token-ttl-seconds: 21600"
  184. _token="$(_post "" "$_token_url" "" "PUT")"
  185. _secure_debug3 "_token" "$_token"
  186. if [ -z "$_token" ]; then
  187. _debug "Unable to fetch IMDSv2 token from instance metadata"
  188. return 1
  189. fi
  190. export _H1="X-aws-ec2-metadata-token: $_token"
  191. fi
  192. if ! _get "$_instance_role_name_url" true 1 | _head_n 1 | grep -Fq 200; then
  193. _debug "Unable to fetch IAM role from instance metadata"
  194. return 1
  195. fi
  196. _instance_role_name=$(_get "$_instance_role_name_url" "" 1)
  197. _debug "_instance_role_name" "$_instance_role_name"
  198. _use_metadata "$_instance_role_name_url$_instance_role_name" "$_token"
  199. }
  200. _use_metadata() {
  201. export _H1="X-aws-ec2-metadata-token: $2"
  202. _aws_creds="$(
  203. _get "$1" "" 1 |
  204. _normalizeJson |
  205. tr '{,}' '\n' |
  206. while read -r _line; do
  207. _key="$(echo "${_line%%:*}" | tr -d '\"')"
  208. _value="${_line#*:}"
  209. _debug3 "_key" "$_key"
  210. _secure_debug3 "_value" "$_value"
  211. case "$_key" in
  212. AccessKeyId) echo "AWS_ACCESS_KEY_ID=$_value" ;;
  213. SecretAccessKey) echo "AWS_SECRET_ACCESS_KEY=$_value" ;;
  214. Token) echo "AWS_SESSION_TOKEN=$_value" ;;
  215. esac
  216. done |
  217. paste -sd' ' -
  218. )"
  219. _secure_debug "_aws_creds" "$_aws_creds"
  220. if [ -z "$_aws_creds" ]; then
  221. return 1
  222. fi
  223. eval "$_aws_creds"
  224. _using_role=true
  225. }
  226. #method uri qstr data
  227. aws_rest() {
  228. mtd="$1"
  229. ep="$2"
  230. qsr="$3"
  231. data="$4"
  232. _debug mtd "$mtd"
  233. _debug ep "$ep"
  234. _debug qsr "$qsr"
  235. _debug data "$data"
  236. CanonicalURI="/$ep"
  237. _debug2 CanonicalURI "$CanonicalURI"
  238. CanonicalQueryString="$qsr"
  239. _debug2 CanonicalQueryString "$CanonicalQueryString"
  240. RequestDate="$(date -u +"%Y%m%dT%H%M%SZ")"
  241. _debug2 RequestDate "$RequestDate"
  242. #RequestDate="20161120T141056Z" ##############
  243. export _H1="x-amz-date: $RequestDate"
  244. aws_host="$AWS_HOST"
  245. CanonicalHeaders="host:$aws_host\nx-amz-date:$RequestDate\n"
  246. SignedHeaders="host;x-amz-date"
  247. if [ -n "$AWS_SESSION_TOKEN" ]; then
  248. export _H3="x-amz-security-token: $AWS_SESSION_TOKEN"
  249. CanonicalHeaders="${CanonicalHeaders}x-amz-security-token:$AWS_SESSION_TOKEN\n"
  250. SignedHeaders="${SignedHeaders};x-amz-security-token"
  251. fi
  252. _debug2 CanonicalHeaders "$CanonicalHeaders"
  253. _debug2 SignedHeaders "$SignedHeaders"
  254. RequestPayload="$data"
  255. _debug2 RequestPayload "$RequestPayload"
  256. Hash="sha256"
  257. CanonicalRequest="$mtd\n$CanonicalURI\n$CanonicalQueryString\n$CanonicalHeaders\n$SignedHeaders\n$(printf "%s" "$RequestPayload" | _digest "$Hash" hex)"
  258. _debug2 CanonicalRequest "$CanonicalRequest"
  259. HashedCanonicalRequest="$(printf "$CanonicalRequest%s" | _digest "$Hash" hex)"
  260. _debug2 HashedCanonicalRequest "$HashedCanonicalRequest"
  261. Algorithm="AWS4-HMAC-SHA256"
  262. _debug2 Algorithm "$Algorithm"
  263. RequestDateOnly="$(echo "$RequestDate" | cut -c 1-8)"
  264. _debug2 RequestDateOnly "$RequestDateOnly"
  265. Region="us-east-1"
  266. Service="route53"
  267. CredentialScope="$RequestDateOnly/$Region/$Service/aws4_request"
  268. _debug2 CredentialScope "$CredentialScope"
  269. StringToSign="$Algorithm\n$RequestDate\n$CredentialScope\n$HashedCanonicalRequest"
  270. _debug2 StringToSign "$StringToSign"
  271. kSecret="AWS4$AWS_SECRET_ACCESS_KEY"
  272. #kSecret="wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" ############################
  273. _secure_debug2 kSecret "$kSecret"
  274. kSecretH="$(printf "%s" "$kSecret" | _hex_dump | tr -d " ")"
  275. _secure_debug2 kSecretH "$kSecretH"
  276. kDateH="$(printf "$RequestDateOnly%s" | _hmac "$Hash" "$kSecretH" hex)"
  277. _debug2 kDateH "$kDateH"
  278. kRegionH="$(printf "$Region%s" | _hmac "$Hash" "$kDateH" hex)"
  279. _debug2 kRegionH "$kRegionH"
  280. kServiceH="$(printf "$Service%s" | _hmac "$Hash" "$kRegionH" hex)"
  281. _debug2 kServiceH "$kServiceH"
  282. kSigningH="$(printf "%s" "aws4_request" | _hmac "$Hash" "$kServiceH" hex)"
  283. _debug2 kSigningH "$kSigningH"
  284. signature="$(printf "$StringToSign%s" | _hmac "$Hash" "$kSigningH" hex)"
  285. _debug2 signature "$signature"
  286. Authorization="$Algorithm Credential=$AWS_ACCESS_KEY_ID/$CredentialScope, SignedHeaders=$SignedHeaders, Signature=$signature"
  287. _debug2 Authorization "$Authorization"
  288. _H2="Authorization: $Authorization"
  289. _debug _H2 "$_H2"
  290. url="$AWS_URL/$ep"
  291. if [ "$qsr" ]; then
  292. url="$AWS_URL/$ep?$qsr"
  293. fi
  294. if [ "$mtd" = "GET" ]; then
  295. response="$(_get "$url")"
  296. else
  297. response="$(_post "$data" "$url")"
  298. fi
  299. _ret="$?"
  300. _debug2 response "$response"
  301. if [ "$_ret" = "0" ]; then
  302. if _contains "$response" "<ErrorResponse"; then
  303. _err "Response error:$response"
  304. return 1
  305. fi
  306. fi
  307. return "$_ret"
  308. }