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.

354 lines
12 KiB

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