2021-08-16 23:30:51 +02:00
|
|
|
package server
|
2021-07-17 14:38:59 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-07-30 17:46:38 +02:00
|
|
|
"fmt"
|
2022-05-08 11:04:57 +02:00
|
|
|
"strings"
|
2021-07-24 16:14:29 +02:00
|
|
|
"time"
|
|
|
|
|
2023-03-30 10:54:09 +02:00
|
|
|
pb "github.com/golang/protobuf/proto" // nolint
|
2021-07-22 10:28:00 +02:00
|
|
|
"github.com/golang/protobuf/ptypes/timestamp"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
"google.golang.org/grpc/codes"
|
2022-09-22 09:25:31 +02:00
|
|
|
gRPCPeer "google.golang.org/grpc/peer"
|
2021-07-17 14:38:59 +02:00
|
|
|
"google.golang.org/grpc/status"
|
2023-03-30 10:54:09 +02:00
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/encryption"
|
|
|
|
"github.com/netbirdio/netbird/management/proto"
|
2023-09-04 11:37:39 +02:00
|
|
|
"github.com/netbirdio/netbird/management/server/jwtclaims"
|
2023-03-30 10:54:09 +02:00
|
|
|
internalStatus "github.com/netbirdio/netbird/management/server/status"
|
2023-09-04 11:37:39 +02:00
|
|
|
"github.com/netbirdio/netbird/management/server/telemetry"
|
2021-07-17 14:38:59 +02:00
|
|
|
)
|
|
|
|
|
2022-07-29 20:37:09 +02:00
|
|
|
// GRPCServer an instance of a Management gRPC API server
|
|
|
|
type GRPCServer struct {
|
2022-02-22 11:28:19 +01:00
|
|
|
accountManager AccountManager
|
2021-07-30 17:46:38 +02:00
|
|
|
wgKey wgtypes.Key
|
2021-07-20 18:09:26 +02:00
|
|
|
proto.UnimplementedManagementServiceServer
|
2021-09-02 14:41:54 +02:00
|
|
|
peersUpdateManager *PeersUpdateManager
|
|
|
|
config *Config
|
|
|
|
turnCredentialsManager TURNCredentialsManager
|
2023-03-30 10:54:09 +02:00
|
|
|
jwtValidator *jwtclaims.JWTValidator
|
2023-02-03 21:47:20 +01:00
|
|
|
jwtClaimsExtractor *jwtclaims.ClaimsExtractor
|
2022-10-22 15:06:54 +02:00
|
|
|
appMetrics telemetry.AppMetrics
|
2023-09-04 11:37:39 +02:00
|
|
|
ephemeralManager *EphemeralManager
|
2021-07-22 10:28:00 +02:00
|
|
|
}
|
|
|
|
|
2021-07-17 14:38:59 +02:00
|
|
|
// NewServer creates a new Management server
|
2023-09-04 11:37:39 +02:00
|
|
|
func NewServer(config *Config, accountManager AccountManager, peersUpdateManager *PeersUpdateManager, turnCredentialsManager TURNCredentialsManager, appMetrics telemetry.AppMetrics, ephemeralManager *EphemeralManager) (*GRPCServer, error) {
|
2021-07-22 10:28:00 +02:00
|
|
|
key, err := wgtypes.GeneratePrivateKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-29 17:48:31 +02:00
|
|
|
|
2023-03-30 16:14:51 +02:00
|
|
|
var jwtValidator *jwtclaims.JWTValidator
|
2022-05-05 20:02:15 +02:00
|
|
|
|
|
|
|
if config.HttpConfig != nil && config.HttpConfig.AuthIssuer != "" && config.HttpConfig.AuthAudience != "" && validateURL(config.HttpConfig.AuthKeysLocation) {
|
2023-03-30 16:14:51 +02:00
|
|
|
jwtValidator, err = jwtclaims.NewJWTValidator(
|
2022-05-05 20:02:15 +02:00
|
|
|
config.HttpConfig.AuthIssuer,
|
2023-04-04 16:40:56 +02:00
|
|
|
config.GetAuthAudiences(),
|
2023-04-14 11:17:28 +02:00
|
|
|
config.HttpConfig.AuthKeysLocation,
|
2023-04-15 02:44:42 +02:00
|
|
|
config.HttpConfig.IdpSignKeyRefreshEnabled,
|
2023-04-14 11:17:28 +02:00
|
|
|
)
|
2022-05-05 20:02:15 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, status.Errorf(codes.Internal, "unable to create new jwt middleware, err: %v", err)
|
|
|
|
}
|
2022-05-08 11:04:57 +02:00
|
|
|
} else {
|
|
|
|
log.Debug("unable to use http config to create new jwt middleware")
|
2022-05-05 20:02:15 +02:00
|
|
|
}
|
|
|
|
|
2022-10-22 15:06:54 +02:00
|
|
|
if appMetrics != nil {
|
|
|
|
// update gauge based on number of connected peers which is equal to open gRPC streams
|
|
|
|
err = appMetrics.GRPCMetrics().RegisterConnectedStreams(func() int64 {
|
|
|
|
return int64(len(peersUpdateManager.peerChannels))
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-03 21:47:20 +01:00
|
|
|
var audience, userIDClaim string
|
|
|
|
if config.HttpConfig != nil {
|
|
|
|
audience = config.HttpConfig.AuthAudience
|
|
|
|
userIDClaim = config.HttpConfig.AuthUserIDClaim
|
|
|
|
}
|
|
|
|
jwtClaimsExtractor := jwtclaims.NewClaimsExtractor(
|
|
|
|
jwtclaims.WithAudience(audience),
|
|
|
|
jwtclaims.WithUserIDClaim(userIDClaim),
|
|
|
|
)
|
|
|
|
|
2022-07-29 20:37:09 +02:00
|
|
|
return &GRPCServer{
|
2021-07-22 10:28:00 +02:00
|
|
|
wgKey: key,
|
|
|
|
// peerKey -> event channel
|
2021-09-02 14:41:54 +02:00
|
|
|
peersUpdateManager: peersUpdateManager,
|
|
|
|
accountManager: accountManager,
|
|
|
|
config: config,
|
|
|
|
turnCredentialsManager: turnCredentialsManager,
|
2023-03-30 16:14:51 +02:00
|
|
|
jwtValidator: jwtValidator,
|
2023-02-03 21:47:20 +01:00
|
|
|
jwtClaimsExtractor: jwtClaimsExtractor,
|
2022-10-22 15:06:54 +02:00
|
|
|
appMetrics: appMetrics,
|
2023-09-04 11:37:39 +02:00
|
|
|
ephemeralManager: ephemeralManager,
|
2021-07-17 14:38:59 +02:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2022-07-29 20:37:09 +02:00
|
|
|
func (s *GRPCServer) GetServerKey(ctx context.Context, req *proto.Empty) (*proto.ServerKeyResponse, error) {
|
2021-07-22 10:28:00 +02:00
|
|
|
// todo introduce something more meaningful with the key expiration/rotation
|
2022-10-22 15:06:54 +02:00
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().CountGetKeyRequest()
|
|
|
|
}
|
2021-07-22 10:28:00 +02:00
|
|
|
now := time.Now().Add(24 * time.Hour)
|
|
|
|
secs := int64(now.Second())
|
|
|
|
nanos := int32(now.Nanosecond())
|
|
|
|
expiresAt := ×tamp.Timestamp{Seconds: secs, Nanos: nanos}
|
|
|
|
|
|
|
|
return &proto.ServerKeyResponse{
|
|
|
|
Key: s.wgKey.PublicKey().String(),
|
|
|
|
ExpiresAt: expiresAt,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2022-05-21 15:21:39 +02:00
|
|
|
// Sync validates the existence of a connecting peer, sends an initial state (all available for the connecting peers) and
|
2021-07-22 10:28:00 +02:00
|
|
|
// notifies the connected peer of any updates (e.g. new peers under the same account)
|
2022-07-29 20:37:09 +02:00
|
|
|
func (s *GRPCServer) Sync(req *proto.EncryptedMessage, srv proto.ManagementService_SyncServer) error {
|
2023-05-19 11:42:25 +02:00
|
|
|
reqStart := time.Now()
|
2022-10-22 15:06:54 +02:00
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().CountSyncRequest()
|
|
|
|
}
|
2022-09-22 09:25:31 +02:00
|
|
|
p, ok := gRPCPeer.FromContext(srv.Context())
|
|
|
|
if ok {
|
|
|
|
log.Debugf("Sync request from peer [%s] [%s]", req.WgPubKey, p.Addr.String())
|
|
|
|
}
|
2021-07-22 10:28:00 +02:00
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
syncReq := &proto.SyncRequest{}
|
|
|
|
peerKey, err := s.parseRequest(req, syncReq)
|
2023-02-13 12:21:02 +01:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
return err
|
2023-02-13 12:21:02 +01:00
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
peer, netMap, err := s.accountManager.SyncPeer(PeerSync{WireGuardPubKey: peerKey.String()})
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
return mapError(err)
|
2021-07-22 10:28:00 +02:00
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
err = s.sendInitialSync(peerKey, peer, netMap, srv)
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
2022-08-27 17:55:05 +02:00
|
|
|
log.Debugf("error while sending initial sync for %s: %v", peerKey.String(), err)
|
2021-07-22 10:28:00 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-02-03 10:33:28 +01:00
|
|
|
updates := s.peersUpdateManager.CreateChannel(peer.ID)
|
2023-09-04 11:37:39 +02:00
|
|
|
|
|
|
|
s.ephemeralManager.OnPeerConnected(peer)
|
|
|
|
|
2021-08-29 17:48:31 +02:00
|
|
|
err = s.accountManager.MarkPeerConnected(peerKey.String(), true)
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed marking peer as connected %s %v", peerKey, err)
|
|
|
|
}
|
2021-09-02 14:41:54 +02:00
|
|
|
|
2021-09-03 17:47:40 +02:00
|
|
|
if s.config.TURNConfig.TimeBasedCredentials {
|
2023-02-03 10:33:28 +01:00
|
|
|
s.turnCredentialsManager.SetupRefresh(peer.ID)
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
2023-05-19 11:42:25 +02:00
|
|
|
|
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().CountSyncRequestDuration(time.Since(reqStart))
|
|
|
|
}
|
|
|
|
|
2021-07-22 10:28:00 +02:00
|
|
|
// keep a connection to the peer and send updates when available
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
// condition when there are some updates
|
|
|
|
case update, open := <-updates:
|
2023-09-25 10:23:43 +02:00
|
|
|
|
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().UpdateChannelQueueLength(len(updates) + 1)
|
|
|
|
}
|
|
|
|
|
2021-07-22 10:28:00 +02:00
|
|
|
if !open {
|
2022-08-27 17:55:05 +02:00
|
|
|
log.Debugf("updates channel for peer %s was closed", peerKey.String())
|
2023-02-28 20:02:30 +01:00
|
|
|
s.cancelPeerRoutines(peer)
|
2021-07-22 10:28:00 +02:00
|
|
|
return nil
|
|
|
|
}
|
2023-11-01 17:11:16 +01:00
|
|
|
log.Debugf("received an update for peer %s", peerKey.String())
|
2021-07-22 10:28:00 +02:00
|
|
|
|
2021-07-22 15:23:24 +02:00
|
|
|
encryptedResp, err := encryption.EncryptMessage(peerKey, s.wgKey, update.Update)
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
2023-09-04 11:37:39 +02:00
|
|
|
s.cancelPeerRoutines(peer)
|
2021-07-22 10:28:00 +02:00
|
|
|
return status.Errorf(codes.Internal, "failed processing update message")
|
|
|
|
}
|
|
|
|
|
2021-07-22 15:23:24 +02:00
|
|
|
err = srv.SendMsg(&proto.EncryptedMessage{
|
|
|
|
WgPubKey: s.wgKey.PublicKey().String(),
|
|
|
|
Body: encryptedResp,
|
|
|
|
})
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
2023-09-04 11:37:39 +02:00
|
|
|
s.cancelPeerRoutines(peer)
|
2021-07-22 10:28:00 +02:00
|
|
|
return status.Errorf(codes.Internal, "failed sending update message")
|
|
|
|
}
|
2021-09-07 18:36:46 +02:00
|
|
|
log.Debugf("sent an update to peer %s", peerKey.String())
|
2021-07-22 10:28:00 +02:00
|
|
|
// condition when client <-> server connection has been terminated
|
|
|
|
case <-srv.Context().Done():
|
|
|
|
// happens when connection drops, e.g. client disconnects
|
|
|
|
log.Debugf("stream of peer %s has been closed", peerKey.String())
|
2023-02-28 20:02:30 +01:00
|
|
|
s.cancelPeerRoutines(peer)
|
2021-07-22 10:28:00 +02:00
|
|
|
return srv.Context().Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-28 20:02:30 +01:00
|
|
|
func (s *GRPCServer) cancelPeerRoutines(peer *Peer) {
|
|
|
|
s.peersUpdateManager.CloseChannel(peer.ID)
|
|
|
|
s.turnCredentialsManager.CancelRefresh(peer.ID)
|
|
|
|
_ = s.accountManager.MarkPeerConnected(peer.Key, false)
|
2023-09-04 11:37:39 +02:00
|
|
|
s.ephemeralManager.OnPeerDisconnected(peer)
|
2023-02-28 20:02:30 +01:00
|
|
|
}
|
|
|
|
|
2023-02-13 12:21:02 +01:00
|
|
|
func (s *GRPCServer) validateToken(jwtToken string) (string, error) {
|
2023-03-30 16:14:51 +02:00
|
|
|
if s.jwtValidator == nil {
|
|
|
|
return "", status.Error(codes.Internal, "no jwt validator set")
|
2023-02-13 12:21:02 +01:00
|
|
|
}
|
|
|
|
|
2023-03-30 16:14:51 +02:00
|
|
|
token, err := s.jwtValidator.ValidateAndParse(jwtToken)
|
2023-02-13 12:21:02 +01:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
return "", status.Errorf(codes.InvalidArgument, "invalid jwt token, err: %v", err)
|
2023-02-13 12:21:02 +01:00
|
|
|
}
|
|
|
|
claims := s.jwtClaimsExtractor.FromToken(token)
|
|
|
|
// we need to call this method because if user is new, we will automatically add it to existing or create a new account
|
|
|
|
_, _, err = s.accountManager.GetAccountFromToken(claims)
|
|
|
|
if err != nil {
|
|
|
|
return "", status.Errorf(codes.Internal, "unable to fetch account with claims, err: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return claims.UserId, nil
|
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
// maps internal internalStatus.Error to gRPC status.Error
|
|
|
|
func mapError(err error) error {
|
|
|
|
if e, ok := internalStatus.FromError(err); ok {
|
|
|
|
switch e.Type() {
|
|
|
|
case internalStatus.PermissionDenied:
|
|
|
|
return status.Errorf(codes.PermissionDenied, e.Message)
|
|
|
|
case internalStatus.Unauthorized:
|
|
|
|
return status.Errorf(codes.PermissionDenied, e.Message)
|
|
|
|
case internalStatus.Unauthenticated:
|
|
|
|
return status.Errorf(codes.PermissionDenied, e.Message)
|
|
|
|
case internalStatus.PreconditionFailed:
|
|
|
|
return status.Errorf(codes.FailedPrecondition, e.Message)
|
|
|
|
case internalStatus.NotFound:
|
|
|
|
return status.Errorf(codes.NotFound, e.Message)
|
|
|
|
default:
|
2022-11-22 12:37:36 +01:00
|
|
|
}
|
2022-05-05 20:02:15 +02:00
|
|
|
}
|
2023-03-23 16:35:06 +01:00
|
|
|
log.Errorf("got an unhandled error: %s", err)
|
2023-03-03 18:35:38 +01:00
|
|
|
return status.Errorf(codes.Internal, "failed handling request")
|
|
|
|
}
|
2022-05-05 20:02:15 +02:00
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
func extractPeerMeta(loginReq *proto.LoginRequest) PeerSystemMeta {
|
|
|
|
return PeerSystemMeta{
|
|
|
|
Hostname: loginReq.GetMeta().GetHostname(),
|
|
|
|
GoOS: loginReq.GetMeta().GetGoOS(),
|
|
|
|
Kernel: loginReq.GetMeta().GetKernel(),
|
|
|
|
Core: loginReq.GetMeta().GetCore(),
|
|
|
|
Platform: loginReq.GetMeta().GetPlatform(),
|
|
|
|
OS: loginReq.GetMeta().GetOS(),
|
|
|
|
WtVersion: loginReq.GetMeta().GetWiretrusteeVersion(),
|
|
|
|
UIVersion: loginReq.GetMeta().GetUiVersion(),
|
2021-08-24 11:50:19 +02:00
|
|
|
}
|
2023-03-03 18:35:38 +01:00
|
|
|
}
|
2022-05-25 23:25:02 +02:00
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
func (s *GRPCServer) parseRequest(req *proto.EncryptedMessage, parsed pb.Message) (wgtypes.Key, error) {
|
|
|
|
peerKey, err := wgtypes.ParseKey(req.GetWgPubKey())
|
2021-07-17 14:38:59 +02:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
log.Warnf("error while parsing peer's WireGuard public key %s.", req.WgPubKey)
|
|
|
|
return wgtypes.Key{}, status.Errorf(codes.InvalidArgument, "provided wgPubKey %s is invalid", req.WgPubKey)
|
2021-07-22 10:28:00 +02:00
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
err = encryption.DecryptMessage(peerKey, s.wgKey, req.Body, parsed)
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
return wgtypes.Key{}, status.Errorf(codes.InvalidArgument, "invalid request message")
|
2021-07-17 14:38:59 +02:00
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
return peerKey, nil
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Login endpoint first checks whether peer is registered under any account
|
|
|
|
// In case it is, the login is successful
|
|
|
|
// In case it isn't, the endpoint checks whether setup key is provided within the request and tries to register a peer.
|
|
|
|
// In case of the successful registration login is also successful
|
2022-07-29 20:37:09 +02:00
|
|
|
func (s *GRPCServer) Login(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error) {
|
2023-05-19 11:42:25 +02:00
|
|
|
reqStart := time.Now()
|
|
|
|
defer func() {
|
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().CountLoginRequestDuration(time.Since(reqStart))
|
|
|
|
}
|
|
|
|
}()
|
2022-10-22 15:06:54 +02:00
|
|
|
if s.appMetrics != nil {
|
|
|
|
s.appMetrics.GRPCMetrics().CountLoginRequest()
|
|
|
|
}
|
2022-09-22 09:25:31 +02:00
|
|
|
p, ok := gRPCPeer.FromContext(ctx)
|
|
|
|
if ok {
|
|
|
|
log.Debugf("Login request from peer [%s] [%s]", req.WgPubKey, p.Addr.String())
|
|
|
|
}
|
2021-08-15 16:56:26 +02:00
|
|
|
|
2022-05-23 13:03:57 +02:00
|
|
|
loginReq := &proto.LoginRequest{}
|
2023-03-03 18:35:38 +01:00
|
|
|
peerKey, err := s.parseRequest(req, loginReq)
|
2022-05-23 13:03:57 +02:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
return nil, err
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
2022-06-23 17:04:53 +02:00
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
if loginReq.GetMeta() == nil {
|
|
|
|
msg := status.Errorf(codes.FailedPrecondition,
|
|
|
|
"peer system meta has to be provided to log in. Peer %s, remote addr %s", peerKey.String(),
|
|
|
|
p.Addr.String())
|
|
|
|
log.Warn(msg)
|
|
|
|
return nil, msg
|
2023-02-13 12:21:02 +01:00
|
|
|
}
|
2023-02-27 16:44:26 +01:00
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
userID := ""
|
|
|
|
// JWT token is not always provided, it is fine for userID to be empty cuz it might be that peer is already registered,
|
|
|
|
// or it uses a setup key to register.
|
|
|
|
if loginReq.GetJwtToken() != "" {
|
|
|
|
userID, err = s.validateToken(loginReq.GetJwtToken())
|
2023-02-13 12:21:02 +01:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
log.Warnf("failed validating JWT token sent from peer %s", peerKey)
|
|
|
|
return nil, mapError(err)
|
2023-02-13 12:21:02 +01:00
|
|
|
}
|
|
|
|
}
|
2022-06-23 17:04:53 +02:00
|
|
|
var sshKey []byte
|
|
|
|
if loginReq.GetPeerKeys() != nil {
|
|
|
|
sshKey = loginReq.GetPeerKeys().GetSshPubKey()
|
|
|
|
}
|
|
|
|
|
2023-03-03 18:35:38 +01:00
|
|
|
peer, netMap, err := s.accountManager.LoginPeer(PeerLogin{
|
|
|
|
WireGuardPubKey: peerKey.String(),
|
|
|
|
SSHKey: string(sshKey),
|
|
|
|
Meta: extractPeerMeta(loginReq),
|
|
|
|
UserID: userID,
|
|
|
|
SetupKey: loginReq.GetSetupKey(),
|
|
|
|
})
|
2023-09-04 11:37:39 +02:00
|
|
|
|
2022-06-24 21:30:51 +02:00
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
log.Warnf("failed logging in peer %s", peerKey)
|
|
|
|
return nil, mapError(err)
|
2022-06-24 21:30:51 +02:00
|
|
|
}
|
|
|
|
|
2023-09-04 11:37:39 +02:00
|
|
|
// if the login request contains setup key then it is a registration request
|
|
|
|
if loginReq.GetSetupKey() != "" {
|
|
|
|
s.ephemeralManager.OnPeerDisconnected(peer)
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// if peer has reached this point then it has logged in
|
|
|
|
loginResp := &proto.LoginResponse{
|
2021-09-02 14:41:54 +02:00
|
|
|
WiretrusteeConfig: toWiretrusteeConfig(s.config, nil),
|
2023-03-03 18:35:38 +01:00
|
|
|
PeerConfig: toPeerConfig(peer, netMap.Network, s.accountManager.GetDNSDomain()),
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
encryptedResp, err := encryption.EncryptMessage(peerKey, s.wgKey, loginResp)
|
|
|
|
if err != nil {
|
2023-03-03 18:35:38 +01:00
|
|
|
log.Warnf("failed encrypting peer %s message", peer.ID)
|
2021-08-15 16:56:26 +02:00
|
|
|
return nil, status.Errorf(codes.Internal, "failed logging in peer")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &proto.EncryptedMessage{
|
|
|
|
WgPubKey: s.wgKey.PublicKey().String(),
|
|
|
|
Body: encryptedResp,
|
|
|
|
}, nil
|
2021-07-17 14:38:59 +02:00
|
|
|
}
|
|
|
|
|
2021-09-02 14:41:54 +02:00
|
|
|
func ToResponseProto(configProto Protocol) proto.HostConfig_Protocol {
|
2021-07-30 17:46:38 +02:00
|
|
|
switch configProto {
|
2021-08-16 23:30:51 +02:00
|
|
|
case UDP:
|
2021-07-30 17:46:38 +02:00
|
|
|
return proto.HostConfig_UDP
|
2021-08-16 23:30:51 +02:00
|
|
|
case DTLS:
|
2021-07-30 17:46:38 +02:00
|
|
|
return proto.HostConfig_DTLS
|
2021-08-16 23:30:51 +02:00
|
|
|
case HTTP:
|
2021-07-30 17:46:38 +02:00
|
|
|
return proto.HostConfig_HTTP
|
2021-08-16 23:30:51 +02:00
|
|
|
case HTTPS:
|
2021-07-30 17:46:38 +02:00
|
|
|
return proto.HostConfig_HTTPS
|
2021-08-16 23:30:51 +02:00
|
|
|
case TCP:
|
2021-07-30 17:46:38 +02:00
|
|
|
return proto.HostConfig_TCP
|
|
|
|
default:
|
|
|
|
panic(fmt.Errorf("unexpected config protocol type %v", configProto))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-02 14:41:54 +02:00
|
|
|
func toWiretrusteeConfig(config *Config, turnCredentials *TURNCredentials) *proto.WiretrusteeConfig {
|
2022-11-08 11:38:40 +01:00
|
|
|
if config == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2021-07-30 17:46:38 +02:00
|
|
|
var stuns []*proto.HostConfig
|
|
|
|
for _, stun := range config.Stuns {
|
|
|
|
stuns = append(stuns, &proto.HostConfig{
|
|
|
|
Uri: stun.URI,
|
2021-09-02 14:41:54 +02:00
|
|
|
Protocol: ToResponseProto(stun.Proto),
|
2021-07-30 17:46:38 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
var turns []*proto.ProtectedHostConfig
|
2021-09-02 14:41:54 +02:00
|
|
|
for _, turn := range config.TURNConfig.Turns {
|
|
|
|
var username string
|
|
|
|
var password string
|
|
|
|
if turnCredentials != nil {
|
|
|
|
username = turnCredentials.Username
|
|
|
|
password = turnCredentials.Password
|
|
|
|
} else {
|
|
|
|
username = turn.Username
|
2021-09-07 18:36:46 +02:00
|
|
|
password = turn.Password
|
2021-09-02 14:41:54 +02:00
|
|
|
}
|
2021-07-30 17:46:38 +02:00
|
|
|
turns = append(turns, &proto.ProtectedHostConfig{
|
|
|
|
HostConfig: &proto.HostConfig{
|
|
|
|
Uri: turn.URI,
|
2021-09-02 14:41:54 +02:00
|
|
|
Protocol: ToResponseProto(turn.Proto),
|
2021-07-30 17:46:38 +02:00
|
|
|
},
|
2021-09-02 14:41:54 +02:00
|
|
|
User: username,
|
|
|
|
Password: password,
|
2021-07-30 17:46:38 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
return &proto.WiretrusteeConfig{
|
2021-07-30 17:46:38 +02:00
|
|
|
Stuns: stuns,
|
|
|
|
Turns: turns,
|
|
|
|
Signal: &proto.HostConfig{
|
|
|
|
Uri: config.Signal.URI,
|
2021-09-02 14:41:54 +02:00
|
|
|
Protocol: ToResponseProto(config.Signal.Proto),
|
2021-07-30 17:46:38 +02:00
|
|
|
},
|
|
|
|
}
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
2021-07-30 17:46:38 +02:00
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
func toPeerConfig(peer *Peer, network *Network, dnsName string) *proto.PeerConfig {
|
2022-06-24 21:30:51 +02:00
|
|
|
netmask, _ := network.Net.Mask.Size()
|
2023-01-02 15:11:32 +01:00
|
|
|
fqdn := peer.FQDN(dnsName)
|
2021-08-15 16:56:26 +02:00
|
|
|
return &proto.PeerConfig{
|
2022-06-24 21:30:51 +02:00
|
|
|
Address: fmt.Sprintf("%s/%d", peer.IP.String(), netmask), // take it from the network
|
2022-06-23 17:04:53 +02:00
|
|
|
SshConfig: &proto.SSHConfig{SshEnabled: peer.SSHEnabled},
|
2022-11-26 13:29:50 +01:00
|
|
|
Fqdn: fqdn,
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
func toRemotePeerConfig(peers []*Peer, dnsName string) []*proto.RemotePeerConfig {
|
2021-09-07 18:36:46 +02:00
|
|
|
remotePeers := []*proto.RemotePeerConfig{}
|
2021-07-30 17:46:38 +02:00
|
|
|
for _, rPeer := range peers {
|
2023-01-02 15:11:32 +01:00
|
|
|
fqdn := rPeer.FQDN(dnsName)
|
2021-07-30 17:46:38 +02:00
|
|
|
remotePeers = append(remotePeers, &proto.RemotePeerConfig{
|
|
|
|
WgPubKey: rPeer.Key,
|
2022-06-04 19:41:01 +02:00
|
|
|
AllowedIps: []string{fmt.Sprintf(AllowedIPsFormat, rPeer.IP)},
|
2022-06-23 17:04:53 +02:00
|
|
|
SshConfig: &proto.SSHConfig{SshPubKey: []byte(rPeer.SSHKey)},
|
2022-11-26 13:29:50 +01:00
|
|
|
Fqdn: fqdn,
|
2021-07-30 17:46:38 +02:00
|
|
|
})
|
|
|
|
}
|
2021-09-07 18:36:46 +02:00
|
|
|
return remotePeers
|
|
|
|
}
|
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
func toSyncResponse(config *Config, peer *Peer, turnCredentials *TURNCredentials, networkMap *NetworkMap, dnsName string) *proto.SyncResponse {
|
2021-09-07 18:36:46 +02:00
|
|
|
wtConfig := toWiretrusteeConfig(config, turnCredentials)
|
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
pConfig := toPeerConfig(peer, networkMap.Network, dnsName)
|
2022-11-07 15:38:21 +01:00
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
remotePeers := toRemotePeerConfig(networkMap.Peers, dnsName)
|
2021-09-07 18:36:46 +02:00
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
routesUpdate := toProtocolRoutes(networkMap.Routes)
|
2021-09-07 18:36:46 +02:00
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
dnsUpdate := toProtocolDNSConfig(networkMap.DNSConfig)
|
2022-08-18 18:22:15 +02:00
|
|
|
|
2023-03-07 10:17:25 +01:00
|
|
|
offlinePeers := toRemotePeerConfig(networkMap.OfflinePeers, dnsName)
|
|
|
|
|
2023-05-29 16:00:18 +02:00
|
|
|
firewallRules := toProtocolFirewallRules(networkMap.FirewallRules)
|
|
|
|
|
2021-07-30 17:46:38 +02:00
|
|
|
return &proto.SyncResponse{
|
2021-09-07 18:36:46 +02:00
|
|
|
WiretrusteeConfig: wtConfig,
|
|
|
|
PeerConfig: pConfig,
|
|
|
|
RemotePeers: remotePeers,
|
|
|
|
RemotePeersIsEmpty: len(remotePeers) == 0,
|
2022-01-16 17:10:36 +01:00
|
|
|
NetworkMap: &proto.NetworkMap{
|
2023-05-31 19:04:38 +02:00
|
|
|
Serial: networkMap.Network.CurrentSerial(),
|
|
|
|
PeerConfig: pConfig,
|
|
|
|
RemotePeers: remotePeers,
|
|
|
|
OfflinePeers: offlinePeers,
|
|
|
|
RemotePeersIsEmpty: len(remotePeers) == 0,
|
|
|
|
Routes: routesUpdate,
|
|
|
|
DNSConfig: dnsUpdate,
|
|
|
|
FirewallRules: firewallRules,
|
|
|
|
FirewallRulesIsEmpty: len(firewallRules) == 0,
|
2022-01-16 17:10:36 +01:00
|
|
|
},
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-17 14:38:59 +02:00
|
|
|
// IsHealthy indicates whether the service is healthy
|
2022-07-29 20:37:09 +02:00
|
|
|
func (s *GRPCServer) IsHealthy(ctx context.Context, req *proto.Empty) (*proto.Empty, error) {
|
2021-07-17 14:38:59 +02:00
|
|
|
return &proto.Empty{}, nil
|
|
|
|
}
|
2021-07-22 10:28:00 +02:00
|
|
|
|
|
|
|
// sendInitialSync sends initial proto.SyncResponse to the peer requesting synchronization
|
2023-03-03 18:35:38 +01:00
|
|
|
func (s *GRPCServer) sendInitialSync(peerKey wgtypes.Key, peer *Peer, networkMap *NetworkMap, srv proto.ManagementService_SyncServer) error {
|
2021-09-02 14:41:54 +02:00
|
|
|
// make secret time based TURN credentials optional
|
|
|
|
var turnCredentials *TURNCredentials
|
|
|
|
if s.config.TURNConfig.TimeBasedCredentials {
|
|
|
|
creds := s.turnCredentialsManager.GenerateCredentials()
|
|
|
|
turnCredentials = &creds
|
|
|
|
} else {
|
|
|
|
turnCredentials = nil
|
|
|
|
}
|
2022-11-26 13:29:50 +01:00
|
|
|
plainResp := toSyncResponse(s.config, peer, turnCredentials, networkMap, s.accountManager.GetDNSDomain())
|
2021-07-22 10:28:00 +02:00
|
|
|
|
2021-07-22 15:23:24 +02:00
|
|
|
encryptedResp, err := encryption.EncryptMessage(peerKey, s.wgKey, plainResp)
|
2021-07-22 10:28:00 +02:00
|
|
|
if err != nil {
|
|
|
|
return status.Errorf(codes.Internal, "error handling request")
|
|
|
|
}
|
2021-09-02 14:41:54 +02:00
|
|
|
|
2021-07-22 15:23:24 +02:00
|
|
|
err = srv.Send(&proto.EncryptedMessage{
|
|
|
|
WgPubKey: s.wgKey.PublicKey().String(),
|
|
|
|
Body: encryptedResp,
|
|
|
|
})
|
2021-07-22 10:28:00 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed sending SyncResponse %v", err)
|
|
|
|
return status.Errorf(codes.Internal, "error handling request")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2022-05-08 11:04:57 +02:00
|
|
|
|
|
|
|
// GetDeviceAuthorizationFlow returns a device authorization flow information
|
|
|
|
// This is used for initiating an Oauth 2 device authorization grant flow
|
|
|
|
// which will be used by our clients to Login
|
2022-07-29 20:37:09 +02:00
|
|
|
func (s *GRPCServer) GetDeviceAuthorizationFlow(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error) {
|
2022-05-08 11:04:57 +02:00
|
|
|
peerKey, err := wgtypes.ParseKey(req.GetWgPubKey())
|
|
|
|
if err != nil {
|
|
|
|
errMSG := fmt.Sprintf("error while parsing peer's Wireguard public key %s on GetDeviceAuthorizationFlow request.", req.WgPubKey)
|
|
|
|
log.Warn(errMSG)
|
|
|
|
return nil, status.Error(codes.InvalidArgument, errMSG)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = encryption.DecryptMessage(peerKey, s.wgKey, req.Body, &proto.DeviceAuthorizationFlowRequest{})
|
|
|
|
if err != nil {
|
|
|
|
errMSG := fmt.Sprintf("error while decrypting peer's message with Wireguard public key %s.", req.WgPubKey)
|
|
|
|
log.Warn(errMSG)
|
|
|
|
return nil, status.Error(codes.InvalidArgument, errMSG)
|
|
|
|
}
|
|
|
|
|
2022-08-24 14:37:18 +02:00
|
|
|
if s.config.DeviceAuthorizationFlow == nil || s.config.DeviceAuthorizationFlow.Provider == string(NONE) {
|
2022-05-08 11:04:57 +02:00
|
|
|
return nil, status.Error(codes.NotFound, "no device authorization flow information available")
|
|
|
|
}
|
|
|
|
|
|
|
|
provider, ok := proto.DeviceAuthorizationFlowProvider_value[strings.ToUpper(s.config.DeviceAuthorizationFlow.Provider)]
|
|
|
|
if !ok {
|
|
|
|
return nil, status.Errorf(codes.InvalidArgument, "no provider found in the protocol for %s", s.config.DeviceAuthorizationFlow.Provider)
|
|
|
|
}
|
|
|
|
|
|
|
|
flowInfoResp := &proto.DeviceAuthorizationFlow{
|
|
|
|
Provider: proto.DeviceAuthorizationFlowProvider(provider),
|
|
|
|
ProviderConfig: &proto.ProviderConfig{
|
2022-08-23 15:46:12 +02:00
|
|
|
ClientID: s.config.DeviceAuthorizationFlow.ProviderConfig.ClientID,
|
|
|
|
ClientSecret: s.config.DeviceAuthorizationFlow.ProviderConfig.ClientSecret,
|
|
|
|
Domain: s.config.DeviceAuthorizationFlow.ProviderConfig.Domain,
|
|
|
|
Audience: s.config.DeviceAuthorizationFlow.ProviderConfig.Audience,
|
|
|
|
DeviceAuthEndpoint: s.config.DeviceAuthorizationFlow.ProviderConfig.DeviceAuthEndpoint,
|
|
|
|
TokenEndpoint: s.config.DeviceAuthorizationFlow.ProviderConfig.TokenEndpoint,
|
2023-04-05 17:46:34 +02:00
|
|
|
Scope: s.config.DeviceAuthorizationFlow.ProviderConfig.Scope,
|
|
|
|
UseIDToken: s.config.DeviceAuthorizationFlow.ProviderConfig.UseIDToken,
|
2022-05-08 11:04:57 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
encryptedResp, err := encryption.EncryptMessage(peerKey, s.wgKey, flowInfoResp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, status.Error(codes.Internal, "failed to encrypt no device authorization flow information")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &proto.EncryptedMessage{
|
|
|
|
WgPubKey: s.wgKey.PublicKey().String(),
|
|
|
|
Body: encryptedResp,
|
|
|
|
}, nil
|
|
|
|
}
|
2023-07-27 11:31:07 +02:00
|
|
|
|
|
|
|
// GetPKCEAuthorizationFlow returns a pkce authorization flow information
|
|
|
|
// This is used for initiating an Oauth 2 pkce authorization grant flow
|
|
|
|
// which will be used by our clients to Login
|
|
|
|
func (s *GRPCServer) GetPKCEAuthorizationFlow(_ context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error) {
|
|
|
|
peerKey, err := wgtypes.ParseKey(req.GetWgPubKey())
|
|
|
|
if err != nil {
|
|
|
|
errMSG := fmt.Sprintf("error while parsing peer's Wireguard public key %s on GetPKCEAuthorizationFlow request.", req.WgPubKey)
|
|
|
|
log.Warn(errMSG)
|
|
|
|
return nil, status.Error(codes.InvalidArgument, errMSG)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = encryption.DecryptMessage(peerKey, s.wgKey, req.Body, &proto.PKCEAuthorizationFlowRequest{})
|
|
|
|
if err != nil {
|
|
|
|
errMSG := fmt.Sprintf("error while decrypting peer's message with Wireguard public key %s.", req.WgPubKey)
|
|
|
|
log.Warn(errMSG)
|
|
|
|
return nil, status.Error(codes.InvalidArgument, errMSG)
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.config.PKCEAuthorizationFlow == nil {
|
|
|
|
return nil, status.Error(codes.NotFound, "no pkce authorization flow information available")
|
|
|
|
}
|
|
|
|
|
|
|
|
flowInfoResp := &proto.PKCEAuthorizationFlow{
|
|
|
|
ProviderConfig: &proto.ProviderConfig{
|
|
|
|
Audience: s.config.PKCEAuthorizationFlow.ProviderConfig.Audience,
|
|
|
|
ClientID: s.config.PKCEAuthorizationFlow.ProviderConfig.ClientID,
|
|
|
|
ClientSecret: s.config.PKCEAuthorizationFlow.ProviderConfig.ClientSecret,
|
|
|
|
TokenEndpoint: s.config.PKCEAuthorizationFlow.ProviderConfig.TokenEndpoint,
|
|
|
|
AuthorizationEndpoint: s.config.PKCEAuthorizationFlow.ProviderConfig.AuthorizationEndpoint,
|
|
|
|
Scope: s.config.PKCEAuthorizationFlow.ProviderConfig.Scope,
|
|
|
|
RedirectURLs: s.config.PKCEAuthorizationFlow.ProviderConfig.RedirectURLs,
|
|
|
|
UseIDToken: s.config.PKCEAuthorizationFlow.ProviderConfig.UseIDToken,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
encryptedResp, err := encryption.EncryptMessage(peerKey, s.wgKey, flowInfoResp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, status.Error(codes.Internal, "failed to encrypt no pkce authorization flow information")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &proto.EncryptedMessage{
|
|
|
|
WgPubKey: s.wgKey.PublicKey().String(),
|
|
|
|
Body: encryptedResp,
|
|
|
|
}, nil
|
|
|
|
}
|