sigv4.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package sigv4
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "sort"
  13. "strings"
  14. "time"
  15. )
  16. type contextKey string
  17. const (
  18. CredentialsContextKey contextKey = "credentials"
  19. )
  20. type AWSCredentials struct {
  21. AccessKeyID string
  22. SecretAccessKey string
  23. SessionToken string
  24. AccountID string
  25. }
  26. // Mock credential store - in production, this would be a database or external service
  27. var mockCredentials = map[string]AWSCredentials{
  28. "AKIAIOSFODNN7EXAMPLE": {
  29. AccessKeyID: "AKIAIOSFODNN7EXAMPLE",
  30. SecretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
  31. AccountID: "123456789012",
  32. },
  33. "ASIAUIJXACK3L66H7KB4": {
  34. AccessKeyID: "ASIAUIJXACK3L66H7KB4",
  35. SecretAccessKey: "test-secret-key",
  36. SessionToken: "test-session-token",
  37. AccountID: "292709995190",
  38. },
  39. }
  40. // ValidateSigV4Middleware validates AWS Signature Version 4
  41. func ValidateSigV4Middleware(next http.HandlerFunc) http.HandlerFunc {
  42. return func(w http.ResponseWriter, r *http.Request) {
  43. // Read the body FIRST before any processing
  44. bodyBytes, err := io.ReadAll(r.Body)
  45. if err != nil {
  46. writeAuthError(w, "InvalidRequest", "Failed to read request body")
  47. return
  48. }
  49. // Restore the body for downstream handlers
  50. r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
  51. // Log the body for debugging
  52. log.Printf("Request body length: %d bytes", len(bodyBytes))
  53. //if len(bodyBytes) > 0 {
  54. //log.Printf("Request body: %s", string(bodyBytes))
  55. //}
  56. // Parse authorization header
  57. authHeader := r.Header.Get("Authorization")
  58. if authHeader == "" {
  59. writeAuthError(w, "MissingAuthenticationToken", "Authorization header cannot be empty")
  60. return
  61. }
  62. // Parse SigV4 components
  63. sigV4, err := parseSigV4Header(authHeader)
  64. if err != nil {
  65. writeAuthError(w, "IncompleteSignature", err.Error())
  66. return
  67. }
  68. // Validate credential
  69. creds, ok := mockCredentials[sigV4.AccessKeyID]
  70. if !ok {
  71. writeAuthError(w, "InvalidClientTokenId", "The security token included in the request is invalid")
  72. return
  73. }
  74. // Validate date
  75. dateHeader := r.Header.Get("X-Amz-Date")
  76. if dateHeader == "" {
  77. writeAuthError(w, "InvalidRequest", "X-Amz-Date header is required")
  78. return
  79. }
  80. reqTime, err := time.Parse("20060102T150405Z", dateHeader)
  81. if err != nil {
  82. writeAuthError(w, "InvalidRequest", "Invalid X-Amz-Date format")
  83. return
  84. }
  85. // Check if request is within 15 minutes
  86. now := time.Now().UTC()
  87. if now.Sub(reqTime) > 15*time.Minute {
  88. writeAuthError(w, "RequestExpired", "Request has expired")
  89. return
  90. }
  91. if reqTime.Sub(now) > 15*time.Minute {
  92. writeAuthError(w, "SignatureDoesNotMatch", "Signature not yet current")
  93. return
  94. }
  95. // Calculate expected signature with the actual body bytes
  96. expectedSig, err := calculateSignature(r, bodyBytes, creds, sigV4)
  97. if err != nil {
  98. writeAuthError(w, "InternalError", fmt.Sprintf("Failed to calculate signature: %v", err))
  99. return
  100. }
  101. // Compare signatures
  102. log.Printf("Expected signature: %s", expectedSig)
  103. log.Printf("Provided signature: %s", sigV4.Signature)
  104. if expectedSig != sigV4.Signature {
  105. writeAuthError(w, "SignatureDoesNotMatch",
  106. "The request signature we calculated does not match the signature you provided")
  107. return
  108. }
  109. // Validate session token if present
  110. if creds.SessionToken != "" {
  111. reqToken := r.Header.Get("X-Amz-Security-Token")
  112. if reqToken != creds.SessionToken {
  113. writeAuthError(w, "InvalidClientTokenId", "The security token included in the request is invalid")
  114. return
  115. }
  116. }
  117. // Add credentials to context
  118. ctx := context.WithValue(r.Context(), CredentialsContextKey, creds)
  119. next.ServeHTTP(w, r.WithContext(ctx))
  120. }
  121. }
  122. type sigV4Components struct {
  123. AccessKeyID string
  124. CredentialScope string
  125. SignedHeaders []string
  126. Signature string
  127. Date string
  128. Region string
  129. Service string
  130. }
  131. func parseSigV4Header(authHeader string) (*sigV4Components, error) {
  132. if !strings.HasPrefix(authHeader, "AWS4-HMAC-SHA256 ") {
  133. return nil, fmt.Errorf("Authorization header must start with 'AWS4-HMAC-SHA256'")
  134. }
  135. authHeader = strings.TrimPrefix(authHeader, "AWS4-HMAC-SHA256 ")
  136. parts := strings.Split(authHeader, ", ")
  137. sig := &sigV4Components{}
  138. for _, part := range parts {
  139. kv := strings.SplitN(part, "=", 2)
  140. if len(kv) != 2 {
  141. return nil, fmt.Errorf("Invalid key=value pair in Authorization header")
  142. }
  143. key := strings.TrimSpace(kv[0])
  144. value := strings.TrimSpace(kv[1])
  145. switch key {
  146. case "Credential":
  147. credParts := strings.Split(value, "/")
  148. if len(credParts) != 5 {
  149. return nil, fmt.Errorf("Invalid credential format")
  150. }
  151. sig.AccessKeyID = strings.ReplaceAll(credParts[0], "\"", "")
  152. sig.Date = credParts[1]
  153. sig.Region = credParts[2]
  154. sig.Service = credParts[3]
  155. sig.CredentialScope = strings.Join(credParts[1:], "/")
  156. case "SignedHeaders":
  157. sig.SignedHeaders = strings.Split(value, ";")
  158. case "Signature":
  159. sig.Signature = value
  160. }
  161. }
  162. if sig.AccessKeyID == "" {
  163. return nil, fmt.Errorf("Authorization header requires 'Credential' parameter")
  164. }
  165. if sig.Signature == "" {
  166. return nil, fmt.Errorf("Authorization header requires 'Signature' parameter")
  167. }
  168. return sig, nil
  169. }
  170. func calculateSignature(r *http.Request, body []byte, creds AWSCredentials, sigV4 *sigV4Components) (string, error) {
  171. amzDate := r.Header.Get("X-Amz-Date")
  172. canonicalRequest := buildCanonicalRequest(r, body, sigV4.SignedHeaders)
  173. stringToSign := buildStringToSign(canonicalRequest, sigV4, amzDate)
  174. log.Printf("String to sign:\n%s", stringToSign)
  175. signingKey := deriveSigningKey(creds.SecretAccessKey, sigV4.Date, sigV4.Region, sigV4.Service)
  176. signature := hmacSHA256(signingKey, stringToSign)
  177. finalSig := hex.EncodeToString(signature)
  178. return finalSig, nil
  179. }
  180. func buildCanonicalRequest(r *http.Request, body []byte, signedHeaders []string) string {
  181. // Method
  182. method := r.Method
  183. // Canonical URI - Use RequestURI which preserves URL encoding
  184. // Split RequestURI to get just the path (before the query string)
  185. canonicalURI := r.RequestURI
  186. if idx := strings.Index(canonicalURI, "?"); idx != -1 {
  187. canonicalURI = canonicalURI[:idx]
  188. }
  189. if canonicalURI == "" {
  190. canonicalURI = "/"
  191. }
  192. // Canonical query string - MUST BE SORTED
  193. canonicalQueryString := buildCanonicalQueryString(r)
  194. // Canonical headers (already includes trailing newlines)
  195. canonicalHeaders := buildCanonicalHeaders(r, signedHeaders)
  196. // Signed headers
  197. signedHeadersStr := strings.Join(signedHeaders, ";")
  198. // Payload hash - THIS IS THE KEY FIX
  199. // Use the actual body bytes passed in, not an empty body
  200. payloadHash := sha256Hash(body)
  201. canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s",
  202. method,
  203. canonicalURI,
  204. canonicalQueryString,
  205. canonicalHeaders,
  206. signedHeadersStr,
  207. payloadHash,
  208. )
  209. log.Printf("=== Canonical Request ===")
  210. log.Printf("Method: %s", method)
  211. log.Printf("Canonical URI: %s", canonicalURI)
  212. log.Printf("Canonical Query String: %s", canonicalQueryString)
  213. log.Printf("Canonical Headers:\n%s", canonicalHeaders)
  214. log.Printf("Signed Headers: %s", signedHeadersStr)
  215. log.Printf("Payload Hash: %s", payloadHash)
  216. log.Printf("Full Canonical Request:\n%s", canonicalRequest)
  217. log.Printf("========================")
  218. return canonicalRequest
  219. }
  220. func buildCanonicalQueryString(r *http.Request) string {
  221. if r.URL.RawQuery == "" {
  222. return ""
  223. }
  224. // Parse the query parameters properly
  225. query := r.URL.Query()
  226. // Get all keys and sort them
  227. keys := make([]string, 0, len(query))
  228. for k := range query {
  229. keys = append(keys, k)
  230. }
  231. sort.Strings(keys)
  232. // Build the canonical query string
  233. var params []string
  234. for _, key := range keys {
  235. values := query[key]
  236. // Sort values for this key
  237. sort.Strings(values)
  238. for _, value := range values {
  239. if value == "" {
  240. // Empty value - add just key with equals sign
  241. params = append(params, key+"=")
  242. } else {
  243. // Non-empty value
  244. params = append(params, key+"="+value)
  245. }
  246. }
  247. }
  248. return strings.Join(params, "&")
  249. }
  250. func buildCanonicalHeaders(r *http.Request, signedHeaders []string) string {
  251. headers := make(map[string]string)
  252. for _, header := range signedHeaders {
  253. headerLower := strings.ToLower(strings.TrimSpace(header))
  254. // Special handling for Host header
  255. if headerLower == "host" {
  256. headers[headerLower] = r.Host
  257. continue
  258. }
  259. values := r.Header[http.CanonicalHeaderKey(header)]
  260. if len(values) > 0 {
  261. trimmedValues := make([]string, len(values))
  262. for i, v := range values {
  263. trimmedValues[i] = strings.TrimSpace(v)
  264. }
  265. headers[headerLower] = strings.Join(trimmedValues, ",")
  266. }
  267. }
  268. // Sort headers
  269. keys := make([]string, 0, len(headers))
  270. for k := range headers {
  271. keys = append(keys, k)
  272. }
  273. sort.Strings(keys)
  274. // Build canonical headers string
  275. var canonical strings.Builder
  276. for _, k := range keys {
  277. canonical.WriteString(k)
  278. canonical.WriteString(":")
  279. canonical.WriteString(headers[k])
  280. canonical.WriteString("\n")
  281. }
  282. return canonical.String()
  283. }
  284. func buildStringToSign(canonicalRequest string, sigV4 *sigV4Components, amzDate string) string {
  285. canonicalRequestHash := sha256Hash([]byte(canonicalRequest))
  286. stringToSign := fmt.Sprintf("AWS4-HMAC-SHA256\n%s\n%s\n%s",
  287. amzDate,
  288. sigV4.CredentialScope,
  289. canonicalRequestHash,
  290. )
  291. return stringToSign
  292. }
  293. func deriveSigningKey(secretKey, date, region, service string) []byte {
  294. kDate := hmacSHA256([]byte("AWS4"+secretKey), date)
  295. kRegion := hmacSHA256(kDate, region)
  296. kService := hmacSHA256(kRegion, service)
  297. kSigning := hmacSHA256(kService, "aws4_request")
  298. return kSigning
  299. }
  300. func hmacSHA256(key []byte, data string) []byte {
  301. h := hmac.New(sha256.New, key)
  302. h.Write([]byte(data))
  303. return h.Sum(nil)
  304. }
  305. func sha256Hash(data []byte) string {
  306. hash := sha256.Sum256(data)
  307. return hex.EncodeToString(hash[:])
  308. }
  309. func writeAuthError(w http.ResponseWriter, code, message string) {
  310. w.Header().Set("Content-Type", "application/xml")
  311. w.WriteHeader(http.StatusForbidden)
  312. errorXML := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
  313. <ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  314. <Error>
  315. <Type>Sender</Type>
  316. <Code>%s</Code>
  317. <Message>%s</Message>
  318. </Error>
  319. <RequestId>%d</RequestId>
  320. </ErrorResponse>`, code, message, time.Now().Unix())
  321. w.Write([]byte(errorXML))
  322. }