-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpsig.go
264 lines (218 loc) · 7.46 KB
/
httpsig.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package httpsig
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"time"
"github.com/MatejLach/astreams"
"github.com/MatejLach/httpsignatures-go"
)
const (
requestDateHeader = "date"
requestTargetHeader = "(request-target)"
requestHostHeader = "host"
requestDigestHeader = "digest"
)
// ReqHasValidSignature validates the signature of POST requests by default
// reqAuthorPubKeyPem can optionally be specified to be the public key (RSA-SHA256 PEM format) of the actor sending the request, if it is empty, the key is fetched using http.Get
// strictMode=true additionally validates GET request signature as well as that the request Date is within the last 12 hours
func ReqHasValidSignature(ctx context.Context, req *http.Request, reqAuthorPubKeyPem string, strictMode bool) (bool, error) {
var err error
allowedMethods := []string{http.MethodPost}
if strictMode {
allowedMethods = append(allowedMethods, http.MethodGet)
}
if !slices.Contains(allowedMethods, req.Method) {
return false, fmt.Errorf("cannot verify request signature; %s is not a whitelisted request method", req.Method)
}
// verify the request body digest
if req.Method == http.MethodPost && req.Body != nil {
gotDigestB64 := req.Header.Get("Digest")
if gotDigestB64 == "" {
return false, fmt.Errorf("digest header value should not be empty for a POST request with a non-nil body")
}
digestAlgoSplit := strings.SplitN(gotDigestB64, "=", 2)
if len(digestAlgoSplit) != 2 || digestAlgoSplit[0] != "sha-256" {
return false, fmt.Errorf("mailformed request digest header; expected a sha-256 digest of the request body")
}
gotDigest, err := base64.StdEncoding.DecodeString(digestAlgoSplit[1])
if err != nil {
return false, err
}
computedDigestB64, err := calculateRequestBodySha256Digest(ctx, req)
if err != nil {
return false, err
}
computedDigest, err := base64.StdEncoding.DecodeString(computedDigestB64)
if err != nil {
return false, err
}
if string(gotDigest) != string(computedDigest) {
return false, fmt.Errorf("digest header value does not match computed digest of the request body")
}
}
// verify the signature
var comparisonHeader []string
gotSignature := req.Header.Get("Signature")
if gotSignature == "" {
return false, fmt.Errorf("no Signature header found")
}
gotSignature = strings.ReplaceAll(gotSignature, ", ", ",")
sigParts := strings.Split(gotSignature, ",")
sigMap := make(map[string]string, 3)
for _, part := range sigParts {
prefix := strings.Split(part, "=")[0]
switch prefix {
case "keyId":
sigMap["keyId"] = trimQuotes(strings.TrimPrefix(part, "keyId="))
case "headers":
sigMap["headers"] = strings.TrimPrefix(part, "headers=")
case "signature":
sigMap["signature"] = trimQuotes(strings.TrimPrefix(part, "signature="))
}
}
gotHeaders := strings.Split(sigMap["headers"], " ")
for idx, sigHeader := range gotHeaders {
gotHeaders[idx] = trimQuotes(sigHeader)
}
if reqAuthorPubKeyPem == "" {
sendingActorId, err := url.Parse(sigMap["keyId"])
if err != nil {
return false, err
}
reqActor, err := getActor(sendingActorId)
if err != nil {
return false, err
}
reqAuthorPubKeyPem = reqActor.PublicKey.PublicKeyPem
}
sendingActorPubKey, err := pubKeyFromString(reqAuthorPubKeyPem)
if err != nil {
return false, err
}
// reconstruct the signed headers from the plaintext headers sent as part of the request
for _, sigHeader := range gotHeaders {
if sigHeader == requestTargetHeader {
switch req.Method {
case http.MethodGet:
comparisonHeader = append(comparisonHeader, fmt.Sprintf("%s: %s", requestTargetHeader, requestTarget(req)))
case http.MethodPost:
comparisonHeader = append(comparisonHeader, fmt.Sprintf("%s: post /inbox", requestTargetHeader))
}
} else {
comparisonHeader = append(comparisonHeader, fmt.Sprintf("%s: %s", sigHeader, req.Header.Get(strings.ToUpper(sigHeader))))
}
}
comparisonHeaderDigest := sha256.Sum256([]byte(strings.Join(comparisonHeader, "\n")))
if strictMode {
// verify that Date is no more than 12 hours old
reqDate, err := http.ParseTime(req.Header.Get("Date"))
if err != nil {
return false, err
}
if reqDate.Before(time.Now().Add(time.Hour * time.Duration(-12))) {
return false, fmt.Errorf("incoming request is too old to process")
}
}
// the signature is base64 encoded in addition to being encrypted with the sending actor's private key
decodedSig, err := base64.StdEncoding.DecodeString(sigMap["signature"])
if err != nil {
return false, err
}
err = rsa.VerifyPKCS1v15(sendingActorPubKey, crypto.SHA256, comparisonHeaderDigest[:], decodedSig)
if err == nil {
return true, nil
}
return false, err
}
func SignRequest(ctx context.Context, req *http.Request, keyId *url.URL, privateKeyPem string) error {
req.Header.Set(requestTargetHeader, requestTarget(req))
req.Header.Set(requestHostHeader, req.URL.Host)
signHeaders := []string{requestTargetHeader, requestHostHeader, requestDateHeader}
if req.Method == http.MethodPost && req.Body != nil {
if req.Header.Get(requestDigestHeader) == "" {
reqBodyDigest, err := calculateRequestBodySha256Digest(ctx, req)
if err != nil {
return err
}
req.Header.Set(requestDigestHeader, fmt.Sprintf("sha-256=%s", reqBodyDigest))
}
signHeaders = append(signHeaders, requestDigestHeader)
}
sign := httpsignatures.NewSigner(httpsignatures.AlgorithmRsaSha256, signHeaders...)
return sign.SignRequest(keyId.String(), privateKeyPem, req, false)
}
func pubKeyFromString(publicKey string) (*rsa.PublicKey, error) {
if publicKey == "" {
return nil, fmt.Errorf("canot convert an emptpy string to a public key")
}
pemBlock, _ := pem.Decode([]byte(publicKey))
if pemBlock == nil {
return nil, fmt.Errorf("cannot parse RSA public key; invalid input")
}
parsedKey, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
if err != nil {
return nil, err
}
rsaPubKey, ok := parsedKey.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("key block is not a valid public key")
}
return rsaPubKey, nil
}
// getActor fetches and parses an AS2.0 Actor authoring a given request, given their fully qualified ID
func getActor(reqActorId *url.URL) (*astreams.Actor, error) {
var reqActor astreams.Actor
actorResp, err := http.Get(reqActorId.String())
if err != nil {
return nil, err
}
defer actorResp.Body.Close()
err = json.NewDecoder(actorResp.Body).Decode(&reqActor)
if err != nil {
return nil, err
}
return &reqActor, nil
}
func requestTarget(req *http.Request) string {
var rUrl string
if req.URL != nil {
rUrl = req.URL.RequestURI()
}
return fmt.Sprintf("%s %s", strings.ToLower(req.Method), rUrl)
}
// calculateRequestBodySha256Digest computes the sha256 sum of the given request body and base64 encodes the result
func calculateRequestBodySha256Digest(ctx context.Context, req *http.Request) (string, error) {
var err error
// don't consume the original request
rClone := req.Clone(ctx)
if req.Body != nil {
rClone.Body, err = req.GetBody()
if err != nil {
return "", err
}
}
if rClone.Body == nil {
return "", fmt.Errorf("cannot calculate digest of an empty request body")
}
reqBody, err := io.ReadAll(rClone.Body)
if err != nil {
return "", err
}
bodyDigest := sha256.Sum256(reqBody)
return base64.StdEncoding.EncodeToString(bodyDigest[:]), nil
}
func trimQuotes(input string) string {
return strings.Trim(strings.TrimSpace(input), `"'`)
}