Exemplo n.º 1
0
        /// <summary>
        /// Gets the public available Users information
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetPublicUsers request)
        {
            var result = _userManager
                         .Users
                         .Where(item => !item.Policy.IsDisabled);

            if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
            {
                var deviceId = _authContext.GetAuthorizationInfo(Request).DeviceId;
                result = result.Where(item => !item.Policy.IsHidden);

                if (!string.IsNullOrWhiteSpace(deviceId))
                {
                    result = result.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
                }

                if (!_networkManager.IsInLocalNetwork(Request.RemoteIp))
                {
                    result = result.Where(i => i.Policy.EnableRemoteAccess);
                }
            }

            return(ToOptimizedResult(result
                                     .OrderBy(u => u.Name)
                                     .Select(i => _userManager.GetPublicUserDto(i, Request.RemoteIp))
                                     .ToArray()
                                     ));
        }
Exemplo n.º 2
0
        private bool ValidateRequest(string remoteIp, bool isLocal)
        {
            if (isLocal)
            {
                return(true);
            }

            if (_config.Configuration.EnableRemoteAccess)
            {
                var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();

                if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
                {
                    if (_config.Configuration.IsRemoteIPFilterBlacklist)
                    {
                        return(!_networkManager.IsAddressInSubnets(remoteIp, addressFilter));
                    }
                    else
                    {
                        return(_networkManager.IsAddressInSubnets(remoteIp, addressFilter));
                    }
                }
            }
            else
            {
                if (!_networkManager.IsInLocalNetwork(remoteIp))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 3
0
        public async Task <ActionResult <ForgotPasswordResult> > ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
        {
            var isLocal = HttpContext.IsLocal() ||
                          _networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp());

            var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 4
0
        public async Task <ActionResult <ForgotPasswordResult> > ForgotPassword([FromBody] string?enteredUsername)
        {
            var isLocal = HttpContext.Connection.RemoteIpAddress.Equals(HttpContext.Connection.LocalIpAddress) ||
                          _networkManager.IsInLocalNetwork(HttpContext.Connection.RemoteIpAddress.ToString());

            var result = await _userManager.StartForgotPasswordProcess(enteredUsername, isLocal).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 5
0
        private bool ValidateRequest(string remoteIp, bool isLocal)
        {
            if (isLocal)
            {
                return(true);
            }

            if (_config.Configuration.EnableRemoteAccess)
            {
                return(true);
            }

            return(_networkManager.IsInLocalNetwork(remoteIp));
        }
Exemplo n.º 6
0
        public async Task <ActionResult <ForgotPasswordResult> > ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
        {
            var ip      = HttpContext.GetNormalizedRemoteIp();
            var isLocal = HttpContext.IsLocal() ||
                          _networkManager.IsInLocalNetwork(ip);

            if (isLocal)
            {
                _logger.LogWarning("Password reset proccess initiated from outside the local network with IP: {IP}", ip);
            }

            var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 7
0
        public async Task <bool> AuthenticateUser(string username, string password, string remoteEndPoint)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username");
            }

            var user = Users.First(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));

            if (user.Configuration.IsDisabled)
            {
                throw new AuthenticationException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
            }

            var success = string.Equals(GetPasswordHash(user), password.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);

            if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
            {
                success = string.Equals(GetLocalPasswordHash(user), password.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
            }

            // Update LastActivityDate and LastLoginDate, then save
            if (success)
            {
                user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
                await UpdateUser(user).ConfigureAwait(false);
            }

            _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));

            return(success);
        }
Exemplo n.º 8
0
        private void ValidateUserAccess(
            User user,
            IRequest request,
            IAuthenticationAttributes authAttribtues,
            AuthorizationInfo auth)
        {
            if (user.Policy.IsDisabled)
            {
                throw new SecurityException("User account has been disabled.")
                      {
                          SecurityExceptionType = SecurityExceptionType.Unauthenticated
                      };
            }

            if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(request.RemoteIp))
            {
                throw new SecurityException("User account has been disabled.")
                      {
                          SecurityExceptionType = SecurityExceptionType.Unauthenticated
                      };
            }

            if (!user.Policy.IsAdministrator &&
                !authAttribtues.EscapeParentalControl &&
                !user.IsParentalScheduleAllowed())
            {
                request.Response.Headers.Add("X-Application-Error-Code", "ParentalControl");

                throw new SecurityException("This user account is not allowed access at this time.")
                      {
                          SecurityExceptionType = SecurityExceptionType.ParentalControl
                      };
            }
        }
Exemplo n.º 9
0
        private bool AuthenticateLocalUser(User user, string password, string hashedPassword, string remoteEndPoint)
        {
            bool success;

            if (password == null)
            {
                // legacy
                success = string.Equals(GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                success = string.Equals(GetPasswordHash(user), GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
            }

            if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
            {
                if (password == null)
                {
                    // legacy
                    success = string.Equals(GetLocalPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    success = string.Equals(GetLocalPasswordHash(user), GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
                }
            }

            return(success);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Validate authenticated claims.
        /// </summary>
        /// <param name="claimsPrincipal">Request claims.</param>
        /// <param name="ignoreSchedule">Whether to ignore parental control.</param>
        /// <param name="localAccessOnly">Whether access is to be allowed locally only.</param>
        /// <param name="requiredDownloadPermission">Whether validation requires download permission.</param>
        /// <returns>Validated claim status.</returns>
        protected bool ValidateClaims(
            ClaimsPrincipal claimsPrincipal,
            bool ignoreSchedule             = false,
            bool localAccessOnly            = false,
            bool requiredDownloadPermission = false)
        {
            // Ensure claim has userId.
            var userId = ClaimHelpers.GetUserId(claimsPrincipal);

            if (!userId.HasValue)
            {
                return(false);
            }

            // Ensure userId links to a valid user.
            var user = _userManager.GetUserById(userId.Value);

            if (user == null)
            {
                return(false);
            }

            // Ensure user is not disabled.
            if (user.HasPermission(PermissionKind.IsDisabled))
            {
                return(false);
            }

            var ip = _httpContextAccessor.HttpContext.GetNormalizedRemoteIp();
            var isInLocalNetwork = _networkManager.IsInLocalNetwork(ip);

            // User cannot access remotely and user is remote
            if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !isInLocalNetwork)
            {
                return(false);
            }

            if (localAccessOnly && !isInLocalNetwork)
            {
                return(false);
            }

            // User attempting to access out of parental control hours.
            if (!ignoreSchedule &&
                !user.HasPermission(PermissionKind.IsAdministrator) &&
                !user.IsParentalScheduleAllowed())
            {
                return(false);
            }

            // User attempting to download without permission.
            if (requiredDownloadPermission &&
                !user.HasPermission(PermissionKind.EnableContentDownloading))
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 11
0
 public object Get(GetEndpointInfo request)
 {
     return(ToOptimizedResult(new EndPointInfo
     {
         IsLocal = Request.IsLocal,
         IsInNetwork = _network.IsInLocalNetwork(request.Endpoint ?? Request.RemoteIp)
     }));
 }
Exemplo n.º 12
0
 public ActionResult <EndPointInfo> GetEndpointInfo()
 {
     return(new EndPointInfo
     {
         IsLocal = HttpContext.IsLocal(),
         IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())
     });
 }
Exemplo n.º 13
0
 public ActionResult <EndPointInfo> GetEndpointInfo()
 {
     return(new EndPointInfo
     {
         IsLocal = Request.HttpContext.Connection.LocalIpAddress.Equals(Request.HttpContext.Connection.RemoteIpAddress),
         IsInNetwork = _network.IsInLocalNetwork(Request.HttpContext.Connection.RemoteIpAddress.ToString())
     });
 }
        private object Get(GetUsers request, bool filterByDevice, bool filterByNetwork)
        {
            var users = _userManager.Users;

            if (request.IsDisabled.HasValue)
            {
                users = users.Where(i => i.Policy.IsDisabled == request.IsDisabled.Value);
            }

            if (request.IsHidden.HasValue)
            {
                users = users.Where(i => i.Policy.IsHidden == request.IsHidden.Value);
            }

            if (request.IsGuest.HasValue)
            {
                users = users.Where(i => (i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest) == request.IsGuest.Value);
            }

            if (filterByDevice)
            {
                var deviceId = _authContext.GetAuthorizationInfo(Request).DeviceId;

                if (!string.IsNullOrWhiteSpace(deviceId))
                {
                    users = users.Where(i => _deviceManager.CanAccessDevice(i, deviceId));
                }
            }

            if (filterByNetwork)
            {
                if (!_networkManager.IsInLocalNetwork(Request.RemoteIp))
                {
                    users = users.Where(i => i.Policy.EnableRemoteAccess);
                }
            }

            var result = users
                         .OrderBy(u => u.Name)
                         .Select(i => _userManager.GetUserDto(i, Request.RemoteIp))
                         .ToArray();

            return(ToOptimizedResult(result));
        }
        /// <summary>
        /// Executes the middleware action.
        /// </summary>
        /// <param name="httpContext">The current HTTP context.</param>
        /// <param name="networkManager">The network manager.</param>
        /// <param name="serverConfigurationManager">The server configuration manager.</param>
        /// <returns>The async task.</returns>
        public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
        {
            if (httpContext.IsLocal())
            {
                // Running locally.
                await _next(httpContext).ConfigureAwait(false);

                return;
            }

            var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;

            if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
            {
                // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
                // If left blank, all remote addresses will be allowed.
                var remoteAddressFilter = networkManager.RemoteAddressFilter;

                if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp))
                {
                    // remoteAddressFilter is a whitelist or blacklist.
                    bool isListed = remoteAddressFilter.ContainsAddress(remoteIp);
                    if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist)
                    {
                        // Black list, so flip over.
                        isListed = !isListed;
                    }

                    if (!isListed)
                    {
                        // If your name isn't on the list, you arn't coming in.
                        return;
                    }
                }
            }
            else if (!networkManager.IsInLocalNetwork(remoteIp))
            {
                // Remote not enabled. So everyone should be LAN.
                return;
            }

            await _next(httpContext).ConfigureAwait(false);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Executes the middleware action.
        /// </summary>
        /// <param name="httpContext">The current HTTP context.</param>
        /// <param name="networkManager">The network manager.</param>
        /// <param name="serverConfigurationManager">The server configuration manager.</param>
        /// <returns>The async task.</returns>
        public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
        {
            if (httpContext.Request.IsLocal())
            {
                await _next(httpContext).ConfigureAwait(false);

                return;
            }

            var remoteIp = httpContext.Request.RemoteIp();

            if (serverConfigurationManager.Configuration.EnableRemoteAccess)
            {
                var addressFilter = serverConfigurationManager.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();

                if (addressFilter.Length > 0 && !networkManager.IsInLocalNetwork(remoteIp))
                {
                    if (serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist)
                    {
                        if (networkManager.IsAddressInSubnets(remoteIp, addressFilter))
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (!networkManager.IsAddressInSubnets(remoteIp, addressFilter))
                        {
                            return;
                        }
                    }
                }
            }
            else
            {
                if (!networkManager.IsInLocalNetwork(remoteIp))
                {
                    return;
                }
            }

            await _next(httpContext).ConfigureAwait(false);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Executes the middleware action.
        /// </summary>
        /// <param name="httpContext">The current HTTP context.</param>
        /// <param name="networkManager">The network manager.</param>
        /// <param name="serverConfigurationManager">The server configuration manager.</param>
        /// <returns>The async task.</returns>
        public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
        {
            var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;

            if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
            {
                return;
            }

            await _next(httpContext).ConfigureAwait(false);
        }
Exemplo n.º 18
0
        private int?GetMaxBitrate(int?clientMaxBitrate)
        {
            var maxBitrate = clientMaxBitrate;

            if (_config.Configuration.RemoteClientBitrateLimit > 0 && !_networkManager.IsInLocalNetwork(Request.RemoteIp))
            {
                maxBitrate = Math.Min(maxBitrate ?? _config.Configuration.RemoteClientBitrateLimit, _config.Configuration.RemoteClientBitrateLimit);
            }

            return(maxBitrate);
        }
Exemplo n.º 19
0
        public async Task <bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username");
            }

            var user = Users
                       .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                throw new SecurityException("Invalid username or password entered.");
            }

            if (user.Policy.IsDisabled)
            {
                throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
            }

            var success = false;

            // Authenticate using local credentials if not a guest
            if (!user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest)
            {
                success = string.Equals(GetPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);

                if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
                {
                    success = string.Equals(GetLocalPasswordHash(user), passwordSha1.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
                }
            }

            // Update LastActivityDate and LastLoginDate, then save
            if (success)
            {
                user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
                await UpdateUser(user).ConfigureAwait(false);
                await UpdateInvalidLoginAttemptCount(user, 0).ConfigureAwait(false);
            }
            else
            {
                await UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1).ConfigureAwait(false);
            }

            _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));

            return(success);
        }
Exemplo n.º 20
0
        private bool ValidateSsl(string remoteIp, string urlString)
        {
            if (_config.Configuration.RequireHttps && _appHost.EnableHttps)
            {
                if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    if (!_networkManager.IsInLocalNetwork(remoteIp))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 21
0
        /// <inheritdoc />
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement)
        {
            var ip = _httpContextAccessor.HttpContext?.Connection.RemoteIpAddress;

            // Loopback will be on LAN, so we can accept null.
            if (ip == null || _networkManager.IsInLocalNetwork(ip))
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 22
0
        private long?GetMaxBitrate(long?clientMaxBitrate)
        {
            var maxBitrate             = clientMaxBitrate;
            var remoteClientMaxBitrate = _config.Configuration.RemoteClientBitrateLimit;

            if (remoteClientMaxBitrate > 0)
            {
                var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp);

                Logger.Info("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
                if (!isInLocalNetwork)
                {
                    maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
                }
            }

            return(maxBitrate);
        }
Exemplo n.º 23
0
        private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress)
        {
            // Within the local network this will likely do more harm than good.
            var ip = RequestHelpers.NormalizeIp(ipAddress).ToString();

            if (_networkManager.IsInLocalNetwork(ip))
            {
                return(false);
            }

            if (!enableAdaptiveBitrateStreaming)
            {
                return(false);
            }

            if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
            {
                // Opening live streams is so slow it's not even worth it
                return(false);
            }

            if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
            {
                return(false);
            }

            if (EncodingHelper.IsCopyCodec(state.OutputAudioCodec))
            {
                return(false);
            }

            if (!state.IsOutputVideo)
            {
                return(false);
            }

            // Having problems in android
            return(false);
            // return state.VideoRequest.VideoBitRate.HasValue;
        }
Exemplo n.º 24
0
        private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
        {
            // Within the local network this will likely do more harm than good.
            if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
            {
                return(false);
            }

            var request = state.Request as IMasterHlsRequest;

            if (request != null && !request.EnableAdaptiveBitrateStreaming)
            {
                return(false);
            }

            if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
            {
                // Opening live streams is so slow it's not even worth it
                return(false);
            }

            if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (!state.IsOutputVideo)
            {
                return(false);
            }

            // Having problems in android
            return(false);
            //return state.VideoRequest.VideoBitRate.HasValue;
        }
Exemplo n.º 25
0
        private long?GetMaxBitrate(long?clientMaxBitrate, User user)
        {
            var maxBitrate             = clientMaxBitrate;
            var remoteClientMaxBitrate = user?.RemoteClientBitrateLimit ?? 0;

            if (remoteClientMaxBitrate <= 0)
            {
                remoteClientMaxBitrate = _serverConfigurationManager.Configuration.RemoteClientBitrateLimit;
            }

            if (remoteClientMaxBitrate > 0)
            {
                var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.HttpContext.Connection.RemoteIpAddress.ToString());

                _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.HttpContext.Connection.RemoteIpAddress.ToString(), isInLocalNetwork);
                if (!isInLocalNetwork)
                {
                    maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
                }
            }

            return(maxBitrate);
        }
Exemplo n.º 26
0
        private long?GetMaxBitrate(long?clientMaxBitrate, User user)
        {
            var maxBitrate             = clientMaxBitrate;
            var remoteClientMaxBitrate = user?.Policy.RemoteClientBitrateLimit ?? 0;

            if (remoteClientMaxBitrate <= 0)
            {
                remoteClientMaxBitrate = ServerConfigurationManager.Configuration.RemoteClientBitrateLimit;
            }

            if (remoteClientMaxBitrate > 0)
            {
                var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp);

                Logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
                if (!isInLocalNetwork)
                {
                    maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
                }
            }

            return(maxBitrate);
        }
Exemplo n.º 27
0
        private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
        {
            // Within the local network this will likely do more harm than good.
            if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
            {
                return(false);
            }

            var request = state.Request as GetMasterHlsVideoStream;

            if (request != null && !request.EnableAdaptiveBitrateStreaming)
            {
                return(false);
            }

            if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
            {
                // Opening live streams is so slow it's not even worth it
                return(false);
            }

            return(state.VideoRequest.VideoBitRate.HasValue);
        }
Exemplo n.º 28
0
        private void ValidateUserAccess(
            User user,
            IRequest request,
            IAuthenticationAttributes authAttributes)
        {
            if (user.HasPermission(PermissionKind.IsDisabled))
            {
                throw new SecurityException("User account has been disabled.");
            }

            if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !_networkManager.IsInLocalNetwork(request.RemoteIp))
            {
                throw new SecurityException("User account has been disabled.");
            }

            if (!user.HasPermission(PermissionKind.IsAdministrator) &&
                !authAttributes.EscapeParentalControl &&
                !user.IsParentalScheduleAllowed())
            {
                request.Response.Headers.Add("X-Application-Error-Code", "ParentalControl");

                throw new SecurityException("This user account is not allowed access at this time.");
            }
        }
Exemplo n.º 29
0
        public async Task <User?> AuthenticateUser(
            string username,
            string password,
            string passwordSha1,
            string remoteEndPoint,
            bool isUserSession)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                _logger.LogInformation("Authentication request without username has been denied (IP: {IP}).", remoteEndPoint);
                throw new ArgumentNullException(nameof(username));
            }

            var  user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
            bool success;
            IAuthenticationProvider?authenticationProvider;

            if (user != null)
            {
                var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint)
                                 .ConfigureAwait(false);

                authenticationProvider = authResult.authenticationProvider;
                success = authResult.success;
            }
            else
            {
                var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint)
                                 .ConfigureAwait(false);

                authenticationProvider = authResult.authenticationProvider;
                string updatedUsername = authResult.username;
                success = authResult.success;

                if (success &&
                    authenticationProvider != null &&
                    !(authenticationProvider is DefaultAuthenticationProvider))
                {
                    // Trust the username returned by the authentication provider
                    username = updatedUsername;

                    // Search the database for the user again
                    // the authentication provider might have created it
                    user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));

                    if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
                    {
                        UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());

                        await UpdateUserAsync(user).ConfigureAwait(false);
                    }
                }
            }

            if (success && user != null && authenticationProvider != null)
            {
                var providerId = authenticationProvider.GetType().FullName;

                if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase))
                {
                    user.AuthenticationProviderId = providerId;
                    await UpdateUserAsync(user).ConfigureAwait(false);
                }
            }

            if (user == null)
            {
                _logger.LogInformation(
                    "Authentication request for {UserName} has been denied (IP: {IP}).",
                    username,
                    remoteEndPoint);
                throw new AuthenticationException("Invalid username or password entered.");
            }

            if (user.HasPermission(PermissionKind.IsDisabled))
            {
                _logger.LogInformation(
                    "Authentication request for {UserName} has been denied because this account is currently disabled (IP: {IP}).",
                    username,
                    remoteEndPoint);
                throw new SecurityException(
                          $"The {user.Username} account is currently disabled. Please consult with your administrator.");
            }

            if (!user.HasPermission(PermissionKind.EnableRemoteAccess) &&
                !_networkManager.IsInLocalNetwork(remoteEndPoint))
            {
                _logger.LogInformation(
                    "Authentication request for {UserName} forbidden: remote access disabled and user not in local network (IP: {IP}).",
                    username,
                    remoteEndPoint);
                throw new SecurityException("Forbidden.");
            }

            if (!user.IsParentalScheduleAllowed())
            {
                _logger.LogInformation(
                    "Authentication request for {UserName} is not allowed at this time due parental restrictions (IP: {IP}).",
                    username,
                    remoteEndPoint);
                throw new SecurityException("User is not allowed access at this time.");
            }

            // Update LastActivityDate and LastLoginDate, then save
            if (success)
            {
                if (isUserSession)
                {
                    user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
                }

                user.InvalidLoginAttemptCount = 0;
                await UpdateUserAsync(user).ConfigureAwait(false);

                _logger.LogInformation("Authentication request for {UserName} has succeeded.", user.Username);
            }
            else
            {
                await IncrementInvalidLoginAttemptCount(user).ConfigureAwait(false);

                _logger.LogInformation(
                    "Authentication request for {UserName} has been denied (IP: {IP}).",
                    user.Username,
                    remoteEndPoint);
            }

            return(success ? user : null);
        }
Exemplo n.º 30
0
        private void RegisterServerEndpoints()
        {
            var udn           = CreateUuid(_appHost.SystemId);
            var descriptorUri = "/dlna/" + udn + "/description.xml";

            var bindAddresses = NetworkManager.CreateCollection(
                _networkManager.GetInternalBindAddresses()
                .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)));

            if (bindAddresses.Count == 0)
            {
                // No interfaces returned, so use loopback.
                bindAddresses = _networkManager.GetLoopbacks();
            }

            foreach (IPNetAddress address in bindAddresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    // Not supporting IPv6 right now
                    continue;
                }

                // Limit to LAN addresses only
                if (!_networkManager.IsInLocalNetwork(address))
                {
                    continue;
                }

                var fullService = "urn:schemas-upnp-org:device:MediaServer:1";

                _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address);

                var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(false) + descriptorUri);

                var device = new SsdpRootDevice
                {
                    CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
                    Location      = uri.Uri,                    // Must point to the URL that serves your devices UPnP description document.
                    Address       = address.Address,
                    PrefixLength  = address.PrefixLength,
                    FriendlyName  = "Jellyfin",
                    Manufacturer  = "Jellyfin",
                    ModelName     = "Jellyfin Server",
                    Uuid          = udn
                                    // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
                };

                SetProperies(device, fullService);
                _publisher.AddDevice(device);

                var embeddedDevices = new[]
                {
                    "urn:schemas-upnp-org:service:ContentDirectory:1",
                    "urn:schemas-upnp-org:service:ConnectionManager:1",
                    // "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
                };

                foreach (var subDevice in embeddedDevices)
                {
                    var embeddedDevice = new SsdpEmbeddedDevice
                    {
                        FriendlyName = device.FriendlyName,
                        Manufacturer = device.Manufacturer,
                        ModelName    = device.ModelName,
                        Uuid         = udn
                                       // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
                    };

                    SetProperies(embeddedDevice, subDevice);
                    device.AddDevice(embeddedDevice);
                }
            }
        }