2017-10-11 17:16:53 +00:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
// Copyright 2017 New Vector 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.
|
|
|
|
|
|
|
|
package routing
|
2017-05-22 14:55:39 +00:00
|
|
|
|
|
|
|
import (
|
2017-09-18 13:15:27 +00:00
|
|
|
"context"
|
2017-09-22 15:13:19 +00:00
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha1"
|
2017-12-05 16:16:14 +00:00
|
|
|
"encoding/json"
|
2017-09-22 15:13:19 +00:00
|
|
|
"errors"
|
2017-05-22 14:55:39 +00:00
|
|
|
"fmt"
|
2017-12-05 16:16:14 +00:00
|
|
|
"io/ioutil"
|
2017-05-22 14:55:39 +00:00
|
|
|
"net/http"
|
2017-12-05 16:16:14 +00:00
|
|
|
"net/url"
|
2017-09-22 15:13:19 +00:00
|
|
|
"regexp"
|
2017-11-29 09:43:03 +00:00
|
|
|
"sort"
|
2018-05-31 14:36:15 +00:00
|
|
|
"strconv"
|
2017-09-22 15:13:19 +00:00
|
|
|
"strings"
|
2019-08-16 04:05:00 +00:00
|
|
|
"sync"
|
2017-12-05 16:16:14 +00:00
|
|
|
"time"
|
2017-05-22 14:55:39 +00:00
|
|
|
|
2020-06-12 13:55:57 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/eventutil"
|
2020-12-02 17:41:00 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2017-09-22 15:13:19 +00:00
|
|
|
|
2017-05-30 16:51:40 +00:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth"
|
2017-05-23 16:43:05 +00:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
|
2017-05-22 14:55:39 +00:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/httputil"
|
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
2018-07-06 10:28:49 +00:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/userutil"
|
2020-06-17 10:22:26 +00:00
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
2020-06-17 11:05:56 +00:00
|
|
|
"github.com/matrix-org/dendrite/userapi/storage/accounts"
|
2017-05-22 14:55:39 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2020-01-30 11:25:57 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/tokens"
|
2017-05-22 14:55:39 +00:00
|
|
|
"github.com/matrix-org/util"
|
2018-05-23 14:42:08 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2017-11-14 09:56:23 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2017-05-22 14:55:39 +00:00
|
|
|
)
|
|
|
|
|
2018-05-23 14:42:08 +00:00
|
|
|
var (
|
|
|
|
// Prometheus metrics
|
|
|
|
amtRegUsers = prometheus.NewCounter(
|
|
|
|
prometheus.CounterOpts{
|
|
|
|
Name: "dendrite_clientapi_reg_users_total",
|
|
|
|
Help: "Total number of registered users",
|
|
|
|
},
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2017-05-22 14:55:39 +00:00
|
|
|
const (
|
|
|
|
minPasswordLength = 8 // http://matrix.org/docs/spec/client_server/r0.2.0.html#password-based
|
|
|
|
maxPasswordLength = 512 // https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161
|
|
|
|
maxUsernameLength = 254 // http://matrix.org/speculator/spec/HEAD/intro.html#user-identifiers TODO account for domain
|
2017-11-29 09:43:03 +00:00
|
|
|
sessionIDLength = 24
|
2017-05-22 14:55:39 +00:00
|
|
|
)
|
|
|
|
|
2018-05-23 14:42:08 +00:00
|
|
|
func init() {
|
|
|
|
// Register prometheus metrics. They must be registered to be exposed.
|
|
|
|
prometheus.MustRegister(amtRegUsers)
|
|
|
|
}
|
|
|
|
|
2018-03-15 17:21:08 +00:00
|
|
|
// sessionsDict keeps track of completed auth stages for each session.
|
2019-08-16 04:05:00 +00:00
|
|
|
// It shouldn't be passed by value because it contains a mutex.
|
2018-03-15 17:21:08 +00:00
|
|
|
type sessionsDict struct {
|
2019-08-16 04:05:00 +00:00
|
|
|
sync.Mutex
|
2018-03-15 17:21:08 +00:00
|
|
|
sessions map[string][]authtypes.LoginType
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetCompletedStages returns the completed stages for a session.
|
2019-08-16 04:05:00 +00:00
|
|
|
func (d *sessionsDict) GetCompletedStages(sessionID string) []authtypes.LoginType {
|
|
|
|
d.Lock()
|
|
|
|
defer d.Unlock()
|
|
|
|
|
2018-03-15 17:21:08 +00:00
|
|
|
if completedStages, ok := d.sessions[sessionID]; ok {
|
|
|
|
return completedStages
|
|
|
|
}
|
|
|
|
// Ensure that a empty slice is returned and not nil. See #399.
|
|
|
|
return make([]authtypes.LoginType, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSessionsDict() *sessionsDict {
|
|
|
|
return &sessionsDict{
|
|
|
|
sessions: make(map[string][]authtypes.LoginType),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-14 17:34:49 +00:00
|
|
|
// AddCompletedSessionStage records that a session has completed an auth stage.
|
|
|
|
func AddCompletedSessionStage(sessionID string, stage authtypes.LoginType) {
|
2019-08-16 04:05:00 +00:00
|
|
|
sessions.Lock()
|
|
|
|
defer sessions.Unlock()
|
|
|
|
|
|
|
|
for _, completedStage := range sessions.sessions[sessionID] {
|
2019-08-14 17:34:49 +00:00
|
|
|
if completedStage == stage {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2019-08-16 04:05:00 +00:00
|
|
|
sessions.sessions[sessionID] = append(sessions.sessions[sessionID], stage)
|
2019-08-14 17:34:49 +00:00
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
var (
|
|
|
|
// TODO: Remove old sessions. Need to do so on a session-specific timeout.
|
2018-03-15 17:21:08 +00:00
|
|
|
// sessions stores the completed flow stages for all sessions. Referenced using their sessionID.
|
|
|
|
sessions = newSessionsDict()
|
2020-11-12 10:36:54 +00:00
|
|
|
validUsernameRegex = regexp.MustCompile(`^[0-9a-z_\-=./]+$`)
|
2017-11-29 09:43:03 +00:00
|
|
|
)
|
2017-09-22 15:13:19 +00:00
|
|
|
|
2017-05-22 14:55:39 +00:00
|
|
|
// registerRequest represents the submitted registration request.
|
|
|
|
// It can be broken down into 2 sections: the auth dictionary and registration parameters.
|
|
|
|
// Registration parameters vary depending on the request, and will need to remembered across
|
|
|
|
// sessions. If no parameters are supplied, the server should use the parameters previously
|
|
|
|
// remembered. If ANY parameters are supplied, the server should REPLACE all knowledge of
|
2017-06-12 17:30:47 +00:00
|
|
|
// previous parameters with the ones supplied. This mean you cannot "build up" request params.
|
2017-05-22 14:55:39 +00:00
|
|
|
type registerRequest struct {
|
2018-02-08 11:02:48 +00:00
|
|
|
// registration parameters
|
2017-05-22 14:55:39 +00:00
|
|
|
Password string `json:"password"`
|
|
|
|
Username string `json:"username"`
|
2017-09-22 15:13:19 +00:00
|
|
|
Admin bool `json:"admin"`
|
2017-05-22 14:55:39 +00:00
|
|
|
// user-interactive auth params
|
|
|
|
Auth authDict `json:"auth"`
|
2017-11-14 09:59:02 +00:00
|
|
|
|
2019-07-22 14:05:38 +00:00
|
|
|
// Both DeviceID and InitialDisplayName can be omitted, or empty strings ("")
|
|
|
|
// Thus a pointer is needed to differentiate between the two
|
2017-11-14 09:59:02 +00:00
|
|
|
InitialDisplayName *string `json:"initial_device_display_name"`
|
2019-07-22 14:05:38 +00:00
|
|
|
DeviceID *string `json:"device_id"`
|
2018-02-08 11:02:48 +00:00
|
|
|
|
2018-07-17 15:57:20 +00:00
|
|
|
// Prevent this user from logging in
|
2020-06-12 13:55:57 +00:00
|
|
|
InhibitLogin eventutil.WeakBoolean `json:"inhibit_login"`
|
2018-07-17 15:57:20 +00:00
|
|
|
|
|
|
|
// Application Services place Type in the root of their registration
|
2018-02-08 11:02:48 +00:00
|
|
|
// request, whereas clients place it in the authDict struct.
|
|
|
|
Type authtypes.LoginType `json:"type"`
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type authDict struct {
|
2017-09-22 15:13:19 +00:00
|
|
|
Type authtypes.LoginType `json:"type"`
|
|
|
|
Session string `json:"session"`
|
|
|
|
Mac gomatrixserverlib.HexString `json:"mac"`
|
2017-11-29 09:43:03 +00:00
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
// Recaptcha
|
|
|
|
Response string `json:"response"`
|
2017-05-22 14:55:39 +00:00
|
|
|
// TODO: Lots of custom keys depending on the type
|
|
|
|
}
|
|
|
|
|
|
|
|
// http://matrix.org/speculator/spec/HEAD/client_server/unstable.html#user-interactive-authentication-api
|
|
|
|
type userInteractiveResponse struct {
|
2017-11-29 09:43:03 +00:00
|
|
|
Flows []authtypes.Flow `json:"flows"`
|
2017-05-23 16:43:05 +00:00
|
|
|
Completed []authtypes.LoginType `json:"completed"`
|
2017-05-22 14:55:39 +00:00
|
|
|
Params map[string]interface{} `json:"params"`
|
|
|
|
Session string `json:"session"`
|
|
|
|
}
|
|
|
|
|
2017-09-22 15:13:19 +00:00
|
|
|
// legacyRegisterRequest represents the submitted registration request for v1 API.
|
|
|
|
type legacyRegisterRequest struct {
|
|
|
|
Password string `json:"password"`
|
|
|
|
Username string `json:"user"`
|
|
|
|
Admin bool `json:"admin"`
|
|
|
|
Type authtypes.LoginType `json:"type"`
|
|
|
|
Mac gomatrixserverlib.HexString `json:"mac"`
|
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// newUserInteractiveResponse will return a struct to be sent back to the client
|
|
|
|
// during registration.
|
|
|
|
func newUserInteractiveResponse(
|
|
|
|
sessionID string,
|
|
|
|
fs []authtypes.Flow,
|
|
|
|
params map[string]interface{},
|
|
|
|
) userInteractiveResponse {
|
2017-05-22 14:55:39 +00:00
|
|
|
return userInteractiveResponse{
|
2018-03-15 17:21:08 +00:00
|
|
|
fs, sessions.GetCompletedStages(sessionID), params, sessionID,
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// http://matrix.org/speculator/spec/HEAD/client_server/unstable.html#post-matrix-client-unstable-register
|
|
|
|
type registerResponse struct {
|
|
|
|
UserID string `json:"user_id"`
|
2018-07-17 15:57:20 +00:00
|
|
|
AccessToken string `json:"access_token,omitempty"`
|
2017-05-22 14:55:39 +00:00
|
|
|
HomeServer gomatrixserverlib.ServerName `json:"home_server"`
|
2018-07-17 15:57:20 +00:00
|
|
|
DeviceID string `json:"device_id,omitempty"`
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
// recaptchaResponse represents the HTTP response from a Google Recaptcha server
|
|
|
|
type recaptchaResponse struct {
|
|
|
|
Success bool `json:"success"`
|
|
|
|
ChallengeTS time.Time `json:"challenge_ts"`
|
|
|
|
Hostname string `json:"hostname"`
|
|
|
|
ErrorCodes []int `json:"error-codes"`
|
|
|
|
}
|
|
|
|
|
2018-07-06 09:27:11 +00:00
|
|
|
// validateUsername returns an error response if the username is invalid
|
|
|
|
func validateUsername(username string) *util.JSONResponse {
|
2017-05-22 14:55:39 +00:00
|
|
|
// https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161
|
2017-10-09 14:24:38 +00:00
|
|
|
if len(username) > maxUsernameLength {
|
2017-05-22 14:55:39 +00:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-10-09 14:24:38 +00:00
|
|
|
JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)),
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
2017-10-09 14:24:38 +00:00
|
|
|
} else if !validUsernameRegex.MatchString(username) {
|
2017-05-22 14:55:39 +00:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2020-11-18 22:56:06 +00:00
|
|
|
JSON: jsonerror.InvalidUsername("Username can only contain characters a-z, 0-9, or '_-./='"),
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
2017-10-09 14:24:38 +00:00
|
|
|
} else if username[0] == '_' { // Regex checks its not a zero length string
|
2017-05-22 14:55:39 +00:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2018-07-06 10:28:49 +00:00
|
|
|
JSON: jsonerror.InvalidUsername("Username cannot start with a '_'"),
|
2018-07-06 09:27:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// validateApplicationServiceUsername returns an error response if the username is invalid for an application service
|
|
|
|
func validateApplicationServiceUsername(username string) *util.JSONResponse {
|
|
|
|
if len(username) > maxUsernameLength {
|
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)),
|
|
|
|
}
|
|
|
|
} else if !validUsernameRegex.MatchString(username) {
|
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
2020-11-18 22:56:06 +00:00
|
|
|
JSON: jsonerror.InvalidUsername("Username can only contain characters a-z, 0-9, or '_-./='"),
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
2017-10-09 14:24:38 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// validatePassword returns an error response if the password is invalid
|
|
|
|
func validatePassword(password string) *util.JSONResponse {
|
|
|
|
// https://github.com/matrix-org/synapse/blob/v0.20.0/synapse/rest/client/v2_alpha/register.py#L161
|
|
|
|
if len(password) > maxPasswordLength {
|
2017-09-22 15:13:19 +00:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-10-09 14:24:38 +00:00
|
|
|
JSON: jsonerror.BadJSON(fmt.Sprintf("'password' >%d characters", maxPasswordLength)),
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
2017-10-09 14:24:38 +00:00
|
|
|
} else if len(password) > 0 && len(password) < minPasswordLength {
|
2017-09-22 15:13:19 +00:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-10-09 14:24:38 +00:00
|
|
|
JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)),
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
2017-05-22 14:55:39 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
// validateRecaptcha returns an error response if the captcha response is invalid
|
|
|
|
func validateRecaptcha(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2017-12-05 16:16:14 +00:00
|
|
|
response string,
|
|
|
|
clientip string,
|
|
|
|
) *util.JSONResponse {
|
2020-08-10 13:18:04 +00:00
|
|
|
if !cfg.RecaptchaEnabled {
|
2017-12-05 16:16:14 +00:00
|
|
|
return &util.JSONResponse{
|
2019-07-09 13:21:33 +00:00
|
|
|
Code: http.StatusConflict,
|
|
|
|
JSON: jsonerror.Unknown("Captcha registration is disabled"),
|
2017-12-05 16:16:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if response == "" {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-12-05 16:16:14 +00:00
|
|
|
JSON: jsonerror.BadJSON("Captcha response is required"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make a POST request to Google's API to check the captcha response
|
2020-08-10 13:18:04 +00:00
|
|
|
resp, err := http.PostForm(cfg.RecaptchaSiteVerifyAPI,
|
2017-12-05 16:16:14 +00:00
|
|
|
url.Values{
|
2020-08-10 13:18:04 +00:00
|
|
|
"secret": {cfg.RecaptchaPrivateKey},
|
2017-12-05 16:16:14 +00:00
|
|
|
"response": {response},
|
|
|
|
"remoteip": {clientip},
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-12-05 16:16:14 +00:00
|
|
|
JSON: jsonerror.BadJSON("Error in requesting validation of captcha response"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the request once we're finishing reading from it
|
|
|
|
defer resp.Body.Close() // nolint: errcheck
|
|
|
|
|
|
|
|
// Grab the body of the response from the captcha server
|
|
|
|
var r recaptchaResponse
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return &util.JSONResponse{
|
2019-07-09 13:21:33 +00:00
|
|
|
Code: http.StatusGatewayTimeout,
|
|
|
|
JSON: jsonerror.Unknown("Error in contacting captcha server" + err.Error()),
|
2017-12-05 16:16:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
err = json.Unmarshal(body, &r)
|
|
|
|
if err != nil {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-12-05 16:16:14 +00:00
|
|
|
JSON: jsonerror.BadJSON("Error in unmarshaling captcha server's response: " + err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check that we received a "success"
|
|
|
|
if !r.Success {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusUnauthorized,
|
2017-12-05 16:16:14 +00:00
|
|
|
JSON: jsonerror.BadJSON("Invalid captcha response. Please try again."),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-07-06 10:28:49 +00:00
|
|
|
// UserIDIsWithinApplicationServiceNamespace checks to see if a given userID
|
|
|
|
// falls within any of the namespaces of a given Application Service. If no
|
|
|
|
// Application Service is given, it will check to see if it matches any
|
|
|
|
// Application Service's namespace.
|
|
|
|
func UserIDIsWithinApplicationServiceNamespace(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2018-07-06 10:28:49 +00:00
|
|
|
userID string,
|
2018-02-08 11:02:48 +00:00
|
|
|
appservice *config.ApplicationService,
|
|
|
|
) bool {
|
|
|
|
if appservice != nil {
|
2018-07-05 16:34:59 +00:00
|
|
|
// Loop through given application service's namespaces and see if any match
|
2018-02-08 11:02:48 +00:00
|
|
|
for _, namespace := range appservice.NamespaceMap["users"] {
|
|
|
|
// AS namespaces are checked for validity in config
|
2018-07-06 10:28:49 +00:00
|
|
|
if namespace.RegexpObject.MatchString(userID) {
|
2018-02-08 11:02:48 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-07-05 16:34:59 +00:00
|
|
|
// Loop through all known application service's namespaces and see if any match
|
2018-07-17 14:36:04 +00:00
|
|
|
for _, knownAppService := range cfg.Derived.ApplicationServices {
|
|
|
|
for _, namespace := range knownAppService.NamespaceMap["users"] {
|
2018-02-08 11:02:48 +00:00
|
|
|
// AS namespaces are checked for validity in config
|
2018-07-06 10:28:49 +00:00
|
|
|
if namespace.RegexpObject.MatchString(userID) {
|
2018-02-08 11:02:48 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// UsernameMatchesMultipleExclusiveNamespaces will check if a given username matches
|
|
|
|
// more than one exclusive namespace. More than one is not allowed
|
|
|
|
func UsernameMatchesMultipleExclusiveNamespaces(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2018-02-08 11:02:48 +00:00
|
|
|
username string,
|
|
|
|
) bool {
|
2018-07-17 15:36:23 +00:00
|
|
|
userID := userutil.MakeUserID(username, cfg.Matrix.ServerName)
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// Check namespaces and see if more than one match
|
|
|
|
matchCount := 0
|
|
|
|
for _, appservice := range cfg.Derived.ApplicationServices {
|
2020-04-14 14:31:27 +00:00
|
|
|
if appservice.OwnsNamespaceCoveringUserId(userID) {
|
2018-07-16 12:30:04 +00:00
|
|
|
if matchCount++; matchCount > 1 {
|
|
|
|
return true
|
2018-02-08 11:02:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-07-16 12:30:04 +00:00
|
|
|
return false
|
2018-02-08 11:02:48 +00:00
|
|
|
}
|
|
|
|
|
2018-07-17 15:36:23 +00:00
|
|
|
// UsernameMatchesExclusiveNamespaces will check if a given username matches any
|
|
|
|
// application service's exclusive users namespace
|
|
|
|
func UsernameMatchesExclusiveNamespaces(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2018-07-17 15:36:23 +00:00
|
|
|
username string,
|
|
|
|
) bool {
|
|
|
|
userID := userutil.MakeUserID(username, cfg.Matrix.ServerName)
|
|
|
|
return cfg.Derived.ExclusiveApplicationServicesUsernameRegexp.MatchString(userID)
|
|
|
|
}
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// validateApplicationService checks if a provided application service token
|
|
|
|
// corresponds to one that is registered. If so, then it checks if the desired
|
|
|
|
// username is within that application service's namespace. As long as these
|
|
|
|
// two requirements are met, no error will be returned.
|
|
|
|
func validateApplicationService(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2018-02-08 11:02:48 +00:00
|
|
|
username string,
|
2018-11-06 14:40:37 +00:00
|
|
|
accessToken string,
|
2018-02-08 11:02:48 +00:00
|
|
|
) (string, *util.JSONResponse) {
|
|
|
|
// Check if the token if the application service is valid with one we have
|
|
|
|
// registered in the config.
|
|
|
|
var matchedApplicationService *config.ApplicationService
|
|
|
|
for _, appservice := range cfg.Derived.ApplicationServices {
|
|
|
|
if appservice.ASToken == accessToken {
|
|
|
|
matchedApplicationService = &appservice
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2018-03-13 15:35:56 +00:00
|
|
|
if matchedApplicationService == nil {
|
2018-02-08 11:02:48 +00:00
|
|
|
return "", &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusUnauthorized,
|
2018-02-08 11:02:48 +00:00
|
|
|
JSON: jsonerror.UnknownToken("Supplied access_token does not match any known application service"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-06 10:28:49 +00:00
|
|
|
userID := userutil.MakeUserID(username, cfg.Matrix.ServerName)
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// Ensure the desired username is within at least one of the application service's namespaces.
|
2018-07-06 10:28:49 +00:00
|
|
|
if !UserIDIsWithinApplicationServiceNamespace(cfg, userID, matchedApplicationService) {
|
2018-02-08 11:02:48 +00:00
|
|
|
// If we didn't find any matches, return M_EXCLUSIVE
|
|
|
|
return "", &util.JSONResponse{
|
2018-06-29 11:09:00 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2018-02-08 11:02:48 +00:00
|
|
|
JSON: jsonerror.ASExclusive(fmt.Sprintf(
|
|
|
|
"Supplied username %s did not match any namespaces for application service ID: %s", username, matchedApplicationService.ID)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check this user does not fit multiple application service namespaces
|
2018-07-06 10:28:49 +00:00
|
|
|
if UsernameMatchesMultipleExclusiveNamespaces(cfg, userID) {
|
2018-02-08 11:02:48 +00:00
|
|
|
return "", &util.JSONResponse{
|
2018-06-29 11:09:00 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2018-02-08 11:02:48 +00:00
|
|
|
JSON: jsonerror.ASExclusive(fmt.Sprintf(
|
|
|
|
"Supplied username %s matches multiple exclusive application service namespaces. Only 1 match allowed", username)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-06 09:27:11 +00:00
|
|
|
// Check username application service is trying to register is valid
|
|
|
|
if err := validateApplicationServiceUsername(username); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// No errors, registration valid
|
|
|
|
return matchedApplicationService.ID, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register processes a /register request.
|
|
|
|
// http://matrix.org/speculator/spec/HEAD/client_server/unstable.html#post-matrix-client-unstable-register
|
2017-09-22 15:13:19 +00:00
|
|
|
func Register(
|
|
|
|
req *http.Request,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2020-02-13 17:27:33 +00:00
|
|
|
accountDB accounts.Database,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2017-09-22 15:13:19 +00:00
|
|
|
) util.JSONResponse {
|
2017-05-22 14:55:39 +00:00
|
|
|
var r registerRequest
|
|
|
|
resErr := httputil.UnmarshalJSONRequest(req, &r)
|
|
|
|
if resErr != nil {
|
|
|
|
return *resErr
|
|
|
|
}
|
2020-01-30 11:25:57 +00:00
|
|
|
if req.URL.Query().Get("kind") == "guest" {
|
2020-06-17 10:22:26 +00:00
|
|
|
return handleGuestRegistration(req, r, cfg, userAPI)
|
2020-01-30 11:25:57 +00:00
|
|
|
}
|
2017-09-22 15:38:22 +00:00
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// Retrieve or generate the sessionID
|
|
|
|
sessionID := r.Auth.Session
|
|
|
|
if sessionID == "" {
|
|
|
|
// Generate a new, random session ID
|
|
|
|
sessionID = util.RandomString(sessionIDLength)
|
|
|
|
}
|
|
|
|
|
2018-05-31 14:36:15 +00:00
|
|
|
// Don't allow numeric usernames less than MAX_INT64.
|
|
|
|
if _, err := strconv.ParseInt(r.Username, 10, 64); err == nil {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.InvalidUsername("Numeric user IDs are reserved"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Auto generate a numeric username if r.Username is empty
|
|
|
|
if r.Username == "" {
|
|
|
|
id, err := accountDB.GetNewNumericLocalpart(req.Context())
|
|
|
|
if err != nil {
|
2020-03-02 16:20:44 +00:00
|
|
|
util.GetLogger(req.Context()).WithError(err).Error("accountDB.GetNewNumericLocalpart failed")
|
|
|
|
return jsonerror.InternalServerError()
|
2018-05-31 14:36:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
r.Username = strconv.FormatInt(id, 10)
|
|
|
|
}
|
|
|
|
|
2017-12-04 09:40:36 +00:00
|
|
|
// Squash username to all lowercase letters
|
|
|
|
r.Username = strings.ToLower(r.Username)
|
|
|
|
|
2018-07-06 09:27:11 +00:00
|
|
|
if resErr = validateUsername(r.Username); resErr != nil {
|
2017-10-09 14:24:38 +00:00
|
|
|
return *resErr
|
|
|
|
}
|
|
|
|
if resErr = validatePassword(r.Password); resErr != nil {
|
2017-05-22 14:55:39 +00:00
|
|
|
return *resErr
|
|
|
|
}
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// Make sure normal user isn't registering under an exclusive application
|
2018-02-27 11:42:10 +00:00
|
|
|
// service namespace. Skip this check if no app services are registered.
|
2018-07-17 15:39:49 +00:00
|
|
|
if r.Auth.Type != authtypes.LoginTypeApplicationService &&
|
2018-02-27 11:42:10 +00:00
|
|
|
len(cfg.Derived.ApplicationServices) != 0 &&
|
2018-07-17 15:36:23 +00:00
|
|
|
UsernameMatchesExclusiveNamespaces(cfg, r.Username) {
|
2018-02-08 11:02:48 +00:00
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2018-02-08 11:02:48 +00:00
|
|
|
JSON: jsonerror.ASExclusive("This username is reserved by an application service."),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-22 14:55:39 +00:00
|
|
|
logger := util.GetLogger(req.Context())
|
|
|
|
logger.WithFields(log.Fields{
|
|
|
|
"username": r.Username,
|
|
|
|
"auth.type": r.Auth.Type,
|
|
|
|
"session_id": r.Auth.Session,
|
|
|
|
}).Info("Processing registration request")
|
|
|
|
|
2020-06-17 10:22:26 +00:00
|
|
|
return handleRegistrationFlow(req, r, sessionID, cfg, userAPI)
|
2017-11-29 09:43:03 +00:00
|
|
|
}
|
|
|
|
|
2020-01-30 11:25:57 +00:00
|
|
|
func handleGuestRegistration(
|
|
|
|
req *http.Request,
|
|
|
|
r registerRequest,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2020-01-30 11:25:57 +00:00
|
|
|
) util.JSONResponse {
|
2020-06-17 10:22:26 +00:00
|
|
|
var res userapi.PerformAccountCreationResponse
|
|
|
|
err := userAPI.PerformAccountCreation(req.Context(), &userapi.PerformAccountCreationRequest{
|
|
|
|
AccountType: userapi.AccountTypeGuest,
|
|
|
|
}, &res)
|
2020-01-30 11:25:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("failed to create account: " + err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
token, err := tokens.GenerateLoginToken(tokens.TokenOptions{
|
|
|
|
ServerPrivateKey: cfg.Matrix.PrivateKey.Seed(),
|
2020-06-17 10:22:26 +00:00
|
|
|
ServerName: string(res.Account.ServerName),
|
|
|
|
UserID: res.Account.UserID,
|
2020-01-30 11:25:57 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("Failed to generate access token"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
//we don't allow guests to specify their own device_id
|
2020-06-17 10:22:26 +00:00
|
|
|
var devRes userapi.PerformDeviceCreationResponse
|
|
|
|
err = userAPI.PerformDeviceCreation(req.Context(), &userapi.PerformDeviceCreationRequest{
|
|
|
|
Localpart: res.Account.Localpart,
|
|
|
|
DeviceDisplayName: r.InitialDisplayName,
|
|
|
|
AccessToken: token,
|
2020-10-09 08:17:23 +00:00
|
|
|
IPAddr: req.RemoteAddr,
|
|
|
|
UserAgent: req.UserAgent(),
|
2020-06-17 10:22:26 +00:00
|
|
|
}, &devRes)
|
2020-01-30 11:25:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("failed to create device: " + err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusOK,
|
|
|
|
JSON: registerResponse{
|
2020-06-17 10:22:26 +00:00
|
|
|
UserID: devRes.Device.UserID,
|
|
|
|
AccessToken: devRes.Device.AccessToken,
|
|
|
|
HomeServer: res.Account.ServerName,
|
|
|
|
DeviceID: devRes.Device.ID,
|
2020-01-30 11:25:57 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// handleRegistrationFlow will direct and complete registration flow stages
|
|
|
|
// that the client has requested.
|
2018-11-06 14:40:37 +00:00
|
|
|
// nolint: gocyclo
|
2017-11-29 09:43:03 +00:00
|
|
|
func handleRegistrationFlow(
|
|
|
|
req *http.Request,
|
|
|
|
r registerRequest,
|
|
|
|
sessionID string,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2017-11-29 09:43:03 +00:00
|
|
|
) util.JSONResponse {
|
2017-05-22 14:55:39 +00:00
|
|
|
// TODO: Shared secret registration (create new user scripts)
|
|
|
|
// TODO: Enable registration config flag
|
|
|
|
// TODO: Guest account upgrading
|
|
|
|
|
|
|
|
// TODO: Handle loading of previous session parameters from database.
|
|
|
|
// TODO: Handle mapping registrationRequest parameters into session parameters
|
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
// TODO: email / msisdn auth types.
|
2017-12-04 17:07:45 +00:00
|
|
|
|
2020-08-10 13:18:04 +00:00
|
|
|
if cfg.RegistrationDisabled && r.Auth.Type != authtypes.LoginTypeSharedSecret {
|
2018-03-13 15:55:45 +00:00
|
|
|
return util.MessageResponse(http.StatusForbidden, "Registration has been disabled")
|
2017-12-04 17:07:45 +00:00
|
|
|
}
|
|
|
|
|
2017-05-22 14:55:39 +00:00
|
|
|
switch r.Auth.Type {
|
2017-12-05 16:16:14 +00:00
|
|
|
case authtypes.LoginTypeRecaptcha:
|
|
|
|
// Check given captcha response
|
|
|
|
resErr := validateRecaptcha(cfg, r.Auth.Response, req.RemoteAddr)
|
|
|
|
if resErr != nil {
|
|
|
|
return *resErr
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
// Add Recaptcha to the list of completed registration stages
|
2019-08-14 17:34:49 +00:00
|
|
|
AddCompletedSessionStage(sessionID, authtypes.LoginTypeRecaptcha)
|
2017-12-05 16:16:14 +00:00
|
|
|
|
|
|
|
case authtypes.LoginTypeSharedSecret:
|
|
|
|
// Check shared secret against config
|
|
|
|
valid, err := isValidMacLogin(cfg, r.Username, r.Password, r.Admin, r.Auth.Mac)
|
2017-09-22 15:13:19 +00:00
|
|
|
|
|
|
|
if err != nil {
|
2020-03-02 16:20:44 +00:00
|
|
|
util.GetLogger(req.Context()).WithError(err).Error("isValidMacLogin failed")
|
|
|
|
return jsonerror.InternalServerError()
|
2017-12-05 16:16:14 +00:00
|
|
|
} else if !valid {
|
2018-03-13 15:55:45 +00:00
|
|
|
return util.MessageResponse(http.StatusForbidden, "HMAC incorrect")
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// Add SharedSecret to the list of completed registration stages
|
2019-08-14 17:34:49 +00:00
|
|
|
AddCompletedSessionStage(sessionID, authtypes.LoginTypeSharedSecret)
|
2017-11-29 09:43:03 +00:00
|
|
|
|
2018-11-06 14:40:37 +00:00
|
|
|
case "":
|
|
|
|
// Extract the access token from the request, if there's one to extract
|
|
|
|
// (which we can know by checking whether the error is nil or not).
|
|
|
|
accessToken, err := auth.ExtractAccessToken(req)
|
|
|
|
|
|
|
|
// A missing auth type can mean either the registration is performed by
|
|
|
|
// an AS or the request is made as the first step of a registration
|
|
|
|
// using the User-Interactive Authentication API. This can be determined
|
|
|
|
// by whether the request contains an access token.
|
|
|
|
if err == nil {
|
|
|
|
return handleApplicationServiceRegistration(
|
2020-06-17 10:22:26 +00:00
|
|
|
accessToken, err, req, r, cfg, userAPI,
|
2018-11-06 14:40:37 +00:00
|
|
|
)
|
2018-02-08 11:02:48 +00:00
|
|
|
}
|
|
|
|
|
2018-11-06 14:40:37 +00:00
|
|
|
case authtypes.LoginTypeApplicationService:
|
|
|
|
// Extract the access token from the request.
|
|
|
|
accessToken, err := auth.ExtractAccessToken(req)
|
|
|
|
// Let the AS registration handler handle the process from here. We
|
|
|
|
// don't need a condition on that call since the registration is clearly
|
|
|
|
// stated as being AS-related.
|
|
|
|
return handleApplicationServiceRegistration(
|
2020-06-17 10:22:26 +00:00
|
|
|
accessToken, err, req, r, cfg, userAPI,
|
2018-07-17 15:57:20 +00:00
|
|
|
)
|
2018-02-08 11:02:48 +00:00
|
|
|
|
2017-09-22 15:13:19 +00:00
|
|
|
case authtypes.LoginTypeDummy:
|
|
|
|
// there is nothing to do
|
2017-11-29 09:43:03 +00:00
|
|
|
// Add Dummy to the list of completed registration stages
|
2019-08-14 17:34:49 +00:00
|
|
|
AddCompletedSessionStage(sessionID, authtypes.LoginTypeDummy)
|
2017-11-29 09:43:03 +00:00
|
|
|
|
2017-09-22 15:13:19 +00:00
|
|
|
default:
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusNotImplemented,
|
2017-09-22 15:13:19 +00:00
|
|
|
JSON: jsonerror.Unknown("unknown/unimplemented auth type"),
|
|
|
|
}
|
|
|
|
}
|
2017-11-29 09:43:03 +00:00
|
|
|
|
|
|
|
// Check if the user's registration flow has been completed successfully
|
2018-02-08 11:02:48 +00:00
|
|
|
// A response with current registration flow and remaining available methods
|
|
|
|
// will be returned if a flow has not been successfully completed yet
|
2018-03-15 17:21:08 +00:00
|
|
|
return checkAndCompleteFlow(sessions.GetCompletedStages(sessionID),
|
2020-06-17 10:22:26 +00:00
|
|
|
req, r, sessionID, cfg, userAPI)
|
2018-02-08 11:02:48 +00:00
|
|
|
}
|
|
|
|
|
2018-11-06 14:40:37 +00:00
|
|
|
// handleApplicationServiceRegistration handles the registration of an
|
|
|
|
// application service's user by validating the AS from its access token and
|
|
|
|
// registering the user. Its two first parameters must be the two return values
|
|
|
|
// of the auth.ExtractAccessToken function.
|
|
|
|
// Returns an error if the access token couldn't be extracted from the request
|
|
|
|
// at an earlier step of the registration workflow, or if the provided access
|
|
|
|
// token doesn't belong to a valid AS, or if there was an issue completing the
|
|
|
|
// registration process.
|
|
|
|
func handleApplicationServiceRegistration(
|
|
|
|
accessToken string,
|
|
|
|
tokenErr error,
|
|
|
|
req *http.Request,
|
|
|
|
r registerRequest,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2018-11-06 14:40:37 +00:00
|
|
|
) util.JSONResponse {
|
|
|
|
// Check if we previously had issues extracting the access token from the
|
|
|
|
// request.
|
|
|
|
if tokenErr != nil {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusUnauthorized,
|
|
|
|
JSON: jsonerror.MissingToken(tokenErr.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check application service register user request is valid.
|
|
|
|
// The application service's ID is returned if so.
|
|
|
|
appserviceID, err := validateApplicationService(
|
|
|
|
cfg, r.Username, accessToken,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return *err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If no error, application service was successfully validated.
|
|
|
|
// Don't need to worry about appending to registration stages as
|
|
|
|
// application service registration is entirely separate.
|
|
|
|
return completeRegistration(
|
2020-10-09 08:17:23 +00:00
|
|
|
req.Context(), userAPI, r.Username, "", appserviceID, req.RemoteAddr, req.UserAgent(),
|
2019-07-22 14:05:38 +00:00
|
|
|
r.InhibitLogin, r.InitialDisplayName, r.DeviceID,
|
2018-11-06 14:40:37 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// checkAndCompleteFlow checks if a given registration flow is completed given
|
|
|
|
// a set of allowed flows. If so, registration is completed, otherwise a
|
|
|
|
// response with
|
|
|
|
func checkAndCompleteFlow(
|
|
|
|
flow []authtypes.LoginType,
|
|
|
|
req *http.Request,
|
|
|
|
r registerRequest,
|
|
|
|
sessionID string,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2018-02-08 11:02:48 +00:00
|
|
|
) util.JSONResponse {
|
|
|
|
if checkFlowCompleted(flow, cfg.Derived.Registration.Flows) {
|
|
|
|
// This flow was completed, registration can continue
|
2018-07-17 15:57:20 +00:00
|
|
|
return completeRegistration(
|
2020-10-09 08:17:23 +00:00
|
|
|
req.Context(), userAPI, r.Username, r.Password, "", req.RemoteAddr, req.UserAgent(),
|
2019-07-22 14:05:38 +00:00
|
|
|
r.InhibitLogin, r.InitialDisplayName, r.DeviceID,
|
2018-07-17 15:57:20 +00:00
|
|
|
)
|
2017-11-29 09:43:03 +00:00
|
|
|
}
|
|
|
|
|
2018-02-08 11:02:48 +00:00
|
|
|
// There are still more stages to complete.
|
|
|
|
// Return the flows and those that have been completed.
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusUnauthorized,
|
2018-02-08 11:02:48 +00:00
|
|
|
JSON: newUserInteractiveResponse(sessionID,
|
|
|
|
cfg.Derived.Registration.Flows, cfg.Derived.Registration.Params),
|
|
|
|
}
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// LegacyRegister process register requests from the legacy v1 API
|
|
|
|
func LegacyRegister(
|
|
|
|
req *http.Request,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2017-09-22 15:13:19 +00:00
|
|
|
) util.JSONResponse {
|
|
|
|
var r legacyRegisterRequest
|
2017-12-04 17:07:45 +00:00
|
|
|
resErr := parseAndValidateLegacyLogin(req, &r)
|
2017-09-22 15:13:19 +00:00
|
|
|
if resErr != nil {
|
|
|
|
return *resErr
|
|
|
|
}
|
2017-12-04 09:40:36 +00:00
|
|
|
|
2017-09-22 15:13:19 +00:00
|
|
|
logger := util.GetLogger(req.Context())
|
|
|
|
logger.WithFields(log.Fields{
|
|
|
|
"username": r.Username,
|
|
|
|
"auth.type": r.Type,
|
|
|
|
}).Info("Processing registration request")
|
|
|
|
|
2020-08-10 13:18:04 +00:00
|
|
|
if cfg.RegistrationDisabled && r.Type != authtypes.LoginTypeSharedSecret {
|
2018-03-13 15:55:45 +00:00
|
|
|
return util.MessageResponse(http.StatusForbidden, "Registration has been disabled")
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
switch r.Type {
|
|
|
|
case authtypes.LoginTypeSharedSecret:
|
2020-08-10 13:18:04 +00:00
|
|
|
if cfg.RegistrationSharedSecret == "" {
|
2018-03-13 15:55:45 +00:00
|
|
|
return util.MessageResponse(http.StatusBadRequest, "Shared secret registration is disabled")
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
2017-12-05 16:16:14 +00:00
|
|
|
valid, err := isValidMacLogin(cfg, r.Username, r.Password, r.Admin, r.Mac)
|
2017-09-22 15:13:19 +00:00
|
|
|
if err != nil {
|
2020-03-02 16:20:44 +00:00
|
|
|
util.GetLogger(req.Context()).WithError(err).Error("isValidMacLogin failed")
|
|
|
|
return jsonerror.InternalServerError()
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if !valid {
|
2018-03-13 15:55:45 +00:00
|
|
|
return util.MessageResponse(http.StatusForbidden, "HMAC incorrect")
|
2017-09-22 15:13:19 +00:00
|
|
|
}
|
|
|
|
|
2020-10-09 08:17:23 +00:00
|
|
|
return completeRegistration(req.Context(), userAPI, r.Username, r.Password, "", req.RemoteAddr, req.UserAgent(), false, nil, nil)
|
2017-05-23 16:43:05 +00:00
|
|
|
case authtypes.LoginTypeDummy:
|
2017-05-22 14:55:39 +00:00
|
|
|
// there is nothing to do
|
2020-10-09 08:17:23 +00:00
|
|
|
return completeRegistration(req.Context(), userAPI, r.Username, r.Password, "", req.RemoteAddr, req.UserAgent(), false, nil, nil)
|
2017-05-22 14:55:39 +00:00
|
|
|
default:
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusNotImplemented,
|
2017-05-22 14:55:39 +00:00
|
|
|
JSON: jsonerror.Unknown("unknown/unimplemented auth type"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-04 17:07:45 +00:00
|
|
|
// parseAndValidateLegacyLogin parses the request into r and checks that the
|
|
|
|
// request is valid (e.g. valid user names, etc)
|
|
|
|
func parseAndValidateLegacyLogin(req *http.Request, r *legacyRegisterRequest) *util.JSONResponse {
|
|
|
|
resErr := httputil.UnmarshalJSONRequest(req, &r)
|
|
|
|
if resErr != nil {
|
|
|
|
return resErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// Squash username to all lowercase letters
|
|
|
|
r.Username = strings.ToLower(r.Username)
|
|
|
|
|
2018-07-06 09:27:11 +00:00
|
|
|
if resErr = validateUsername(r.Username); resErr != nil {
|
2017-12-04 17:07:45 +00:00
|
|
|
return resErr
|
|
|
|
}
|
|
|
|
if resErr = validatePassword(r.Password); resErr != nil {
|
|
|
|
return resErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// All registration requests must specify what auth they are using to perform this request
|
|
|
|
if r.Type == "" {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-12-04 17:07:45 +00:00
|
|
|
JSON: jsonerror.BadJSON("invalid type"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-07-22 14:05:38 +00:00
|
|
|
// completeRegistration runs some rudimentary checks against the submitted
|
|
|
|
// input, then if successful creates an account and a newly associated device
|
|
|
|
// We pass in each individual part of the request here instead of just passing a
|
|
|
|
// registerRequest, as this function serves requests encoded as both
|
|
|
|
// registerRequests and legacyRegisterRequests, which share some attributes but
|
|
|
|
// not all
|
2017-09-18 13:15:27 +00:00
|
|
|
func completeRegistration(
|
|
|
|
ctx context.Context,
|
2020-06-17 10:22:26 +00:00
|
|
|
userAPI userapi.UserInternalAPI,
|
2020-10-09 08:17:23 +00:00
|
|
|
username, password, appserviceID, ipAddr, userAgent string,
|
2020-06-12 13:55:57 +00:00
|
|
|
inhibitLogin eventutil.WeakBoolean,
|
2019-07-22 14:05:38 +00:00
|
|
|
displayName, deviceID *string,
|
2017-09-18 13:15:27 +00:00
|
|
|
) util.JSONResponse {
|
2017-05-30 16:51:40 +00:00
|
|
|
if username == "" {
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-05-30 16:51:40 +00:00
|
|
|
JSON: jsonerror.BadJSON("missing username"),
|
|
|
|
}
|
|
|
|
}
|
2018-02-08 11:02:48 +00:00
|
|
|
// Blank passwords are only allowed by registered application services
|
|
|
|
if password == "" && appserviceID == "" {
|
2017-05-30 16:51:40 +00:00
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-05-30 16:51:40 +00:00
|
|
|
JSON: jsonerror.BadJSON("missing password"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-17 10:22:26 +00:00
|
|
|
var accRes userapi.PerformAccountCreationResponse
|
|
|
|
err := userAPI.PerformAccountCreation(ctx, &userapi.PerformAccountCreationRequest{
|
|
|
|
AppServiceID: appserviceID,
|
|
|
|
Localpart: username,
|
|
|
|
Password: password,
|
|
|
|
AccountType: userapi.AccountTypeUser,
|
|
|
|
OnConflict: userapi.ConflictAbort,
|
|
|
|
}, &accRes)
|
2017-05-22 14:55:39 +00:00
|
|
|
if err != nil {
|
2020-06-17 10:22:26 +00:00
|
|
|
if _, ok := err.(*userapi.ErrorConflict); ok { // user already exists
|
2020-06-01 17:34:29 +00:00
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.UserInUse("Desired user ID is already taken."),
|
|
|
|
}
|
|
|
|
}
|
2017-05-22 14:55:39 +00:00
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-05-22 14:55:39 +00:00
|
|
|
JSON: jsonerror.Unknown("failed to create account: " + err.Error()),
|
|
|
|
}
|
|
|
|
}
|
2017-05-30 16:51:40 +00:00
|
|
|
|
2019-07-22 14:05:38 +00:00
|
|
|
// Increment prometheus counter for created users
|
|
|
|
amtRegUsers.Inc()
|
|
|
|
|
2018-07-17 15:57:20 +00:00
|
|
|
// Check whether inhibit_login option is set. If so, don't create an access
|
|
|
|
// token or a device for this user
|
|
|
|
if inhibitLogin {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusOK,
|
|
|
|
JSON: registerResponse{
|
2020-06-17 10:22:26 +00:00
|
|
|
UserID: userutil.MakeUserID(username, accRes.Account.ServerName),
|
|
|
|
HomeServer: accRes.Account.ServerName,
|
2018-07-17 15:57:20 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-30 16:51:40 +00:00
|
|
|
token, err := auth.GenerateAccessToken()
|
|
|
|
if err != nil {
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-05-30 16:51:40 +00:00
|
|
|
JSON: jsonerror.Unknown("Failed to generate access token"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-17 10:22:26 +00:00
|
|
|
var devRes userapi.PerformDeviceCreationResponse
|
|
|
|
err = userAPI.PerformDeviceCreation(ctx, &userapi.PerformDeviceCreationRequest{
|
|
|
|
Localpart: username,
|
|
|
|
AccessToken: token,
|
|
|
|
DeviceDisplayName: displayName,
|
|
|
|
DeviceID: deviceID,
|
2020-10-09 08:17:23 +00:00
|
|
|
IPAddr: ipAddr,
|
|
|
|
UserAgent: userAgent,
|
2020-06-17 10:22:26 +00:00
|
|
|
}, &devRes)
|
2017-05-30 16:51:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-05-30 16:51:40 +00:00
|
|
|
JSON: jsonerror.Unknown("failed to create device: " + err.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-22 14:55:39 +00:00
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusOK,
|
2017-05-22 14:55:39 +00:00
|
|
|
JSON: registerResponse{
|
2020-06-17 10:22:26 +00:00
|
|
|
UserID: devRes.Device.UserID,
|
|
|
|
AccessToken: devRes.Device.AccessToken,
|
|
|
|
HomeServer: accRes.Account.ServerName,
|
|
|
|
DeviceID: devRes.Device.ID,
|
2017-05-22 14:55:39 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2017-09-22 15:13:19 +00:00
|
|
|
|
|
|
|
// Used for shared secret registration.
|
|
|
|
// Checks if the username, password and isAdmin flag matches the given mac.
|
|
|
|
func isValidMacLogin(
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2017-09-22 15:13:19 +00:00
|
|
|
username, password string,
|
|
|
|
isAdmin bool,
|
|
|
|
givenMac []byte,
|
|
|
|
) (bool, error) {
|
2020-08-10 13:18:04 +00:00
|
|
|
sharedSecret := cfg.RegistrationSharedSecret
|
2017-12-05 16:16:14 +00:00
|
|
|
|
|
|
|
// Check that shared secret registration isn't disabled.
|
2020-08-10 13:18:04 +00:00
|
|
|
if cfg.RegistrationSharedSecret == "" {
|
2017-12-05 16:16:14 +00:00
|
|
|
return false, errors.New("Shared secret registration is disabled")
|
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// Double check that username/password don't contain the HMAC delimiters. We should have
|
2017-09-22 15:13:19 +00:00
|
|
|
// already checked this.
|
|
|
|
if strings.Contains(username, "\x00") {
|
|
|
|
return false, errors.New("Username contains invalid character")
|
|
|
|
}
|
|
|
|
if strings.Contains(password, "\x00") {
|
|
|
|
return false, errors.New("Password contains invalid character")
|
|
|
|
}
|
|
|
|
if sharedSecret == "" {
|
|
|
|
return false, errors.New("Shared secret registration is disabled")
|
|
|
|
}
|
|
|
|
|
|
|
|
adminString := "notadmin"
|
|
|
|
if isAdmin {
|
|
|
|
adminString = "admin"
|
|
|
|
}
|
|
|
|
joined := strings.Join([]string{username, password, adminString}, "\x00")
|
|
|
|
|
|
|
|
mac := hmac.New(sha1.New, []byte(sharedSecret))
|
|
|
|
_, err := mac.Write([]byte(joined))
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
expectedMAC := mac.Sum(nil)
|
|
|
|
|
|
|
|
return hmac.Equal(givenMac, expectedMAC), nil
|
|
|
|
}
|
2017-10-09 14:24:38 +00:00
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// checkFlows checks a single completed flow against another required one. If
|
|
|
|
// one contains at least all of the stages that the other does, checkFlows
|
|
|
|
// returns true.
|
|
|
|
func checkFlows(
|
|
|
|
completedStages []authtypes.LoginType,
|
|
|
|
requiredStages []authtypes.LoginType,
|
|
|
|
) bool {
|
|
|
|
// Create temporary slices so they originals will not be modified on sorting
|
|
|
|
completed := make([]authtypes.LoginType, len(completedStages))
|
|
|
|
required := make([]authtypes.LoginType, len(requiredStages))
|
|
|
|
copy(completed, completedStages)
|
|
|
|
copy(required, requiredStages)
|
|
|
|
|
|
|
|
// Sort the slices for simple comparison
|
|
|
|
sort.Slice(completed, func(i, j int) bool { return completed[i] < completed[j] })
|
|
|
|
sort.Slice(required, func(i, j int) bool { return required[i] < required[j] })
|
|
|
|
|
|
|
|
// Iterate through each slice, going to the next required slice only once
|
|
|
|
// we've found a match.
|
|
|
|
i, j := 0, 0
|
|
|
|
for j < len(required) {
|
|
|
|
// Exit if we've reached the end of our input without being able to
|
|
|
|
// match all of the required stages.
|
|
|
|
if i >= len(completed) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we've found a stage we want, move on to the next required stage.
|
|
|
|
if completed[i] == required[j] {
|
|
|
|
j++
|
|
|
|
}
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkFlowCompleted checks if a registration flow complies with any allowed flow
|
|
|
|
// dictated by the server. Order of stages does not matter. A user may complete
|
|
|
|
// extra stages as long as the required stages of at least one flow is met.
|
2018-02-08 11:02:48 +00:00
|
|
|
func checkFlowCompleted(
|
|
|
|
flow []authtypes.LoginType,
|
|
|
|
allowedFlows []authtypes.Flow,
|
|
|
|
) bool {
|
2017-11-29 09:43:03 +00:00
|
|
|
// Iterate through possible flows to check whether any have been fully completed.
|
|
|
|
for _, allowedFlow := range allowedFlows {
|
|
|
|
if checkFlows(flow, allowedFlow.Stages) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2017-10-09 14:24:38 +00:00
|
|
|
type availableResponse struct {
|
|
|
|
Available bool `json:"available"`
|
|
|
|
}
|
|
|
|
|
2017-11-29 09:43:03 +00:00
|
|
|
// RegisterAvailable checks if the username is already taken or invalid.
|
2017-10-09 14:24:38 +00:00
|
|
|
func RegisterAvailable(
|
|
|
|
req *http.Request,
|
2020-08-10 13:18:04 +00:00
|
|
|
cfg *config.ClientAPI,
|
2020-02-13 17:27:33 +00:00
|
|
|
accountDB accounts.Database,
|
2017-10-09 14:24:38 +00:00
|
|
|
) util.JSONResponse {
|
|
|
|
username := req.URL.Query().Get("username")
|
|
|
|
|
2017-12-04 09:40:36 +00:00
|
|
|
// Squash username to all lowercase letters
|
|
|
|
username = strings.ToLower(username)
|
|
|
|
|
2018-07-06 09:27:11 +00:00
|
|
|
if err := validateUsername(username); err != nil {
|
2017-10-09 14:24:38 +00:00
|
|
|
return *err
|
|
|
|
}
|
|
|
|
|
2018-08-20 09:23:01 +00:00
|
|
|
// Check if this username is reserved by an application service
|
|
|
|
userID := userutil.MakeUserID(username, cfg.Matrix.ServerName)
|
|
|
|
for _, appservice := range cfg.Derived.ApplicationServices {
|
2020-04-14 14:31:27 +00:00
|
|
|
if appservice.OwnsNamespaceCoveringUserId(userID) {
|
2018-08-20 09:23:01 +00:00
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.UserInUse("Desired user ID is reserved by an application service."),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-09 14:24:38 +00:00
|
|
|
availability, availabilityErr := accountDB.CheckAccountAvailability(req.Context(), username)
|
|
|
|
if availabilityErr != nil {
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusInternalServerError,
|
2017-10-09 14:24:38 +00:00
|
|
|
JSON: jsonerror.Unknown("failed to check availability: " + availabilityErr.Error()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !availability {
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2018-08-20 09:23:01 +00:00
|
|
|
JSON: jsonerror.UserInUse("Desired User ID is already taken."),
|
2017-10-09 14:24:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusOK,
|
2017-10-09 14:24:38 +00:00
|
|
|
JSON: availableResponse{
|
|
|
|
Available: true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|