Enforce permissions on websocket connections

This commit is contained in:
Shadowghost 2023-06-09 17:11:22 +02:00
parent 46a6755e65
commit 05d98fe24c
7 changed files with 58 additions and 26 deletions

View File

@ -12,6 +12,7 @@ using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Net.WebSocketMessages; using MediaBrowser.Controller.Net.WebSocketMessages;
using MediaBrowser.Controller.Net.WebSocketMessages.Outbound; using MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
using MediaBrowser.Model.Session; using MediaBrowser.Model.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.HttpServer namespace Emby.Server.Implementations.HttpServer
@ -43,14 +44,17 @@ namespace Emby.Server.Implementations.HttpServer
/// </summary> /// </summary>
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="socket">The socket.</param> /// <param name="socket">The socket.</param>
/// <param name="authorizationInfo">The authorization information.</param>
/// <param name="remoteEndPoint">The remote end point.</param> /// <param name="remoteEndPoint">The remote end point.</param>
public WebSocketConnection( public WebSocketConnection(
ILogger<WebSocketConnection> logger, ILogger<WebSocketConnection> logger,
WebSocket socket, WebSocket socket,
AuthorizationInfo authorizationInfo,
IPAddress? remoteEndPoint) IPAddress? remoteEndPoint)
{ {
_logger = logger; _logger = logger;
_socket = socket; _socket = socket;
AuthorizationInfo = authorizationInfo;
RemoteEndPoint = remoteEndPoint; RemoteEndPoint = remoteEndPoint;
_jsonOptions = JsonDefaults.Options; _jsonOptions = JsonDefaults.Options;
@ -60,30 +64,22 @@ namespace Emby.Server.Implementations.HttpServer
/// <inheritdoc /> /// <inheritdoc />
public event EventHandler<EventArgs>? Closed; public event EventHandler<EventArgs>? Closed;
/// <summary> /// <inheritdoc />
/// Gets the remote end point. public AuthorizationInfo AuthorizationInfo { get; }
/// </summary>
/// <inheritdoc />
public IPAddress? RemoteEndPoint { get; } public IPAddress? RemoteEndPoint { get; }
/// <summary> /// <inheritdoc />
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; } public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
/// <summary> /// <inheritdoc />
/// Gets the last activity date.
/// </summary>
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; } public DateTime LastActivityDate { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public DateTime LastKeepAliveDate { get; set; } public DateTime LastKeepAliveDate { get; set; }
/// <summary> /// <inheritdoc />
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State => _socket.State; public WebSocketState State => _socket.State;
/// <inheritdoc /> /// <inheritdoc />
@ -101,7 +97,7 @@ namespace Emby.Server.Implementations.HttpServer
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task ProcessAsync(CancellationToken cancellationToken = default) public async Task ReceiveAsync(CancellationToken cancellationToken = default)
{ {
var pipe = new Pipe(); var pipe = new Pipe();
var writer = pipe.Writer; var writer = pipe.Writer;

View File

@ -51,6 +51,7 @@ namespace Emby.Server.Implementations.HttpServer
using var connection = new WebSocketConnection( using var connection = new WebSocketConnection(
_loggerFactory.CreateLogger<WebSocketConnection>(), _loggerFactory.CreateLogger<WebSocketConnection>(),
webSocket, webSocket,
authorizationInfo,
context.GetNormalizedRemoteIP()) context.GetNormalizedRemoteIP())
{ {
OnReceive = ProcessWebSocketMessageReceived OnReceive = ProcessWebSocketMessageReceived
@ -64,7 +65,7 @@ namespace Emby.Server.Implementations.HttpServer
await Task.WhenAll(tasks).ConfigureAwait(false); await Task.WhenAll(tasks).ConfigureAwait(false);
await connection.ProcessAsync().ConfigureAwait(false); await connection.ReceiveAsync().ConfigureAwait(false);
_logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress); _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
} }
catch (Exception ex) // Otherwise ASP.Net will ignore the exception catch (Exception ex) // Otherwise ASP.Net will ignore the exception

View File

@ -1,6 +1,8 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using Jellyfin.Data.Events; using Jellyfin.Data.Events;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Activity; using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Session; using MediaBrowser.Model.Session;
@ -9,7 +11,7 @@ using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.WebSocketListeners; namespace Jellyfin.Api.WebSocketListeners;
/// <summary> /// <summary>
/// Class SessionInfoWebSocketListener. /// Class ActivityLogWebSocketListener.
/// </summary> /// </summary>
public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState> public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState>
{ {
@ -56,6 +58,16 @@ public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<Activi
base.Dispose(dispose); base.Dispose(dispose);
} }
private new void Start(WebSocketMessageInfo message)
{
if (!message.Connection.AuthorizationInfo.User.HasPermission(PermissionKind.IsAdministrator))
{
throw new AuthenticationException("Only admin users can retrieve the activity log.");
}
base.Start(message);
}
private async void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) private async void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e)
{ {
await SendData(true).ConfigureAwait(false); await SendData(true).ConfigureAwait(false);

View File

@ -1,5 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Session;
@ -66,6 +68,16 @@ public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnume
base.Dispose(dispose); base.Dispose(dispose);
} }
private new void Start(WebSocketMessageInfo message)
{
if (!message.Connection.AuthorizationInfo.User.HasPermission(PermissionKind.IsAdministrator))
{
throw new AuthenticationException("Only admin users can subscribe to session information.");
}
base.Start(message);
}
private async void OnSessionManagerSessionActivity(object? sender, SessionEventArgs e) private async void OnSessionManagerSessionActivity(object? sender, SessionEventArgs e)
{ {
await SendData(false).ConfigureAwait(false); await SendData(false).ConfigureAwait(false);

View File

@ -96,7 +96,7 @@ namespace MediaBrowser.Controller.Net
/// Starts sending messages over a web socket. /// Starts sending messages over a web socket.
/// </summary> /// </summary>
/// <param name="message">The message.</param> /// <param name="message">The message.</param>
private void Start(WebSocketMessageInfo message) protected void Start(WebSocketMessageInfo message)
{ {
var vals = message.Data.Split(','); var vals = message.Data.Split(',');

View File

@ -1,5 +1,3 @@
#pragma warning disable CS1591
using System; using System;
using System.Net; using System.Net;
using System.Net.WebSockets; using System.Net.WebSockets;
@ -9,6 +7,9 @@ using MediaBrowser.Controller.Net.WebSocketMessages;
namespace MediaBrowser.Controller.Net namespace MediaBrowser.Controller.Net
{ {
/// <summary>
/// Interface for WebSocket connections.
/// </summary>
public interface IWebSocketConnection : IAsyncDisposable, IDisposable public interface IWebSocketConnection : IAsyncDisposable, IDisposable
{ {
/// <summary> /// <summary>
@ -40,6 +41,11 @@ namespace MediaBrowser.Controller.Net
/// <value>The state.</value> /// <value>The state.</value>
WebSocketState State { get; } WebSocketState State { get; }
/// <summary>
/// Gets the authorization information.
/// </summary>
public AuthorizationInfo AuthorizationInfo { get; }
/// <summary> /// <summary>
/// Gets the remote end point. /// Gets the remote end point.
/// </summary> /// </summary>
@ -65,6 +71,11 @@ namespace MediaBrowser.Controller.Net
/// <exception cref="ArgumentNullException">The message is null.</exception> /// <exception cref="ArgumentNullException">The message is null.</exception>
Task SendAsync<T>(OutboundWebSocketMessage<T> message, CancellationToken cancellationToken); Task SendAsync<T>(OutboundWebSocketMessage<T> message, CancellationToken cancellationToken);
Task ProcessAsync(CancellationToken cancellationToken = default); /// <summary>
/// Receives a message asynchronously.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task ReceiveAsync(CancellationToken cancellationToken = default);
} }
} }

View File

@ -13,7 +13,7 @@ namespace Jellyfin.Server.Implementations.Tests.HttpServer
[Fact] [Fact]
public void DeserializeWebSocketMessage_SingleSegment_Success() public void DeserializeWebSocketMessage_SingleSegment_Success()
{ {
var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!); var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json"); var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json");
con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed); con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed);
Assert.Equal(109, bytesConsumed); Assert.Equal(109, bytesConsumed);
@ -23,7 +23,7 @@ namespace Jellyfin.Server.Implementations.Tests.HttpServer
public void DeserializeWebSocketMessage_MultipleSegments_Success() public void DeserializeWebSocketMessage_MultipleSegments_Success()
{ {
const int SplitPos = 64; const int SplitPos = 64;
var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!); var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json"); var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json");
var seg1 = new BufferSegment(new Memory<byte>(bytes, 0, SplitPos)); var seg1 = new BufferSegment(new Memory<byte>(bytes, 0, SplitPos));
var seg2 = seg1.Append(new Memory<byte>(bytes, SplitPos, bytes.Length - SplitPos)); var seg2 = seg1.Append(new Memory<byte>(bytes, SplitPos, bytes.Length - SplitPos));
@ -34,7 +34,7 @@ namespace Jellyfin.Server.Implementations.Tests.HttpServer
[Fact] [Fact]
public void DeserializeWebSocketMessage_ValidPartial_Success() public void DeserializeWebSocketMessage_ValidPartial_Success()
{ {
var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!); var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
var bytes = File.ReadAllBytes("Test Data/HttpServer/ValidPartial.json"); var bytes = File.ReadAllBytes("Test Data/HttpServer/ValidPartial.json");
con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed); con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed);
Assert.Equal(109, bytesConsumed); Assert.Equal(109, bytesConsumed);
@ -43,7 +43,7 @@ namespace Jellyfin.Server.Implementations.Tests.HttpServer
[Fact] [Fact]
public void DeserializeWebSocketMessage_Partial_ThrowJsonException() public void DeserializeWebSocketMessage_Partial_ThrowJsonException()
{ {
var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!); var con = new WebSocketConnection(new NullLogger<WebSocketConnection>(), null!, null!, null!);
var bytes = File.ReadAllBytes("Test Data/HttpServer/Partial.json"); var bytes = File.ReadAllBytes("Test Data/HttpServer/Partial.json");
Assert.Throws<JsonException>(() => con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed)); Assert.Throws<JsonException>(() => con.DeserializeWebSocketMessage(new ReadOnlySequence<byte>(bytes), out var bytesConsumed));
} }