example.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Command webhooks provides example consumer code for Tailscale
  4. // webhooks.
  5. package main
  6. import (
  7. "crypto/hmac"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net/http"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. type event struct {
  22. Timestamp string `json:"timestamp"`
  23. Version int `json:"version"`
  24. Type string `json:"type"`
  25. Tailnet string `json:"tailnet"`
  26. Message string `json:"message"`
  27. Data map[string]string `json:"data"`
  28. }
  29. const (
  30. currentVersion = "v1"
  31. secret = "tskey-webhook-xxxxx" // sensitive, here just as an example
  32. )
  33. var (
  34. errNotSigned = errors.New("webhook has no signature")
  35. errInvalidHeader = errors.New("webhook has an invalid signature")
  36. )
  37. func main() {
  38. http.HandleFunc("/webhook", webhooksHandler)
  39. if err := http.ListenAndServe(":80", nil); err != nil {
  40. log.Fatal(err)
  41. }
  42. }
  43. func webhooksHandler(w http.ResponseWriter, req *http.Request) {
  44. defer req.Body.Close()
  45. events, err := verifyWebhookSignature(req, secret)
  46. if err != nil {
  47. log.Printf("error validating signature: %v\n", err)
  48. } else {
  49. log.Printf("events received %v\n", events)
  50. // Do something with your events. :)
  51. }
  52. // The handler should always report 2XX except in the case of
  53. // transient failures (e.g. database backend is down).
  54. // Otherwise your future events will be blocked by retries.
  55. }
  56. // verifyWebhookSignature checks the request's "Tailscale-Webhook-Signature"
  57. // header to verify that the events were signed by your webhook secret.
  58. // If verification fails, an error is reported.
  59. // If verification succeeds, the list of contained events is reported.
  60. func verifyWebhookSignature(req *http.Request, secret string) (events []event, err error) {
  61. defer req.Body.Close()
  62. // Grab the signature sent on the request header.
  63. timestamp, signatures, err := parseSignatureHeader(req.Header.Get("Tailscale-Webhook-Signature"))
  64. if err != nil {
  65. return nil, err
  66. }
  67. // Verify that the timestamp is recent.
  68. // Here, we use a threshold of 5 minutes.
  69. if timestamp.Before(time.Now().Add(-time.Minute * 5)) {
  70. return nil, fmt.Errorf("invalid header: timestamp older than 5 minutes")
  71. }
  72. // Form the expected signature.
  73. b, err := io.ReadAll(req.Body)
  74. if err != nil {
  75. return nil, err
  76. }
  77. mac := hmac.New(sha256.New, []byte(secret))
  78. mac.Write([]byte(fmt.Sprint(timestamp.Unix())))
  79. mac.Write([]byte("."))
  80. mac.Write(b)
  81. want := hex.EncodeToString(mac.Sum(nil))
  82. // Verify that the signatures match.
  83. var match bool
  84. for _, signature := range signatures[currentVersion] {
  85. if subtle.ConstantTimeCompare([]byte(signature), []byte(want)) == 1 {
  86. match = true
  87. break
  88. }
  89. }
  90. if !match {
  91. return nil, fmt.Errorf("signature does not match: want = %q, got = %q", want, signatures[currentVersion])
  92. }
  93. // If verified, return the events.
  94. if err := json.Unmarshal(b, &events); err != nil {
  95. return nil, err
  96. }
  97. return events, nil
  98. }
  99. // parseSignatureHeader splits header into its timestamp and included signatures.
  100. // The signatures are reported as a map of version (e.g. "v1") to a list of signatures
  101. // found with that version.
  102. func parseSignatureHeader(header string) (timestamp time.Time, signatures map[string][]string, err error) {
  103. if header == "" {
  104. return time.Time{}, nil, fmt.Errorf("request has no signature")
  105. }
  106. signatures = make(map[string][]string)
  107. pairs := strings.Split(header, ",")
  108. for _, pair := range pairs {
  109. parts := strings.Split(pair, "=")
  110. if len(parts) != 2 {
  111. return time.Time{}, nil, errNotSigned
  112. }
  113. switch parts[0] {
  114. case "t":
  115. tsint, err := strconv.ParseInt(parts[1], 10, 64)
  116. if err != nil {
  117. return time.Time{}, nil, errInvalidHeader
  118. }
  119. timestamp = time.Unix(tsint, 0)
  120. case currentVersion:
  121. signatures[parts[0]] = append(signatures[parts[0]], parts[1])
  122. default:
  123. // Ignore unknown parts of the header.
  124. continue
  125. }
  126. }
  127. if len(signatures) == 0 {
  128. return time.Time{}, nil, errNotSigned
  129. }
  130. return
  131. }