When theory meets practice for secure development
Presented By: Ivan Zlatanov
Prepared By: ICB's Internal Security Team
# ICB
"The practice of designing, building, and maintaining software with a focus on minimizing vulnerabilities and ensuring the software is resilient against attacks"
Secure Development Lifecycle (SDL) is a multi-stage process:
Growing Threats
New technology breeds new threat actors.
Threat actors are constantly advancing.
Misconceptions
"Security is somebody else's job."
"Nobody can find the IP."
"It is inside the local network, so it is safe."
Customer trust
Breaches that lead to data exposure undermine customers' trust in the capabilities of the organisation.
# ICB
Developers are the first line of defence.
# ICB
Open Worldwide Application Security Project
OWASP is:
# ICB
Web Application Vulnerabilities
The Top 10 list is:
# ICB
Broken Access Control
Example: A user accessing admin-only features by modifying a URL.
Mitigation: Implement role-based access control and test for privilege escalation vulnerabilities.
Occurs when users gain unauthorized access to resources or actions.
# ICB
Cross-Site Scripting (XSS)
Example: A comment box on a website accepts <script>alert('pwn!');</script>
as input and renders it directly to other users.
Mitigation: Always validate, sanitise, and escape user-supplied data. Implement appropriate Content Security Policy (CSP) to prevent execution.
Occurs when an attacker injects malicious scripts into web pages viewed by other users. These scripts execute in the victim’s browser.
Threat Actor
# ICB
Cross-Site Request Forgery (CSRF)
Example: A victim clicks a malicious link or loads a crafted image that submits a hidden form to transfer funds using their banking session.
Mitigation: Implement anti-CSRF tokens, require re-authentication for sensitive actions. Utilise SameSite
cookies.
CSRF tricks a victim into performing actions they did not intend by exploiting their authenticated session with a website.
# ICB
SQL Injection (SQLi)
Example: Entering 1' OR '1'='1 in a vulnerable search field manipulates the SQL query and returns all data.
Mitigation: Use parametrised queries, employ input validation, utilise a "Least Privileged" approach for your database.
SQLi exploits vulnerabilities in a web application’s database query mechanism, allowing attackers to execute arbitrary SQL commands
# ICB
Insecure Deserialisation
Example: An attacker sends a malicious serialised payload containing code to the server. When deserialized, the payload executes system commands, granting the attacker remote code execution (RCE) on the server.
Mitigation: Validate serialised data into predetermined objects. Validate data.
It happens when untrusted or manipulated serialized data is processed by an application, leading to code execution or other malicious actions.
# ICB
Improper Session Management
Example: An application does not invalidate a user’s session after logout, allowing an attacker with the session token to access user data.
Mitigation: Use secure, random session tokens, enforce HTTPS, and implement proper session timeout and invalidation mechanisms.
It occurs when an application does not securely handle session data, such as session IDs or cookies, making it easier for attackers to hijack active sessions or impersonate users.
# ICB
# ICB
What is the OWASP ASVS:
# ICB
Key features of the OWASP ASVS:
# ICB
[HttpPost]
public IActionResult ProcessData([FromBody] byte[] serializedData)
{
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream(serializedData))
{
// Deserializing user-provided data
var obj = formatter.Deserialize(ms);
ProcessObject(obj); // Perform some actions with the deserialized object
}
return Ok();
}
private void ProcessObject(object obj)
{
// Simulating processing
Console.WriteLine(obj.ToString());
}
# ICB
public class SafeBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
var allowedTypes = new[] { typeof(MySafeObject) };
var type = Type.GetType($"{typeName}, {assemblyName}");
if (type != null && allowedTypes.Contains(type))
{
return type;
}
throw new SerializationException("Unauthorized type detected.");
}
}
[HttpPost]
public IActionResult ProcessData([FromBody] byte[] serializedData)
{
var formatter = new BinaryFormatter
{
Binder = new SafeBinder()
};
using (var ms = new MemoryStream(serializedData))
{
var obj = formatter.Deserialize(ms);
ProcessObject(obj);
}
return Ok();
}
# ICB
[HttpGet]
public IActionResult GetFile(string filename)
{
string path = Path.Combine("C:\\Files", filename);
if (System.IO.File.Exists(path))
{
return PhysicalFile(path, "application/octet-stream");
}
return NotFound("File not found");
}
// Similar code can introduce vulnerability to blobs and other storage units.
# ICB
[HttpGet]
public IActionResult GetFile(string filename)
{
// Ensure filename contains no directory traversal
string sanitizedFilename = Path.GetFileName(filename);
string path = Path.Combine("C:\\Files", sanitizedFilename);
if (System.IO.File.Exists(path))
{
return PhysicalFile(path, "application/octet-stream");
}
return NotFound("File not found");
}
# ICB
[HttpPost]
public IActionResult Execute(string command)
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C " + command,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
return Ok(result);
}
# ICB
[HttpPost]
public IActionResult ExecuteSafe(string operation)
{
if (operation == "list")
{
string[] files = Directory.GetFiles("C:\\Files");
return Ok(files);
}
return BadRequest("Invalid operation");
}
# ICB
[HttpGet]
public IActionResult GetUser(string username)
{
string query = $"SELECT * FROM Users WHERE Username = '{username}'";
using (var connection = new SqlConnection("your_connection_string"))
{
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
// Process the results
}
return Ok();
}
# ICB
[HttpGet]
public IActionResult GetUser(string username)
{
using (var connection = new SqlConnection("your_connection_string"))
{
var query = "SELECT * FROM Users WHERE Username = @Username";
var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Username", username);
connection.Open();
var reader = command.ExecuteReader();
// Process the results
}
return Ok();
}
# ICB
[HttpGet]
public IActionResult Greet(string name)
{
return Content($"<h1>Welcome, {name}</h1>", "text/html");
}
# ICB
[HttpGet]
public IActionResult Greet(string name)
{
string sanitized = System.Net.WebUtility.HtmlEncode(name);
return Content($"<h1>Welcome, {sanitized}</h1>", "text/html");
}
# ICB
var token = new JwtSecurityToken(
issuer: "myapp",
audience: "myaudience",
claims: claims,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("random-weak-key")),
SecurityAlgorithms.HmacSha256
)
);
# ICB
var token = new JwtSecurityToken(
issuer: "myapp",
audience: "myaudience",
claims: claims,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(GenerateSecureKey()), SecurityAlgorithms.HmacSha256)
);
private byte[] GenerateSecureKey()
{
using (var rng = new RNGCryptoServiceProvider())
{
var key = new byte[32];
rng.GetBytes(key);
return key;
}
}
Important Takeaway: Aways use secure random crypto providers.
# ICB
webSocket.OnMessage += async (sender, e) =>
{
var message = Encoding.UTF8.GetString(e.RawData); // No validation
await ProcessMessage(message); // Allows potentially harmful input
};
# ICB
webSocket.OnMessage += async (sender, e) =>
{
var message = Encoding.UTF8.GetString(e.RawData);
if (!IsValidJson(message))
{
await webSocket.CloseAsync();
return;
}
await ProcessMessage(message);
};
private bool IsValidJson(string input)
{
try
{
JToken.Parse(input); // Validate input as JSON
return true;
}
catch
{
return false;
}
}
# ICB
# ICB
# ICB
# ICB
# ICB
# ICB
# ICB
"Security is not a product, but a process." — Bruce Schneier
And some interesting reads:
Useful links:
"Building secure software is not about eliminating risks but managing them effectively." — Gary McGraw