2017-04-21 00:40:52 +02:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2017-05-23 18:43:05 +02:00
|
|
|
// Package auth implements authentication checks and storage.
|
2017-03-07 14:43:32 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2017-09-18 16:51:26 +02:00
|
|
|
"context"
|
2017-05-30 18:51:40 +02:00
|
|
|
"crypto/rand"
|
2017-05-25 14:33:50 +02:00
|
|
|
"database/sql"
|
2017-05-30 18:51:40 +02:00
|
|
|
"encoding/base64"
|
2017-03-07 14:43:32 +01:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
"github.com/matrix-org/dendrite/appservice/types"
|
2017-05-23 18:43:05 +02:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
|
2017-11-16 16:46:52 +01:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/httputil"
|
2017-03-07 14:43:32 +01:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
2018-06-01 13:16:19 +02:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/userutil"
|
|
|
|
"github.com/matrix-org/dendrite/common/config"
|
2017-03-07 14:43:32 +01:00
|
|
|
"github.com/matrix-org/util"
|
|
|
|
)
|
|
|
|
|
2017-05-30 18:51:40 +02:00
|
|
|
// OWASP recommends at least 128 bits of entropy for tokens: https://www.owasp.org/index.php/Insufficient_Session-ID_Length
|
|
|
|
// 32 bytes => 256 bits
|
|
|
|
var tokenByteLength = 32
|
|
|
|
|
2017-07-17 18:20:57 +02:00
|
|
|
// DeviceDatabase represents a device database.
|
|
|
|
type DeviceDatabase interface {
|
2017-08-23 16:08:48 +02:00
|
|
|
// Look up the device matching the given access token.
|
2017-09-18 16:51:26 +02:00
|
|
|
GetDeviceByAccessToken(ctx context.Context, token string) (*authtypes.Device, error)
|
2017-07-17 18:20:57 +02:00
|
|
|
}
|
|
|
|
|
2018-06-01 13:16:19 +02:00
|
|
|
// AccountDatabase represents an account database.
|
|
|
|
type AccountDatabase interface {
|
|
|
|
// Look up the account matching the given localpart.
|
|
|
|
GetAccountByLocalpart(ctx context.Context, localpart string) (*authtypes.Account, error)
|
|
|
|
}
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
// Data contains information required to authenticate a request.
|
|
|
|
type Data struct {
|
|
|
|
AccountDB AccountDatabase
|
|
|
|
DeviceDB DeviceDatabase
|
|
|
|
// AppServices is the list of all registered AS
|
|
|
|
AppServices []config.ApplicationService
|
|
|
|
}
|
|
|
|
|
2018-06-01 13:16:19 +02:00
|
|
|
// VerifyUserFromRequest authenticates the HTTP request,
|
2018-07-17 00:17:03 +02:00
|
|
|
// on success returns Device of the requester.
|
2018-06-01 13:16:19 +02:00
|
|
|
// Finds local user or an application service user.
|
2018-07-17 00:17:03 +02:00
|
|
|
// Note: For an AS user, AS dummy device is returned.
|
2018-06-01 13:16:19 +02:00
|
|
|
// On failure returns an JSON error response which can be sent to the client.
|
|
|
|
func VerifyUserFromRequest(
|
2018-07-17 00:17:03 +02:00
|
|
|
req *http.Request, data Data,
|
|
|
|
) (*authtypes.Device, *util.JSONResponse) {
|
2018-06-01 13:16:19 +02:00
|
|
|
// Try to find the Application Service user
|
2018-07-23 15:40:35 +02:00
|
|
|
token, err := ExtractAccessToken(req)
|
2018-06-01 13:16:19 +02:00
|
|
|
if err != nil {
|
2018-07-17 00:17:03 +02:00
|
|
|
return nil, &util.JSONResponse{
|
2018-06-01 13:16:19 +02:00
|
|
|
Code: http.StatusUnauthorized,
|
|
|
|
JSON: jsonerror.MissingToken(err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Search for app service with given access_token
|
|
|
|
var appService *config.ApplicationService
|
2018-07-17 00:17:03 +02:00
|
|
|
for _, as := range data.AppServices {
|
2018-06-01 13:16:19 +02:00
|
|
|
if as.ASToken == token {
|
|
|
|
appService = &as
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if appService != nil {
|
2018-07-17 00:17:03 +02:00
|
|
|
// Create a dummy device for AS user
|
|
|
|
dev := authtypes.Device{
|
|
|
|
// Use AS dummy device ID
|
|
|
|
ID: types.AppServiceDeviceID,
|
|
|
|
// AS dummy device has AS's token.
|
|
|
|
AccessToken: token,
|
|
|
|
}
|
|
|
|
|
2018-06-01 13:16:19 +02:00
|
|
|
userID := req.URL.Query().Get("user_id")
|
|
|
|
localpart, err := userutil.ParseUsernameParam(userID, nil)
|
|
|
|
if err != nil {
|
2018-07-17 00:17:03 +02:00
|
|
|
return nil, &util.JSONResponse{
|
2018-06-01 13:16:19 +02:00
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.InvalidUsername(err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
if localpart != "" { // AS is masquerading as another user
|
|
|
|
// Verify that the user is registered
|
|
|
|
account, err := data.AccountDB.GetAccountByLocalpart(req.Context(), localpart)
|
|
|
|
// Verify that account exists & appServiceID matches
|
|
|
|
if err == nil && account.AppServiceID == appService.ID {
|
|
|
|
// Set the userID of dummy device
|
|
|
|
dev.UserID = userID
|
|
|
|
return &dev, nil
|
|
|
|
}
|
2018-06-01 13:16:19 +02:00
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
return nil, &util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
|
|
|
JSON: jsonerror.Forbidden("Application service has not registered this user"),
|
|
|
|
}
|
2018-06-01 13:16:19 +02:00
|
|
|
}
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
// AS is not masquerading as any user, so use AS's sender_localpart
|
|
|
|
dev.UserID = appService.SenderLocalpart
|
|
|
|
return &dev, nil
|
2018-06-01 13:16:19 +02:00
|
|
|
}
|
|
|
|
|
2019-03-21 15:48:21 +01:00
|
|
|
// Try to find local user from device database
|
|
|
|
dev, devErr := verifyAccessToken(req, data.DeviceDB)
|
|
|
|
if devErr == nil {
|
|
|
|
return dev, verifyUserParameters(req)
|
|
|
|
}
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
return nil, &util.JSONResponse{
|
2018-06-01 13:16:19 +02:00
|
|
|
Code: http.StatusUnauthorized,
|
2019-06-19 15:05:03 +02:00
|
|
|
JSON: jsonerror.UnknownToken("Unrecognized access token"), // nolint: misspell
|
2018-06-01 13:16:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-17 17:45:30 +02:00
|
|
|
// verifyUserParameters ensures that a request coming from a regular user is not
|
|
|
|
// using any query parameters reserved for an application service
|
|
|
|
func verifyUserParameters(req *http.Request) *util.JSONResponse {
|
|
|
|
if req.URL.Query().Get("ts") != "" {
|
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.Unknown("parameter 'ts' not allowed without valid parameter 'access_token'"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-07-17 00:17:03 +02:00
|
|
|
// verifyAccessToken verifies that an access token was supplied in the given HTTP request
|
2017-05-23 18:43:05 +02:00
|
|
|
// and returns the device it corresponds to. Returns resErr (an error response which can be
|
2017-03-07 14:43:32 +01:00
|
|
|
// sent to the client) if the token is invalid or there was a problem querying the database.
|
2018-07-17 00:17:03 +02:00
|
|
|
func verifyAccessToken(req *http.Request, deviceDB DeviceDatabase) (device *authtypes.Device, resErr *util.JSONResponse) {
|
2018-07-23 15:40:35 +02:00
|
|
|
token, err := ExtractAccessToken(req)
|
2017-05-23 18:43:05 +02:00
|
|
|
if err != nil {
|
2017-03-07 14:43:32 +01:00
|
|
|
resErr = &util.JSONResponse{
|
2018-03-13 16:55:45 +01:00
|
|
|
Code: http.StatusUnauthorized,
|
2017-05-23 18:43:05 +02:00
|
|
|
JSON: jsonerror.MissingToken(err.Error()),
|
2017-03-07 14:43:32 +01:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2017-09-18 16:51:26 +02:00
|
|
|
device, err = deviceDB.GetDeviceByAccessToken(req.Context(), token)
|
2017-05-23 18:43:05 +02:00
|
|
|
if err != nil {
|
2017-05-25 14:33:50 +02:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
resErr = &util.JSONResponse{
|
2018-03-13 16:55:45 +01:00
|
|
|
Code: http.StatusUnauthorized,
|
2017-10-10 11:40:52 +02:00
|
|
|
JSON: jsonerror.UnknownToken("Unknown token"),
|
2017-05-25 14:33:50 +02:00
|
|
|
}
|
|
|
|
} else {
|
2017-11-16 16:46:52 +01:00
|
|
|
jsonErr := httputil.LogThenError(req, err)
|
|
|
|
resErr = &jsonErr
|
2017-05-23 18:43:05 +02:00
|
|
|
}
|
2017-03-07 14:43:32 +01:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-30 18:51:40 +02:00
|
|
|
// GenerateAccessToken creates a new access token. Returns an error if failed to generate
|
|
|
|
// random bytes.
|
|
|
|
func GenerateAccessToken() (string, error) {
|
|
|
|
b := make([]byte, tokenByteLength)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
// url-safe no padding
|
|
|
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
|
|
|
}
|
|
|
|
|
2018-07-23 15:40:35 +02:00
|
|
|
// ExtractAccessToken from a request, or return an error detailing what went wrong. The
|
2017-03-07 14:43:32 +01:00
|
|
|
// error message MUST be human-readable and comprehensible to the client.
|
2018-07-23 15:40:35 +02:00
|
|
|
func ExtractAccessToken(req *http.Request) (string, error) {
|
2017-03-07 14:43:32 +01:00
|
|
|
// cf https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/api/auth.py#L631
|
|
|
|
authBearer := req.Header.Get("Authorization")
|
|
|
|
queryToken := req.URL.Query().Get("access_token")
|
|
|
|
if authBearer != "" && queryToken != "" {
|
|
|
|
return "", fmt.Errorf("mixing Authorization headers and access_token query parameters")
|
|
|
|
}
|
|
|
|
|
|
|
|
if queryToken != "" {
|
|
|
|
return queryToken, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if authBearer != "" {
|
|
|
|
parts := strings.SplitN(authBearer, " ", 2)
|
|
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
|
|
return "", fmt.Errorf("invalid Authorization header")
|
|
|
|
}
|
|
|
|
return parts[1], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", fmt.Errorf("missing access token")
|
|
|
|
}
|