2021-07-05 12:23:03 +01:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
2021-12-20 14:19:53 +00:00
|
|
|
"github.com/superseriousbusiness/gotosocial/internal/ap"
|
2022-07-19 09:47:55 +01:00
|
|
|
"github.com/superseriousbusiness/gotosocial/internal/log"
|
2021-12-20 14:19:53 +00:00
|
|
|
|
2021-07-05 12:23:03 +01:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/go-fed/httpsig"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SignatureCheck checks whether an incoming http request has been signed. If so, it will check if the domain
|
|
|
|
// that signed the request is permitted to access the server. If it is permitted, the handler will set the key
|
2021-09-16 10:35:09 +01:00
|
|
|
// verifier and the signature in the gin context for use down the line.
|
2021-07-05 12:23:03 +01:00
|
|
|
func (m *Module) SignatureCheck(c *gin.Context) {
|
|
|
|
// create the verifier from the request
|
|
|
|
// if the request is signed, it will have a signature header
|
|
|
|
verifier, err := httpsig.NewVerifier(c.Request)
|
|
|
|
if err == nil {
|
|
|
|
// the request was signed!
|
|
|
|
|
|
|
|
// The key ID should be given in the signature so that we know where to fetch it from the remote server.
|
|
|
|
// This will be something like https://example.org/users/whatever_requesting_user#main-key
|
|
|
|
requestingPublicKeyID, err := url.Parse(verifier.KeyId())
|
|
|
|
if err == nil && requestingPublicKeyID != nil {
|
|
|
|
// we managed to parse the url!
|
|
|
|
|
|
|
|
// if the domain is blocked we want to bail as early as possible
|
2021-08-25 14:34:33 +01:00
|
|
|
blocked, err := m.db.IsURIBlocked(c.Request.Context(), requestingPublicKeyID)
|
2021-07-05 12:23:03 +01:00
|
|
|
if err != nil {
|
2022-07-19 09:47:55 +01:00
|
|
|
log.Errorf("could not tell if domain %s was blocked or not: %s", requestingPublicKeyID.Host, err)
|
2021-07-05 12:23:03 +01:00
|
|
|
c.AbortWithStatus(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2021-08-20 11:26:56 +01:00
|
|
|
if blocked {
|
2022-07-19 09:47:55 +01:00
|
|
|
log.Infof("domain %s is blocked", requestingPublicKeyID.Host)
|
2021-07-05 12:23:03 +01:00
|
|
|
c.AbortWithStatus(http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-09-16 10:35:09 +01:00
|
|
|
// set the verifier and signature on the context here to save some work further down the line
|
2021-12-20 14:19:53 +00:00
|
|
|
c.Set(string(ap.ContextRequestingPublicKeyVerifier), verifier)
|
2021-09-16 10:35:09 +01:00
|
|
|
signature := c.GetHeader("Signature")
|
|
|
|
if signature != "" {
|
2021-12-20 14:19:53 +00:00
|
|
|
c.Set(string(ap.ContextRequestingPublicKeySignature), signature)
|
2021-09-16 10:35:09 +01:00
|
|
|
}
|
2021-07-05 12:23:03 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|