Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More backend admin panel functionality #148

Merged
merged 17 commits into from
Jan 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 6 additions & 65 deletions UT4MasterServer/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,6 @@ namespace UT4MasterServer.Controllers;
[Produces("application/json")]
public sealed class AccountController : JsonAPIController
{
private static readonly Regex regexEmail;
private static readonly List<string> disallowedUsernameWords;

static AccountController()
{
regexEmail = new Regex(@"^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])");
disallowedUsernameWords = new List<string>
{
"cock", "dick", "penis", "vagina", "tits", "pussy", "boner",
"shit", "fuck", "bitch", "slut", "sex", "cum",
"nigger", "hitler", "nazi"
};
}


private readonly SessionService sessionService;
private readonly AccountService accountService;
private readonly IOptions<ReCaptchaSettings> reCaptchaSettings;
Expand Down Expand Up @@ -244,7 +229,7 @@ public async Task<IActionResult> RegisterAccount([FromForm] string username, [Fr
return Conflict("Username already exists");
}

if (!ValidateUsername(username))
if (!ValidationHelper.ValidateUsername(username))
{
logger.LogInformation($"Entered an invalid username: {username}");
return Conflict("You have entered an invalid username");
Expand All @@ -258,13 +243,13 @@ public async Task<IActionResult> RegisterAccount([FromForm] string username, [Fr
return Conflict("Email already exists");
}

if (!ValidateEmail(email))
if (!ValidationHelper.ValidateEmail(email))
{
logger.LogInformation($"Entered an invalid email format: {email}");
return Conflict("You have entered an invalid email address");
}

if (!ValidatePassword(password))
if (!ValidationHelper.ValidatePassword(password))
{
logger.LogInformation($"Entered password was in invalid format");
return Conflict("Unexpected password format");
Expand All @@ -286,7 +271,7 @@ public async Task<IActionResult> UpdateUsername([FromForm] string newUsername)
return Unauthorized();
}

if (!ValidateUsername(newUsername))
if (!ValidationHelper.ValidateUsername(newUsername))
{
return ValidationProblem();
}
Expand Down Expand Up @@ -327,7 +312,7 @@ public async Task<IActionResult> UpdateEmail([FromForm] string newEmail)
}

newEmail = newEmail.ToLower();
if (!ValidateEmail(newEmail))
if (!ValidationHelper.ValidateEmail(newEmail))
{
return ValidationProblem();
}
Expand Down Expand Up @@ -363,7 +348,7 @@ public async Task<IActionResult> UpdatePassword([FromForm] string currentPasswor
}

// passwords should already be hashed, but check its length just in case
if (!ValidatePassword(newPassword))
if (!ValidationHelper.ValidatePassword(newPassword))
{
return BadRequest(new ErrorResponse()
{
Expand Down Expand Up @@ -400,48 +385,4 @@ public async Task<IActionResult> UpdatePassword([FromForm] string currentPasswor
}

#endregion

[NonAction]
private static bool ValidateEmail(string email)
{
if (email.Length < 6 || email.Length > 64)
return false;

return regexEmail.IsMatch(email);
}

[NonAction]
private static bool ValidateUsername(string username)
{
if (username.Length < 3 || username.Length > 32)
return false;

username = username.ToLower();

// try to prevent impersonation of authority
if (username == "admin" || username == "administrator" || username == "system")
return false;

// there's no way to prevent people from getting highly creative.
// we just try some minimal filtering for now...
foreach (var word in disallowedUsernameWords)
{
if (username.Contains(word))
return false;
}
return true;
}

[NonAction]
private static bool ValidatePassword(string password)
{
// we are expecting password to be SHA512 hash (64 bytes) in hex string form (128 chars)
if (password.Length != 128)
return false;

if (!password.IsHexString())
return false;

return true;
}
}
137 changes: 137 additions & 0 deletions UT4MasterServer/Controllers/AdminPanelController.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
using Microsoft.AspNetCore.Mvc;
using UT4MasterServer.Authentication;
using UT4MasterServer.Helpers;
using UT4MasterServer.Models;
using UT4MasterServer.Other;
using UT4MasterServer.Services;

namespace UT4MasterServer.Controllers;

[ApiController]
[Route("admin")]
[AuthorizeBearer]
public sealed class AdminPanelController : ControllerBase
{
private readonly ILogger<AdminPanelController> logger;
private readonly AccountService accountService;
private readonly SessionService sessionService;
private readonly CodeService codeService;
private readonly CloudStorageService cloudStorageService;
private readonly StatisticsService statisticsService;
private readonly ClientService clientService;
private readonly TrustedGameServerService trustedGameServerService;

public AdminPanelController(
ILogger<AdminPanelController> logger,
AccountService accountService,
SessionService sessionService,
CodeService codeService,
CloudStorageService cloudStorageService,
StatisticsService statisticsService,
ClientService clientService,
TrustedGameServerService trustedGameServerService)
{
this.logger = logger;
this.accountService = accountService;
this.sessionService = sessionService;
this.codeService = codeService;
this.cloudStorageService = cloudStorageService;
this.statisticsService = statisticsService;
this.clientService = clientService;
this.trustedGameServerService = trustedGameServerService;
}
Expand Down Expand Up @@ -206,13 +223,127 @@ public async Task<IActionResult> DeleteTrustedServer(string id)
return Ok(ret);
}

[HttpPatch("change_password/{id}")]
public async Task<IActionResult> ChangePassword(string id, [FromBody] string newPassword, [FromBody] bool? iAmSure)
belmirp marked this conversation as resolved.
Show resolved Hide resolved
{
await VerifyAdmin();

var account = await accountService.GetAccountAsync(EpicID.FromString(id));
if (account is null)
{
return NotFound(new ErrorResponse() { ErrorMessage = $"Failed to find account {id}" });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Braces.

}

if (account.Flags.HasFlag(AccountFlags.Moderator) || account.Flags.HasFlag(AccountFlags.Admin))
{
throw new UnauthorizedAccessException("Cannot change password of other admins or moderators");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Braces.

}

// passwords should already be hashed, but check its length just in case
if (!ValidationHelper.ValidatePassword(newPassword))
{
return BadRequest(new ErrorResponse()
{
ErrorMessage = $"newPassword is not a SHA512 hash"
});
}

if (iAmSure != true)
belmirp marked this conversation as resolved.
Show resolved Hide resolved
{
return BadRequest(new ErrorResponse()
{
ErrorMessage = $"'areYouSure' was not 'true'"
});
}

await accountService.UpdateAccountPasswordAsync(account, newPassword);

// logout user to make sure they remember they changed password by being forced to log in again,
// as well as prevent anyone else from using this account after successful password change.
await sessionService.RemoveSessionsWithFilterAsync(EpicID.Empty, account.ID, EpicID.Empty);

logger.LogInformation("Updated password for {AccountID}", account.ID);

return Ok();
}

[HttpGet("mcp_files")]
public async Task<IActionResult> GetMCPFiles()
{
await VerifyAdmin();
return Ok(await cloudStorageService.ListFilesAsync(EpicID.Empty));
}

[HttpPost("mcp_files/{filename}")]
[HttpPatch("mcp_files/{filename}")]
public async Task<IActionResult> UpdateMCPFile(string filename)
{
await VerifyAdmin();
await cloudStorageService.UpdateFileAsync(EpicID.Empty, filename, HttpContext.Request.BodyReader);
return Ok();
}

[HttpGet("mcp_files/{filename}")]
public async Task<IActionResult> GetMCPFile(string filename)
{
await VerifyAdmin();

var file = await cloudStorageService.GetFileAsync(EpicID.Empty, filename);
if (file is null)
{
return NotFound(new ErrorResponse() { ErrorMessage = "File not found" });
}

return new FileContentResult(file.RawContent, "application/octet-stream");
}

[HttpDelete("account/{id}")]
public async Task<IActionResult> DeleteAccountInfo(string id, [FromBody] bool? forceCheckBroken)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same security consideration as in ChangePassword.

{
var admin = await VerifyAdmin();

var accountID = EpicID.FromString(id);
var account = await accountService.GetAccountAsync(accountID);
if (account is null)
{
if (forceCheckBroken != true)
belmirp marked this conversation as resolved.
Show resolved Hide resolved
{
return NotFound(new ErrorResponse() { ErrorMessage = "Account not found" });
}
}
else
{
if (admin.Account.Flags.HasFlag(AccountFlags.Admin) && account.Flags.HasFlag(AccountFlags.Admin))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Braces.

{
throw new UnauthorizedAccessException("Cannot delete account of other admin");
}

if (admin.Account.Flags.HasFlag(AccountFlags.Moderator) &&
(account.Flags.HasFlag(AccountFlags.Admin) || account.Flags.HasFlag(AccountFlags.Moderator)))
{
throw new UnauthorizedAccessException("Cannot delete account of other admin or moderator");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Braces.

}

await accountService.RemoveAccountAsync(account.ID);
}

// remove all associated data
await sessionService.RemoveSessionsWithFilterAsync(EpicID.Empty, accountID, EpicID.Empty);
await codeService.RemoveCodesByAccountAsync(accountID);
await cloudStorageService.RemoveFilesByAccountAsync(accountID);
await statisticsService.RemoveStatisticsByAccountAsync(accountID);

return Ok();
}


[NonAction]
private bool IsSpecialClientID(EpicID id)
{
if (id == ClientIdentification.Game.ID || id == ClientIdentification.ServerInstance.ID || id == ClientIdentification.Launcher.ID)
{
return true;
}

return false;
}
Expand All @@ -221,14 +352,20 @@ private bool IsSpecialClientID(EpicID id)
private async Task<(Session Session, Account Account)> VerifyAdmin()
{
if (User.Identity is not EpicUserIdentity user)
{
throw new UnauthorizedAccessException("User not logged in");
}

var account = await accountService.GetAccountAsync(user.Session.AccountID);
if (account == null)
{
throw new UnauthorizedAccessException("User not found");
}

if (!account.Flags.HasFlag(AccountFlags.Admin) && !account.Flags.HasFlag(AccountFlags.Moderator))
{
throw new UnauthorizedAccessException("User has insufficient privileges");
}

return (user.Session, account);
}
Expand Down
14 changes: 0 additions & 14 deletions UT4MasterServer/Controllers/CloudStorageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,6 @@ public async Task<IActionResult> ListUserFiles(string id)
{
// list all files this user has in storage - any user can see files from another user

/* [
{"uniqueFilename":"user_progression_1",
"filename":"user_progression_1",
"hash":"32a17bdf348e653a5cc7f94c3afb404301502d43",
"hash256":"7dcfaac101dbba0337e1b51bf3c088e591742d5f1c299f10cc0c9da01eab5fe8",
"length":21,
"contentType":"text/plain",
"uploaded":"2020-05-24T07:10:43.198Z",
"storageType":"S3",
"accountId":"64bf8c6d81004e88823d577abe157373"
},
]
*/

var eid = EpicID.FromString(id);

var files = await cloudStorageService.ListFilesAsync(eid);
Expand Down
63 changes: 63 additions & 0 deletions UT4MasterServer/Helpers/ValidationHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;

namespace UT4MasterServer.Helpers;

public static class ValidationHelper
{
private static readonly Regex regexEmail;
private static readonly List<string> disallowedUsernameWords;

static ValidationHelper()
{
// regex from: https://www.emailregex.com/
regexEmail = new Regex(@"^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])");
disallowedUsernameWords = new List<string>
{
"cock", "dick", "penis", "vagina", "tits", "pussy", "boner",
"shit", "fuck", "bitch", "slut", "sex", "cum",
"nigger", "hitler", "nazi"
};
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove one empty line.

public static bool ValidateEmail(string email)
{
if (email.Length < 6 || email.Length > 64)
return false;

return regexEmail.IsMatch(email);
}

public static bool ValidateUsername(string username)
{
if (username.Length < 3 || username.Length > 32)
return false;

username = username.ToLower();

// try to prevent impersonation of authority
if (username == "admin" || username == "administrator" || username == "system")
return false;

// there's no way to prevent people from getting highly creative.
// we just try some minimal filtering for now...
foreach (var word in disallowedUsernameWords)
{
if (username.Contains(word))
return false;
}
return true;
}

public static bool ValidatePassword(string password)
{
// we are expecting password to be SHA512 hash (64 bytes) in hex string form (128 chars)
if (password.Length != 128)
return false;

if (!password.IsHexString())
return false;

return true;
}
}
Loading