2020-11-16 13:42:23 +01:00
package middleware
import (
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
2020-11-20 16:00:11 +01:00
"net/http"
"net/url"
"strings"
"time"
2022-05-04 14:49:59 +02:00
"github.com/owncloud/ocis/v2/ocis-pkg/log"
2022-06-20 16:49:06 +02:00
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
2023-03-15 17:20:14 +01:00
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles"
2025-03-04 16:02:36 +01:00
revactx "github.com/owncloud/reva/v2/pkg/ctx"
2024-02-26 16:08:03 +01:00
microstore "go-micro.dev/v4/store"
2020-11-16 13:42:23 +01:00
"golang.org/x/crypto/pbkdf2"
)
2022-08-08 15:49:22 +02:00
const (
_paramOCSignature = "OC-Signature"
2024-10-22 10:57:01 +02:00
_paramOCCredential = "OC-Credential" // #nosec G101
2022-08-08 15:49:22 +02:00
_paramOCDate = "OC-Date"
_paramOCExpires = "OC-Expires"
_paramOCVerb = "OC-Verb"
2024-02-07 15:44:33 +01:00
_paramOCAlgo = "OC-Algo"
2022-08-08 15:49:22 +02:00
)
2020-11-16 13:42:23 +01:00
2022-08-08 15:49:22 +02:00
var (
_requiredParams = [ ... ] string {
_paramOCSignature ,
_paramOCCredential ,
_paramOCDate ,
_paramOCExpires ,
_paramOCVerb ,
2020-11-16 13:42:23 +01:00
}
2022-08-08 15:49:22 +02:00
)
2020-11-16 13:42:23 +01:00
2022-08-16 16:53:27 +02:00
// SignedURLAuthenticator is the authenticator responsible for authenticating signed URL requests.
2022-08-08 15:49:22 +02:00
type SignedURLAuthenticator struct {
Logger log . Logger
PreSignedURLConfig config . PreSignedURL
UserProvider backend . UserBackend
2023-03-15 17:20:14 +01:00
UserRoleAssigner userroles . UserRoleAssigner
2024-02-26 16:08:03 +01:00
Store microstore . Store
2024-02-07 15:44:33 +01:00
Now func () time . Time
2020-11-16 13:42:23 +01:00
}
2022-08-04 17:38:55 +02:00
func ( m SignedURLAuthenticator ) shouldServe ( req * http . Request ) bool {
2022-08-08 15:49:22 +02:00
if ! m . PreSignedURLConfig . Enabled {
2020-11-20 16:00:11 +01:00
return false
}
2022-08-08 15:49:22 +02:00
return req . URL . Query (). Get ( _paramOCSignature ) != ""
2020-11-16 13:42:23 +01:00
}
2022-08-04 17:38:55 +02:00
func ( m SignedURLAuthenticator ) validate ( req * http . Request ) ( err error ) {
2020-11-16 13:42:23 +01:00
query := req . URL . Query ()
2024-02-07 15:44:33 +01:00
if err := m . allRequiredParametersArePresent ( query ); err != nil {
2020-11-16 13:42:23 +01:00
return err
}
2024-02-07 15:44:33 +01:00
if err := m . requestMethodMatches ( req . Method , query ); err != nil {
2020-11-16 13:42:23 +01:00
return err
}
2024-02-07 15:44:33 +01:00
if err := m . requestMethodIsAllowed ( req . Method ); err != nil {
2020-11-16 13:42:23 +01:00
return err
}
2024-02-07 15:44:33 +01:00
if err = m . urlIsExpired ( query ); err != nil {
2020-11-16 13:42:23 +01:00
return err
}
2024-02-07 15:44:33 +01:00
if err := m . signatureIsValid ( req ); err != nil {
2020-11-16 13:42:23 +01:00
return err
}
return nil
}
2024-02-07 15:44:33 +01:00
func ( m SignedURLAuthenticator ) allRequiredParametersArePresent ( query url . Values ) ( err error ) {
2020-11-16 13:42:23 +01:00
// check if required query parameters exist in given request query parameters
// OC-Signature - the computed signature - server will verify the request upon this REQUIRED
// OC-Credential - defines the user scope (shall we use the owncloud user id here - this might leak internal data ....) REQUIRED
// OC-Date - defined the date the url was signed (ISO 8601 UTC) REQUIRED
// OC-Expires - defines the expiry interval in seconds (between 1 and 604800 = 7 days) REQUIRED
// TODO OC-Verb - defines for which http verb the request is valid - defaults to GET OPTIONAL
2022-08-08 15:49:22 +02:00
for _ , p := range _requiredParams {
2020-11-16 13:42:23 +01:00
if query . Get ( p ) == "" {
2024-02-07 15:44:33 +01:00
return fmt . Errorf ( "required %s parameter not found" , p )
2020-11-16 13:42:23 +01:00
}
}
2024-02-07 15:44:33 +01:00
return nil
2020-11-16 13:42:23 +01:00
}
2024-02-07 15:44:33 +01:00
func ( m SignedURLAuthenticator ) requestMethodMatches ( meth string , query url . Values ) ( err error ) {
2020-11-16 13:42:23 +01:00
// check if given url query parameter OC-Verb matches given request method
2022-08-08 15:49:22 +02:00
if ! strings . EqualFold ( meth , query . Get ( _paramOCVerb )) {
2024-02-07 15:44:33 +01:00
return errors . New ( "required OC-Verb parameter did not match request method" )
2020-11-16 13:42:23 +01:00
}
2024-02-07 15:44:33 +01:00
return nil
2020-11-16 13:42:23 +01:00
}
2024-02-07 15:44:33 +01:00
func ( m SignedURLAuthenticator ) requestMethodIsAllowed ( meth string ) ( err error ) {
2020-11-16 13:42:23 +01:00
// check if given request method is allowed
methodIsAllowed := false
2022-08-08 15:49:22 +02:00
for _ , am := range m . PreSignedURLConfig . AllowedHTTPMethods {
2020-11-16 13:42:23 +01:00
if strings . EqualFold ( meth , am ) {
methodIsAllowed = true
break
}
}
if ! methodIsAllowed {
2024-02-07 15:44:33 +01:00
return errors . New ( "request method is not listed in PreSignedURLConfig AllowedHTTPMethods" )
2020-11-16 13:42:23 +01:00
}
2024-02-07 15:44:33 +01:00
return nil
2020-11-16 13:42:23 +01:00
}
2022-08-08 15:49:22 +02:00
2024-02-07 15:44:33 +01:00
func ( m SignedURLAuthenticator ) urlIsExpired ( query url . Values ) ( err error ) {
2020-11-16 13:42:23 +01:00
// check if url is expired by checking if given date (OC-Date) + expires in seconds (OC-Expires) is after now
2022-08-08 15:49:22 +02:00
validFrom , err := time . Parse ( time . RFC3339 , query . Get ( _paramOCDate ))
2020-11-16 13:42:23 +01:00
if err != nil {
2024-02-07 15:44:33 +01:00
return err
2020-11-16 13:42:23 +01:00
}
2022-08-08 15:49:22 +02:00
requestExpiry , err := time . ParseDuration ( query . Get ( _paramOCExpires ) + "s" )
2020-11-16 13:42:23 +01:00
if err != nil {
2024-02-07 15:44:33 +01:00
return err
2020-11-16 13:42:23 +01:00
}
2020-11-16 16:45:29 +01:00
validTo := validFrom . Add ( requestExpiry )
2024-02-07 15:44:33 +01:00
if !( m . Now (). Before ( validTo )) {
return errors . New ( "URL is expired" )
}
2020-11-16 13:42:23 +01:00
2024-02-07 15:44:33 +01:00
return nil
2020-11-16 13:42:23 +01:00
}
2024-02-07 15:44:33 +01:00
func ( m SignedURLAuthenticator ) signatureIsValid ( req * http . Request ) ( err error ) {
c := revactx . ContextMustGetUser ( req . Context ())
2024-02-26 16:08:03 +01:00
signingKey , err := m . Store . Read ( c . Id . OpaqueId )
2020-11-16 13:42:23 +01:00
if err != nil {
2022-08-08 15:49:22 +02:00
m . Logger . Error (). Err ( err ). Msg ( "could not retrieve signing key" )
2024-02-07 15:44:33 +01:00
return err
2020-11-16 13:42:23 +01:00
}
2026-06-23 12:23:54 +03:00
// A store may return an empty result set without an error (e.g. the "noop"
// store, or a store that has no signing key for this user). Guard the index
// access to avoid an out-of-range panic, and return a real error so the
// request fails authentication instead of proceeding with an empty key.
if len ( signingKey ) == 0 || len ( signingKey [ 0 ]. Value ) == 0 {
m . Logger . Error (). Str ( "userid" , c . Id . OpaqueId ). Msg ( "signing key empty or not found" )
return errors . New ( "signing key not found" )
2024-02-07 15:44:33 +01:00
}
u := m . buildUrlToSign ( req )
2024-02-26 16:08:03 +01:00
computedSignature := m . createSignature ( u , signingKey [ 0 ]. Value )
2024-02-07 15:44:33 +01:00
signatureInURL := req . URL . Query (). Get ( _paramOCSignature )
if computedSignature == signatureInURL {
return nil
2020-11-16 13:42:23 +01:00
}
2024-10-04 09:50:58 +02:00
// try a workaround for https://github.com/owncloud/ocis/issues/10180
// Some reverse proxies might replace $ with %24 in the URL leading to a mismatch in the signature
u = strings . Replace ( u , "$" , "%24" , 1 )
computedSignature = m . createSignature ( u , signingKey [ 0 ]. Value )
signatureInURL = req . URL . Query (). Get ( _paramOCSignature )
if computedSignature == signatureInURL {
return nil
}
2024-02-07 15:44:33 +01:00
return fmt . Errorf ( "signature mismatch: expected %s != actual %s" , computedSignature , signatureInURL )
}
func ( m SignedURLAuthenticator ) buildUrlToSign ( req * http . Request ) string {
2020-11-16 13:42:23 +01:00
q := req . URL . Query ()
2024-02-07 15:44:33 +01:00
// only params required for signing
signParameters := make ( url . Values )
signParameters . Add ( _paramOCCredential , q . Get ( _paramOCCredential ))
signParameters . Add ( _paramOCDate , q . Get ( _paramOCDate ))
signParameters . Add ( _paramOCExpires , q . Get ( _paramOCExpires ))
signParameters . Add ( _paramOCVerb , q . Get ( _paramOCVerb ))
// remaining query params
q . Del ( _paramOCAlgo )
q . Del ( _paramOCCredential )
q . Del ( _paramOCDate )
q . Del ( _paramOCExpires )
2022-08-08 15:49:22 +02:00
q . Del ( _paramOCSignature )
2024-02-07 15:44:33 +01:00
q . Del ( _paramOCVerb )
2020-11-16 13:42:23 +01:00
2024-02-07 15:44:33 +01:00
url := * req . URL
if len ( q ) == 0 {
url . RawQuery = signParameters . Encode ()
} else {
url . RawQuery = strings . Join ([] string { q . Encode (), signParameters . Encode ()}, "&" )
}
u := url . String ()
if ! url . IsAbs () {
u = "https://" + req . Host + u // TODO where do we get the scheme
}
return u
2020-11-16 13:42:23 +01:00
}
2022-08-04 17:38:55 +02:00
func ( m SignedURLAuthenticator ) createSignature ( url string , signingKey [] byte ) string {
2020-11-16 13:42:23 +01:00
// the oc10 signature check: $hash = \hash_pbkdf2("sha512", $url, $signingKey, 10000, 64, false);
// - sets the length of the output string to 64
// - sets raw output to false -> if raw_output is FALSE length corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits).
// TODO change to length 128 in oc10?
// fo golangs pbkdf2.Key we need to use 32 because it will be encoded into 64 hexits later
hash := pbkdf2 . Key ([] byte ( url ), signingKey , 10000 , 32 , sha512 . New )
return hex . EncodeToString ( hash )
}
2022-08-22 14:15:13 +02:00
// Authenticate implements the authenticator interface to authenticate requests via signed URL auth.
2026-09-29 09:37:48 +02:00
func ( m SignedURLAuthenticator ) Authenticate ( r * http . Request ) ( * http . Request , error ) {
2022-08-04 17:38:55 +02:00
if ! m . shouldServe ( r ) {
2026-09-29 09:37:48 +02:00
return nil , ErrAuthenticationFailed
2022-08-04 17:38:55 +02:00
}
2023-03-07 17:30:07 +01:00
user , _ , err := m . UserProvider . GetUserByClaims ( r . Context (), "username" , r . URL . Query (). Get ( _paramOCCredential ))
if err != nil {
m . Logger . Error ().
Err ( err ).
Str ( "authenticator" , "signed_url" ).
Str ( "path" , r . URL . Path ).
Msg ( "Could not get user by claim" )
2026-09-29 09:37:48 +02:00
return nil , ErrAuthenticationFailed
2023-03-07 17:30:07 +01:00
}
2023-03-15 17:20:14 +01:00
user , err = m . UserRoleAssigner . ApplyUserRole ( r . Context (), user )
2022-08-04 17:38:55 +02:00
if err != nil {
2022-08-08 15:49:22 +02:00
m . Logger . Error ().
Err ( err ).
Str ( "authenticator" , "signed_url" ).
Str ( "path" , r . URL . Path ).
Msg ( "Could not get user by claim" )
2026-09-29 09:37:48 +02:00
return nil , ErrAuthenticationFailed
2022-08-04 17:38:55 +02:00
}
ctx := revactx . ContextSetUser ( r . Context (), user )
r = r . WithContext ( ctx )
if err := m . validate ( r ); err != nil {
2022-08-08 15:49:22 +02:00
m . Logger . Error ().
Err ( err ).
Str ( "authenticator" , "signed_url" ).
Str ( "path" , r . URL . Path ).
2024-02-07 15:44:33 +01:00
Str ( "url" , r . URL . String ()).
2022-08-08 15:49:22 +02:00
Msg ( "Could not get user by claim" )
2026-09-29 09:37:48 +02:00
return nil , ErrAuthenticationFailed
2022-08-04 17:38:55 +02:00
}
2024-02-07 15:44:33 +01:00
// TODO: set user in context
2022-08-08 15:49:22 +02:00
m . Logger . Debug ().
Str ( "authenticator" , "signed_url" ).
Str ( "path" , r . URL . Path ).
Msg ( "successfully authenticated request" )
2026-09-29 09:37:48 +02:00
return r , nil
2022-08-04 17:38:55 +02:00
}