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