From 7576824cee0dc0d8e1729ae0a7e8e4f256b71efd Mon Sep 17 00:00:00 2001 From: cvium Date: Thu, 10 Sep 2020 14:16:41 +0200 Subject: [PATCH] Standardize use of IsLocal and RemoteIp --- .../HttpServer/Security/SessionContext.cs | 2 +- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 3 +- .../Controllers/MediaInfoController.cs | 3 +- Jellyfin.Api/Controllers/SystemController.cs | 5 +- .../Controllers/UniversalAudioController.cs | 3 +- Jellyfin.Api/Controllers/UserController.cs | 21 +++++---- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 10 ++-- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 3 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 3 +- .../IpBasedAccessValidationMiddleware.cs | 4 +- .../Middleware/ResponseTimeMiddleware.cs | 3 +- .../Extensions/HttpContextExtensions.cs | 46 +++++-------------- 12 files changed, 45 insertions(+), 61 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index 8777c59b7b..86914dea20 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.HttpServer.Security var authorization = _authContext.GetAuthorizationInfo(requestContext); var user = authorization.User; - return _sessionManager.LogSessionActivity(authorization.Client, authorization.Version, authorization.DeviceId, authorization.Device, requestContext.Request.RemoteIp(), user); + return _sessionManager.LogSessionActivity(authorization.Client, authorization.Version, authorization.DeviceId, authorization.Device, requestContext.GetNormalizedRemoteIp(), user); } public SessionInfo GetSession(object requestContext) diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index aa366f5672..d732b6bc6a 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,6 +1,7 @@ using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; @@ -69,7 +70,7 @@ namespace Jellyfin.Api.Auth return false; } - var ip = RequestHelpers.NormalizeIp(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress).ToString(); + var ip = _httpContextAccessor.HttpContext.GetNormalizedRemoteIp(); var isInLocalNetwork = _networkManager.IsInLocalNetwork(ip); // User cannot access remotely and user is remote if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !isInLocalNetwork) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index cc6eba4ae7..f32bdb1617 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -8,6 +8,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.MediaInfoDtos; using Jellyfin.Api.Models.VideoDtos; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; @@ -164,7 +165,7 @@ namespace Jellyfin.Api.Controllers enableTranscoding, allowVideoStreamCopy, allowAudioStreamCopy, - Request.HttpContext.Connection.RemoteIpAddress.ToString()); + Request.HttpContext.GetNormalizedRemoteIp()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index bbfd163de5..34c7bb18d9 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Constants; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -176,8 +177,8 @@ namespace Jellyfin.Api.Controllers { return new EndPointInfo { - IsLocal = Request.HttpContext.Connection.LocalIpAddress.Equals(Request.HttpContext.Connection.RemoteIpAddress), - IsInNetwork = _network.IsInLocalNetwork(Request.HttpContext.Connection.RemoteIpAddress.ToString()) + IsLocal = HttpContext.IsLocal(), + IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()) }; } diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index f7f2d01748..e3e3166b00 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.StreamingDtos; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -158,7 +159,7 @@ namespace Jellyfin.Api.Controllers true, true, true, - Request.HttpContext.Connection.RemoteIpAddress.ToString()); + Request.HttpContext.GetNormalizedRemoteIp()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 95067bc177..85430e63f6 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -7,6 +7,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.UserDtos; using Jellyfin.Data.Enums; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Configuration; @@ -117,7 +118,7 @@ namespace Jellyfin.Api.Controllers return NotFound("User not found"); } - var result = _userManager.GetUserDto(user, HttpContext.Connection.RemoteIpAddress.ToString()); + var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp()); return result; } @@ -203,7 +204,7 @@ namespace Jellyfin.Api.Controllers DeviceName = auth.Device, Password = request.Pw, PasswordSha1 = request.Password, - RemoteEndPoint = HttpContext.Connection.RemoteIpAddress.ToString(), + RemoteEndPoint = HttpContext.GetNormalizedRemoteIp(), Username = request.Username }).ConfigureAwait(false); @@ -212,7 +213,7 @@ namespace Jellyfin.Api.Controllers catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.Connection.RemoteIpAddress}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); } } @@ -246,7 +247,7 @@ namespace Jellyfin.Api.Controllers catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.Connection.RemoteIpAddress}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); } } @@ -290,7 +291,7 @@ namespace Jellyfin.Api.Controllers user.Username, request.CurrentPw, request.CurrentPw, - HttpContext.Connection.RemoteIpAddress.ToString(), + HttpContext.GetNormalizedRemoteIp(), false).ConfigureAwait(false); if (success == null) @@ -496,7 +497,7 @@ namespace Jellyfin.Api.Controllers await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false); } - var result = _userManager.GetUserDto(newUser, HttpContext.Connection.RemoteIpAddress.ToString()); + var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp()); return result; } @@ -511,8 +512,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public async Task> ForgotPassword([FromBody] string? enteredUsername) { - var isLocal = HttpContext.Connection.RemoteIpAddress.Equals(HttpContext.Connection.LocalIpAddress) - || _networkManager.IsInLocalNetwork(HttpContext.Connection.RemoteIpAddress.ToString()); + var isLocal = HttpContext.IsLocal() + || _networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()); var result = await _userManager.StartForgotPasswordProcess(enteredUsername, isLocal).ConfigureAwait(false); @@ -559,7 +560,7 @@ namespace Jellyfin.Api.Controllers if (filterByNetwork) { - if (!_networkManager.IsInLocalNetwork(HttpContext.Connection.RemoteIpAddress.ToString())) + if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())) { users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess)); } @@ -567,7 +568,7 @@ namespace Jellyfin.Api.Controllers var result = users .OrderBy(u => u.Username) - .Select(i => _userManager.GetUserDto(i, HttpContext.Connection.RemoteIpAddress.ToString())); + .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp())); return result; } diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 6a8829d462..af0519ffa8 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -8,6 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -198,12 +199,12 @@ namespace Jellyfin.Api.Helpers if (!string.IsNullOrWhiteSpace(subtitleGroup)) { - AddSubtitles(state, subtitleStreams, builder, _httpContextAccessor.HttpContext.Request.HttpContext.User); + AddSubtitles(state, subtitleStreams, builder, _httpContextAccessor.HttpContext.User); } AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup); - if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.Request.HttpContext.Connection.RemoteIpAddress)) + if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp())) { var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0; @@ -334,11 +335,10 @@ namespace Jellyfin.Api.Helpers } } - private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress) + private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, string ipAddress) { // Within the local network this will likely do more harm than good. - var ip = RequestHelpers.NormalizeIp(ipAddress).ToString(); - if (_networkManager.IsInLocalNetwork(ip)) + if (_networkManager.IsInLocalNetwork(ipAddress)) { return false; } diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 3a736d1e8a..1207fb5134 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -498,7 +499,7 @@ namespace Jellyfin.Api.Helpers true, true, true, - httpRequest.HttpContext.Connection.RemoteIpAddress.ToString()); + httpRequest.HttpContext.GetNormalizedRemoteIp()); } else { diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index fbaa692700..d15b5603e6 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Net; using Jellyfin.Data.Enums; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Querying; @@ -119,7 +120,7 @@ namespace Jellyfin.Api.Helpers authorization.Version, authorization.DeviceId, authorization.Device, - request.HttpContext.Connection.RemoteIpAddress.ToString(), + request.HttpContext.GetNormalizedRemoteIp(), user); if (session == null) diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 59b5fb1ed2..4bda8f2737 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -32,13 +32,13 @@ namespace Jellyfin.Server.Middleware /// The async task. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) { - if (httpContext.Request.IsLocal()) + if (httpContext.IsLocal()) { await _next(httpContext).ConfigureAwait(false); return; } - var remoteIp = httpContext.Request.RemoteIp(); + var remoteIp = httpContext.GetNormalizedRemoteIp(); if (serverConfigurationManager.Configuration.EnableRemoteAccess) { diff --git a/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs index 3122d92cbc..74874da1b0 100644 --- a/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs +++ b/Jellyfin.Server/Middleware/ResponseTimeMiddleware.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; @@ -69,7 +70,7 @@ namespace Jellyfin.Server.Middleware _logger.LogWarning( "Slow HTTP Response from {url} to {remoteIp} in {elapsed:g} with Status Code {statusCode}", context.Request.GetDisplayUrl(), - context.Connection.RemoteIpAddress, + context.GetNormalizedRemoteIp(), watch.Elapsed, context.Response.StatusCode); } diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs index e0cf3f9ac3..8d29088825 100644 --- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs +++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs @@ -1,5 +1,3 @@ -using System.Net; -using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; namespace MediaBrowser.Common.Extensions @@ -10,54 +8,32 @@ namespace MediaBrowser.Common.Extensions public static class HttpContextExtensions { /// - /// Checks the origin of the HTTP request. + /// Checks the origin of the HTTP context. /// - /// The incoming HTTP request. + /// The incoming HTTP context. /// true if the request is coming from LAN, false otherwise. - public static bool IsLocal(this HttpRequest request) + public static bool IsLocal(this HttpContext context) { - return (request.HttpContext.Connection.LocalIpAddress == null - && request.HttpContext.Connection.RemoteIpAddress == null) - || request.HttpContext.Connection.LocalIpAddress.Equals(request.HttpContext.Connection.RemoteIpAddress); + return (context.Connection.LocalIpAddress == null + && context.Connection.RemoteIpAddress == null) + || context.Connection.LocalIpAddress.Equals(context.Connection.RemoteIpAddress); } /// - /// Extracts the remote IP address of the caller of the HTTP request. + /// Extracts the remote IP address of the caller of the HTTP context. /// - /// The HTTP request. + /// The HTTP context. /// The remote caller IP address. - public static string RemoteIp(this HttpRequest request) + public static string GetNormalizedRemoteIp(this HttpContext context) { - var cachedRemoteIp = request.HttpContext.Items["RemoteIp"]?.ToString(); - if (!string.IsNullOrEmpty(cachedRemoteIp)) - { - return cachedRemoteIp; - } - - IPAddress ip; - - // "Real" remote ip might be in X-Forwarded-For of X-Real-Ip - // (if the server is behind a reverse proxy for example) - if (!IPAddress.TryParse(request.Headers[CustomHeaderNames.XForwardedFor].ToString(), out ip)) - { - if (!IPAddress.TryParse(request.Headers[CustomHeaderNames.XRealIP].ToString(), out ip)) - { - ip = request.HttpContext.Connection.RemoteIpAddress; - - // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests) - ip ??= IPAddress.Loopback; - } - } + var ip = context.Connection.RemoteIpAddress; if (ip.IsIPv4MappedToIPv6) { ip = ip.MapToIPv4(); } - var normalizedIp = ip.ToString(); - - request.HttpContext.Items["RemoteIp"] = normalizedIp; - return normalizedIp; + return ip.ToString(); } } }